дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 21:42:27 +02:00
Порівняти коміти
475
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
b5521c2605 | ||
|
|
26992ec4ce | ||
|
|
2c22574be0 | ||
|
|
93368d4379 | ||
|
|
14741101bd | ||
|
|
db60deede5 | ||
|
|
ab2a7767c7 | ||
|
|
49c917880d | ||
|
|
f0db09aca5 | ||
|
|
979cce1175 | ||
|
|
faa7571038 | ||
|
|
264bf6969f | ||
|
|
66e17df216 | ||
|
|
4ff5739854 | ||
|
|
a0c03447a0 | ||
|
|
c4e0900485 | ||
|
|
a42f13edc2 | ||
|
|
18d6041f2f | ||
|
|
15c5e921df | ||
|
|
bc64188c38 | ||
|
|
a3c819e064 | ||
|
|
1f2e92b433 | ||
|
|
8dfca955a5 | ||
|
|
91aba61c97 | ||
|
|
1fb4135b5b | ||
|
|
24598e0dae | ||
|
|
2436ad6fe9 | ||
|
|
c2c6931f0e | ||
|
|
2e0c8dd527 | ||
|
|
f4be752dda | ||
|
|
a52a639b8e | ||
|
|
1b0bf4d741 | ||
|
|
13597e40a1 | ||
|
|
aa1aa91b0d | ||
|
|
032a3b0453 | ||
|
|
07750ad984 | ||
|
|
ba38f070d9 | ||
|
|
c77f4db777 | ||
|
|
d3067c8d3a | ||
|
|
7bf2702565 | ||
|
|
65c45ffe05 | ||
|
|
84b528f0cd | ||
|
|
8621764813 | ||
|
|
22e1c4b927 | ||
|
|
e2817656e8 | ||
|
|
306c71290c | ||
|
|
51ccb68b72 | ||
|
|
2e965810e9 | ||
|
|
31b70cf0ac | ||
|
|
d0989e2a4b | ||
|
|
d96ed8d154 | ||
|
|
6b41870368 | ||
|
|
660becbaa4 | ||
|
|
a0afc478c1 | ||
|
|
07a88c6fa4 | ||
|
|
46bd6fad3c | ||
|
|
f64dbe65b4 | ||
|
|
e2a5a5db81 | ||
|
|
6eb7abff9f | ||
|
|
b46112fe0b | ||
|
|
4507dc172d | ||
|
|
8442c0c339 | ||
|
|
8ffe3bd230 | ||
|
|
1babff55fc | ||
|
|
2ad95150eb | ||
|
|
fe3e647abb | ||
|
|
62cc6768fe | ||
|
|
2e93422270 | ||
|
|
3a1353cc0e | ||
|
|
c5eab0a4a3 | ||
|
|
581c8cf025 | ||
|
|
807c447792 | ||
|
|
217693a56f | ||
|
|
557295b1df | ||
|
|
7c674e70e5 | ||
|
|
1602a5d010 | ||
|
|
a6d135d66f | ||
|
|
924bf6d3b9 | ||
|
|
318c227b0c | ||
|
|
2ce7621abb | ||
|
|
7ecccb3b75 | ||
|
|
7cbf17b10e | ||
|
|
cb0d02620d | ||
|
|
d6ca43cba4 | ||
|
|
165d4f7d76 | ||
|
|
5785ebadd8 | ||
|
|
0c67a4eea2 | ||
|
|
5e2deed81e | ||
|
|
cae7c05fb1 | ||
|
|
be83458161 | ||
|
|
661124d0d4 | ||
|
|
0dae111b2d | ||
|
|
61d269045b | ||
|
|
266d85fa1a | ||
|
|
f964d79e10 | ||
|
|
4a3eacff62 | ||
|
|
aebc2fe02d | ||
|
|
9b63aa9526 | ||
|
|
df07073886 | ||
|
|
3433ee951b | ||
|
|
8f5b281486 | ||
|
|
43aee8058c | ||
|
|
4016c3c905 | ||
|
|
e6cb7df653 | ||
|
|
2a26c82357 | ||
|
|
66f0bce92f | ||
|
|
dfbd13e2af | ||
|
|
944b57dead | ||
|
|
5bcb37492f | ||
|
|
d5bde9af67 | ||
|
|
5b3e2b7a3d | ||
|
|
dbb6fa51c3 | ||
|
|
3d1769ef00 | ||
|
|
c966429f92 | ||
|
|
dfcc05dd41 | ||
|
|
d41feefc07 | ||
|
|
f0fe910017 | ||
|
|
b932220b41 | ||
|
|
bcad8f61cb | ||
|
|
2cdcb888cf | ||
|
|
9ed0fd9fa7 | ||
|
|
fe76dc4573 | ||
|
|
45a75f782a | ||
|
|
bd1fd011e4 | ||
|
|
b44015b2ce | ||
|
|
0cce0a9840 | ||
|
|
db8224f74e | ||
|
|
b075f5de2a | ||
|
|
3240164840 | ||
|
|
f70f362a3d | ||
|
|
806bb4c78d | ||
|
|
57094bc285 | ||
|
|
a5e0c41663 | ||
|
|
77071238a0 | ||
|
|
64097d3c20 | ||
|
|
cf0e57e5df | ||
|
|
703cf23296 | ||
|
|
a88073d6fb | ||
|
|
4b5745c1b6 | ||
|
|
4667c81e6b | ||
|
|
cea9d863f9 | ||
|
|
5fa953eddd | ||
|
|
031f1acd07 | ||
|
|
add23fe97f | ||
|
|
3d2b0946de | ||
|
|
6c7282b442 | ||
|
|
1f79a7f805 | ||
|
|
3d1eaf71e4 | ||
|
|
138209c627 | ||
|
|
b283d352b7 | ||
|
|
f7f9dabe2b | ||
|
|
787d4fbcfa | ||
|
|
3fbd0e05a5 | ||
|
|
2d021a3414 | ||
|
|
cd7582c5e5 | ||
|
|
d16b852054 | ||
|
|
06223d9bd7 | ||
|
|
dcd81d601b | ||
|
|
762ebecd86 | ||
|
|
fd4efff6e3 | ||
|
|
8968974f42 | ||
|
|
5f083ae47c | ||
|
|
83b14b4329 | ||
|
|
74eefd6116 | ||
|
|
a96c70f2a7 | ||
|
|
304503b9f1 | ||
|
|
06cf8fb16a | ||
|
|
521e00d075 | ||
|
|
b4cad6ec1b | ||
|
|
62e26fa7e3 | ||
|
|
1119467ab4 | ||
|
|
e1ce850a29 | ||
|
|
3e39368d43 | ||
|
|
b2a5ea1594 | ||
|
|
902d8ca257 | ||
|
|
92b5b5306f | ||
|
|
707cee9b0b | ||
|
|
d64be035c6 | ||
|
|
cb60c742fc | ||
|
|
b245335cc6 | ||
|
|
e13ed093ec | ||
|
|
aa0f8105af | ||
|
|
0adc816a56 | ||
|
|
ea29339b6b | ||
|
|
84854bed0e | ||
|
|
81b6cb7af6 | ||
|
|
ffe96c2ca2 | ||
|
|
33bd5372b6 | ||
|
|
44aeb95993 | ||
|
|
fa6b4be6f5 | ||
|
|
144cd90175 | ||
|
|
da3b621345 | ||
|
|
b301e2bbe1 | ||
|
|
feac919a1b | ||
|
|
0155d74084 | ||
|
|
130f75e7e8 | ||
|
|
2abd65aedd | ||
|
|
1b3e4fac6a | ||
|
|
72b0c7c48c | ||
|
|
25d1046af0 | ||
|
|
1cdb998532 | ||
|
|
b1ab5afa67 | ||
|
|
0101d11ac9 | ||
|
|
07d26722b1 | ||
|
|
df48d9271b | ||
|
|
cb6b7ccd3f | ||
|
|
13c0e8aa8d | ||
|
|
9f643af069 | ||
|
|
0c02a9e467 | ||
|
|
8c7bdc9bf2 | ||
|
|
a3f6d82391 | ||
|
|
bfde0ffc34 | ||
|
|
9067abf0cf | ||
|
|
4939b63c88 | ||
|
|
78d34af971 | ||
|
|
d47c9eb347 | ||
|
|
5348e42c59 | ||
|
|
a42eee29f4 | ||
|
|
a3e7142e4c | ||
|
|
d21fd65341 | ||
|
|
422f424b60 | ||
|
|
c10862b1a6 | ||
|
|
d4db49689e | ||
|
|
36ab40797c | ||
|
|
de7d62dce8 | ||
|
|
e3f9049e26 | ||
|
|
3e9f018cf4 | ||
|
|
e44d7fd396 | ||
|
|
dc490f1017 | ||
|
|
5289f44620 | ||
|
|
81aac31cc7 | ||
|
|
026163af9e | ||
|
|
ce03ae7c0f | ||
|
|
1cd8e8def5 | ||
|
|
a0b9fba2f2 | ||
|
|
1f6a3bbf0d | ||
|
|
5265455313 | ||
|
|
64cc72ba2e | ||
|
|
b79dbae83f | ||
|
|
e909c50fe4 | ||
|
|
da7125a944 | ||
|
|
e54e309d61 | ||
|
|
8c3371212c | ||
|
|
e08531c458 | ||
|
|
9c9e0e59cb | ||
|
|
1d5d33cf76 | ||
|
|
2bbba9b945 | ||
|
|
14f143b703 | ||
|
|
f2a372428c | ||
|
|
89524bd583 | ||
|
|
f90d94538d | ||
|
|
a4ad387085 | ||
|
|
f8a148c06d | ||
|
|
aa1a027162 | ||
|
|
b30716e22c | ||
|
|
7fb21003f3 | ||
|
|
ad8d32d9c7 | ||
|
|
08aef06844 | ||
|
|
3d5ec8a147 | ||
|
|
0f14314156 | ||
|
|
2413cc4b43 | ||
|
|
30291971e1 | ||
|
|
9f3d75976f | ||
|
|
72d9aad715 | ||
|
|
7264e7d66d | ||
|
|
10379a54f7 | ||
|
|
6564b9e6cb | ||
|
|
d437cd46f5 | ||
|
|
925d474274 | ||
|
|
89463afc18 | ||
|
|
c884aa4cc6 | ||
|
|
09108e02e3 | ||
|
|
2b6ca90457 | ||
|
|
3c3681ef2b | ||
|
|
b0d7bfef24 | ||
|
|
527add030a | ||
|
|
81c2fc9ace | ||
|
|
ef1b159544 | ||
|
|
7bfba926c2 | ||
|
|
1042f5fa56 | ||
|
|
fdad01034c | ||
|
|
6dddfde3bc | ||
|
|
0324bc368d | ||
|
|
96c6e65aad | ||
|
|
6eebd895ea | ||
|
|
cfad729dbd | ||
|
|
bd905c6689 | ||
|
|
7138becb3a | ||
|
|
6f7d2ce34d | ||
|
|
719961e34e | ||
|
|
11c432fc23 | ||
|
|
0b8698e47c | ||
|
|
f595a7abf0 | ||
|
|
fe7fa7d505 | ||
|
|
e998e2ca8e | ||
|
|
18424b322f | ||
|
|
daee26e680 | ||
|
|
5886e055b4 | ||
|
|
8d4b360933 | ||
|
|
f6704b53f6 | ||
|
|
91da88d09d | ||
|
|
5ab91245dd | ||
|
|
fb063c1f84 | ||
|
|
f926390d2e | ||
|
|
9b66744e72 | ||
|
|
071f768635 | ||
|
|
bbe9cf7a86 | ||
|
|
c10d2f0732 | ||
|
|
ec02a121e9 | ||
|
|
12eb2db641 | ||
|
|
2735d45d7e | ||
|
|
60262c92ba | ||
|
|
ca472742bf | ||
|
|
023408eb26 | ||
|
|
92c0e304cd | ||
|
|
3d534b447d | ||
|
|
89a3359aaf | ||
|
|
d88c4c87b6 | ||
|
|
197c7d6141 | ||
|
|
c61bb2b56d | ||
|
|
b9429858a6 | ||
|
|
c1e9707c7e | ||
|
|
a483ea77f4 | ||
|
|
de36b46660 | ||
|
|
5918605b2b | ||
|
|
f69d394480 | ||
|
|
eb078a0a19 | ||
|
|
5a884d7cba | ||
|
|
2ba2f33232 | ||
|
|
c9bb5a3169 | ||
|
|
bfbc70a438 | ||
|
|
e74edbcedc | ||
|
|
ebeb6476eb | ||
|
|
b8b245da5f | ||
|
|
5aeadcc888 | ||
|
|
edc750174b | ||
|
|
cdff357fdd | ||
|
|
de971848ab | ||
|
|
90cb56e9f8 | ||
|
|
baa0171d8a | ||
|
|
0d493fb515 | ||
|
|
a56add66ea | ||
|
|
2d568980c5 | ||
|
|
7920a4985e | ||
|
|
d6c7e7edc4 | ||
|
|
b1c69d1991 | ||
|
|
a869acdca2 | ||
|
|
fb3a037b7e | ||
|
|
dfaa784513 | ||
|
|
67e58f61b6 | ||
|
|
e75deb11c0 | ||
|
|
94b67515a5 | ||
|
|
a0b2678466 | ||
|
|
e3dc7e950b | ||
|
|
0a53c7b864 | ||
|
|
d4447c7aba | ||
|
|
9740edbfd4 | ||
|
|
b49b0e5c98 | ||
|
|
c88e379c8b | ||
|
|
db63c6c93b | ||
|
|
54a7962043 | ||
|
|
7c3b9824e6 | ||
|
|
0450de5321 | ||
|
|
fadd2a78aa | ||
|
|
53f5ecb233 | ||
|
|
0b079af75d | ||
|
|
6dab294dbf | ||
|
|
fc0ca1e029 | ||
|
|
fe024713da | ||
|
|
42c7834023 | ||
|
|
96f73c82da | ||
|
|
854c81e49b | ||
|
|
b19922b71d | ||
|
|
afab9d0ba2 | ||
|
|
04ed8712b5 | ||
|
|
971b520399 | ||
|
|
c67363ec6b | ||
|
|
2568772700 | ||
|
|
536f85b9df | ||
|
|
e5c5915f2e | ||
|
|
ca2bf89f86 | ||
|
|
735fe5dd30 | ||
|
|
0cfd17979b | ||
|
|
41165bb8c0 | ||
|
|
91264713e7 | ||
|
|
71a4f7cb63 | ||
|
|
dfa632cf18 | ||
|
|
f1425854fb | ||
|
|
752650b971 | ||
|
|
d33ee53c92 | ||
|
|
57eac70018 | ||
|
|
497948eeff | ||
|
|
834846840b | ||
|
|
a393bcdcc2 | ||
|
|
08f6079316 | ||
|
|
0db493b944 | ||
|
|
2a90677e4f | ||
|
|
fed9a00dd9 | ||
|
|
f034d96ed4 | ||
|
|
eead66df7d | ||
|
|
0dccfafa90 | ||
|
|
6fba7e9424 | ||
|
|
475e35281b | ||
|
|
387670573f | ||
|
|
48aac102e1 | ||
|
|
2d7353e39f | ||
|
|
912da2551b | ||
|
|
06bd43e46f | ||
|
|
b9a5b8d90b | ||
|
|
92917d1c26 | ||
|
|
4f0ab6c968 | ||
|
|
43fdb0aba7 | ||
|
|
d65d58a4e8 | ||
|
|
d3792e5667 | ||
|
|
d0bffb5e90 | ||
|
|
8e26003894 | ||
|
|
372d23b7e4 | ||
|
|
dc35952cf4 | ||
|
|
2622c9d778 | ||
|
|
c878fb1edc | ||
|
|
9ca7a297e1 | ||
|
|
b748a4cfbc | ||
|
|
5be5487ac6 | ||
|
|
f597ae8c81 | ||
|
|
eb036f2b67 | ||
|
|
ad95695588 | ||
|
|
9e6c29a7b7 | ||
|
|
89fa6cb02c | ||
|
|
6f284741b3 | ||
|
|
4b253d368e | ||
|
|
f274189c92 | ||
|
|
5f17748295 | ||
|
|
2d94628d1d | ||
|
|
26aabf5229 | ||
|
|
87ce01d251 | ||
|
|
3dd918c5b2 | ||
|
|
9a74fe4418 | ||
|
|
a70a0ae6f1 | ||
|
|
9be4803462 | ||
|
|
8122127dde | ||
|
|
cdcce048fe | ||
|
|
1cea43694e | ||
|
|
260ac4efbf | ||
|
|
9805fb42b8 | ||
|
|
4a18d4d205 | ||
|
|
9ecef0ef0f | ||
|
|
aec80ced53 | ||
|
|
e5a4a6940a | ||
|
|
196af0ac37 | ||
|
|
1e4388490c | ||
|
|
ad8958901b | ||
|
|
25b49b1473 | ||
|
|
1a689ff5da | ||
|
|
2544db3025 | ||
|
|
6355534ed5 | ||
|
|
7bc26b9387 | ||
|
|
d7b9401a07 | ||
|
|
465e4f80bc | ||
|
|
1743aec533 | ||
|
|
52e2215dcf | ||
|
|
57bccc916c | ||
|
|
46a712524d | ||
|
|
0f5607d76c | ||
|
|
8c23c589ca | ||
|
|
ae7a8e74c8 | ||
|
|
a7b67347c2 | ||
|
|
707b6fe169 | ||
|
|
b9a0c66ca6 | ||
|
|
26f83240a7 | ||
|
|
c6bb0b84ce | ||
|
|
09d1f4a673 | ||
|
|
3b875620d2 | ||
|
|
843f2024c5 | ||
|
|
4ed7bf14d6 | ||
|
|
4bc46baddb |
No files matched your search
@@ -156,6 +156,44 @@ jobs:
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- name: Restore Maven artifacts for Java build tests
|
||||
id: jbuild-maven-cache
|
||||
if: runner.environment == 'github-hosted'
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: jbuild-maven-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
|
||||
- name: Prepare Maven artifacts for Java build tests
|
||||
id: jbuild-maven
|
||||
if: runner.environment == 'github-hosted'
|
||||
timeout-minutes: 5
|
||||
shell: bash
|
||||
env:
|
||||
CACHE_HIT: ${{ steps.jbuild-maven-cache.outputs.cache-hit }}
|
||||
run: |
|
||||
if [[ -z "${JAVA_HOME:-}" || ! -d "$JAVA_HOME/bin" ]] || ! command -v mvn >/dev/null; then
|
||||
exit 0
|
||||
fi
|
||||
export MAVEN_OPTS="${MAVEN_OPTS:+$MAVEN_OPTS }-Dmaven.repo.local=$RUNNER_TEMP/jbuild-maven-repository"
|
||||
echo "MAVEN_OPTS=$MAVEN_OPTS" >> "$GITHUB_ENV"
|
||||
if [[ "$CACHE_HIT" == true ]]; then
|
||||
exit 0
|
||||
fi
|
||||
# The IDE also reads the compiler plugin descriptor when it builds the Maven model.
|
||||
for delay in 0 10 30; do
|
||||
sleep "$delay"
|
||||
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml resources:resources compiler:compile; then
|
||||
echo "prepared=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
exit 1
|
||||
- name: Save Maven artifacts for Java build tests
|
||||
if: steps.jbuild-maven.outputs.prepared == 'true'
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
|
||||
- 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).
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
name: Homebrew
|
||||
|
||||
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
|
||||
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
|
||||
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
|
||||
# and without the HOMEBREW_TAP_DEPLOY_KEY secret (the private half of a write deploy key on
|
||||
# l0ng-ai/homebrew-tap).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Published stable release to write the cask for (e.g. v0.1.51)"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: homebrew-tap
|
||||
|
||||
jobs:
|
||||
cask:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
TAP: l0ng-ai/homebrew-tap
|
||||
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check tag and deploy key
|
||||
id: check
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::notice::$TAG is not a stable release: the cask stays as is"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$HOMEBREW_TAP_DEPLOY_KEY" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { sparse-checkout: scripts }
|
||||
- uses: actions/checkout@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Download DMGs
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: gh release download "$TAG" -R "$GITHUB_REPOSITORY" -p '*.dmg' -D assets
|
||||
- name: Write the cask
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: node scripts/homebrew-cask.ts "$TAG" assets tap/Casks/openidea.rb
|
||||
- name: Push to the tap
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
working-directory: tap
|
||||
run: |
|
||||
git add Casks/openidea.rb
|
||||
if git diff --cached --quiet; then
|
||||
echo "the cask is already at ${TAG#v}"
|
||||
exit 0
|
||||
fi
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git commit -m "openidea ${TAG#v}"
|
||||
git push
|
||||
@@ -23,6 +23,7 @@ on:
|
||||
- "Cargo.lock"
|
||||
- "src/features/run/**"
|
||||
- "src/features/debugger/**"
|
||||
- "src/features/build/**"
|
||||
- "src/features/build-tools/**"
|
||||
- "src/platform/**"
|
||||
- "src/workbench/**"
|
||||
@@ -38,6 +39,7 @@ on:
|
||||
- "src/editor/lsp/hint.ts"
|
||||
- "src/editor/lsp/lsp.ts"
|
||||
- "src/editor/lsp/positions.ts"
|
||||
- "src/editor/lsp/snippet.ts"
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
@@ -105,7 +107,7 @@ jobs:
|
||||
# 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-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
@@ -178,3 +178,10 @@ jobs:
|
||||
uses: ./.github/workflows/cnb-mirror.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"detector": {
|
||||
"ignoreRules": [],
|
||||
"ignoreFiles": [],
|
||||
"ignoreValues": [
|
||||
{
|
||||
"rule": "gradient-text",
|
||||
"value": "*",
|
||||
"files": ["src/features/agents/Session.module.css"],
|
||||
"createdAt": "2026-11-24T14:58:12.514Z",
|
||||
"reason": "agent: .shimmer is an animated in-progress sweep on running-step labels (commit 18b286e7e, comment documents intent), not decorative gradient text"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
{
|
||||
"schemaVersion": 2,
|
||||
"generatedAt": "2026-11-24T15:06:05+00:00",
|
||||
"title": "Design System: OpenIDEA",
|
||||
"extensions": {
|
||||
"colorMeta": {
|
||||
"workbench-blue": {
|
||||
"role": "primary",
|
||||
"displayName": "Workbench Blue",
|
||||
"canonical": "#3871e1",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.073 262)",
|
||||
"oklch(25% 0.121 262)",
|
||||
"oklch(35% 0.17 262)",
|
||||
"oklch(48% 0.17 262)",
|
||||
"oklch(60% 0.17 262)",
|
||||
"oklch(72% 0.136 262)",
|
||||
"oklch(84% 0.078 262)",
|
||||
"oklch(95% 0.024 262)"
|
||||
]
|
||||
},
|
||||
"link-blue": {
|
||||
"role": "primary",
|
||||
"displayName": "Link Blue",
|
||||
"canonical": "#2f5eb9",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.064 262)",
|
||||
"oklch(25% 0.107 262)",
|
||||
"oklch(35% 0.15 262)",
|
||||
"oklch(48% 0.15 262)",
|
||||
"oklch(60% 0.15 262)",
|
||||
"oklch(72% 0.12 262)",
|
||||
"oklch(84% 0.069 262)",
|
||||
"oklch(95% 0.021 262)"
|
||||
]
|
||||
},
|
||||
"selection-wash": {
|
||||
"role": "primary",
|
||||
"displayName": "Selection Wash",
|
||||
"canonical": "#d0dffe",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.034 262)",
|
||||
"oklch(25% 0.057 262)",
|
||||
"oklch(35% 0.08 262)",
|
||||
"oklch(48% 0.08 262)",
|
||||
"oklch(60% 0.08 262)",
|
||||
"oklch(72% 0.064 262)",
|
||||
"oklch(84% 0.037 262)",
|
||||
"oklch(95% 0.011 262)"
|
||||
]
|
||||
},
|
||||
"tab-wash": {
|
||||
"role": "primary",
|
||||
"displayName": "Tab Wash",
|
||||
"canonical": "#e3ebfe",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.026 262)",
|
||||
"oklch(25% 0.043 262)",
|
||||
"oklch(35% 0.06 262)",
|
||||
"oklch(48% 0.06 262)",
|
||||
"oklch(60% 0.06 262)",
|
||||
"oklch(72% 0.048 262)",
|
||||
"oklch(84% 0.027 262)",
|
||||
"oklch(95% 0.009 262)"
|
||||
]
|
||||
},
|
||||
"danger": {
|
||||
"role": "status",
|
||||
"displayName": "Danger",
|
||||
"canonical": "#c54e58",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.064 18)",
|
||||
"oklch(25% 0.107 18)",
|
||||
"oklch(35% 0.15 18)",
|
||||
"oklch(48% 0.15 18)",
|
||||
"oklch(60% 0.15 18)",
|
||||
"oklch(72% 0.12 18)",
|
||||
"oklch(84% 0.069 18)",
|
||||
"oklch(95% 0.021 18)"
|
||||
]
|
||||
},
|
||||
"warning": {
|
||||
"role": "status",
|
||||
"displayName": "Warning",
|
||||
"canonical": "#a56906",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.056 70)",
|
||||
"oklch(25% 0.093 70)",
|
||||
"oklch(35% 0.13 70)",
|
||||
"oklch(48% 0.13 70)",
|
||||
"oklch(60% 0.13 70)",
|
||||
"oklch(72% 0.104 70)",
|
||||
"oklch(84% 0.059 70)",
|
||||
"oklch(95% 0.019 70)"
|
||||
]
|
||||
},
|
||||
"success": {
|
||||
"role": "status",
|
||||
"displayName": "Success",
|
||||
"canonical": "#338555",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.047 152)",
|
||||
"oklch(25% 0.079 152)",
|
||||
"oklch(35% 0.11 152)",
|
||||
"oklch(48% 0.11 152)",
|
||||
"oklch(60% 0.11 152)",
|
||||
"oklch(72% 0.088 152)",
|
||||
"oklch(84% 0.05 152)",
|
||||
"oklch(95% 0.016 152)"
|
||||
]
|
||||
},
|
||||
"frame-grey": {
|
||||
"role": "neutral",
|
||||
"displayName": "Frame Grey",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"island-white": {
|
||||
"role": "neutral",
|
||||
"displayName": "Island White",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"raised-paper": {
|
||||
"role": "neutral",
|
||||
"displayName": "Raised Paper",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-secondary": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Secondary",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-muted": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Muted",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-faint": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Faint",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"hairline": {
|
||||
"role": "neutral",
|
||||
"displayName": "Hairline",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"control-edge": {
|
||||
"role": "neutral",
|
||||
"displayName": "Control Edge",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"frame-grey-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Frame Grey (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"island-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Island (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-strong-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Strong (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"ink-muted-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Ink Muted (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"control-edge-dark": {
|
||||
"role": "neutral",
|
||||
"displayName": "Control Edge (Dark)",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.005 265)",
|
||||
"oklch(25% 0.009 265)",
|
||||
"oklch(35% 0.012 265)",
|
||||
"oklch(48% 0.012 265)",
|
||||
"oklch(60% 0.012 265)",
|
||||
"oklch(72% 0.01 265)",
|
||||
"oklch(84% 0.005 265)",
|
||||
"oklch(95% 0.002 265)"
|
||||
]
|
||||
},
|
||||
"selection-wash-dark": {
|
||||
"role": "primary",
|
||||
"displayName": "Selection Wash (Dark)",
|
||||
"canonical": "#2a4371",
|
||||
"tonalRamp": [
|
||||
"oklch(15% 0.034 262)",
|
||||
"oklch(25% 0.057 262)",
|
||||
"oklch(35% 0.08 262)",
|
||||
"oklch(48% 0.08 262)",
|
||||
"oklch(60% 0.08 262)",
|
||||
"oklch(72% 0.064 262)",
|
||||
"oklch(84% 0.037 262)",
|
||||
"oklch(95% 0.011 262)"
|
||||
]
|
||||
}
|
||||
},
|
||||
"typographyMeta": {
|
||||
"title": {
|
||||
"displayName": "Title",
|
||||
"purpose": "Tool window titles, section headers, dialog titles; weight 600 is the main emphasis."
|
||||
},
|
||||
"body": {
|
||||
"displayName": "Body",
|
||||
"purpose": "Default UI text, menus, rows, buttons."
|
||||
},
|
||||
"label": {
|
||||
"displayName": "Label",
|
||||
"purpose": "Secondary metadata, chips, status bar, table cells; the most-used size."
|
||||
},
|
||||
"label-tiny": {
|
||||
"displayName": "Label Tiny",
|
||||
"purpose": "Stripe labels, counters, badges."
|
||||
},
|
||||
"input-large": {
|
||||
"displayName": "Input Large",
|
||||
"purpose": "Search Everywhere and other large query fields."
|
||||
},
|
||||
"code": {
|
||||
"displayName": "Code",
|
||||
"purpose": "Editor, console, terminal and every monospace preview; size and weights are user settings."
|
||||
}
|
||||
},
|
||||
"shadows": [
|
||||
{
|
||||
"name": "shadow-popup",
|
||||
"value": "0 6px 20px rgba(0, 0, 0, 0.12)",
|
||||
"purpose": "Popups, menus, completion, floating toolbar (Light; Dark uses 0.45 alpha)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-dialog",
|
||||
"value": "0 0 0 0.5px rgba(0, 0, 0, 0.1), 0 10px 24px rgba(0, 0, 0, 0.1), 0 24px 72px rgba(0, 0, 0, 0.2)",
|
||||
"purpose": "Window-style shadow for dialogs (Light)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-tooltip",
|
||||
"value": "0 4px 12px rgba(0, 0, 0, 0.12)",
|
||||
"purpose": "Hover tooltips (Light)."
|
||||
},
|
||||
{
|
||||
"name": "shadow-balloon",
|
||||
"value": "0 8px 24px rgba(0, 0, 0, 0.14)",
|
||||
"purpose": "Notification balloons (Light)."
|
||||
}
|
||||
],
|
||||
"motion": [
|
||||
{
|
||||
"name": "ease",
|
||||
"value": "cubic-bezier(0.2, 0, 0, 1)",
|
||||
"purpose": "Default easing for every state transition."
|
||||
},
|
||||
{
|
||||
"name": "dur-fast",
|
||||
"value": "80ms",
|
||||
"purpose": "Hover, press and focus changes on controls."
|
||||
},
|
||||
{
|
||||
"name": "dur",
|
||||
"value": "140ms",
|
||||
"purpose": "Standard transitions such as popup fades."
|
||||
},
|
||||
{
|
||||
"name": "dur-slow",
|
||||
"value": "220ms",
|
||||
"purpose": "Upper bound for any state transition."
|
||||
}
|
||||
],
|
||||
"density": [
|
||||
{
|
||||
"name": "default",
|
||||
"value": "rows 24px, fields/buttons 28px, titlebar 40px, tab bar 38px, status bar 30px, island gap 6px, island radius 10px"
|
||||
},
|
||||
{
|
||||
"name": "compact",
|
||||
"value": "rows 22px, fields/buttons 24px, titlebar/headers 32px, tab bar 32px, status bar 24px, island gap 4px, island radius 8px, chrome text -1px"
|
||||
}
|
||||
]
|
||||
},
|
||||
"components": [
|
||||
{
|
||||
"name": "Primary Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-primary",
|
||||
"description": "The one default action in a dialog or form.",
|
||||
"html": "<button class=\"ds-btn ds-btn-primary\">OK</button>",
|
||||
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-primary { background:var(--bg-button-primary,#3871e1); color:var(--fg-button-primary,#fff); } .ds-btn-primary:hover { background:var(--bg-button-primary-hover,#3366cc); }"
|
||||
},
|
||||
{
|
||||
"name": "Secondary Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-secondary",
|
||||
"description": "Every other dialog action: Cancel, Apply, Browse.",
|
||||
"html": "<button class=\"ds-btn ds-btn-secondary\">Cancel</button>",
|
||||
"css": ".ds-btn { display:inline-flex; align-items:center; justify-content:center; height:var(--h-button,28px); min-width:72px; padding:0 16px; border:0; border-radius:var(--radius-control,4px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease), box-shadow var(--dur-fast,80ms) var(--ease); } .ds-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; } .ds-btn-secondary { background:var(--bg-button,#fff); color:var(--fg-strong,#000); box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); } .ds-btn-secondary:hover { background:color-mix(in srgb, var(--bg-button,#fff) 94%, var(--fg-strong,#000)); }"
|
||||
},
|
||||
{
|
||||
"name": "Ghost Button",
|
||||
"kind": "button",
|
||||
"refersTo": "button-ghost",
|
||||
"description": "Low-emphasis text actions in headers and inline rows.",
|
||||
"html": "<button class=\"ds-btn-ghost\">Show all</button>",
|
||||
"css": ".ds-btn-ghost { display:inline-flex; align-items:center; height:var(--h-button,28px); padding:0 8px; border:0; background:transparent; border-radius:var(--radius-control,4px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-ui,13px); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-btn-ghost:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-btn-ghost:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-btn-ghost:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:1px; }"
|
||||
},
|
||||
{
|
||||
"name": "Toolbar Icon Button",
|
||||
"kind": "button",
|
||||
"refersTo": "icon-button",
|
||||
"description": "Toolbar and tool window header actions; frameless at rest, toggles show Selection Wash.",
|
||||
"html": "<div class=\"ds-iconbar\"><button class=\"ds-icon-btn\" aria-label=\"Refresh\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M13 8a5 5 0 1 1-1.46-3.54M13 3v2.5h-2.5\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg></button><button class=\"ds-icon-btn\" aria-label=\"Show options\" aria-pressed=\"true\"><svg width=\"16\" height=\"16\" viewBox=\"0 0 16 16\" fill=\"none\"><path d=\"M2.5 4.5h11M2.5 8h11M2.5 11.5h11\" stroke=\"currentColor\" stroke-width=\"1.2\" stroke-linecap=\"round\"/></svg></button></div>",
|
||||
"css": ".ds-iconbar { display:flex; gap:2px; } .ds-icon-btn { display:inline-flex; align-items:center; justify-content:center; width:24px; height:24px; padding:0; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-muted,#6c707e); cursor:default; transition:background var(--dur-fast,80ms) var(--ease), color var(--dur-fast,80ms) var(--ease); } .ds-icon-btn:hover { background:var(--bg-toolbar-hover,#00000012); color:var(--fg-strong,#000); } .ds-icon-btn:active { background:var(--bg-toolbar-pressed,#00000020); } .ds-icon-btn[aria-pressed=\"true\"] { background:var(--bg-toolbar-selected,#d0dffe); color:var(--fg-strong,#000); } .ds-icon-btn:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
|
||||
},
|
||||
{
|
||||
"name": "Text Field",
|
||||
"kind": "input",
|
||||
"refersTo": "input",
|
||||
"description": "Framed text field; the frame doubles in Workbench Blue on focus.",
|
||||
"html": "<input class=\"ds-input\" placeholder=\"Project name\" />",
|
||||
"css": ".ds-input { height:var(--h-field,28px); padding:0 8px; border:0; appearance:none; border-radius:var(--radius-control,4px); background:var(--bg-field,#fff); color:var(--fg-strong,#000); font-family:var(--font-ui); font-size:var(--fs-ui,13px); outline:none; box-shadow:inset 0 0 0 1px var(--border-button,#d1d3d9); transition:box-shadow var(--dur-fast,80ms) var(--ease); } .ds-input::placeholder { color:var(--fg-faint,#9fa2a8); } .ds-input:focus { box-shadow:inset 0 0 0 1px var(--focus-ring,#3871e1), 0 0 0 1px var(--focus-ring,#3871e1); }"
|
||||
},
|
||||
{
|
||||
"name": "Chip",
|
||||
"kind": "chip",
|
||||
"refersTo": "chip",
|
||||
"description": "Flat read-only fact or picker trigger, sized like the toolbar widgets.",
|
||||
"html": "<button class=\"ds-chip\"><svg width=\"14\" height=\"14\" viewBox=\"0 0 16 16\" fill=\"none\"><circle cx=\"5\" cy=\"4\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"5\" cy=\"12\" r=\"1.5\" stroke=\"currentColor\"/><circle cx=\"11\" cy=\"6\" r=\"1.5\" stroke=\"currentColor\"/><path d=\"M5 5.5v5M11 7.5c0 2-2 2.5-6 3\" stroke=\"currentColor\"/></svg><span>main</span></button>",
|
||||
"css": ".ds-chip { display:inline-flex; align-items:center; gap:var(--space-1,4px); height:22px; padding:0 6px; border:0; background:transparent; border-radius:var(--radius-toolbar-button,6px); color:var(--fg-secondary,#5f6269); font-family:var(--font-ui); font-size:var(--fs-small,12px); line-height:1; cursor:default; transition:background var(--dur-fast,80ms) var(--ease); } .ds-chip svg { color:var(--fg-muted,#6c707e); } .ds-chip:hover { background:var(--bg-toolbar-hover,#00000012); } .ds-chip:focus-visible { outline:2px solid var(--focus-ring,#3871e1); outline-offset:-2px; }"
|
||||
},
|
||||
{
|
||||
"name": "Tree Rows",
|
||||
"kind": "custom",
|
||||
"refersTo": "list-row-selected",
|
||||
"description": "24px rows with an inset rounded selection wash; unfocused selection turns neutral.",
|
||||
"html": "<div class=\"ds-tree\" tabindex=\"0\"><div class=\"ds-row\">src</div><div class=\"ds-row ds-row-sel\">main.tsx</div><div class=\"ds-row\">workbench</div></div>",
|
||||
"css": ".ds-tree { width:220px; padding:4px var(--tree-inset,6px); background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); font-family:var(--font-ui); font-size:var(--fs-ui,13px); color:var(--fg,#000); outline:none; } .ds-row { height:var(--h-row,24px); display:flex; align-items:center; padding:0 8px; border-radius:var(--radius-row,4px); } .ds-row:hover { background:var(--bg-tree-hover,#0000000a); } .ds-row-sel, .ds-row-sel:hover { background:var(--bg-tree-selected-inactive,#e9eaee); } .ds-tree:focus .ds-row-sel { background:var(--bg-tree-selected,#d0dffe); }"
|
||||
},
|
||||
{
|
||||
"name": "Island on Frame",
|
||||
"kind": "card",
|
||||
"description": "The signature layout unit: rounded islands 6px apart on the grey frame, flat at rest.",
|
||||
"html": "<div class=\"ds-frame\"><div class=\"ds-island ds-side\"><div class=\"ds-head\">Project</div></div><div class=\"ds-island ds-main\"><code>fn main() {}</code></div></div>",
|
||||
"css": ".ds-frame { display:flex; gap:var(--island-gap,6px); padding:var(--island-gap,6px); background:var(--bg-frame,#e9eaee); height:160px; } .ds-island { background:var(--bg-island,#fff); border-radius:var(--island-radius,10px); } .ds-side { width:140px; } .ds-main { flex:1; padding:12px; font-family:var(--font-mono); font-size:var(--fs-code,13px); color:var(--fg-editor,#080808); } .ds-head { height:40px; display:flex; align-items:center; padding:0 12px; font-family:var(--font-ui); font-size:var(--fs-ui,13px); font-weight:600; color:var(--fg-strong,#000); }"
|
||||
},
|
||||
{
|
||||
"name": "Tooltip",
|
||||
"kind": "custom",
|
||||
"refersTo": "tooltip",
|
||||
"description": "Floating hover help: one of the few surfaces allowed a shadow.",
|
||||
"html": "<div class=\"ds-tooltip\">Run 'main' <span class=\"ds-kbd\">⌃R</span></div>",
|
||||
"css": ".ds-tooltip { display:inline-flex; gap:8px; align-items:center; padding:6px 10px; border-radius:var(--radius-tooltip,6px); background:var(--bg-tooltip,#fff); color:var(--fg-tooltip,#000); border:1px solid var(--border-tooltip,#d1d3d9); box-shadow:var(--shadow-tooltip,0 4px 12px rgba(0,0,0,.12)); font-family:var(--font-ui); font-size:var(--fs-ui,13px); } .ds-kbd { font-family:var(--font-keys); color:var(--fg-muted,#6c707e); }"
|
||||
}
|
||||
],
|
||||
"narrative": {
|
||||
"northStar": "The Quiet Workbench",
|
||||
"overview": "The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.\n\nThe visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.\n\nEvery panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.\n\nThe tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.\n\nExpression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.",
|
||||
"keyCharacteristics": [
|
||||
"JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.",
|
||||
"Grey frame, rounded content islands, tonal layering only.",
|
||||
"A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.",
|
||||
"High density on a 4px grid. Compact mode is a first-class variant.",
|
||||
"Controls are quiet at rest: toolbar buttons and chips have no frame until hover.",
|
||||
"Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.",
|
||||
"Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins."
|
||||
],
|
||||
"rules": [
|
||||
{
|
||||
"name": "The IDEA Reference Rule",
|
||||
"body": "When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.",
|
||||
"section": "overview"
|
||||
},
|
||||
{
|
||||
"name": "The One Accent Rule",
|
||||
"body": "Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.",
|
||||
"section": "colors"
|
||||
},
|
||||
{
|
||||
"name": "The Token Only Rule",
|
||||
"body": "Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.",
|
||||
"section": "colors"
|
||||
},
|
||||
{
|
||||
"name": "The Flat Scale Rule",
|
||||
"body": "The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.",
|
||||
"section": "typography"
|
||||
},
|
||||
{
|
||||
"name": "The User Owns Size Rule",
|
||||
"body": "Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.",
|
||||
"section": "typography"
|
||||
},
|
||||
{
|
||||
"name": "The Flat at Rest Rule",
|
||||
"body": "No docked panel, island, row or control gets a shadow. A shadow means \"this floats over the workbench and will go away\". Depth inside the layout is only ever a tonal step.",
|
||||
"section": "elevation"
|
||||
}
|
||||
],
|
||||
"dos": [
|
||||
"**Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).",
|
||||
"**Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.",
|
||||
"**Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.",
|
||||
"**Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.",
|
||||
"**Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.",
|
||||
"**Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.",
|
||||
"**Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.",
|
||||
"**Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`."
|
||||
],
|
||||
"donts": [
|
||||
"**Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.",
|
||||
"**Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.",
|
||||
"**Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.",
|
||||
"**Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.",
|
||||
"**Don't** put shadows on docked panels, islands, rows or controls.",
|
||||
"**Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.",
|
||||
"**Don't** use hex, `rgb()` or named colours in component CSS or inline styles.",
|
||||
"**Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature."
|
||||
]
|
||||
}
|
||||
}
|
||||
+2
-11
@@ -149,17 +149,8 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": [
|
||||
"evals/**/*.ts",
|
||||
"perf/**/*.ts",
|
||||
"smoke/**/*.ts",
|
||||
"src/features/vcs/**/*.ts",
|
||||
"src/features/vcs/**/*.tsx",
|
||||
"src/features/run/**/*.ts",
|
||||
"src/features/run/**/*.tsx",
|
||||
"src/features/database/**/*.ts",
|
||||
"src/features/database/**/*.tsx"
|
||||
],
|
||||
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
|
||||
"excludeFiles": ["e2e/**"],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
}
|
||||
|
||||
Створено
+263
-197
File diff suppressed because it is too large.
Load diff
+2
-2
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.51"
|
||||
version = "0.1.54"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -108,7 +108,7 @@ jupyter-zmq-client = { version = "=2.0.0", default-features = false, features =
|
||||
jupyter-protocol = "=2.0.3"
|
||||
zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] }
|
||||
lsp-types = "0.97"
|
||||
gix = { version = "0.89", default-features = false }
|
||||
gix = { version = "0.90", default-features = false }
|
||||
portable-pty = "0.9"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
---
|
||||
name: OpenIDEA
|
||||
description: The IDE you know, rebuilt in Rust.
|
||||
colors:
|
||||
workbench-blue: "#3871e1"
|
||||
link-blue: "#2f5eb9"
|
||||
frame-grey: "#e9eaee"
|
||||
island-white: "#ffffff"
|
||||
raised-paper: "#f7f8f9"
|
||||
ink: "#000000"
|
||||
ink-secondary: "#5f6269"
|
||||
ink-muted: "#6c707e"
|
||||
ink-faint: "#9fa2a8"
|
||||
hairline: "#e9eaee"
|
||||
control-edge: "#d1d3d9"
|
||||
selection-wash: "#d0dffe"
|
||||
tab-wash: "#e3ebfe"
|
||||
danger: "#c54e58"
|
||||
warning: "#a56906"
|
||||
success: "#338555"
|
||||
frame-grey-dark: "#26282c"
|
||||
island-dark: "#191a1c"
|
||||
ink-dark: "#d1d3d9"
|
||||
ink-strong-dark: "#dfe1e5"
|
||||
ink-muted-dark: "#8c8f95"
|
||||
control-edge-dark: "#40434a"
|
||||
selection-wash-dark: "#2a4371"
|
||||
typography:
|
||||
title:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "13px"
|
||||
fontWeight: 600
|
||||
lineHeight: 1.4
|
||||
body:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "13px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
label:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "12px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
label-tiny:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "11px"
|
||||
fontWeight: 400
|
||||
lineHeight: 1.4
|
||||
input-large:
|
||||
fontFamily: "Inter Variable, Inter, system-ui, -apple-system, sans-serif"
|
||||
fontSize: "15px"
|
||||
fontWeight: 400
|
||||
code:
|
||||
fontFamily: "JetBrains Mono, JetBrains Mono Variable, ui-monospace, Menlo, monospace"
|
||||
fontSize: "13px"
|
||||
fontWeight: 400
|
||||
lineHeight: "22px"
|
||||
fontFeature: "\"liga\" 0"
|
||||
rounded:
|
||||
small: "4px"
|
||||
control: "4px"
|
||||
row: "4px"
|
||||
selection: "5px"
|
||||
tab: "6px"
|
||||
toolbar-button: "6px"
|
||||
tooltip: "6px"
|
||||
popup: "8px"
|
||||
island: "10px"
|
||||
popup-large: "10px"
|
||||
dialog: "10px"
|
||||
spacing:
|
||||
space-0-5: "2px"
|
||||
space-1: "4px"
|
||||
space-1-5: "6px"
|
||||
space-2: "8px"
|
||||
space-3: "12px"
|
||||
space-4: "16px"
|
||||
components:
|
||||
button-primary:
|
||||
backgroundColor: "{colors.workbench-blue}"
|
||||
textColor: "{colors.island-white}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 16px"
|
||||
height: "28px"
|
||||
button-secondary:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 16px"
|
||||
height: "28px"
|
||||
button-ghost:
|
||||
textColor: "{colors.ink-secondary}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 8px"
|
||||
height: "28px"
|
||||
icon-button:
|
||||
textColor: "{colors.ink-muted}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
size: "24px"
|
||||
icon-button-selected:
|
||||
backgroundColor: "{colors.selection-wash}"
|
||||
textColor: "{colors.ink}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
size: "24px"
|
||||
input:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.control}"
|
||||
padding: "0 8px"
|
||||
height: "28px"
|
||||
chip:
|
||||
textColor: "{colors.ink-secondary}"
|
||||
typography: "{typography.label}"
|
||||
rounded: "{rounded.toolbar-button}"
|
||||
padding: "0 6px"
|
||||
height: "22px"
|
||||
tooltip:
|
||||
backgroundColor: "{colors.island-white}"
|
||||
textColor: "{colors.ink}"
|
||||
typography: "{typography.body}"
|
||||
rounded: "{rounded.tooltip}"
|
||||
padding: "6px 10px"
|
||||
list-row-selected:
|
||||
backgroundColor: "{colors.selection-wash}"
|
||||
textColor: "{colors.ink}"
|
||||
rounded: "{rounded.row}"
|
||||
height: "24px"
|
||||
---
|
||||
|
||||
# Design System: OpenIDEA
|
||||
|
||||
## Overview
|
||||
|
||||
**Creative North Star: "The Quiet Workbench"**
|
||||
|
||||
The interface is a workbench, not a showroom. Code, trees, logs and diffs are the work. The chrome around them stays quiet, so the eye goes to the content and a long session stays calm.
|
||||
|
||||
The visual language is the JetBrains new UI in its **Islands** form, and this document records it rather than inventing one. The tokens in `src/styles/tokens.css` take their values from the Islands Light and Islands Dark theme JSON and editor schemes, at 100% zoom. Component metrics follow the matching IntelliJ theme keys (a Swing `arc` is a diameter, so the CSS radius is half of it), and component CSS names the key it follows. Behaviour follows IDEA as well, from focus and selection to dialogs and drag and drop. Users bring their JetBrains muscle memory, so a layout, metric or state that looks or behaves differently from IDEA counts as a bug, not a style choice.
|
||||
|
||||
Every panel sits on a grey frame as a rounded island (10px corners, 6px gaps). Depth comes from that tonal step, not from decoration. The density is that of a professional desktop tool: 13px UI text, 24px rows, 28px controls, with a compact mode that tightens all of them.
|
||||
|
||||
The tokens are a theming contract, not one palette. The built-in themes are Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark. Users can also change the accent colour, give tool windows a different background from the editor, set a background image, use contrast scrollbars, or adjust colours for red-green vision deficiency. Imported IntelliJ themes and plugin themes set the same tokens at runtime. A component that looks right only in Islands Light is broken.
|
||||
|
||||
Expression is kept to precise details: one blue accent, controls with no frame until they're hovered, hairline frames on fields and secondary buttons, and fast state transitions. Three things are rejected outright. It must not look like a web app: no big rounded cards, airy marketing whitespace, decorative gradients or illustrations. It has no second accent colour. And it has no eye-catching animation.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The IDEA Reference Rule.** When tokens and this document don't answer a question, the answer is what IntelliJ IDEA does in the Islands theme, with the same metric and the same state behaviour. Take the value from the theme key, add it as a token, and name the key in a CSS comment.
|
||||
|
||||
**Key Characteristics:**
|
||||
|
||||
- JetBrains new UI (Islands): metrics and behaviour follow IntelliJ's theme keys.
|
||||
- Grey frame, rounded content islands, tonal layering only.
|
||||
- A single accent (Workbench Blue) for primary actions, focus, selection and the active tool window.
|
||||
- High density on a 4px grid. Compact mode is a first-class variant.
|
||||
- Controls are quiet at rest: toolbar buttons and chips have no frame until hover.
|
||||
- Semantic colour (status, VCS, diff, syntax) carries meaning and is never decoration.
|
||||
- Every colour and metric is a token in `src/styles/tokens.css`. Tokens are the public theme API for plugins.
|
||||
|
||||
## Colors
|
||||
|
||||
A near-neutral grey ramp with one cool blue accent. Status, VCS and syntax colours are functional vocabularies with fixed meanings. Values in the frontmatter are Islands Light (the default), and `-dark` keys are the Islands Dark counterparts. High Contrast, the Solarized themes, imported IntelliJ themes and plugin themes override the same tokens, so the names describe roles, not hexes.
|
||||
|
||||
### Project colour
|
||||
|
||||
- **Project wash** (`--project-color`): a radial tint of the project's colour (22% strength, 600 × 300px) that fades in from the frame's top-left corner, as the IDEA project gradient does. It identifies the project window. It is the one gradient in the chrome.
|
||||
|
||||
### Primary
|
||||
|
||||
- **Workbench Blue** (`--accent`): primary buttons, the focus ring, the selected-and-active stripe button, and search-match emphasis. The appearance setting can override it, so components reference `--accent`, never the hex.
|
||||
- **Link Blue** (`--link`): inline links. In Dark it lightens to stay readable on the dark islands.
|
||||
|
||||
### Neutral
|
||||
|
||||
- **Frame Grey** (`--bg-frame`): the window frame behind the islands, and the stripes (the tool window button bars).
|
||||
- **Island White** (`--bg-island`, `--bg-app`): editor and tool window surfaces. This is where the work lives.
|
||||
- **Raised Paper** (`--bg-elev`, `--bg-dialog`): dialog bodies and inline popups, one tonal step off the island.
|
||||
- **Ink** (`--fg`, `--fg-strong`): primary text. **Ink Secondary / Muted / Faint** (`--fg-secondary`, `--fg-muted`, `--fg-faint`): metadata, icons and placeholders, then disabled text.
|
||||
- **Hairline** (`--border`): dividers between regions inside an island. **Control Edge** (`--border-button`, `--border-strong`): the 1px inset frame of fields and secondary buttons.
|
||||
- **Selection Wash** (`--bg-tree-selected`, `--bg-selected`, `--bg-toolbar-selected`): the selected row in focused trees and lists, and pressed-on toolbar toggles. When the tree loses focus, the selection drops to the neutral `--bg-tree-selected-inactive`.
|
||||
|
||||
### Functional vocabularies
|
||||
|
||||
- **Status:** `--danger`, `--warning`, `--success` and `--info`, each with `--bg-feedback-*` and `--border-feedback-*` pairs for banners.
|
||||
- **VCS and diff:** `--vcs-*` for file status in trees and tabs, `--gutter-*` for gutter marks, and `--diff-*` for diff fills and their error-stripe marks.
|
||||
- **Syntax:** `--syn-*`, from the editor colour scheme. Users and plugins replace these per scheme.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The One Accent Rule.** Workbench Blue is the only accent. Every other hue in the UI belongs to a functional vocabulary (status, VCS, diff, syntax, charts) and means something specific. If a new colour has no meaning to carry, it doesn't ship.
|
||||
|
||||
**The Token Only Rule.** Components never contain hex, `rgb()` or named colour literals. A new colour is a new token with a value in every theme variant, named for its purpose. Run `pnpm gen:theme-docs` afterwards.
|
||||
|
||||
## Typography
|
||||
|
||||
**UI Font:** Inter Variable (with system-ui and -apple-system fallbacks)
|
||||
**Code Font:** JetBrains Mono (with ui-monospace and Menlo fallbacks)
|
||||
**Key Glyph Font:** the system UI font (`--font-keys`), so shortcut glyphs such as ⌘⇧⌥⌃↵ render as they do in native menus
|
||||
|
||||
**Character:** a neutral sans for chrome and a coding mono for content. Neither performs. Hierarchy comes from weight and colour, not size.
|
||||
|
||||
### Hierarchy
|
||||
|
||||
- **Title** (600, 13px, 1.4): tool window titles, section headers, dialog titles and emphasised names. Weight 600 is the system's main emphasis.
|
||||
- **Body** (400, 13px, 1.4): default UI text, menus, tree and list rows, and buttons.
|
||||
- **Label** (400, 12px): the most common size. It covers secondary metadata, chips, status bar items, table cells and hints.
|
||||
- **Label Tiny** (400, 11px): stripe labels, counters and badges.
|
||||
- **Input Large** (400, 15px): Search Everywhere and similar large query fields.
|
||||
- **Code** (400, 13px, 22px line height): the editor, console, terminal and every monospace preview. Ligatures are off by default and follow the `editor.ligatures` setting. Users set the weights (`--fw-code`, `--fw-code-bold`) and the size.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The Flat Scale Rule.** The UI uses 11, 12, 13 and 15px, and nothing in between. Emphasis is weight 600 or a stronger ink colour, not a bigger size.
|
||||
|
||||
**The User Owns Size Rule.** Sizes are tokens because users change them (UI font size, editor font, compact mode's -1px chrome offset). Never hard-code a font size.
|
||||
|
||||
## Layout
|
||||
|
||||
The window is a grey frame holding docked islands: the editor in the centre, tool windows around it, stripes of tool window buttons on the edges (58px wide), a titlebar with the main toolbar (40px), and a status bar (30px). The status bar sits directly on the frame with no divider. Islands sit 6px apart and have 10px corners. Trees are inset 6px inside their island.
|
||||
|
||||
Spacing follows a 4px grid (`--space-0-5` to `--space-4`, 2–16px). It is used for gaps, with component heights doing most of the rhythm work: rows 24px, fields and buttons 28px, small controls 24px or 20px, tabs 28px in a 38px tab bar, and tool window headers 40px.
|
||||
|
||||
**Compact mode** (`data-compact`) is a full variant, not an afterthought. Rows drop to 22px, fields and buttons to 24px, the titlebar and headers to 32px, the status bar to 24px, the island gap to 4px and island corners to 8px, and chrome text gets 1px smaller. Every layout must hold in both modes.
|
||||
|
||||
The app is a desktop window. It is never a scrolling page: the document never scrolls, and every scroll region is its own scroller inside an island. Dialogs open about 10vh from the top and below the titlebar. Wide reading surfaces, such as an agent conversation, cap their width (900px) inside the island.
|
||||
|
||||
## Elevation & Depth
|
||||
|
||||
Static layout is flat and layered by tone. The grey frame sits under white islands (in Dark, a lighter frame under darker islands). Shadows exist only on surfaces that float above the layout: popups, menus, dialogs, tooltips, balloons, undocked tool windows and drag ghosts. Dialogs use a window-style shadow, because they are separate windows in spirit.
|
||||
|
||||
### Shadow Vocabulary
|
||||
|
||||
- **Popup** (`--shadow-popup`; Light `0 6px 20px rgba(0,0,0,0.12)`): popups, menus, completion and the floating editor toolbar.
|
||||
- **Dialog** (`--shadow-dialog`): a hairline ring plus two soft drops, like a native window shadow.
|
||||
- **Tooltip** (`--shadow-tooltip`) and **Balloon** (`--shadow-balloon`): small and medium drops for hover help and notifications.
|
||||
|
||||
### Named Rules
|
||||
|
||||
**The Flat at Rest Rule.** No docked panel, island, row or control gets a shadow. A shadow means "this floats over the workbench and will go away". Depth inside the layout is only ever a tonal step.
|
||||
|
||||
## Shapes
|
||||
|
||||
Corners scale with the size of the surface. Small controls get 4px (buttons, fields, combos, rows, small icon buttons). Toolbar buttons, chips, tabs and tooltips get 6px, and selection highlights get 5px. Popups get 8–10px, and islands and dialogs get 10px. Compact mode tightens island corners to 8px and combo corners to 2px. Frames are drawn as 1px inset box-shadows rather than borders, so they never shift layout and can double on focus. There are no pills, circles (apart from macOS window buttons and status dots), or rounding beyond 10px.
|
||||
|
||||
## Components
|
||||
|
||||
Quiet and dependable. Components don't call attention to themselves, they behave the same everywhere, and they come from `src/ui/` primitives before anything custom.
|
||||
|
||||
### Buttons
|
||||
|
||||
- **Shape:** gently rounded (4px). Minimum width 72px, 28px tall, 16px horizontal padding. The small variant is 24px tall with 10px padding.
|
||||
- **Primary:** Workbench Blue fill with white text. Hover mixes it toward the strong ink colour (`--accent-hover`). Use it for one default action per dialog.
|
||||
- **Secondary:** island-coloured with a 1px Control Edge inset frame. Hover darkens the fill by about 6%.
|
||||
- **Ghost:** no fill or frame, secondary ink colour, 8px padding. Hover shows the toolbar hover wash and strong ink. Pressed is a stronger wash.
|
||||
- **Focus:** a 2px Workbench Blue outline, 1px outside the button. **Disabled:** transparent fill, faint text and a hairline frame.
|
||||
- **Motion:** background, colour and frame change over 80ms (`--dur-fast`) with `--ease`. There are no transitions under `prefers-reduced-motion`, and forced-colours mode gets a real border.
|
||||
|
||||
### Icon Buttons (toolbar actions)
|
||||
|
||||
- 20, 24 or 28px square, with 6px corners (4px at 20px). The icon is muted at rest.
|
||||
- Hover shows the toolbar hover wash (`--bg-toolbar-hover`, a translucent ink) across the full hit target, and the icon turns strong ink. Pressed shows `--bg-toolbar-pressed`.
|
||||
- A toggled-on button (`aria-pressed`) shows Selection Wash. The focus ring is drawn 2px inside the button.
|
||||
- Tone variants (`danger`, `accent`) recolour only the icon.
|
||||
|
||||
### Chips
|
||||
|
||||
- **Style:** flat, like the main toolbar's project and branch widgets. They are 22px tall with 6px corners, have no fill or frame at rest, and use 12px secondary ink with a muted icon.
|
||||
- **State:** a chip that opens a picker gets the toolbar hover wash. A read-only chip never changes on hover.
|
||||
|
||||
### Inputs / Fields
|
||||
|
||||
- **Style:** 28px tall with 8px horizontal padding and 4px corners. Island fill with a 1px Control Edge inset frame. Placeholders use the faint ink.
|
||||
- **Focus:** the frame turns Workbench Blue and doubles with a 1px outer ring, drawn entirely with box-shadow.
|
||||
- **Error:** the same doubled ring in `--danger`. **Disabled:** transparent fill, faint text and a hairline frame.
|
||||
- Search fields have a muted leading icon. Monospace fields use the code font.
|
||||
|
||||
### Lists and Trees
|
||||
|
||||
- Rows are 24px (22px compact). The selection is a 4–5px rounded wash inset from the island edge, not a full-bleed bar.
|
||||
- A focused selection uses Selection Wash, and an unfocused one drops to a neutral grey. Hover is a faint translucent wash. Search matches use `--bg-search-match`.
|
||||
|
||||
### Popups, Menus and Dialogs
|
||||
|
||||
- **Popups and menus:** `--bg-popup` with a 1px popup frame, 10px corners (`--radius-popup-large`) and the popup shadow.
|
||||
- **Dialogs:** Raised Paper body with 10px corners and the dialog shadow. They behave like IDEA's dialogs, which are separate windows: the modal layer blocks the workbench but never dims it. The footer actions are right-aligned buttons. Focus returns to wherever it came from when the dialog closes.
|
||||
|
||||
### Tabs
|
||||
|
||||
- 28px tabs (24px compact) in a 38px bar, with 6px corners and 8px horizontal padding.
|
||||
- As in IDEA, only the part holding focus accents its selected tab (`--bg-tab-selected` with `--border-tab-selected`). Elsewhere the selected tab drops to the neutral inactive pair.
|
||||
- **Tooltips:** 6px corners with 6px × 10px padding, using `--bg-tooltip` (white in Light, dark grey in Dark) and the tooltip shadow.
|
||||
|
||||
### Tool Window Stripes (signature)
|
||||
|
||||
The edge bars of tool window buttons are 58px wide on Frame Grey, with icons over 11px labels. Hover and selected states are translucent ink washes. The selected button of the active tool window fills with Workbench Blue and white content. This is the one place the accent fills a large shape in the chrome, and it marks the active tool window.
|
||||
|
||||
## Do's and Don'ts
|
||||
|
||||
### Do:
|
||||
|
||||
- **Do** match IntelliJ IDEA's Islands theme for any metric or state that isn't tokenized yet. Take the value from the theme key and name the key in a CSS comment (for example `Button.arc 8 (radius 4)`).
|
||||
- **Do** take every colour and metric from `src/styles/tokens.css`, and add a token for every theme variant when you need a new one.
|
||||
- **Do** separate regions with a tonal step (frame against island) or a 1px hairline, never with a shadow.
|
||||
- **Do** keep toolbar buttons and chips without a frame at rest, with the toolbar hover wash over the full hit target.
|
||||
- **Do** draw frames and focus rings as inset box-shadows (1px at rest, doubled on focus), and keep the 2px Workbench Blue focus outline visible.
|
||||
- **Do** check every surface in Islands Light and Islands Dark at least, as the contribution guidelines require. Check High Contrast and compact density whenever a change touches colour or metrics.
|
||||
- **Do** keep transitions to state changes: 80ms (`--dur-fast`), 140ms (`--dur`) or at most 220ms (`--dur-slow`) with `--ease`, and none under reduced motion.
|
||||
- **Do** use icons from the `src/ui/icons.tsx` registry, drawn in `currentColor`.
|
||||
|
||||
### Don't:
|
||||
|
||||
- **Don't** make it look like a web app: no large rounded cards, airy marketing whitespace, decorative gradients, hero illustrations or corners above 10px. The project wash is the one gradient in the chrome. Progress shimmer counts as activity, not decoration.
|
||||
- **Don't** invent a look or behaviour where IDEA already has one. A custom variant of an IDEA pattern breaks muscle memory.
|
||||
- **Don't** add a second accent. Any hue other than Workbench Blue must carry status, VCS, diff, syntax or chart meaning.
|
||||
- **Don't** add attention-seeking animation: no bounces, no staggered entrances, and no state transition over 220ms. Looping animation is only for activity that is really happening (spinners, progress, loading shimmer, a running pulse, the caret), never decoration.
|
||||
- **Don't** put shadows on docked panels, islands, rows or controls.
|
||||
- **Don't** use sizes off the 11/12/13/15px scale, or hard-code a font size users can change.
|
||||
- **Don't** use hex, `rgb()` or named colours in component CSS or inline styles.
|
||||
- **Don't** use emoji as icons or decoration, or inline ad-hoc SVG in a feature.
|
||||
@@ -0,0 +1,73 @@
|
||||
# Product
|
||||
|
||||
<!-- impeccable:product-schema 1 -->
|
||||
|
||||
## Platform
|
||||
|
||||
web
|
||||
|
||||
The IDE is a Tauri desktop app for macOS, Windows and Linux. Its UI is a web frontend (React, CSS Modules) inside the system webview, with its own design language rather than each operating system's native one. Scope: this record covers the IDE application only. The openidea.sh docs site and home page (`docs/`) are out of scope.
|
||||
|
||||
## Users
|
||||
|
||||
- **Primary: JetBrains users who want something lighter.** They already know the IntelliJ IDEA keymap, tool windows and search-everything habits, and find IDEA heavy and slow. They do everyday multi-language development on the desktop: editing, navigating, refactoring, running and debugging, Git, terminal, database and HTTP clients.
|
||||
- **Primary: developers working with AI coding agents.** They run CLI agents (Claude Code, Codex, Gemini CLI, Copilot, Cursor and others over ACP) inside the IDE as tasks, often several at once, each in its own Git worktree or in the checkout. They review the agents' diffs, answer their permission requests, and give agents the IDE's own tools through the built-in MCP server.
|
||||
- **Secondary: people moving from VS Code or Eclipse.** Their keymaps are built in.
|
||||
|
||||
## Product Purpose
|
||||
|
||||
OpenIDEA brings the IntelliJ IDEA way of working to a native app with a Rust core: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages. Success means people who know the IDEA way of working can switch without relearning anything, and it opens, responds and quits much faster while using a fraction of the memory.
|
||||
|
||||
## Positioning
|
||||
|
||||
"The IDE you know, rebuilt in Rust." The habits are familiar (keymap, tool windows, Search Everywhere, Alt+Enter), the app is open source (Apache 2.0), and performance is measured: on the published benchmark, the window opens in 0.9 s against 3.1 s and the app uses 169 MB against 2011 MB. Coding agents are part of the IDE (tasks, worktrees, diffs and the IDE's tools over MCP) rather than a separate chat app.
|
||||
|
||||
## Operating Context
|
||||
|
||||
- Long sessions in one desktop window: the editor in the middle, tool windows docked around it, and keyboard-first navigation (Search Everywhere, Find Action, Go to Class/File/Symbol).
|
||||
- Local projects, and remote development over SSH or in dev containers through the `openidea-server` backend.
|
||||
- Agent tasks running alongside the developer's own work, with diff review and permission prompts.
|
||||
- Built-in themes: Islands Light (the default), Islands Dark, High Contrast, Solarized Light and Solarized Dark, with an option to follow the OS's light or dark mode. Users can import IntelliJ themes and `.icls` colour schemes, and plugins add more themes.
|
||||
|
||||
## Capabilities and Constraints
|
||||
|
||||
Hard constraints future work must preserve:
|
||||
|
||||
1. The default keymap and interaction habits stay the same as IDEA's.
|
||||
2. All user-visible text is written in English and must also have a Chinese translation, through the text catalog (`T`, translated `aria-label`).
|
||||
3. WebKit floor is Safari 15.4 (macOS 12). No regex lookbehind or `v` flag, no import attributes, and no newer runtime APIs in startup code. `scripts/check-webkit.ts` enforces this.
|
||||
4. Design tokens in `src/styles/tokens.css` are the public theme API for plugins. Components use tokens only and never colour literals. A new token needs a value for every theme variant, and the docs must be regenerated with `pnpm gen:theme-docs`.
|
||||
5. Every user operation is an action with a stable id, reachable from the keyboard and Find Action, not only by mouse.
|
||||
6. No emoji as icons or decoration, in the UI or in user-visible text. Icons come from the `src/ui/icons.tsx` registry.
|
||||
7. Performance (startup, memory, idle CPU) is the core selling point. UI work must not slow it down.
|
||||
|
||||
Other facts:
|
||||
|
||||
- Plugins are sandboxed WebAssembly components that add actions, completion, quick fixes, tool windows, custom editors, themes, file icons and languages. The plugin API is still a preview.
|
||||
- UI is built from the primitives in `src/ui/` (Button, Dialog, Popup, Menu, List, Tree, Tabs and others). Workbench pieces come from contributions, not custom layout.
|
||||
|
||||
## Brand Commitments
|
||||
|
||||
- Name: OpenIDEA. Wordmarks are in `src-tauri/icons/source/` (`openidea-wordmark.svg` and `openidea-wordmark-dark.svg`).
|
||||
- Not affiliated with JetBrains. IntelliJ IDEA is a trademark of JetBrains s.r.o.
|
||||
- Voice is plain, short and factual. It states measurements with their conditions rather than superlatives.
|
||||
|
||||
## Evidence on Hand
|
||||
|
||||
- Benchmark table and method: `README.md`, `perf/compare`. The conditions are stated with it: freqtrade, warm caches, median of 5 runs, Windows 11, 32-core AMD.
|
||||
- Demo video linked from `README.md`.
|
||||
- No testimonials, customer logos or user counts exist. Do not fabricate them.
|
||||
|
||||
## Product Principles
|
||||
|
||||
1. **Familiar first.** Existing IDEA habits must keep working. New behaviour must not break that muscle memory.
|
||||
2. **Speed is a feature.** Every surface is judged by how much it costs in startup time, memory and responsiveness.
|
||||
3. **Keyboard reachable.** If something can be done, it is an action that can be found and bound.
|
||||
4. **Agents work inside the IDE.** Agent work is reviewed and controlled with the IDE's own tools: diffs, worktrees and permissions.
|
||||
5. **Themeable by contract.** Visual decisions go through tokens that themes and plugins can rely on.
|
||||
|
||||
## Accessibility & Inclusion
|
||||
|
||||
- Use real `<button>` and `<input>` elements or the primitives that render them. Every icon-only button has a translated `aria-label`.
|
||||
- Keep focus visible and predictable. Dialogs and popups return focus to where it came from.
|
||||
- A dark high-contrast theme (`dark-hc`) ships and must be kept working.
|
||||
@@ -33,6 +33,12 @@ its search-everything habits — to a native app with a Rust core.
|
||||
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
|
||||
for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
|
||||
On macOS you can also install it with Homebrew:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Benchmark
|
||||
|
||||
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
|
||||
|
||||
@@ -33,6 +33,12 @@ her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir
|
||||
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
|
||||
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
|
||||
|
||||
macOS'ta Homebrew ile de kurabilirsiniz:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Performans karşılaştırması
|
||||
|
||||
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
|
||||
|
||||
@@ -35,6 +35,12 @@ OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处
|
||||
编辑器、代码洞察、调试器、Git、终端、数据库客户端和 HTTP 客户端,支持 60 多种语言。
|
||||
提供 macOS、Windows 和 Linux 版本。
|
||||
|
||||
在 macOS 上也可以用 Homebrew 安装:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## 性能对比
|
||||
|
||||
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),
|
||||
|
||||
@@ -6,6 +6,30 @@
|
||||
[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: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
|
||||
|
||||
DuckDB is a trademark of the DuckDB Foundation. The data source icon uses the
|
||||
light and dark symbols from the [DuckDB Design Manual](https://duckdb.org/design/manual/#logo-usage).
|
||||
The SVG paths and colors are preserved. See the [DuckDB trademark guidelines](https://duckdb.org/trademark_guidelines.html).
|
||||
|
||||
## Agent logos
|
||||
|
||||
The `src/ui/openidea/agents/` logos of agents listed in the
|
||||
[ACP agent registry](https://github.com/agentclientprotocol/registry) (`agoragentic-acp`, `amp-acp`,
|
||||
`antigravity-acp`, `autohand`, `bob`, `cline`, `codebuddy-code`, `cortex-code`, `corust-agent`,
|
||||
`crow-cli`, `deepagents`, `devin`, `dimcode`, `dirac`, `factory-droid`, `fast-agent`, `glm-acp-agent`,
|
||||
`grok-build`, `harn`, `junie`, `kilo`, `kimchi`, `minimax-code`, `minion-code`, `muse-code`, `nova`,
|
||||
`pi-acp`, `poolside`, `sigit`, `stakpak`, `vtcode`) are the registry's icons, with a root `fill`
|
||||
moved onto a group. The registry is licensed under Apache-2.0; the logos remain trademarks of
|
||||
their owners.
|
||||
|
||||
## Microsoft ConPTY
|
||||
|
||||
`crates/ide-core/resources/conpty/` contains the unmodified Microsoft Windows Console
|
||||
ConPTY runtime 1.25.260930003, embedded in Windows builds. Copyright (c) Microsoft
|
||||
Corporation. Licensed under MIT; see its [license](crates/ide-core/resources/conpty/LICENSE)
|
||||
and [package provenance](crates/ide-core/resources/conpty/README.md).
|
||||
|
||||
## Project Lombok
|
||||
|
||||
`java/lombok/lombok-1.18.48-openidea.3.jar` contains Project Lombok v1.18.48 with the Equinox
|
||||
@@ -66,7 +90,7 @@ At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor
|
||||
These icons of [flutter-intellij](https://github.com/flutter/flutter-intellij) (commit `d02813ad5890`) are used
|
||||
under the BSD 3-Clause License:
|
||||
|
||||
- `src/ui/expui/flutter/*.svg`: the DevTools tool window icons, copied unmodified from
|
||||
- `src/ui/expui/flutter/*.svg`: the Flutter tool window icons, copied unmodified from
|
||||
`resources/icons/expui/`.
|
||||
- `src/ui/expui/flutter/[email protected]` and `[email protected]`: the Flutter outline's widget
|
||||
icons, `resources/icons/custom/[email protected]` and `[email protected]`, renamed, content unmodified.
|
||||
@@ -131,6 +155,7 @@ languages whose JetBrains icons are not open source (Go, Ruby, Dart, Lua, Zig,
|
||||
Svelte, …). Those using the page-with-corner-badge layout (`goMod`, `goWork`,
|
||||
`dotenv`, `readme`, `lock`, `license`) reuse the page outline of the Apache-2.0
|
||||
expui `fileTypes/h.svg`; that outline is modified from the original by JetBrains.
|
||||
`goTest` adds a scaled copy of the Apache-2.0 expui `nodes/test.svg` as its badge.
|
||||
`src/ui/openidea/runConfigurations/springBoot*.svg` (the Spring Boot run configuration
|
||||
leaf) is OpenIDEA's own drawing.
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
let retry = run_once(shared, spec, true, model).await;
|
||||
@@ -196,11 +196,11 @@ fn levels_for_model_from_slice(options: &[AgentConfigOption]) -> Vec<AgentConfig
|
||||
.filter(|o| config::is_per_model_option(o))
|
||||
.cloned()
|
||||
.map(|mut o| {
|
||||
if config::is_context_option(&o.id) {
|
||||
if config::is_context_option(&o.id) || config::is_fast_option(&o.id) {
|
||||
if o.category.is_none() {
|
||||
o.category = Some("model_config".into());
|
||||
}
|
||||
} else if o.category.as_deref() != Some("thought_level") {
|
||||
} else if o.category.is_none() {
|
||||
o.category = Some("thought_level".into());
|
||||
}
|
||||
o
|
||||
|
||||
@@ -168,11 +168,12 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
|
||||
assert_eq!(calls.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/new"]);
|
||||
assert_eq!(calls[1].1["mcpServers"], json!([]));
|
||||
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
|
||||
let fast = cursor.config.iter().find(|o| o.id == "fast").expect("fast option");
|
||||
// Per-model options (`effort`, `fast`, `context`) belong to the session's model, not provider-wide config.
|
||||
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
|
||||
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
|
||||
let fast = cursor.thought_levels["m1"].iter().find(|o| o.id == "fast").expect("fast option");
|
||||
assert_eq!(fast.category.as_deref(), Some("model_config"));
|
||||
assert_eq!(fast.current.as_deref(), Some("false"));
|
||||
// The effort option belongs to the session's model; m2 may offer other levels.
|
||||
assert_eq!(cursor.thought_levels.keys().collect::<Vec<_>>(), ["m1"]);
|
||||
assert!(cursor.thought_levels["m1"].iter().any(|o| o.category.as_deref() == Some("thought_level")));
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ use tokio::time::Instant;
|
||||
|
||||
const FRESH_FOR: Duration = Duration::from_secs(15 * 60);
|
||||
const COOLDOWN: Duration = Duration::from_secs(30);
|
||||
/// Persisted catalog layout version; bump when option classification changes so stale per-model entries re-discover.
|
||||
const CATALOG_SCHEMA: u8 = 2;
|
||||
|
||||
type Store = Arc<Mutex<HashMap<String, Known>>>;
|
||||
type Key = (PathBuf, PathBuf, String);
|
||||
@@ -80,6 +82,8 @@ impl CatalogData {
|
||||
pub(crate) struct SavedCatalog {
|
||||
/// An opaque cryptographic digest, never raw launch arguments or credentials.
|
||||
fingerprint: String,
|
||||
#[serde(default)]
|
||||
schema: u8,
|
||||
#[serde(flatten)]
|
||||
catalog: CatalogData,
|
||||
}
|
||||
@@ -111,7 +115,7 @@ impl LaunchContext {
|
||||
hash.update(&(value.len() as u64).to_le_bytes());
|
||||
hash.update(value);
|
||||
}
|
||||
field(&mut hash, b"openidea-model-catalog-v1");
|
||||
field(&mut hash, b"openidea-model-catalog-v2");
|
||||
field(
|
||||
&mut hash,
|
||||
match self.spec.driver {
|
||||
@@ -200,7 +204,14 @@ impl AgentCatalogs {
|
||||
cache
|
||||
.get(provider)
|
||||
.and_then(|known| known.catalogs.get(&shared.root_key()))
|
||||
.map(|saved| saved.catalog.clone())
|
||||
.map(|saved| {
|
||||
let mut catalog = saved.catalog.clone();
|
||||
if saved.schema < CATALOG_SCHEMA {
|
||||
catalog.refreshed_at_ms = None;
|
||||
catalog.thought_levels.clear();
|
||||
}
|
||||
catalog
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -228,7 +239,8 @@ impl AgentCatalogs {
|
||||
}
|
||||
drop(state);
|
||||
let cache = shared.known.lock();
|
||||
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
|
||||
let saved = cache.get(provider)?.catalogs.get(&shared.root_key())?;
|
||||
(saved.schema >= CATALOG_SCHEMA).then(|| saved.catalog.thought_levels.get(model).cloned()).flatten()
|
||||
}
|
||||
|
||||
pub(super) async fn load_levels(
|
||||
@@ -271,6 +283,20 @@ impl AgentCatalogs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
|
||||
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
|
||||
let key = Self::key(shared, provider);
|
||||
let mut state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get_mut(&key)
|
||||
&& entry.flight.is_none()
|
||||
&& entry.error.is_some()
|
||||
{
|
||||
entry.completed = None;
|
||||
entry.retry_at_ms = None;
|
||||
entry.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
@@ -281,7 +307,7 @@ impl AgentCatalogs {
|
||||
AgentModelCatalog {
|
||||
provider: provider.to_owned(),
|
||||
config: shared.config_for_new_task(catalog.config, provider),
|
||||
thought_levels: catalog.thought_levels,
|
||||
thought_levels: shared.thought_levels_for_new_task(catalog.thought_levels, provider),
|
||||
refreshing: entry.flight.is_some(),
|
||||
refreshed_at_ms: catalog.refreshed_at_ms,
|
||||
retry_at_ms: model_failure
|
||||
@@ -318,7 +344,9 @@ impl AgentCatalogs {
|
||||
let generation = state.generation;
|
||||
let saved =
|
||||
shared.known.lock().get(&spec.id).and_then(|known| known.catalogs.get(&shared.root_key())).cloned();
|
||||
let matching = saved.as_ref().is_some_and(|saved| saved.fingerprint == context.fingerprint());
|
||||
let matching = saved
|
||||
.as_ref()
|
||||
.is_some_and(|saved| saved.schema >= CATALOG_SCHEMA && saved.fingerprint == context.fingerprint());
|
||||
let age = saved
|
||||
.as_ref()
|
||||
.filter(|_| matching)
|
||||
@@ -489,7 +517,11 @@ impl AgentCatalogs {
|
||||
}
|
||||
known.catalogs.insert(
|
||||
shared.root_key(),
|
||||
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
|
||||
SavedCatalog {
|
||||
fingerprint: entry.context.fingerprint(),
|
||||
schema: CATALOG_SCHEMA,
|
||||
catalog: catalog.clone(),
|
||||
},
|
||||
);
|
||||
entry.catalog = Some(catalog);
|
||||
shared.persist_known(&cache);
|
||||
@@ -595,6 +627,40 @@ impl crate::AgentManager {
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
|
||||
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
|
||||
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
|
||||
.into_iter()
|
||||
.find(|p| p.id == "copilot")
|
||||
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
|
||||
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
let account = account.trim();
|
||||
if !account.is_empty() {
|
||||
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
|
||||
}
|
||||
match discover(&self.shared, spec, model).await {
|
||||
Ok(found) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: self.shared.config_for_new_task(found.config, "copilot"),
|
||||
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
|
||||
retry_at_ms: None,
|
||||
error: None,
|
||||
}),
|
||||
Err(error) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: Vec::new(),
|
||||
thought_levels: BTreeMap::new(),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: None,
|
||||
retry_at_ms: None,
|
||||
error: Some(error),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover(
|
||||
|
||||
@@ -65,7 +65,7 @@ fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
}
|
||||
|
||||
/// Moves options that approve everything without asking to a value that asks: the agent's
|
||||
/// default or ask mode, else its first one that asks.
|
||||
/// own default (when it asks), else `default` or `ask`, else its first one that asks.
|
||||
pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
for option in config {
|
||||
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
|
||||
@@ -73,9 +73,15 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
continue;
|
||||
}
|
||||
let asks = |v: &&AgentConfigValue| !bypass(&v.value);
|
||||
let value = ["default", "ask"]
|
||||
.iter()
|
||||
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
|
||||
let value = option
|
||||
.default_value
|
||||
.as_deref()
|
||||
.and_then(|def| option.values.iter().filter(asks).find(|v| v.value == def))
|
||||
.or_else(|| {
|
||||
["default", "ask"]
|
||||
.iter()
|
||||
.find_map(|preferred| option.values.iter().filter(asks).find(|v| v.value == *preferred))
|
||||
})
|
||||
.or_else(|| option.values.iter().find(asks));
|
||||
if let Some(value) = value {
|
||||
option.current = Some(value.value.clone());
|
||||
@@ -83,11 +89,26 @@ pub(crate) fn ask_for_approvals(config: &mut [AgentConfigOption]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode that approves everything without asking (`bypassPermissions`, `yolo`, `full-access`…), if the agent has one.
|
||||
pub(crate) fn bypass_mode(options: &[AgentConfigOption]) -> Option<(&AgentConfigOption, &AgentConfigValue)> {
|
||||
let option = options.iter().find(|o| o.category.as_deref() == Some("mode"))?;
|
||||
let value = option.values.iter().find(|v| is_bypass_mode(&v.value))?;
|
||||
Some((option, value))
|
||||
/// Moves approval-bearing options (`mode`, `permissions`, `approval`) to their approving value.
|
||||
pub(crate) fn apply_bypass_approvals(config: &mut [AgentConfigOption]) {
|
||||
for option in config {
|
||||
let Some(bypass) = option.category.as_deref().and_then(bypass_value) else { continue };
|
||||
if let Some(value) = option.values.iter().find(|v| bypass(&v.value)) {
|
||||
option.current = Some(value.value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies provider-specific defaults to per-model options for new tasks without altering `default_value`.
|
||||
pub(crate) fn apply_model_defaults(provider: &str, options: &mut [AgentConfigOption]) {
|
||||
if provider != "cursor" {
|
||||
return;
|
||||
}
|
||||
if let Some(fast) = options.iter_mut().find(|o| is_fast_option(&o.id))
|
||||
&& fast.values.iter().any(|v| v.value == "false")
|
||||
{
|
||||
fast.current = Some("false".into());
|
||||
}
|
||||
}
|
||||
|
||||
fn is_bypass_mode(mode: &str) -> bool {
|
||||
@@ -126,15 +147,22 @@ pub(crate) fn options_of(result: &Value) -> Vec<AgentConfigOption> {
|
||||
}
|
||||
|
||||
pub(crate) fn is_context_option(id: &str) -> bool {
|
||||
matches!(id, "context_tier" | "contextTier")
|
||||
matches!(id, "context" | "context_tier" | "contextTier")
|
||||
}
|
||||
|
||||
pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
id == "fast"
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`thought_level` and model context-tier options) rather than the provider as a whole.
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context`, `fast` and `service_tier`)
|
||||
/// rather than the provider as a whole.
|
||||
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier"))
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|
||||
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
|| is_fast_option(&o.id)
|
||||
|| is_context_option(&o.id)
|
||||
|| o.id == "service_tier"
|
||||
}
|
||||
|
||||
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
|
||||
@@ -164,7 +192,7 @@ pub(crate) fn parse_options(options: &Value) -> Vec<AgentConfigOption> {
|
||||
matches!(id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
.then(|| "thought_level".into())
|
||||
})
|
||||
.or_else(|| (id == "fast" || is_context_option(&id)).then(|| "model_config".into()))
|
||||
.or_else(|| (is_fast_option(&id) || is_context_option(&id)).then(|| "model_config".into()))
|
||||
}),
|
||||
current,
|
||||
default_value,
|
||||
@@ -337,6 +365,11 @@ fn legacy(
|
||||
}
|
||||
}
|
||||
|
||||
fn clean_label(s: String, fallback: &str) -> String {
|
||||
let trimmed = s.trim_matches(|c: char| c.is_whitespace() || matches!(c, '\u{200B}'..='\u{200D}' | '\u{FEFF}'));
|
||||
if trimmed.is_empty() { fallback.to_owned() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
fn value_of(v: &Value) -> Option<AgentConfigValue> {
|
||||
let value = v.get("value")?.as_str()?.to_owned();
|
||||
let meta = v.get("_meta");
|
||||
@@ -352,7 +385,7 @@ fn value_of(v: &Value) -> Option<AgentConfigValue> {
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned);
|
||||
Some(AgentConfigValue {
|
||||
name: str_of(v, "name").unwrap_or_else(|| value.clone()),
|
||||
name: str_of(v, "name").map(|n| clean_label(n, &value)).unwrap_or_else(|| value.clone()),
|
||||
description: str_of(v, "description"),
|
||||
cost_category,
|
||||
usage_multiplier,
|
||||
@@ -434,19 +467,16 @@ mod tests {
|
||||
]}
|
||||
}));
|
||||
assert!(bypass_approvals(&full_access));
|
||||
assert_eq!(bypass_mode(&full_access).map(|(_, v)| v.value.as_str()), Some("full-access"));
|
||||
|
||||
let asking = options_of(&json!({
|
||||
let mut asking = options_of(&json!({
|
||||
"modes": {"currentModeId": "ask", "availableModes": [
|
||||
{"id": "ask", "name": "Ask"}, {"id": "full-access", "name": "Full Access"}
|
||||
]}
|
||||
}));
|
||||
assert!(!bypass_approvals(&asking));
|
||||
assert_eq!(
|
||||
bypass_mode(&asking).map(|(_, v)| v.value.as_str()),
|
||||
Some("full-access"),
|
||||
"the offered bypass mode stays available"
|
||||
);
|
||||
apply_bypass_approvals(&mut asking);
|
||||
assert_eq!(asking[0].current.as_deref(), Some("full-access"));
|
||||
assert!(bypass_approvals(&asking));
|
||||
|
||||
let permissions = |current: &str| {
|
||||
options_of(&json!({"configOptions": [{
|
||||
@@ -503,7 +533,16 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_and_fast_categories_are_inferred_from_ids() {
|
||||
fn service_tier_is_per_model() {
|
||||
let options = options_of(&json!({ "configOptions": [
|
||||
{ "id": "service_tier", "type": "select", "currentValue": "false",
|
||||
"options": [{ "value": "false" }, { "value": "true" }] }
|
||||
] }));
|
||||
assert!(is_per_model_option(&options[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_context_and_fast_are_per_model_options() {
|
||||
let mut c = options_of(&json!({
|
||||
"configOptions": [
|
||||
{"id": "model", "type": "select", "currentValue": "gemini-4-carbon",
|
||||
@@ -512,19 +551,39 @@ mod tests {
|
||||
"_meta": {"copilotPriceCategory": "Medium", "copilotUsage": "1x"}}]},
|
||||
{"id": "effort", "type": "select", "currentValue": "medium",
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
|
||||
{"id": "context", "type": "select", "currentValue": "256k",
|
||||
"options": [{"value": "256k", "name": "256K"}, {"value": "500k", "name": "500K"}]},
|
||||
{"id": "contextTier", "type": "select", "currentValue": "default",
|
||||
"options": [{"value": "default", "name": "200K"}, {"value": "long_context", "name": "1M"}]},
|
||||
{"id": "fast", "type": "select", "currentValue": "false",
|
||||
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "On"}]}
|
||||
{"id": "fast", "type": "select", "currentValue": "true",
|
||||
"options": [{"value": "false", "name": "Off"}, {"value": "true", "name": "Fast\u{200b}\u{200b}"}]}
|
||||
]
|
||||
}));
|
||||
assert_eq!(c.len(), 4);
|
||||
assert_eq!(c.len(), 5);
|
||||
assert_eq!(c[0].values[0].cost_category.as_deref(), Some("medium"));
|
||||
assert_eq!(c[0].values[0].usage_multiplier.as_deref(), Some("1x"));
|
||||
assert_eq!(c[1].category.as_deref(), Some("thought_level"));
|
||||
assert_eq!(c[1].default_value.as_deref(), Some("medium"));
|
||||
assert_eq!(c[2].category.as_deref(), Some("model_config"));
|
||||
assert!(is_per_model_option(&c[1]) && is_per_model_option(&c[2]) && !is_per_model_option(&c[3]));
|
||||
assert_eq!(c[3].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[4].category.as_deref(), Some("model_config"));
|
||||
assert_eq!(c[4].values[1].name, "Fast");
|
||||
assert!(
|
||||
is_per_model_option(&c[1])
|
||||
&& is_per_model_option(&c[2])
|
||||
&& is_per_model_option(&c[3])
|
||||
&& is_per_model_option(&c[4])
|
||||
);
|
||||
assert!(!is_per_model_option(&c[0]));
|
||||
|
||||
// Cursor defaults fast off for new tasks while preserving the agent's own default_value.
|
||||
let mut cursor_opts = c.clone();
|
||||
apply_model_defaults("cursor", &mut cursor_opts);
|
||||
let fast = cursor_opts.iter().find(|o| o.id == "fast").unwrap();
|
||||
assert_eq!((fast.current.as_deref(), fast.default_value.as_deref()), (Some("false"), Some("true")));
|
||||
let mut other_opts = c.clone();
|
||||
apply_model_defaults("claude", &mut other_opts);
|
||||
assert_eq!(other_opts.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("true"));
|
||||
|
||||
// Editing effort on the same model preserves its initial `default_value` for Reset.
|
||||
merge_update(
|
||||
@@ -546,11 +605,34 @@ mod tests {
|
||||
{"id": "model", "type": "select", "currentValue": "gpt-6-sol",
|
||||
"options": [{"value": "gemini-4-carbon"}, {"value": "gpt-6-sol"}]},
|
||||
{"id": "effort", "type": "select", "currentValue": "low",
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]}
|
||||
"options": [{"value": "low"}, {"value": "medium"}, {"value": "high"}]},
|
||||
{"id": "context", "type": "select", "currentValue": "1m",
|
||||
"options": [{"value": "300k", "name": "300K"}, {"value": "1m", "name": "1M"}]}
|
||||
]),
|
||||
);
|
||||
let effort = c.iter().find(|o| o.id == "effort").unwrap();
|
||||
assert_eq!((effort.current.as_deref(), effort.default_value.as_deref()), (Some("low"), Some("low")));
|
||||
let context = c.iter().find(|o| o.id == "context").unwrap();
|
||||
assert_eq!((context.current.as_deref(), context.default_value.as_deref()), (Some("1m"), Some("1m")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_bypass_approvals_covers_mode_permissions_and_approval() {
|
||||
let mut c = options_of(&json!({"configOptions": [
|
||||
{"id": "mode", "category": "mode", "type": "select", "currentValue": "ask",
|
||||
"options": [{"value": "ask"}, {"value": "full-access"}]},
|
||||
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "off",
|
||||
"options": [{"value": "off"}, {"value": "on"}]},
|
||||
{"id": "approval", "category": "approval", "type": "select", "currentValue": "ask",
|
||||
"options": [{"value": "ask"}, {"value": "bypass"}]}
|
||||
]}));
|
||||
apply_bypass_approvals(&mut c);
|
||||
assert_eq!(ids(&c), [("mode", Some("full-access")), ("allow_all", Some("on")), ("approval", Some("bypass"))]);
|
||||
// Original agent default_values stay intact.
|
||||
assert_eq!(
|
||||
c.iter().map(|o| o.default_value.as_deref()).collect::<Vec<_>>(),
|
||||
[Some("ask"), Some("off"), Some("ask")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Images in agent content: ACP content blocks, `data:` URLs and image files on disk.
|
||||
|
||||
use crate::model::AgentImage;
|
||||
use base64::Engine;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::Path;
|
||||
|
||||
/// Image files larger than this are not inlined into the conversation.
|
||||
const MAX_FILE_BYTES: u64 = 10 * 1024 * 1024;
|
||||
|
||||
/// The image an ACP content block shows: an `image` (inline or by URI), a `resource` with an
|
||||
/// image blob, or a `resource_link` to an image file.
|
||||
pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
|
||||
match str_of(content, "type")? {
|
||||
"image" => {
|
||||
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
}
|
||||
from_uri(str_of(content, "uri")?)
|
||||
}
|
||||
"resource" => {
|
||||
let resource = content.get("resource")?;
|
||||
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
|
||||
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
|
||||
}
|
||||
"resource_link" => {
|
||||
let uri = str_of(content, "uri")?;
|
||||
let declared = str_of(content, "mimeType").is_some_and(|m| m.starts_with("image/"));
|
||||
if !declared && mime_of(Path::new(&uri_path(uri))).is_none() {
|
||||
return None;
|
||||
}
|
||||
let mut image = from_uri(uri)?;
|
||||
image.name = str_of(content, "name").map(str::to_owned);
|
||||
Some(image)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn str_of<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
|
||||
v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// The image at a `data:` URL or a `file://` URI.
|
||||
pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
|
||||
if let Some(rest) = uri.strip_prefix("data:") {
|
||||
let (mime, data) = rest.split_once(";base64,")?;
|
||||
return (mime.starts_with("image/") && !data.is_empty()).then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
});
|
||||
}
|
||||
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
|
||||
}
|
||||
|
||||
/// The image file at `path`, when it has an image extension and isn't too large.
|
||||
pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
|
||||
let mime = mime_of(path)?;
|
||||
if std::fs::metadata(path).ok()?.len() > MAX_FILE_BYTES {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
(!bytes.is_empty()).then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: base64::engine::general_purpose::STANDARD.encode(bytes),
|
||||
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
|
||||
})
|
||||
}
|
||||
|
||||
/// `image` as an ACP image content block.
|
||||
pub(crate) fn content(image: &AgentImage) -> Value {
|
||||
json!({ "type": "image", "mimeType": image.media_type(), "data": image.data })
|
||||
}
|
||||
|
||||
fn mime_of(path: &Path) -> Option<&'static str> {
|
||||
let ext = path.extension()?.to_str()?.to_ascii_lowercase();
|
||||
Some(match ext.as_str() {
|
||||
"png" => "image/png",
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"gif" => "image/gif",
|
||||
"webp" => "image/webp",
|
||||
"bmp" => "image/bmp",
|
||||
"svg" => "image/svg+xml",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
|
||||
pub(crate) fn uri_path(uri: &str) -> String {
|
||||
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
|
||||
let bytes = rest.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
|
||||
{
|
||||
out.push(b);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let path = String::from_utf8_lossy(&out).into_owned();
|
||||
// `file:///C:/x` on Windows.
|
||||
match path.as_bytes() {
|
||||
[b'/', drive, b':', ..] if drive.is_ascii_alphabetic() => path[1..].to_owned(),
|
||||
_ => path,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn content_blocks_inline_data_urls_blobs_and_image_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("shot 1.png");
|
||||
std::fs::write(&file, b"\x89PNG\r\n").unwrap();
|
||||
std::fs::write(dir.path().join("notes.txt"), b"hi").unwrap();
|
||||
let uri = crate::file_uri(&file);
|
||||
let inline = json!({"type": "image", "mimeType": "image/png", "data": "aW1n"});
|
||||
assert_eq!(from_content(&inline).unwrap().data, "aW1n");
|
||||
let by_url = json!({"type": "image", "uri": "data:image/jpeg;base64,AAA"});
|
||||
assert_eq!(from_content(&by_url).unwrap().mime_type, "image/jpeg");
|
||||
let by_file = from_content(&json!({"type": "image", "uri": uri})).unwrap();
|
||||
assert_eq!(by_file.data, base64::engine::general_purpose::STANDARD.encode(b"\x89PNG\r\n"));
|
||||
let blob = json!({"type": "resource", "resource": {"uri": "x", "mimeType": "image/gif", "blob": "R0lG"}});
|
||||
assert_eq!(from_content(&blob).unwrap().mime_type, "image/gif");
|
||||
let link = from_content(&json!({"type": "resource_link", "uri": uri, "name": "shot"})).unwrap();
|
||||
assert_eq!((link.mime_type.as_str(), link.name.as_deref()), ("image/png", Some("shot")));
|
||||
let text = crate::file_uri(&dir.path().join("notes.txt"));
|
||||
assert!(from_content(&json!({"type": "resource_link", "uri": text, "name": "notes"})).is_none());
|
||||
assert!(from_content(&json!({"type": "resource", "resource": {"uri": "x", "text": "t"}})).is_none());
|
||||
assert!(from_content(&json!({"type": "image", "uri": "https://example.com/a.png"})).is_none());
|
||||
assert!(from_file(&dir.path().join("missing.png")).is_none());
|
||||
}
|
||||
}
|
||||
+853
-152
File diff suppressed because it is too large.
Load diff
@@ -547,6 +547,9 @@ pub enum AgentEntry {
|
||||
started_ms: Option<f64>,
|
||||
#[serde(default)]
|
||||
ended_ms: Option<f64>,
|
||||
/// The command an `execute` call runs, from its structured input; `None` when the agent gave none.
|
||||
#[serde(default)]
|
||||
command: Option<String>,
|
||||
},
|
||||
Plan {
|
||||
items: Vec<AgentPlanItem>,
|
||||
@@ -612,6 +615,9 @@ pub struct AgentProvider {
|
||||
/// Executable and arguments actually launched, without flattening paths containing spaces.
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
/// Settings-managed suffix of `args`; absent for launches that cannot be edited.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub additional_args: Option<Vec<String>>,
|
||||
pub default_program: Option<String>,
|
||||
pub default_args: Vec<String>,
|
||||
pub login_hint: Option<String>,
|
||||
@@ -620,6 +626,9 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
|
||||
#[serde(default)]
|
||||
pub can_sign_in: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
@@ -644,6 +653,34 @@ pub enum AgentCommandReadOnlyReason {
|
||||
CustomAgent,
|
||||
}
|
||||
|
||||
/// An authenticated `github.com` account stored in GitHub CLI (`gh`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhAuthAccount {
|
||||
pub login: String,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
/// GitHub Copilot's default sign-in status alongside the accounts available through `gh`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CopilotAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
pub gh_installed: bool,
|
||||
pub gh_accounts: Vec<GhAuthAccount>,
|
||||
}
|
||||
|
||||
/// Output and completion of an interactive sign-in PTY started by the IDE.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum AgentLoginEvent {
|
||||
Output { data: String },
|
||||
Exited { code: Option<i32> },
|
||||
}
|
||||
|
||||
/// Where an agent comes from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
@@ -700,6 +737,10 @@ pub struct NewAgentTask {
|
||||
/// `!` command runs in it first.
|
||||
#[serde(default)]
|
||||
pub idle: bool,
|
||||
/// A throwaway task (Generate Commit Message): it isn't saved, so it doesn't outlive a
|
||||
/// restart, and the agent keeps no session history of its own for it.
|
||||
#[serde(default)]
|
||||
pub ephemeral: bool,
|
||||
}
|
||||
|
||||
/// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
|
||||
|
||||
@@ -30,6 +30,67 @@ pub(super) fn transcript(config_dir: &Path, cwd: &Path, id: &str) -> PathBuf {
|
||||
.unwrap_or(direct)
|
||||
}
|
||||
|
||||
/// Brings session `id` into `config_dir` when it is missing there but another Claude Code
|
||||
/// configuration directory beside it (`~/.claude`, `~/.claude-work`...) has it: switching
|
||||
/// `CLAUDE_CONFIG_DIR` (another account) would otherwise lose every earlier conversation.
|
||||
/// Copies the transcript and its folder (subagents, tool results) under the same project
|
||||
/// directory name. Returns whether the session is in `config_dir` now.
|
||||
pub(super) fn adopt(config_dir: &Path, cwd: &Path, id: &str) -> bool {
|
||||
if transcript(config_dir, cwd, id).exists() {
|
||||
return true;
|
||||
}
|
||||
let file = format!("{id}.jsonl");
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
|
||||
let mut homes: Vec<PathBuf> = config_dir
|
||||
.parent()
|
||||
.into_iter()
|
||||
.chain(home.as_deref())
|
||||
.flat_map(|dir| std::fs::read_dir(dir).into_iter().flatten().flatten())
|
||||
.filter(|d| d.file_name().to_string_lossy().starts_with(".claude"))
|
||||
.map(|d| d.path())
|
||||
.filter(|p| p != config_dir && p.join("projects").is_dir())
|
||||
.collect();
|
||||
homes.sort();
|
||||
homes.dedup();
|
||||
let found = homes.iter().find_map(|other| {
|
||||
let projects = other.join("projects");
|
||||
let direct = projects.join(escape(cwd));
|
||||
std::iter::once(direct.clone())
|
||||
.chain(std::fs::read_dir(&projects).into_iter().flatten().flatten().map(|d| d.path()))
|
||||
.find(|dir| dir.join(&file).is_file())
|
||||
});
|
||||
let Some(source) = found else { return false };
|
||||
let Some(name) = source.file_name() else { return false };
|
||||
let target = config_dir.join("projects").join(name);
|
||||
let copied = std::fs::create_dir_all(&target)
|
||||
.and_then(|()| copy_tree(&source.join(id), &target.join(id)))
|
||||
.and_then(|()| std::fs::copy(source.join(&file), target.join(&file)).map(drop));
|
||||
match copied {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
tracing::warn!("claude session {id}: copying it from {}: {e}", source.display());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
if !from.is_dir() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::create_dir_all(to)?;
|
||||
for entry in std::fs::read_dir(from)? {
|
||||
let entry = entry?;
|
||||
let dest = to.join(entry.file_name());
|
||||
if entry.file_type()?.is_dir() {
|
||||
copy_tree(&entry.path(), &dest)?;
|
||||
} else if !dest.exists() {
|
||||
std::fs::copy(entry.path(), dest)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The project directory name Claude Code uses for `cwd`.
|
||||
pub(crate) fn escape(cwd: &Path) -> String {
|
||||
cwd.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()
|
||||
@@ -207,6 +268,26 @@ mod tests {
|
||||
json!({"type": "assistant", "uuid": id, "parentUuid": parent, "message": {"role": "assistant", "content": content}})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_from_another_config_dir_is_copied_in() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let (old, new) = (root.path().join(".claude-2"), root.path().join(".claude-3"));
|
||||
let cwd = Path::new("/work/app");
|
||||
let project = old.join("projects").join(escape(cwd));
|
||||
std::fs::create_dir_all(project.join("s1/subagents")).unwrap();
|
||||
std::fs::write(project.join("s1.jsonl"), "{}\n").unwrap();
|
||||
std::fs::write(project.join("s1/subagents/a.jsonl"), "{}\n").unwrap();
|
||||
std::fs::create_dir_all(new.join("projects")).unwrap();
|
||||
|
||||
assert!(!adopt(&new, cwd, "missing"));
|
||||
assert!(adopt(&new, cwd, "s1"));
|
||||
let copied = new.join("projects").join(escape(cwd));
|
||||
assert_eq!(transcript(&new, cwd, "s1"), copied.join("s1.jsonl"));
|
||||
assert!(copied.join("s1/subagents/a.jsonl").is_file());
|
||||
assert!(project.join("s1.jsonl").is_file(), "the original stays");
|
||||
assert!(adopt(&new, cwd, "s1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_branch_is_the_conversation() {
|
||||
let entries = vec![
|
||||
|
||||
@@ -178,6 +178,8 @@ struct Session {
|
||||
additional_dirs: Vec<String>,
|
||||
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
|
||||
skills_settings: Option<String>,
|
||||
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
|
||||
ephemeral: bool,
|
||||
shim: Weak<Shim>,
|
||||
st: Mutex<State>,
|
||||
/// Serializes (re)starting the process.
|
||||
@@ -334,6 +336,12 @@ impl Shim {
|
||||
Some(history::transcript(self.config.config_dir.as_deref()?, cwd, id))
|
||||
}
|
||||
|
||||
/// Whether session `id` is in the configuration directory, copied there from another one
|
||||
/// if need be (see [`history::adopt`]).
|
||||
fn adopt(&self, cwd: &Path, id: &str) -> bool {
|
||||
self.config.config_dir.as_deref().is_some_and(|dir| history::adopt(dir, cwd, id))
|
||||
}
|
||||
|
||||
/// The conversation a session started with `start` begins with.
|
||||
fn base_chain(&self, cwd: &Path, start: &Start) -> Result<Vec<Value>, String> {
|
||||
let (id, at) = match start {
|
||||
@@ -370,6 +378,7 @@ impl Shim {
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
additional_dirs: additional_dirs(params),
|
||||
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
|
||||
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
proc: None,
|
||||
@@ -435,10 +444,13 @@ impl Shim {
|
||||
let id = params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
|
||||
let cwd = self.cwd_of(¶ms);
|
||||
let (start, pending) = match self.load_pending(id) {
|
||||
Some(s) => (s, true),
|
||||
None if self.transcript(&cwd, id).is_some_and(|p| p.exists()) => {
|
||||
(Start::Resume { id: id.to_owned(), at: None }, false)
|
||||
Some(s) => {
|
||||
if let Start::Resume { id: from, .. } | Start::Fork { from, .. } = &s {
|
||||
self.adopt(&cwd, from);
|
||||
}
|
||||
(s, true)
|
||||
}
|
||||
None if self.adopt(&cwd, id) => (Start::Resume { id: id.to_owned(), at: None }, false),
|
||||
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
|
||||
};
|
||||
let chain = self.base_chain(&cwd, &start).map_err(internal)?;
|
||||
@@ -451,24 +463,43 @@ impl Shim {
|
||||
Ok(json!({ "configOptions": session.st.lock().settings.options() }))
|
||||
}
|
||||
"session/fork" => {
|
||||
let source = self.session(¶ms)?;
|
||||
let id = new_uuid(false);
|
||||
let (start, settings) = {
|
||||
let st = source.st.lock();
|
||||
let start = match &st.start {
|
||||
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
|
||||
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
|
||||
}
|
||||
Start::New { .. } => Start::New { id: id.clone() },
|
||||
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
|
||||
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
|
||||
}
|
||||
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
|
||||
};
|
||||
(start, st.settings.clone())
|
||||
let source_id =
|
||||
params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
|
||||
let source = self.sessions.lock().get(source_id).cloned();
|
||||
// The host names the fork's session id so the task knows it before the CLI
|
||||
// starts; only a canonical UUID is accepted.
|
||||
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
|
||||
if let Some(target) = requested
|
||||
&& !crate::canonical_uuid(target)
|
||||
{
|
||||
return Err(invalid("A fork session id must be a canonical UUID"));
|
||||
}
|
||||
let id = requested.map_or_else(|| new_uuid(false), str::to_owned);
|
||||
if self.sessions.lock().contains_key(&id) {
|
||||
return Err(invalid(format!("session {id} is already open")));
|
||||
}
|
||||
let cwd = source.as_ref().map_or_else(|| self.cwd_of(¶ms), |session| session.cwd.clone());
|
||||
let (start, settings) = match &source {
|
||||
Some(source) => {
|
||||
let st = source.st.lock();
|
||||
let start = match &st.start {
|
||||
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
|
||||
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
|
||||
}
|
||||
Start::New { .. } => Start::New { id: id.clone() },
|
||||
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
|
||||
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
|
||||
}
|
||||
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
|
||||
};
|
||||
(start, st.settings.clone())
|
||||
}
|
||||
// A recorded session is not open in this connection: the CLI forks it
|
||||
// from its transcript on disk when the task's first prompt starts it.
|
||||
None => (Start::Fork { from: source_id.to_owned(), id: id.clone(), at: None }, Settings::default()),
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, ¶ms);
|
||||
let session = self.add_session(&id, cwd, start, true, ¶ms);
|
||||
session.st.lock().settings = settings;
|
||||
let options = session.st.lock().settings.options();
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
@@ -505,7 +536,16 @@ impl Shim {
|
||||
"_openidea/context_usage" => {
|
||||
let session = self.session(¶ms)?;
|
||||
let proc = session.st.lock().proc.clone().ok_or_else(|| internal("Claude Code is not running"))?;
|
||||
rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)
|
||||
let usage = rt.block_on(proc.control(json!({ "subtype": "get_context_usage" }))).map_err(internal)?;
|
||||
// The meter shows the same numbers as these details from now on.
|
||||
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
|
||||
if let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) {
|
||||
let update = session.st.lock().tr.on_context_usage(used, size);
|
||||
if let Some(shim) = session.shim() {
|
||||
shim.notify(vec![update]);
|
||||
}
|
||||
}
|
||||
Ok(usage)
|
||||
}
|
||||
"_openidea/stop_task" => {
|
||||
let session = self.session(¶ms)?;
|
||||
@@ -694,6 +734,9 @@ impl Session {
|
||||
if let Some(settings) = &self.skills_settings {
|
||||
args.extend(["--settings".to_owned(), settings.clone()]);
|
||||
}
|
||||
if self.ephemeral {
|
||||
args.push("--no-session-persistence".to_owned());
|
||||
}
|
||||
args.extend(start.args());
|
||||
let launch =
|
||||
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
|
||||
|
||||
@@ -464,6 +464,7 @@ async fn replay_simple() {
|
||||
let args = r.cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--session-id", r.session.as_str()]), "{args:?}");
|
||||
assert!(args.contains(&"--permission-prompt-tool".to_owned()));
|
||||
assert!(!args.contains(&"--no-session-persistence".to_owned()));
|
||||
let user = r.sent(0).into_iter().find(|m| m["type"] == "user").unwrap();
|
||||
assert_eq!(user["message"]["content"][0]["text"], "Reply with exactly: hello there");
|
||||
}
|
||||
@@ -652,6 +653,84 @@ async fn replay_resume() {
|
||||
assert!(args.windows(2).any(|w| w == ["--resume", r.session.as_str()]), "{args:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() {
|
||||
/// Registering a fork must not start a process: its first prompt does.
|
||||
struct NoLaunch;
|
||||
impl Cli for NoLaunch {
|
||||
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
|
||||
panic!("session/fork must not launch the CLI")
|
||||
}
|
||||
}
|
||||
|
||||
let config = tempfile::tempdir().unwrap();
|
||||
let pending = tempfile::tempdir().unwrap();
|
||||
let h = Harness::connect(
|
||||
Arc::new(NoLaunch),
|
||||
config.path().to_path_buf(),
|
||||
pending.path().to_path_buf(),
|
||||
std::env::temp_dir(),
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
let source = "11111111-1111-4111-8111-111111111111";
|
||||
let target = "22222222-2222-4222-8222-222222222222";
|
||||
let reply = h
|
||||
.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": source,
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": target } }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(reply["sessionId"], target);
|
||||
// The host chose this id for the fork: the next process must fork the recorded
|
||||
// session under exactly it.
|
||||
let saved: Value =
|
||||
serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap();
|
||||
assert_eq!(saved, json!({ "fork": source, "id": target, "at": null }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_rejects_a_requested_id_that_is_not_canonical() {
|
||||
struct NoLaunch;
|
||||
impl Cli for NoLaunch {
|
||||
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
|
||||
panic!("no process")
|
||||
}
|
||||
}
|
||||
|
||||
let config = tempfile::tempdir().unwrap();
|
||||
let pending = tempfile::tempdir().unwrap();
|
||||
let h = Harness::connect(
|
||||
Arc::new(NoLaunch),
|
||||
config.path().to_path_buf(),
|
||||
pending.path().to_path_buf(),
|
||||
std::env::temp_dir(),
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
for rejected in ["../../x", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", ""] {
|
||||
let error = h
|
||||
.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": "11111111-1111-4111-8111-111111111111",
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": rejected } }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect_err("only a canonical id may name the fork");
|
||||
assert!(error.to_string().contains("canonical"), "{rejected}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- recording ----------
|
||||
|
||||
/// Passes the real CLI's stdio through, keeping what went over it.
|
||||
@@ -1148,6 +1227,24 @@ fn a_compaction_replaces_the_context_usage() {
|
||||
assert!(t.on_result(&result).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_codes_own_window_wins_over_the_results_context_window() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
let assistant = |model: &str| {
|
||||
json!({"type": "assistant", "parent_tool_use_id": null,
|
||||
"message": {"id": "m1", "model": model, "content": [], "usage": {"input_tokens": 900, "output_tokens": 100}}})
|
||||
};
|
||||
t.on_message(&assistant("x"));
|
||||
let result = json!({"modelUsage": {"x": {"contextWindow": 1_000_000}, "y": {"contextWindow": 200_000}}});
|
||||
assert_eq!(t.on_result(&result)[0].update["size"], 1_000_000);
|
||||
// `get_context_usage` reports the window Claude Code compacts against.
|
||||
assert_eq!(t.on_context_usage(1000, 400_000).update["size"], 400_000);
|
||||
assert_eq!(t.on_result(&result)[0].update["size"], 400_000);
|
||||
// Another model: its own window again until Claude Code reports one for it.
|
||||
t.on_message(&assistant("y"));
|
||||
assert_eq!(t.on_result(&result)[0].update["size"], 200_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limits_and_cost() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), false);
|
||||
@@ -1332,3 +1429,16 @@ fn additional_directories_are_read_from_the_session_params() {
|
||||
assert_eq!(additional_dirs(¶ms), ["/w/web", "/w/docs"]);
|
||||
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_session_is_not_saved() {
|
||||
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": { "ephemeral": true } } });
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
|
||||
}
|
||||
@@ -58,6 +58,10 @@ pub(super) struct Translator {
|
||||
pub used: Option<u64>,
|
||||
pub model: Option<String>,
|
||||
windows: HashMap<String, u64>,
|
||||
/// The window Claude Code itself counts against (`get_context_usage` `maxTokens`) and the
|
||||
/// model it was read for. It can be smaller than the model's `contextWindow` in a `result`
|
||||
/// (its compaction threshold follows this one), so it wins while the model is the same.
|
||||
context_max: Option<(Option<String>, u64)>,
|
||||
/// The session's cost so far in USD, as the last `result` reported it.
|
||||
cost_usd: Option<f64>,
|
||||
}
|
||||
@@ -77,6 +81,7 @@ impl Translator {
|
||||
used: None,
|
||||
model: None,
|
||||
windows: HashMap::new(),
|
||||
context_max: None,
|
||||
cost_usd: None,
|
||||
}
|
||||
}
|
||||
@@ -571,6 +576,7 @@ impl Translator {
|
||||
/// The context usage Claude Code reports (`get_context_usage`), as a usage update.
|
||||
pub fn on_context_usage(&mut self, used: u64, size: u64) -> Update {
|
||||
self.used = Some(used);
|
||||
self.context_max = Some((self.model.clone(), size));
|
||||
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
|
||||
if let Some(amount) = self.cost_usd {
|
||||
update["cost"] = json!({ "amount": amount, "currency": "USD" });
|
||||
@@ -580,13 +586,14 @@ impl Translator {
|
||||
|
||||
fn usage_update(&self) -> Option<Update> {
|
||||
let used = self.used?;
|
||||
let size = self
|
||||
.model
|
||||
.as_ref()
|
||||
.and_then(|m| {
|
||||
self.windows
|
||||
.get(m)
|
||||
.or_else(|| self.windows.iter().find(|(k, _)| k.starts_with(m.as_str())).map(|(_, v)| v))
|
||||
let own = self.context_max.as_ref().filter(|(model, _)| *model == self.model).map(|(_, size)| size);
|
||||
let size = own
|
||||
.or_else(|| {
|
||||
self.model.as_ref().and_then(|m| {
|
||||
self.windows
|
||||
.get(m)
|
||||
.or_else(|| self.windows.iter().find(|(k, _)| k.starts_with(m.as_str())).map(|(_, v)| v))
|
||||
})
|
||||
})
|
||||
.or_else(|| (self.windows.len() == 1).then(|| self.windows.values().next()).flatten())?;
|
||||
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
|
||||
|
||||
@@ -108,7 +108,7 @@ pub(crate) async fn discover(
|
||||
let options = translate::config_options(&models, &settings);
|
||||
let levels = crate::config::options_of(&json!({ "configOptions": options }))
|
||||
.into_iter()
|
||||
.filter(|o| o.category.as_deref() == Some("thought_level"))
|
||||
.filter(|o| matches!(o.category.as_deref(), Some("thought_level" | "model_config")))
|
||||
.collect();
|
||||
(model.id.clone(), levels)
|
||||
})
|
||||
@@ -492,8 +492,14 @@ impl CodexShim {
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
// Not written to `~/.codex/sessions`, so it isn't listed among the past threads.
|
||||
if params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool) == Some(true) {
|
||||
request["ephemeral"] = json!(true);
|
||||
}
|
||||
let result = self.call("thread/start", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, None);
|
||||
let mut settings = Settings::of(&result, &models);
|
||||
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
|
||||
let (id, options) = self.open_thread(&result, &models, Some(settings));
|
||||
if id.is_empty() {
|
||||
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
|
||||
}
|
||||
@@ -510,7 +516,9 @@ impl CodexShim {
|
||||
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
let result = self.call("thread/resume", request).await?;
|
||||
let (_, options) = self.open_thread(&result, &models, None);
|
||||
let mut settings = Settings::of(&result, &models);
|
||||
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
|
||||
let (_, options) = self.open_thread(&result, &models, Some(settings));
|
||||
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
|
||||
let thread = result.get("thread").unwrap_or(&Value::Null);
|
||||
for update in translate::history(thread, cwd.as_deref()) {
|
||||
@@ -613,6 +621,9 @@ impl CodexShim {
|
||||
if let Some(effort) = &s.effort {
|
||||
request["effort"] = json!(effort);
|
||||
}
|
||||
if let Some(tier) = s.service_tier_override(&models) {
|
||||
request["serviceTier"] = json!(tier);
|
||||
}
|
||||
}
|
||||
self.call("turn/start", request).await
|
||||
}
|
||||
@@ -1470,14 +1481,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
|
||||
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
|
||||
let message = translate::error_message(&e);
|
||||
return match translate::classify(&e, rate_limits) {
|
||||
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
|
||||
Failure::UsageLimit(resets) => Err(ResponseError {
|
||||
code: codes::INTERNAL_ERROR,
|
||||
message,
|
||||
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
|
||||
}),
|
||||
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
|
||||
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
};
|
||||
}
|
||||
_ => "end_turn",
|
||||
@@ -1595,3 +1605,6 @@ fn mcp_text(response: &Value) -> String {
|
||||
.collect::<Vec<_>>();
|
||||
format!("MCP servers:\n{}", lines.join("\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod reconnect_tests;
|
||||
@@ -0,0 +1,217 @@
|
||||
//! User-facing task operations through the native shim, with a local app-server stand-in.
|
||||
use super::*;
|
||||
use crate::{AgentManager, AgentPrompt, AgentStatus, Isolation, NewAgentTask};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Runtime {
|
||||
models: Mutex<HashMap<String, String>>,
|
||||
hide_a: std::sync::atomic::AtomicBool,
|
||||
turns: Mutex<Vec<Value>>,
|
||||
tiers: Mutex<HashMap<String, Value>>,
|
||||
servers: Mutex<Vec<Peer>>,
|
||||
}
|
||||
struct Connection {
|
||||
runtime: Arc<Runtime>,
|
||||
peer: OnceLock<Peer>,
|
||||
}
|
||||
impl Handler for Connection {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
fn on_request(&self, method: &str, p: Value) -> Result<Value, (i64, String)> {
|
||||
match method {
|
||||
"initialize" => Ok(json!({})),
|
||||
"model/list" => {
|
||||
let mut data = vec![json!({"id":"b", "model":"b", "serviceTiers":[]})];
|
||||
if !self.runtime.hide_a.swap(false, std::sync::atomic::Ordering::SeqCst) {
|
||||
data.insert(0, json!({"id":"a", "model":"a", "isDefault":true, "serviceTiers":[{"id":"fast"}]}));
|
||||
}
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
"config/read" => Ok(json!({"layers":[]})),
|
||||
"skills/list" => Ok(json!({"data":[]})),
|
||||
"thread/start" | "thread/resume" => {
|
||||
let mut models = self.runtime.models.lock();
|
||||
let id = p["threadId"].as_str().map(str::to_owned).unwrap_or_else(|| format!("s{}", models.len()));
|
||||
let model = models.entry(id.clone()).or_insert_with(|| "a".into()).clone();
|
||||
Ok(json!({"thread":{"id":id,"name":"fixture","turns":[]}, "model":model,
|
||||
"serviceTier":self.runtime.tiers.lock().get(&id).cloned().unwrap_or(json!("fast"))}))
|
||||
}
|
||||
"turn/start" => {
|
||||
let id = p["threadId"].as_str().unwrap();
|
||||
self.runtime.models.lock().insert(id.into(), p["model"].as_str().unwrap().into());
|
||||
if let Some(tier) = p.get("serviceTier") {
|
||||
self.runtime.tiers.lock().insert(id.into(), tier.clone());
|
||||
}
|
||||
self.runtime.turns.lock().push(p.clone());
|
||||
self.peer
|
||||
.get()
|
||||
.unwrap()
|
||||
.notify(
|
||||
"turn/completed",
|
||||
json!({"threadId":id,
|
||||
"turn":{"id":"t","status":"completed"}}),
|
||||
)
|
||||
.unwrap();
|
||||
Ok(json!({"turn":{"id":"t"}}))
|
||||
}
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn manager(dir: &Path, runtime: Arc<Runtime>) -> AgentManager {
|
||||
let agents = dir.join("agents");
|
||||
crate::provider::set_builtin_command(&agents, None, "codex", Some("/missing/fixture-codex")).unwrap();
|
||||
AgentManager::with_connector(
|
||||
crate::AgentPaths {
|
||||
project_root: dir.into(),
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
custom_agents_dir: Some(agents),
|
||||
home_dir: Some(dir.into()),
|
||||
env_secrets: None,
|
||||
catalogs: Arc::default(),
|
||||
},
|
||||
tokio::runtime::Handle::current(),
|
||||
Arc::new(move |spec, _, client, _| {
|
||||
assert_eq!(spec.driver, crate::provider::Driver::Codex);
|
||||
let handler = Arc::new(Connection { runtime: runtime.clone(), peer: OnceLock::new() });
|
||||
let (a, b) = tokio::io::duplex(1 << 20);
|
||||
let (r, w) = tokio::io::split(b);
|
||||
let server = Peer::connect_framed(r, w, handler.clone(), Framing::Lines);
|
||||
handler.peer.set(server.clone()).ok().unwrap();
|
||||
runtime.servers.lock().push(server);
|
||||
attach(client, |events| {
|
||||
let (r, w) = tokio::io::split(a);
|
||||
Ok(Peer::connect_framed(r, w, events, Framing::Lines))
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
fn prompt() -> AgentPrompt {
|
||||
AgentPrompt { text: "fixture".into(), ..Default::default() }
|
||||
}
|
||||
async fn ready(mgr: &AgentManager, id: &str) {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let task = mgr.task(id).unwrap();
|
||||
let (status, busy) = {
|
||||
let s = task.state.lock();
|
||||
(s.task.status, s.busy)
|
||||
};
|
||||
assert_ne!(status, AgentStatus::Failed);
|
||||
if status == AgentStatus::Ready && !busy {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn send(mgr: &AgentManager, id: &str) {
|
||||
mgr.prompt(id, prompt(), false).await.unwrap();
|
||||
ready(mgr, id).await;
|
||||
}
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn explicit_tier_survives_standard_only_reconnect_before_immediate_prompt() {
|
||||
for late_model in [0, 1, 2, 3] {
|
||||
for choice in [Some("true"), Some("false"), None] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let runtime = Arc::new(Runtime::default());
|
||||
let mgr = manager(tmp.path(), runtime.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "codex".into(),
|
||||
prompt: prompt(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
ready(&mgr, &task.id).await;
|
||||
let catalog_config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
|
||||
if let Some(value) = choice {
|
||||
mgr.set_config(&task.id, "service_tier", value.into()).await.unwrap();
|
||||
}
|
||||
send(&mgr, &task.id).await;
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
|
||||
);
|
||||
mgr.set_config(&task.id, "model", "b".into()).await.unwrap();
|
||||
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
|
||||
send(&mgr, &task.id).await;
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|_| json!("default")).as_ref()
|
||||
);
|
||||
mgr.shutdown();
|
||||
drop(mgr);
|
||||
runtime.hide_a.store(late_model >= 2, std::sync::atomic::Ordering::SeqCst);
|
||||
let mut mgr = manager(tmp.path(), runtime.clone());
|
||||
send(&mgr, &task.id).await; // Reconnect while still on Standard-only B.
|
||||
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|_| json!("default")).as_ref()
|
||||
);
|
||||
if late_model != 0 {
|
||||
// Catalog knows A, but the session's picker has not received it yet.
|
||||
let current = mgr.task(&task.id).unwrap();
|
||||
let mut s = current.state.lock();
|
||||
let catalog = serde_json::from_value(
|
||||
json!({"fingerprint":"fixture", "schema":2, "config":catalog_config, "thoughtLevels":{"a":catalog_config.iter().filter(|o|crate::config::is_per_model_option(o)).collect::<Vec<_>>() }}),
|
||||
)
|
||||
.unwrap();
|
||||
mgr.shared
|
||||
.known
|
||||
.lock()
|
||||
.entry("codex".into())
|
||||
.or_default()
|
||||
.catalogs
|
||||
.insert(mgr.shared.root_key(), catalog);
|
||||
s.task.config.iter_mut().find(|o| o.id == "model").unwrap().values.retain(|v| v.value != "a");
|
||||
}
|
||||
mgr.set_config(&task.id, "model", "a".into()).await.unwrap();
|
||||
if late_model == 3 {
|
||||
// An older saved pending switch has no retained intent field.
|
||||
mgr.task(&task.id).unwrap().state.lock().pending_model.as_mut().unwrap().retained_service_tier = None;
|
||||
mgr.shutdown();
|
||||
mgr = manager(tmp.path(), runtime.clone());
|
||||
}
|
||||
let displayed = mgr
|
||||
.task(&task.id)
|
||||
.unwrap()
|
||||
.state
|
||||
.lock()
|
||||
.snapshot()
|
||||
.config
|
||||
.iter()
|
||||
.find(|o| o.id == "service_tier")
|
||||
.unwrap()
|
||||
.current
|
||||
.clone();
|
||||
assert_eq!(displayed.as_deref(), Some(choice.unwrap_or("true")));
|
||||
send(&mgr, &task.id).await; // No sleeps/retries between selecting A and submitting.
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
|
||||
);
|
||||
let other = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "codex".into(),
|
||||
prompt: prompt(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
ready(&mgr, &other.id).await;
|
||||
assert!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier").is_none(),
|
||||
"choices must not leak to another task"
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,7 +110,8 @@ for line in sys.stdin:
|
||||
cursor = request['params']['cursor']
|
||||
model = 'one' if cursor is None else 'two'
|
||||
result = {'data': [{'id': model, 'isDefault': cursor is None,
|
||||
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}]}],
|
||||
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}],
|
||||
'serviceTiers': [{'id': 'fast', 'name': 'Fast', 'description': ''}] if cursor is None else []}],
|
||||
'nextCursor': 'second-page' if cursor is None else None}
|
||||
else:
|
||||
raise RuntimeError('must not create a thread or prompt: ' + method)
|
||||
@@ -125,6 +126,7 @@ for line in sys.stdin:
|
||||
driver: crate::provider::Driver::Codex,
|
||||
command: script.to_string_lossy().into_owned(),
|
||||
args: Vec::new(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: String::new(),
|
||||
source: crate::AgentSource::Builtin,
|
||||
@@ -138,6 +140,9 @@ for line in sys.stdin:
|
||||
.collect();
|
||||
assert_eq!(models, ["one", "two"]);
|
||||
assert_eq!(found.levels.keys().map(String::as_str).collect::<Vec<_>>(), ["one", "two"]);
|
||||
assert!(found.config.iter().any(|o| o.id == SERVICE_TIER));
|
||||
assert!(found.levels["one"].iter().any(|o| o.id == SERVICE_TIER));
|
||||
assert!(found.levels["two"].iter().all(|o| o.id != SERVICE_TIER));
|
||||
let requests = std::fs::read_to_string(tmp.path().join("requests")).unwrap();
|
||||
let requests: Vec<Value> = requests.lines().map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(
|
||||
@@ -162,6 +167,72 @@ for line in sys.stdin:
|
||||
|
||||
// ---- Pure translations -------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn fast_is_offered_only_when_the_model_advertises_it() {
|
||||
for capability in [
|
||||
json!({ "additionalSpeedTiers": ["fast"] }),
|
||||
json!({ "serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }] }),
|
||||
json!({ "serviceTiers": [{ "id": "priority", "name": "Fast", "description": "" }] }),
|
||||
] {
|
||||
let mut model = json!({ "id": "supported", "isDefault": true });
|
||||
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
|
||||
let models = models_of(&json!({ "data": [model, { "id": "unsupported" }] }));
|
||||
let mut settings = Settings::of(&json!({}), &models);
|
||||
let options = config_options(&models, &settings);
|
||||
let fast = options.as_array().unwrap().iter().find(|o| o["id"] == "service_tier").expect("Fast option");
|
||||
assert_eq!(fast["category"], "model_config");
|
||||
assert_eq!(fast["currentValue"], "false");
|
||||
assert!(settings.set(&models, "service_tier", "true").is_ok());
|
||||
assert!(settings.set(&models, "service_tier", "invalid").is_err());
|
||||
let selected = settings.service_tier_override(&models).map(str::to_owned);
|
||||
settings.set(&models, "model", "unsupported").unwrap();
|
||||
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
|
||||
assert!(settings.set(&models, "service_tier", "true").is_err());
|
||||
assert_eq!(settings.service_tier_override(&models), Some("default"));
|
||||
settings.set(&models, "model", "supported").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), selected.as_deref());
|
||||
let options = config_options(&models, &settings);
|
||||
assert_eq!(
|
||||
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
|
||||
"true"
|
||||
);
|
||||
}
|
||||
for capability in [json!({}), json!({ "additionalSpeedTiers": [] }), json!({ "serviceTiers": [] })] {
|
||||
let mut model = json!({ "id": "old", "isDefault": true });
|
||||
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
|
||||
let models = models_of(&json!({ "data": [model] }));
|
||||
let settings = Settings::of(&json!({}), &models);
|
||||
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_defaults_do_not_become_user_overrides() {
|
||||
let models = models_of(&json!({ "data": [{
|
||||
"id": "m", "isDefault": true, "defaultServiceTier": "fast",
|
||||
"serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }]
|
||||
}] }));
|
||||
for (reported, current) in [
|
||||
(json!({}), "true"),
|
||||
(json!({ "serviceTier": null }), "false"),
|
||||
(json!({ "serviceTier": "fast" }), "true"),
|
||||
(json!({ "serviceTier": "priority" }), "true"),
|
||||
(json!({ "serviceTier": "default" }), "false"),
|
||||
] {
|
||||
let mut settings = Settings::of(&reported, &models);
|
||||
let options = config_options(&models, &settings);
|
||||
assert_eq!(
|
||||
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
|
||||
current
|
||||
);
|
||||
assert_eq!(settings.service_tier_override(&models), None);
|
||||
settings.set(&models, SERVICE_TIER, "true").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), Some("fast"));
|
||||
settings.set(&models, SERVICE_TIER, "false").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), Some("default"));
|
||||
}
|
||||
}
|
||||
|
||||
fn models() -> Vec<ModelInfo> {
|
||||
models_of(&json!({"data": [
|
||||
{"id": "big", "model": "big", "displayName": "Big", "description": "d", "hidden": false, "isDefault": true,
|
||||
@@ -185,6 +256,8 @@ fn settings_follow_the_thread_and_the_models() {
|
||||
Settings {
|
||||
model: "big".into(),
|
||||
effort: Some("low".into()),
|
||||
service_tier: None,
|
||||
fast_override: None,
|
||||
mode: Mode::Ask,
|
||||
collaboration_mode: DEFAULT_COLLABORATION_MODE.into(),
|
||||
collaboration_mode_override: None,
|
||||
@@ -382,6 +455,90 @@ fn failures_are_classified() {
|
||||
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turns_preserve_codex_error_diagnostics() {
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
|
||||
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
|
||||
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
|
||||
assert_eq!(failure.code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
// A completed turn's own error wins over an older error notification.
|
||||
let failure = stop_reason(
|
||||
&json!({ "status": "failed", "error": policy }),
|
||||
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
|
||||
for (value, expected) in [
|
||||
(
|
||||
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
|
||||
"Context is full.\nCodex error: contextWindowExceeded",
|
||||
),
|
||||
(
|
||||
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
|
||||
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
|
||||
),
|
||||
(
|
||||
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
|
||||
"Failed\nbecause",
|
||||
),
|
||||
(
|
||||
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
|
||||
"Codex failed\nDetails\nCodex error: cyberPolicy",
|
||||
),
|
||||
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
|
||||
(json!({}), "Codex failed"),
|
||||
] {
|
||||
assert_eq!(error_message(&value), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
|
||||
for notification_only in [false, true] {
|
||||
let mut transcript = load(Scenario::UsageLimit.file());
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
match frame["method"].as_str() {
|
||||
Some("error") => frame["params"]["error"] = policy.clone(),
|
||||
Some("turn/completed") => {
|
||||
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
|
||||
match result(&results, "prompt") {
|
||||
Err(RpcError::Server { code, message, .. }) => {
|
||||
assert_eq!(*code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(
|
||||
message,
|
||||
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
|
||||
);
|
||||
}
|
||||
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approvals_offer_what_codex_offers_and_always_a_decline() {
|
||||
let params = json!({"availableDecisions": ["accept",
|
||||
@@ -473,6 +630,39 @@ fn history_replays_turns() {
|
||||
assert_eq!(updates[4]["status"], "completed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewed_generated_and_attached_images_carry_their_pixels() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("shot.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let png_path = png.to_str().unwrap();
|
||||
let encoded = "iVBORw0K";
|
||||
let view = json!({"id": "v", "type": "imageView", "path": png_path});
|
||||
assert!(tool_call(&view, false, None, None).unwrap().get("content").is_none());
|
||||
let image = &tool_call(&view, true, None, None).unwrap()["content"][0]["content"];
|
||||
assert_eq!((image["type"].as_str(), image["data"].as_str()), (Some("image"), Some(encoded)));
|
||||
let missing = json!({"id": "v", "type": "imageView", "path": dir.path().join("gone.png")});
|
||||
assert!(tool_call(&missing, true, None, None).unwrap().get("content").is_none());
|
||||
let inline = json!({"id": "g", "type": "imageGeneration", "status": "completed", "result": encoded});
|
||||
let image = &tool_call(&inline, true, None, None).unwrap()["content"][0]["content"];
|
||||
assert_eq!((image["mimeType"].as_str(), image["data"].as_str()), (Some("image/png"), Some(encoded)));
|
||||
let saved =
|
||||
json!({"id": "g", "type": "imageGeneration", "status": "completed", "fileId": "f", "savedPath": png_path});
|
||||
assert_eq!(tool_call(&saved, true, None, None).unwrap()["content"][0]["content"]["data"], encoded);
|
||||
|
||||
let thread = json!({"turns": [{"items": [{"type": "userMessage", "id": "u", "content": [
|
||||
{"type": "image", "url": "data:image/jpeg;base64,/9j/"},
|
||||
{"type": "image", "url": "https://example.com/a.png"},
|
||||
{"type": "localImage", "path": png_path},
|
||||
{"type": "localImage", "path": "/gone.png"}
|
||||
]}]}]});
|
||||
let contents: Vec<Value> = history(&thread, None).into_iter().map(|u| u["content"].clone()).collect();
|
||||
assert_eq!(contents[0], json!({"type": "image", "mimeType": "image/jpeg", "data": "/9j/"}));
|
||||
assert_eq!(contents[1]["type"], "resource_link");
|
||||
assert_eq!(contents[2], json!({"type": "image", "mimeType": "image/png", "data": encoded}));
|
||||
assert_eq!(contents[3], json!({"type": "text", "text": "/gone.png"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_preserves_async_questions_with_stable_answer_ids() {
|
||||
let updates = history(
|
||||
@@ -615,6 +805,7 @@ enum Scenario {
|
||||
Steer,
|
||||
Simple,
|
||||
MultiTurn,
|
||||
ServiceTier { first: Option<bool>, second: Option<bool> },
|
||||
Approvals,
|
||||
UsageLimit,
|
||||
Subagent,
|
||||
@@ -633,6 +824,7 @@ impl Scenario {
|
||||
Scenario::Steer => "steer",
|
||||
Scenario::Simple => "simple",
|
||||
Scenario::MultiTurn => "multi_turn",
|
||||
Scenario::ServiceTier { .. } => "multi_turn",
|
||||
Scenario::Approvals => "approvals",
|
||||
Scenario::UsageLimit => "usage_limit",
|
||||
Scenario::Subagent => "subagent",
|
||||
@@ -739,6 +931,16 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa
|
||||
out.push(("effort", request(acp, "session/set_config_option", set(EFFORT, "high")).await));
|
||||
out.push(("second", request(acp, "session/prompt", prompt("Reply with: two")).await));
|
||||
}
|
||||
Scenario::ServiceTier { first, second } => {
|
||||
for (label, choice) in [("first", first), ("second", second)] {
|
||||
if let Some(fast) = choice {
|
||||
request(acp, "session/set_config_option", set(SERVICE_TIER, if fast { "true" } else { "false" }))
|
||||
.await
|
||||
.expect("the model advertises Fast");
|
||||
}
|
||||
out.push((label, request(acp, "session/prompt", prompt("Reply with: hi")).await));
|
||||
}
|
||||
}
|
||||
Scenario::Approvals => {
|
||||
client.answers.lock().extend([Some("accept"), None]);
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Run `touch b.txt`, then write a.txt.")).await));
|
||||
@@ -1271,6 +1473,44 @@ fn thread_names_are_the_first_line_of_the_reply() {
|
||||
assert_eq!(thread_name(&"x".repeat(100)).map(|n| n.chars().count()), Some(80));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fast_selection_reaches_the_first_and_next_turn_and_standard_clears_it() {
|
||||
for (first, second, expected) in [
|
||||
(Some(true), Some(false), [Some("fast"), Some("default")]),
|
||||
(Some(false), Some(true), [Some("default"), Some("fast")]),
|
||||
(Some(true), None, [Some("fast"), Some("fast")]),
|
||||
(None, None, [None, None]),
|
||||
] {
|
||||
let scenario = Scenario::ServiceTier { first, second };
|
||||
let mut transcript = load(scenario.file());
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
if let Some(models) = frame.pointer_mut("/result/data").and_then(Value::as_array_mut) {
|
||||
for model in models {
|
||||
model["serviceTiers"] = json!([{ "id": "fast", "name": "Fast", "description": "" }]);
|
||||
model["defaultServiceTier"] = json!("fast");
|
||||
}
|
||||
}
|
||||
if frame.pointer("/result/thread").is_some() {
|
||||
frame["result"]["serviceTier"] = json!("fast");
|
||||
}
|
||||
}
|
||||
let (results, _client, frames, _meta, _codex) = replay_transcript(scenario, transcript).await;
|
||||
assert!(result(&results, "first").is_ok());
|
||||
assert!(result(&results, "second").is_ok());
|
||||
let starts = sent(&frames, "turn/start");
|
||||
assert_eq!(starts.len(), 2);
|
||||
for (start, expected) in starts.iter().zip(expected) {
|
||||
assert_eq!(start["params"].get("serviceTier"), expected.map(|value| json!(value)).as_ref());
|
||||
assert!(start["params"].get("serviceTierForTurn").is_none());
|
||||
}
|
||||
assert!(sent(&frames, "turn/settings/update").is_empty());
|
||||
assert!(sent(&frames, "config/value/write").is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn settings_apply_to_the_next_turn() {
|
||||
let (results, client, frames, _) = replay(Scenario::MultiTurn).await;
|
||||
@@ -1858,3 +2098,40 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
|
||||
assert!(request.get("runtimeWorkspaceRoots").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_session_starts_an_ephemeral_thread() {
|
||||
for ephemeral in [true, false] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cwd = tmp.path().to_string_lossy().into_owned();
|
||||
let server = Arc::new(TrustServer {
|
||||
cwd: cwd.clone(),
|
||||
disabled: false,
|
||||
other_project: false,
|
||||
write_error: false,
|
||||
overridden: false,
|
||||
calls: Mutex::default(),
|
||||
});
|
||||
let client = Arc::new(Client::default());
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
|
||||
let acp = attach(client.clone(), |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
request(&acp, "initialize", json!({})).await.unwrap();
|
||||
let mut params = json!({"cwd": cwd, "mcpServers": []});
|
||||
if ephemeral {
|
||||
params["_meta"] = json!({"openidea": {"ephemeral": true}});
|
||||
}
|
||||
request(&acp, "session/new", params).await.unwrap();
|
||||
let calls = server.calls.lock();
|
||||
let (_, start) = calls.iter().find(|(m, _)| m == "thread/start").unwrap();
|
||||
assert_eq!(start.get("ephemeral"), ephemeral.then_some(&Value::Bool(true)), "{start}");
|
||||
drop(calls);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,8 @@ pub(super) struct ModelInfo {
|
||||
/// `(effort, description)`.
|
||||
pub efforts: Vec<(String, String)>,
|
||||
pub default_effort: Option<String>,
|
||||
pub fast_tier: Option<String>,
|
||||
pub default_service_tier: Option<String>,
|
||||
pub is_default: bool,
|
||||
pub hidden: bool,
|
||||
}
|
||||
@@ -123,6 +125,22 @@ pub(super) fn models_of(list: &Value) -> Vec<ModelInfo> {
|
||||
})
|
||||
.collect(),
|
||||
default_effort: str_of(m, "defaultReasoningEffort"),
|
||||
fast_tier: m
|
||||
.get("serviceTiers")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|tier| tier.get("id").and_then(Value::as_str))
|
||||
.chain(
|
||||
m.get("additionalSpeedTiers")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str),
|
||||
)
|
||||
.find(|tier| is_fast_tier(tier))
|
||||
.map(str::to_owned),
|
||||
default_service_tier: str_of(m, "defaultServiceTier"),
|
||||
is_default: m.get("isDefault").and_then(Value::as_bool) == Some(true),
|
||||
hidden: m.get("hidden").and_then(Value::as_bool) == Some(true),
|
||||
id,
|
||||
@@ -137,6 +155,9 @@ pub(super) struct Settings {
|
||||
/// A model id from `model/list`, or the one the thread reported.
|
||||
pub model: String,
|
||||
pub effort: Option<String>,
|
||||
pub service_tier: Option<String>,
|
||||
/// No choice preserves the runtime's default; false explicitly selects Standard.
|
||||
pub fast_override: Option<bool>,
|
||||
pub mode: Mode,
|
||||
/// Codex's Default/Plan collaboration mode. It is sent with each turn because it is
|
||||
/// part of the turn contract rather than the sandbox permission mode above.
|
||||
@@ -158,6 +179,12 @@ impl Settings {
|
||||
let mut s = Settings {
|
||||
model,
|
||||
effort: str_of(result, "reasoningEffort"),
|
||||
service_tier: match result.get("serviceTier") {
|
||||
// A live thread can explicitly report Standard even when the catalog defaults to Fast.
|
||||
Some(Value::Null) => Some("default".into()),
|
||||
_ => str_of(result, "serviceTier"),
|
||||
},
|
||||
fast_override: None,
|
||||
mode: Mode::of(
|
||||
result.get("approvalPolicy").unwrap_or(&Value::Null),
|
||||
result.get("sandbox").unwrap_or(&Value::Null),
|
||||
@@ -205,6 +232,16 @@ impl Settings {
|
||||
}
|
||||
self.effort = Some(value.to_owned());
|
||||
}
|
||||
SERVICE_TIER => {
|
||||
if !models.iter().any(|m| m.id == self.model && m.fast_tier.is_some()) {
|
||||
return Err(format!("{} has no Fast mode", self.model));
|
||||
}
|
||||
self.fast_override = Some(match value {
|
||||
"true" => true,
|
||||
"false" => false,
|
||||
_ => return Err(format!("unknown Fast mode {value}")),
|
||||
});
|
||||
}
|
||||
MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?,
|
||||
COLLABORATION_MODE => {
|
||||
if !matches!(value, DEFAULT_COLLABORATION_MODE | PLAN_COLLABORATION_MODE) {
|
||||
@@ -217,16 +254,32 @@ impl Settings {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `turn/start.serviceTier`: omission inherits; "default" explicitly resets Fast.
|
||||
pub fn service_tier_override<'a>(&self, models: &'a [ModelInfo]) -> Option<&'a str> {
|
||||
match self.fast_override {
|
||||
Some(true) => Some(
|
||||
models.iter().find(|m| m.id == self.model).and_then(|m| m.fast_tier.as_deref()).unwrap_or("default"),
|
||||
),
|
||||
Some(false) => Some("default"),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const MODEL: &str = "model";
|
||||
pub(super) const EFFORT: &str = "reasoning_effort";
|
||||
pub(super) const SERVICE_TIER: &str = "service_tier";
|
||||
pub(super) const MODE: &str = "mode";
|
||||
pub(super) const COLLABORATION_MODE: &str = "collaboration_mode";
|
||||
pub(super) const DEFAULT_COLLABORATION_MODE: &str = "default";
|
||||
pub(super) const PLAN_COLLABORATION_MODE: &str = "plan";
|
||||
|
||||
/// ACP `configOptions`: model, reasoning effort (for models that have it) and mode.
|
||||
fn is_fast_tier(tier: &str) -> bool {
|
||||
matches!(tier, "fast" | "priority")
|
||||
}
|
||||
|
||||
/// ACP `configOptions`: model, its supported settings and session modes.
|
||||
pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
let mut model_values: Vec<Value> = models
|
||||
.iter()
|
||||
@@ -253,6 +306,16 @@ pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
"currentValue": effort, "options": values,
|
||||
}));
|
||||
}
|
||||
if let Some(model) = models.iter().find(|m| m.id == s.model && m.fast_tier.is_some()) {
|
||||
let fast = s.fast_override.unwrap_or_else(|| {
|
||||
s.service_tier.as_deref().or(model.default_service_tier.as_deref()).is_some_and(is_fast_tier)
|
||||
});
|
||||
out.push(json!({
|
||||
"id": SERVICE_TIER, "name": "Fast", "category": "model_config", "type": "select",
|
||||
"currentValue": if fast { "true" } else { "false" },
|
||||
"options": [select_value("false", "Standard", None), select_value("true", "Fast", None)],
|
||||
}));
|
||||
}
|
||||
out.push(json!({
|
||||
"id": MODE, "name": "Mode", "category": "mode", "type": "select", "currentValue": s.mode.id(),
|
||||
"options": Mode::ALL.iter().map(|m| select_value(m.id(), m.name(), Some(m.description()))).collect::<Vec<_>>(),
|
||||
@@ -348,36 +411,18 @@ pub(super) fn user_input(prompt: &Value) -> Vec<Value> {
|
||||
}
|
||||
"resource" => {
|
||||
let r = b.get("resource")?;
|
||||
let path = uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
|
||||
let path = crate::images::uri_path(r.get("uri").and_then(Value::as_str).unwrap_or_default());
|
||||
let text = r.get("text").and_then(Value::as_str)?;
|
||||
Some(json!({ "type": "text", "text": format!("<file path=\"{path}\">\n{text}\n</file>") }))
|
||||
}
|
||||
"resource_link" => Some(json!({ "type": "text", "text": uri_path(b.get("uri")?.as_str()?) })),
|
||||
"resource_link" => {
|
||||
Some(json!({ "type": "text", "text": crate::images::uri_path(b.get("uri")?.as_str()?) }))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The path of a `file://` URI (percent-decoded); other URIs as they are.
|
||||
fn uri_path(uri: &str) -> String {
|
||||
let Some(rest) = uri.strip_prefix("file://") else { return uri.to_owned() };
|
||||
let bytes = rest.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%'
|
||||
&& let Some(b) = rest.get(i + 1..i + 3).and_then(|h| u8::from_str_radix(h, 16).ok())
|
||||
{
|
||||
out.push(b);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
/// A `session/update` notification's `update` for content.
|
||||
pub(super) fn chunk(kind: &str, text: &str) -> Value {
|
||||
json!({ "sessionUpdate": kind, "content": { "type": "text", "text": text } })
|
||||
@@ -467,6 +512,9 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
"imageView" => {
|
||||
let path = item.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
call.insert("locations".into(), json!([{ "path": path }]));
|
||||
if done && let Some(image) = crate::images::from_file(std::path::Path::new(path)) {
|
||||
call.insert("content".into(), json!([image_content(&image)]));
|
||||
}
|
||||
(format!("View {}", display_path(path, cwd)), "read")
|
||||
}
|
||||
"collabAgentToolCall" => {
|
||||
@@ -482,7 +530,12 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
}
|
||||
"contextCompaction" => ("Compact the conversation".to_owned(), "other"),
|
||||
"sleep" => ("Wait".to_owned(), "other"),
|
||||
"imageGeneration" => ("Generate an image".to_owned(), "other"),
|
||||
"imageGeneration" => {
|
||||
if done && let Some(image) = generated_image(item) {
|
||||
call.insert("content".into(), json!([image_content(&image)]));
|
||||
}
|
||||
("Generate an image".to_owned(), "other")
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
call.insert("sessionUpdate".into(), json!(if done { "tool_call_update" } else { "tool_call" }));
|
||||
@@ -493,6 +546,19 @@ pub(super) fn tool_call(item: &Value, done: bool, cwd: Option<&str>, output: Opt
|
||||
Some(Value::Object(call))
|
||||
}
|
||||
|
||||
fn image_content(image: &crate::model::AgentImage) -> Value {
|
||||
json!({ "type": "content", "content": crate::images::content(image) })
|
||||
}
|
||||
|
||||
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
|
||||
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
|
||||
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
|
||||
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
|
||||
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
|
||||
}
|
||||
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
|
||||
}
|
||||
|
||||
/// The output of a running command, as a `tool_call_update`.
|
||||
pub(super) fn command_output(id: &str, output: &str) -> Value {
|
||||
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "content": [text_content(&tail(output))] })
|
||||
@@ -674,7 +740,7 @@ pub(super) enum Failure {
|
||||
UsageLimit(Option<f64>),
|
||||
/// Signed out or refused.
|
||||
Auth,
|
||||
/// The model declined.
|
||||
/// The server blocked the turn under a safety policy.
|
||||
Refusal,
|
||||
Other,
|
||||
}
|
||||
@@ -714,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
|
||||
exhausted.map(|s| s * 1000.0)
|
||||
}
|
||||
|
||||
/// The text a failed turn reports: codex's message, with its details.
|
||||
/// The text a failed turn reports: Codex's message, details and diagnostic code.
|
||||
pub(super) fn error_message(error: &Value) -> String {
|
||||
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
|
||||
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
|
||||
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
|
||||
_ => message.to_owned(),
|
||||
let original =
|
||||
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
|
||||
let mut message = original.to_owned();
|
||||
if let Some(details) =
|
||||
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
|
||||
&& !original.contains(details)
|
||||
{
|
||||
message.push('\n');
|
||||
message.push_str(details);
|
||||
}
|
||||
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
|
||||
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
|
||||
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
|
||||
message.push_str(&format!("\nCodex error: {code}"));
|
||||
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
|
||||
message.push_str(&format!(" (HTTP {status})"));
|
||||
}
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
/// One choice of an approval: what ACP shows and what codex gets back.
|
||||
@@ -856,9 +936,23 @@ pub(super) fn history(thread: &Value, cwd: Option<&str>) -> Vec<Value> {
|
||||
"user_message_chunk",
|
||||
c.get("text").and_then(Value::as_str).unwrap_or_default(),
|
||||
)),
|
||||
Some("image") => out.push(json!({ "sessionUpdate": "user_message_chunk",
|
||||
"content": { "type": "resource_link", "uri": c.get("url"), "name": "image" } })),
|
||||
Some("localImage" | "mention" | "skill") => {
|
||||
Some("image") => {
|
||||
let url = c.get("url").and_then(Value::as_str).unwrap_or_default();
|
||||
let content = crate::images::from_uri(url).map_or_else(
|
||||
|| json!({ "type": "resource_link", "uri": url, "name": "image" }),
|
||||
|image| crate::images::content(&image),
|
||||
);
|
||||
out.push(json!({ "sessionUpdate": "user_message_chunk", "content": content }));
|
||||
}
|
||||
Some("localImage") => {
|
||||
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
out.push(match crate::images::from_file(std::path::Path::new(path)) {
|
||||
Some(image) => json!({ "sessionUpdate": "user_message_chunk",
|
||||
"content": crate::images::content(&image) }),
|
||||
None => chunk("user_message_chunk", path),
|
||||
});
|
||||
}
|
||||
Some("mention" | "skill") => {
|
||||
let path = c.get("path").and_then(Value::as_str).unwrap_or_default();
|
||||
out.push(chunk("user_message_chunk", path));
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ pub(crate) fn is_missing_binary_error(err: &std::io::Error) -> bool {
|
||||
pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discovered, DiscoverError> {
|
||||
tokio::time::timeout(DISCOVER_TIMEOUT, async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
match discover_once(spec.clone(), cwd.clone(), prefer_stored).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
@@ -185,6 +185,78 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
|
||||
res
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct CliAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
}
|
||||
|
||||
/// Queries `auth.getStatus` on Copilot's headless server (ignoring any IDE-selected `gh`
|
||||
/// account override so the UI can show what the "Default" account resolves to).
|
||||
pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> Option<CliAuthStatus> {
|
||||
spec.env.retain(|(name, _)| name != crate::provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
tokio::time::timeout(Duration::from_secs(8), async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await;
|
||||
if !prefer_stored
|
||||
&& has_ambient
|
||||
&& first.as_ref().is_none_or(|s| !s.authenticated)
|
||||
&& let Some(retry) = probe_auth_once(spec, cwd, true).await
|
||||
{
|
||||
if retry.authenticated {
|
||||
crate::provider::mark_prefer_stored_copilot_auth();
|
||||
}
|
||||
return Some(retry);
|
||||
}
|
||||
first
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
async fn probe_auth_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) -> Option<CliAuthStatus> {
|
||||
let launch = tokio::task::spawn_blocking({
|
||||
let cwd = cwd.clone();
|
||||
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
|
||||
})
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
|
||||
let args = headless_args(&launch.args);
|
||||
let peer = Peer::spawn_framed(
|
||||
&launch.command,
|
||||
&args,
|
||||
&cwd,
|
||||
&launch.env,
|
||||
Arc::new(ide_jsonrpc::NoopHandler),
|
||||
Box::new(|_| {}),
|
||||
Framing::ContentLength,
|
||||
)
|
||||
.ok()?;
|
||||
let res = async {
|
||||
handshake(&peer).await.ok()?;
|
||||
let auth: Value = peer.request("auth.getStatus", json!({}), None).await.ok()?;
|
||||
let authenticated = auth.get("isAuthenticated").and_then(Value::as_bool).unwrap_or(false);
|
||||
let str_field = |key: &str| {
|
||||
auth.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
|
||||
};
|
||||
Some(CliAuthStatus {
|
||||
authenticated,
|
||||
login: str_field("login"),
|
||||
auth_type: str_field("authType"),
|
||||
status_message: str_field("statusMessage"),
|
||||
})
|
||||
}
|
||||
.await;
|
||||
peer.kill();
|
||||
res
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn attach(
|
||||
client: Arc<dyn Handler>,
|
||||
|
||||
@@ -751,3 +751,47 @@ async fn stop_ends_a_turn_left_running_only_by_background_shells() {
|
||||
assert_eq!(res["stopReason"], "cancelled");
|
||||
assert!(!server.calls.lock().iter().any(|(m, _)| m == "session.abort"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skills() {
|
||||
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": {
|
||||
"skills": {
|
||||
"copilotSkillDirectories": ["/farm/task-1/copilot"],
|
||||
"copilotDisabledSkills": ["muted", "off"],
|
||||
}
|
||||
}
|
||||
});
|
||||
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["skillDirectories"], json!(["/farm/task-1/copilot"]), "{method}: {params}");
|
||||
assert_eq!(params["disabledSkills"], json!(["muted", "off"]), "{method}: {params}");
|
||||
assert!(params.get("enableConfigDiscovery").is_none(), "{method} must not auto-enable workspace MCP discovery");
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,10 @@
|
||||
//! `<config>/agents/<id>.toml` (written by hand, or by installing one from the ACP
|
||||
//! Registry, see `registry`).
|
||||
|
||||
use crate::{AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets};
|
||||
use crate::{
|
||||
AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets,
|
||||
GhAuthAccount,
|
||||
};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -33,6 +36,8 @@ pub(crate) struct ProviderSpec {
|
||||
pub driver: Driver,
|
||||
pub command: String,
|
||||
pub args: Vec<String>,
|
||||
/// Number of trailing arguments added by the built-in agent's settings.
|
||||
pub additional_args_len: usize,
|
||||
pub env: Vec<(String, String)>,
|
||||
/// How to sign in when the agent reports it needs authentication.
|
||||
pub login_hint: String,
|
||||
@@ -71,7 +76,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
"GitHub Copilot",
|
||||
Driver::Copilot,
|
||||
&["copilot", "--headless", "--no-auto-update", "--stdio"],
|
||||
"Run `copilot` in a terminal and sign in.",
|
||||
"Run `copilot login` in a terminal.",
|
||||
),
|
||||
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
|
||||
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
|
||||
@@ -96,6 +101,7 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
driver: *driver,
|
||||
command: cmd[0].into(),
|
||||
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: (*hint).into(),
|
||||
source: AgentSource::Builtin,
|
||||
@@ -148,12 +154,26 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
|
||||
let is_copilot = is_copilot_provider(&self.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());
|
||||
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
|
||||
if let Some(account) = account {
|
||||
let token = github_token_for_account(&account)?;
|
||||
// Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's
|
||||
// shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`.
|
||||
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
|
||||
} else if is_copilot
|
||||
&& !strip_ambient_tokens
|
||||
&& !explicit_copilot_token
|
||||
&& ide_core::project_env::github_token(cwd).is_some()
|
||||
&& let Some(default_token) = default_github_token()
|
||||
{
|
||||
// A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model
|
||||
// billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present.
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token));
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
@@ -163,7 +183,7 @@ impl ProviderSpec {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
|
||||
@@ -173,6 +193,80 @@ impl ProviderSpec {
|
||||
.into_owned();
|
||||
self
|
||||
}
|
||||
|
||||
/// Resolves the executable, arguments, and environment to run this agent's interactive
|
||||
/// sign-in flow directly in an IDE PTY without shell quoting.
|
||||
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
|
||||
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
|
||||
let candidate =
|
||||
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
|
||||
if candidate.is_absolute() && is_executable(&candidate) {
|
||||
return Some(candidate);
|
||||
}
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
_ => None,
|
||||
} {
|
||||
let program = resolve_exe(separate_cmd, &self.env)?;
|
||||
return Some(LoginLaunch {
|
||||
program,
|
||||
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
|
||||
env: self.env.iter().cloned().collect(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
.or_else(|| builtin_login_args(&builtin))?;
|
||||
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) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
}
|
||||
return Some(LoginLaunch { program, args, env });
|
||||
}
|
||||
|
||||
let args = terminal_auth_args?.to_vec();
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
|
||||
}
|
||||
|
||||
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
|
||||
self.login_launch(cwd, terminal_auth_args).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LoginLaunch {
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
|
||||
match rest {
|
||||
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
|
||||
let (args, _) = after_space.split_once('`')?;
|
||||
Some(args.split_whitespace().map(str::to_owned).collect())
|
||||
}
|
||||
Some(_) => Some(Vec::new()),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
@@ -191,16 +285,26 @@ pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String>
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn is_valid_github_login(account: &str) -> bool {
|
||||
let bytes = account.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
let path = ide_core::process::shell_env()
|
||||
.find(|(name, _)| name == "PATH")
|
||||
.map(|(_, value)| value)
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"));
|
||||
let program = path
|
||||
.as_deref()
|
||||
.and_then(|path| ide_core::process::find_executable("gh", path))
|
||||
if !is_valid_github_login(account) {
|
||||
return Err(format!("Invalid GitHub account login: {account}"));
|
||||
}
|
||||
let program = find_gh_executable()
|
||||
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
@@ -226,6 +330,140 @@ fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
Ok(token.to_owned())
|
||||
}
|
||||
|
||||
/// Interactive `gh auth login` launch for adding/switching GitHub CLI accounts in-IDE,
|
||||
/// with ambient `GITHUB_TOKEN` / `GH_TOKEN` cleared so `gh` does not refuse to run.
|
||||
pub fn gh_login_launch() -> IdeResult<LoginLaunch> {
|
||||
let program = find_gh_executable().ok_or_else(|| IdeError::unavailable("GitHub CLI (`gh`) is not installed"))?;
|
||||
let mut env = BTreeMap::new();
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
Ok(LoginLaunch {
|
||||
program,
|
||||
args: vec!["auth".into(), "login".into(), "--hostname".into(), "github.com".into()],
|
||||
env,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns `(gh_installed, authenticated_accounts)` for `github.com` from `gh auth status`,
|
||||
/// ignoring ambient token environment variables so keyring accounts remain visible.
|
||||
pub fn gh_authenticated_accounts() -> (bool, Vec<GhAuthAccount>) {
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return (false, Vec::new());
|
||||
};
|
||||
let run_gh = |args: &[&str]| -> Option<std::process::Output> {
|
||||
let mut command = std::process::Command::new(&program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command
|
||||
.args(args)
|
||||
.envs(ide_core::process::shell_env())
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1");
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
command.output().ok()
|
||||
};
|
||||
if let Some(output) = run_gh(&["auth", "status", "--json", "hosts"]) {
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
if let Some(accounts) = parse_gh_auth_status_json(&stdout) {
|
||||
return (true, accounts);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.contains("unknown flag: --json") {
|
||||
return (true, Vec::new());
|
||||
}
|
||||
}
|
||||
let fallback = run_gh(&["auth", "status", "--hostname", "github.com"])
|
||||
.map(|out| format!("{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
|
||||
.map(|text| parse_gh_auth_status_text(&text))
|
||||
.unwrap_or_default();
|
||||
(true, fallback)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_json(text: &str) -> Option<Vec<GhAuthAccount>> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Entry {
|
||||
#[serde(default)]
|
||||
state: Option<String>,
|
||||
#[serde(default)]
|
||||
active: bool,
|
||||
#[serde(default)]
|
||||
login: String,
|
||||
#[serde(default)]
|
||||
token_source: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
#[serde(default)]
|
||||
hosts: BTreeMap<String, Vec<Entry>>,
|
||||
}
|
||||
let parsed: Response = serde_json::from_str(text.trim()).ok()?;
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
if let Some(entries) = parsed.hosts.get("github.com") {
|
||||
for entry in entries {
|
||||
let login = entry.login.trim();
|
||||
if login.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if entry.state.as_deref().is_some_and(|s| s != "success") {
|
||||
continue;
|
||||
}
|
||||
// Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts.
|
||||
if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") {
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
|
||||
existing.active |= entry.active;
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: entry.active });
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(accounts)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
let mut current: Option<usize> = None;
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") {
|
||||
let login = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
current = None;
|
||||
if !login.is_empty() && !rest.contains("_TOKEN") {
|
||||
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
|
||||
current = Some(idx);
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: false });
|
||||
current = Some(accounts.len() - 1);
|
||||
}
|
||||
}
|
||||
} else if trimmed.starts_with("- Active account: true")
|
||||
&& let Some(idx) = current
|
||||
{
|
||||
accounts[idx].active = true;
|
||||
}
|
||||
}
|
||||
accounts
|
||||
}
|
||||
|
||||
fn default_github_token() -> Option<String> {
|
||||
let program = find_gh_executable()?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
let output = command.output().ok().filter(|out| out.status.success())?;
|
||||
let token = String::from_utf8(output.stdout).ok()?;
|
||||
let token = token.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn prefer_stored_copilot_auth() -> bool {
|
||||
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -234,18 +472,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() {
|
||||
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool {
|
||||
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
|
||||
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
|
||||
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
|
||||
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
ide_core::process::shell_env()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
|
||||
fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option<String> {
|
||||
ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| {
|
||||
ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds child environment overrides for `copilot`:
|
||||
@@ -256,9 +493,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
|
||||
pub(crate) fn sanitized_copilot_env(
|
||||
spec_env: &[(String, String)],
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Vec<(String, String)> {
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd))
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_copilot_env_with(
|
||||
@@ -347,16 +585,28 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
|
||||
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
|
||||
}
|
||||
|
||||
fn uses_package_runner(command: &str) -> bool {
|
||||
matches!(command, "npx" | "bunx" | "uvx")
|
||||
}
|
||||
|
||||
fn allows_additional_args(builtin: &ProviderSpec, driver: Driver) -> bool {
|
||||
builtin.driver == Driver::Acp && driver == Driver::Acp && !uses_package_runner(&builtin.command)
|
||||
}
|
||||
|
||||
/// Public launch metadata, keeping the built-in defaults separate from agent-file overrides.
|
||||
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 let Some(default) = &builtin {
|
||||
matches!(default.command.as_str(), "npx" | "bunx" | "uvx").then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
} else {
|
||||
Some(AgentCommandReadOnlyReason::CustomAgent)
|
||||
};
|
||||
let additional_args = builtin
|
||||
.as_ref()
|
||||
.filter(|b| reason.is_none() && allows_additional_args(b, spec.driver))
|
||||
.map(|_| spec.args[spec.args.len() - spec.additional_args_len..].to_vec());
|
||||
AgentProvider {
|
||||
id: spec.id.clone(),
|
||||
name: spec.name.clone(),
|
||||
@@ -366,6 +616,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
.join(" "),
|
||||
program: spec.command.clone(),
|
||||
args: spec.args.clone(),
|
||||
additional_args,
|
||||
default_program: builtin.as_ref().map(|b| b.command.clone()),
|
||||
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
|
||||
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))),
|
||||
@@ -373,6 +624,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
@@ -391,7 +643,24 @@ pub(crate) fn set_builtin_command(
|
||||
command: Option<&str>,
|
||||
) -> IdeResult<()> {
|
||||
update_builtin(custom_dir, secrets, id, |agent, builtin| {
|
||||
agent.command = command.unwrap_or(&builtin.command).to_owned()
|
||||
agent.command = command.unwrap_or(&builtin.command).to_owned();
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Appends arguments to a directly launched built-in ACP agent; an empty list resets them.
|
||||
pub(crate) fn set_builtin_additional_args(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
args: Vec<String>,
|
||||
) -> IdeResult<()> {
|
||||
update_builtin(custom_dir, secrets, id, |agent, builtin| {
|
||||
if !allows_additional_args(builtin, agent.driver) {
|
||||
return Err(IdeError::invalid(format!("{id} does not support additional arguments")));
|
||||
}
|
||||
agent.additional_args = args;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -427,7 +696,10 @@ pub(crate) fn set_builtin_env(
|
||||
return agent.write(&file).map_err(Into::into);
|
||||
}
|
||||
}
|
||||
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
|
||||
update_builtin(custom_dir, secrets, id, |agent, _| {
|
||||
agent.env = env;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
|
||||
@@ -435,7 +707,7 @@ fn update_builtin(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
change: impl FnOnce(&mut CustomAgent, &ProviderSpec),
|
||||
change: impl FnOnce(&mut CustomAgent, &ProviderSpec) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
let Some(builtin) = builtin_spec(id) else {
|
||||
return Err(IdeError::invalid(format!("{id} is not a built-in agent")));
|
||||
@@ -449,6 +721,7 @@ fn update_builtin(
|
||||
driver: builtin.driver,
|
||||
command: builtin.command.clone(),
|
||||
args: builtin.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: None,
|
||||
}
|
||||
@@ -456,11 +729,12 @@ fn update_builtin(
|
||||
if agent.registry.is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
|
||||
}
|
||||
change(&mut agent, &builtin);
|
||||
change(&mut agent, &builtin)?;
|
||||
if agent.command == builtin.command
|
||||
&& agent.name.as_deref() == Some(builtin.name.as_str())
|
||||
&& agent.driver == builtin.driver
|
||||
&& agent.args == builtin.args
|
||||
&& agent.additional_args.is_empty()
|
||||
&& agent.env.is_empty()
|
||||
{
|
||||
match std::fs::remove_file(&file) {
|
||||
@@ -502,6 +776,7 @@ pub(crate) fn save_custom(
|
||||
driver: Driver::Acp,
|
||||
command: input.command.clone(),
|
||||
args: input.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: input.env.clone(),
|
||||
registry: None,
|
||||
}
|
||||
@@ -572,6 +847,7 @@ pub(crate) fn import_acp(
|
||||
driver: Driver::Acp,
|
||||
command: server.command,
|
||||
args: server.args,
|
||||
additional_args: Vec::new(),
|
||||
env: server.env,
|
||||
registry: None,
|
||||
}
|
||||
@@ -615,6 +891,9 @@ pub(crate) struct CustomAgent {
|
||||
pub command: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub args: Vec<String>,
|
||||
/// Kept separate from `args` so Settings reset does not erase a hand-written launch line.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub additional_args: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Set when the agent was installed from the ACP Registry.
|
||||
@@ -746,6 +1025,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
driver: agent.driver,
|
||||
command: agent.command,
|
||||
args: agent.args,
|
||||
additional_args_len: 0,
|
||||
env,
|
||||
login_hint: "Sign in with the agent's own command line first.".into(),
|
||||
source,
|
||||
@@ -763,6 +1043,10 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
spec.args = crate::native::copilot::headless_args(&spec.args);
|
||||
}
|
||||
if spec.source == AgentSource::Custom {
|
||||
if allows_additional_args(existing, spec.driver) {
|
||||
spec.additional_args_len = agent.additional_args.len();
|
||||
spec.args.extend(agent.additional_args);
|
||||
}
|
||||
spec.source = AgentSource::Builtin;
|
||||
}
|
||||
*existing = spec;
|
||||
@@ -853,6 +1137,22 @@ mod tests {
|
||||
assert_eq!(reset.env, custom.env);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
|
||||
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
|
||||
for spec in builtins() {
|
||||
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
|
||||
continue;
|
||||
}
|
||||
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
|
||||
}
|
||||
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
|
||||
for spec in builtins() {
|
||||
@@ -1043,6 +1343,53 @@ mod tests {
|
||||
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_args_append_and_reset_without_replacing_agent_file_overrides() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let omp = || load(Some(root), None).into_iter().find(|spec| spec.id == "omp").unwrap();
|
||||
assert_eq!(describe(&omp()).additional_args, Some(vec![]));
|
||||
set_builtin_additional_args(root, None, "omp", vec!["--extra".into()]).unwrap();
|
||||
assert_eq!(omp().args, ["acp", "--extra"]);
|
||||
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
|
||||
assert!(!root.join("omp.toml").exists());
|
||||
|
||||
let file = root.join("omp.toml");
|
||||
std::fs::write(
|
||||
&file,
|
||||
"name = \"My OMP\"\ncommand = \"/opt/my tools/omp\"\nargs = [\"acp\", \"--manual\"]\n[env]\nKEEP = \"value\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let original = omp();
|
||||
let extra = vec!["--label".into(), "two words".into(), String::new()];
|
||||
set_builtin_additional_args(root, None, "omp", extra.clone()).unwrap();
|
||||
let configured = omp();
|
||||
assert_eq!(configured.args, ["acp", "--manual", "--label", "two words", ""]);
|
||||
assert_eq!(describe(&configured).additional_args, Some(extra));
|
||||
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
|
||||
assert_eq!(omp(), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_args_cannot_modify_managed_or_non_acp_launches() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::write(
|
||||
root.join("gemini.toml"),
|
||||
"command = \"gemini\"\nargs = [\"--experimental-acp\"]\n[registry]\nid = \"gemini\"\nversion = \"1\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(root.join("mine.toml"), "command = \"mine\"\n").unwrap();
|
||||
std::fs::write(root.join("omp.toml"), "command = \"omp\"\ndriver = \"codex\"\n").unwrap();
|
||||
let before = load(Some(root), None);
|
||||
for id in ["gemini", "mine", "omp", "codex", "claude-acp"] {
|
||||
let spec = before.iter().find(|spec| spec.id == id).unwrap();
|
||||
assert!(describe(spec).additional_args.is_none());
|
||||
assert!(set_builtin_additional_args(root, None, id, vec!["--extra".into()]).is_err());
|
||||
}
|
||||
assert_eq!(load(Some(root), None), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_copilot_allows_only_the_github_account_override() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1052,6 +1399,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/tools/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
|
||||
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
|
||||
}
|
||||
@@ -1064,12 +1412,12 @@ mod tests {
|
||||
"copilot",
|
||||
BTreeMap::from([
|
||||
("REGISTRY_SETTING".into(), "kept".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("alice-work"));
|
||||
|
||||
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
|
||||
.unwrap_err();
|
||||
@@ -1078,7 +1426,7 @@ mod tests {
|
||||
#[test]
|
||||
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()));
|
||||
let resolved = spec.resolve_for_launch(Path::new("."));
|
||||
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
|
||||
}
|
||||
@@ -1108,6 +1456,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "amp".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "amp-acp".into(), version: "1.0.0".into() }),
|
||||
}
|
||||
@@ -1133,6 +1482,7 @@ mod tests {
|
||||
driver: Driver::Claude,
|
||||
command: "/old/claude".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: None,
|
||||
};
|
||||
@@ -1186,6 +1536,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
|
||||
args: vec!["acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
|
||||
registry: Some(RegistryRef { id: "amp-acp".into(), version: "0.10.0".into() }),
|
||||
};
|
||||
@@ -1359,4 +1710,68 @@ mod tests {
|
||||
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() {
|
||||
let raw = r#"{
|
||||
"hosts": {
|
||||
"github.com": [
|
||||
{"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"},
|
||||
{"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"}
|
||||
],
|
||||
"ghe.example.com": [
|
||||
{"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"}
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_json(raw),
|
||||
Some(vec![
|
||||
GhAuthAccount { login: "alice".into(), active: true },
|
||||
GhAuthAccount { login: "alice-work".into(), active: false },
|
||||
])
|
||||
);
|
||||
|
||||
let text = "\
|
||||
github.com
|
||||
✓ Logged in to github.com account env_user (GH_TOKEN)
|
||||
- Active account: true
|
||||
✓ Logged in to github.com account alice (keyring)
|
||||
- Active account: false
|
||||
✓ Logged in to github.com account alice-work (keyring)
|
||||
- Active account: true
|
||||
";
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_text(text),
|
||||
vec![
|
||||
GhAuthAccount { login: "alice".into(), active: false },
|
||||
GhAuthAccount { login: "alice-work".into(), active: true },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let app_support = dir.path().join("Application Support/copilot");
|
||||
std::fs::create_dir_all(&app_support).unwrap();
|
||||
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
|
||||
std::fs::write(&bin, "#!/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 mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.command = bin.to_string_lossy().into_owned();
|
||||
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert_eq!(launch.args, ["login"]);
|
||||
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
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(""));
|
||||
}
|
||||
}
|
||||
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
|
||||
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
|
||||
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
|
||||
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
|
||||
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
|
||||
}
|
||||
|
||||
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
|
||||
let tag = format!("v{}", entry.version.trim_start_matches('v'));
|
||||
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
|
||||
let sha256_url = format!("{base}/SHA256SUMS.txt");
|
||||
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
Some(p) => (p.args.clone(), p.env.clone()),
|
||||
None => (vec!["--acp".into()], BTreeMap::new()),
|
||||
};
|
||||
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
|
||||
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
|
||||
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
|
||||
let linux_arm = format!(
|
||||
"copilot-{}-arm64.tar.gz",
|
||||
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
|
||||
);
|
||||
let linux_x64 =
|
||||
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
|
||||
let targets = [
|
||||
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
|
||||
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
|
||||
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
|
||||
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
|
||||
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
|
||||
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
|
||||
let (glibc_rel, musl_rel) = match arch {
|
||||
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
|
||||
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
|
||||
};
|
||||
let glibc = root.join(glibc_rel);
|
||||
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
|
||||
let points_to_musl =
|
||||
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
|
||||
let has_glibc = glibc.exists() && !points_to_musl;
|
||||
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
|
||||
}
|
||||
|
||||
fn safe_segment(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& !s.starts_with('.')
|
||||
@@ -443,7 +467,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
|
||||
/// Installs (or updates to) the registry's current version of `id`, streaming progress
|
||||
/// through `emit`, and points the agent file at it.
|
||||
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
/// Installs agent `id`; an npm package retries against the public npm registry when the
|
||||
/// configured one misses it only with `public_npm_fallback`.
|
||||
pub fn install(
|
||||
paths: &RegistryPaths,
|
||||
id: &str,
|
||||
public_npm_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let id = canonical_id(id);
|
||||
// The saved index is what the user picked from; fetch only when there is none.
|
||||
let text = match fs::read_to_string(&paths.cache_file) {
|
||||
@@ -455,9 +487,14 @@ pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit
|
||||
.iter()
|
||||
.find(|e| e.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("{id} is not in the ACP Registry")))?;
|
||||
install_entry(paths, entry, Platform::current(), &on_path, cancel, emit)
|
||||
let npm_installer =
|
||||
move |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, public_npm_fallback, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, Platform::current(), &on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn install_entry(
|
||||
paths: &RegistryPaths,
|
||||
entry: &Entry,
|
||||
@@ -466,7 +503,10 @@ fn install_entry(
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
|
||||
let npm_installer = |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, true, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, platform, on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
|
||||
@@ -550,6 +590,7 @@ fn install_entry_with(
|
||||
driver: Driver::Acp,
|
||||
command: exe.to_string_lossy().into_owned(),
|
||||
args,
|
||||
additional_args: Vec::new(),
|
||||
env,
|
||||
registry: Some(RegistryRef { id: entry.id.clone(), version: entry.version.clone() }),
|
||||
};
|
||||
@@ -662,20 +703,23 @@ fn install_npm(
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn install_npm_with(
|
||||
npm: &Path,
|
||||
p: &Package,
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
@@ -703,6 +747,7 @@ fn install_npm_with(
|
||||
},
|
||||
&specs,
|
||||
false,
|
||||
public_fallback,
|
||||
cancel,
|
||||
emit,
|
||||
)?;
|
||||
@@ -941,6 +986,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/x".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: id.into(), version: version.into() }),
|
||||
};
|
||||
@@ -1002,7 +1048,7 @@ mod tests {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss_unless_registries_are_configured_only() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let install_dir = dir.path().join("acme/1.2.0");
|
||||
fs::create_dir_all(&install_dir).unwrap();
|
||||
@@ -1041,8 +1087,8 @@ esac
|
||||
]}"#;
|
||||
let entry = parse(index).unwrap().remove(0);
|
||||
let pkg = entry.distribution.npx.as_ref().unwrap();
|
||||
let exe =
|
||||
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let exe = install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, true, &CancellationToken::new(), &|_| {})
|
||||
.unwrap();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
@@ -1050,6 +1096,15 @@ esac
|
||||
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
|
||||
assert!(exe.is_file());
|
||||
// Only the configured registries: the miss is the error, and npmjs is never asked.
|
||||
let only = dir.path().join("acme-only/1.2.0");
|
||||
fs::create_dir_all(&only).unwrap();
|
||||
let err =
|
||||
install_npm_with(&npm, pkg, &entry, &only, MAC_ARM, false, &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 3, "{calls:?}");
|
||||
assert!(!calls[2].contains("--registry="), "{calls:?}");
|
||||
assert!(err.message.contains("notarget"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1168,6 +1223,7 @@ esac
|
||||
driver: Driver::Acp,
|
||||
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.104".into() }),
|
||||
}
|
||||
@@ -1180,7 +1236,7 @@ esac
|
||||
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
|
||||
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(spec.name, "GitHub Copilot");
|
||||
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
|
||||
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
|
||||
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
|
||||
|
||||
let mut providers = vec![provider::describe(&spec)];
|
||||
@@ -1272,4 +1328,96 @@ esac
|
||||
assert!(npm_bin.is_file());
|
||||
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
|
||||
let index = r#"{"agents":[
|
||||
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
|
||||
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let archives_for = |root: &Path| -> (String, String) {
|
||||
let mut entry = parse(index).unwrap().remove(0);
|
||||
entry.distribution.binary.clear();
|
||||
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
|
||||
(
|
||||
entry.distribution.binary["linux-x86_64"].archive.clone(),
|
||||
entry.distribution.binary["linux-aarch64"].archive.clone(),
|
||||
)
|
||||
};
|
||||
let touch = |path: PathBuf| {
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, b"").unwrap();
|
||||
};
|
||||
|
||||
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
assert_eq!(
|
||||
archives_for(empty.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
|
||||
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
|
||||
let glibc = tempfile::tempdir().unwrap();
|
||||
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
|
||||
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
|
||||
let musl = tempfile::tempdir().unwrap();
|
||||
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::create_dir_all(musl.path().join("lib64")).unwrap();
|
||||
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
|
||||
.unwrap();
|
||||
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let parsed = parse(index).unwrap().remove(0);
|
||||
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
|
||||
assert!(
|
||||
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
|
||||
"unexpected linux-x86_64 archive: {}",
|
||||
parsed.distribution.binary["linux-x86_64"].archive
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ pub fn widens_access(params: &Value) -> bool {
|
||||
tool.and_then(|t| t.pointer("/rawInput/networkApprovalContext")).is_some_and(|c| !c.is_null())
|
||||
}
|
||||
|
||||
fn command_from_value(val: &Value) -> Option<String> {
|
||||
pub(crate) fn command_from_value(val: &Value) -> Option<String> {
|
||||
match val {
|
||||
Value::String(s) => {
|
||||
let trimmed = s.trim();
|
||||
|
||||
@@ -649,11 +649,14 @@ pub struct Delivery {
|
||||
|
||||
/// Stages the skills a session of `provider` runs with into `farm` — linking (copying on
|
||||
/// Windows, where directory symlinks need Developer Mode) every active skill folder into
|
||||
/// the CLI's tree — and reports what to hand the CLI. Skills the CLI discovers natively
|
||||
/// (its own folders of the working directory and the home) are not staged again: it already
|
||||
/// sees them, and seeing both would list one skill twice. Skills `off` are never staged;
|
||||
/// the CLI's native disable (where it has one) receives their names or paths. An ACP
|
||||
/// agent gets nothing here: its `/` menu is filtered instead.
|
||||
/// the CLI's tree — and reports what to hand the CLI. For Claude Code and Codex, skills
|
||||
/// the CLI discovers natively (its own folders of the working directory and the home) are
|
||||
/// not staged again so the CLI does not see duplicates. For Copilot (`copilot --headless`),
|
||||
/// config discovery is off by default (enabling it would also auto-load workspace `.mcp.json`
|
||||
/// outside OpenIDEA's MCP approvals), so every active `Auto` skill is staged into
|
||||
/// `skillDirectories`. Skills `off` are never staged; the CLI's native disable (where it has
|
||||
/// one) receives their names or paths. An ACP agent gets nothing here: its `/` menu is
|
||||
/// filtered instead.
|
||||
pub fn stage(
|
||||
farm: &Path,
|
||||
provider: &str,
|
||||
@@ -705,7 +708,7 @@ pub fn stage(
|
||||
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if let Some(tree) = copilot_tree.as_ref().filter(|_| !native_copilot(&state.skill, &cwd, home)) {
|
||||
if let Some(tree) = copilot_tree.as_ref() {
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if let Some(tree) = codex_tree.as_ref().filter(|_| !native_codex(&state.skill, &cwd, home)) {
|
||||
@@ -794,29 +797,6 @@ fn native_claude(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Copilot natively scans `.github/skills`, `.agents/skills` and `.claude/skills` in `cwd`,
|
||||
/// plus `~/.copilot` and `~/.agents/skills` in `home`. `.openidea/skills` is NOT native.
|
||||
fn native_copilot(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
let target = skill.path.0.as_path();
|
||||
for rel in [".github/skills", ".agents/skills", ".claude/skills"] {
|
||||
let root = cwd.join(rel);
|
||||
if is_under(target, &root) || direct_link_matches(&root, &skill.name, target) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if let Some(h) = home {
|
||||
let h = dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf());
|
||||
if is_under(target, &h.join(".copilot"))
|
||||
|| is_under(target, &h.join(".agents/skills"))
|
||||
|| direct_link_matches(&h.join(".copilot/skills"), &skill.name, target)
|
||||
|| direct_link_matches(&h.join(".agents/skills"), &skill.name, target)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Codex natively scans `.codex/skills` and `.agents/skills` in `cwd` and `home`.
|
||||
fn native_codex(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
let target = skill.path.0.as_path();
|
||||
@@ -1232,8 +1212,9 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
|
||||
//For a local session, `.github/skills`, `.agents/skills` and `~/.agents/skills` are
|
||||
// already scanned natively by Copilot; `.openidea/skills` and `~/.codex/skills` are staged.
|
||||
// Copilot headless does not run disk config discovery unless explicitly opted in, so
|
||||
// every active `Auto` skill — including `.github/skills`, `.agents/skills`, `~/.agents/skills`,
|
||||
// `~/.copilot/installed-plugins`, `.openidea/skills`, and `~/.codex/skills` — must be staged.
|
||||
let mut states = states;
|
||||
std::fs::create_dir_all(repo.join(".openidea/skills/ideonly")).unwrap();
|
||||
states.push(AgentSkillState {
|
||||
@@ -1241,6 +1222,13 @@ mod tests {
|
||||
mode: AgentSkillMode::Auto,
|
||||
origin: AgentSkillOrigin::None,
|
||||
});
|
||||
let copilot_plugin_skills = home.join(".copilot/installed-plugins/_direct/azure/skills");
|
||||
std::fs::create_dir_all(copilot_plugin_skills.join("azure-ai")).unwrap();
|
||||
states.push(AgentSkillState {
|
||||
skill: skill("azure-ai", AgentSkillSource::CopilotUser, &copilot_plugin_skills),
|
||||
mode: AgentSkillMode::Auto,
|
||||
origin: AgentSkillOrigin::None,
|
||||
});
|
||||
|
||||
let farm = farm_dir(&root.join("store"), "task-1");
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
@@ -1249,7 +1237,7 @@ mod tests {
|
||||
let staged = listed(&claude_tree);
|
||||
assert_eq!(
|
||||
staged,
|
||||
["codexy", "gh", "ideonly", "lint", "muted", "tdd"],
|
||||
["azure-ai", "codexy", "gh", "ideonly", "lint", "muted", "tdd"],
|
||||
"everything but the off one: none is native to Claude here, and slash-only needs the folder"
|
||||
);
|
||||
|
||||
@@ -1259,8 +1247,8 @@ mod tests {
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert_eq!(
|
||||
copilot_staged,
|
||||
["codexy", "ideonly"],
|
||||
"`gh` (.github), `tdd` (.agents) and `lint` (~/.agents) are native to Copilot; `.openidea` & `~/.codex` are staged"
|
||||
["azure-ai", "codexy", "gh", "ideonly", "lint", "tdd"],
|
||||
"all active Auto skills (including .github, .agents, ~/.agents, and ~/.copilot/installed-plugins) are staged for Copilot headless"
|
||||
);
|
||||
assert_eq!(
|
||||
delivery.codex_off,
|
||||
@@ -1276,12 +1264,12 @@ mod tests {
|
||||
]
|
||||
);
|
||||
|
||||
// A worktree task: the repo's skills are untracked, so workspace skills are staged now.
|
||||
// A worktree task also stages all active workspace, user, and plugin skills.
|
||||
let worktree = root.join("wt");
|
||||
std::fs::create_dir_all(&worktree).unwrap();
|
||||
let _ = stage(&farm, "copilot", &states, &worktree, Some(&home)).unwrap();
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert!(copilot_staged.contains(&"gh".to_string()) && copilot_staged.contains(&"tdd".to_string()));
|
||||
assert_eq!(copilot_staged, ["azure-ai", "codexy", "gh", "ideonly", "lint", "tdd"]);
|
||||
|
||||
// Slash-only reaches Claude as `user-invocable-only`, off as `off`.
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
@@ -1289,7 +1277,7 @@ mod tests {
|
||||
assert_eq!(settings["skillOverrides"]["muted"], "user-invocable-only");
|
||||
assert_eq!(settings["skillOverrides"]["off"], "off");
|
||||
|
||||
// Restaging after a session turned `lint` off drops its link and leaves the skill.
|
||||
// Restaging after a session turned `lint` off drops its link and leaves the skill on disk.
|
||||
let session = BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)]);
|
||||
let restated = resolve(
|
||||
states.iter().map(|s| s.skill.clone()).collect(),
|
||||
@@ -1299,10 +1287,14 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
stage(&farm, "claude", &restated, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(listed(&claude_tree), ["codexy", "gh", "ideonly", "muted", "tdd"]);
|
||||
assert_eq!(listed(&claude_tree), ["azure-ai", "codexy", "gh", "ideonly", "muted", "tdd"]);
|
||||
assert!(home.join(".agents/skills/lint").is_dir());
|
||||
assert!(farm.join("copilot").is_dir(), "restaging Claude's tree leaves Copilot's alone");
|
||||
|
||||
let delivery = stage(&farm, "copilot", &restated, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(listed(&farm.join("copilot")), ["azure-ai", "codexy", "gh", "ideonly", "tdd"]);
|
||||
assert_eq!(delivery.copilot_disabled_skills, ["lint", "muted", "off"]);
|
||||
|
||||
// An ACP agent gets no farm.
|
||||
let delivery = stage(&farm, "cursor-acp", &states, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(delivery, Delivery::default());
|
||||
|
||||
@@ -63,6 +63,8 @@ struct FakeAgent {
|
||||
session_steering: bool,
|
||||
/// Records the `mcpServers` array passed to `session/new`, `session/load`, and `session/fork`.
|
||||
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
|
||||
/// The params of every `session/fork`, in order.
|
||||
forks: Mutex<Vec<Value>>,
|
||||
/// The content blocks of each `session/prompt`.
|
||||
prompts: Mutex<Vec<Value>>,
|
||||
}
|
||||
@@ -175,6 +177,9 @@ impl Handler for FakeAgent {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
self.mcp_calls.lock().push((method.to_owned(), names));
|
||||
if params.pointer("/_meta/openidea/ephemeral") == Some(&json!(true)) {
|
||||
self.calls.lock().push("ephemeral".into());
|
||||
}
|
||||
}
|
||||
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
|
||||
match method {
|
||||
@@ -203,7 +208,11 @@ impl Handler for FakeAgent {
|
||||
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
|
||||
"configOptions": options}))
|
||||
}
|
||||
"session/fork" => Ok(json!({"sessionId": "s2"})),
|
||||
"session/fork" => {
|
||||
self.forks.lock().push(params.clone());
|
||||
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
|
||||
Ok(json!({ "sessionId": requested.unwrap_or("s2") }))
|
||||
}
|
||||
"_openidea/stop_task" => {
|
||||
self.calls.lock().push(format!("{method} {}", params["taskId"]));
|
||||
Ok(json!({}))
|
||||
@@ -633,15 +642,124 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
|
||||
mgr.shutdown();
|
||||
let restored_agent = Arc::new(FakeAgent::default());
|
||||
let restored = manager(tmp.path(), restored_agent.clone());
|
||||
// Listing the tasks leaves the conversation on disk until something asks for it.
|
||||
assert_eq!(restored.subscribe_as("view", Arc::new(|_| {})).len(), 1);
|
||||
assert!(!restored.task(&task.id).unwrap().state.lock().history.is_loaded());
|
||||
assert!(!restored.entries(&task.id, None).unwrap().is_empty());
|
||||
assert!(restored.task(&task.id).unwrap().state.lock().history.is_loaded());
|
||||
assert!(restored_agent.calls.lock().is_empty());
|
||||
assert!(restored.entries("missing-task", None).is_err());
|
||||
assert!(restored.entries(&task.id, Some("missing-subagent".into())).is_err());
|
||||
restored.task(&task.id).unwrap().state.lock().conversation = Conversation::default();
|
||||
restored.task(&task.id).unwrap().state.lock().history.conversation = Conversation::default();
|
||||
assert!(restored.entries(&task.id, None).unwrap().is_empty());
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_archived_task_keeps_no_command_list_and_completes_the_known_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("hello"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let names = |list: Vec<AgentCommand>| list.into_iter().map(|c| c.name).collect::<Vec<_>>();
|
||||
let snapshot = |mgr: &AgentManager| mgr.task(&task.id).unwrap().state.lock().snapshot();
|
||||
assert!(names(snapshot(&mgr).commands).contains(&"review".to_owned()));
|
||||
|
||||
mgr.archive(&task.id).unwrap();
|
||||
assert!(snapshot(&mgr).commands.is_empty());
|
||||
assert!(names(mgr.commands("claude", Some(&task.id)).await.unwrap()).contains(&"review".to_owned()));
|
||||
mgr.shutdown();
|
||||
|
||||
// A list saved with an archived task (by an earlier version) isn't read back.
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(other.path().join("store")).unwrap();
|
||||
let name = format!("{}.json", task.id);
|
||||
let mut file: Value =
|
||||
serde_json::from_slice(&std::fs::read(tmp.path().join("store").join(&name)).unwrap()).unwrap();
|
||||
assert_eq!(file["task"]["status"], json!("archived"));
|
||||
file["task"]["commands"] = json!([{"name": "old", "description": "Old", "hint": null}]);
|
||||
std::fs::write(other.path().join("store").join(&name), serde_json::to_vec(&file).unwrap()).unwrap();
|
||||
let restored = manager(other.path(), Arc::new(FakeAgent::default()));
|
||||
assert!(snapshot(&restored).commands.is_empty());
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_conversation_that_cannot_be_read_is_never_saved_over() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("Keep this"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.shutdown();
|
||||
// In a store of its own: a late save of the first manager can't touch it.
|
||||
let name = format!("{}.json", task.id);
|
||||
let mut file: Value =
|
||||
serde_json::from_slice(&std::fs::read(tmp.path().join("store").join(&name)).unwrap()).unwrap();
|
||||
file["entries"].as_array_mut().unwrap().push(json!({"type": "no-such-entry"}));
|
||||
let damaged = serde_json::to_vec(&file).unwrap();
|
||||
let other = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(other.path().join("store")).unwrap();
|
||||
let path = other.path().join("store").join(&name);
|
||||
std::fs::write(&path, &damaged).unwrap();
|
||||
|
||||
let restored = manager(other.path(), Arc::new(FakeAgent::default()));
|
||||
// The task is listed from its own fields; its conversation shows empty.
|
||||
assert_eq!(restored.subscribe_as("view", Arc::new(|_| {})).len(), 1);
|
||||
assert!(restored.entries(&task.id, None).unwrap().is_empty());
|
||||
restored.rename(&task.id, "Renamed").unwrap();
|
||||
restored.shutdown();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), damaged);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for ephemeral in [true, false] {
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Write a commit message"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
ephemeral,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert_eq!(agent.calls.lock().iter().any(|c| c == "ephemeral"), ephemeral);
|
||||
mgr.shutdown();
|
||||
// The caller never deleted it (its window closed): only a saved task comes back.
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
assert_eq!(restored.task(&task.id).is_ok(), !ephemeral);
|
||||
restored.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn claude_commands_share_catalog_discovery_and_persist_results() {
|
||||
@@ -1444,9 +1562,9 @@ async fn saving_a_large_task_does_not_hold_up_readers() {
|
||||
let path = task_file(tmp.path(), &task.id);
|
||||
for i in 0..24 {
|
||||
let text = format!("output {i}: \"quoted\"\n").repeat(40_000);
|
||||
handle.state.lock().conversation.main.push(AgentEntry::Agent { text });
|
||||
handle.state.lock().history.conversation.main.push(AgentEntry::Agent { text });
|
||||
}
|
||||
let entries = handle.state.lock().conversation.main.entries.clone();
|
||||
let entries = handle.state.lock().history.conversation.main.entries.clone();
|
||||
let started = std::time::Instant::now();
|
||||
let json = serde_json::to_vec(&entries).unwrap();
|
||||
let serialising = started.elapsed();
|
||||
@@ -1539,7 +1657,7 @@ async fn concurrent_saves_keep_the_newest_state_of_each_task() {
|
||||
let task = idle_task(&mgr, name).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
// Long enough that a save takes a while between the copy and the write.
|
||||
handle.state.lock().conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
|
||||
handle.state.lock().history.conversation.main.push(AgentEntry::Agent { text: "text ".repeat(60_000) });
|
||||
tasks.push((name, handle, task_file(tmp.path(), &task.id)));
|
||||
}
|
||||
// "<name> <n>", n growing with every change made under the state lock.
|
||||
@@ -1632,6 +1750,47 @@ async fn shutdown_writes_the_saves_still_waiting_and_a_delete_drops_them() {
|
||||
assert_eq!(saved_title(&kept_path).as_deref(), Some("renamed"));
|
||||
}
|
||||
|
||||
/// Closing a project with many restored/archived tasks must not rewrite tasks that never changed.
|
||||
#[tokio::test]
|
||||
async fn shutdown_skips_rewriting_untouched_restored_tasks() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let untouched = idle_task(&mgr, "untouched").await;
|
||||
let archived = idle_task(&mgr, "archived").await;
|
||||
mgr.archive(&archived.id).unwrap();
|
||||
let dirty = idle_task(&mgr, "dirty").await;
|
||||
mgr.shutdown();
|
||||
|
||||
let (untouched_path, archived_path, dirty_path) =
|
||||
(task_file(tmp.path(), &untouched.id), task_file(tmp.path(), &archived.id), task_file(tmp.path(), &dirty.id));
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let before_untouched = FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0);
|
||||
let before_archived = FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0);
|
||||
let before_dirty = FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0);
|
||||
|
||||
let dirty_handle = restored.task(&dirty.id).unwrap();
|
||||
dirty_handle.state.lock().task.title = "updated".into();
|
||||
dirty_handle.persist_soon();
|
||||
|
||||
restored.shutdown();
|
||||
|
||||
assert_eq!(
|
||||
FILE_WRITES.lock().get(&untouched_path).copied().unwrap_or(0),
|
||||
before_untouched,
|
||||
"untouched task should not be rewritten on shutdown"
|
||||
);
|
||||
assert_eq!(
|
||||
FILE_WRITES.lock().get(&archived_path).copied().unwrap_or(0),
|
||||
before_archived,
|
||||
"archived task should not be rewritten on shutdown"
|
||||
);
|
||||
assert!(
|
||||
FILE_WRITES.lock().get(&dirty_path).copied().unwrap_or(0) > before_dirty,
|
||||
"pending persist_soon task must still be flushed on shutdown"
|
||||
);
|
||||
assert_eq!(saved_title(&dirty_path).as_deref(), Some("updated"));
|
||||
}
|
||||
|
||||
/// Archiving saves the task as it is, including changes nobody asked to be saved.
|
||||
#[tokio::test]
|
||||
async fn archiving_saves_the_task_before_it_returns() {
|
||||
@@ -2617,7 +2776,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task()
|
||||
mgr.shutdown();
|
||||
let restored = manager(tmp.path(), agent);
|
||||
let handle = restored.task(&task.id).unwrap();
|
||||
assert_eq!(handle.state.lock().conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
|
||||
assert_eq!(handle.state.lock().history.conversation.main.entries.iter().filter(|entry| matches!(entry, AgentEntry::Error {message} if message == "Project MCP config is disabled until trusted.")).count(), 1);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
@@ -2688,7 +2847,7 @@ async fn forks_rollbacks_and_steering() {
|
||||
}
|
||||
|
||||
// Undoing the last turn hands its message back.
|
||||
let undone = mgr.rollback(&task.id, 1).await.unwrap().unwrap();
|
||||
let undone = mgr.rollback(&task.id, 1, false).await.unwrap().unwrap();
|
||||
assert_eq!(undone.text, "again");
|
||||
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1);
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "_openidea/rollback 1"));
|
||||
@@ -2713,13 +2872,13 @@ async fn forks_rollbacks_and_steering() {
|
||||
"state": {"state": "idle", "stopReason": "end_turn"}}),
|
||||
);
|
||||
}
|
||||
handle.state.lock().conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
|
||||
handle.state.lock().history.conversation.main.entries.insert(0, AgentEntry::Agent { text: "Welcome".into() });
|
||||
let rewinds = agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count();
|
||||
let first = mgr.rollback(&task.id, 0).await.unwrap().unwrap();
|
||||
let first = mgr.rollback(&task.id, 0, false).await.unwrap().unwrap();
|
||||
assert_eq!(first.text, "again");
|
||||
assert!(mgr.entries(&task.id, None).unwrap().is_empty());
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_none());
|
||||
assert!(handle.state.lock().conversation.saved_subagents().is_empty());
|
||||
assert!(handle.state.lock().history.conversation.saved_subagents().is_empty());
|
||||
assert!(handle.state.lock().task.usage.is_none());
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| c.starts_with("_openidea/rollback")).count(), rewinds);
|
||||
mgr.shutdown();
|
||||
@@ -2732,6 +2891,128 @@ async fn forks_rollbacks_and_steering() {
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
const NATIVE_SOURCE: &str = "11111111-1111-4111-8111-111111111111";
|
||||
const NATIVE_TARGET: &str = "22222222-2222-4222-8222-222222222222";
|
||||
|
||||
/// Plants a recorded claude transcript for `session_id` under the project's escaped folder.
|
||||
fn plant_claude_session(mgr: &AgentManager, root: &Path, session_id: &str) {
|
||||
let config = root.join("claude-config");
|
||||
mgr.set_builtin_env(
|
||||
"claude",
|
||||
[("CLAUDE_CONFIG_DIR".to_string(), config.to_string_lossy().into_owned())].into_iter().collect(),
|
||||
)
|
||||
.unwrap();
|
||||
mgr.reload_providers();
|
||||
let escaped: String =
|
||||
root.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
|
||||
let transcript = config.join("projects").join(escaped).join(format!("{session_id}.jsonl"));
|
||||
std::fs::create_dir_all(transcript.parent().unwrap()).unwrap();
|
||||
std::fs::write(
|
||||
&transcript,
|
||||
format!(
|
||||
"{}\n",
|
||||
json!({
|
||||
"type": "user",
|
||||
"uuid": "u1",
|
||||
"parentUuid": null,
|
||||
"message": {"role": "user", "content": "fix the login bug"},
|
||||
"cwd": root.to_string_lossy(),
|
||||
})
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_starts_a_ready_task_as_the_recorded_session_s_fork() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let task = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap();
|
||||
assert_eq!(task.provider, "claude");
|
||||
assert_eq!(task.status, AgentStatus::Ready);
|
||||
assert_eq!(task.isolation, Isolation::Local);
|
||||
|
||||
mgr.prompt(&task.id, text("again"), true).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let forks = agent.forks.lock().clone();
|
||||
assert_eq!(forks.len(), 1, "one fork start");
|
||||
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
|
||||
let target = forks[0]["_meta"]["openidea"]["forkSessionId"].as_str().unwrap();
|
||||
assert!(canonical_uuid(target), "the host chooses a canonical fork id: {target}");
|
||||
assert_ne!(target, NATIVE_SOURCE);
|
||||
assert!(
|
||||
!agent.calls.lock().iter().any(|call| call == "session/new" || call == "session/load"),
|
||||
"the task forks the recorded session instead of starting or loading another"
|
||||
);
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(target));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
/// Plants a recorded codex rollout for `session_id` under the home `.codex/sessions` tree.
|
||||
fn plant_codex_session(root: &Path, session_id: &str) {
|
||||
let dir = root.join(".codex").join("sessions").join("2026").join("11").join("23");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join(format!("rollout-{session_id}.jsonl")),
|
||||
format!(
|
||||
"{}\n{}\n",
|
||||
json!({"type": "session_meta", "payload": {"id": session_id, "cwd": root.to_string_lossy()}}),
|
||||
json!({"type": "event_msg", "payload": {"type": "user_message", "message": "fix the login bug"}})
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_uses_the_id_codex_assigns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_codex_session(tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let task = mgr.fork_session("codex", NATIVE_SOURCE, tmp.path()).unwrap();
|
||||
assert_eq!(task.status, AgentStatus::Ready);
|
||||
mgr.prompt(&task.id, text("again"), true).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let forks = agent.forks.lock().clone();
|
||||
assert_eq!(forks.len(), 1);
|
||||
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
|
||||
assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "codex names its own fork");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2"));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_rejects_invalid_input_before_starting() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
// Non-native provider, malformed id, unknown session, wrong directory.
|
||||
let cases: [(&str, &str, &Path, ide_core::error::ErrorKind); 4] = [
|
||||
("gemini", NATIVE_SOURCE, tmp.path(), ide_core::error::ErrorKind::InvalidInput),
|
||||
("claude", "not-a-uuid", tmp.path(), ide_core::error::ErrorKind::InvalidInput),
|
||||
("claude", NATIVE_TARGET, tmp.path(), ide_core::error::ErrorKind::NotFound),
|
||||
("claude", NATIVE_SOURCE, Path::new("/elsewhere"), ide_core::error::ErrorKind::InvalidInput),
|
||||
];
|
||||
for (index, (provider, id, cwd, kind)) in cases.into_iter().enumerate() {
|
||||
let error = mgr.fork_session(provider, id, cwd).unwrap_err();
|
||||
assert_eq!(error.kind, kind, "case {index}: {error}");
|
||||
}
|
||||
// A session already held by a task cannot be forked again.
|
||||
mgr.import_session("claude", NATIVE_SOURCE).unwrap();
|
||||
let error = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap_err();
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput, "{error}");
|
||||
assert!(agent.calls.lock().is_empty(), "no process may start");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn usage_limits_and_late_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -3004,6 +3285,46 @@ async fn rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_compl
|
||||
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")] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = vec![json!({
|
||||
"id": "service_tier", "name": "Fast", "category": "model_config", "type": "select",
|
||||
"currentValue": value.unwrap_or("true"),
|
||||
"options": [{"value": "false"}, {"value": "true"}]
|
||||
})];
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "codex".into(),
|
||||
config: value
|
||||
.map(|value| vec![AgentConfigChoice { id: "service_tier".into(), value: value.into() }])
|
||||
.unwrap_or_default(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let calls = agent.calls.lock();
|
||||
let prompt = calls.iter().position(|call| call == "session/prompt").unwrap();
|
||||
if let Some(value) = value {
|
||||
let setting = calls
|
||||
.iter()
|
||||
.position(|call| call == &format!("session/set_config_option \"{value}\""))
|
||||
.expect("an explicit tier must not be mistaken for an inherited default");
|
||||
assert!(setting < prompt);
|
||||
} else {
|
||||
assert!(!calls.iter().any(|call| call == "session/set_config_option"));
|
||||
}
|
||||
drop(calls);
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
|
||||
for (effort, applied) in [("medium", true), ("high", false)] {
|
||||
@@ -3654,7 +3975,7 @@ async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
tokio::time::sleep(Duration::from_millis(600)).await;
|
||||
assert!(!live(&mgr, &task.id));
|
||||
mgr.rollback(&task.id, 1).await.unwrap();
|
||||
mgr.rollback(&task.id, 1, false).await.unwrap();
|
||||
assert!(live(&mgr, &task.id));
|
||||
tokio::time::sleep(Duration::from_millis(600)).await;
|
||||
assert!(!live(&mgr, &task.id), "an agent started to undo turns stops too");
|
||||
@@ -3942,14 +4263,10 @@ async fn composer_commands_discover_cursor_effort_and_fast() {
|
||||
assert!(calls.iter().any(|m| m.as_str() == "session/new"));
|
||||
assert_eq!(calls.iter().filter(|m| m.as_str() == "initialize").count(), 1);
|
||||
let cursor = mgr.providers().into_iter().find(|p| p.id == "cursor").unwrap();
|
||||
assert_eq!(cursor.config.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
|
||||
assert!(
|
||||
cursor
|
||||
.thought_levels
|
||||
.values()
|
||||
.next()
|
||||
.is_some_and(|levels| { levels.iter().any(|o| o.category.as_deref() == Some("thought_level")) })
|
||||
);
|
||||
assert!(!cursor.config.iter().any(|o| o.id == "fast"));
|
||||
let levels = cursor.thought_levels.values().next().expect("discovered model options");
|
||||
assert_eq!(levels.iter().find(|o| o.id == "fast").unwrap().current.as_deref(), Some("false"));
|
||||
assert!(levels.iter().any(|o| o.category.as_deref() == Some("thought_level")));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -4135,6 +4452,7 @@ fn a_running_tools_output_is_sent_as_appends() {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(1.0),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let running = |output| call(AgentToolStatus::Running, output);
|
||||
let event = |streamed: &mut Streamed, session: Session, i, entry: &AgentEntry| {
|
||||
@@ -4665,6 +4983,157 @@ async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rolling_back_to_a_message_puts_back_the_files_as_it_was_sent() {
|
||||
for isolation in [Isolation::Local, Isolation::Worktree] {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
repo.write("a.txt", "base\n");
|
||||
repo.write("gone.txt", "base\n");
|
||||
repo.commit("init");
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), isolation, ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
let cwd = task.cwd.0.clone();
|
||||
let write = |rel: &str, text: &str| std::fs::write(cwd.join(rel), text).unwrap();
|
||||
let read = |rel: &str| std::fs::read_to_string(cwd.join(rel)).ok();
|
||||
let case = format!("{isolation:?}");
|
||||
|
||||
one_turn(&mgr, &task.id, None, || write("a.txt", "base\nturn 1\n")).await;
|
||||
// The user's own work between the turns.
|
||||
write("mine.txt", "mine\n");
|
||||
one_turn(&mgr, &task.id, Some("more"), || {
|
||||
write("a.txt", "base\nturn 1\nturn 2\n");
|
||||
write("two.txt", "two\n");
|
||||
})
|
||||
.await;
|
||||
one_turn(&mgr, &task.id, Some("last"), || {
|
||||
write("a.txt", "base\nturn 1\nturn 2\nturn 3\n");
|
||||
std::fs::remove_file(cwd.join("gone.txt")).unwrap();
|
||||
})
|
||||
.await;
|
||||
// And after the last one.
|
||||
write("later.txt", "later\n");
|
||||
|
||||
// After a restart: the turns' records are kept with the task.
|
||||
mgr.shutdown();
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let undone = mgr.rollback(&task.id, 1, true).await.unwrap().unwrap();
|
||||
assert_eq!(undone.text, "more", "{case}");
|
||||
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1, "{case}");
|
||||
assert_eq!(read("a.txt").as_deref(), Some("base\nturn 1\n"), "{case}");
|
||||
assert_eq!(read("gone.txt").as_deref(), Some("base\n"), "{case}");
|
||||
assert_eq!(read("two.txt"), None, "{case}");
|
||||
// There before the message was sent.
|
||||
assert_eq!(read("mine.txt").as_deref(), Some("mine\n"), "{case}");
|
||||
let later = match isolation {
|
||||
// In the project's own checkout, a file no turn of the task changed is the user's.
|
||||
Isolation::Local => Some("later\n"),
|
||||
// In its own worktree, everything changed there since is the task's.
|
||||
Isolation::Worktree => None,
|
||||
};
|
||||
assert_eq!(read("later.txt").as_deref(), later, "{case}");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().history.turns.len(), 1, "{case}");
|
||||
|
||||
// Without `files` they stay; the first message takes the task back to its start.
|
||||
one_turn(&mgr, &task.id, Some("retry"), || write("a.txt", "again\n")).await;
|
||||
mgr.rollback(&task.id, 1, false).await.unwrap();
|
||||
assert_eq!(read("a.txt").as_deref(), Some("again\n"), "{case}");
|
||||
mgr.rollback(&task.id, 0, true).await.unwrap();
|
||||
assert_eq!(read("a.txt").as_deref(), Some("base\n"), "{case}");
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().history.turns.is_empty(), "{case}");
|
||||
let left = std::fs::read_dir(repo.dir.join("store").join(format!("{}.turn", task.id)));
|
||||
assert!(left.map_or(true, |mut d| d.next().is_none()), "{case}: no copies left");
|
||||
mgr.delete(&task.id, true).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_message_sent_before_turns_were_recorded_cannot_take_the_files_back() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
repo.write("a.txt", "base\n");
|
||||
repo.commit("init");
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
one_turn(&mgr, &task.id, None, || repo.write("a.txt", "base\nturn 1\n")).await;
|
||||
one_turn(&mgr, &task.id, Some("more"), || repo.write("a.txt", "base\nturn 1\nturn 2\n")).await;
|
||||
one_turn(&mgr, &task.id, Some("last"), || repo.write("a.txt", "base\nturn 1\nturn 2\nturn 3\n")).await;
|
||||
// As a task saved with its last turn's record only.
|
||||
mgr.task(&task.id).unwrap().state.lock().history.turns[1] = None;
|
||||
assert!(mgr.rollback(&task.id, 1, true).await.is_err());
|
||||
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 3, "nothing changed");
|
||||
assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\nturn 3\n");
|
||||
mgr.rollback(&task.id, 2, true).await.unwrap();
|
||||
assert_eq!(repo.read("a.txt"), "base\nturn 1\nturn 2\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rolling_back_to_first_message_without_turn_record_checks_before_changing_anything() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
repo.write("a.txt", "base\n");
|
||||
repo.write("b.txt", "base\n");
|
||||
repo.commit("init");
|
||||
repo.write("a.txt", "user edit\n");
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("Hello"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
one_turn(&mgr, &task.id, None, || {
|
||||
repo.write("a.txt", "agent edit\n");
|
||||
repo.write("b.txt", "agent edit\n");
|
||||
})
|
||||
.await;
|
||||
{
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let mut s = handle.state.lock();
|
||||
s.history.turns[0] = None;
|
||||
s.saved = None;
|
||||
}
|
||||
assert!(mgr.rollback(&task.id, 0, true).await.is_err());
|
||||
assert_eq!(turn_starts(&mgr.entries(&task.id, None).unwrap()).len(), 1, "conversation stays intact");
|
||||
assert!(mgr.task(&task.id).unwrap().state.lock().session_id.is_some(), "session stays intact");
|
||||
assert_eq!(repo.read("a.txt"), "agent edit\n");
|
||||
assert_eq!(repo.read("b.txt"), "agent edit\n");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn local_turn_rollback_keeps_user_edits_to_other_turns_files_and_reverts_committed_files() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
repo.write("turn1.txt", "base\n");
|
||||
repo.write("turn2.txt", "base\n");
|
||||
repo.commit("init");
|
||||
let mgr = manager(&repo.dir, Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("Hello"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
one_turn(&mgr, &task.id, None, || repo.write("turn1.txt", "turn 1\n")).await;
|
||||
one_turn(&mgr, &task.id, Some("more"), || {
|
||||
repo.write("turn2.txt", "turn 2\n");
|
||||
repo.write("committed.txt", "from turn 2\n");
|
||||
repo.git(&["add", "committed.txt"]);
|
||||
repo.git(&["commit", "-q", "-m", "turn 2 commit"]);
|
||||
})
|
||||
.await;
|
||||
// User edits a file from turn 1 after turn 2 finishes.
|
||||
repo.write("turn1.txt", "turn 1 + user edit\n");
|
||||
|
||||
mgr.rollback(&task.id, 1, true).await.unwrap();
|
||||
assert_eq!(repo.read("turn1.txt"), "turn 1 + user edit\n");
|
||||
assert_eq!(repo.read("turn2.txt"), "base\n");
|
||||
assert!(!repo.dir.join("committed.txt").exists());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rolling_back_the_whole_task_leaves_the_last_turn_nothing_to_list() {
|
||||
let repo = Checkout::new(Eol::Lf);
|
||||
@@ -5233,6 +5702,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5295,6 +5765,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
|
||||
("tdd".into(), AgentSkillMode::Auto),
|
||||
("noisy".into(), AgentSkillMode::Off),
|
||||
]),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5438,6 +5909,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -5464,6 +5936,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::new(),
|
||||
ephemeral: false,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -8,6 +8,9 @@ use std::collections::HashMap;
|
||||
/// Tool output kept per call; longer output keeps its tail.
|
||||
const MAX_OUTPUT: usize = 64 * 1024;
|
||||
|
||||
/// Image files a read tool names that are shown when it reports none itself.
|
||||
const MAX_READ_IMAGES: usize = 4;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Timeline {
|
||||
pub entries: Vec<AgentEntry>,
|
||||
@@ -88,6 +91,7 @@ impl Timeline {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let index = match self.tools.get(&id) {
|
||||
Some(&i) => {
|
||||
@@ -151,7 +155,7 @@ impl Timeline {
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, command, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
@@ -168,54 +172,25 @@ impl Timeline {
|
||||
*ended_ms = Some(crate::now_ms());
|
||||
}
|
||||
}
|
||||
if let Some(raw) = update.pointer("/rawInput/command").or_else(|| update.pointer("/rawInput/cmd"))
|
||||
&& let Some(cmd) = crate::security::command_from_value(raw)
|
||||
{
|
||||
*command = Some(crate::shell_script(&cmd).unwrap_or(cmd));
|
||||
}
|
||||
if update.get("locations").is_some_and(Value::is_array) {
|
||||
*locs = locations(update.get("locations"));
|
||||
}
|
||||
let Some(content) = update.get("content").and_then(Value::as_array) else { return };
|
||||
let mut text = String::new();
|
||||
let mut new_diffs = Vec::new();
|
||||
let mut new_images = Vec::new();
|
||||
for item in content {
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("content") => {
|
||||
let content = item.get("content");
|
||||
if let Some(image) = content.filter(|c| c.get("type").and_then(Value::as_str) == Some("image"))
|
||||
&& let (Some(data), Some(mime)) =
|
||||
(image.get("data").and_then(Value::as_str), image.get("mimeType").and_then(Value::as_str))
|
||||
&& !data.is_empty()
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
new_images.push(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
}
|
||||
if let Some(t) = content_text(content) {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&t);
|
||||
}
|
||||
}
|
||||
Some("diff") => {
|
||||
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
|
||||
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
|
||||
let (added, removed) = line_stats(old, new);
|
||||
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(content) = update.get("content").and_then(Value::as_array) {
|
||||
merge_content(content, output, images, diffs);
|
||||
}
|
||||
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;
|
||||
// Agents that only name the image a read tool opened (Cursor): show the file itself.
|
||||
if *status == AgentToolStatus::Completed && kind == "read" && images.is_empty() {
|
||||
images.extend(
|
||||
locs.iter()
|
||||
.filter(|p| p.0.is_absolute())
|
||||
.take(MAX_READ_IMAGES)
|
||||
.filter_map(|p| crate::images::from_file(&p.0)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -382,6 +357,54 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>
|
||||
})
|
||||
}
|
||||
|
||||
/// Folds a tool update's content into its output, diffs and images.
|
||||
fn merge_content(
|
||||
content: &[Value],
|
||||
output: &mut Option<String>,
|
||||
images: &mut Vec<AgentImage>,
|
||||
diffs: &mut Vec<AgentToolDiff>,
|
||||
) {
|
||||
let mut text = String::new();
|
||||
let mut new_diffs = Vec::new();
|
||||
let mut new_images = Vec::new();
|
||||
for item in content {
|
||||
match item.get("type").and_then(Value::as_str) {
|
||||
Some("content") => {
|
||||
let content = item.get("content");
|
||||
if let Some(image) = content.and_then(crate::images::from_content) {
|
||||
new_images.push(image);
|
||||
} else if let Some(t) = content_text(content) {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&t);
|
||||
}
|
||||
}
|
||||
Some("diff") => {
|
||||
let old = item.get("oldText").and_then(Value::as_str).unwrap_or_default();
|
||||
let new = item.get("newText").and_then(Value::as_str).unwrap_or_default();
|
||||
let (added, removed) = line_stats(old, new);
|
||||
new_diffs.push(AgentToolDiff { path: IpcPath(str_field(item, "path").into()), added, removed });
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
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 text of a list of content blocks, one per line.
|
||||
pub(crate) fn blocks_text(content: Option<&Value>) -> String {
|
||||
let blocks = content.and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
@@ -432,6 +455,7 @@ fn tail(mut text: String) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::AgentImage;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
@@ -453,6 +477,34 @@ mod tests {
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_execute_call_keeps_the_command_from_its_structured_input() {
|
||||
let mut t = Timeline::default();
|
||||
let command = |t: &Timeline, i: usize| match &t.entries[i] {
|
||||
AgentEntry::Tool { command, .. } => command.clone(),
|
||||
_ => panic!(),
|
||||
};
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "a", "title": "Run command", "kind": "execute",
|
||||
"rawInput": {"command": "python hello_world.py"}}));
|
||||
assert_eq!(command(&t, 0).as_deref(), Some("python hello_world.py"));
|
||||
// An argv array whose shell wraps the script, sent with a later update.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "b", "title": "Run command", "kind": "execute"}));
|
||||
assert_eq!(command(&t, 1), None);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "b",
|
||||
"rawInput": {"cmd": ["bash", "-lc", "cargo test -p ide-agent"]}}));
|
||||
assert_eq!(command(&t, 1).as_deref(), Some("cargo test -p ide-agent"));
|
||||
// One shell line, unwrapped as the permission card does.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "kind": "execute",
|
||||
"rawInput": {"command": "/bin/zsh -lc 'node hello.js'"}}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
// A later update without one keeps it; tasks saved before the field load without it.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c", "status": "completed"}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
let mut old = serde_json::to_value(&t.entries[2]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("command");
|
||||
assert!(matches!(serde_json::from_value(old).unwrap(), AgentEntry::Tool { command: None, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
@@ -478,6 +530,47 @@ mod tests {
|
||||
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_come_from_linked_files_and_resource_blobs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("out.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let mut t = Timeline::default();
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r", "title": "Read", "kind": "read"}));
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "r", "content": [
|
||||
{"type": "content", "content": {"type": "text", "text": "Read the image"}},
|
||||
{"type": "content", "content": {"type": "resource_link", "uri": crate::file_uri(&png), "name": "out.png"}},
|
||||
{"type": "content", "content": {"type": "resource", "resource": {"uri": "mem:1", "mimeType": "image/gif", "blob": "R0lG"}}}
|
||||
]}));
|
||||
let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() };
|
||||
let types: Vec<&str> = images.iter().map(|i| i.mime_type.as_str()).collect();
|
||||
assert_eq!(types, ["image/png", "image/gif"]);
|
||||
assert_eq!(output.as_deref(), Some("Read the image"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_completed_read_shows_the_image_file_it_names() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let png = dir.path().join("icon.png");
|
||||
std::fs::write(&png, b"\x89PNG\r\n").unwrap();
|
||||
let text = dir.path().join("a.rs");
|
||||
std::fs::write(&text, b"fn main() {}").unwrap();
|
||||
let mut t = Timeline::default();
|
||||
for (id, path) in [("img", &png), ("src", &text)] {
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": id, "title": "Read", "kind": "read",
|
||||
"locations": [{"path": path}]}));
|
||||
}
|
||||
let images = |t: &Timeline, i: usize| match &t.entries[i] {
|
||||
AgentEntry::Tool { images, .. } => images.len(),
|
||||
_ => panic!(),
|
||||
};
|
||||
assert_eq!(images(&t, 0), 0, "not before the read completes");
|
||||
for id in ["img", "src"] {
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed"}));
|
||||
}
|
||||
assert_eq!((images(&t, 0), images(&t, 1)), (1, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_merge_into_one_message_until_another_entry_comes() {
|
||||
let mut t = Timeline::default();
|
||||
|
||||
@@ -697,12 +697,24 @@ pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
|
||||
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
|
||||
out.insert(rel, stamp(&s.path));
|
||||
}
|
||||
if let Some(old) = &s.renamed_from
|
||||
&& let Some(rel) = nested_rel(&base, repo, &roots, &repo.root().join(old))
|
||||
{
|
||||
out.entry(rel).or_insert(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(out);
|
||||
}
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
Ok(repo.status()?.into_iter().map(|s| (s.rel_path, stamp(&s.path))).collect())
|
||||
let mut out = BTreeMap::new();
|
||||
for s in repo.status()? {
|
||||
out.insert(s.rel_path, stamp(&s.path));
|
||||
if let Some(old) = s.renamed_from {
|
||||
out.entry(old).or_insert(None);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The files whose state changed between two snapshots of a checkout: edited, new, deleted,
|
||||
@@ -763,6 +775,36 @@ pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Pa
|
||||
Ok(saved)
|
||||
}
|
||||
|
||||
fn restore_content(
|
||||
cwd: &Path,
|
||||
rev: Option<&str>,
|
||||
change: &AgentChange,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<Option<Vec<u8>>> {
|
||||
match before.get(&change.rel_path) {
|
||||
Some(None) => Ok(None),
|
||||
Some(Some(_)) => {
|
||||
let copy =
|
||||
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
|
||||
IdeError::invalid(format!(
|
||||
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
|
||||
change.rel_path
|
||||
))
|
||||
})?;
|
||||
Ok(Some(std::fs::read(copy)?))
|
||||
}
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
|
||||
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
repo.file_bytes_at(&change.path.0, Some(rev))
|
||||
}
|
||||
None => Ok(None),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Rolls `change` back: to the copy saved when the task started when the file had changes
|
||||
/// then (`before`, `saved` holding the copies), otherwise to `rev` (removed when `rev` lacks
|
||||
/// it, or when there is no `rev`: the repository had no commits).
|
||||
@@ -773,28 +815,35 @@ pub(crate) fn restore(
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<()> {
|
||||
let content = match before.get(&change.rel_path) {
|
||||
Some(None) => None,
|
||||
Some(Some(_)) => {
|
||||
let copy =
|
||||
saved.map(|d| d.join(saved_name(&change.rel_path))).filter(|p| p.is_file()).ok_or_else(|| {
|
||||
IdeError::invalid(format!(
|
||||
"{} had changes of yours when the task started that weren't saved; roll it back in Git instead",
|
||||
change.rel_path
|
||||
))
|
||||
})?;
|
||||
Some(std::fs::read(copy)?)
|
||||
}
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let at = change.repo.as_ref().map_or(cwd, |r| r.0.as_path());
|
||||
let repo = Repo::discover(at)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
repo.file_bytes_at(&change.path.0, Some(rev))?
|
||||
}
|
||||
None => None,
|
||||
},
|
||||
put(&change.path.0, restore_content(cwd, rev, change, before, saved)?)
|
||||
}
|
||||
|
||||
/// The files the task changed since it started, with what to put back. Fails, changing
|
||||
/// nothing, when one can't be put back.
|
||||
pub(crate) fn plan_restore(
|
||||
at: &TaskBase,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<PutBack>> {
|
||||
let changes = made_by_task(at.changes(before, None)?, touched);
|
||||
let rev = at.rev()?;
|
||||
let sources = match rev.as_deref() {
|
||||
Some(rev) => rename_sources(at.cwd(), rev)?,
|
||||
None => Default::default(),
|
||||
};
|
||||
put(&change.path.0, content)
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut out = Vec::new();
|
||||
for change in &changes {
|
||||
for change in std::iter::once(change).chain(sources.get(&change.rel_path)) {
|
||||
if !seen.insert(change.rel_path.clone()) {
|
||||
continue;
|
||||
}
|
||||
let content = restore_content(at.cwd(), rev.as_deref(), change, before, saved)?;
|
||||
out.push(PutBack { rel: change.rel_path.clone(), path: change.path.0.clone(), content });
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Writes `content` to `path`, or removes the file when there is none.
|
||||
@@ -819,7 +868,7 @@ pub(crate) fn saved_copy(dir: &Path, rel: &str) -> Option<Vec<u8>> {
|
||||
std::fs::read(dir.join(saved_name(rel))).ok()
|
||||
}
|
||||
|
||||
/// The checkout as the task's last turn started: what that turn's changes are compared with
|
||||
/// The checkout as one of the task's turns started: what that turn's changes are compared with
|
||||
/// and rolled back to. Recorded like the task's own start: `HEAD`, the files already changed,
|
||||
/// and copies of those.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
@@ -840,13 +889,45 @@ pub(crate) struct TurnStart {
|
||||
/// The files that changed while the turn ran, recorded as it ended (`None` while it runs).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub changed: Option<BTreeSet<String>>,
|
||||
/// The copies are named by file and stamp, so the turns share them; the turn recorded
|
||||
/// before that named them by file alone.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub stamped: bool,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
/// The name of the copy of `rel` as stamped `stamp`: the same while the file is unchanged.
|
||||
fn turn_copy_name(rel: &str, stamp: &Stamp) -> String {
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher.update(rel.as_bytes());
|
||||
hasher.update(&[0]);
|
||||
if let Some((len, modified)) = stamp {
|
||||
hasher.update(&[1]);
|
||||
hasher.update(&len.to_le_bytes());
|
||||
hasher.update(&modified.to_le_bytes());
|
||||
}
|
||||
let hex = hasher.finalize().to_hex();
|
||||
format!("t{}", &hex[..16])
|
||||
}
|
||||
|
||||
impl TurnStart {
|
||||
/// The name of the copy saved of `rel` as the turn began.
|
||||
fn copy_name(&self, rel: &str) -> Option<String> {
|
||||
if !self.stamped {
|
||||
return Some(saved_name(rel));
|
||||
}
|
||||
Some(turn_copy_name(rel, self.before.get(rel)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the checkout at `cwd` as a turn starts, with copies of its changed files in `dir`.
|
||||
/// The copies `previous` saved of files unchanged since are kept rather than made again, so
|
||||
/// A copy an earlier turn saved of a file unchanged since is used rather than made again, so
|
||||
/// starting a turn copies little more than what the turn before it changed.
|
||||
pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -> IdeResult<TurnStart> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) };
|
||||
pub(crate) fn start_turn(cwd: &Path, dir: &Path) -> IdeResult<TurnStart> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart { stamped: true, ..Default::default() }) };
|
||||
let mut heads = BTreeMap::new();
|
||||
let head = if at.nested {
|
||||
for repo in &at.repos {
|
||||
@@ -859,37 +940,95 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
|
||||
// As the turn's end is read, so the two compare.
|
||||
let before = snapshot(cwd)?;
|
||||
let mut saved = BTreeSet::new();
|
||||
match previous {
|
||||
Some(previous) => {
|
||||
for rel in &previous.saved {
|
||||
let unchanged =
|
||||
before.get(rel).is_some_and(|now| now.is_some() && previous.before.get(rel) == Some(now));
|
||||
if unchanged {
|
||||
saved.insert(rel.clone());
|
||||
} else {
|
||||
let _ = std::fs::remove_file(dir.join(saved_name(rel)));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
for (rel, stamp) in &before {
|
||||
let path = at.base.join(rel);
|
||||
if stamp.is_none()
|
||||
|| saved.contains(rel)
|
||||
|| !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX)
|
||||
{
|
||||
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
|
||||
continue;
|
||||
}
|
||||
let copy = dir.join(turn_copy_name(rel, stamp));
|
||||
if copy.is_file() {
|
||||
saved.insert(rel.clone());
|
||||
continue;
|
||||
}
|
||||
std::fs::create_dir_all(dir)?;
|
||||
// One that can't be copied is listed but can't be rolled back, as a large one.
|
||||
if std::fs::copy(&path, dir.join(saved_name(rel))).is_ok() {
|
||||
if std::fs::copy(&path, ©).is_ok() {
|
||||
saved.insert(rel.clone());
|
||||
}
|
||||
}
|
||||
Ok(TurnStart { head, heads, before, saved, changed: None })
|
||||
Ok(TurnStart { head, heads, before, saved, changed: None, stamped: true })
|
||||
}
|
||||
|
||||
/// Removes the copies in `dir` that none of `turns` uses any more.
|
||||
pub(crate) fn prune_turn_copies<'a>(dir: &Path, turns: impl IntoIterator<Item = &'a TurnStart>) {
|
||||
let used: BTreeSet<String> =
|
||||
turns.into_iter().flat_map(|t| t.saved.iter().filter_map(move |rel| t.copy_name(rel))).collect();
|
||||
let Ok(read) = std::fs::read_dir(dir) else { return };
|
||||
for entry in read.flatten() {
|
||||
if !used.contains(&*entry.file_name().to_string_lossy()) {
|
||||
let _ = std::fs::remove_file(entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A file to put back as it was.
|
||||
pub(crate) struct PutBack {
|
||||
/// Relative to the checkout, as the task names it.
|
||||
pub rel: String,
|
||||
pub path: PathBuf,
|
||||
/// `None`: there was no file.
|
||||
pub content: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// The files among `rels` that differ from how they were as the turn `start` began, with what
|
||||
/// to put back. Fails, changing nothing, when one can't be put back.
|
||||
pub(crate) fn rewind(cwd: &Path, start: &TurnStart, dir: &Path, rels: &BTreeSet<String>) -> IdeResult<Vec<PutBack>> {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut lower_counts: BTreeMap<String, usize> = BTreeMap::new();
|
||||
for rel in rels {
|
||||
*lower_counts.entry(rel.to_lowercase()).or_default() += 1;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for rel in rels {
|
||||
let path = at.base.join(rel);
|
||||
// A folder (a submodule, say) has nothing to put back.
|
||||
if path.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let then = at_turn_start(&at, rel, start, dir)?;
|
||||
// On a case-insensitive disk, `existing(&path)` can read a case-only rename's new name;
|
||||
// keep the write so `put_back` deletes the new name and recreates the old one.
|
||||
let case_collision = lower_counts.get(&rel.to_lowercase()).is_some_and(|&n| n > 1);
|
||||
if !case_collision && existing(&path).is_some_and(|now| now == then) {
|
||||
continue;
|
||||
}
|
||||
out.push(PutBack { rel: rel.clone(), path, content: then });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Writes what `rewind` or `plan_restore` planned, returning the files back to their saved
|
||||
/// pre-task copy so `before` can be restamped.
|
||||
pub(crate) fn put_back(
|
||||
mut planned: Vec<PutBack>,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
saved: Option<&Path>,
|
||||
) -> IdeResult<Vec<(String, Stamp)>> {
|
||||
// Removals first so a case-only rename on a case-insensitive disk ends at its old name.
|
||||
planned.sort_by_key(|f| f.content.is_some());
|
||||
let mut restamped = Vec::new();
|
||||
for file in planned {
|
||||
let should_restamp = matches!(before.get(&file.rel), Some(Some(_)))
|
||||
&& file
|
||||
.content
|
||||
.as_deref()
|
||||
.is_some_and(|bytes| saved.and_then(|d| saved_copy(d, &file.rel)).as_deref() == Some(bytes));
|
||||
put(&file.path, file.content)?;
|
||||
if should_restamp {
|
||||
restamped.push((file.rel, stamp(&file.path)));
|
||||
}
|
||||
}
|
||||
Ok(restamped)
|
||||
}
|
||||
|
||||
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
|
||||
@@ -919,7 +1058,12 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<S
|
||||
fn at_turn_start(at: &TurnRepos, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
match start.before.get(rel) {
|
||||
Some(None) => Ok(None),
|
||||
Some(Some(_)) => match start.saved.contains(rel).then(|| saved_copy(dir, rel)).flatten() {
|
||||
Some(Some(_)) => match start
|
||||
.saved
|
||||
.contains(rel)
|
||||
.then(|| start.copy_name(rel).and_then(|name| std::fs::read(dir.join(name)).ok()))
|
||||
.flatten()
|
||||
{
|
||||
Some(bytes) => Ok(Some(bytes)),
|
||||
None => Err(IdeError::invalid(format!(
|
||||
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
|
||||
@@ -1312,30 +1456,64 @@ mod tests {
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
let dir = tmp.path().join("turn");
|
||||
let set = |names: &[&str]| names.iter().map(|n| (*n).to_owned()).collect::<BTreeSet<_>>();
|
||||
let copy = |turn: &TurnStart, rel: &str| std::fs::read(dir.join(turn.copy_name(rel).unwrap())).ok();
|
||||
let at = |turn: &TurnStart, rel: &str| {
|
||||
at_turn_start(&TurnRepos::of(&repo).unwrap().unwrap(), rel, turn, &dir).unwrap()
|
||||
};
|
||||
|
||||
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
|
||||
std::fs::write(repo.join("b.txt"), "b\n").unwrap();
|
||||
let first = start_turn(&repo, &dir, None).unwrap();
|
||||
let first = start_turn(&repo, &dir).unwrap();
|
||||
assert_eq!(first.saved, set(&["a.txt", "b.txt"]));
|
||||
// A copy made again would replace this mark.
|
||||
std::fs::write(dir.join(saved_name("b.txt")), "kept\n").unwrap();
|
||||
std::fs::write(dir.join(first.copy_name("b.txt").unwrap()), "kept\n").unwrap();
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(repo.join("a.txt"), "turn two\n").unwrap();
|
||||
let second = start_turn(&repo, &dir, Some(&first)).unwrap();
|
||||
let second = start_turn(&repo, &dir).unwrap();
|
||||
assert_eq!(second.saved, set(&["a.txt", "b.txt"]));
|
||||
assert_eq!(saved_copy(&dir, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
|
||||
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"kept\n"[..]));
|
||||
assert_eq!(copy(&second, "a.txt").as_deref(), Some(&b"turn two\n"[..]));
|
||||
assert_eq!(copy(&second, "b.txt").as_deref(), Some(&b"kept\n"[..]));
|
||||
// The first turn keeps its own copy of the file changed since.
|
||||
assert_eq!(at(&first, "a.txt").as_deref(), Some(&b"turn 1\n"[..]));
|
||||
|
||||
// Back as committed: nothing to keep a copy of.
|
||||
// Back as committed: nothing to keep a copy of, and the committed text is the start.
|
||||
git(&repo, &["checkout", "--", "a.txt"]);
|
||||
let third = start_turn(&repo, &dir, Some(&second)).unwrap();
|
||||
let third = start_turn(&repo, &dir).unwrap();
|
||||
assert_eq!(third.saved, set(&["b.txt"]));
|
||||
assert_eq!(saved_copy(&dir, "a.txt"), None);
|
||||
// Without a record of the last turn (a task from before), every copy is made afresh.
|
||||
let fresh = start_turn(&repo, &dir, None).unwrap();
|
||||
assert_eq!(fresh.saved, set(&["b.txt"]));
|
||||
assert_eq!(saved_copy(&dir, "b.txt").as_deref(), Some(&b"b\n"[..]));
|
||||
assert_eq!(at(&third, "a.txt").as_deref(), Some(&b"base\n"[..]));
|
||||
|
||||
// Dropping the earlier turns drops the copies only they used.
|
||||
prune_turn_copies(&dir, [&third]);
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
|
||||
assert_eq!(copy(&third, "b.txt").as_deref(), Some(&b"kept\n"[..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn put_back_removes_new_name_before_writing_old_name_for_case_only_rename() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("A.txt"), "upper\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let dir = tmp.path().join("turn");
|
||||
let start = start_turn(&repo, &dir).unwrap();
|
||||
git(&repo, &["mv", "A.txt", "a.txt"]);
|
||||
let changed = changed_in_turn(&repo, &start).unwrap().1;
|
||||
let planned = rewind(&repo, &start, &dir, &changed).unwrap();
|
||||
put_back(planned, &BTreeMap::new(), None).unwrap();
|
||||
|
||||
assert_eq!(std::fs::read_to_string(repo.join("A.txt")).unwrap(), "upper\n");
|
||||
let entries: Vec<String> = std::fs::read_dir(&repo)
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n != ".git")
|
||||
.collect();
|
||||
assert_eq!(entries, ["A.txt"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -1350,7 +1528,7 @@ mod tests {
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
std::fs::write(repo.join("a.txt"), "turn 1\n").unwrap();
|
||||
let dir = tmp.path().join("turn");
|
||||
let start = start_turn(&repo, &dir, None).unwrap();
|
||||
let start = start_turn(&repo, &dir).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "turn 2\n").unwrap();
|
||||
std::fs::write(repo.join("new.txt"), "new\n").unwrap();
|
||||
let link = tmp.path().join("link");
|
||||
|
||||
@@ -10,3 +10,6 @@ ide-core.workspace = true
|
||||
serde.workspace = true
|
||||
specta.workspace = true
|
||||
which = "8"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -12,11 +12,12 @@ mod process;
|
||||
|
||||
pub use model::*;
|
||||
|
||||
use ide_core::process::{own_group, prepare};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// `adb devices` is quick unless it starts the daemon, which can take a moment.
|
||||
const DEVICES: Duration = Duration::from_secs(20);
|
||||
@@ -28,6 +29,8 @@ const TAIL_LINES: u32 = 200;
|
||||
/// while `IDLE` makes sure a quiet stream still shows its last line promptly.
|
||||
const BATCH_IDLE: Duration = Duration::from_millis(60);
|
||||
const BATCH_MAX: usize = 300;
|
||||
/// How long a started emulator gets to fail: a locked or broken AVD exits within it.
|
||||
const EMULATOR_STARTUP: Duration = Duration::from_secs(3);
|
||||
|
||||
fn exe(name: &str) -> String {
|
||||
if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }
|
||||
@@ -91,6 +94,51 @@ fn executable() -> IdeResult<PathBuf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The SDK's `emulator` executable, which starts AVDs.
|
||||
pub fn emulator_executable() -> Option<PathBuf> {
|
||||
let name = exe("emulator");
|
||||
sdk_roots().into_iter().map(|root| root.join("emulator").join(&name)).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Starts AVD `avd` in its own process group, so it
|
||||
/// outlives whoever asked: a restarted `flutter daemon`, a closed project, the IDE. Fails when
|
||||
/// the emulator exits within its first seconds, with what it printed.
|
||||
pub fn launch_emulator(avd: &str) -> IdeResult<()> {
|
||||
let emulator = emulator_executable().ok_or_else(|| {
|
||||
IdeError::unavailable(
|
||||
"the Android emulator was not found: install it with the Android SDK Manager, or set ANDROID_HOME",
|
||||
)
|
||||
})?;
|
||||
start_emulator(&emulator, avd)
|
||||
}
|
||||
|
||||
fn start_emulator(emulator: &Path, avd: &str) -> IdeResult<()> {
|
||||
let name: String = avd.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
|
||||
let log_path = std::env::temp_dir().join(format!("openidea-emulator-{name}.log"));
|
||||
let log = std::fs::File::create(&log_path)?;
|
||||
let mut cmd = Command::new(emulator);
|
||||
cmd.arg("-avd").arg(avd);
|
||||
cmd.stdin(Stdio::null()).stdout(log.try_clone()?).stderr(log);
|
||||
let mut child = prepare(own_group(&mut cmd)).spawn()?;
|
||||
let deadline = Instant::now() + EMULATOR_STARTUP;
|
||||
while Instant::now() < deadline {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
let output = std::fs::read_to_string(&log_path).unwrap_or_default();
|
||||
let tail: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail[tail.len().saturating_sub(8)..].join("\n");
|
||||
return Err(IdeError::unavailable(if tail.is_empty() {
|
||||
format!("the emulator exited ({status})")
|
||||
} else {
|
||||
tail
|
||||
}));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
// Reaps it whenever it ends.
|
||||
std::thread::spawn(move || child.wait());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Connected devices, online ones first; starting the adb daemon when needed.
|
||||
pub fn devices() -> IdeResult<Vec<AndroidDevice>> {
|
||||
let adb = executable()?;
|
||||
@@ -206,6 +254,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn an_emulator_that_fails_at_once_says_why_and_one_that_runs_is_left_running() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let script = |name: &str, body: &str| {
|
||||
let path = dir.path().join(name);
|
||||
std::fs::write(&path, format!("#!/bin/sh\n{body}")).unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
path
|
||||
};
|
||||
let broken = script("broken", "echo \"PANIC: Missing emulator engine for $2\" >&2\nexit 1\n");
|
||||
let e = start_emulator(&broken, "Pixel_9").unwrap_err();
|
||||
assert_eq!(e.message, "PANIC: Missing emulator engine for Pixel_9");
|
||||
|
||||
let args = dir.path().join("args");
|
||||
let running =
|
||||
script("running", &format!("echo $$ > '{0}.pid'\necho \"$@\" > '{0}'\nexec sleep 30\n", args.display()));
|
||||
start_emulator(&running, "Pixel_9").unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&args).unwrap().trim(), "-avd Pixel_9");
|
||||
let pid = std::fs::read_to_string(dir.path().join("args.pid")).unwrap();
|
||||
assert!(Command::new("kill").arg(pid.trim()).status().unwrap().success(), "still running");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executable_is_absolute_when_found() {
|
||||
if let Some(adb) = adb_executable() {
|
||||
|
||||
@@ -26,9 +26,10 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
let module = dunce::canonicalize(root.join(module))?;
|
||||
if let Some(p) = model.maven.as_ref().and_then(|m| m.projects.iter().find(|p| root.join(&p.dir) == module)) {
|
||||
let mut args = p.options.clone();
|
||||
let repo = crate::maven::local_repository_for(&p.options);
|
||||
args.extend([
|
||||
"process-resources".into(),
|
||||
"help:evaluate".into(),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
|
||||
"-Dexpression=project.build.outputDirectory".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::io::Read;
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// `(byte length, mtime, blake3 hex)`; the hash is recorded for files inside the project only.
|
||||
type Stamp = (u64, SystemTime, Option<String>);
|
||||
pub(crate) type Stamp = (u64, SystemTime, Option<String>);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LaunchFingerprint {
|
||||
@@ -182,7 +182,7 @@ fn collect(
|
||||
}
|
||||
|
||||
/// Scans every input, storing project inputs relative to the project.
|
||||
pub(super) fn scan_all(
|
||||
pub(crate) fn scan_all(
|
||||
root: &Path,
|
||||
inputs: Vec<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
@@ -282,6 +282,11 @@ pub(super) fn module_fingerprint(
|
||||
}
|
||||
|
||||
impl LaunchFingerprint {
|
||||
/// The fingerprint of `parameters` and the files under `inputs` (see [`scan_all`]).
|
||||
pub(crate) fn new(parameters: String, files: BTreeMap<PathBuf, Option<Stamp>>) -> Self {
|
||||
LaunchFingerprint { version: 2, parameters, files }
|
||||
}
|
||||
|
||||
/// Folders (relative to the project) of the Maven projects whose POM is an input.
|
||||
pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> {
|
||||
self.files
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
//! background with cancellation and parses the compiler output into messages
|
||||
//! for the Build tool window, the Problems view and the editor.
|
||||
|
||||
mod fingerprint;
|
||||
pub(crate) mod fingerprint;
|
||||
mod launch_resources;
|
||||
mod modules;
|
||||
mod parse;
|
||||
mod single;
|
||||
mod structure;
|
||||
mod tsc_watch;
|
||||
mod up_to_date;
|
||||
|
||||
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
|
||||
@@ -16,12 +17,14 @@ pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
|
||||
single_file_classpath, single_file_target,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
|
||||
};
|
||||
pub use tsc_watch::{tsc_watch, tsc_watch_roots};
|
||||
pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
|
||||
use crate::process::{self, Stream};
|
||||
@@ -236,10 +239,13 @@ pub fn plan(
|
||||
let project_name = root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned());
|
||||
let module_dir = match file {
|
||||
Some(f) => {
|
||||
let scope = model
|
||||
.gradle
|
||||
.iter()
|
||||
.flat_map(|g| std::iter::once(root.join(&g.dir)).chain(g.projects.iter().map(|p| root.join(&p.dir))))
|
||||
let maven_dirs = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| normalize(&root.join(&p.dir))));
|
||||
let gradle_dirs = model.gradle.iter().flat_map(|g| {
|
||||
std::iter::once(normalize(&root.join(&g.dir)))
|
||||
.chain(g.projects.iter().map(|p| normalize(&root.join(&p.dir))))
|
||||
});
|
||||
let scope = maven_dirs
|
||||
.chain(gradle_dirs)
|
||||
.filter(|dir| f.starts_with(dir))
|
||||
.max_by_key(|dir| dir.components().count())
|
||||
.unwrap_or_else(|| root.to_path_buf());
|
||||
@@ -251,10 +257,13 @@ pub fn plan(
|
||||
None => None,
|
||||
};
|
||||
let dir = module_dir.clone().unwrap_or_else(|| root.to_path_buf());
|
||||
// A folder of sibling projects has no build file itself; its Maven projects are built one by one.
|
||||
let system = detect_dir(&dir, model, root)
|
||||
.or((!model.gradle.is_empty()).then_some(BuildSystem::Gradle))
|
||||
.or_else(|| model.maven.as_ref().filter(|m| !m.projects.is_empty()).map(|_| BuildSystem::Maven))
|
||||
let direct_system = detect_dir(&dir, model, root);
|
||||
let has_gradle = !model.gradle.is_empty();
|
||||
let has_maven = model.maven.as_ref().is_some_and(|m| !m.projects.is_empty());
|
||||
// A folder of sibling projects has no build file itself; build every linked Gradle and Maven project in it.
|
||||
let system = direct_system
|
||||
.or(has_gradle.then_some(BuildSystem::Gradle))
|
||||
.or(has_maven.then_some(BuildSystem::Maven))
|
||||
.ok_or_else(|| {
|
||||
IdeError::not_found("no supported build system (Maven, Gradle, .NET, Cargo, Go, TypeScript, CMake) found")
|
||||
})?;
|
||||
@@ -267,17 +276,26 @@ pub fn plan(
|
||||
),
|
||||
None => project_name,
|
||||
};
|
||||
let steps = match system {
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
|
||||
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Cargo => cargo_steps(&dir, kind),
|
||||
// Go builds the file's package (a module holds many).
|
||||
BuildSystem::Go => go_steps(file.and_then(Path::parent).unwrap_or(&dir), kind)?,
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
|
||||
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
|
||||
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
|
||||
let steps = if module_dir.is_none() && direct_system.is_none() && has_gradle && has_maven {
|
||||
let mut combined = gradle_steps(root, model, kind, None)?;
|
||||
combined.extend(maven_steps(root, model, kind, None, cache, cancel)?);
|
||||
combined
|
||||
} else {
|
||||
match system {
|
||||
BuildSystem::Maven => maven_steps(root, model, kind, module_dir.as_deref(), cache, cancel)?,
|
||||
BuildSystem::Gradle => gradle_steps(root, model, kind, module_dir.as_deref())?,
|
||||
BuildSystem::Cargo => cargo_steps(&dir, kind),
|
||||
// Go builds the file's package (a module holds many); a directory target builds itself.
|
||||
BuildSystem::Go => {
|
||||
let pkg = file.map(|f| if f.is_dir() { f } else { f.parent().unwrap_or(f) }).unwrap_or(&dir);
|
||||
go_steps(pkg, kind)?
|
||||
}
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
|
||||
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
|
||||
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
|
||||
}
|
||||
};
|
||||
Ok(BuildPlan { system, title, steps })
|
||||
}
|
||||
@@ -796,6 +814,11 @@ pub fn run(
|
||||
|
||||
/// Per-file editor / Problems diagnostics of the messages that have a position.
|
||||
pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
|
||||
diagnostics_from(messages, DIAGNOSTICS_SOURCE)
|
||||
}
|
||||
|
||||
/// [`diagnostics`] reported by `source`.
|
||||
pub fn diagnostics_from(messages: &[BuildMessage], source: &str) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
|
||||
let mut out: BTreeMap<PathBuf, Vec<Diagnostic>> = BTreeMap::new();
|
||||
for m in messages {
|
||||
let (Some(path), Some(range)) = (&m.path, m.range) else { continue };
|
||||
@@ -803,11 +826,11 @@ pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnosti
|
||||
range,
|
||||
severity: m.severity,
|
||||
message: m.text.clone(),
|
||||
source: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
source: Some(source.to_owned()),
|
||||
code: m.code.clone(),
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
server: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
server: Some(source.to_owned()),
|
||||
});
|
||||
}
|
||||
out
|
||||
@@ -845,6 +868,28 @@ fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject)
|
||||
projects
|
||||
}
|
||||
|
||||
/// A step running Maven, its output parsed as Maven's.
|
||||
pub(crate) fn maven_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
|
||||
BuildStep::new(program, args, cwd, Format::Maven)
|
||||
}
|
||||
|
||||
pub(crate) fn gradle_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
|
||||
BuildStep::new(program, args, cwd, Format::Gradle)
|
||||
}
|
||||
|
||||
/// The linked reactor root building the project at `module` (project-relative).
|
||||
pub(crate) fn maven_reactor_dir<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
|
||||
maven_reactor(m, module)
|
||||
}
|
||||
|
||||
/// The projects of the reactor `top`.
|
||||
pub(crate) fn reactor_projects_of<'a>(
|
||||
m: &'a maven::MavenModel,
|
||||
top: &'a maven::MavenProject,
|
||||
) -> Vec<&'a maven::MavenProject> {
|
||||
reactor_projects(m, top)
|
||||
}
|
||||
|
||||
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
|
||||
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
|
||||
}
|
||||
@@ -965,6 +1010,7 @@ pub struct LaunchBuild {
|
||||
|
||||
/// Compiles the module at `module` with its build system before a JVM launch and
|
||||
/// returns the class directories it wrote, to put ahead of the jdtls classpath.
|
||||
/// The build's console, messages and progress stream to `on_event` as it runs.
|
||||
pub fn build_for_launch(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
@@ -972,8 +1018,9 @@ pub fn build_for_launch(
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<LaunchBuild> {
|
||||
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel)?;
|
||||
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel, on_event)?;
|
||||
Ok(built.pop().unwrap())
|
||||
}
|
||||
|
||||
@@ -986,9 +1033,10 @@ pub fn build_for_launches(
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<Vec<LaunchBuild>> {
|
||||
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
|
||||
let result = run(root, &plan, cancel, &|_| {})?;
|
||||
let result = run(root, &plan, cancel, on_event)?;
|
||||
let failure = if !result.success {
|
||||
let errors: Vec<String> = result
|
||||
.messages
|
||||
@@ -1822,8 +1870,16 @@ mod tests {
|
||||
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut model = reactor_model();
|
||||
model.maven.as_mut().unwrap().projects[0].command = wrapper.to_string_lossy().into_owned();
|
||||
let dirs = build_for_launch(root, &model, &root.join("app"), true, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap();
|
||||
let dirs = build_for_launch(
|
||||
root,
|
||||
&model,
|
||||
&root.join("app"),
|
||||
true,
|
||||
BuildKind::Build,
|
||||
&CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
dirs.class_dirs,
|
||||
["app/target/test-classes", "app/target/classes", "middle/target/classes", "lib/target/classes"]
|
||||
@@ -1834,16 +1890,25 @@ mod tests {
|
||||
"mvnw",
|
||||
"#!/bin/sh\necho '[ERROR] Kotlin compilation failed: unresolved reference broken' >&2\nexit 1\n",
|
||||
);
|
||||
let error =
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new())
|
||||
.unwrap()
|
||||
.failure
|
||||
.unwrap();
|
||||
let error = build_for_launch(
|
||||
root,
|
||||
&model,
|
||||
&root.join("app"),
|
||||
false,
|
||||
BuildKind::Build,
|
||||
&CancellationToken::new(),
|
||||
&|_| {},
|
||||
)
|
||||
.unwrap()
|
||||
.failure
|
||||
.unwrap();
|
||||
assert!(error.contains("Kotlin compilation failed"), "{error}");
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert_eq!(
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel).unwrap_err().kind,
|
||||
build_for_launch(root, &model, &root.join("app"), false, BuildKind::Build, &cancel, &|_| {})
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ide_core::error::ErrorKind::Cancelled
|
||||
);
|
||||
}
|
||||
@@ -1870,4 +1935,92 @@ mod tests {
|
||||
assert_eq!(launch_class_dirs(BuildSystem::Gradle, m, true)[0], m.join("build/classes/kotlin/test"));
|
||||
assert_eq!(launch_class_dirs(BuildSystem::Maven, m, true), [m.join("target/classes")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polyglot_root_targets_selected_subproject_or_combines_sibling_builds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("polyglot");
|
||||
write(&root, "Cargo.toml", "[package]\nname = \"root\"\nversion = \"0.1.0\"\n");
|
||||
write(
|
||||
&root,
|
||||
"fixtures/java-app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>app</artifactId><version>1</version></project>",
|
||||
);
|
||||
write(&root, "fixtures/kotlin-gradle/build.gradle.kts", "plugins { kotlin(\"jvm\") }\n");
|
||||
let model = crate::load(&root, &tmp.path().join("cache"), None);
|
||||
|
||||
let maven = plan(
|
||||
&root,
|
||||
&model,
|
||||
BuildKind::Build,
|
||||
Some(&root.join("fixtures/java-app")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(maven.system, BuildSystem::Maven);
|
||||
assert_eq!(maven.steps.len(), 1);
|
||||
assert_eq!(maven.steps[0].cwd, root.join("fixtures/java-app"));
|
||||
|
||||
let gradle = plan(
|
||||
&root,
|
||||
&model,
|
||||
BuildKind::Build,
|
||||
Some(&root.join("fixtures/kotlin-gradle")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(gradle.system, BuildSystem::Gradle);
|
||||
assert_eq!(gradle.steps.len(), 1);
|
||||
assert_eq!(gradle.steps[0].cwd, root.join("fixtures/kotlin-gradle"));
|
||||
|
||||
let cargo = plan(&root, &model, BuildKind::Build, Some(&root), None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(cargo.system, BuildSystem::Cargo);
|
||||
assert_eq!(cargo.steps[0].cwd, root);
|
||||
|
||||
// Folder without a root build file builds both linked Gradle and Maven subprojects on Build Project.
|
||||
let mixed = tmp.path().join("mixed");
|
||||
write(&mixed, "gradle-app/build.gradle.kts", "plugins { java }\n");
|
||||
write(
|
||||
&mixed,
|
||||
"maven-app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>m</artifactId><version>1</version></project>",
|
||||
);
|
||||
let mixed_model = crate::load(&mixed, &tmp.path().join("cache2"), None);
|
||||
let all = plan(&mixed, &mixed_model, BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(all.steps.len(), 2);
|
||||
assert_eq!(all.steps[0].cwd, mixed.join("gradle-app"));
|
||||
assert_eq!(all.steps[1].cwd, mixed.join("maven-app"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_directory_target_builds_that_package_without_stepping_to_parent() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("go-app");
|
||||
write(&root, "go.mod", "module example.com/app\n\ngo 1.22\n");
|
||||
write(&root, "cmd/server/main.go", "package main\nfunc main() {}\n");
|
||||
|
||||
let pkg = plan(
|
||||
&root,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&root.join("cmd/server")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(pkg.system, BuildSystem::Go);
|
||||
assert_eq!(pkg.steps[0].cwd, root);
|
||||
assert_eq!(pkg.steps[0].args, ["build", "./cmd/server/..."]);
|
||||
|
||||
let whole =
|
||||
plan(&root, &BuildModel::default(), BuildKind::Build, Some(&root), None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(whole.steps[0].cwd, root);
|
||||
assert_eq!(whole.steps[0].args, ["build", "./..."]);
|
||||
}
|
||||
}
|
||||
@@ -94,12 +94,12 @@ pub(super) fn build_javac_step(
|
||||
Ok(step)
|
||||
}
|
||||
|
||||
/// The resolved dependency classpath for one module and scope, tied to the same
|
||||
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
|
||||
/// The last resolved dependency classpath for one module and scope. A fingerprint
|
||||
/// permits reuse during a build; NoBuild also uses records without one.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct CachedClasspath {
|
||||
version: u32,
|
||||
fingerprint: LaunchFingerprint,
|
||||
fingerprint: Option<LaunchFingerprint>,
|
||||
classpath: String,
|
||||
}
|
||||
|
||||
@@ -162,9 +162,6 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
|
||||
.iter()
|
||||
.find(|p| root.join(&p.dir) == module)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
if project.packaging == "pom" {
|
||||
return Err(IdeError::not_found("the launch module is a Maven aggregator without sources"));
|
||||
}
|
||||
let top = maven_reactor(m, &project.dir)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
@@ -217,6 +214,30 @@ pub fn module_classpath(
|
||||
module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, cancel)
|
||||
}
|
||||
|
||||
/// Uses the last launch classpath, or probes dependencies without invoking the compile lifecycle.
|
||||
pub fn module_classpath_without_build(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
cache: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let target = module_target(root, model, module, test)?;
|
||||
if let Some(path) = classpath_cache_path(root, cache, module, test)
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(cached.classpath);
|
||||
}
|
||||
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
|
||||
}
|
||||
|
||||
/// [`module_classpath`] of `modules[0]`. The other modules, launched together with it
|
||||
/// (#3971), share its Maven probe when they have no cached classpath, which leaves
|
||||
/// theirs cached for their own launches.
|
||||
@@ -245,7 +266,7 @@ pub fn module_classpaths(
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& cached.fingerprint == *fingerprint
|
||||
&& cached.fingerprint.as_ref() == Some(fingerprint)
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
@@ -269,7 +290,7 @@ pub fn module_classpaths(
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
for (Probe(_, fingerprint, cache_path), classpath) in probes.into_iter().zip(&classpaths) {
|
||||
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
|
||||
if let Some(path) = cache_path {
|
||||
let cached =
|
||||
CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
|
||||
if let Err(error) = cache_classpath(&path, &cached) {
|
||||
@@ -361,7 +382,9 @@ fn classpaths(
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let build_classpath =
|
||||
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
|
||||
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();
|
||||
let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| {
|
||||
@@ -673,6 +696,81 @@ mod tests {
|
||||
assert!(single_file_target(root, &model, &root.join("other/Main.java")).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn pom_launch_resolves_dependencies_without_compiling_for_no_build() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
fixture(&root);
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
|
||||
);
|
||||
let script = root.join("mvnw");
|
||||
write(
|
||||
&root,
|
||||
"mvnw",
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target\nprintf '/repo/runtime.jar' > app/target/ide-compile-cp.txt\n",
|
||||
);
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(&root, &root.join("cache"), None);
|
||||
let cancel = CancellationToken::new();
|
||||
let cp = module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
|
||||
.unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert!(paths.contains(&root.join("lib/target/classes")), "{cp}");
|
||||
assert!(paths.contains(&root.join("shared/target/classes")), "{cp}");
|
||||
assert!(paths.contains(&PathBuf::from("/repo/runtime.jar")), "{cp}");
|
||||
assert!(!paths.contains(&root.join("app/target/classes")), "{cp}");
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(!args.lines().any(|a| matches!(a, "compile" | "package" | "test-compile")), "{args}");
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=runtime"), "{args}");
|
||||
|
||||
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "compile"), "{args}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn no_build_keeps_the_last_launch_classpath_after_a_pom_change() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
fixture(&root);
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"mvnw",
|
||||
"#!/bin/sh\necho called >> calls.txt\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target repo\ntouch repo/runtime.jar repo/runtime-v2.jar\nif grep -q changed app/pom.xml; then printf \"$PWD/repo/runtime-v2.jar\" > app/target/ide-compile-cp.txt; else printf \"$PWD/repo/runtime.jar\" > app/target/ide-compile-cp.txt; fi\n",
|
||||
);
|
||||
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(&root, &root.join("cache"), None);
|
||||
let cancel = CancellationToken::new();
|
||||
let previous =
|
||||
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
|
||||
assert!(previous.contains("repo/runtime.jar"), "{previous}");
|
||||
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(&root, "app/pom.xml", &pom.replace("</project>", "<description>changed</description></project>"));
|
||||
let launch =
|
||||
module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
|
||||
.unwrap();
|
||||
assert!(launch.contains("repo/runtime.jar"), "{launch}");
|
||||
assert!(!launch.contains("runtime-v2.jar"), "{launch}");
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap().lines().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,451 @@
|
||||
//! Problems › TypeScript project errors: the project's own `tsc --watch` on each root
|
||||
//! `tsconfig.json`, its output parsed like Build's tsc step, one compilation at a time.
|
||||
//!
|
||||
//! A background check never writes into the project. A plain project runs `tsc --noEmit -p`
|
||||
//! with its `.tsbuildinfo` (written by `composite` / `incremental` even without emit) moved to a
|
||||
//! scratch folder. `tsc -b` cannot check without emitting (`--noEmit` fails with TS6310 on
|
||||
//! composite references), and plain `tsc -p` on a project with references needs their built
|
||||
//! `.d.ts` (TS6305). So a solution runs `tsc -b` on scratch copies of its configurations: each
|
||||
//! `extends` the real one and only sends the outputs and `.tsbuildinfo` to the scratch folder,
|
||||
//! keeping every option, file list and source position of the project.
|
||||
|
||||
use super::parse::{Format, OutputParser, RawMessage};
|
||||
use super::{BuildMessage, Lines, PathMap, resolve};
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
// ponytail: one `tsc` per root; past this the shallowest roots win. Raise it, or watch
|
||||
// on demand, if monorepos without a solution tsconfig need more.
|
||||
const MAX_ROOTS: usize = 8;
|
||||
|
||||
/// The configurations among `found` (the `tsconfig.json` files of the project) that no other
|
||||
/// one references: the ones a watcher runs on. Referenced projects are checked by their solution.
|
||||
pub fn tsc_watch_roots(found: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
let referenced: BTreeSet<PathBuf> = found.iter().flat_map(|c| references(c)).collect();
|
||||
let mut roots: Vec<PathBuf> = found.into_iter().filter(|c| !referenced.contains(c)).collect();
|
||||
roots.sort_by_key(|c| (c.components().count(), c.clone()));
|
||||
roots.truncate(MAX_ROOTS);
|
||||
roots
|
||||
}
|
||||
|
||||
fn read_json(path: &Path) -> Option<Value> {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
serde_json::from_str(&ide_core::jsonc::strip(&text)).ok()
|
||||
}
|
||||
|
||||
/// The configurations `config` lists in `references` (a folder means its `tsconfig.json`).
|
||||
fn references(config: &Path) -> Vec<PathBuf> {
|
||||
let Some(json) = read_json(config) else { return Vec::new() };
|
||||
let dir = config.parent().unwrap_or(Path::new(""));
|
||||
let refs = json.get("references").and_then(|r| r.as_array()).into_iter().flatten();
|
||||
refs.filter_map(|r| r.get("path")?.as_str())
|
||||
.map(|p| {
|
||||
let p = super::normalize(&dir.join(p));
|
||||
if p.extension().is_some_and(|e| e == "json") { p } else { p.join("tsconfig.json") }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A configuration and the ones it `extends`, most derived first, each with its folder (the
|
||||
/// base of its relative paths). A package base (`@tsconfig/node20/tsconfig.json`) is looked up
|
||||
/// in `node_modules` above the configuration.
|
||||
fn chain(config: &Path) -> Vec<(PathBuf, Value)> {
|
||||
let mut out = Vec::new();
|
||||
let mut next = vec![config.to_path_buf()];
|
||||
// A cycle or a deep chain ends here.
|
||||
while let Some(path) = next.pop().filter(|_| out.len() < 16) {
|
||||
let Some(json) = read_json(&path) else { continue };
|
||||
let dir = path.parent().unwrap_or(Path::new("")).to_path_buf();
|
||||
let bases: Vec<String> = match json.get("extends") {
|
||||
Some(Value::String(s)) => vec![s.clone()],
|
||||
Some(Value::Array(a)) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// Later bases override earlier ones: visit them first.
|
||||
next.extend(bases.iter().filter_map(|b| resolve_base(&dir, b)));
|
||||
out.push((dir, json));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn resolve_base(dir: &Path, base: &str) -> Option<PathBuf> {
|
||||
let with_json = |p: PathBuf| {
|
||||
if p.is_dir() {
|
||||
p.join("tsconfig.json")
|
||||
} else if p.extension().is_some_and(|e| e == "json") {
|
||||
p
|
||||
} else {
|
||||
let mut s = p.into_os_string();
|
||||
s.push(".json");
|
||||
PathBuf::from(s)
|
||||
}
|
||||
};
|
||||
if base.starts_with('.') || Path::new(base).is_absolute() {
|
||||
return Some(with_json(super::normalize(&dir.join(base))));
|
||||
}
|
||||
dir.ancestors().map(|a| with_json(a.join("node_modules").join(base))).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// The first value of `key` (a top-level key, or `compilerOptions.<key>`) along `chain`, with the
|
||||
/// folder it is relative to.
|
||||
fn lookup<'a>(chain: &'a [(PathBuf, Value)], key: &str) -> Option<(&'a Path, &'a Value)> {
|
||||
chain.iter().find_map(|(dir, json)| {
|
||||
let value = match key.strip_prefix("compilerOptions.") {
|
||||
Some(option) => json.get("compilerOptions")?.get(option)?,
|
||||
None => json.get(key)?,
|
||||
};
|
||||
Some((dir.as_path(), value))
|
||||
})
|
||||
}
|
||||
|
||||
/// The scratch copy of `config` for `tsc -b`: the real configuration with its outputs and
|
||||
/// `.tsbuildinfo` in `scratch` (file `<n>`), referencing the scratch copies `refs`. Settings that
|
||||
/// default relative to the configuration's own folder are spelled out, since the copy lives
|
||||
/// elsewhere: the files (`**/*`), their exclusions (`node_modules`, the output folder) and the
|
||||
/// `rootDir` of a composite project.
|
||||
fn scratch_config(config: &Path, scratch: &Path, n: usize, refs: &[PathBuf]) -> Value {
|
||||
let chain = chain(config);
|
||||
let dir = config.parent().unwrap_or(Path::new(""));
|
||||
let out = scratch.join(n.to_string());
|
||||
let mut options = json!({ "outDir": out, "tsBuildInfoFile": scratch.join(format!("{n}.tsbuildinfo")) });
|
||||
if lookup(&chain, "compilerOptions.declarationDir").is_some() {
|
||||
options["declarationDir"] = json!(out);
|
||||
}
|
||||
if lookup(&chain, "compilerOptions.outFile").is_some() {
|
||||
options["outFile"] = json!(out.join("out.js"));
|
||||
}
|
||||
if lookup(&chain, "compilerOptions.composite").is_some_and(|(_, v)| v == &json!(true))
|
||||
&& lookup(&chain, "compilerOptions.rootDir").is_none()
|
||||
{
|
||||
options["rootDir"] = json!(dir);
|
||||
}
|
||||
let mut copy = json!({
|
||||
"extends": config,
|
||||
"compilerOptions": options,
|
||||
"references": refs.iter().map(|r| json!({ "path": r })).collect::<Vec<_>>(),
|
||||
});
|
||||
if lookup(&chain, "include").is_none() && lookup(&chain, "files").is_none() {
|
||||
copy["include"] = json!([dir.join("**/*")]);
|
||||
}
|
||||
if lookup(&chain, "exclude").is_none() {
|
||||
let mut exclude = vec![dir.join("node_modules")];
|
||||
if let Some((base, Value::String(out_dir))) = lookup(&chain, "compilerOptions.outDir") {
|
||||
exclude.push(super::normalize(&base.join(out_dir)));
|
||||
}
|
||||
copy["exclude"] = json!(exclude);
|
||||
}
|
||||
copy
|
||||
}
|
||||
|
||||
/// The `tsc` arguments that watch `config` without writing into the project, writing the
|
||||
/// scratch configurations a solution needs into `scratch`.
|
||||
fn watch_args(config: &Path, scratch: &Path) -> std::io::Result<Vec<String>> {
|
||||
let path = |p: &Path| p.to_string_lossy().into_owned();
|
||||
let mut args: Vec<String> = if references(config).is_empty() {
|
||||
let name = config.file_name().map_or_else(|| "tsconfig.json".into(), |n| n.to_string_lossy().into_owned());
|
||||
let info = path(&scratch.join("tsconfig.tsbuildinfo"));
|
||||
["--noEmit", "-p", &name, "--incremental", "--tsBuildInfoFile", &info].map(String::from).to_vec()
|
||||
} else {
|
||||
// Every configuration the solution reaches gets a number: the solution 0, then in order.
|
||||
let mut numbers: BTreeMap<PathBuf, usize> = BTreeMap::from([(config.to_path_buf(), 0)]);
|
||||
let mut queue = vec![config.to_path_buf()];
|
||||
let mut i = 0;
|
||||
while i < queue.len() {
|
||||
let current = queue[i].clone();
|
||||
let refs: Vec<PathBuf> = references(¤t)
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let next = numbers.len();
|
||||
let n = *numbers.entry(r.clone()).or_insert_with(|| {
|
||||
queue.push(r);
|
||||
next
|
||||
});
|
||||
scratch.join(format!("{n}.json"))
|
||||
})
|
||||
.collect();
|
||||
let copy = scratch_config(¤t, scratch, numbers[¤t], &refs);
|
||||
std::fs::write(scratch.join(format!("{}.json", numbers[¤t])), copy.to_string())?;
|
||||
i += 1;
|
||||
}
|
||||
vec!["-b".into(), path(&scratch.join("0.json"))]
|
||||
};
|
||||
args.extend(["--watch", "--pretty", "false", "--preserveWatchOutput"].map(String::from));
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// The project's own `tsc` (`node_modules/.bin` from the configuration's folder up to `root`).
|
||||
fn local_tsc(root: &Path, dir: &Path) -> Option<PathBuf> {
|
||||
dir.ancestors()
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find_map(|d| ide_core::tool_path::find_command("tsc", d.join("node_modules/.bin").as_os_str(), dir))
|
||||
}
|
||||
|
||||
/// The messages of one compilation at a time: tsc ends each with
|
||||
/// `… - Found 2 errors. Watching for file changes.` `tsc -b` reports the errors of every
|
||||
/// project of the solution that has some, rebuilt this time or not ("out of date because it had
|
||||
/// errors"), so each compilation's list replaces the last.
|
||||
#[derive(Default)]
|
||||
struct Compilations {
|
||||
parser: Option<OutputParser>,
|
||||
raws: Vec<RawMessage>,
|
||||
}
|
||||
|
||||
impl Compilations {
|
||||
fn feed(&mut self, line: &str) -> Option<Vec<RawMessage>> {
|
||||
let parser = self.parser.get_or_insert_with(|| OutputParser::new(Format::Tsc));
|
||||
if line.contains("Watching for file changes.") {
|
||||
self.raws.extend(parser.finish());
|
||||
return Some(std::mem::take(&mut self.raws));
|
||||
}
|
||||
self.raws.extend(parser.feed(line).messages);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A scratch folder of this process for `config`, removed when dropped.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
impl Scratch {
|
||||
fn new(config: &Path) -> std::io::Result<Self> {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hash = std::collections::hash_map::DefaultHasher::new();
|
||||
config.hash(&mut hash);
|
||||
let dir = std::env::temp_dir().join("openidea-tsc-watch").join(format!(
|
||||
"{}-{:016x}",
|
||||
std::process::id(),
|
||||
hash.finish()
|
||||
));
|
||||
// Fresh: a `.tsbuildinfo` left by an earlier run would make tsc skip unchanged projects.
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(Scratch(dir))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the project's `tsc --watch` on `config` until `cancel` fires or tsc exits, handing the
|
||||
/// messages of every finished compilation (all of them, an empty list when it passes) to
|
||||
/// `on_compilation`. Not found when the project has no TypeScript of its own.
|
||||
pub fn tsc_watch(
|
||||
root: &Path,
|
||||
config: &Path,
|
||||
cancel: &CancellationToken,
|
||||
mut on_compilation: impl FnMut(Vec<BuildMessage>),
|
||||
) -> IdeResult<()> {
|
||||
let dir = config.parent().ok_or_else(|| IdeError::invalid("no tsconfig folder"))?;
|
||||
let tsc = local_tsc(root, dir).ok_or_else(|| IdeError::not_found("no local typescript"))?;
|
||||
let scratch = Scratch::new(config)?;
|
||||
let args = watch_args(config, &scratch.0)?;
|
||||
let paths = PathMap::new(root);
|
||||
let mut compilations = Compilations::default();
|
||||
let program = tsc.to_string_lossy();
|
||||
process::run_bounded(&program, &args, dir, &BTreeMap::new(), cancel, |_, line| {
|
||||
if let Some(raws) = compilations.feed(line) {
|
||||
// Fresh file texts each time: the files changed since the last compilation.
|
||||
let mut lines = Lines::default();
|
||||
on_compilation(raws.into_iter().map(|r| resolve(r, dir, &paths, &mut lines)).collect());
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(dir: &Path, rel: &str, text: &str) {
|
||||
let p = dir.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roots_are_the_configurations_no_other_one_references() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
// A solution with references (one by folder, one by file), plus an unrelated package.
|
||||
write(
|
||||
root,
|
||||
"tsconfig.json",
|
||||
r#"{ "files": [], // solution
|
||||
"references": [{ "path": "./packages/a" }, { "path": "packages/b/tsconfig.json" },] }"#,
|
||||
);
|
||||
write(root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(root, "packages/b/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(root, "tools/cli/tsconfig.json", "{}");
|
||||
let found = ["tools/cli", "packages/b", "", "packages/a"].map(|d| root.join(d).join("tsconfig.json"));
|
||||
assert_eq!(tsc_watch_roots(found.to_vec()), [root.join("tsconfig.json"), root.join("tools/cli/tsconfig.json")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_solution_is_checked_through_scratch_copies_of_its_configurations() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
|
||||
std::fs::create_dir_all(&scratch).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"tsconfig.json",
|
||||
r#"{"files": [], "references": [{"path": "./packages/a"}, {"path": "./packages/b"}]}"#,
|
||||
);
|
||||
// a: composite, every setting by default.
|
||||
write(&root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
// b: references a, settles its files, outputs and root in a shared base.
|
||||
write(
|
||||
&root,
|
||||
"packages/b/tsconfig.json",
|
||||
r#"{"extends": "../../tsconfig.base", "references": [{"path": "../a"}], "compilerOptions": {"outFile": "b.js"}}"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"tsconfig.base.json",
|
||||
r#"{"compilerOptions": {"composite": true, "rootDir": ".", "outDir": "dist", "declarationDir": "types"},
|
||||
"include": ["packages/*/src"]}"#,
|
||||
);
|
||||
let args = watch_args(&root.join("tsconfig.json"), &scratch).unwrap();
|
||||
let s = |p: &str| scratch.join(p).to_string_lossy().into_owned();
|
||||
assert_eq!(args, ["-b", &s("0.json"), "--watch", "--pretty", "false", "--preserveWatchOutput"]);
|
||||
let copy = |n: usize| read_json(&scratch.join(format!("{n}.json"))).unwrap();
|
||||
let path = |p: &Path| json!(p);
|
||||
assert_eq!(
|
||||
copy(0),
|
||||
json!({
|
||||
"extends": path(&root.join("tsconfig.json")),
|
||||
"compilerOptions": {"outDir": path(&scratch.join("0")), "tsBuildInfoFile": s("0.tsbuildinfo")},
|
||||
"references": [{"path": s("1.json")}, {"path": s("2.json")}],
|
||||
"exclude": [path(&root.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
// Chained joins: the configurations name native paths, `packages/a` would mix separators on Windows.
|
||||
let a = root.join("packages").join("a");
|
||||
assert_eq!(
|
||||
copy(1),
|
||||
json!({
|
||||
"extends": path(&a.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("1")), "tsBuildInfoFile": s("1.tsbuildinfo"), "rootDir": path(&a),
|
||||
},
|
||||
"references": [],
|
||||
"include": [path(&a.join("**/*"))],
|
||||
"exclude": [path(&a.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let b = root.join("packages").join("b");
|
||||
assert_eq!(
|
||||
copy(2),
|
||||
json!({
|
||||
"extends": path(&b.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2").join("out.js")),
|
||||
},
|
||||
"references": [{"path": s("1.json")}],
|
||||
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_composite_package_base_gets_its_root_folder() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
|
||||
write(&root, "node_modules/@acme/tsconfig/base.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(&root, "app/tsconfig.json", r#"{"extends": "@acme/tsconfig/base", "include": ["src"]}"#);
|
||||
let copy = scratch_config(&root.join("app/tsconfig.json"), &scratch, 3, &[]);
|
||||
assert_eq!(copy["compilerOptions"]["rootDir"], json!(root.join("app")));
|
||||
assert_eq!(copy.get("include"), None, "the files come from the real configuration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_compilation_reports_its_own_messages() {
|
||||
// `tsc --noEmit --watch --pretty false --preserveWatchOutput`, as printed.
|
||||
let output = "\
|
||||
2:14:08 PM - Starting compilation in watch mode...
|
||||
|
||||
2:14:09 PM - Found 0 errors. Watching for file changes.
|
||||
2:14:12 PM - File change detected. Starting incremental compilation...
|
||||
|
||||
src/b.ts(1,37): error TS2322: Type 'string' is not assignable to type 'number'.
|
||||
src/c.ts(2,1): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
|
||||
Type 'string' is not assignable to type 'number'.
|
||||
|
||||
2:14:12 PM - Found 2 errors. Watching for file changes.
|
||||
2:14:15 PM - File change detected. Starting incremental compilation...
|
||||
|
||||
2:14:15 PM - Found 0 errors. Watching for file changes.";
|
||||
let mut compilations = Compilations::default();
|
||||
let found: Vec<Vec<(String, Option<String>)>> = output
|
||||
.lines()
|
||||
.filter_map(|l| compilations.feed(l))
|
||||
.map(|raws| raws.into_iter().map(|r| (r.path.unwrap_or_default(), r.code)).collect())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
vec![],
|
||||
vec![("src/b.ts".into(), Some("TS2322".into())), ("src/c.ts".into(), Some("TS2345".into()))],
|
||||
vec![]
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_projects_tsc_reports_until_cancelled() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(root, "app/tsconfig.json", "{}");
|
||||
write(root, "app/src/b.ts", "export const b: number = a;\n");
|
||||
// A watcher that prints one compilation and keeps running, like `tsc --watch`.
|
||||
write(
|
||||
root,
|
||||
"node_modules/.bin/tsc",
|
||||
"#!/bin/sh\necho \"$@\" > args.txt\n\
|
||||
echo 'src/b.ts(1,26): error TS2322: Type string is not assignable to type number.'\n\
|
||||
echo '1:00:00 PM - Found 1 error. Watching for file changes.'\nexec sleep 30\n",
|
||||
);
|
||||
let bin = root.join("node_modules/.bin/tsc");
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let mut compilations = Vec::new();
|
||||
let started = std::time::Instant::now();
|
||||
let result = tsc_watch(root, &root.join("app/tsconfig.json"), &cancel, |messages| {
|
||||
compilations.push(messages);
|
||||
cancel.cancel();
|
||||
});
|
||||
assert_eq!(result.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(started.elapsed().as_secs() < 10, "cancelling stops the watcher");
|
||||
let [messages] = &compilations[..] else { panic!("{compilations:?}") };
|
||||
let paths: Vec<_> = messages.iter().map(|m| (m.path.clone().map(PathBuf::from), m.range)).collect();
|
||||
let at = |l, c| ide_core::Pos::new(l, c);
|
||||
assert_eq!(paths, [(Some(root.join("app/src/b.ts")), Some(ide_core::Range::new(at(0, 25), at(0, 26))))]);
|
||||
let args = std::fs::read_to_string(root.join("app/args.txt")).unwrap();
|
||||
let (check, rest) = args.trim().split_once(" --tsBuildInfoFile ").unwrap();
|
||||
assert_eq!(check, "--noEmit -p tsconfig.json --incremental");
|
||||
let (info, watch) = rest.split_once(' ').unwrap();
|
||||
assert_eq!(watch, "--watch --pretty false --preserveWatchOutput");
|
||||
// The `.tsbuildinfo` goes to a scratch folder outside the project, gone with the watcher.
|
||||
let scratch = Path::new(info).parent().unwrap();
|
||||
assert!(scratch.starts_with(std::env::temp_dir()) && !scratch.starts_with(root), "{info}");
|
||||
assert!(!scratch.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_local_typescript_runs_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write(tmp.path(), "tsconfig.json", "{}");
|
||||
let err = tsc_watch(tmp.path(), &tmp.path().join("tsconfig.json"), &CancellationToken::new(), |_| {
|
||||
panic!("no compilation without typescript")
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
|
||||
}
|
||||
}
|
||||
@@ -364,9 +364,9 @@ pub fn parse_reported_projects(output: &str) -> Vec<ReportedProject> {
|
||||
output.lines().filter_map(|l| serde_json::from_str(l.trim_end().strip_prefix(MODEL_LINE)?).ok()).collect()
|
||||
}
|
||||
|
||||
/// Source roots of the reported source sets: `(absolute folder, is test, is resources)`.
|
||||
pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, ReportedRoot)> {
|
||||
let mut out: Vec<(PathBuf, ReportedRoot)> = Vec::new();
|
||||
/// Source roots of the reported source sets: `(absolute folder, role, absolute folder of its project)`.
|
||||
pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, ReportedRoot, PathBuf)> {
|
||||
let mut out: Vec<(PathBuf, ReportedRoot, PathBuf)> = Vec::new();
|
||||
for p in reported {
|
||||
for set in &p.source_sets {
|
||||
let (src, res) = if set.test {
|
||||
@@ -377,14 +377,14 @@ pub fn reported_source_roots(reported: &[ReportedProject]) -> Vec<(PathBuf, Repo
|
||||
for (dir, kind) in set.src.iter().map(|d| (d, src)).chain(set.res.iter().map(|d| (d, res))) {
|
||||
let dir = PathBuf::from(dir);
|
||||
// A folder shared by `main` and another set is `main`'s, as in IDEA.
|
||||
if !out.iter().any(|(d, _)| *d == dir) {
|
||||
out.push((dir, kind));
|
||||
if !out.iter().any(|(d, _, _)| *d == dir) {
|
||||
out.push((dir, kind, PathBuf::from(&p.dir)));
|
||||
}
|
||||
}
|
||||
}
|
||||
// IDEA excludes the build folder of every module.
|
||||
if let Some(b) = &p.build_dir {
|
||||
out.push((PathBuf::from(b), ReportedRoot::Excluded));
|
||||
out.push((PathBuf::from(b), ReportedRoot::Excluded, PathBuf::from(&p.dir)));
|
||||
}
|
||||
}
|
||||
out
|
||||
|
||||
@@ -0,0 +1,482 @@
|
||||
//! What the incremental build needs from a class file (JVMS §4): its name, supertypes, the
|
||||
//! classes its constant pool refers to, and fingerprints of its API and of its compile-time
|
||||
//! constants. Bounds-checked: a malformed file is `None`, never a panic.
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// A class file, as the dependency graph and the API diff see it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ClassFile {
|
||||
/// Internal name (`com/acme/Order$Line`).
|
||||
pub name: String,
|
||||
pub super_name: Option<String>,
|
||||
pub interfaces: Vec<String>,
|
||||
/// Classes named in the constant pool: references, descriptors, signatures, annotation types.
|
||||
pub refs: BTreeSet<String>,
|
||||
/// What other classes compile against: non-private, non-synthetic members and their
|
||||
/// signatures, supertypes, nested classes, permitted subclasses, record components.
|
||||
pub api: u64,
|
||||
/// The compile-time constants (`static final` fields with a `ConstantValue`), which javac
|
||||
/// copies into the classes that use them: a change can't be traced through references.
|
||||
pub constants: u64,
|
||||
}
|
||||
|
||||
const ACC_PRIVATE: u16 = 0x0002;
|
||||
const ACC_SYNTHETIC: u16 = 0x1000;
|
||||
|
||||
struct Bytes<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> Bytes<'a> {
|
||||
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
|
||||
let end = self.pos.checked_add(n)?;
|
||||
let slice = self.data.get(self.pos..end)?;
|
||||
self.pos = end;
|
||||
Some(slice)
|
||||
}
|
||||
fn u1(&mut self) -> Option<u8> {
|
||||
Some(self.take(1)?[0])
|
||||
}
|
||||
fn u2(&mut self) -> Option<u16> {
|
||||
let b = self.take(2)?;
|
||||
Some(u16::from_be_bytes([b[0], b[1]]))
|
||||
}
|
||||
fn u4(&mut self) -> Option<u32> {
|
||||
let b = self.take(4)?;
|
||||
Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Entry {
|
||||
Empty,
|
||||
Utf8(String),
|
||||
Class(u16),
|
||||
String(u16),
|
||||
/// Integer, float, long, double: the raw bytes.
|
||||
Number(Vec<u8>),
|
||||
NameAndType(u16),
|
||||
MethodType(u16),
|
||||
Other,
|
||||
}
|
||||
|
||||
struct Pool(Vec<Entry>);
|
||||
|
||||
impl Pool {
|
||||
fn utf8(&self, index: u16) -> Option<&str> {
|
||||
match self.0.get(index as usize)? {
|
||||
Entry::Utf8(s) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn class(&self, index: u16) -> Option<&str> {
|
||||
match self.0.get(index as usize)? {
|
||||
Entry::Class(name) => self.utf8(*name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// A `ConstantValue`'s value, as bytes.
|
||||
fn constant(&self, index: u16) -> Option<Vec<u8>> {
|
||||
match self.0.get(index as usize)? {
|
||||
Entry::Number(bytes) => Some(bytes.clone()),
|
||||
Entry::String(utf8) => Some(self.utf8(*utf8)?.as_bytes().to_vec()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// FNV-1a: stable across Rust versions, so recorded fingerprints stay comparable.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Fnv(u64);
|
||||
|
||||
impl Fnv {
|
||||
fn new() -> Self {
|
||||
Fnv(0xcbf2_9ce4_8422_2325)
|
||||
}
|
||||
fn bytes(&mut self, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
|
||||
}
|
||||
// A separator, so `ab`+`c` and `a`+`bc` differ.
|
||||
self.0 = (self.0 ^ 0xff).wrapping_mul(0x100_0000_01b3);
|
||||
}
|
||||
fn str(&mut self, s: &str) {
|
||||
self.bytes(s.as_bytes());
|
||||
}
|
||||
fn u16(&mut self, v: u16) {
|
||||
self.bytes(&v.to_be_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the class names a descriptor or signature mentions (`Lcom/acme/Order<Lx/Y;>;`).
|
||||
fn descriptor_refs(text: &str, out: &mut BTreeSet<String>) {
|
||||
let bytes = text.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'L'
|
||||
&& (i == 0
|
||||
|| matches!(
|
||||
bytes[i - 1],
|
||||
b'(' | b')'
|
||||
| b'['
|
||||
| b';'
|
||||
| b'<'
|
||||
| b'>'
|
||||
| b'+'
|
||||
| b'-'
|
||||
| b':'
|
||||
| b'*'
|
||||
| b'I'
|
||||
| b'J'
|
||||
| b'Z'
|
||||
| b'B'
|
||||
| b'C'
|
||||
| b'S'
|
||||
| b'F'
|
||||
| b'D'
|
||||
| b'V'
|
||||
| b'^'
|
||||
))
|
||||
{
|
||||
let start = i + 1;
|
||||
let mut end = start;
|
||||
while end < bytes.len() && !matches!(bytes[end], b';' | b'<' | b'.') {
|
||||
end += 1;
|
||||
}
|
||||
if end < bytes.len() && end > start {
|
||||
let name = &text[start..end];
|
||||
if name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'$' | b'_') || b >= 0x80) {
|
||||
out.insert(name.to_owned());
|
||||
}
|
||||
}
|
||||
i = end;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn class_ref(name: &str, out: &mut BTreeSet<String>) {
|
||||
if name.starts_with('[') {
|
||||
descriptor_refs(name, out);
|
||||
} else {
|
||||
out.insert(name.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
struct Member {
|
||||
access: u16,
|
||||
name: String,
|
||||
descriptor: String,
|
||||
/// Fingerprint of the attributes that are part of the API.
|
||||
extra: u64,
|
||||
constant: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
fn attributes(r: &mut Bytes, pool: &Pool, mut on: impl FnMut(&str, &[u8])) -> Option<()> {
|
||||
let count = r.u2()?;
|
||||
for _ in 0..count {
|
||||
let name = pool.utf8(r.u2()?)?.to_owned();
|
||||
let len = r.u4()? as usize;
|
||||
let body = r.take(len)?;
|
||||
on(&name, body);
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Vec<Member>> {
|
||||
let count = r.u2()?;
|
||||
let mut out = Vec::with_capacity(count as usize);
|
||||
for _ in 0..count {
|
||||
let access = r.u2()?;
|
||||
let name = pool.utf8(r.u2()?)?.to_owned();
|
||||
let descriptor = pool.utf8(r.u2()?)?.to_owned();
|
||||
descriptor_refs(&descriptor, refs);
|
||||
let mut extra = Fnv::new();
|
||||
let mut constant = None;
|
||||
attributes(r, pool, |attr, body| {
|
||||
let mut b = Bytes { data: body, pos: 0 };
|
||||
match attr {
|
||||
"Signature" => {
|
||||
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
|
||||
descriptor_refs(sig, refs);
|
||||
extra.str("S");
|
||||
extra.str(sig);
|
||||
}
|
||||
}
|
||||
"ConstantValue" => constant = b.u2().and_then(|i| pool.constant(i)),
|
||||
"Exceptions" => {
|
||||
let mut names: Vec<&str> = Vec::new();
|
||||
if let Some(n) = b.u2() {
|
||||
for _ in 0..n {
|
||||
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
|
||||
names.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
names.sort_unstable();
|
||||
extra.str("E");
|
||||
for n in names {
|
||||
extra.str(n);
|
||||
}
|
||||
}
|
||||
// An annotation element's default value is compiled into its uses.
|
||||
"AnnotationDefault" => {
|
||||
extra.str("D");
|
||||
element_value(&mut b, pool, refs, &mut extra);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
})?;
|
||||
out.push(Member { access, name, descriptor, extra: extra.0, constant });
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
r.u2()?;
|
||||
r.u2()?;
|
||||
let count = r.u2()?;
|
||||
let mut entries = vec![Entry::Empty];
|
||||
let mut i = 1;
|
||||
while i < count {
|
||||
let tag = r.u1()?;
|
||||
let entry = match tag {
|
||||
1 => {
|
||||
let len = r.u2()? as usize;
|
||||
Entry::Utf8(String::from_utf8_lossy(r.take(len)?).into_owned())
|
||||
}
|
||||
3 | 4 => Entry::Number(r.take(4)?.to_vec()),
|
||||
5 | 6 => Entry::Number(r.take(8)?.to_vec()),
|
||||
7 => Entry::Class(r.u2()?),
|
||||
8 => Entry::String(r.u2()?),
|
||||
9..=11 => {
|
||||
r.take(4)?;
|
||||
Entry::Other
|
||||
}
|
||||
12 => {
|
||||
r.u2()?;
|
||||
Entry::NameAndType(r.u2()?)
|
||||
}
|
||||
15 => {
|
||||
r.take(3)?;
|
||||
Entry::Other
|
||||
}
|
||||
16 => Entry::MethodType(r.u2()?),
|
||||
17 | 18 => {
|
||||
r.take(4)?;
|
||||
Entry::Other
|
||||
}
|
||||
19 | 20 => {
|
||||
r.take(2)?;
|
||||
Entry::Other
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let wide = matches!(tag, 5 | 6);
|
||||
entries.push(entry);
|
||||
i += 1;
|
||||
if wide {
|
||||
entries.push(Entry::Empty);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let pool = Pool(entries);
|
||||
let mut refs = BTreeSet::new();
|
||||
for entry in &pool.0 {
|
||||
match entry {
|
||||
Entry::Class(name) => class_ref(pool.utf8(*name)?, &mut refs),
|
||||
Entry::NameAndType(descriptor) | Entry::MethodType(descriptor) => {
|
||||
descriptor_refs(pool.utf8(*descriptor)?, &mut refs)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let access = r.u2()?;
|
||||
let name = pool.class(r.u2()?)?.to_owned();
|
||||
let super_index = r.u2()?;
|
||||
let super_name = if super_index == 0 { None } else { Some(pool.class(super_index)?.to_owned()) };
|
||||
let mut interfaces = Vec::new();
|
||||
for _ in 0..r.u2()? {
|
||||
interfaces.push(pool.class(r.u2()?)?.to_owned());
|
||||
}
|
||||
let fields = members(&mut r, &pool, &mut refs)?;
|
||||
let methods = members(&mut r, &pool, &mut refs)?;
|
||||
|
||||
let mut api = Fnv::new();
|
||||
// ACC_SUPER and ACC_SYNTHETIC say nothing about what compiles against the class.
|
||||
api.u16(access & !(0x0020 | ACC_SYNTHETIC));
|
||||
api.str(&name);
|
||||
api.str(super_name.as_deref().unwrap_or(""));
|
||||
let mut sorted = interfaces.clone();
|
||||
sorted.sort();
|
||||
for i in &sorted {
|
||||
api.str(i);
|
||||
}
|
||||
let mut class_attrs: Vec<(String, u64)> = Vec::new();
|
||||
attributes(&mut r, &pool, |attr, body| {
|
||||
let mut b = Bytes { data: body, pos: 0 };
|
||||
let mut h = Fnv::new();
|
||||
match attr {
|
||||
"Signature" => {
|
||||
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
|
||||
descriptor_refs(sig, &mut refs);
|
||||
h.str(sig);
|
||||
}
|
||||
}
|
||||
"PermittedSubclasses" => {
|
||||
let mut names = Vec::new();
|
||||
for _ in 0..b.u2().unwrap_or(0) {
|
||||
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
|
||||
names.push(c.to_owned());
|
||||
}
|
||||
}
|
||||
names.sort();
|
||||
names.iter().for_each(|n| h.str(n));
|
||||
}
|
||||
"Record" => {
|
||||
for _ in 0..b.u2().unwrap_or(0) {
|
||||
let (Some(n), Some(d)) = (b.u2().and_then(|i| pool.utf8(i)), b.u2().and_then(|i| pool.utf8(i)))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
h.str(n);
|
||||
h.str(d);
|
||||
let mut component = |attr: &str, body: &[u8]| {
|
||||
if attr == "Signature"
|
||||
&& let Some(sig) = (Bytes { data: body, pos: 0 }).u2().and_then(|i| pool.utf8(i))
|
||||
{
|
||||
h.str(sig);
|
||||
}
|
||||
};
|
||||
if attributes(&mut b, &pool, &mut component).is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Nested classes this class declares, and their access.
|
||||
"InnerClasses" => {
|
||||
let mut nested = Vec::new();
|
||||
for _ in 0..b.u2().unwrap_or(0) {
|
||||
let (Some(inner), Some(outer), Some(_), Some(flags)) = (b.u2(), b.u2(), b.u2(), b.u2()) else {
|
||||
break;
|
||||
};
|
||||
let inner = pool.class(inner).unwrap_or("");
|
||||
if outer != 0 && pool.class(outer) == Some(name.as_str()) && flags & ACC_PRIVATE == 0 {
|
||||
nested.push(format!("{inner}:{flags}"));
|
||||
}
|
||||
}
|
||||
nested.sort();
|
||||
nested.iter().for_each(|n| h.str(n));
|
||||
}
|
||||
"RuntimeVisibleAnnotations" | "RuntimeInvisibleAnnotations" => {
|
||||
// Annotation types are dependencies; their values aren't API.
|
||||
annotation_types(body, &pool, &mut refs);
|
||||
return;
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
class_attrs.push((attr.to_owned(), h.0));
|
||||
})?;
|
||||
class_attrs.sort();
|
||||
for (attr, h) in &class_attrs {
|
||||
api.str(attr);
|
||||
api.bytes(&h.to_be_bytes());
|
||||
}
|
||||
let mut constants = Fnv::new();
|
||||
let mut api_members: Vec<(u8, &str, &str, u16, u64)> = Vec::new();
|
||||
for (kind, list) in [(0u8, &fields), (1u8, &methods)] {
|
||||
for m in list.iter() {
|
||||
if kind == 0
|
||||
&& let Some(value) = &m.constant
|
||||
{
|
||||
// Private constants are inlined too, but only in their own class.
|
||||
if m.access & ACC_PRIVATE == 0 {
|
||||
constants.str(&m.name);
|
||||
constants.str(&m.descriptor);
|
||||
constants.bytes(value);
|
||||
}
|
||||
}
|
||||
if m.access & (ACC_PRIVATE | ACC_SYNTHETIC) != 0 || m.name == "<clinit>" {
|
||||
continue;
|
||||
}
|
||||
api_members.push((kind, &m.name, &m.descriptor, m.access & !ACC_SYNTHETIC, m.extra));
|
||||
}
|
||||
}
|
||||
api_members.sort();
|
||||
for (kind, name, descriptor, access, extra) in api_members {
|
||||
api.bytes(&[kind]);
|
||||
api.str(name);
|
||||
api.str(descriptor);
|
||||
api.u16(access);
|
||||
api.bytes(&extra.to_be_bytes());
|
||||
}
|
||||
refs.remove(&name);
|
||||
refs.retain(|r| !r.starts_with("java/"));
|
||||
Some(ClassFile { name, super_name, interfaces, refs, api: api.0, constants: constants.0 })
|
||||
}
|
||||
|
||||
/// Adds the types of the annotations in a `Runtime*Annotations` attribute.
|
||||
fn annotation_types(body: &[u8], pool: &Pool, refs: &mut BTreeSet<String>) {
|
||||
let mut b = Bytes { data: body, pos: 0 };
|
||||
let Some(count) = b.u2() else { return };
|
||||
let mut ignored = Fnv::new();
|
||||
for _ in 0..count {
|
||||
if annotation(&mut b, pool, refs, &mut ignored).is_none() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn annotation(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
|
||||
let ty = pool.utf8(b.u2()?)?;
|
||||
descriptor_refs(ty, refs);
|
||||
h.str(ty);
|
||||
for _ in 0..b.u2()? {
|
||||
h.str(pool.utf8(b.u2()?)?);
|
||||
element_value(b, pool, refs, h)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// An annotation element value: its class names go to `refs`, its value (resolved, not the
|
||||
/// constant pool indices) to `h`.
|
||||
fn element_value(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
|
||||
let tag = b.u1()?;
|
||||
h.bytes(&[tag]);
|
||||
match tag {
|
||||
b'B' | b'C' | b'D' | b'F' | b'I' | b'J' | b'S' | b'Z' => h.bytes(&pool.constant(b.u2()?)?),
|
||||
b's' => h.str(pool.utf8(b.u2()?)?),
|
||||
b'e' => {
|
||||
let ty = pool.utf8(b.u2()?)?;
|
||||
descriptor_refs(ty, refs);
|
||||
h.str(ty);
|
||||
h.str(pool.utf8(b.u2()?)?);
|
||||
}
|
||||
b'c' => {
|
||||
let ty = pool.utf8(b.u2()?)?;
|
||||
descriptor_refs(ty, refs);
|
||||
h.str(ty);
|
||||
}
|
||||
b'@' => annotation(b, pool, refs, h)?,
|
||||
b'[' => {
|
||||
for _ in 0..b.u2()? {
|
||||
element_value(b, pool, refs, h)?;
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The simple name of a class (`com/acme/Order$Line` → `Line`), which a new class can shadow.
|
||||
pub fn simple_name(name: &str) -> &str {
|
||||
let tail = name.rsplit('/').next().unwrap_or(name);
|
||||
tail.rsplit('$').next().unwrap_or(tail)
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// OpenIDEA's Java build of a Gradle build (ide_build::jbuild). With -Popenidea.build.output=<dir>,
|
||||
// every Java source set writes its classes and resources to <dir>/[<group>.]<project>/classes|test-classes,
|
||||
// so neither the language server nor a terminal `gradle` writes what the IDE runs. The task
|
||||
// `openideaBuildModel` (-Popenidea.build.model=<file>) runs what generates sources, processes the
|
||||
// resources and writes, as JSON, each source set's roots, classpaths and how JavaCompile compiles it:
|
||||
// the same model the Maven extension writes (java/java-build, BuildModel).
|
||||
import groovy.json.JsonOutput
|
||||
import org.gradle.api.tasks.compile.AbstractCompile
|
||||
import org.gradle.api.tasks.compile.JavaCompile
|
||||
import org.gradle.jvm.tasks.Jar
|
||||
|
||||
def property = { String name -> gradle.startParameter.projectProperties[name] }
|
||||
def outRoot = property('openidea.build.output')
|
||||
if (outRoot == null || gradle.parent != null) return
|
||||
|
||||
// The project's name in the build: unique, unlike `name`.
|
||||
def nameOf = { Project p -> p == p.rootProject ? p.name : p.path.substring(1).replace(':', '.') }
|
||||
def outputOf = { Project p, String set ->
|
||||
def folder = p.group ? "${p.group}.${nameOf(p)}" : nameOf(p)
|
||||
new File(outRoot, folder + '/' + (set == 'main' ? 'classes' : 'test-classes'))
|
||||
}
|
||||
def javaSets = { Project p ->
|
||||
def sets = p.extensions.findByName('sourceSets')
|
||||
sets == null ? [] : ['main', 'test'].collect { sets.findByName(it) }.findAll { it != null }
|
||||
}
|
||||
|
||||
gradle.projectsEvaluated {
|
||||
def root = gradle.rootProject
|
||||
root.allprojects.each { p ->
|
||||
javaSets(p).each { ss ->
|
||||
def out = outputOf(p, ss.name)
|
||||
ss.java.destinationDirectory.set(out)
|
||||
ss.output.resourcesDir = out
|
||||
p.tasks.named(ss.processResourcesTaskName).configure { destinationDir = out }
|
||||
}
|
||||
}
|
||||
root.tasks.register('openideaBuildModel') {
|
||||
// What compiling needs from the same project (generated sources), and the resources.
|
||||
dependsOn {
|
||||
root.allprojects.collectMany { p ->
|
||||
javaSets(p).collectMany { ss ->
|
||||
def compile = p.tasks.getByName(ss.compileJavaTaskName)
|
||||
def generators = compile.taskDependencies.getDependencies(compile).findAll {
|
||||
it.project == p && !(it instanceof AbstractCompile) && !(it instanceof Jar)
|
||||
}
|
||||
generators + [p.tasks.getByName(ss.processResourcesTaskName)]
|
||||
}
|
||||
}
|
||||
}
|
||||
doLast {
|
||||
// Project artifacts resolve to the projects' outputs.
|
||||
def artifacts = [:]
|
||||
root.allprojects.each { p ->
|
||||
def main = javaSets(p).find { it.name == 'main' }
|
||||
if (main == null) return
|
||||
def jar = p.tasks.findByName('jar')
|
||||
if (jar instanceof Jar) artifacts[jar.archiveFile.get().asFile.canonicalPath] = outputOf(p, 'main')
|
||||
}
|
||||
def files = { collection ->
|
||||
def out = []
|
||||
try {
|
||||
collection?.files?.each { f ->
|
||||
def mapped = artifacts[f.canonicalPath] ?: f
|
||||
if (!out.contains(mapped.canonicalPath)) out << mapped.canonicalPath
|
||||
}
|
||||
} catch (e) {
|
||||
out << "!${e.message}".toString()
|
||||
}
|
||||
out
|
||||
}
|
||||
def included = gradle.includedBuilds.collect { it.name }
|
||||
def projects = root.allprojects.findAll { !javaSets(it).isEmpty() }.collect { p ->
|
||||
def problems = included.isEmpty() ? [] : ["it is a composite build (${included.join(', ')})".toString()]
|
||||
def others = p.tasks.withType(AbstractCompile).findAll {
|
||||
!(it instanceof JavaCompile) && it.name ==~ /(?i)compile.*(Kotlin|Groovy|Scala|Aspectj).*/
|
||||
}.collect { "${it.class.name.replace('_Decorated', '')}@${it.name}".toString() }
|
||||
def setModel = { String name ->
|
||||
def ss = javaSets(p).find { it.name == name }
|
||||
if (ss == null) return [sourceRoots: [], output: outputOf(p, name).path, classpath: [], runtimeClasspath: []]
|
||||
JavaCompile compile = p.tasks.getByName(ss.compileJavaTaskName)
|
||||
def o = compile.options
|
||||
def classpath = files(compile.classpath)
|
||||
def runtime = files(ss.runtimeClasspath)
|
||||
(classpath + runtime).findAll { it.startsWith('!') }.each { problems << "Cannot resolve the dependencies: ${it.substring(1)}".toString() }
|
||||
def processorPath = files(o.annotationProcessorPath)
|
||||
def processorProblems = processorPath.findAll { it.startsWith('!') }
|
||||
def projectProcessors = processorPath.findAll { path -> artifacts.values().any { it.canonicalPath == path } }
|
||||
def home = null
|
||||
try { home = compile.javaCompiler.orNull?.metadata?.installationPath?.asFile?.canonicalPath } catch (ignored) {}
|
||||
[
|
||||
sourceRoots: ss.java.srcDirs.collect { it.canonicalPath },
|
||||
output: outputOf(p, name).canonicalPath,
|
||||
classpath: classpath.findAll { !it.startsWith('!') },
|
||||
runtimeClasspath: runtime.findAll { !it.startsWith('!') },
|
||||
resources: ss.resources.srcDirs.collect { [directory: it.canonicalPath, filtering: false] },
|
||||
compiler: [
|
||||
compilerId: 'javac',
|
||||
source: compile.sourceCompatibility,
|
||||
target: compile.targetCompatibility,
|
||||
release: o.release.orNull?.toString(),
|
||||
encoding: o.encoding,
|
||||
debug: o.debug,
|
||||
debuglevel: o.debugOptions.debugLevel,
|
||||
showWarnings: o.warnings,
|
||||
showDeprecation: o.deprecation,
|
||||
fork: home != null,
|
||||
executable: home == null ? null : new File(home, 'bin/javac').path,
|
||||
generatedSourcesDirectory: o.generatedSourceOutputDirectory.asFile.orNull?.canonicalPath,
|
||||
includes: ss.java.includes as List,
|
||||
excludes: ss.java.excludes as List,
|
||||
compilerArgs: o.allCompilerArgs.collect { it.toString() },
|
||||
processorPath: processorProblems.isEmpty() && projectProcessors.isEmpty() ? processorPath : null,
|
||||
processorPathError: !processorProblems.isEmpty()
|
||||
? processorProblems[0].substring(1)
|
||||
: (projectProcessors.isEmpty() ? null : 'its annotation processors are built in the same build'),
|
||||
],
|
||||
]
|
||||
}
|
||||
def mainModel = setModel('main')
|
||||
def testModel = setModel('test')
|
||||
// Gradle compiles tests against the main classes: they're the main output here.
|
||||
[
|
||||
dir: p.projectDir.canonicalPath,
|
||||
groupId: (p.group ?: '').toString(),
|
||||
artifactId: nameOf(p),
|
||||
version: p.version.toString(),
|
||||
packaging: 'jar',
|
||||
main: mainModel,
|
||||
test: testModel,
|
||||
otherCompilers: others,
|
||||
testGenerators: [],
|
||||
problems: problems,
|
||||
gradlePath: p.path,
|
||||
]
|
||||
}
|
||||
def modelFile = property('openidea.build.model')
|
||||
if (modelFile != null) {
|
||||
def file = new File(modelFile)
|
||||
def temporary = new File(file.parentFile, file.name + '.tmp')
|
||||
temporary.text = JsonOutput.toJson([version: 1, projects: projects])
|
||||
temporary.renameTo(file) || { file.delete(); temporary.renameTo(file) }()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Class-level incremental compilation (#4078 step 3). Each source set records, per class it
|
||||
//! compiled, the source it came from, its supertypes, the classes its constant pool names and
|
||||
//! fingerprints of its API and constants ([`super::classfile`]). A build compiles the changed
|
||||
//! sources, then the sources of classes that refer to a class whose API changed (or to a
|
||||
//! subclass of one), round after round until no API changes. Sets compiled against this one
|
||||
//! read its log of API changes; a changed compile-time constant, which javac copies into the
|
||||
//! classes that use it, recompiles the whole set and every set compiled against it.
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
pub(super) struct ClassRecord {
|
||||
/// The source javac compiled it from; `None` for classes an annotation processor wrote
|
||||
/// without naming an originating source.
|
||||
pub source: Option<PathBuf>,
|
||||
pub file: PathBuf,
|
||||
pub super_name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub interfaces: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub refs: Vec<String>,
|
||||
pub api: u64,
|
||||
pub constants: u64,
|
||||
}
|
||||
|
||||
impl ClassRecord {
|
||||
pub fn new(class: classfile::ClassFile, file: PathBuf, source: Option<PathBuf>) -> (String, Self) {
|
||||
let record = ClassRecord {
|
||||
source,
|
||||
file,
|
||||
super_name: class.super_name,
|
||||
interfaces: class.interfaces,
|
||||
refs: class.refs.into_iter().collect(),
|
||||
api: class.api,
|
||||
constants: class.constants,
|
||||
};
|
||||
(class.name, record)
|
||||
}
|
||||
|
||||
fn has_constants(&self) -> bool {
|
||||
self.constants != NO_CONSTANTS
|
||||
}
|
||||
}
|
||||
|
||||
/// The constant fingerprint of a class without compile-time constants.
|
||||
pub(super) const NO_CONSTANTS: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
|
||||
/// The classes whose API one compilation of a set changed.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
pub(super) struct ApiChange {
|
||||
/// The set's generation before and after the compilation.
|
||||
pub since: u64,
|
||||
pub generation: u64,
|
||||
pub classes: Vec<String>,
|
||||
/// Everything counts as changed: a constant changed, or there was nothing to compare with.
|
||||
pub all: bool,
|
||||
}
|
||||
|
||||
/// How many compilations' API changes a set keeps for the sets compiled against it; one that
|
||||
/// fell further behind compiles from scratch.
|
||||
const CHANGE_LOG: usize = 64;
|
||||
|
||||
/// The inputs of a source set that, when changed, compile it from scratch.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
pub(super) struct SetStamp {
|
||||
pub options: Vec<String>,
|
||||
/// Classpath entries outside the reactor's outputs, with their stamps (folders have none).
|
||||
pub libraries: Vec<(PathBuf, Option<FileStamp>)>,
|
||||
/// The reactor outputs on the classpath, in order.
|
||||
pub reactor: Vec<PathBuf>,
|
||||
pub processor_path: Vec<(PathBuf, Option<FileStamp>)>,
|
||||
pub java_home: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize)]
|
||||
pub(super) struct SetState {
|
||||
pub stamp: SetStamp,
|
||||
/// The sources as of the last compilation.
|
||||
pub sources: BTreeMap<PathBuf, FileStamp>,
|
||||
/// Changes whenever the set's classes do.
|
||||
pub generation: u64,
|
||||
/// The generation of each reactor output it was compiled against.
|
||||
pub upstream: BTreeMap<PathBuf, u64>,
|
||||
pub classes: BTreeMap<String, ClassRecord>,
|
||||
/// Sources a failed compilation left uncompiled.
|
||||
pub dirty: BTreeSet<PathBuf>,
|
||||
pub changes: Vec<ApiChange>,
|
||||
/// Sources annotation processors wrote, and other files they wrote without an originating
|
||||
/// source (`META-INF/services`…): processors that aggregate. While there are any, a change
|
||||
/// compiles the set from scratch.
|
||||
pub generated: Vec<PathBuf>,
|
||||
pub unowned: Vec<PathBuf>,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
impl SetState {
|
||||
/// The classes whose API changed since generation `since`; `None` when unknown (the log
|
||||
/// doesn't reach back that far) or when everything counts as changed.
|
||||
pub fn changes_since(&self, since: u64) -> Option<BTreeSet<String>> {
|
||||
let mut changed = BTreeSet::new();
|
||||
let mut at = since;
|
||||
while at != self.generation {
|
||||
let change = self.changes.iter().find(|c| c.since == at)?;
|
||||
if change.all {
|
||||
return None;
|
||||
}
|
||||
changed.extend(change.classes.iter().cloned());
|
||||
at = change.generation;
|
||||
}
|
||||
Some(changed)
|
||||
}
|
||||
|
||||
pub fn log(&mut self, generation: u64, classes: BTreeSet<String>, all: bool) {
|
||||
self.changes.push(ApiChange {
|
||||
since: self.generation,
|
||||
generation,
|
||||
classes: classes.into_iter().collect(),
|
||||
all,
|
||||
});
|
||||
if self.changes.len() > CHANGE_LOG {
|
||||
self.changes.drain(..self.changes.len() - CHANGE_LOG);
|
||||
}
|
||||
self.generation = generation;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn load_state(path: &Path) -> Option<SetState> {
|
||||
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
|
||||
}
|
||||
|
||||
/// `seeds` and the classes of `classes` that extend or implement one of them, transitively:
|
||||
/// a class that inherits a changed member changes for the classes that use it.
|
||||
pub(super) fn with_subclasses(classes: &BTreeMap<String, ClassRecord>, seeds: &BTreeSet<String>) -> BTreeSet<String> {
|
||||
let mut out = seeds.clone();
|
||||
loop {
|
||||
let before = out.len();
|
||||
for (name, record) in classes {
|
||||
if !out.contains(name)
|
||||
&& (record.super_name.as_ref().is_some_and(|s| out.contains(s))
|
||||
|| record.interfaces.iter().any(|i| out.contains(i)))
|
||||
{
|
||||
out.insert(name.clone());
|
||||
}
|
||||
}
|
||||
if out.len() == before {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sources of the classes that refer to one of `affected`.
|
||||
pub(super) fn dependent_sources(
|
||||
classes: &BTreeMap<String, ClassRecord>,
|
||||
affected: &BTreeSet<String>,
|
||||
) -> BTreeSet<PathBuf> {
|
||||
if affected.is_empty() {
|
||||
return BTreeSet::new();
|
||||
}
|
||||
classes
|
||||
.iter()
|
||||
.filter(|(name, r)| affected.contains(*name) || r.refs.iter().any(|x| affected.contains(x)))
|
||||
.filter_map(|(_, r)| r.source.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The sources of the classes that refer to a class with the same simple name as one of
|
||||
/// `added`: a new class can take a simple name over from an on-demand import.
|
||||
pub(super) fn shadowed_sources(classes: &BTreeMap<String, ClassRecord>, added: &BTreeSet<String>) -> BTreeSet<PathBuf> {
|
||||
let names: BTreeSet<&str> = added.iter().map(|n| classfile::simple_name(n)).collect();
|
||||
if names.is_empty() {
|
||||
return BTreeSet::new();
|
||||
}
|
||||
classes
|
||||
.iter()
|
||||
.filter(|(name, r)| {
|
||||
!added.contains(*name)
|
||||
&& r.refs.iter().any(|x| !added.contains(x) && names.contains(classfile::simple_name(x)))
|
||||
})
|
||||
.filter_map(|(_, r)| r.source.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What one round's classes changed, compared with the classes the round replaced.
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct RoundDiff {
|
||||
pub api: BTreeSet<String>,
|
||||
pub added: BTreeSet<String>,
|
||||
pub constants: bool,
|
||||
}
|
||||
|
||||
pub(super) fn diff(old: &BTreeMap<String, ClassRecord>, new: &BTreeMap<String, ClassRecord>) -> RoundDiff {
|
||||
let mut out = RoundDiff::default();
|
||||
for (name, record) in new {
|
||||
match old.get(name) {
|
||||
Some(before) => {
|
||||
if before.api != record.api {
|
||||
out.api.insert(name.clone());
|
||||
}
|
||||
if before.constants != record.constants {
|
||||
out.constants = true;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
out.api.insert(name.clone());
|
||||
out.added.insert(name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, before) in old {
|
||||
if !new.contains_key(name) {
|
||||
out.api.insert(name.clone());
|
||||
out.constants |= before.has_constants();
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
//! Resident javac processes (`java/java-build`, `ai.openidea.javac.Server`): one JVM per JDK
|
||||
//! and JVM options, kept warm between builds, compiling one request at a time in process.
|
||||
use super::*;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
/// A message of the server about one request.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq)]
|
||||
#[serde(tag = "kind", rename_all = "kebab-case", rename_all_fields = "camelCase")]
|
||||
pub enum Reply {
|
||||
Diagnostic {
|
||||
severity: String,
|
||||
path: Option<PathBuf>,
|
||||
/// 1-based.
|
||||
line: Option<u32>,
|
||||
/// 0-based UTF-16.
|
||||
column: Option<u32>,
|
||||
end_line: Option<u32>,
|
||||
end_column: Option<u32>,
|
||||
code: Option<String>,
|
||||
message: String,
|
||||
},
|
||||
/// A class (or resource) file javac wrote, and the source it came from.
|
||||
Output {
|
||||
path: PathBuf,
|
||||
source: Option<PathBuf>,
|
||||
},
|
||||
/// A source file an annotation processor wrote.
|
||||
Generated {
|
||||
path: PathBuf,
|
||||
source: Option<PathBuf>,
|
||||
},
|
||||
OutputText {
|
||||
text: String,
|
||||
},
|
||||
Done {
|
||||
success: bool,
|
||||
cancelled: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Request<'a> {
|
||||
id: u64,
|
||||
op: &'static str,
|
||||
options: &'a [String],
|
||||
sources: &'a [PathBuf],
|
||||
encoding: Option<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
|
||||
pub struct ServerKey {
|
||||
pub java_home: PathBuf,
|
||||
/// Options of the compiler's JVM (`.mvn/jvm.config`: `--add-opens` for processors).
|
||||
pub jvm_args: Vec<String>,
|
||||
}
|
||||
|
||||
type Pending = Arc<Mutex<HashMap<u64, mpsc::Sender<Reply>>>>;
|
||||
|
||||
pub struct JavacServer {
|
||||
child: Mutex<Child>,
|
||||
stdin: Mutex<ChildStdin>,
|
||||
pending: Pending,
|
||||
alive: Arc<AtomicBool>,
|
||||
next: AtomicU64,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
impl JavacServer {
|
||||
fn start(jar: &Path, key: &ServerKey) -> IdeResult<Self> {
|
||||
let java = key.java_home.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" });
|
||||
let mut cmd = Command::new(&java);
|
||||
cmd.args(&key.jvm_args)
|
||||
.args(["-XX:+UseSerialGC", "-XX:TieredStopAtLevel=1", "-Dfile.encoding=UTF-8", "-cp"])
|
||||
.arg(jar)
|
||||
.arg("ai.openidea.javac.Server")
|
||||
.env("JAVA_HOME", &key.java_home)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
ide_core::process::own_group(&mut cmd);
|
||||
let mut child =
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("Cannot start javac ({}): {e}", java.display())))?;
|
||||
let stdin = child.stdin.take().expect("piped");
|
||||
let stdout = child.stdout.take().expect("piped");
|
||||
let pending: Pending = Arc::default();
|
||||
let alive = Arc::new(AtomicBool::new(true));
|
||||
let (ready_tx, ready_rx) = mpsc::channel::<Result<String, String>>();
|
||||
{
|
||||
let (pending, alive) = (pending.clone(), alive.clone());
|
||||
std::thread::Builder::new()
|
||||
.name("javac-server".into())
|
||||
.spawn(move || {
|
||||
let mut ready = Some(ready_tx);
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
|
||||
match value.get("kind").and_then(|k| k.as_str()) {
|
||||
Some("ready") => {
|
||||
let version = value.get("version").and_then(|v| v.as_str()).unwrap_or("").to_owned();
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Ok(version));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Some("fatal") => {
|
||||
let message = value.get("message").and_then(|v| v.as_str()).unwrap_or("").to_owned();
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Err(message));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let Some(id) = value.get("id").and_then(|v| v.as_u64()) else { continue };
|
||||
let Ok(reply) = serde_json::from_value::<Reply>(value) else { continue };
|
||||
let done = matches!(reply, Reply::Done { .. });
|
||||
let mut pending = pending.lock().unwrap();
|
||||
if let Some(tx) = pending.get(&id) {
|
||||
let _ = tx.send(reply);
|
||||
}
|
||||
if done {
|
||||
pending.remove(&id);
|
||||
}
|
||||
}
|
||||
alive.store(false, Ordering::SeqCst);
|
||||
// Requests still waiting learn that the server is gone.
|
||||
for (_, tx) in pending.lock().unwrap().drain() {
|
||||
let _ = tx.send(Reply::Diagnostic {
|
||||
severity: "error".into(),
|
||||
path: None,
|
||||
line: None,
|
||||
column: None,
|
||||
end_line: None,
|
||||
end_column: None,
|
||||
code: None,
|
||||
message: "The javac process exited".into(),
|
||||
});
|
||||
let _ = tx.send(Reply::Done { success: false, cancelled: false });
|
||||
}
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Err("The javac process exited while starting".into()));
|
||||
}
|
||||
})
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
}
|
||||
let version = match ready_rx.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok(Ok(version)) => version,
|
||||
Ok(Err(message)) => {
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
return Err(IdeError::unavailable(format!("Cannot start javac ({}): {message}", java.display())));
|
||||
}
|
||||
Err(_) => {
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
return Err(IdeError::unavailable(format!("javac ({}) did not start", java.display())));
|
||||
}
|
||||
};
|
||||
Ok(JavacServer {
|
||||
child: Mutex::new(child),
|
||||
stdin: Mutex::new(stdin),
|
||||
pending,
|
||||
alive,
|
||||
next: AtomicU64::new(1),
|
||||
version,
|
||||
})
|
||||
}
|
||||
|
||||
fn alive(&self) -> bool {
|
||||
self.alive.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn send(&self, value: &impl Serialize) -> IdeResult<()> {
|
||||
let mut line = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
line.push(b'\n');
|
||||
let mut stdin = self.stdin.lock().unwrap();
|
||||
stdin.write_all(&line).and_then(|()| stdin.flush()).map_err(|e| IdeError::internal(format!("javac: {e}")))
|
||||
}
|
||||
|
||||
/// Compiles `sources` with javac `options`, passing each reply to `on_reply`, until the
|
||||
/// compilation ends. Cancelling stops javac at its next phase.
|
||||
pub fn compile(
|
||||
&self,
|
||||
options: &[String],
|
||||
sources: &[PathBuf],
|
||||
encoding: Option<&str>,
|
||||
cancel: &CancellationToken,
|
||||
mut on_reply: impl FnMut(&Reply),
|
||||
) -> IdeResult<bool> {
|
||||
let id = self.next.fetch_add(1, Ordering::SeqCst);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.pending.lock().unwrap().insert(id, tx);
|
||||
if let Err(e) = self.send(&Request { id, op: "compile", options, sources, encoding }) {
|
||||
self.pending.lock().unwrap().remove(&id);
|
||||
return Err(e);
|
||||
}
|
||||
let mut cancelled = false;
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok(reply) => {
|
||||
if let Reply::Done { success, cancelled: stopped } = reply {
|
||||
if stopped || cancelled {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
return Ok(success);
|
||||
}
|
||||
on_reply(&reply);
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {
|
||||
if cancel.is_cancelled() && !cancelled {
|
||||
cancelled = true;
|
||||
let _ = self.send(&serde_json::json!({ "op": "cancel", "id": id }));
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => {
|
||||
return Err(IdeError::internal("The javac process exited"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for JavacServer {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.send(&serde_json::json!({ "op": "exit" }));
|
||||
let mut child = self.child.lock().unwrap();
|
||||
for _ in 0..20 {
|
||||
if child.try_wait().ok().flatten().is_some() {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
}
|
||||
}
|
||||
|
||||
/// The resident javac servers of one IDE process.
|
||||
#[derive(Default)]
|
||||
pub struct JavacPool {
|
||||
servers: Mutex<HashMap<ServerKey, Arc<JavacServer>>>,
|
||||
}
|
||||
|
||||
impl JavacPool {
|
||||
/// The running server for `key`, started on first use (or after it died).
|
||||
pub fn server(&self, jar: &Path, key: &ServerKey) -> IdeResult<Arc<JavacServer>> {
|
||||
let mut servers = self.servers.lock().unwrap();
|
||||
if let Some(server) = servers.get(key).filter(|s| s.alive()) {
|
||||
return Ok(server.clone());
|
||||
}
|
||||
let server = Arc::new(JavacServer::start(jar, key)?);
|
||||
servers.insert(key.clone(), server.clone());
|
||||
Ok(server)
|
||||
}
|
||||
|
||||
/// Stops every server (the project closed).
|
||||
pub fn shutdown(&self) {
|
||||
self.servers.lock().unwrap().clear();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,342 @@
|
||||
//! The build model of a Maven reactor or Gradle build as the build tool itself configures it,
|
||||
//! recorded by the prepare run (`java/java-build` `BuildModel`, `gradle-build.init.gradle`), and when that run is due.
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
/// `model.json` of the prepare run (see `BuildModel.java`).
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReactorModel {
|
||||
pub version: u32,
|
||||
pub projects: Vec<ProjectModel>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProjectModel {
|
||||
/// Absolute project directory.
|
||||
pub dir: PathBuf,
|
||||
pub group_id: String,
|
||||
pub artifact_id: String,
|
||||
pub version: String,
|
||||
pub packaging: String,
|
||||
pub main: SourceSet,
|
||||
pub test: SourceSet,
|
||||
/// Executions in the compile phases that aren't javac (`group:artifact:goal@id`).
|
||||
#[serde(default)]
|
||||
pub other_compilers: Vec<String>,
|
||||
/// Test source generators the prepare run doesn't reach.
|
||||
#[serde(default)]
|
||||
pub test_generators: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub problems: Vec<String>,
|
||||
/// The Gradle project path (`:`, `:app`); `None` for Maven.
|
||||
#[serde(default)]
|
||||
pub gradle_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SourceSet {
|
||||
pub source_roots: Vec<PathBuf>,
|
||||
pub output: PathBuf,
|
||||
pub classpath: Vec<PathBuf>,
|
||||
pub runtime_classpath: Vec<PathBuf>,
|
||||
#[serde(default)]
|
||||
pub resources: Vec<ResourceRoot>,
|
||||
pub compiler: Option<CompilerConfig>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ResourceRoot {
|
||||
pub directory: PathBuf,
|
||||
#[serde(default)]
|
||||
pub filtering: bool,
|
||||
pub target_path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub includes: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub excludes: Vec<String>,
|
||||
}
|
||||
|
||||
/// maven-compiler-plugin's configuration of one source set, as its mojo was configured.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CompilerConfig {
|
||||
pub compiler_id: Option<String>,
|
||||
pub source: Option<String>,
|
||||
pub target: Option<String>,
|
||||
pub release: Option<String>,
|
||||
pub encoding: Option<String>,
|
||||
pub parameters: Option<bool>,
|
||||
pub debug: Option<bool>,
|
||||
pub debuglevel: Option<String>,
|
||||
pub proc: Option<String>,
|
||||
pub enable_preview: Option<bool>,
|
||||
pub fork: Option<bool>,
|
||||
pub executable: Option<String>,
|
||||
pub skip: Option<bool>,
|
||||
pub show_warnings: Option<bool>,
|
||||
pub show_deprecation: Option<bool>,
|
||||
pub generated_sources_directory: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
pub includes: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub excludes: Vec<String>,
|
||||
pub annotation_processors: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub compiler_args: Vec<String>,
|
||||
pub compiler_argument: Option<String>,
|
||||
#[serde(default)]
|
||||
pub compiler_arguments: BTreeMap<String, Option<String>>,
|
||||
pub multi_release_output: Option<bool>,
|
||||
pub processor_path: Option<Vec<PathBuf>>,
|
||||
pub processor_path_error: Option<String>,
|
||||
}
|
||||
|
||||
impl ProjectModel {
|
||||
pub fn key(&self) -> String {
|
||||
format!("{}:{}", self.group_id, self.artifact_id)
|
||||
}
|
||||
|
||||
pub fn set(&self, test: bool) -> &SourceSet {
|
||||
if test { &self.test } else { &self.main }
|
||||
}
|
||||
|
||||
/// Why the IDE can't compile this project with javac itself, if it can't.
|
||||
pub fn unsupported(&self, test: bool) -> Option<String> {
|
||||
// What the build tool couldn't resolve or read: the model would be incomplete.
|
||||
if let Some(problem) = self.problems.first() {
|
||||
return Some(format!("{}: {problem}", self.artifact_id));
|
||||
}
|
||||
if !self.other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
|
||||
}
|
||||
if test && !self.test_generators.is_empty() {
|
||||
return Some(format!(
|
||||
"{} generates test sources with {}",
|
||||
self.artifact_id,
|
||||
self.test_generators.join(", ")
|
||||
));
|
||||
}
|
||||
for set in [&self.main, &self.test] {
|
||||
let Some(c) = &set.compiler else { continue };
|
||||
if c.compiler_id.as_deref().is_some_and(|id| id != "javac") {
|
||||
return Some(format!("{} compiles with {}", self.artifact_id, c.compiler_id.as_deref().unwrap()));
|
||||
}
|
||||
if c.multi_release_output == Some(true) {
|
||||
return Some(format!("{} is a multi-release jar", self.artifact_id));
|
||||
}
|
||||
if let Some(error) = &c.processor_path_error {
|
||||
return Some(format!("{}: {error}", self.artifact_id));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the IDE's build of the reactor at `top_dir` keeps its model and outputs.
|
||||
pub(super) fn reactor_dir(cache: &Path, top_dir: &str) -> PathBuf {
|
||||
let base = cache.join("java-build");
|
||||
if top_dir.is_empty() { base.join("_root") } else { base.join(top_dir) }
|
||||
}
|
||||
|
||||
/// The outputs of every project, `<out>/<groupId>.<artifactId>/classes`, as the extension
|
||||
/// redirects them (`-Dopenidea.build.output=<out>`).
|
||||
pub(super) fn output_root(cache: &Path, top_dir: &str) -> PathBuf {
|
||||
reactor_dir(cache, top_dir).join("out")
|
||||
}
|
||||
|
||||
/// What the recorded model was prepared from.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub(super) struct PrepareRecord {
|
||||
pub fingerprint: LaunchFingerprint,
|
||||
pub model: ReactorModel,
|
||||
}
|
||||
|
||||
const MODEL_VERSION: u32 = 1;
|
||||
|
||||
/// Files the model depends on: the POM chains, settings, toolchains, the Maven launcher,
|
||||
/// and generator inputs (any `src/<set>/<dir>` that isn't Java sources or resources:
|
||||
/// `proto`, `antlr4`, `avro`…), but not the Java sources and resources themselves.
|
||||
pub(super) fn prepare_fingerprint(
|
||||
root: &Path,
|
||||
reactor: &[&maven::MavenProject],
|
||||
step: &BuildStep,
|
||||
local_repo: Option<PathBuf>,
|
||||
jar_version: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<LaunchFingerprint>> {
|
||||
let Some(mut inputs) = maven::model_inputs(root, reactor, local_repo) else { return Ok(None) };
|
||||
for project in reactor {
|
||||
let src = subdir(root, &project.dir).join("src");
|
||||
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
|
||||
for dir in fs::read_dir(set.path()).into_iter().flatten().flatten() {
|
||||
let name = dir.file_name();
|
||||
if dir.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
|
||||
inputs.push(dir.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for dir in step.cwd.ancestors() {
|
||||
inputs.extend([dir.join(".mvn"), dir.join("mvnw"), dir.join("mvnw.cmd")]);
|
||||
if dir == root {
|
||||
break;
|
||||
}
|
||||
}
|
||||
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
inputs.extend([home.join(".m2/settings.xml"), home.join(".m2/toolchains.xml")]);
|
||||
}
|
||||
if let Some(home) = step.env.get("JAVA_HOME") {
|
||||
inputs.push(Path::new(home).join("release"));
|
||||
}
|
||||
inputs.sort();
|
||||
inputs.dedup();
|
||||
let parameters = serde_json::to_string(&(MODEL_VERSION, jar_version, &step.program, &step.args, &step.env))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
Ok(Some(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?)))
|
||||
}
|
||||
|
||||
pub(super) fn load_record(dir: &Path) -> Option<PrepareRecord> {
|
||||
let record: PrepareRecord = serde_json::from_slice(&fs::read(dir.join("prepare.json")).ok()?).ok()?;
|
||||
(record.model.version == MODEL_VERSION).then_some(record)
|
||||
}
|
||||
|
||||
pub(super) fn save_record(dir: &Path, record: &PrepareRecord) -> IdeResult<()> {
|
||||
write_json(&dir.join("prepare.json"), record)
|
||||
}
|
||||
|
||||
pub(super) fn write_json(path: &Path, value: &impl Serialize) -> IdeResult<()> {
|
||||
let parent = path.parent().ok_or_else(|| IdeError::internal("no parent folder"))?;
|
||||
fs::create_dir_all(parent)?;
|
||||
let mut file = tempfile::NamedTempFile::new_in(parent)?;
|
||||
serde_json::to_writer(file.as_file_mut(), value).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
file.persist(path).map_err(|e| IdeError::from(e.error))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the generated source roots the model lists still exist: `mvn clean` removes them.
|
||||
pub(super) fn generated_roots_exist(model: &ReactorModel) -> bool {
|
||||
model.projects.iter().all(|p| {
|
||||
[&p.main, &p.test].iter().all(|set| {
|
||||
set.source_roots.iter().all(|root| {
|
||||
root.exists() || !root.components().any(|c| c.as_os_str() == "target") || is_processor_output(set, root)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The annotation processors' output folder, which javac writes into and never reads as a root.
|
||||
pub(super) fn is_processor_output(set: &SourceSet, root: &Path) -> bool {
|
||||
set.compiler.as_ref().and_then(|c| c.generated_sources_directory.as_deref()).is_some_and(|dir| dir == root)
|
||||
}
|
||||
|
||||
/// A Maven step at the reactor root running `goals` with the IDE's extension loaded.
|
||||
pub(super) fn maven_step(
|
||||
root: &Path,
|
||||
top: &maven::MavenProject,
|
||||
jar: &Path,
|
||||
output_root: &Path,
|
||||
model_file: Option<&Path>,
|
||||
extra: &[String],
|
||||
) -> BuildStep {
|
||||
let mut step = maven_build_step(
|
||||
&top.command,
|
||||
&["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG],
|
||||
&subdir(root, &top.dir),
|
||||
);
|
||||
step.args.extend(top.options.iter().cloned());
|
||||
step.args.push(format!("-Dmaven.ext.class.path={}", jar.display()));
|
||||
step.args.push(format!("-Dopenidea.build.output={}", output_root.display()));
|
||||
if let Some(file) = model_file {
|
||||
step.args.push(format!("-Dopenidea.build.model={}", file.display()));
|
||||
}
|
||||
step.args.extend(extra.iter().cloned());
|
||||
step.env = top.env.clone();
|
||||
step
|
||||
}
|
||||
|
||||
/// The init script that gives a Gradle build the IDE's outputs and writes its model.
|
||||
const GRADLE_INIT_SCRIPT: &str = include_str!("gradle-build.init.gradle");
|
||||
|
||||
/// Writes the init script into the build's state folder, and returns its path.
|
||||
pub(super) fn gradle_init_script(dir: &Path) -> IdeResult<PathBuf> {
|
||||
fs::create_dir_all(dir)?;
|
||||
let path = dir.join("openidea-build.init.gradle");
|
||||
if fs::read_to_string(&path).ok().as_deref() != Some(GRADLE_INIT_SCRIPT) {
|
||||
fs::write(&path, GRADLE_INIT_SCRIPT)?;
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// A Gradle step at the build's root running `tasks` with the IDE's init script.
|
||||
pub(super) fn gradle_step(
|
||||
root: &Path,
|
||||
g: &crate::GradleModel,
|
||||
init: &Path,
|
||||
output_root: &Path,
|
||||
model_file: Option<&Path>,
|
||||
tasks: &[String],
|
||||
) -> BuildStep {
|
||||
let mut step = gradle_build_step(
|
||||
&g.command,
|
||||
// The init script configures the evaluated projects, which a configuration cache skips.
|
||||
&["--console=plain", "--no-configuration-cache"],
|
||||
&subdir(root, &g.dir),
|
||||
);
|
||||
step.args.extend(["--init-script".to_owned(), init.to_string_lossy().into_owned()]);
|
||||
step.args.push(format!("-Popenidea.build.output={}", output_root.display()));
|
||||
if let Some(file) = model_file {
|
||||
step.args.push(format!("-Popenidea.build.model={}", file.display()));
|
||||
}
|
||||
step.args.extend(tasks.iter().cloned());
|
||||
step.env = g.env.clone();
|
||||
step
|
||||
}
|
||||
|
||||
/// Files a Gradle build's model depends on: settings and build scripts (with what they apply),
|
||||
/// properties, the wrapper and catalogs, `buildSrc`, and generator inputs.
|
||||
pub(super) fn gradle_prepare_fingerprint(
|
||||
root: &Path,
|
||||
g: &crate::GradleModel,
|
||||
step: &BuildStep,
|
||||
jar_version: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<LaunchFingerprint> {
|
||||
let mut inputs = crate::gradle::build_files(root, g);
|
||||
let dir = subdir(root, &g.dir);
|
||||
inputs.extend([dir.join("buildSrc"), dir.join("gradle"), dir.join("gradlew"), dir.join("gradlew.bat")]);
|
||||
for project in &g.projects {
|
||||
let src = subdir(root, &project.dir).join("src");
|
||||
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
|
||||
for generator in fs::read_dir(set.path()).into_iter().flatten().flatten() {
|
||||
let name = generator.file_name();
|
||||
if generator.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
|
||||
inputs.push(generator.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
inputs.push(home.join(".gradle/gradle.properties"));
|
||||
inputs.push(home.join(".gradle/init.d"));
|
||||
}
|
||||
if let Some(home) = step.env.get("JAVA_HOME") {
|
||||
inputs.push(Path::new(home).join("release"));
|
||||
}
|
||||
inputs.sort();
|
||||
inputs.dedup();
|
||||
let parameters =
|
||||
serde_json::to_string(&(MODEL_VERSION, jar_version, GRADLE_INIT_SCRIPT, &step.program, &step.args, &step.env))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
Ok(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?))
|
||||
}
|
||||
|
||||
pub(super) fn read_model(path: &Path) -> IdeResult<ReactorModel> {
|
||||
let bytes = fs::read(path).map_err(|e| IdeError::internal(format!("The build wrote no model ({e})")))?;
|
||||
serde_json::from_slice(&bytes).map_err(|e| IdeError::internal(format!("Unreadable build model: {e}")))
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
use super::*;
|
||||
use crate::BuildModel;
|
||||
use std::fs;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
|
||||
const JAR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../java/java-build/openidea-java-build.jar");
|
||||
|
||||
fn write(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
|
||||
fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
|
||||
let mvn = ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path())?;
|
||||
Some((home, mvn))
|
||||
}
|
||||
|
||||
const ROOT_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/pom.xml");
|
||||
const LIB_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/lib/pom.xml");
|
||||
const APP_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/app/pom.xml");
|
||||
|
||||
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
|
||||
struct Fixture {
|
||||
_tmp: tempfile::TempDir,
|
||||
root: PathBuf,
|
||||
cache: PathBuf,
|
||||
model: BuildModel,
|
||||
/// Where the build keeps its state under the cache (`Reactor::key`).
|
||||
key: &'static str,
|
||||
service: JavaBuildService,
|
||||
events: StdMutex<Vec<BuildEvent>>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new(files: &[(&str, &str)]) -> Option<Self> {
|
||||
let Some((home, mvn)) = tools() else {
|
||||
eprintln!("skipped: needs JAVA_HOME and mvn");
|
||||
return None;
|
||||
};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for (rel, text) in
|
||||
[("pom.xml", ROOT_POM), ("lib/pom.xml", LIB_POM), ("app/pom.xml", APP_POM)].iter().chain(files)
|
||||
{
|
||||
write(&root, rel, text);
|
||||
}
|
||||
let cache = root.join(".cache");
|
||||
let mut model = crate::load(&root, &cache, None);
|
||||
for p in &mut model.maven.as_mut().unwrap().projects {
|
||||
p.command = mvn.to_string_lossy().into_owned();
|
||||
p.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
|
||||
}
|
||||
Some(Fixture {
|
||||
_tmp: tmp,
|
||||
root,
|
||||
cache,
|
||||
model,
|
||||
key: "",
|
||||
service: JavaBuildService::default(),
|
||||
events: StdMutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The same `lib` ← `app` build with Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the
|
||||
/// search path).
|
||||
fn gradle(files: &[(&str, &str)]) -> Option<Self> {
|
||||
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir());
|
||||
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()));
|
||||
let (Some(home), Some(gradle)) = (home, gradle) else {
|
||||
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
|
||||
return None;
|
||||
};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let build = [
|
||||
// A persistent Gradle daemon can keep the fixture's output pipes open on Windows.
|
||||
("gradle.properties", "org.gradle.daemon=false\n"),
|
||||
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n"),
|
||||
(
|
||||
"build.gradle",
|
||||
"subprojects {\n apply plugin: 'java'\n group = 't'\n tasks.withType(JavaCompile).configureEach { options.release = 11; options.encoding = 'UTF-8' }\n}\n",
|
||||
),
|
||||
("lib/build.gradle", ""),
|
||||
(
|
||||
"app/build.gradle",
|
||||
"dependencies { implementation project(':lib') }\nprocessResources { filesMatching('*.properties') { expand(version: '1') } }\n",
|
||||
),
|
||||
];
|
||||
for (rel, text) in build.iter().chain(files) {
|
||||
write(&root, rel, text);
|
||||
}
|
||||
let cache = root.join(".cache");
|
||||
let mut model = crate::load(&root, &cache, None);
|
||||
assert_eq!(model.gradle.len(), 1, "{model:?}");
|
||||
let g = &mut model.gradle[0];
|
||||
g.command = gradle.to_string_lossy().into_owned();
|
||||
g.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
|
||||
Some(Fixture {
|
||||
_tmp: tmp,
|
||||
root,
|
||||
cache,
|
||||
model,
|
||||
key: "_gradle",
|
||||
service: JavaBuildService::default(),
|
||||
events: StdMutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
write(&self.root, rel, text);
|
||||
}
|
||||
|
||||
fn out(&self, rel: &str) -> PathBuf {
|
||||
model::output_root(&self.cache, self.key).join(rel)
|
||||
}
|
||||
|
||||
/// Builds the launch of `app` (its tests when `test`).
|
||||
fn launch(&self, test: bool) -> LaunchOutputs {
|
||||
self.build(Target::Launch { module: &self.root.join("app"), test })
|
||||
}
|
||||
|
||||
fn build(&self, target: Target) -> LaunchOutputs {
|
||||
let jdk = |_: Option<u32>| None;
|
||||
let build = JavaBuild {
|
||||
root: &self.root,
|
||||
model: &self.model,
|
||||
cache: &self.cache,
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
service: &self.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The steps of the launch builds since the last call.
|
||||
fn steps(&self) -> Vec<String> {
|
||||
self.events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.drain(..)
|
||||
.filter_map(|e| match e {
|
||||
BuildEvent::Step { command, .. } => Some(command),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Builds and returns the steps it took, which must succeed.
|
||||
fn steps_of_launch(&self) -> Vec<String> {
|
||||
self.steps();
|
||||
let built = self.launch(false);
|
||||
assert_eq!(built.failure, None, "{:?}", built.messages);
|
||||
self.steps()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
(
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
|
||||
),
|
||||
(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
),
|
||||
("app/src/main/resources/app.properties", "version=${project.version}\n"),
|
||||
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// First build: Maven prepares the model, javac compiles lib then app into the IDE's outputs.
|
||||
let first = f.launch(false);
|
||||
assert_eq!(first.failure, None, "{:?}", first.messages);
|
||||
assert_eq!(first.class_paths[0], f.out("t.app/classes"));
|
||||
assert!(first.class_paths.contains(&f.out("t.lib/classes")), "{:?}", first.class_paths);
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
assert!(f.out("t.lib/classes/l/L.class").is_file());
|
||||
assert!(!f.root.join("app/target/classes/a/A.class").exists());
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
|
||||
let steps = f.steps();
|
||||
assert!(steps[0].contains("process-resources"), "{steps:?}");
|
||||
assert_eq!(steps[1..], ["javac lib (main, 1 file)", "javac app (main, 1 file)"]);
|
||||
|
||||
// Nothing changed: no Maven, no javac.
|
||||
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
|
||||
|
||||
// A change inside a method compiles that class only, without Maven.
|
||||
f.write(
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib 2\"; } }\n",
|
||||
);
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 file)"]);
|
||||
|
||||
// A resource change is processed by Maven (it filters), and compiles nothing.
|
||||
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
|
||||
|
||||
// A deleted source leaves no class behind.
|
||||
f.write("app/src/main/java/a/Gone.java", "package a;\nclass Gone {}\n");
|
||||
assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]);
|
||||
assert!(f.out("t.app/classes/a/Gone.class").is_file());
|
||||
fs::remove_file(f.root.join("app/src/main/java/a/Gone.java")).unwrap();
|
||||
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
|
||||
assert!(!f.out("t.app/classes/a/Gone.class").exists());
|
||||
|
||||
// Compile errors fail the build with positioned messages.
|
||||
f.write("app/src/main/java/a/A.java", "package a;\npublic class A { int x = \"s\"; }\n");
|
||||
let failed = f.launch(false);
|
||||
let failure = failed.failure.expect("fails");
|
||||
assert!(failure.contains("incompatible types"), "{failure}");
|
||||
let error = failed.messages.iter().find(|m| m.severity == Severity::Error).unwrap();
|
||||
assert_eq!(error.path.as_deref(), Some(f.root.join("app/src/main/java/a/A.java").as_path()));
|
||||
assert_eq!(error.range.unwrap().start, Pos::new(1, 25));
|
||||
// It compiles again next time, even unchanged.
|
||||
f.steps();
|
||||
assert!(f.launch(false).failure.is_some());
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
|
||||
// A test launch compiles the module's tests after its main classes.
|
||||
f.write(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
);
|
||||
let tests = f.launch(true);
|
||||
assert_eq!(tests.failure, None, "{:?}", tests.messages);
|
||||
assert_eq!(tests.class_paths[..2], [f.out("t.app/test-classes"), f.out("t.app/classes")]);
|
||||
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
|
||||
|
||||
// Recompile compiles the file even unchanged.
|
||||
f.steps();
|
||||
let file = f.root.join("app/src/main/java/a/A.java");
|
||||
assert_eq!(f.build(Target::File(&file)).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
// Build Project builds every module's main and test classes.
|
||||
f.write("lib/src/test/java/l/LTest.java", "package l;\nclass LTest { String s = L.name(); }\n");
|
||||
assert_eq!(f.build(Target::Project).failure, None);
|
||||
assert_eq!(f.steps(), ["javac lib (tests, 1 file)"]);
|
||||
assert!(f.out("t.lib/test-classes/l/LTest.class").is_file());
|
||||
|
||||
// Build Module on the root aggregator compiles every submodule under it.
|
||||
f.write("app/src/test/java/a/AggTest.java", "package a;\nclass AggTest { String s = l.L.name(); }\n");
|
||||
assert_eq!(f.build(Target::Module(&f.root)).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (tests, 1 of 2 files)"]);
|
||||
assert!(f.out("t.app/test-classes/a/AggTest.class").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recompiles_the_classes_an_api_change_reaches() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int m() { return 1; } }\n"),
|
||||
("lib/src/main/java/l/Sub.java", "package l;\npublic class Sub extends Base {}\n"),
|
||||
("lib/src/main/java/l/User.java", "package l;\nclass User { int u(Sub s) { return s.m(); } }\n"),
|
||||
("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 1; }\n"),
|
||||
("lib/src/main/java/l/ConstUser.java", "package l;\nclass ConstUser { int c() { return Const.X; } }\n"),
|
||||
("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 1; } }\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new l.Other().o(); } }\n"),
|
||||
("app/src/main/java/a/B.java", "package a;\nclass B { int b() { return l.Const.X; } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(f.steps_of_launch()[1..], ["javac lib (main, 6 files)", "javac app (main, 2 files)"]);
|
||||
|
||||
// A body change: that class only, and nothing downstream.
|
||||
f.write("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 2; } }\n");
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)"]);
|
||||
|
||||
// An API change reaches the classes that use the class or a subclass of it.
|
||||
f.write(
|
||||
"lib/src/main/java/l/Base.java",
|
||||
"package l;\npublic class Base { public int m() { return 1; } public int n() { return 2; } }\n",
|
||||
);
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac lib (main, 2 of 6 files)"]);
|
||||
|
||||
// Across modules: only the classes that use it.
|
||||
f.write(
|
||||
"lib/src/main/java/l/Other.java",
|
||||
"package l;\npublic class Other { public int o() { return 2; } public void p() {} }\n",
|
||||
);
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac app (main, 1 of 2 files)"]);
|
||||
|
||||
// A compile-time constant is copied into its uses: everything compiled against it compiles again.
|
||||
f.write("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 2; }\n");
|
||||
assert_eq!(
|
||||
f.steps_of_launch(),
|
||||
["javac lib (main, 1 of 6 files)", "javac lib (main, 5 of 6 files)", "javac app (main, 2 files)"]
|
||||
);
|
||||
|
||||
// A removed method fails the classes that still call it.
|
||||
f.write("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int n() { return 2; } }\n");
|
||||
let failed = f.launch(false);
|
||||
assert!(failed.failure.expect("fails").contains("User.java"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_api_change_from_a_failed_build_still_reaches_other_modules() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int m() { return 1; } }\n"),
|
||||
("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.m(); } }\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.m(); } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
|
||||
// L compiles, then U, which still calls the removed method, fails lib before app compiles.
|
||||
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int n() { return 1; } }\n");
|
||||
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
|
||||
|
||||
// Once lib compiles, app learns that L changed, and A fails too instead of keeping a class
|
||||
// that calls a method L no longer has.
|
||||
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
|
||||
let failed = f.launch(false);
|
||||
assert!(failed.failure.expect("app fails").contains("A.java"), "{:?}", failed.messages);
|
||||
|
||||
// So does a changed constant: C compiles, then the whole set, where U fails.
|
||||
f.write("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.n() + l.C.X; } }\n");
|
||||
let c = |x: u32, y: &str| format!("package l;\npublic class C {{ public static final int X = {x};{y} }}\n");
|
||||
f.write("lib/src/main/java/l/C.java", &c(1, " public static int y() { return 0; }"));
|
||||
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n() + C.y(); } }\n");
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
f.write("lib/src/main/java/l/C.java", &c(2, ""));
|
||||
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
|
||||
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
|
||||
f.steps();
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
let steps = f.steps();
|
||||
assert!(steps.contains(&"javac app (main, 1 file)".to_owned()), "{steps:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_what_a_class_file_declares() {
|
||||
let Some((home, _)) = tools() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let compile = |text: &str| {
|
||||
write(tmp.path(), "p/C.java", text);
|
||||
let status = std::process::Command::new(home.join("bin/javac"))
|
||||
.args(["-d", "out", "p/C.java"])
|
||||
.current_dir(tmp.path())
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
classfile::parse(&fs::read(tmp.path().join("out/p/C.class")).unwrap()).unwrap()
|
||||
};
|
||||
let a = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public x.Y g() { return null; }\n private int hidden() { return 1; }\n}\nclass Z {}\n"
|
||||
.replace("x.Y", "Object")
|
||||
.as_str(),
|
||||
);
|
||||
assert_eq!(a.name, "p/C");
|
||||
assert_eq!(a.super_name.as_deref(), Some("java/lang/Thread"));
|
||||
assert_eq!(a.interfaces, ["java/lang/Runnable"]);
|
||||
assert!(a.refs.contains("javax/swing/JButton"), "{:?}", a.refs);
|
||||
assert!(!a.refs.iter().any(|r| r.starts_with("java/")), "{:?}", a.refs);
|
||||
// Private members and method bodies aren't API; constants have their own fingerprint.
|
||||
let b = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n private long hidden2() { return 1; }\n}\nclass Z {}\n",
|
||||
);
|
||||
assert_eq!((a.api, a.constants), (b.api, b.constants));
|
||||
let c = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"changed\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
|
||||
);
|
||||
assert_eq!(a.api, c.api);
|
||||
assert_ne!(a.constants, c.constants);
|
||||
let d = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JLabel> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
|
||||
);
|
||||
assert_ne!(a.api, d.api);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_api_changes_through_the_log() {
|
||||
let mut state = SetState { generation: 1, ..Default::default() };
|
||||
state.log(2, ["a/A".to_owned()].into(), false);
|
||||
state.log(3, ["a/B".to_owned()].into(), false);
|
||||
assert_eq!(state.changes_since(3), Some(BTreeSet::new()));
|
||||
assert_eq!(state.changes_since(2), Some(["a/B".to_owned()].into()));
|
||||
assert_eq!(state.changes_since(1), Some(["a/A".to_owned(), "a/B".to_owned()].into()));
|
||||
// Unknown generations, and a log entry where everything changed, mean everything.
|
||||
assert_eq!(state.changes_since(0), None);
|
||||
state.log(4, BTreeSet::new(), true);
|
||||
assert_eq!(state.changes_since(3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ant_patterns_match_like_maven() {
|
||||
assert!(ant_match("**/*.java", "a/b/C.java"));
|
||||
assert!(ant_match("**/*.java", "C.java"));
|
||||
assert!(ant_match("com/acme/**", "com/acme/x/Y.java"));
|
||||
assert!(!ant_match("com/acme/**", "com/other/Y.java"));
|
||||
assert!(ant_match("**/generated/", "x/generated/Y.java"));
|
||||
assert!(ant_match("**/*Test?.java", "a/FooTest1.java"));
|
||||
assert!(!ant_match("*.java", "a/B.java"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_options_follow_the_compiler_configuration() {
|
||||
let set = SourceSet {
|
||||
output: PathBuf::from("/o"),
|
||||
compiler: Some(CompilerConfig {
|
||||
release: Some("17".into()),
|
||||
source: Some("1.8".into()),
|
||||
encoding: Some("UTF-8".into()),
|
||||
parameters: Some(true),
|
||||
debuglevel: Some("lines,vars".into()),
|
||||
proc: Some("none".into()),
|
||||
processor_path: Some(vec![PathBuf::from("/p.jar")]),
|
||||
annotation_processors: Some(vec!["a.P".into()]),
|
||||
compiler_args: vec!["-Xlint:unchecked".into()],
|
||||
compiler_arguments: [("Akey=v".to_owned(), None)].into(),
|
||||
show_warnings: Some(false),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let args = javac_options(&set, &[PathBuf::from("/lib.jar")], Path::new("/gen"), Some(21));
|
||||
let joined = args.join(" ");
|
||||
let separator = if cfg!(windows) { ";" } else { ":" };
|
||||
assert!(joined.starts_with(&format!("-d /o -classpath /o{separator}/lib.jar -sourcepath -s /gen")), "{joined}");
|
||||
for expected in [
|
||||
"-processorpath /p.jar",
|
||||
"-processor a.P",
|
||||
"-proc:none",
|
||||
"-g:lines,vars",
|
||||
"-parameters",
|
||||
"-nowarn",
|
||||
"-encoding UTF-8",
|
||||
"--release 17",
|
||||
"-Akey=v",
|
||||
] {
|
||||
assert!(joined.contains(expected), "{expected} in {joined}");
|
||||
}
|
||||
assert!(joined.ends_with("-Xlint:unchecked"), "{joined}");
|
||||
// JDK 8 has no --release: source and target instead.
|
||||
let old = javac_options(&set, &[], Path::new("/gen"), Some(8)).join(" ");
|
||||
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_gradle_projects_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
(
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
|
||||
),
|
||||
(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
),
|
||||
("app/src/main/resources/app.properties", "version=${version}\n"),
|
||||
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 3, "{steps:?}");
|
||||
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
|
||||
assert!(steps[1].starts_with("javac lib (main"), "{steps:?}");
|
||||
assert!(steps[2].starts_with("javac app (main"), "{steps:?}");
|
||||
assert!(f.out("t.lib/classes/l/L.class").is_file());
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
|
||||
// Gradle's own outputs stay untouched.
|
||||
assert!(!f.root.join("app/build/classes").exists());
|
||||
|
||||
let built = f.launch(false);
|
||||
assert!(built.class_paths.iter().any(|p| p.ends_with("t.lib/classes")), "{:?}", built.class_paths);
|
||||
assert!(!built.class_paths.iter().any(|p| p.extension().is_some_and(|e| e == "jar")), "{:?}", built.class_paths);
|
||||
assert_eq!(f.steps(), Vec::<String>::new(), "nothing changed");
|
||||
|
||||
f.write(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name() + 1); } }\n",
|
||||
);
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].starts_with("javac app (main"), "{steps:?}");
|
||||
|
||||
f.write("app/src/main/resources/app.properties", "version=${version}\nname=app\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].contains(":app:processResources"), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nname=app\n");
|
||||
|
||||
// Tests compile against the main classes.
|
||||
f.steps();
|
||||
let built = f.launch(true);
|
||||
assert_eq!(built.failure, None, "{:?}", built.messages);
|
||||
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
|
||||
|
||||
// A changed build script prepares again.
|
||||
f.write("lib/build.gradle", "// changed\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
|
||||
|
||||
// An error is a javac diagnostic on the source.
|
||||
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static String name() { return 1; } }\n");
|
||||
let built = f.launch(false);
|
||||
assert!(built.failure.is_some());
|
||||
let error = built.messages.iter().find(|m| m.severity == Severity::Error).expect("an error");
|
||||
assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_gradle_projects_with_other_compilers_to_gradle() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
("app/build.gradle", "apply plugin: 'groovy'\ndependencies { implementation project(':lib') }\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let jdk = |_: Option<u32>| None;
|
||||
let build = JavaBuild {
|
||||
root: &f.root,
|
||||
model: &f.model,
|
||||
cache: &f.cache,
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
service: &f.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
let target = Target::Launch { module: &f.root.join("app"), test: false };
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &|_| {}) {
|
||||
Ok(Built::Unsupported(reason)) => assert!(reason.contains("GroovyCompile"), "{reason}"),
|
||||
Ok(Built::Done(outputs)) => panic!("built: {outputs:?}"),
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
@@ -91,12 +91,14 @@ fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResul
|
||||
|
||||
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
|
||||
/// redirector loaded before Maven calculates its lifecycle execution plans.
|
||||
/// Builds the Kotlin libraries; `on_progress` gets Maven's progress (message, fraction 0..1).
|
||||
pub fn build(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
bundle: &Path,
|
||||
generation: &Path,
|
||||
cancel: &CancellationToken,
|
||||
on_progress: &(dyn Fn(&str, Option<f32>) + Sync),
|
||||
) -> IdeResult<Outcome> {
|
||||
std::fs::create_dir_all(generation)?;
|
||||
let mut plan = plan(root, model, cancel)?;
|
||||
@@ -124,10 +126,10 @@ pub fn build(
|
||||
for step in &plan.steps {
|
||||
let mut reactor = plan.clone();
|
||||
reactor.steps = vec![step.clone()];
|
||||
let result = compile::run(root, &reactor, cancel, &|event| {
|
||||
if let BuildEvent::Output { text, .. } = event {
|
||||
tracing::debug!("kotlin bridge: {}", text.trim_end());
|
||||
}
|
||||
let result = compile::run(root, &reactor, cancel, &|event| match event {
|
||||
BuildEvent::Output { text, .. } => tracing::debug!("kotlin bridge: {}", text.trim_end()),
|
||||
BuildEvent::Progress { message, fraction } => on_progress(&message, fraction),
|
||||
_ => {}
|
||||
})?;
|
||||
messages.extend(result.messages);
|
||||
}
|
||||
@@ -456,6 +458,7 @@ mod tests {
|
||||
Path::new("unused.jar"),
|
||||
&directory.path().join("private"),
|
||||
&CancellationToken::new(),
|
||||
&|_, _| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod application_update;
|
||||
pub mod compile;
|
||||
pub mod gradle;
|
||||
mod gradle_deps;
|
||||
pub mod jbuild;
|
||||
pub mod kotlin_bridge;
|
||||
pub mod maven;
|
||||
pub mod pom_edit;
|
||||
@@ -16,6 +17,7 @@ mod process;
|
||||
#[cfg(test)]
|
||||
mod process_numbers;
|
||||
pub mod sbt;
|
||||
pub mod surefire;
|
||||
mod sync;
|
||||
pub mod web;
|
||||
mod xml;
|
||||
@@ -162,12 +164,13 @@ pub fn maven_external_roots(
|
||||
gradle::external_roots(root, owned.iter().map(String::as_str))
|
||||
}
|
||||
|
||||
/// Source, resource and build folders of the last Gradle sync, absolute.
|
||||
/// Source, resource and build folders of the last Gradle sync, with the folder of the
|
||||
/// project reporting each; all absolute.
|
||||
pub fn gradle_source_roots(
|
||||
root: &Path,
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot)> {
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
|
||||
let reported = gradle::linked_dirs(root, settings)
|
||||
.iter()
|
||||
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
|
||||
|
||||
@@ -517,6 +517,59 @@ pub fn local_repository_of(settings: &Path) -> Option<PathBuf> {
|
||||
Some(PathBuf::from(repo.replace("${user.home}", &home)))
|
||||
}
|
||||
|
||||
/// The local repository a Maven run with these options resolves into: `-Dmaven.repo.local=`
|
||||
/// first, then `<localRepository>` of the `-s` settings, then the user's default.
|
||||
pub fn local_repository_for(options: &[String]) -> Option<PathBuf> {
|
||||
if let Some(repo) = options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")) {
|
||||
return Some(PathBuf::from(repo));
|
||||
}
|
||||
let mut args = options.iter();
|
||||
while let Some(arg) = args.next() {
|
||||
let path = match arg.as_str() {
|
||||
"-s" | "--settings" => args.next().map(String::as_str),
|
||||
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
|
||||
};
|
||||
if let Some(path) = path {
|
||||
return local_repository_of(Path::new(path)).or_else(default_local_repo);
|
||||
}
|
||||
}
|
||||
default_local_repo()
|
||||
}
|
||||
|
||||
/// A goal of the IDE's own (`help:evaluate`, `dependency:build-classpath`, …) by its plugin's
|
||||
/// coordinates rather than its prefix: offline, Maven resolves a prefix only from group metadata
|
||||
/// in the local repository, which a repository filled from a private mirror often lacks even when
|
||||
/// the plugin itself is there. Uses the newest 3.x version already in `repo`, so nothing is
|
||||
/// downloaded, else a pinned one.
|
||||
pub fn plugin_goal(goal: &str, repo: Option<&Path>) -> String {
|
||||
let (prefix, goal) = goal.split_once(':').expect("prefix:goal");
|
||||
let (artifact, pinned) = match prefix {
|
||||
"help" => ("maven-help-plugin", "3.5.1"),
|
||||
"dependency" => ("maven-dependency-plugin", "3.8.1"),
|
||||
_ => unreachable!("not a goal of the IDE's own: {prefix}"),
|
||||
};
|
||||
let version = repo.and_then(|repo| newest_local_plugin(repo, artifact, 3)).unwrap_or_else(|| pinned.to_owned());
|
||||
format!("org.apache.maven.plugins:{artifact}:{version}:{goal}")
|
||||
}
|
||||
|
||||
/// The newest release of `org.apache.maven.plugins:<artifact>` whose jar is in `repo`,
|
||||
/// from major version `min_major` up.
|
||||
pub(crate) fn newest_local_plugin(repo: &Path, artifact: &str, min_major: u64) -> Option<String> {
|
||||
let dir = repo.join("org/apache/maven/plugins").join(artifact);
|
||||
let parse = |v: &str| v.split('.').map(|n| n.parse::<u64>().ok()).collect::<Option<Vec<u64>>>();
|
||||
std::fs::read_dir(&dir)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().into_string().ok())
|
||||
.filter_map(|v| parse(&v).map(|n| (n, v)))
|
||||
.filter(|(n, v)| {
|
||||
n.first().is_some_and(|&major| major >= min_major)
|
||||
&& dir.join(v).join(format!("{artifact}-{v}.jar")).is_file()
|
||||
})
|
||||
.max()
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
|
||||
impl Resolver {
|
||||
fn new(local_repo: Option<PathBuf>, profiles: &[String]) -> Self {
|
||||
Self::new_with_jdk(local_repo, profiles, None)
|
||||
@@ -700,7 +753,26 @@ pub(crate) fn launch_inputs(
|
||||
projects: &[&MavenProject],
|
||||
local_repo: Option<PathBuf>,
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
fn roots(el: &Element, parent: &str, dir: &Path, out: &mut Vec<PathBuf>) -> Option<()> {
|
||||
project_inputs(root, projects, local_repo, true)
|
||||
}
|
||||
|
||||
/// The POM chains (with imported BOMs) of `projects` and the files their profiles activate
|
||||
/// on: what Maven's model of them is built from, without their sources.
|
||||
pub(crate) fn model_inputs(
|
||||
root: &Path,
|
||||
projects: &[&MavenProject],
|
||||
local_repo: Option<PathBuf>,
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
project_inputs(root, projects, local_repo, false)
|
||||
}
|
||||
|
||||
fn project_inputs(
|
||||
root: &Path,
|
||||
projects: &[&MavenProject],
|
||||
local_repo: Option<PathBuf>,
|
||||
sources: bool,
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
fn roots(el: &Element, parent: &str, dir: &Path, sources: bool, out: &mut Vec<PathBuf>) -> Option<()> {
|
||||
let input =
|
||||
matches!(el.name.as_str(), "sourceDirectory" | "testSourceDirectory" | "sourceDir" | "testSourceDir")
|
||||
|| (matches!(parent, "sources" | "sourceDirs" | "testSources" | "testSourceDirs")
|
||||
@@ -709,6 +781,7 @@ pub(crate) fn launch_inputs(
|
||||
|| (parent == "filters" && el.name == "filter");
|
||||
// Profile activation may depend on the presence of an otherwise unrelated file.
|
||||
let activation = parent == "file" && matches!(el.name.as_str(), "exists" | "missing");
|
||||
let input = input && sources;
|
||||
if input || activation {
|
||||
// A source root under Maven's build directory is generated by the build itself.
|
||||
// Skip it without resolving the property: `<build><directory>` may be custom, and
|
||||
@@ -734,7 +807,7 @@ pub(crate) fn launch_inputs(
|
||||
}
|
||||
}
|
||||
for child in &el.children {
|
||||
roots(child, &el.name, dir, out)?;
|
||||
roots(child, &el.name, dir, sources, out)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
@@ -743,7 +816,9 @@ pub(crate) fn launch_inputs(
|
||||
for project in projects {
|
||||
let dir = root.join(&project.dir);
|
||||
// Include all conventional language/resource roots, including nonstandard files under src.
|
||||
out.push(dir.join("src"));
|
||||
if sources {
|
||||
out.push(dir.join("src"));
|
||||
}
|
||||
let pom = root.join(&project.pom);
|
||||
resolver.context(&pom, 0);
|
||||
let mut path = pom;
|
||||
@@ -755,7 +830,7 @@ pub(crate) fn launch_inputs(
|
||||
}
|
||||
out.push(path.clone());
|
||||
let text = xml::read_text(&path)?;
|
||||
roots(&xml::parse(&text)?, "", &dir, &mut out)?;
|
||||
roots(&xml::parse(&text)?, "", &dir, sources, &mut out)?;
|
||||
let raw = resolver.pom(&path)?;
|
||||
let Some(parent) = raw.parent else { break };
|
||||
path = resolver.parent_path(path.parent()?, &parent)?;
|
||||
@@ -2557,6 +2632,24 @@ mod tests {
|
||||
assert!(local_repository_of(&tmp.path().join("missing.xml")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ide_goals_resolve_from_the_repository_the_run_uses() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let settings = tmp.path().join("settings.xml");
|
||||
std::fs::write(&settings, "<settings><localRepository>/srv/m2</localRepository></settings>").unwrap();
|
||||
let s = settings.to_string_lossy().into_owned();
|
||||
let opts = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
assert_eq!(local_repository_for(&opts(&["-s", &s])), Some(PathBuf::from("/srv/m2")));
|
||||
assert_eq!(local_repository_for(&opts(&[&format!("--settings={s}")])), Some(PathBuf::from("/srv/m2")));
|
||||
let explicit = opts(&["-s", &s, "-Dmaven.repo.local=/tmp/r"]);
|
||||
assert_eq!(local_repository_for(&explicit), Some(PathBuf::from("/tmp/r")));
|
||||
// No repository known: a pinned version, still by coordinates.
|
||||
assert_eq!(
|
||||
plugin_goal("dependency:build-classpath", None),
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:build-classpath"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effective_pom_goals_come_from_the_local_repository_it_is_given() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::io::{BufRead, BufReader, Read};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Stream {
|
||||
@@ -28,6 +28,8 @@ pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
|
||||
/// `on_line` takes its lines waits on its full pipe, as it would on a terminal, instead of
|
||||
/// the lines piling up in memory (a line is at most [`MAX_LINE_BYTES`] in [`run_bounded`]).
|
||||
const LINE_QUEUE: usize = 64;
|
||||
/// How long output may keep arriving after the child exits before the run stops reading it.
|
||||
const OUTPUT_AFTER_EXIT: Duration = Duration::from_secs(1);
|
||||
/// What [`pump_bounded`] reads from a pipe at a time.
|
||||
const PUMP_CHUNK: usize = 64 * 1024;
|
||||
|
||||
@@ -236,6 +238,10 @@ fn run_with_env_capture(
|
||||
let mut tail_bytes = 0usize;
|
||||
let mut total = 0usize;
|
||||
let mut truncated = false;
|
||||
// When the child exited. A process it left running (a Gradle daemon on Windows) can inherit
|
||||
// the pipes and keep them open long after; the run ends once they have been quiet this long.
|
||||
let mut exited: Option<Instant> = None;
|
||||
let mut pipes_held = false;
|
||||
loop {
|
||||
if cancel.is_cancelled() {
|
||||
kill_tree(&mut child);
|
||||
@@ -244,6 +250,9 @@ fn run_with_env_capture(
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok((_, line)) if encoding.notice.as_ref() == Some(&line) => {}
|
||||
Ok((stream, line)) => {
|
||||
if exited.is_some() {
|
||||
exited = Some(Instant::now());
|
||||
}
|
||||
on_line(stream, &line);
|
||||
if !bounded {
|
||||
// The caller parses a complete model from `text`, so keep every line.
|
||||
@@ -274,12 +283,26 @@ fn run_with_env_capture(
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => match exited {
|
||||
Some(at) if at.elapsed() >= OUTPUT_AFTER_EXIT => {
|
||||
pipes_held = true;
|
||||
break;
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
if child.try_wait()?.is_some() {
|
||||
exited = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
for r in readers.into_iter().flatten() {
|
||||
let _ = r.join();
|
||||
// Readers still blocked on a pipe that a leftover process holds end with it, on their own.
|
||||
if !pipes_held {
|
||||
for r in readers.into_iter().flatten() {
|
||||
let _ = r.join();
|
||||
}
|
||||
}
|
||||
let status = child.wait()?;
|
||||
let mut text = head;
|
||||
@@ -392,6 +415,31 @@ mod tests {
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_process_left_holding_the_pipes_does_not_hold_the_run() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// The background child inherits stdout and stderr, as a Gradle daemon can on Windows.
|
||||
let script = "echo built; (sleep 30) & echo done >&2";
|
||||
let started = Instant::now();
|
||||
let mut lines = Vec::new();
|
||||
let out = run(
|
||||
"sh",
|
||||
&["-c".into(), script.into()],
|
||||
tmp.path(),
|
||||
&BTreeMap::new(),
|
||||
&CancellationToken::new(),
|
||||
|_, l| lines.push(l.to_owned()),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "took {:?}", started.elapsed());
|
||||
assert!(out.success);
|
||||
lines.sort();
|
||||
assert_eq!(lines, ["built", "done"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_kills_grandchildren() {
|
||||
if cfg!(windows) {
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
//! A Maven module's Surefire configuration, for test runs OpenIDEA starts itself instead of
|
||||
//! Surefire (IDEA's `MavenJUnitPatcher`): what the forked test JVM would get from the POM.
|
||||
//!
|
||||
//! Read from the effective POM the last sync cached (Maven merged parents, profiles and
|
||||
//! `pluginManagement` there), else from the module's own `pom.xml` and its `<properties>`.
|
||||
|
||||
use crate::maven::{MavenModel, interpolate};
|
||||
use crate::xml::{self, Element};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::Path;
|
||||
|
||||
const SUREFIRE: &str = "maven-surefire-plugin";
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SurefireConfig {
|
||||
/// `<argLine>`, split into JVM options.
|
||||
pub arg_line: Vec<String>,
|
||||
/// `<systemPropertyVariables>` and the older `<systemProperties>`.
|
||||
pub system_properties: BTreeMap<String, String>,
|
||||
/// `<environmentVariables>`.
|
||||
pub environment: BTreeMap<String, String>,
|
||||
pub working_directory: Option<String>,
|
||||
/// `<additionalClasspathElements>`.
|
||||
pub additional_classpath: Vec<String>,
|
||||
/// `<classpathDependencyExcludes>`: `groupId:artifactId`.
|
||||
pub classpath_excludes: Vec<String>,
|
||||
}
|
||||
|
||||
/// The Surefire configuration of the Maven module at `module` (absolute), if it is one.
|
||||
pub fn surefire_config(root: &Path, cache_dir: &Path, model: &MavenModel, module: &Path) -> Option<SurefireConfig> {
|
||||
let same = |a: &Path, b: &Path| dunce::canonicalize(a).ok() == dunce::canonicalize(b).ok();
|
||||
let project = model.projects.iter().find(|p| same(&root.join(&p.dir), module))?;
|
||||
let pom = root.join(&project.pom);
|
||||
let modified = |p: &Path| std::fs::metadata(p).and_then(|m| m.modified()).ok();
|
||||
// A cache written before the POM last changed would apply an old configuration.
|
||||
let effective = std::fs::read_dir(cache_dir).ok()?.flatten().map(|e| e.path()).find_map(|path| {
|
||||
let name = path.file_name()?.to_str()?;
|
||||
if !(name.starts_with("effective-pom-") && name.ends_with(".xml")) || modified(&path) < modified(&pom) {
|
||||
return None;
|
||||
}
|
||||
let root = xml::parse(&xml::read_text(&path)?)?;
|
||||
let projects: Vec<Element> = if root.name == "projects" {
|
||||
root.children.into_iter().filter(|p| p.name == "project").collect()
|
||||
} else {
|
||||
vec![root]
|
||||
};
|
||||
projects.into_iter().find(|p| {
|
||||
let group = p.text_of("groupId").or_else(|| p.at("parent/groupId").map(|g| g.text.trim().to_owned()));
|
||||
group.as_deref() == Some(project.group_id.as_str())
|
||||
&& p.text_of("artifactId").as_deref() == Some(&project.artifact_id)
|
||||
})
|
||||
});
|
||||
let (element, own) = match effective {
|
||||
Some(e) => (e, false),
|
||||
// ponytail: without a sync, inherited configuration and parent properties are missing; Reload adds them.
|
||||
None => (xml::parse(&xml::read_text(&pom)?)?, true),
|
||||
};
|
||||
let mut props: HashMap<String, String> = element
|
||||
.child("properties")
|
||||
.map(|p| p.children.iter().map(|c| (c.name.clone(), c.text.trim().to_owned())).collect())
|
||||
.unwrap_or_default();
|
||||
let dir = module.to_string_lossy().into_owned();
|
||||
for (key, value) in [
|
||||
("basedir", dir.clone()),
|
||||
("project.basedir", dir.clone()),
|
||||
("project.build.directory", format!("{dir}/target")),
|
||||
("project.groupId", project.group_id.clone()),
|
||||
("project.artifactId", project.artifact_id.clone()),
|
||||
("project.version", project.version.clone()),
|
||||
] {
|
||||
props.entry(key.into()).or_insert(value);
|
||||
}
|
||||
Some(read(&element, &props, own))
|
||||
}
|
||||
|
||||
/// `<build><plugins>` Surefire's configuration, then its `default-test` execution's.
|
||||
fn read(project: &Element, props: &HashMap<String, String>, own: bool) -> SurefireConfig {
|
||||
let is_surefire = |p: &&Element| p.text_of("artifactId").as_deref() == Some(SUREFIRE);
|
||||
let mut plugins: Vec<&Element> = project.list("build/plugins", "plugin").into_iter().filter(is_surefire).collect();
|
||||
if own && plugins.is_empty() {
|
||||
plugins = project.list("build/pluginManagement/plugins", "plugin").into_iter().filter(is_surefire).collect();
|
||||
}
|
||||
let mut configurations: Vec<&Element> = Vec::new();
|
||||
for plugin in plugins {
|
||||
configurations.extend(plugin.child("configuration"));
|
||||
let default_test = plugin
|
||||
.list("executions", "execution")
|
||||
.into_iter()
|
||||
.find(|e| e.text_of("id").as_deref() == Some("default-test"));
|
||||
configurations.extend(default_test.and_then(|e| e.child("configuration")));
|
||||
}
|
||||
let value = |text: &str| resolve(text.trim(), props);
|
||||
let mut config = SurefireConfig::default();
|
||||
for c in configurations {
|
||||
if let Some(arg_line) = c.child("argLine") {
|
||||
config.arg_line = split_arg_line(&value(&arg_line.text));
|
||||
}
|
||||
for p in c.child("systemPropertyVariables").map_or(&[][..], |p| &p.children) {
|
||||
config.system_properties.insert(p.name.clone(), value(&p.text));
|
||||
}
|
||||
// `<systemProperties>`: `<property><name/><value/></property>` (deprecated, still honoured).
|
||||
for p in c.list("systemProperties", "property") {
|
||||
if let Some(name) = p.text_of("name") {
|
||||
config.system_properties.insert(name, value(&p.text_of("value").unwrap_or_default()));
|
||||
}
|
||||
}
|
||||
for e in c.child("environmentVariables").map_or(&[][..], |e| &e.children) {
|
||||
config.environment.insert(e.name.clone(), value(&e.text));
|
||||
}
|
||||
if let Some(dir) = c.text_of("workingDirectory").map(|d| value(&d)).filter(|d| !d.is_empty()) {
|
||||
config.working_directory = Some(dir);
|
||||
}
|
||||
let texts = |list: &str, item: &str| -> Vec<String> {
|
||||
c.list(list, item).into_iter().map(|e| value(&e.text)).filter(|t| !t.is_empty()).collect()
|
||||
};
|
||||
config.additional_classpath.extend(texts("additionalClasspathElements", "additionalClasspathElement"));
|
||||
config.classpath_excludes.extend(texts("classpathDependencyExcludes", "classpathDependencyExclude"));
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// `${…}` from the POM's properties, then Surefire's late replacement `@{…}` (a property a plugin
|
||||
/// sets during the build, such as JaCoCo's `argLine`, is unknown here and left out, as in IDEA).
|
||||
fn resolve(text: &str, props: &HashMap<String, String>) -> String {
|
||||
let mut out = interpolate(text, props);
|
||||
for open in ["@{", "${"] {
|
||||
while let Some(start) = out.find(open) {
|
||||
let Some(len) = out[start..].find('}') else { break };
|
||||
let key = &out[start + 2..start + len];
|
||||
let replacement = if open == "@{" { props.get(key).cloned().unwrap_or_default() } else { String::new() };
|
||||
out.replace_range(start..=start + len, &replacement);
|
||||
}
|
||||
}
|
||||
out.trim().to_owned()
|
||||
}
|
||||
|
||||
/// Splits `argLine` as Surefire does (plexus `CommandLineUtils`): whitespace, `"…"` and `'…'`, no escapes.
|
||||
fn split_arg_line(line: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut current: Option<String> = None;
|
||||
let mut quote: Option<char> = None;
|
||||
for c in line.chars() {
|
||||
match quote {
|
||||
Some(q) if c == q => quote = None,
|
||||
Some(_) => current.get_or_insert_default().push(c),
|
||||
None if c == '"' || c == '\'' => {
|
||||
quote = Some(c);
|
||||
current.get_or_insert_default();
|
||||
}
|
||||
None if c.is_whitespace() => out.extend(current.take()),
|
||||
None => current.get_or_insert_default().push(c),
|
||||
}
|
||||
}
|
||||
out.extend(current);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const POM: &str = r#"<project>
|
||||
<groupId>com.example</groupId><artifactId>orders</artifactId><version>1</version>
|
||||
<properties><openideaFail>true</openideaFail><mockito>/m2/mockito.jar</mockito></properties>
|
||||
<build><plugins><plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<argLine>@{argLine} @{jacoco} -javaagent:${mockito} --add-opens "java.base/java.lang=ALL-UNNAMED" -Dx=${undefined}</argLine>
|
||||
<systemPropertyVariables><openidea.fail>${openideaFail}</openidea.fail><dir>${project.build.directory}</dir></systemPropertyVariables>
|
||||
<systemProperties><property><name>old</name><value>style</value></property></systemProperties>
|
||||
<environmentVariables><TZ>UTC</TZ></environmentVariables>
|
||||
<additionalClasspathElements><additionalClasspathElement>${basedir}/extra</additionalClasspathElement></additionalClasspathElements>
|
||||
<classpathDependencyExcludes><classpathDependencyExclude>org.slf4j:slf4j-simple</classpathDependencyExclude></classpathDependencyExcludes>
|
||||
</configuration>
|
||||
<executions><execution><id>default-test</id><configuration><workingDirectory>${basedir}/work</workingDirectory></configuration></execution></executions>
|
||||
</plugin></plugins></build>
|
||||
</project>"#;
|
||||
|
||||
fn model(dir: &Path) -> MavenModel {
|
||||
crate::maven::load(dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_module_pom_and_the_effective_pom_the_sync_cached() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::write(root.join("pom.xml"), POM).unwrap();
|
||||
let cache = root.join("cache");
|
||||
std::fs::create_dir_all(&cache).unwrap();
|
||||
let config = surefire_config(root, &cache, &model(root), root).unwrap();
|
||||
let d = root.to_string_lossy();
|
||||
assert_eq!(
|
||||
config.arg_line,
|
||||
["-javaagent:/m2/mockito.jar", "--add-opens", "java.base/java.lang=ALL-UNNAMED", "-Dx="]
|
||||
);
|
||||
assert_eq!(config.system_properties["openidea.fail"], "true");
|
||||
assert_eq!(config.system_properties["dir"], format!("{d}/target"));
|
||||
assert_eq!(config.system_properties["old"], "style");
|
||||
assert_eq!(config.environment["TZ"], "UTC");
|
||||
assert_eq!(config.working_directory, Some(format!("{d}/work")));
|
||||
assert_eq!(config.additional_classpath, [format!("{d}/extra")]);
|
||||
assert_eq!(config.classpath_excludes, ["org.slf4j:slf4j-simple"]);
|
||||
|
||||
// A sync's effective POM wins: it has what the module inherits.
|
||||
let effective = POM.replace("<argLine>", "<argLine>-Xmx1g ").replace("<TZ>UTC</TZ>", "<TZ>Asia/Tokyo</TZ>");
|
||||
std::fs::write(cache.join("effective-pom-0.xml"), format!("<projects>{effective}</projects>")).unwrap();
|
||||
let config = surefire_config(root, &cache, &model(root), root).unwrap();
|
||||
assert_eq!(config.arg_line[0], "-Xmx1g");
|
||||
assert_eq!(config.environment["TZ"], "Asia/Tokyo");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_arg_line_like_surefire() {
|
||||
assert_eq!(split_arg_line(r#" -a "b c" 'd "e"' C:\x\y "" "#), ["-a", "b c", r#"d "e""#, r"C:\x\y", ""]);
|
||||
}
|
||||
}
|
||||
@@ -86,22 +86,37 @@ 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 project's own
|
||||
/// plugin version is, which may be cached instead.
|
||||
/// 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.
|
||||
/// `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());
|
||||
vec![
|
||||
"help:effective-pom".into(),
|
||||
format!("-Doutput={}", effective.to_string_lossy()),
|
||||
if pinned { DEPENDENCY_TREE.into() } else { "dependency:tree".into() },
|
||||
"-Dverbose".into(),
|
||||
]
|
||||
let tree = if pinned {
|
||||
DEPENDENCY_TREE.to_owned()
|
||||
} else {
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).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());
|
||||
let mut goals = Vec::with_capacity(4);
|
||||
if has_help {
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo));
|
||||
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
|
||||
}
|
||||
goals.push(tree);
|
||||
goals.push("-Dverbose".into());
|
||||
goals
|
||||
}
|
||||
|
||||
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
|
||||
@@ -367,25 +382,8 @@ pub fn sync_maven(
|
||||
verbose: true,
|
||||
..MavenCache::default()
|
||||
};
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read
|
||||
// from: `-Dmaven.repo.local=` first, then `<localRepository>` of the `-s` settings,
|
||||
// then the user's default repository (which `plugin()` resolves itself).
|
||||
let local_repo: Option<PathBuf> =
|
||||
options.maven_options.iter().find_map(|a| a.strip_prefix("-Dmaven.repo.local=")).map(PathBuf::from).or_else(
|
||||
|| {
|
||||
let mut args = options.maven_options.iter();
|
||||
while let Some(arg) = args.next() {
|
||||
let path = match arg.as_str() {
|
||||
"-s" | "--settings" => args.next().map(String::as_str),
|
||||
_ => arg.strip_prefix("-s=").or_else(|| arg.strip_prefix("--settings=")),
|
||||
};
|
||||
if let Some(path) = path {
|
||||
return maven::local_repository_of(Path::new(path));
|
||||
}
|
||||
}
|
||||
None
|
||||
},
|
||||
);
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read from.
|
||||
let repo = maven::local_repository_for(&options.maven_options);
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
for (n, top) in model.projects.iter().filter(|p| !p.aggregated).enumerate() {
|
||||
let effective = cache_dir.join(format!("effective-pom-{n}.xml"));
|
||||
@@ -407,7 +405,6 @@ pub fn sync_maven(
|
||||
if !options.profiles.is_empty() {
|
||||
args.push(format!("-P{}", options.profiles.join(",")));
|
||||
}
|
||||
let repo = local_repo.clone().or_else(maven::default_local_repo);
|
||||
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);
|
||||
@@ -425,7 +422,7 @@ pub fn sync_maven(
|
||||
}
|
||||
})?;
|
||||
let effective_projects = std::fs::read_to_string(&effective)
|
||||
.map(|t| maven::parse_effective_pom_in(&t, local_repo.as_deref()))
|
||||
.map(|t| maven::parse_effective_pom_in(&t, repo.as_deref()))
|
||||
.unwrap_or_default();
|
||||
let trees = maven::parse_dependency_tree(&out.text);
|
||||
for (key, plugins, deps) in effective_projects {
|
||||
@@ -810,12 +807,13 @@ mod tests {
|
||||
Some(gradle::ProcessedResources { task: "processResources".into(), dir: "/p/build/resources/main".into() })
|
||||
);
|
||||
let src = |p: &str| PathBuf::from(core_src(p));
|
||||
let core = PathBuf::from(format!("{b}/modules/core"));
|
||||
assert_eq!(
|
||||
gradle::reported_source_roots(&projects),
|
||||
[
|
||||
(src("main/java"), gradle::ReportedRoot::Source),
|
||||
(src("main/resources"), gradle::ReportedRoot::Resources),
|
||||
(src("test/java"), gradle::ReportedRoot::Test),
|
||||
(src("main/java"), gradle::ReportedRoot::Source, core.clone()),
|
||||
(src("main/resources"), gradle::ReportedRoot::Resources, core.clone()),
|
||||
(src("test/java"), gradle::ReportedRoot::Test, core),
|
||||
]
|
||||
);
|
||||
let mut model = gradle::load(&root).unwrap();
|
||||
@@ -953,11 +951,32 @@ mod tests {
|
||||
#[test]
|
||||
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, None);
|
||||
assert_eq!(online, ["help:effective-pom", "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
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()));
|
||||
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()));
|
||||
assert_eq!(offline[2], "dependency:tree");
|
||||
assert!(offline.contains(&"-Dverbose".to_owned()));
|
||||
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;
|
||||
// a repository with `maven-dependency-plugin` but no 3.x `maven-help-plugin` runs only the tree.
|
||||
for (artifact, version) in [("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] {
|
||||
let jar =
|
||||
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
|
||||
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()));
|
||||
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()));
|
||||
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();
|
||||
@@ -1029,7 +1048,7 @@ mod tests {
|
||||
let cache = tmp.path().join("cache");
|
||||
sync_maven(&root, &cache, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let args = std::fs::read_to_string(root.join("mvnw-args")).unwrap();
|
||||
assert!(args.contains("help:effective-pom"), "args: {args}");
|
||||
assert!(args.contains("maven-help-plugin:"), "args: {args}");
|
||||
let loaded = crate::load_linked(&root, &cache, None, &Default::default(), &Default::default());
|
||||
let maven = loaded.maven.unwrap();
|
||||
assert!(maven.synced_at.is_some() && maven.sync_error.is_none(), "{:?}", maven.sync_error);
|
||||
@@ -1054,6 +1073,6 @@ mod tests {
|
||||
let args = std::fs::read_to_string(root.join("mvnd-args")).unwrap();
|
||||
// `-T1` pins the daemon serial so the dependency trees stay parseable.
|
||||
assert!(args.contains("-T1"), "args: {args}");
|
||||
assert!(args.contains("help:effective-pom"), "args: {args}");
|
||||
assert!(args.contains("maven-help-plugin:"), "args: {args}");
|
||||
}
|
||||
}
|
||||
@@ -137,19 +137,16 @@ 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());
|
||||
probe.extend([
|
||||
"-f".into(),
|
||||
root.join(&p.pom).to_string_lossy().into_owned(),
|
||||
"help:evaluate".into(),
|
||||
evaluate.clone(),
|
||||
"-Dexpression=project.id".into(),
|
||||
format!("-Doutput={}", output.display()),
|
||||
]);
|
||||
args.extend([
|
||||
"-DskipTests".into(),
|
||||
"package".into(),
|
||||
"help:evaluate".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
args.extend(["-DskipTests".into(), "package".into(), evaluate, format!("-Doutput={}", manifest.display())]);
|
||||
return Ok(WebBuild {
|
||||
command: top.command.clone(),
|
||||
args,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
<artifactId>app</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,9 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
<artifactId>lib</artifactId>
|
||||
</project>
|
||||
@@ -0,0 +1,35 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
<packaging>pom</packaging>
|
||||
<modules>
|
||||
<module>lib</module>
|
||||
<module>app</module>
|
||||
</modules>
|
||||
<properties>
|
||||
<maven.compiler.release>11</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.4.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<parameters>true</parameters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-clipboard"
|
||||
description = "The OS clipboard's file list (Explorer <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB or macOS NSPasteboard, no window or message loop"
|
||||
description = "The OS clipboard's file list (file manager <-> project view) and pasted images: Windows CF_HDROP / PNG / CF_DIB, macOS NSPasteboard, Linux text/uri-list via GTK"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
use std::io::{Cursor, Error, ErrorKind, Result};
|
||||
|
||||
/// A top-down BITMAPV5HEADER and BGRA pixels. The alpha mask lets native paste targets
|
||||
/// retain transparency; the PNG flavor is also written for browsers and image editors.
|
||||
pub(crate) fn png_to_dib(png: &[u8]) -> Result<Vec<u8>> {
|
||||
let invalid = |error| Error::new(ErrorKind::InvalidData, error);
|
||||
let mut decoder = png::Decoder::new(Cursor::new(png));
|
||||
decoder.set_transformations(png::Transformations::normalize_to_color8());
|
||||
let mut reader = decoder.read_info().map_err(invalid)?;
|
||||
let rgba_size = (reader.info().width as usize)
|
||||
.checked_mul(reader.info().height as usize)
|
||||
.and_then(|pixels| pixels.checked_mul(4))
|
||||
.filter(|size| *size <= 64 * 1024 * 1024)
|
||||
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
|
||||
let size = reader
|
||||
.output_buffer_size()
|
||||
.filter(|size| *size <= 64 * 1024 * 1024)
|
||||
.ok_or_else(|| Error::new(ErrorKind::InvalidData, "Clipboard image is too large"))?;
|
||||
let mut pixels = vec![0; size];
|
||||
let info = reader.next_frame(&mut pixels).map_err(invalid)?;
|
||||
let mut dib = vec![0; 124];
|
||||
dib[0..4].copy_from_slice(&124u32.to_le_bytes());
|
||||
dib[4..8].copy_from_slice(&info.width.to_le_bytes());
|
||||
dib[8..12].copy_from_slice(&(-(info.height as i32)).to_le_bytes());
|
||||
dib[12..14].copy_from_slice(&1u16.to_le_bytes());
|
||||
dib[14..16].copy_from_slice(&32u16.to_le_bytes());
|
||||
dib[16..20].copy_from_slice(&3u32.to_le_bytes()); // BI_BITFIELDS
|
||||
dib[20..24].copy_from_slice(&(rgba_size as u32).to_le_bytes());
|
||||
for (at, value) in [(40, 0x00ff0000u32), (44, 0x0000ff00), (48, 0x000000ff), (52, 0xff000000), (56, 0x73524742)] {
|
||||
dib[at..at + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
dib[108..112].copy_from_slice(&4u32.to_le_bytes()); // LCS_GM_IMAGES
|
||||
for pixel in pixels[..info.buffer_size()].chunks_exact(info.color_type.samples()) {
|
||||
let rgba = match info.color_type {
|
||||
png::ColorType::Rgba => [pixel[0], pixel[1], pixel[2], pixel[3]],
|
||||
png::ColorType::Rgb => [pixel[0], pixel[1], pixel[2], 255],
|
||||
png::ColorType::Grayscale => [pixel[0], pixel[0], pixel[0], 255],
|
||||
png::ColorType::GrayscaleAlpha => [pixel[0], pixel[0], pixel[0], pixel[1]],
|
||||
png::ColorType::Indexed => unreachable!("palette expansion requested"),
|
||||
};
|
||||
dib.extend_from_slice(&[rgba[2], rgba[1], rgba[0], rgba[3]]);
|
||||
}
|
||||
Ok(dib)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn encode(color: png::ColorType, pixels: &[u8]) -> Vec<u8> {
|
||||
let mut png = Vec::new();
|
||||
{
|
||||
let mut encoder = png::Encoder::new(&mut png, 1, 2);
|
||||
encoder.set_color(color);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
encoder.write_header().unwrap().write_image_data(pixels).unwrap();
|
||||
}
|
||||
png
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_rgba_colors_alpha_and_top_down_row_order() {
|
||||
let png = encode(png::ColorType::Rgba, &[255, 0, 0, 128, 0, 255, 0, 255]);
|
||||
let dib = png_to_dib(&png).unwrap();
|
||||
assert_eq!(i32::from_le_bytes(dib[8..12].try_into().unwrap()), -2);
|
||||
assert_eq!(&dib[124..], &[0, 0, 255, 128, 0, 255, 0, 255]);
|
||||
let round_trip = crate::dib_to_png(&dib).unwrap();
|
||||
let mut reader = png::Decoder::new(Cursor::new(round_trip)).read_info().unwrap();
|
||||
let mut pixels = vec![0; reader.output_buffer_size().unwrap()];
|
||||
reader.next_frame(&mut pixels).unwrap();
|
||||
assert_eq!(pixels, [255, 0, 0, 128, 0, 255, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supports_rgb_and_grayscale_without_assuming_an_alpha_channel() {
|
||||
for (color, pixels, expected) in [
|
||||
(png::ColorType::Rgb, vec![255, 0, 0, 0, 255, 0], vec![0, 0, 255, 255, 0, 255, 0, 255]),
|
||||
(png::ColorType::Grayscale, vec![20, 200], vec![20, 20, 20, 255, 200, 200, 200, 255]),
|
||||
(png::ColorType::GrayscaleAlpha, vec![20, 10, 200, 250], vec![20, 20, 20, 10, 200, 200, 200, 250]),
|
||||
] {
|
||||
assert_eq!(&png_to_dib(&encode(color, &pixels)).unwrap()[124..], expected);
|
||||
}
|
||||
assert!(png_to_dib(b"not a PNG").is_err());
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,12 @@
|
||||
//! thread: AppKit and WebKit also access the general pasteboard there, and its
|
||||
//! mutable type cache cannot be protected by a mutex in this crate.
|
||||
//!
|
||||
//! Other platforms (`text/uri-list` on X11) are not wired up: [`files`] is
|
||||
//! empty and [`set_files`] fails there.
|
||||
//! Linux keeps it as `text/uri-list` (Dolphin, Nautilus and most file
|
||||
//! managers) or GNOME's `x-special/gnome-copied-files` (`copy` or `cut`, then
|
||||
//! one URI per line), read and written through the GTK clipboard on X11 and
|
||||
//! Wayland alike; [`request_files`] reads it without blocking the main loop.
|
||||
//! Other platforms are not wired up: [`files`] is empty and [`set_files`]
|
||||
//! fails there.
|
||||
//!
|
||||
//! [`png`] reads an image (a screenshot) for the project view's Paste, which
|
||||
//! saves it as a file: `public.png` or `public.tiff` on macOS, the registered
|
||||
@@ -25,15 +29,39 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
mod image;
|
||||
|
||||
/// Writes a PNG as a native image, independently of WebView clipboard permissions.
|
||||
/// Call on the main thread on macOS and Linux; `owner` is a window handle on Windows.
|
||||
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
|
||||
if png.get(..8) != Some(b"\x89PNG\r\n\x1a\n") || png.get(12..16) != Some(b"IHDR") || png.len() < 24 {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
|
||||
}
|
||||
let width = u32::from_be_bytes(png[16..20].try_into().unwrap()) as usize;
|
||||
let height = u32::from_be_bytes(png[20..24].try_into().unwrap()) as usize;
|
||||
if width == 0
|
||||
|| height == 0
|
||||
|| !width
|
||||
.checked_mul(height)
|
||||
.and_then(|pixels| pixels.checked_mul(4))
|
||||
.is_some_and(|size| size <= 64 * 1024 * 1024)
|
||||
{
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Clipboard image is too large"));
|
||||
}
|
||||
imp::set_png(png, owner)
|
||||
}
|
||||
|
||||
/// Replaces every clipboard flavor with plain text. `owner` is the calling window
|
||||
/// handle on Windows, ignored elsewhere. Call on the main thread on macOS and Linux.
|
||||
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
|
||||
imp::set_text(text, owner)
|
||||
}
|
||||
|
||||
/// The clipboard's plain text, None when it holds none. macOS only (main thread);
|
||||
/// Linux reads it asynchronously through GTK in the app, Windows through the WebView.
|
||||
#[cfg(target_os = "macos")]
|
||||
/// The clipboard's plain text. None when macOS holds none, or when Windows cannot
|
||||
/// open the clipboard; empty when Windows holds none. Call on the main thread on
|
||||
/// macOS; Linux reads it asynchronously through GTK in the app.
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
pub fn text() -> Option<String> {
|
||||
imp::text()
|
||||
}
|
||||
@@ -56,6 +84,7 @@ const HEADER: usize = 20;
|
||||
|
||||
/// The absolute paths on the clipboard, empty when it holds no file list.
|
||||
/// Read failures remain errors so callers can retain an internal copy.
|
||||
/// Empty on Linux, where [`request_files`] reads it.
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
imp::files()
|
||||
}
|
||||
@@ -78,7 +107,7 @@ pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
/// line. An editor paste inserts names, not the absolute paths the file list
|
||||
/// keeps for Explorer (#1878; IDEA's text flavor is names too). A path with no
|
||||
/// file name (a root like `C:\`) keeps its whole path.
|
||||
#[cfg(any(windows, target_os = "macos", test))]
|
||||
#[cfg(any(windows, target_os = "macos", target_os = "linux", test))]
|
||||
fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
paths
|
||||
.iter()
|
||||
@@ -89,6 +118,82 @@ fn names_text(paths: &[PathBuf], separator: &str) -> String {
|
||||
.join(separator)
|
||||
}
|
||||
|
||||
/// The `file://` URIs in a `text/uri-list` or `x-special/gnome-copied-files`
|
||||
/// payload as local paths: comments, the `copy`/`cut` line and URIs for other
|
||||
/// hosts or schemes are skipped.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn uri_list_paths(text: &str) -> Vec<PathBuf> {
|
||||
text.lines().map(str::trim).filter(|line| !line.starts_with('#')).filter_map(uri_to_path).collect()
|
||||
}
|
||||
|
||||
/// A local `file://` URI (`file:///a%20b` or `file://localhost/a%20b`) as a
|
||||
/// path; its percent-escapes are raw bytes, as GLib writes them.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn uri_to_path(uri: &str) -> Option<PathBuf> {
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let rest = uri.strip_prefix("file://")?;
|
||||
let path = if rest.starts_with('/') { rest } else { rest.strip_prefix("localhost")? };
|
||||
let path = path.split(['?', '#']).next()?;
|
||||
if !path.starts_with('/') {
|
||||
return None;
|
||||
}
|
||||
let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
|
||||
let bytes = path.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
let escaped =
|
||||
(bytes[i] == b'%').then(|| Some((hex(*bytes.get(i + 1)?)? << 4) | hex(*bytes.get(i + 2)?)?)).flatten();
|
||||
match escaped {
|
||||
Some(b) => {
|
||||
out.push(b);
|
||||
i += 3;
|
||||
}
|
||||
None => {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(PathBuf::from(std::ffi::OsString::from_vec(out)))
|
||||
}
|
||||
|
||||
/// `path` as a `file://` URI, every byte outside the unreserved set and `/`
|
||||
/// percent-escaped.
|
||||
#[cfg(any(target_os = "linux", all(test, unix)))]
|
||||
fn file_uri(path: &std::path::Path) -> String {
|
||||
use std::fmt::Write;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let mut uri = String::from("file://");
|
||||
for &b in path.as_os_str().as_bytes() {
|
||||
if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) {
|
||||
uri.push(b as char);
|
||||
} else {
|
||||
let _ = write!(uri, "%{b:02X}");
|
||||
}
|
||||
}
|
||||
uri
|
||||
}
|
||||
|
||||
/// Reads the clipboard's file list without blocking: `text/uri-list` first,
|
||||
/// then GNOME's list, and calls `done` with the paths (empty without a list).
|
||||
/// Call on the main thread; `done` runs there later.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn request_files(done: impl FnOnce(Vec<PathBuf>) + 'static) {
|
||||
use gtk::gdk::{Atom, SELECTION_CLIPBOARD};
|
||||
fn paths_in(data: >k::SelectionData) -> Vec<PathBuf> {
|
||||
// A failed request has a negative length and no data.
|
||||
if data.length() <= 0 { Vec::new() } else { uri_list_paths(&String::from_utf8_lossy(&data.data())) }
|
||||
}
|
||||
gtk::Clipboard::get(&SELECTION_CLIPBOARD).request_contents(&Atom::intern(imp::URI_LIST), move |board, data| {
|
||||
let paths = paths_in(data);
|
||||
if !paths.is_empty() {
|
||||
return done(paths);
|
||||
}
|
||||
board.request_contents(&Atom::intern(imp::GNOME_COPIED), move |_, data| done(paths_in(data)));
|
||||
});
|
||||
}
|
||||
|
||||
/// `DROPFILES` for `paths`, in the wide form so names outside the ANSI code
|
||||
/// page survive. Empty paths are skipped.
|
||||
pub fn encode(paths: &[PathBuf]) -> Vec<u8> {
|
||||
@@ -151,6 +256,15 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// A `CF_UNICODETEXT` block as a string: UTF-16LE up to the first NUL. The block
|
||||
/// may be larger than the text, and a malformed one may lack the NUL.
|
||||
#[cfg(any(windows, test))]
|
||||
fn unicode_text(bytes: &[u8]) -> String {
|
||||
let (pairs, _) = bytes.as_chunks::<2>();
|
||||
let units: Vec<u16> = pairs.iter().map(|&pair| u16::from_le_bytes(pair)).take_while(|&unit| unit != 0).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
|
||||
/// `BI_RGB` and `BI_BITFIELDS`: uncompressed pixels, the forms screenshots take.
|
||||
#[cfg(any(windows, test))]
|
||||
const BI_RGB: u32 = 0;
|
||||
@@ -206,7 +320,7 @@ fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
|
||||
|
||||
#[cfg(windows)]
|
||||
mod imp {
|
||||
use super::{HEADER, decode, dib_to_png, encode, names_text};
|
||||
use super::{HEADER, decode, dib_to_png, encode, names_text, unicode_text};
|
||||
use std::ffi::c_void;
|
||||
use std::path::PathBuf;
|
||||
use std::ptr;
|
||||
@@ -240,6 +354,7 @@ mod imp {
|
||||
/// `CF_DIB`: Windows synthesizes it from `CF_BITMAP` and `CF_DIBV5`, so every
|
||||
/// bitmap on the clipboard reads as one.
|
||||
const CF_DIB: u32 = 8;
|
||||
const CF_DIBV5: u32 = 17;
|
||||
|
||||
/// The `PNG` format browsers and the Snipping Tool add beside the bitmap; it
|
||||
/// keeps transparency, so it is read first.
|
||||
@@ -289,6 +404,19 @@ mod imp {
|
||||
image
|
||||
}
|
||||
|
||||
pub fn text() -> Option<String> {
|
||||
// Empty rather than None: a None falls back to the WebView, which prompts the user.
|
||||
if unsafe { IsClipboardFormatAvailable(CF_UNICODETEXT) } == 0 {
|
||||
return Some(String::new());
|
||||
}
|
||||
if !open() {
|
||||
return None;
|
||||
}
|
||||
let text = read_block(CF_UNICODETEXT).map(|bytes| unicode_text(&bytes));
|
||||
unsafe { CloseClipboard() };
|
||||
text
|
||||
}
|
||||
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn GlobalAlloc(flags: u32, bytes: usize) -> Handle;
|
||||
@@ -422,6 +550,48 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
|
||||
let dib = super::image::png_to_dib(png)?;
|
||||
let format = png_format();
|
||||
if format == 0 {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
let formats = [(format, png), (CF_DIBV5, dib.as_slice())];
|
||||
// SAFETY: allocations remain ours until SetClipboardData accepts them. Prepare both
|
||||
// before replacing the clipboard; free only allocations the OS did not take.
|
||||
unsafe {
|
||||
let mut blocks: Vec<_> = formats.iter().map(|(_, bytes)| global_bytes(bytes)).collect();
|
||||
if blocks.iter().any(|memory| memory.is_null()) || !open_for(owner as Handle) {
|
||||
let error = std::io::Error::last_os_error();
|
||||
for memory in blocks {
|
||||
if !memory.is_null() {
|
||||
GlobalFree(memory);
|
||||
}
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
let mut result = Ok(());
|
||||
if EmptyClipboard() == 0 {
|
||||
result = Err(std::io::Error::last_os_error());
|
||||
} else {
|
||||
for ((format, _), memory) in formats.iter().zip(&mut blocks) {
|
||||
if SetClipboardData(*format, *memory).is_null() {
|
||||
result = Err(std::io::Error::last_os_error());
|
||||
break;
|
||||
}
|
||||
*memory = ptr::null_mut();
|
||||
}
|
||||
}
|
||||
CloseClipboard();
|
||||
for memory in blocks {
|
||||
if !memory.is_null() {
|
||||
GlobalFree(memory);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
let bytes = encode(paths);
|
||||
if bytes.len() <= HEADER {
|
||||
@@ -489,7 +659,7 @@ mod imp {
|
||||
NSBitmapImageFileType, NSBitmapImageRep, NSPasteboard, NSPasteboardReadingOptionKey, NSPasteboardTypePNG,
|
||||
NSPasteboardTypeString, NSPasteboardTypeTIFF, NSPasteboardURLReadingFileURLsOnlyKey, NSPasteboardWriting,
|
||||
};
|
||||
use objc2_foundation::{NSArray, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use objc2_foundation::{NSArray, NSData, NSDictionary, NSNumber, NSString, NSURL};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::names_text;
|
||||
@@ -587,6 +757,23 @@ mod imp {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
let data = NSData::with_bytes(png);
|
||||
if NSBitmapImageRep::imageRepWithData(&data).is_none() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid clipboard image"));
|
||||
}
|
||||
let board = NSPasteboard::generalPasteboard();
|
||||
board.clearContents();
|
||||
if board.setData_forType(Some(&data), unsafe { NSPasteboardTypePNG }) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(std::io::Error::other("Cannot write clipboard image"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
debug_assert!(MainThreadMarker::new().is_some(), "NSPasteboard access requires the main thread");
|
||||
autoreleasepool(|_| {
|
||||
@@ -617,6 +804,21 @@ mod imp {
|
||||
mod imp {
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub fn set_png(png: &[u8], _owner: usize) -> std::io::Result<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let image = gtk::gdk_pixbuf::Pixbuf::from_read(std::io::Cursor::new(png.to_vec()))
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()))?;
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).set_image(&image);
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = png;
|
||||
Err(std::io::Error::other("Clipboard images are unavailable on this platform"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_text(text: &str, _owner: usize) -> std::io::Result<()> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
@@ -630,8 +832,25 @@ mod imp {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const URI_LIST: &str = "text/uri-list";
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const GNOME_COPIED: &str = "x-special/gnome-copied-files";
|
||||
|
||||
pub fn has_files() -> bool {
|
||||
false
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).wait_for_targets().is_some_and(|targets| {
|
||||
targets.into_iter().any(|target| {
|
||||
let name = target.name();
|
||||
name == URI_LIST || name == GNOME_COPIED
|
||||
})
|
||||
})
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_image() -> bool {
|
||||
@@ -649,6 +868,33 @@ mod imp {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Offers `paths` as `text/uri-list` (KDE and most file managers), GNOME's
|
||||
/// list (Nautilus, Thunar) and their names as text, rendered on request.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
use gtk::{TargetEntry, TargetFlags};
|
||||
let uris: Vec<String> = paths.iter().map(|p| super::file_uri(p)).collect();
|
||||
let uri_list: String = uris.iter().map(|uri| format!("{uri}\r\n")).collect();
|
||||
let gnome = format!("copy\n{}", uris.join("\n"));
|
||||
let names = super::names_text(paths, "\n");
|
||||
let entry = |name: &str, info: u32| TargetEntry::new(name, TargetFlags::empty(), info);
|
||||
let targets = [
|
||||
entry(URI_LIST, 0),
|
||||
entry(GNOME_COPIED, 1),
|
||||
entry("UTF8_STRING", 2),
|
||||
entry("text/plain;charset=utf-8", 2),
|
||||
entry("text/plain", 2),
|
||||
];
|
||||
gtk::Clipboard::get(>k::gdk::SELECTION_CLIPBOARD).set_with_data(&targets, move |_, data, info| match info {
|
||||
0 => data.set(&data.target(), 8, uri_list.as_bytes()),
|
||||
1 => data.set(&data.target(), 8, gnome.as_bytes()),
|
||||
_ => {
|
||||
let _ = data.set_text(&names);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn set_files(_paths: &[PathBuf]) -> bool {
|
||||
false
|
||||
}
|
||||
@@ -658,10 +904,51 @@ mod imp {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn invalid_or_oversized_images_are_rejected_before_accessing_the_clipboard() {
|
||||
assert!(set_png(b"not a PNG", 0).is_err());
|
||||
let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
|
||||
header.extend_from_slice(&100_000u32.to_be_bytes());
|
||||
header.extend_from_slice(&100_000u32.to_be_bytes());
|
||||
assert!(set_png(&header, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_text_stops_at_the_nul() {
|
||||
let mut bytes: Vec<u8> = "héllo\r\n世界".encode_utf16().chain([0, 0x41]).flat_map(u16::to_le_bytes).collect();
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
// No terminator, and a stray odd byte, still read the whole text.
|
||||
bytes.truncate(bytes.len() - 4);
|
||||
bytes.push(7);
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
}
|
||||
|
||||
fn paths(list: &[&str]) -> Vec<PathBuf> {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn file_manager_uri_lists_become_paths() {
|
||||
// Dolphin: CRLF-separated `text/uri-list`, with a comment line.
|
||||
let kde = "# copied\r\nfile:///home/u/a%20b.txt\r\nfile://localhost/home/u/%E6%A1%8C%E9%9D%A2\r\n";
|
||||
assert_eq!(uri_list_paths(kde), paths(&["/home/u/a b.txt", "/home/u/桌面"]));
|
||||
// Nautilus/Thunar: `copy` or `cut`, then one URI per line.
|
||||
assert_eq!(uri_list_paths("cut\nfile:///tmp/x\nfile:///tmp/y"), paths(&["/tmp/x", "/tmp/y"]));
|
||||
// Other hosts and schemes are not local files.
|
||||
assert!(uri_list_paths("file://server/share/x\nhttps://example.com/x\nsmb:///x").is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn written_uris_read_back_as_the_same_paths() {
|
||||
let list = paths(&["/home/u/a b#1%.txt", "/home/u/桌面/项目", "/tmp/plain-name_1.~"]);
|
||||
let uris: Vec<String> = list.iter().map(|p| file_uri(p)).collect();
|
||||
assert_eq!(uris[0], "file:///home/u/a%20b%231%25.txt");
|
||||
assert_eq!(uris[2], "file:///tmp/plain-name_1.~");
|
||||
assert_eq!(uri_list_paths(&uris.join("\r\n")), list);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_written_list_reads_back_unchanged() {
|
||||
let list = paths(&["C:/work/project/a.txt", "C:/work/project/sub"]);
|
||||
|
||||
@@ -15,12 +15,16 @@ specta.workspace = true
|
||||
specta-typescript.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio-util.workspace = true
|
||||
portable-pty.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
sha2 = "0.10"
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -0,0 +1,21 @@
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
|
||||
MIT License
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Bundled Windows console host
|
||||
|
||||
Unmodified files from Microsoft's MIT-licensed
|
||||
[Microsoft.Windows.Console.ConPTY 1.25.260930003](https://www.nuget.org/packages/Microsoft.Windows.Console.ConPTY/1.25.260930003).
|
||||
The system ConPTY on Windows 10 build 19045 consumes alternate-screen transitions; xterm then
|
||||
puts full-screen applications' redraws in normal scrollback. A current console host
|
||||
preserves those transitions, including while resizing and updating a running TUI.
|
||||
|
||||
The package is pinned, checked in and embedded by `ide-core`, so desktop, server,
|
||||
Run and debugger builds work offline and do not depend on another installed IDE.
|
||||
Only the target architecture is embedded, along with its MIT license. `src/pty.rs`
|
||||
extracts them atomically to a versioned user cache and preloads the DLL's absolute
|
||||
path before portable-pty initializes.
|
||||
Windows reuses that module when portable-pty loads `conpty.dll` by name. Loading
|
||||
failure is logged and falls back to the system backend. Windows builds before
|
||||
19041 also retain the system backend.
|
||||
|
||||
Source archive:
|
||||
`https://api.nuget.org/v3-flatcontainer/microsoft.windows.console.conpty/1.25.260930003/microsoft.windows.console.conpty.1.25.260930003.nupkg`
|
||||
|
||||
Archive SHA-256: `02b07b349af66d801159bdf9e440d4a1ce78bb951f37fc8609731665afdae7ee`
|
||||
|
||||
For each architecture, `conpty.dll` comes from
|
||||
`runtimes/win-<arch>/native/conpty.dll`, and `OpenConsole.exe` from
|
||||
`build/native/runtimes/<arch>/OpenConsole.exe` in that archive. Preserve the pair and
|
||||
the license when updating; update `VERSION` in `src/pty.rs` and these checksums too.
|
||||
|
||||
| File | SHA-256 |
|
||||
| --------------------- | ------------------------------------------------------------------ |
|
||||
| arm64/conpty.dll | `151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf` |
|
||||
| arm64/OpenConsole.exe | `4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f` |
|
||||
| x64/conpty.dll | `feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a` |
|
||||
| x64/OpenConsole.exe | `3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586` |
|
||||
| x86/conpty.dll | `d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93` |
|
||||
| x86/OpenConsole.exe | `e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3` |
|
||||
|
||||
Verification: `cargo test -p ide-core pty::`. `pty::checksums` checks the embedded files against the table above on every platform. The native PTY test launches a child
|
||||
console application and requires alternate-screen entry and exit to reach the
|
||||
reader; a system ConPTY that consumes them fails this check.
|
||||
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
Бінарний файл не відображається.
@@ -201,6 +201,7 @@ pub struct FoldingSettings {
|
||||
pub file_header: bool,
|
||||
pub imports: bool,
|
||||
pub doc_comments: bool,
|
||||
pub go_short_blocks: bool,
|
||||
}
|
||||
|
||||
impl Default for FoldingSettings {
|
||||
@@ -211,6 +212,7 @@ impl Default for FoldingSettings {
|
||||
file_header: true,
|
||||
imports: true,
|
||||
doc_comments: false,
|
||||
go_short_blocks: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -362,6 +364,8 @@ pub struct InlayHintsSettings {
|
||||
pub parameters: bool,
|
||||
/// Hints of other kinds (chaining, closing labels…).
|
||||
pub other: bool,
|
||||
/// The Dart server's closing labels (`// Column` after a widget's closing bracket).
|
||||
pub closing_labels: bool,
|
||||
pub disabled_languages: Vec<String>,
|
||||
/// Code vision as a whole (usages, author and language-server lenses); the switches below apply while it is on.
|
||||
pub code_vision: bool,
|
||||
@@ -394,6 +398,7 @@ impl Default for InlayHintsSettings {
|
||||
types: true,
|
||||
parameters: true,
|
||||
other: true,
|
||||
closing_labels: true,
|
||||
disabled_languages: Vec::new(),
|
||||
code_vision: true,
|
||||
code_vision_usages: true,
|
||||
@@ -481,6 +486,38 @@ pub struct LanguageCodeStyle {
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
/// Java: organize imports switches to a wildcard import once this many
|
||||
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
/// 5; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub class_count_to_use_import_with_star: Option<u32>,
|
||||
/// Java: organize imports switches to a wildcard static import once this
|
||||
/// many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
/// IDEA's default 3; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub names_count_to_use_static_import_with_star: Option<u32>,
|
||||
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub semicolons: Option<String>,
|
||||
/// JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub quotes: Option<String>,
|
||||
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub spaces: BTreeMap<String, bool>,
|
||||
/// JavaScript / TypeScript › Imports › Import paths:
|
||||
/// `shortest` | `relative` | `non-relative` | `project-relative`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier_ending: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_file_exclude_patterns: Vec<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_specifier_exclude_regexes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
@@ -538,6 +575,25 @@ pub struct EncodingSettings {
|
||||
pub native_to_ascii: bool,
|
||||
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
|
||||
pub utf8_bom: String,
|
||||
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
|
||||
/// relative to the project with `/` separators. The status bar's choice is kept here.
|
||||
#[serde(deserialize_with = "labels")]
|
||||
#[specta(type = BTreeMap<String, String>)]
|
||||
pub mappings: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
|
||||
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
|
||||
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
|
||||
return Ok(BTreeMap::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter_map(|(path, label)| match label {
|
||||
serde_json::Value::String(label) => Some((path, label)),
|
||||
_ => None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
impl Default for EncodingSettings {
|
||||
@@ -548,10 +604,30 @@ impl Default for EncodingSettings {
|
||||
properties: "iso-8859-1".into(),
|
||||
native_to_ascii: false,
|
||||
utf8_bom: "never".into(),
|
||||
mappings: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod encoding_mappings_tests {
|
||||
use super::EncodingSettings;
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_keep_the_entries_that_are_labels() {
|
||||
let json = serde_json::json!({
|
||||
"project": "gbk",
|
||||
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
|
||||
});
|
||||
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(settings.project, "gbk");
|
||||
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
|
||||
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
|
||||
assert!(not_a_table.mappings.is_empty());
|
||||
assert!(EncodingSettings::default().mappings.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod auto_import_tests {
|
||||
use super::{AutoImportSettings, ImportsOnPaste};
|
||||
|
||||
@@ -46,6 +46,8 @@ pub enum ErrorData {
|
||||
JavaBuildProblems {
|
||||
problems: Vec<String>,
|
||||
},
|
||||
/// A remote backend of another OpenIDEA build still serves the project and refused to retire.
|
||||
RemoteBackendBusy,
|
||||
}
|
||||
|
||||
/// Git's reported result for each destination ref. A remote with several push URLs can
|
||||
|
||||
@@ -13,13 +13,34 @@ use std::sync::Arc;
|
||||
|
||||
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
|
||||
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
|
||||
/// started or failed to.
|
||||
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
|
||||
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
|
||||
/// Run would, answered the same way.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum McpUiRequest {
|
||||
Confirm { client: String, tool: String, subject: String, project: String, detail: Option<String> },
|
||||
OpenFile { path: crate::IpcPath, line: Option<u32>, column: Option<u32> },
|
||||
AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap<String, String> },
|
||||
Confirm {
|
||||
client: String,
|
||||
tool: String,
|
||||
subject: String,
|
||||
project: String,
|
||||
detail: Option<String>,
|
||||
},
|
||||
OpenFile {
|
||||
path: crate::IpcPath,
|
||||
line: Option<u32>,
|
||||
column: Option<u32>,
|
||||
},
|
||||
AgentRun {
|
||||
name: String,
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
config: serde_json::Value,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -27,6 +48,10 @@ pub enum McpUiRequest {
|
||||
pub enum IdeEvent {
|
||||
/// Project data source settings changed; reload the Database tree.
|
||||
DbSourcesChanged,
|
||||
/// A Python run saved a matplotlib figure for the Plots tool window (a PNG file).
|
||||
PlotAdded {
|
||||
path: String,
|
||||
},
|
||||
McpRequest {
|
||||
id: u32,
|
||||
request: McpUiRequest,
|
||||
@@ -264,6 +289,20 @@ pub struct FlutterDevice {
|
||||
pub emulator: bool,
|
||||
/// The adb state keeping it from being used (`unauthorized`, `offline`, …).
|
||||
pub unavailable: Option<String>,
|
||||
/// The [`FlutterEmulator`] it runs on: an AVD name, or `apple_ios_simulator`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub emulator_id: Option<String>,
|
||||
}
|
||||
|
||||
/// An Android emulator (AVD) or the iOS Simulator that `flutter emulators --launch` can start.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FlutterEmulator {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// `android` or `ios`.
|
||||
pub platform_type: Option<String>,
|
||||
}
|
||||
|
||||
/// See [`FlutterDeviceList`].
|
||||
@@ -289,6 +328,10 @@ pub enum FlutterDaemonStatus {
|
||||
pub struct FlutterDeviceList {
|
||||
pub status: FlutterDaemonStatus,
|
||||
pub devices: Vec<FlutterDevice>,
|
||||
/// The emulators that no listed device runs on.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub emulators: Vec<FlutterEmulator>,
|
||||
}
|
||||
|
||||
/// See [`IdeEvent::Direnv`].
|
||||
|
||||
@@ -19,12 +19,14 @@ pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
pub mod memory;
|
||||
pub mod output_encoding;
|
||||
pub mod output_rate;
|
||||
pub mod platform;
|
||||
pub mod process;
|
||||
pub mod project_dir;
|
||||
pub mod project_env;
|
||||
pub mod project_roots;
|
||||
pub mod proxy_settings;
|
||||
pub mod pty;
|
||||
pub mod real_path;
|
||||
pub mod remote_settings;
|
||||
pub mod settings;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
//! How often the terminal and Run console pumps hand output to the UI, from
|
||||
//! Settings › Tools › Terminal › Max FPS (#5897). The frontend paints at most that
|
||||
//! often anyway; batching at half its frame interval keeps a fresh batch ready for
|
||||
//! every frame while cutting the IPC events (and their handling on the UI thread)
|
||||
//! that would only be buffered there.
|
||||
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Frames per second; 0 is Unlimited.
|
||||
static MAX_FPS: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
/// Applies the `terminal.maxFps` setting: `"unlimited"` or a number of frames per second.
|
||||
/// Running sessions pick it up at their next batch.
|
||||
pub fn set_max_fps(setting: &str) {
|
||||
MAX_FPS.store(setting.trim().parse::<u32>().unwrap_or(0), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The batch interval for a pump whose Unlimited interval is `unlimited`.
|
||||
pub fn batch_interval(unlimited: Duration) -> Duration {
|
||||
interval_for(MAX_FPS.load(Ordering::Relaxed), unlimited)
|
||||
}
|
||||
|
||||
/// Half the paint interval, within 4–200 ms, and never faster than the Unlimited rate.
|
||||
fn interval_for(fps: u32, unlimited: Duration) -> Duration {
|
||||
if fps == 0 {
|
||||
return unlimited;
|
||||
}
|
||||
Duration::from_millis((500 / u64::from(fps)).clamp(4, 200)).max(unlimited)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn interval_is_half_the_frame_and_clamped() {
|
||||
let terminal = Duration::from_millis(4);
|
||||
let run = Duration::from_millis(8);
|
||||
let ms = |fps, unlimited| interval_for(fps, unlimited).as_millis();
|
||||
assert_eq!(ms(0, terminal), 4, "Unlimited keeps the pump's own rate");
|
||||
assert_eq!(ms(0, run), 8);
|
||||
assert_eq!([60, 30, 15, 10, 5].map(|fps| ms(fps, terminal)), [8, 16, 33, 50, 100]);
|
||||
assert_eq!(ms(1, terminal), 200, "upper bound");
|
||||
assert_eq!(ms(1000, terminal), 4, "lower bound");
|
||||
assert_eq!(ms(1000, run), 8, "never faster than Unlimited");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_values_parse_and_unknown_means_unlimited() {
|
||||
set_max_fps("30");
|
||||
assert_eq!(batch_interval(Duration::from_millis(4)).as_millis(), 16);
|
||||
set_max_fps("unlimited");
|
||||
assert_eq!(batch_interval(Duration::from_millis(4)).as_millis(), 4);
|
||||
set_max_fps("fast");
|
||||
assert_eq!(batch_interval(Duration::from_millis(8)).as_millis(), 8);
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,33 @@ pub type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
|
||||
|
||||
struct Entry {
|
||||
root: PathBuf,
|
||||
direnv: Vec<(OsString, Option<OsString>)>,
|
||||
github_token: Option<OsString>,
|
||||
changes: Changes,
|
||||
loading: bool,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn new(root: PathBuf) -> Self {
|
||||
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
|
||||
}
|
||||
|
||||
fn rebuild(&mut self) {
|
||||
let mut combined = Vec::with_capacity(self.direnv.len() + usize::from(self.github_token.is_some()));
|
||||
if let Some(token) = &self.github_token {
|
||||
combined.push(("GH_TOKEN".into(), Some(token.clone())));
|
||||
}
|
||||
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
|
||||
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
|
||||
combined.extend(self.direnv.iter().cloned());
|
||||
self.changes = Arc::new(combined);
|
||||
}
|
||||
|
||||
fn is_idle_empty(&self) -> bool {
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
static ENTRIES: Mutex<Vec<Entry>> = Mutex::new(Vec::new());
|
||||
static SETTLED: Condvar = Condvar::new();
|
||||
|
||||
@@ -31,35 +54,103 @@ pub fn begin_loading(root: &Path) {
|
||||
let mut entries = entries();
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => entry.loading = true,
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }),
|
||||
None => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.loading = true;
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What children started in `root` (or below it) get on top of the IDE's own environment
|
||||
/// (`None`: removed). Ends a [`begin_loading`].
|
||||
/// What children started in `root` (or below it) get from direnv on top of the IDE's own
|
||||
/// environment (`None`: removed). Ends a [`begin_loading`].
|
||||
pub fn set(root: &Path, changes: Vec<(OsString, Option<OsString>)>) {
|
||||
let mut entries = entries();
|
||||
let changes = Arc::new(changes);
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => {
|
||||
entry.changes = changes;
|
||||
match entries.iter_mut().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv = changes;
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }),
|
||||
None if !changes.is_empty() => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.direnv = changes;
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays.
|
||||
pub fn settle(root: &Path) {
|
||||
if let Some(entry) = entries().iter_mut().find(|e| e.root == root) {
|
||||
entry.loading = false;
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
entries[idx].loading = false;
|
||||
if entries[idx].is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// `root` has no environment of its own any more (closed, or not trusted).
|
||||
/// `root` has no direnv environment of its own any more (no `.envrc`, closed, or not trusted).
|
||||
/// Preserves any project-scoped GitHub token until [`remove_all`] or [`set_github_token`].
|
||||
pub fn remove(root: &Path) {
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv.clear();
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Sets or clears the project-scoped `GH_TOKEN` injected for children started in `root`
|
||||
/// (unless overridden by `root`'s direnv `.envrc`). Returns whether the effective token changed.
|
||||
pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
|
||||
let token = token.filter(|t| !t.is_empty());
|
||||
let mut entries = entries();
|
||||
match entries.iter().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
if entries[idx].github_token == token {
|
||||
return false;
|
||||
}
|
||||
let entry = &mut entries[idx];
|
||||
entry.github_token = token;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
true
|
||||
}
|
||||
None => {
|
||||
let Some(token) = token else { return false };
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.github_token = Some(token);
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
|
||||
pub fn github_token(dir: &Path) -> Option<OsString> {
|
||||
find(&entries(), dir).and_then(|e| e.github_token.clone())
|
||||
}
|
||||
|
||||
/// Removes both direnv and project GitHub token entries for `root` (project closed or untrusted).
|
||||
pub fn remove_all(root: &Path) {
|
||||
entries().retain(|e| e.root != root);
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
@@ -135,4 +226,26 @@ mod tests {
|
||||
assert_eq!(*for_dir(root), [change("NEW", Some("2"))]);
|
||||
remove(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_token_survives_direnv_absence_and_yields_to_explicit_envrc_override() {
|
||||
let root = Path::new("/openidea-test-env/gh-project");
|
||||
let worktrees = Path::new("/openidea-test-env/gh-project.worktrees");
|
||||
assert!(set_github_token(root, Some("gho_work".into())));
|
||||
assert!(!set_github_token(root, Some("gho_work".into())), "idempotent");
|
||||
assert!(set_github_token(worktrees, Some("gho_work".into())));
|
||||
remove(root); // no `.envrc` in `root`
|
||||
assert_eq!(*for_dir(&root.join("src")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(*for_dir(&worktrees.join("task-1")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(github_token(&worktrees.join("task-1")), Some("gho_work".into()));
|
||||
|
||||
// An explicit `.envrc` GH_TOKEN overrides the project GitHub account token.
|
||||
set(root, vec![change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
assert_eq!(*for_dir(root), [change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
|
||||
remove_all(root);
|
||||
remove_all(worktrees);
|
||||
assert!(for_dir(root).is_empty());
|
||||
assert!(for_dir(worktrees).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
//! The PTY backend shared by terminals, Run consoles and debugger launchers.
|
||||
|
||||
pub fn native_pty_system() -> Box<dyn portable_pty::PtySystem + Send> {
|
||||
#[cfg(windows)]
|
||||
windows::initialize();
|
||||
portable_pty::native_pty_system()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use std::fs;
|
||||
use std::io::{self, Write};
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use windows_sys::Win32::Foundation::FreeLibrary;
|
||||
use windows_sys::Win32::System::LibraryLoader::{
|
||||
GetProcAddress, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
|
||||
};
|
||||
|
||||
const VERSION: &str = "1.25.260930003";
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"x64",
|
||||
include_bytes!("../resources/conpty/x64/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
|
||||
);
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"arm64",
|
||||
include_bytes!("../resources/conpty/arm64/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
|
||||
);
|
||||
#[cfg(target_arch = "x86")]
|
||||
const RUNTIME: (&str, &[u8], &[u8]) = (
|
||||
"x86",
|
||||
include_bytes!("../resources/conpty/x86/conpty.dll"),
|
||||
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
|
||||
);
|
||||
|
||||
pub(super) fn initialize() -> bool {
|
||||
static BUNDLED: OnceLock<bool> = OnceLock::new();
|
||||
*BUNDLED.get_or_init(|| {
|
||||
if !crate::platform::windows_build_number().is_some_and(|build| build >= 19041) {
|
||||
return false;
|
||||
}
|
||||
match load() {
|
||||
Ok(()) => true,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "bundled ConPTY unavailable; using the system terminal backend");
|
||||
false
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn load() -> io::Result<()> {
|
||||
let cache = dirs::cache_dir().ok_or_else(|| io::Error::other("no user cache directory"))?;
|
||||
let directory = cache.join("OpenIDEA").join("conpty").join(VERSION).join(RUNTIME.0);
|
||||
fs::create_dir_all(&directory)?;
|
||||
install(&directory.join("LICENSE.txt"), include_bytes!("../resources/conpty/LICENSE"))?;
|
||||
install(&directory.join("OpenConsole.exe"), RUNTIME.2)?;
|
||||
let library = directory.join("conpty.dll");
|
||||
install(&library, RUNTIME.1)?;
|
||||
let wide: Vec<u16> = library.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
// portable-pty 0.9 opens conpty.dll by name. Preload our verified absolute path:
|
||||
// Windows reuses this module, without adding the project directory to DLL search.
|
||||
// SAFETY: the path is terminated and the module is retained for the process lifetime.
|
||||
let module = unsafe {
|
||||
LoadLibraryExW(
|
||||
wide.as_ptr(),
|
||||
std::ptr::null_mut(),
|
||||
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32,
|
||||
)
|
||||
};
|
||||
if module.is_null() {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
for name in [c"CreatePseudoConsole", c"ResizePseudoConsole", c"ClosePseudoConsole"] {
|
||||
// SAFETY: `module` is loaded and each name is a terminated export name.
|
||||
if unsafe { GetProcAddress(module, name.as_ptr().cast()) }.is_none() {
|
||||
// SAFETY: no PTY uses this rejected module yet; release our load reference.
|
||||
unsafe { FreeLibrary(module) };
|
||||
return Err(io::Error::other("bundled ConPTY lacks the portable-pty exports"));
|
||||
}
|
||||
}
|
||||
// Keep this reference for the process lifetime, including between PTY sessions.
|
||||
tracing::info!(path = %library.display(), version = VERSION, "loaded bundled ConPTY");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn install(path: &Path, data: &[u8]) -> io::Result<()> {
|
||||
if fs::read(path).is_ok_and(|existing| existing == data) {
|
||||
return Ok(());
|
||||
}
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let pending =
|
||||
path.with_extension(format!("{}-{}.tmp", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let result = (|| {
|
||||
let mut file = fs::OpenOptions::new().write(true).create_new(true).open(&pending)?;
|
||||
file.write_all(data)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
match fs::rename(&pending, path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(_) if fs::read(path).is_ok_and(|existing| existing == data) => Ok(()),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
})();
|
||||
let _ = fs::remove_file(pending);
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn installs_atomically_and_repairs_incomplete_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("conpty.dll");
|
||||
fs::write(&path, b"partial").unwrap();
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..8 {
|
||||
let path = &path;
|
||||
scope.spawn(move || install(path, b"complete runtime").unwrap());
|
||||
}
|
||||
});
|
||||
assert_eq!(fs::read(&path).unwrap(), b"complete runtime");
|
||||
assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loads_the_bundled_backend() {
|
||||
assert!(initialize());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conpty_output_child() {
|
||||
if std::env::var_os("OPENIDEA_CONPTY_TEST_CHILD").is_none() {
|
||||
return;
|
||||
}
|
||||
use windows_sys::Win32::System::Console::{
|
||||
ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle, STD_OUTPUT_HANDLE, SetConsoleMode,
|
||||
};
|
||||
// SAFETY: the inherited console output handle and a local writable mode word.
|
||||
unsafe {
|
||||
let output = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||
let mut mode = 0;
|
||||
assert_ne!(GetConsoleMode(output, &mut mode), 0);
|
||||
assert_ne!(SetConsoleMode(output, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING), 0);
|
||||
}
|
||||
std::io::stdout()
|
||||
.write_all(b"\x1b[?1049h\x1b[2J\x1b[HWorking (3m 19s)\x1b[1;1H\x1b[2KWorking (2m 59s)\x1b[?1049l\r\nVT_DONE\r\n")
|
||||
.unwrap();
|
||||
std::io::stdout().flush().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conpty_preserves_alternate_screen_transitions() {
|
||||
use std::io::Read;
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
let pair = super::super::native_pty_system().openpty(portable_pty::PtySize::default()).unwrap();
|
||||
let mut reader = pair.master.try_clone_reader().unwrap();
|
||||
let mut writer = pair.master.take_writer().unwrap();
|
||||
let mut command = portable_pty::CommandBuilder::new(std::env::current_exe().unwrap());
|
||||
command.args(["--exact", "pty::windows::tests::conpty_output_child", "--nocapture"]);
|
||||
command.env("OPENIDEA_CONPTY_TEST_CHILD", "1");
|
||||
let mut child = pair.slave.spawn_command(command).unwrap();
|
||||
drop(pair.slave);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let reading = std::thread::spawn(move || {
|
||||
let mut bytes = [0; 4096];
|
||||
while let Ok(count) = reader.read(&mut bytes) {
|
||||
if count == 0 || tx.send(bytes[..count].to_vec()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
let mut output = Vec::new();
|
||||
let mut cursor_replied = false;
|
||||
while Instant::now() < deadline {
|
||||
if let Ok(bytes) = rx.recv_timeout(Duration::from_millis(50)) {
|
||||
output.extend_from_slice(&bytes);
|
||||
if !cursor_replied && output.windows(4).any(|s| s == b"\x1b[6n") {
|
||||
writer.write_all(b"\x1b[1;1R").unwrap();
|
||||
cursor_replied = true;
|
||||
}
|
||||
if output.windows(7).any(|s| s == b"VT_DONE") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
drop(writer);
|
||||
drop(pair.master);
|
||||
reading.join().unwrap();
|
||||
let output = String::from_utf8_lossy(&output);
|
||||
assert!(output.contains("\x1b[?1049h"), "alternate screen entry missing: {output:?}");
|
||||
assert!(output.contains("\x1b[?1049l"), "alternate screen exit missing: {output:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The embedded runtime is the pinned NuGet package's files (`resources/conpty/README.md`).
|
||||
#[cfg(test)]
|
||||
mod checksums {
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const FILES: [(&str, &[u8], &str); 6] = [
|
||||
(
|
||||
"arm64/conpty.dll",
|
||||
include_bytes!("../resources/conpty/arm64/conpty.dll"),
|
||||
"151a02355227710c20c9f8f1eaf68ac4668aa09cdc921adc7ec661804d8eb1bf",
|
||||
),
|
||||
(
|
||||
"arm64/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/arm64/OpenConsole.exe"),
|
||||
"4313825a3ba634d113cc6ed3bc8ce735e3c19d360cecd985794787479469f91f",
|
||||
),
|
||||
(
|
||||
"x64/conpty.dll",
|
||||
include_bytes!("../resources/conpty/x64/conpty.dll"),
|
||||
"feeef341d891643c62d30b6b07800bc70f0bc148f44cb8c3bee84aa557ae805a",
|
||||
),
|
||||
(
|
||||
"x64/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/x64/OpenConsole.exe"),
|
||||
"3d66b23d0a71bb8eed2b77edc8b9df9bf54ce6c8fb74c863a30e760997f80586",
|
||||
),
|
||||
(
|
||||
"x86/conpty.dll",
|
||||
include_bytes!("../resources/conpty/x86/conpty.dll"),
|
||||
"d145f621bf64a9da3b7395587ddef9831ca404805d8987ec8c9903d0c4603d93",
|
||||
),
|
||||
(
|
||||
"x86/OpenConsole.exe",
|
||||
include_bytes!("../resources/conpty/x86/OpenConsole.exe"),
|
||||
"e3e475547d57da0689dc9fc5e0101d10390e2a4719a6eb5dcad569f6cb33c1a3",
|
||||
),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn embedded_runtime_matches_the_pinned_package() {
|
||||
for (name, bytes, expected) in FILES {
|
||||
let actual: String = Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect();
|
||||
assert_eq!(actual, expected, "{name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,12 +95,24 @@ pub struct AgentSettings {
|
||||
pub show_usage_limits: bool,
|
||||
/// What the session has cost so far, as the agent reports it.
|
||||
pub show_cost: bool,
|
||||
/// A finished turn's work folds into one line under its message, leaving the reply.
|
||||
pub fold_turns: bool,
|
||||
/// Streaming text is revealed at a steady pace rather than chunk by chunk.
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
pub fit_window_width: bool,
|
||||
/// Chat text follows the interface font (Appearance › Use custom font).
|
||||
pub chat_use_ui_font: bool,
|
||||
/// Chat text family when it does not follow the interface font.
|
||||
pub chat_font_family: String,
|
||||
/// Covers characters the chat font lacks.
|
||||
pub chat_font_fallback: String,
|
||||
pub chat_font_size: u32,
|
||||
/// Code in chat follows the built-in code font.
|
||||
pub code_use_default_font: bool,
|
||||
/// Code family when it does not follow the built-in code font.
|
||||
pub code_font_family: String,
|
||||
/// Covers characters the code font lacks.
|
||||
pub code_font_fallback: String,
|
||||
pub code_font_size: u32,
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ThinkingDisplay)]
|
||||
pub thinking: ThinkingDisplay,
|
||||
@@ -145,9 +157,16 @@ impl Default for AgentSettings {
|
||||
show_work_time: true,
|
||||
show_usage_limits: true,
|
||||
show_cost: false,
|
||||
fold_turns: true,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
chat_use_ui_font: true,
|
||||
chat_font_family: "Inter".into(),
|
||||
chat_font_fallback: String::new(),
|
||||
chat_font_size: 13,
|
||||
code_use_default_font: true,
|
||||
code_font_family: "JetBrains Mono".into(),
|
||||
code_font_fallback: String::new(),
|
||||
code_font_size: 13,
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
tool_calls: ToolCallDisplay::Grouped,
|
||||
expand_tool_output: false,
|
||||
@@ -420,10 +439,10 @@ impl Default for McpServerSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Tools › Download sources: a mirror the installer tries when `github.com` is slow or
|
||||
/// unreachable.
|
||||
/// Tools › Download sources: mirrors the installer tries, in order, when `github.com` is slow
|
||||
/// or unreachable.
|
||||
///
|
||||
/// The mirror is a proxy prefix: the official URL is appended to it unchanged
|
||||
/// A mirror is a proxy prefix: the official URL is appended to it unchanged
|
||||
/// (`https://mirror.example/https://github.com/o/r/releases/download/…`), which is what the
|
||||
/// public GitHub proxies speak. Only `github.com` downloads are affected — those proxies
|
||||
/// hard-code that host, so Eclipse JDT LS and Open VSX keep their official addresses. Empty by
|
||||
@@ -431,9 +450,16 @@ impl Default for McpServerSettings {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ToolDownloadSettings {
|
||||
/// Proxy prefix prepended to `https://github.com/…` archive addresses only; empty keeps
|
||||
/// every download on its official host.
|
||||
/// Proxy prefixes prepended to `https://github.com/…` archive addresses only, separated by
|
||||
/// commas or whitespace and tried in order before the official host; empty keeps every
|
||||
/// download on its official host.
|
||||
pub github_mirror: String,
|
||||
/// Package registries only as configured (a company Nexus or Artifactory): npm and pnpm
|
||||
/// installs and update checks never retry against the public npm registry, and the IDE
|
||||
/// fetches nothing from public package registries itself (the JUnit Platform launcher from
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
}
|
||||
|
||||
/// Absent profiles retain automatic discovery for existing projects.
|
||||
@@ -826,6 +852,8 @@ pub struct AppearanceSettings {
|
||||
pub contrast_scrollbars: bool,
|
||||
/// Adjust colours for red-green vision deficiency.
|
||||
pub red_green_vision: bool,
|
||||
/// Turn off animations and transitions (also on when the OS asks for reduced motion).
|
||||
pub reduce_motion: bool,
|
||||
pub different_tool_window_background: bool,
|
||||
pub compact_mode: bool,
|
||||
/// IDEA "Use smaller indents in trees": tool window trees indent less per level.
|
||||
@@ -966,6 +994,7 @@ impl Default for AppearanceSettings {
|
||||
ui_font_fallback: String::new(),
|
||||
contrast_scrollbars: false,
|
||||
red_green_vision: false,
|
||||
reduce_motion: false,
|
||||
different_tool_window_background: false,
|
||||
compact_mode: false,
|
||||
small_tree_indents: false,
|
||||
@@ -1211,6 +1240,8 @@ pub struct LanguagesSettings {
|
||||
pub prettier: ExternalFormatterSettings,
|
||||
pub oxfmt: ExternalFormatterSettings,
|
||||
pub biome: ExternalFormatterSettings,
|
||||
/// dprint formats every file its configuration covers: `languages` is unused.
|
||||
pub dprint: ExternalFormatterSettings,
|
||||
pub ruff: ExternalFormatterSettings,
|
||||
pub black: ExternalFormatterSettings,
|
||||
pub java: JavaSettings,
|
||||
@@ -1218,6 +1249,7 @@ pub struct LanguagesSettings {
|
||||
pub markdown: MarkdownSettings,
|
||||
pub arduino: ArduinoSettings,
|
||||
pub zig: ZigSettings,
|
||||
pub flutter: FlutterSettings,
|
||||
}
|
||||
|
||||
impl Default for LanguagesSettings {
|
||||
@@ -1236,6 +1268,7 @@ impl Default for LanguagesSettings {
|
||||
languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(),
|
||||
..ExternalFormatterSettings::default()
|
||||
},
|
||||
dprint: ExternalFormatterSettings { languages: Vec::new(), ..ExternalFormatterSettings::default() },
|
||||
ruff: ExternalFormatterSettings {
|
||||
languages: vec!["python".into()],
|
||||
..ExternalFormatterSettings::default()
|
||||
@@ -1249,6 +1282,7 @@ impl Default for LanguagesSettings {
|
||||
markdown: MarkdownSettings::default(),
|
||||
arduino: ArduinoSettings::default(),
|
||||
zig: ZigSettings::default(),
|
||||
flutter: FlutterSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1312,6 +1346,7 @@ impl LanguagesSettings {
|
||||
ExternalFormatter::Prettier => &self.prettier,
|
||||
ExternalFormatter::Oxfmt => &self.oxfmt,
|
||||
ExternalFormatter::Biome => &self.biome,
|
||||
ExternalFormatter::Dprint => &self.dprint,
|
||||
ExternalFormatter::Ruff => &self.ruff,
|
||||
ExternalFormatter::Black => &self.black,
|
||||
}
|
||||
@@ -1325,6 +1360,7 @@ pub enum ExternalFormatter {
|
||||
Prettier,
|
||||
Oxfmt,
|
||||
Biome,
|
||||
Dprint,
|
||||
Ruff,
|
||||
Black,
|
||||
}
|
||||
@@ -1336,6 +1372,7 @@ impl ExternalFormatter {
|
||||
Self::Prettier => "prettier",
|
||||
Self::Oxfmt => "oxfmt",
|
||||
Self::Biome => "biome",
|
||||
Self::Dprint => "dprint",
|
||||
Self::Ruff => "ruff",
|
||||
Self::Black => "black",
|
||||
}
|
||||
@@ -1346,11 +1383,11 @@ impl ExternalFormatter {
|
||||
pub const BIOME_LANGUAGES: [&str; 8] =
|
||||
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
|
||||
|
||||
/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats.
|
||||
/// An external formatter (Prettier, oxfmt, Biome, dprint, Ruff, Black) and the languages it formats.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ExternalFormatterSettings {
|
||||
/// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH.
|
||||
/// Empty path: project node_modules (Prettier/oxfmt/Biome/dprint), managed installation, then PATH.
|
||||
pub path: String,
|
||||
/// Ruff only: directory containing its configuration, or a configuration file.
|
||||
pub configuration_directory: String,
|
||||
@@ -1411,6 +1448,15 @@ pub struct PythonSettings {
|
||||
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
|
||||
/// by interpreter executable; absolute or `~/`.
|
||||
pub interpreter_paths: BTreeMap<String, Vec<String>>,
|
||||
/// 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`.
|
||||
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.
|
||||
pub show_plots_in_tool_window: bool,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1423,6 +1469,9 @@ impl Default for PythonSettings {
|
||||
hide_other_project_interpreters: false,
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
test_runner: "auto".into(),
|
||||
profiler: "auto".into(),
|
||||
show_plots_in_tool_window: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1515,6 +1564,15 @@ pub struct ZigSettings {
|
||||
pub zig: String,
|
||||
}
|
||||
|
||||
/// The Flutter plugin's "Flutter SDK path".
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FlutterSettings {
|
||||
/// Flutter SDK root (holding `bin/flutter`); its `flutter` and Dart replace the ones on
|
||||
/// `PATH`. Empty = `PATH`.
|
||||
pub sdk: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GoSettings {
|
||||
@@ -1657,6 +1715,20 @@ pub struct MavenSettings {
|
||||
/// Always update snapshots (`-U`): Maven checks remote repositories for newer SNAPSHOT
|
||||
/// dependencies on every sync, build and run, and jdtls on import (`java.maven.updateSnapshots`).
|
||||
pub update_snapshots: bool,
|
||||
/// Who runs the JUnit 5 tests of the gutter's Run / Debug.
|
||||
pub run_tests_using: MavenRunTestsUsing,
|
||||
}
|
||||
|
||||
/// Build Tools › Maven › Run tests using. IDEA runs a Maven project's tests itself unless its build
|
||||
/// and run actions are delegated to Maven.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MavenRunTestsUsing {
|
||||
/// OpenIDEA's JUnit Platform runner on the language server's test classpath (`java/junit-runner`).
|
||||
#[default]
|
||||
Ide,
|
||||
/// Surefire (`mvn test -Dtest=…`).
|
||||
Maven,
|
||||
}
|
||||
|
||||
impl MavenSettings {
|
||||
@@ -1698,11 +1770,14 @@ pub struct TypeScriptSettings {
|
||||
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
|
||||
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
|
||||
pub tsserver_max_memory: u32,
|
||||
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
|
||||
/// `tsconfig.json` reports the errors of files that are not open.
|
||||
pub watch_problems: bool,
|
||||
}
|
||||
|
||||
impl Default for TypeScriptSettings {
|
||||
fn default() -> Self {
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0 }
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2095,7 +2170,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn agent_meters_default_and_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"agents":{"showCost":true}}"#).unwrap();
|
||||
let old: Settings = serde_json::from_str(r#"{"agents":{"showCost":true,"foldTurns":true}}"#).unwrap();
|
||||
assert!(old.agents.show_cost);
|
||||
assert!(old.agents.show_context_usage && old.agents.show_work_time && old.agents.show_usage_limits);
|
||||
assert!(!old.agents.fit_window_width);
|
||||
@@ -2318,6 +2393,7 @@ mod maven_linkage_tests {
|
||||
let old: MavenSettings = serde_json::from_str(r#"{"home":"/opt/maven"}"#).unwrap();
|
||||
assert!(old.runner_jre.is_empty());
|
||||
assert!(!old.delegate_build);
|
||||
assert_eq!(old.run_tests_using, MavenRunTestsUsing::Ide);
|
||||
assert!(MavenSettings::default().runner_jre.is_empty());
|
||||
let settings = MavenSettings { runner_jre: "/opt/jdk-21".into(), delegate_build: true, ..old };
|
||||
let encoded = serde_json::to_string(&settings).unwrap();
|
||||
|
||||
@@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
|
||||
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
|
||||
}
|
||||
|
||||
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
|
||||
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
|
||||
/// only when installed, then the user's `PATH`), and standard OS install locations.
|
||||
pub fn find_gh_executable() -> Option<PathBuf> {
|
||||
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
|
||||
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
|
||||
}
|
||||
|
||||
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
|
||||
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
|
||||
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
|
||||
return Some(explicit);
|
||||
}
|
||||
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
|
||||
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
|
||||
return Some(explicit.to_path_buf());
|
||||
}
|
||||
if let Some(found) = find_command("gh", search, Path::new("")) {
|
||||
return Some(found);
|
||||
}
|
||||
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
fn is_executable(path: &Path) -> bool {
|
||||
let Ok(metadata) = path.metadata() else { return false };
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -25,6 +25,17 @@ pub struct VcsSettings {
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
/// Directory Mappings: repository roots added to or excluded from the detected ones.
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GithubSettings {
|
||||
/// GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project.
|
||||
/// Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected).
|
||||
pub account: String,
|
||||
}
|
||||
|
||||
/// Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
@@ -68,6 +79,7 @@ impl Default for VcsSettings {
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-coverage"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo XML)"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Cobertura XML reports (`coverage xml` of coverage.py, and many other tools):
|
||||
//!
|
||||
//! ```xml
|
||||
//! <coverage>
|
||||
//! <sources><source>/home/runner/work/app/app</source></sources>
|
||||
//! <packages><package name="calc"><classes>
|
||||
//! <class filename="src/calc/__init__.py">
|
||||
//! <methods/>
|
||||
//! <lines>
|
||||
//! <line number="2" hits="1" branch="true" condition-coverage="50% (1/2)"/>
|
||||
//! ```
|
||||
//!
|
||||
//! A relative `filename` belongs to the first `<source>` it exists under, else to the
|
||||
//! first `<source>` (whose path may be another machine's; the importer relocates it).
|
||||
//! Lines repeated under `<methods>` are skipped so their hits don't count twice.
|
||||
|
||||
use crate::Accumulator;
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
use quick_xml::{Reader, XmlVersion};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn attr(e: &BytesStart, name: &str) -> Option<String> {
|
||||
e.attributes()
|
||||
.flatten()
|
||||
.find(|a| a.key.as_ref() == name)
|
||||
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok())
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
/// `"50% (1/2)"` → `(1, 2)`.
|
||||
fn conditions(text: &str) -> Option<(u32, u32)> {
|
||||
let (_, rest) = text.split_once('(')?;
|
||||
let (covered, total) = rest.trim_end_matches(')').split_once('/')?;
|
||||
Some((covered.trim().parse().ok()?, total.trim().parse().ok()?))
|
||||
}
|
||||
|
||||
/// `sources` pairs each `<source>` with whether it exists here (asked once: another
|
||||
/// machine's `/home/…` is slow to look up on macOS).
|
||||
fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf {
|
||||
let p = Path::new(filename);
|
||||
if p.has_root() {
|
||||
return p.to_path_buf();
|
||||
}
|
||||
sources
|
||||
.iter()
|
||||
.filter(|(_, here)| *here)
|
||||
.map(|(s, _)| s.join(p))
|
||||
.find(|c| c.is_file())
|
||||
.unwrap_or_else(|| sources.first().map_or_else(|| base.join(p), |(s, _)| s.join(p)))
|
||||
}
|
||||
|
||||
/// 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();
|
||||
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
|
||||
let mut source: Option<String> = None;
|
||||
let mut file: Option<PathBuf> = None;
|
||||
let mut in_methods = false;
|
||||
loop {
|
||||
match reader.read_event()? {
|
||||
Event::Start(e) if e.name().as_ref() == "methods" => in_methods = true,
|
||||
Event::Start(e) | Event::Empty(e) => match e.name().as_ref() {
|
||||
"source" => source = Some(String::new()),
|
||||
"class" => {
|
||||
let path = resolve(&attr(&e, "filename").unwrap_or_default(), &sources, base);
|
||||
acc.file(&path);
|
||||
file = Some(path);
|
||||
}
|
||||
"line" if !in_methods => {
|
||||
let Some(path) = &file else { continue };
|
||||
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")
|
||||
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
|
||||
{
|
||||
acc.has_branches = true;
|
||||
for i in 0..total {
|
||||
acc.branch(path, line, i.to_string(), i < covered);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Event::Text(t) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push_str(t.as_ref());
|
||||
}
|
||||
}
|
||||
Event::GeneralRef(r) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push('&');
|
||||
s.push_str(r.as_ref());
|
||||
s.push(';');
|
||||
}
|
||||
}
|
||||
Event::End(e) => match e.name().as_ref() {
|
||||
"source" => {
|
||||
let raw = source.take().unwrap_or_default();
|
||||
let text = quick_xml::escape::unescape(raw.trim()).map(|t| t.into_owned()).unwrap_or(raw);
|
||||
if !text.is_empty() {
|
||||
let path = Path::new(&text);
|
||||
// Joining a drive-less foreign root on Windows would add the checkout's drive.
|
||||
let dir = if path.has_root() { path.to_path_buf() } else { base.join(path) };
|
||||
let here = dir.is_dir();
|
||||
sources.push((dir, here));
|
||||
}
|
||||
}
|
||||
"methods" => in_methods = false,
|
||||
"class" => file = None,
|
||||
_ => {}
|
||||
},
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(acc)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_lines_branches_and_skips_method_lines() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let second = tmp.path().join("b&c");
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
std::fs::write(second.join("m.py"), "").unwrap();
|
||||
let xml = format!(
|
||||
r#"<?xml version="1.0" ?>
|
||||
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">
|
||||
<coverage><sources><source>/elsewhere/a</source><source>{}</source></sources>
|
||||
<packages><package name="p"><classes>
|
||||
<class name="m" filename="m.py">
|
||||
<methods><method name="f"><lines><line number="2" hits="5"/></lines></method></methods>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="5" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
<class name="n" filename="n.py"><lines><line number="1" hits="0"/></lines></class>
|
||||
<class name="abs" filename="/abs/x.py"><lines><line number="7" hits="2"/></lines></class>
|
||||
</classes></package></packages></coverage>"#,
|
||||
tmp.path().join("b&c").display()
|
||||
);
|
||||
let suite = parse(&xml, tmp.path()).unwrap().finish("Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
assert_eq!(suite.files.len(), 3);
|
||||
let file = |path: &Path| suite.files.iter().find(|f| f.path.as_ref() as &Path == path).unwrap();
|
||||
// `m.py` exists under the second source; `n.py` falls back to the first.
|
||||
let m = file(&second.join("m.py"));
|
||||
assert_eq!(file(Path::new("/elsewhere/a/n.py")).lines[0].hits, 0);
|
||||
assert_eq!(
|
||||
m.lines.iter().map(|l| (l.line, l.hits, l.branches_total, l.branches_covered)).collect::<Vec<_>>(),
|
||||
[(0, 1, 0, 0), (1, 5, 2, 1), (2, 0, 0, 0)]
|
||||
);
|
||||
assert!(m.lines[1].partial());
|
||||
assert_eq!(file(Path::new("/abs/x.py")).lines[0].line, 6);
|
||||
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
|
||||
}
|
||||
|
||||
#[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>"#;
|
||||
let suite = parse(xml, Path::new("/root")).unwrap().finish("Cobertura");
|
||||
assert_eq!(suite.files[0].path.as_ref() as &Path, Path::new("/root/a/b.py"));
|
||||
assert!(!suite.has_branches);
|
||||
assert_eq!(conditions("100% (4/4)"), Some((4, 4)));
|
||||
assert_eq!(conditions("100%"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! coverage.py data files (`.coverage`, and `.coverage.*` of parallel runs): SQLite databases of
|
||||
//! executed lines and arcs. Which lines are statements, excluded or branches only comes from
|
||||
//! analysing the source, so coverage.py in the project's interpreter combines the data into a
|
||||
//! scratch file (`[paths]` of the project's configuration applies) and writes Cobertura XML.
|
||||
|
||||
use crate::{CoverageSuite, cobertura};
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::ffi::OsStr;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const COVERAGE_PY: CliTool = CliTool::new("coverage.py", Decoding::ToolOutput);
|
||||
/// Analysing a large project's sources takes a while; a `[run] plugins` that hangs must not
|
||||
/// block the import for good.
|
||||
const TIMEOUT: Duration = Duration::from_secs(600);
|
||||
/// Files of the combined data (`relative_files` keeps them relative to the directory it ran in).
|
||||
const MEASURED: &str = "import sys, json, coverage\n\
|
||||
d = coverage.CoverageData(sys.argv[1]); d.read(); print(json.dumps(sorted(d.measured_files())))";
|
||||
/// The files coverage.py reads its configuration from, in the directory it runs in.
|
||||
const CONFIG_FILES: [&str; 4] = [".coveragerc", "setup.cfg", "tox.ini", "pyproject.toml"];
|
||||
|
||||
/// Whether `path` is an SQLite database (coverage.py 5+ data).
|
||||
pub fn is_data_file(path: &Path) -> bool {
|
||||
let mut head = [0u8; 16];
|
||||
std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && &head == b"SQLite format 3\0"
|
||||
}
|
||||
|
||||
/// `path`, or every `.coverage.*` file next to it when it is one of a parallel run's.
|
||||
fn inputs(path: &Path) -> Vec<PathBuf> {
|
||||
let parallel = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage."));
|
||||
let mut files: Vec<PathBuf> = match (parallel, path.parent()) {
|
||||
(true, Some(dir)) => std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| {
|
||||
p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage.")) && is_data_file(p)
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if files.is_empty() {
|
||||
files.push(path.to_path_buf());
|
||||
}
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
/// Where coverage.py ran: the nearest directory of `path` inside `root` with a coverage.py
|
||||
/// configuration file (a monorepo's `backend/pyproject.toml`), else `root`.
|
||||
fn run_dir(path: &Path, root: &Path) -> PathBuf {
|
||||
path.ancestors()
|
||||
.skip(1)
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find(|d| CONFIG_FILES.iter().any(|f| d.join(f).is_file()))
|
||||
.unwrap_or(root)
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
/// Runs `python -W ignore <args>` in `dir` and returns its stdout. Python warnings are
|
||||
/// ignored so `PYTHONWARNINGS=error` can't turn coverage.py's warnings into failures.
|
||||
fn python(python: &Path, dir: &Path, args: &[&OsStr]) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(python);
|
||||
cmd.current_dir(dir).args(["-W", "ignore"]).args(args);
|
||||
let out = COVERAGE_PY.run(cmd, TIMEOUT, None)?;
|
||||
if out.success {
|
||||
return Ok(out.stdout);
|
||||
}
|
||||
let text = if out.stderr.trim().is_empty() { out.stdout } else { out.stderr };
|
||||
let text = text.trim();
|
||||
if text.contains("No module named coverage") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py in the project's interpreter ({}). Install it, or import the output of `coverage xml`.",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
if text.contains("no such option") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py 6.3 or later in the project's interpreter ({}): {text}",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
Err(IdeError::invalid(format!("coverage.py could not read the data: {text}")))
|
||||
}
|
||||
|
||||
/// Reads the data file at `path` with `python`'s coverage.py, run where the project's coverage.py
|
||||
/// configuration is; `out` holds the scratch files. Blocking.
|
||||
pub(crate) fn import(path: &Path, root: &Path, python_path: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
let dir = run_dir(path, root);
|
||||
let data = out.join(".coverage");
|
||||
let xml = out.join("coverage.xml");
|
||||
let coverage = |args: &[&OsStr]| {
|
||||
let mut all: Vec<&OsStr> = vec!["-m".as_ref(), "coverage".as_ref()];
|
||||
all.extend(args);
|
||||
python(python_path, &dir, &all)
|
||||
};
|
||||
let inputs = inputs(path);
|
||||
let mut args: Vec<&OsStr> = vec!["combine".as_ref(), "--keep".as_ref(), "--data-file".as_ref(), data.as_ref()];
|
||||
args.extend(inputs.iter().map(|p| p.as_os_str()));
|
||||
coverage(&args)?;
|
||||
// `-i`: report what has source here instead of failing on the first file that has none.
|
||||
// `--fail-under=0`: a `[report] fail_under` the data misses must not fail the import.
|
||||
coverage(&[
|
||||
"xml".as_ref(),
|
||||
"-i".as_ref(),
|
||||
"--fail-under=0".as_ref(),
|
||||
"--data-file".as_ref(),
|
||||
data.as_ref(),
|
||||
"-o".as_ref(),
|
||||
xml.as_ref(),
|
||||
])?;
|
||||
let text = std::fs::read_to_string(&xml)?;
|
||||
let mut acc = cobertura::parse(&text, &dir).map_err(|e| IdeError::invalid(format!("{}: {e}", xml.display())))?;
|
||||
// The files the report left out (no source here): listed without lines.
|
||||
let measured = python(python_path, &dir, &["-c".as_ref(), MEASURED.as_ref(), data.as_ref()])?;
|
||||
let measured: Vec<PathBuf> = serde_json::from_str(measured.trim())
|
||||
.map_err(|e| IdeError::invalid(format!("coverage.py listed the measured files unreadably: {e}")))?;
|
||||
for file in measured {
|
||||
acc.file(&dir.join(file));
|
||||
}
|
||||
Ok(acc.finish("coverage.py"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_the_files_of_a_parallel_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let db = |name: &str| {
|
||||
let p = tmp.path().join(name);
|
||||
std::fs::write(&p, b"SQLite format 3\0rest").unwrap();
|
||||
p
|
||||
};
|
||||
let a = db(".coverage.host.1.x");
|
||||
let b = db(".coverage.host.2.y");
|
||||
let single = db(".coverage");
|
||||
std::fs::write(tmp.path().join(".coverage.notes"), "text").unwrap();
|
||||
std::fs::write(tmp.path().join(".coveragerc"), "[run]\n").unwrap();
|
||||
assert!(is_data_file(&a) && !is_data_file(&tmp.path().join(".coveragerc")));
|
||||
assert_eq!(inputs(&a), [a.clone(), b]);
|
||||
assert_eq!(inputs(&single), [single]);
|
||||
}
|
||||
|
||||
/// Two parallel runs recorded on another machine (`…/ci/app`), mapped by the project's `[paths]`.
|
||||
/// Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn combines_parallel_data_with_the_projects_paths() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// coverage.py reports real paths (`/private/var/…` for macOS's `/var/…`).
|
||||
let base = tmp.path().canonicalize().unwrap();
|
||||
let ci = base.join("ci/app");
|
||||
let root = base.join("project");
|
||||
let calc = "def sign(n):\n if n < 0:\n return -1\n return 1\n";
|
||||
for dir in [&ci, &root] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join("calc.py"), calc).unwrap();
|
||||
}
|
||||
std::fs::write(ci.join("gone.py"), "x = 1\n").unwrap();
|
||||
std::fs::write(ci.join("neg.py"), "import calc, gone\ncalc.sign(-1)\n").unwrap();
|
||||
std::fs::write(ci.join("pos.py"), "import calc\ncalc.sign(1)\n").unwrap();
|
||||
for script in ["neg.py", "pos.py"] {
|
||||
let ok = Command::new("python3")
|
||||
.current_dir(&ci)
|
||||
.args(["-m", "coverage", "run", "--branch", "--parallel-mode", script])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(ok.success());
|
||||
}
|
||||
let data = root.join("data");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
for e in std::fs::read_dir(&ci).unwrap().flatten() {
|
||||
if e.file_name().to_string_lossy().starts_with(".coverage.") {
|
||||
std::fs::rename(e.path(), data.join(e.file_name())).unwrap();
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&ci).unwrap();
|
||||
std::fs::write(root.join(".coveragerc"), "[paths]\nsource =\n ./\n */ci/app/\n").unwrap();
|
||||
let first = std::fs::read_dir(&data).unwrap().flatten().next().unwrap().path();
|
||||
let out = base.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&first, &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("calc.py")).unwrap();
|
||||
// Both runs together take both branches of line 2.
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (4, 4, 2, 2));
|
||||
// The scripts and `gone.py` have no source in the project: listed without lines.
|
||||
let empty: Vec<&str> = suite
|
||||
.files
|
||||
.iter()
|
||||
.filter(|f| f.lines.is_empty())
|
||||
.filter_map(|f| (f.path.as_ref() as &Path).file_name()?.to_str())
|
||||
.collect();
|
||||
assert_eq!(empty, ["gone.py", "neg.py", "pos.py"]);
|
||||
// They keep the recorded path, so the import notification counts them as not in the project.
|
||||
assert!(suite.files.iter().filter(|f| f.lines.is_empty()).all(|f| (f.path.as_ref() as &Path).starts_with(&ci)));
|
||||
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 2, "the user's data files are kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_where_the_coverage_configuration_is() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir_all(root.join("backend/reports")).unwrap();
|
||||
std::fs::create_dir_all(root.join("data")).unwrap();
|
||||
std::fs::write(root.join("backend/pyproject.toml"), "").unwrap();
|
||||
assert_eq!(run_dir(&root.join("backend/reports/.coverage"), root), root.join("backend"));
|
||||
assert_eq!(run_dir(&root.join("data/.coverage"), root), root);
|
||||
// A data file outside the project runs in the project.
|
||||
assert_eq!(run_dir(Path::new("/elsewhere/.coverage"), root), root);
|
||||
}
|
||||
|
||||
/// A stand-in interpreter that prints `stderr` and exits with `code`.
|
||||
#[cfg(unix)]
|
||||
fn fake_python(dir: &Path, stderr: &str, code: i32) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let p = dir.join("python");
|
||||
std::fs::write(&p, format!("#!/bin/sh\necho '{stderr}' >&2\nexit {code}\n")).unwrap();
|
||||
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn reports_why_coverage_py_failed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let data = tmp.path().join(".coverage");
|
||||
let err = |stderr: &str| {
|
||||
let python = fake_python(tmp.path(), stderr, 1);
|
||||
import(&data, tmp.path(), &python, tmp.path()).unwrap_err().to_string()
|
||||
};
|
||||
assert!(err("No module named coverage").contains("needs coverage.py in the project's interpreter"));
|
||||
assert!(err("no such option: --data-file").contains("needs coverage.py 6.3 or later"));
|
||||
assert!(err("No usable data files").contains("coverage.py could not read the data: No usable data files"));
|
||||
}
|
||||
|
||||
/// A monorepo member's data recorded with `relative_files`, below its `fail_under`, with
|
||||
/// coverage.py's warnings turned off. Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn reads_a_members_relative_data_below_fail_under() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
let member = root.join("backend");
|
||||
std::fs::create_dir_all(member.join("app")).unwrap();
|
||||
std::fs::write(
|
||||
member.join("pyproject.toml"),
|
||||
"[tool.coverage.run]\nrelative_files = true\nbranch = true\ndisable_warnings = [\"couldnt-parse\"]\n\
|
||||
[tool.coverage.report]\nfail_under = 90\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(member.join("app/x.py"), "def f(n):\n if n:\n return 1\n return 2\n").unwrap();
|
||||
std::fs::write(member.join("t.py"), "from app import x\nx.f(1)\n").unwrap();
|
||||
let ok = Command::new("python3").current_dir(&member).args(["-m", "coverage", "run", "t.py"]).status().unwrap();
|
||||
assert!(ok.success());
|
||||
std::fs::remove_file(member.join("t.py")).unwrap();
|
||||
let out = root.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&member.join(".coverage"), &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let x = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("app/x.py")).unwrap();
|
||||
assert_eq!((x.lines_total, x.lines_covered, x.branches_total, x.branches_covered), (4, 3, 2, 1));
|
||||
// `t.py` has no source any more and its warning is off: still listed, without lines.
|
||||
let t = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("t.py")).unwrap();
|
||||
assert!(t.lines.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
//! "Import a report collected in CI from disk": the format is sniffed from the
|
||||
//! content (lcov, Go cover profile, JaCoCo XML, SimpleCov resultset) and paths recorded on another
|
||||
//! content (lcov, Go cover profile, JaCoCo or Cobertura XML, SimpleCov resultset) and paths recorded on another
|
||||
//! machine are mapped into the project by their longest existing suffix.
|
||||
|
||||
use crate::{Accumulator, CoverageSuite, goprofile, jacoco, lcov, simplecov};
|
||||
use crate::{Accumulator, CoverageSuite, cobertura, goprofile, jacoco, lcov, simplecov};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -11,13 +12,19 @@ pub(crate) enum Format {
|
||||
Lcov,
|
||||
GoProfile,
|
||||
Jacoco,
|
||||
Cobertura,
|
||||
SimpleCov,
|
||||
}
|
||||
|
||||
pub(crate) fn detect(text: &str) -> Option<Format> {
|
||||
let head = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if head.starts_with('<') {
|
||||
return head.contains("<report").then_some(Format::Jacoco);
|
||||
// The root element, after any prolog or DOCTYPE naming it.
|
||||
return match (head.find("<report"), head.find("<coverage")) {
|
||||
(Some(r), c) if c.is_none_or(|c| r < c) => Some(Format::Jacoco),
|
||||
(_, Some(_)) => Some(Format::Cobertura),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if head.starts_with('{') {
|
||||
return head.contains("\"coverage\"").then_some(Format::SimpleCov);
|
||||
@@ -39,6 +46,9 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
let (module, module_dir) = go_module_for(root, &text);
|
||||
goprofile::parse(&text, &module, &module_dir).finish("go test -cover")
|
||||
}
|
||||
Some(Format::Cobertura) => cobertura::parse(&text, root)
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?
|
||||
.finish("Cobertura"),
|
||||
Some(Format::Jacoco) => {
|
||||
// A report inside the project (`<module>/target/site/jacoco/…`) knows its module.
|
||||
let module = jacoco::module_dir(path);
|
||||
@@ -53,18 +63,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
|
||||
acc.finish("JaCoCo")
|
||||
}
|
||||
None if text.starts_with("!coverage.py: This is a private format") => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is coverage.py 4 data, which current coverage.py can't read. Import the output of `coverage xml` instead.",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
None => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo XML report or SimpleCov resultset",
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo or Cobertura XML report or SimpleCov resultset",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dirs = HashMap::new();
|
||||
for f in &mut suite.files {
|
||||
let p: &Path = f.path.as_ref();
|
||||
if !p.exists()
|
||||
&& let Some(found) = relocate(p, root)
|
||||
{
|
||||
let present = p.parent().is_none_or(|d| dir_exists(d, &mut dirs)) && p.exists();
|
||||
if !present && let Some(found) = relocate(p, root) {
|
||||
f.path = found.into();
|
||||
}
|
||||
}
|
||||
@@ -72,6 +88,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
Ok(suite)
|
||||
}
|
||||
|
||||
/// Reads a coverage.py data file (see [`crate::is_data_file`]) with the coverage.py of `python`,
|
||||
/// run in `root`; `out` is an empty scratch directory. Blocking.
|
||||
pub fn import_data(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
crate::coveragepy::import(path, root, python, out)
|
||||
}
|
||||
|
||||
/// Whether `dir` exists, without asking again below a directory known to be missing: every
|
||||
/// lookup under macOS's `/home` (autofs) takes tens of milliseconds, and CI reports
|
||||
/// (`/home/runner/work/…`) name thousands of files there.
|
||||
fn dir_exists(dir: &Path, known: &mut HashMap<PathBuf, bool>) -> bool {
|
||||
if let Some(&e) = known.get(dir) {
|
||||
return e;
|
||||
}
|
||||
let e = dir.parent().is_none_or(|p| dir_exists(p, known)) && dir.is_dir();
|
||||
known.insert(dir.to_path_buf(), e);
|
||||
e
|
||||
}
|
||||
|
||||
/// `/home/runner/work/app/app/src/lib.rs` → `<root>/src/lib.rs`: the longest suffix of
|
||||
/// `path` that exists under `root`.
|
||||
pub(crate) fn relocate(path: &Path, root: &Path) -> Option<PathBuf> {
|
||||
@@ -129,12 +163,30 @@ mod tests {
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE report><report name=\"x\"></report>"),
|
||||
Some(Format::Jacoco)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), None);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), Some(Format::Cobertura));
|
||||
assert_eq!(
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE coverage SYSTEM \"x.dtd\"><coverage/>"),
|
||||
Some(Format::Cobertura)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><html/>"), None);
|
||||
assert_eq!(detect("{\"RSpec\": {\"coverage\": {}}}"), Some(Format::SimpleCov));
|
||||
assert_eq!(detect("{\"name\": \"package.json\"}"), None);
|
||||
assert_eq!(detect("hello"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_directories_are_looked_up_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut known = HashMap::new();
|
||||
assert!(dir_exists(tmp.path(), &mut known));
|
||||
let gone = tmp.path().join("gone");
|
||||
assert!(!dir_exists(&gone.join("a/b"), &mut known));
|
||||
std::fs::create_dir_all(gone.join("a/c")).unwrap();
|
||||
// Known to be missing, so its subdirectories are not looked up.
|
||||
assert!(!dir_exists(&gone.join("a/c"), &mut known));
|
||||
assert_eq!(known.get(&gone), Some(&false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_ci_simplecov_with_foreign_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -168,8 +220,75 @@ mod tests {
|
||||
assert!(import(&tmp.path().join("missing"), &root).is_err());
|
||||
std::fs::write(&report, "nothing").unwrap();
|
||||
assert!(import(&report, &root).is_err());
|
||||
std::fs::write(&report, "!coverage.py: This is a private format, don't read it directly!{\"lines\":{}}")
|
||||
.unwrap();
|
||||
assert!(import(&report, &root).unwrap_err().to_string().contains("coverage.py 4 data"));
|
||||
}
|
||||
|
||||
/// `coverage xml` (coverage.py 7.17, `--branch`) of a project checked out on a CI runner.
|
||||
#[test]
|
||||
fn imports_coverage_py_xml_with_foreign_sources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("app");
|
||||
std::fs::create_dir_all(root.join("src/calc")).unwrap();
|
||||
std::fs::write(root.join("src/calc/__init__.py"), "").unwrap();
|
||||
let report = tmp.path().join("coverage.xml");
|
||||
std::fs::write(&report, COVERAGE_PY_XML).unwrap();
|
||||
let suite = import(&report, &root).unwrap();
|
||||
assert_eq!(suite.runner, "Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("src/calc/__init__.py")).unwrap();
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (8, 5, 4, 2));
|
||||
assert_eq!(calc.lines.iter().filter(|l| l.partial()).map(|l| l.line).collect::<Vec<_>>(), [1, 3]);
|
||||
// The test file is not in this checkout: it keeps the runner's path.
|
||||
assert!(
|
||||
suite.files.iter().any(|f| f.path.as_ref() as &Path == Path::new("/home/runner/work/app/app/test_calc.py"))
|
||||
);
|
||||
}
|
||||
|
||||
const COVERAGE_PY_XML: &str = r#"<?xml version="1.0" ?>
|
||||
<coverage version="7.17.5" timestamp="1795754882920" lines-valid="13" lines-covered="10" line-rate="0.7692" branches-valid="4" branches-covered="2" branch-rate="0.5" complexity="0">
|
||||
<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.17.5 -->
|
||||
<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
|
||||
<sources>
|
||||
<source>/home/runner/work/app/app</source>
|
||||
</sources>
|
||||
<packages>
|
||||
<package name="." line-rate="1" branch-rate="1" complexity="0">
|
||||
<classes>
|
||||
<class name="test_calc.py" filename="test_calc.py" complexity="0" line-rate="1" branch-rate="1">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1"/>
|
||||
<line number="3" hits="1"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="7" hits="1"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
<package name="src.calc" line-rate="0.625" branch-rate="0.5" complexity="0">
|
||||
<classes>
|
||||
<class name="__init__.py" filename="src/calc/__init__.py" complexity="0" line-rate="0.625" branch-rate="0.5">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
<line number="4" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="5"/>
|
||||
<line number="5" hits="0"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="13" hits="1"/>
|
||||
<line number="14" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
</packages>
|
||||
</coverage>
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn imports_go_profiles_of_nested_modules() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
//!
|
||||
//! Lines in the model are 0-based, like every IPC coordinate.
|
||||
|
||||
mod cobertura;
|
||||
mod coveragepy;
|
||||
mod goprofile;
|
||||
mod import;
|
||||
mod jacoco;
|
||||
@@ -23,7 +25,8 @@ mod lcov;
|
||||
mod plan;
|
||||
mod simplecov;
|
||||
|
||||
pub use import::import;
|
||||
pub use coveragepy::is_data_file;
|
||||
pub use import::{import, import_data};
|
||||
pub use plan::prepare;
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
|
||||
@@ -326,7 +326,8 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
|
||||
argv.extend(py.target.iter().cloned());
|
||||
let report = CoverageReportSpec::Exported {
|
||||
runner: s("coverage.py"),
|
||||
argv: with(&["-m", "coverage", "lcov", "-o", &path(&lcov)]),
|
||||
// `--fail-under=0`: a `[report] fail_under` the run misses must not lose its report.
|
||||
argv: with(&["-m", "coverage", "lcov", "--fail-under=0", "-o", &path(&lcov)]),
|
||||
cwd: dir.to_path_buf().into(),
|
||||
env: config.env.clone(),
|
||||
lcov: lcov.into(),
|
||||
|
||||
@@ -859,6 +859,21 @@ async fn connect_with_retries(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
|
||||
/// language (a template one) declares debugpy before Python.
|
||||
#[test]
|
||||
fn debugpy_comes_from_the_python_language() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let python = include_str!("../../../languages/python.toml").replace(
|
||||
"args = [\"-m\", \"debugpy.adapter\"]",
|
||||
"args = [\"-X\", \"frozen_modules=off\", \"-m\", \"debugpy.adapter\"]",
|
||||
);
|
||||
assert!(python.contains("frozen_modules"));
|
||||
std::fs::write(dir.path().join("python.toml"), python).unwrap();
|
||||
let languages = LanguageRegistry::load(Some(dir.path())).unwrap();
|
||||
assert_eq!(find_config(&languages, "debugpy").unwrap().args[0], "-X");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapters_run_on_the_tool_search_path() {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Python Debug Server (`attach` with `listen`): the program connects with its own debugpy,
|
||||
//! which may differ from the IDE's adapter. Nothing in the protocol compares them.
|
||||
|
||||
use crate::session::Session;
|
||||
use ide_core::IdeError;
|
||||
use ide_core::event::DebugEvent;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) fn listens(adapter: &str, request: &str, arguments: &Value) -> bool {
|
||||
adapter == "debugpy" && request == "attach" && arguments.get("listen").is_some()
|
||||
}
|
||||
|
||||
/// debugpy's adapter leaves an `attach` whose port is taken unanswered (it only logs the error),
|
||||
/// which would wait for the program forever: find out before starting it. Listening again right
|
||||
/// after a program ended races the previous adapter, which still listens until its shutdown ends.
|
||||
pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
|
||||
// ponytail: polls; waiting on the previous session's shutdown would report a taken port sooner.
|
||||
const RELEASE: Duration = Duration::from_secs(5);
|
||||
let listen = &arguments["listen"];
|
||||
let host = listen["host"].as_str().unwrap_or("127.0.0.1");
|
||||
let Some(port) = listen["port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { return Ok(()) };
|
||||
let deadline = tokio::time::Instant::now() + RELEASE;
|
||||
loop {
|
||||
match std::net::TcpListener::bind((host, port)) {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && tokio::time::Instant::now() < deadline => {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Err(e) => return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On the program's first stop: warns in the Debug console when its debugpy is not the adapter's.
|
||||
/// Evaluated in the stopped frame as a hover: without a frame, debugpy before 1.8 runs the
|
||||
/// expression as a statement and prints its value into the program's output.
|
||||
pub(crate) async fn check_version(s: Arc<Session>, thread: i64) {
|
||||
const WAIT: Duration = Duration::from_secs(5);
|
||||
let request = |command: &'static str, arguments: Value| s.conn.request_timeout(command, arguments, WAIT);
|
||||
let Ok(info) = request("debugpySystemInfo", json!({})).await else { return };
|
||||
let Some(ide) = info.pointer("/debugpy/version").and_then(Value::as_str) else { return };
|
||||
let Ok(trace) = request("stackTrace", json!({ "threadId": thread, "levels": 1 })).await else { return };
|
||||
let Some(frame) = trace.pointer("/stackFrames/0/id").and_then(Value::as_i64) else { return };
|
||||
let expression = json!({ "expression": "__import__('debugpy').__version__", "frameId": frame, "context": "hover" });
|
||||
let Ok(reply) = request("evaluate", expression).await else { return };
|
||||
let Some(program) = reply.get("result").and_then(Value::as_str) else { return };
|
||||
if let Some(warning) = version_warning(ide, program) {
|
||||
s.emit(DebugEvent::Output { category: "console".into(), output: warning });
|
||||
}
|
||||
}
|
||||
|
||||
fn version_warning(ide: &str, program: &str) -> Option<String> {
|
||||
let program = program.trim_matches(|c| c == '\'' || c == '"');
|
||||
(program != ide).then(|| {
|
||||
format!(
|
||||
"The program uses debugpy {program}, the IDE's debugger debugpy {ide}. If breakpoints or stepping \
|
||||
misbehave, install the same version where the program runs: pip install debugpy=={ide}\n"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn warns_only_when_versions_differ() {
|
||||
assert_eq!(version_warning("1.8.22", "'1.8.22'"), None);
|
||||
assert_eq!(version_warning("1.8.22", "1.8.22"), None);
|
||||
let w = version_warning("1.8.22", "'1.8.0'").unwrap();
|
||||
assert!(w.contains("debugpy 1.8.0") && w.ends_with("pip install debugpy==1.8.22\n"), "{w}");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_taken_port_is_reported_before_the_adapter_starts() {
|
||||
let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = taken.local_addr().unwrap().port();
|
||||
let listen = json!({"listen": {"host": "127.0.0.1", "port": port}});
|
||||
let e = require_free_port(&listen).await.unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}");
|
||||
drop(taken);
|
||||
assert!(require_free_port(&listen).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_address_the_machine_lacks_is_reported_at_once() {
|
||||
// 192.0.2.0/24 is reserved for documentation, never a local address.
|
||||
let started = std::time::Instant::now();
|
||||
let e = require_free_port(&json!({"listen": {"host": "192.0.2.1", "port": 5678}})).await.unwrap_err();
|
||||
assert!(e.to_string().contains("Cannot listen on 192.0.2.1:5678"), "{e}");
|
||||
assert!(started.elapsed() < Duration::from_secs(1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waits_for_the_previous_adapter_to_release_the_port() {
|
||||
let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = previous.local_addr().unwrap().port();
|
||||
let released = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
drop(previous);
|
||||
});
|
||||
require_free_port(&json!({"listen": {"host": "127.0.0.1", "port": port}})).await.unwrap();
|
||||
released.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_debugpy_listen_attaches_check() {
|
||||
assert!(listens("debugpy", "attach", &json!({"listen": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "attach", &json!({"connect": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "launch", &json!({"listen": {}})));
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target,
|
||||
pub(crate) use scan::watch_for_attached_jvm;
|
||||
pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port};
|
||||
use snapshot::{AttachProbe, JdkProbe, take_snapshot};
|
||||
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, run_jvm_thread_dump};
|
||||
pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, VirtualThreadsNote, run_jvm_thread_dump};
|
||||
pub(crate) use threads::{debugged_run_thread_dump, session_thread_dump};
|
||||
|
||||
pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER];
|
||||
|
||||
@@ -33,6 +33,7 @@ pub(crate) trait AttachProbe: Send + Sync {
|
||||
fn ensure_listener(&self, pid: u32) -> Result<(), AttachError>;
|
||||
/// Confirmed HotSpot and not one of Gradle's own JVMs; asks the JVM nothing.
|
||||
fn is_application_jvm(&self, pid: u32) -> bool;
|
||||
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError>;
|
||||
}
|
||||
|
||||
pub(super) struct JdkProbe {
|
||||
@@ -91,6 +92,10 @@ impl AttachProbe for JdkProbe {
|
||||
fn is_application_jvm(&self, pid: u32) -> bool {
|
||||
ide_jvm_attach::is_application_jvm(pid)
|
||||
}
|
||||
|
||||
fn thread_dump_json(&self, pid: u32, dir: &Path) -> Result<String, AttachError> {
|
||||
ide_jvm_attach::thread_dump_json(pid, dir, ide_jvm_attach::THREAD_DUMP_TIMEOUT)
|
||||
}
|
||||
}
|
||||
|
||||
fn alive(pid: u32) -> bool {
|
||||
|
||||
@@ -47,6 +47,8 @@ struct FakeProbe {
|
||||
application_jvms: Vec<u32>,
|
||||
/// Pids `ensure_listener` was asked for.
|
||||
ensured: parking_lot::Mutex<Vec<u32>>,
|
||||
json_dumps: parking_lot::Mutex<VecDeque<Result<String, AttachError>>>,
|
||||
json_dirs: parking_lot::Mutex<Vec<PathBuf>>,
|
||||
}
|
||||
|
||||
type StopHook = Box<dyn Fn() + Send + Sync>;
|
||||
@@ -109,6 +111,8 @@ impl FakeProbe {
|
||||
listener_starts: parking_lot::Mutex::new(VecDeque::new()),
|
||||
application_jvms: Vec::new(),
|
||||
ensured: parking_lot::Mutex::new(Vec::new()),
|
||||
json_dumps: parking_lot::Mutex::new(VecDeque::new()),
|
||||
json_dirs: parking_lot::Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,6 +197,12 @@ impl AttachProbe for FakeProbe {
|
||||
fn is_application_jvm(&self, pid: u32) -> bool {
|
||||
self.application_jvms.contains(&pid)
|
||||
}
|
||||
fn thread_dump_json(&self, _pid: u32, dir: &Path) -> Result<String, AttachError> {
|
||||
self.enter("thread_dump_json");
|
||||
self.json_dirs.lock().push(dir.to_owned());
|
||||
self.leave();
|
||||
self.json_dumps.lock().pop_front().expect("unexpected JSON thread dump request")
|
||||
}
|
||||
}
|
||||
|
||||
const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener";
|
||||
@@ -1205,10 +1215,95 @@ fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable {
|
||||
JvmThreadsUnavailable::Jvm { reason }
|
||||
}
|
||||
|
||||
/// The text dump alone: without a directory no JSON dump is asked for.
|
||||
fn dump_text(fake: &FakeProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
|
||||
dump_threads(fake, pid, suspended, None, &|| suspended)
|
||||
}
|
||||
|
||||
fn ready_dump(r: JvmThreadsResult) -> JvmThreadDump {
|
||||
match r {
|
||||
JvmThreadsResult::Ready { dump } => dump,
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
const VIRTUAL_JSON: &str = r#"{"threadDump":{"threadContainers":[]}}"#;
|
||||
|
||||
fn json_dir() -> &'static Path {
|
||||
Path::new("/data/cache/heap-snapshots/x")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_below_21_ask_for_no_json() {
|
||||
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, None));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_on_21_add_the_json_after_the_text() {
|
||||
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
|
||||
assert_eq!(dump.text, THREADS);
|
||||
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
|
||||
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_json_dump_keeps_the_text_dump() {
|
||||
let cases = [
|
||||
(AttachError::TooLarge, VirtualThreadsNote::TooLarge),
|
||||
(AttachError::Timeout, VirtualThreadsNote::Failed),
|
||||
(AttachError::Protocol("no thread dump file".into()), VirtualThreadsNote::Failed),
|
||||
];
|
||||
for (error, note) in cases {
|
||||
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
*fake.json_dumps.lock() = vec![Err(error)].into();
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| false));
|
||||
assert_eq!((dump.text.as_str(), dump.virtual_json, dump.virtual_note), (THREADS, None, Some(note)));
|
||||
}
|
||||
|
||||
// No directory to write the file into.
|
||||
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
let dump = ready_dump(dump_text(&fake, 12, false));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::Failed)));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_text_dump_asks_for_no_json() {
|
||||
let fake = dumping_threads(99, vec![Err(AttachError::Timeout)]);
|
||||
let r = dump_threads(&fake, 12, false, Some(json_dir()), &|| false);
|
||||
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::TimedOut));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_while_suspended_on_21_skip_the_json() {
|
||||
let fake = dumping_threads(12, vec![Ok(THREADS.into())]);
|
||||
let dump = ready_dump(dump_threads(&fake, 12, true, Some(json_dir()), &|| true));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["thread_print"]);
|
||||
|
||||
// The program hits a breakpoint while the text dump is taken.
|
||||
let stopped = Arc::new(AtomicBool::new(false));
|
||||
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
let stop = stopped.clone();
|
||||
fake.stops_on = Some(("thread_print", Box::new(move || stop.store(true, Ordering::SeqCst))));
|
||||
let dump = ready_dump(dump_threads(&fake, 12, false, Some(json_dir()), &|| stopped.load(Ordering::SeqCst)));
|
||||
assert!(!dump.taken_while_suspended);
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_while_running_start_the_listener() {
|
||||
let fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
let r = dump_threads(&fake, 12, false);
|
||||
let r = dump_text(&fake, 12, false);
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!((dump.text.as_str(), dump.pid, dump.java_version.as_str()), (THREADS, 12, "21.0.5"));
|
||||
assert!(!dump.taken_while_suspended);
|
||||
@@ -1218,10 +1313,7 @@ fn threads_while_running_start_the_listener() {
|
||||
#[test]
|
||||
fn threads_while_suspended_without_listener_do_not_attach() {
|
||||
let fake = dumping_threads(99, Vec::new());
|
||||
assert_eq!(
|
||||
threads_unavailable(dump_threads(&fake, 12, true)),
|
||||
threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)
|
||||
);
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
}
|
||||
|
||||
@@ -1230,12 +1322,12 @@ fn threads_while_suspended_on_11_are_refused() {
|
||||
let mut fake = dumping_threads(12, Vec::new());
|
||||
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
|
||||
assert_eq!(
|
||||
threads_unavailable(dump_threads(&fake, 12, true)),
|
||||
threads_unavailable(dump_text(&fake, 12, true)),
|
||||
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })
|
||||
);
|
||||
fake.version = None;
|
||||
assert_eq!(
|
||||
threads_unavailable(dump_threads(&fake, 12, true)),
|
||||
threads_unavailable(dump_text(&fake, 12, true)),
|
||||
threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 })
|
||||
);
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
@@ -1245,7 +1337,7 @@ fn threads_while_suspended_on_11_are_refused() {
|
||||
fn threads_while_suspended_on_17_use_the_running_listener() {
|
||||
let mut fake = dumping_threads(12, vec![Ok(THREADS.into())]);
|
||||
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
|
||||
let r = dump_threads(&fake, 12, true);
|
||||
let r = dump_text(&fake, 12, true);
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert!(dump.taken_while_suspended);
|
||||
assert_eq!(dump.java_version, "17.0.13");
|
||||
@@ -1257,7 +1349,7 @@ fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
|
||||
// A shell (10) started a Gradle client (11) that started the program's JVM (12).
|
||||
let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]);
|
||||
fake.application_jvms = vec![12];
|
||||
let r = dump_tree(&fake, &[10, 11, 12], false);
|
||||
let r = dump_tree(&fake, &[10, 11, 12], false, None, &|| false);
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!(dump.pid, 12);
|
||||
assert_eq!(*fake.ensured.lock(), [12]);
|
||||
@@ -1266,7 +1358,7 @@ fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() {
|
||||
let fake = dumping_threads(99, Vec::new());
|
||||
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm)].into();
|
||||
assert_eq!(
|
||||
threads_unavailable(dump_tree(&fake, &[10, 11], false)),
|
||||
threads_unavailable(dump_tree(&fake, &[10, 11], false, None, &|| false)),
|
||||
threads_jvm(JvmMemoryUnavailable::NoJvmProcess)
|
||||
);
|
||||
assert_eq!(*fake.ensured.lock(), [10]);
|
||||
@@ -1290,7 +1382,7 @@ async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reporte
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let target = JvmTarget::Launched(std::process::id() as i32);
|
||||
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
|
||||
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!(dump.pid, jvm);
|
||||
assert_eq!(*fake.ensured.lock(), [jvm]);
|
||||
@@ -1340,7 +1432,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
|
||||
let bare = stopped_attach(0);
|
||||
let fake = Arc::new(dumping_threads(99, Vec::new()));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
|
||||
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
|
||||
@@ -1348,7 +1440,7 @@ async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() {
|
||||
let bare = bare_session("attach");
|
||||
let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())]));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 555, None).await.unwrap();
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!((dump.pid, dump.taken_while_suspended), (555, false));
|
||||
assert_eq!(*fake.ensured.lock(), [555]);
|
||||
@@ -1369,26 +1461,71 @@ async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() {
|
||||
fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() });
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
|
||||
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 }));
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
|
||||
// No listener: none is started, the JVM's Signal Dispatcher being stopped.
|
||||
let fake = Arc::new(dumping_threads(99, Vec::new()));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
|
||||
assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning));
|
||||
assert!(fake.commands.lock().is_empty());
|
||||
|
||||
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
|
||||
fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() });
|
||||
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap();
|
||||
let r = known_pid_dump(&bare.session, |_| probe, 4242, None).await.unwrap();
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert!(dump.taken_while_suspended);
|
||||
assert_eq!(dump.pid, 4242);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_dump_of_a_debugged_jvm_asks_for_no_json_while_the_session_holds_it() {
|
||||
let bare = stopped_attach(4242);
|
||||
let fake = Arc::new(dumping_threads(4242, vec![Ok(THREADS.into())]));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
|
||||
assert!(dump.taken_while_suspended);
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["thread_print"]);
|
||||
|
||||
// Running at first, the program hits a breakpoint while the text dump is taken.
|
||||
let bare = bare_session("attach");
|
||||
bare.session.jvm_pid.store(4242, Ordering::Release);
|
||||
let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]);
|
||||
let session = bare.session.clone();
|
||||
fake.stops_on = Some(("thread_print", Box::new(move || session.suspended.stopped(None, true))));
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 4242, Some(json_dir().into())).await.unwrap());
|
||||
assert!(!dump.taken_while_suspended);
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_dump_through_a_linked_session_whose_jvm_is_not_located_asks_for_no_json_while_stopped() {
|
||||
// Gradle bootRun Debug after an earlier run dump opened the listener: the session's pid is still 0.
|
||||
let bare = stopped_attach(0);
|
||||
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
|
||||
assert_eq!((dump.pid, dump.taken_while_suspended), (555, true));
|
||||
assert_eq!((dump.virtual_json, dump.virtual_note), (None, Some(VirtualThreadsNote::WhileSuspended)));
|
||||
assert_eq!(*fake.commands.lock(), ["thread_print"]);
|
||||
|
||||
// Running, the same session gets the JSON dump too.
|
||||
let bare = bare_session("attach");
|
||||
let fake = Arc::new(dumping_threads(555, vec![Ok(THREADS.into())]));
|
||||
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let dump = ready_dump(known_pid_dump(&bare.session, |_| probe, 555, Some(json_dir().into())).await.unwrap());
|
||||
assert_eq!((dump.virtual_json.as_deref(), dump.virtual_note), (Some(VIRTUAL_JSON), None));
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print", "thread_dump_json"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
|
||||
let bare = bare_session("attach");
|
||||
@@ -1397,7 +1534,7 @@ async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() {
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
|
||||
let histogram = bare.session.jvm_memory.lock().await;
|
||||
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242));
|
||||
let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242, None));
|
||||
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
|
||||
// The program hits a breakpoint while the dump waits behind the session's histogram.
|
||||
bare.session.suspended.stopped(None, true);
|
||||
@@ -1411,28 +1548,28 @@ fn threads_of_an_exited_program() {
|
||||
let mut fake = dumping_threads(99, Vec::new());
|
||||
fake.alive = false;
|
||||
*fake.listener_starts.lock() = vec![Err(AttachError::NoListener)].into();
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_dump_errors_map_to_reasons() {
|
||||
let fake = dumping_threads(12, vec![Err(AttachError::Timeout)]);
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut));
|
||||
|
||||
let fake = dumping_threads(99, Vec::new());
|
||||
*fake.listener_starts.lock() = vec![Err(AttachError::ListenerDidNotStart)].into();
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart);
|
||||
assert_eq!(*fake.commands.lock(), ["ensure_listener"]);
|
||||
|
||||
let mut fake = dumping_threads(99, Vec::new());
|
||||
*fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm), Err(AttachError::NotAJvm)].into();
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess));
|
||||
fake.alive = false;
|
||||
assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
assert_eq!(threads_unavailable(dump_text(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited));
|
||||
|
||||
let fake = dumping_threads(12, vec![Err(AttachError::Command { code: 1, message: "no".into() })]);
|
||||
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_threads(&fake, 12, false)) else {
|
||||
let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_text(&fake, 12, false)) else {
|
||||
panic!("not a failure")
|
||||
};
|
||||
assert!(message.contains("no"), "{message}");
|
||||
@@ -1456,14 +1593,20 @@ fn thread_results_serialize_with_camel_case_tags() {
|
||||
java_version: String::new(),
|
||||
taken_while_suspended: true,
|
||||
elapsed_ms: 3,
|
||||
virtual_json: None,
|
||||
virtual_note: Some(VirtualThreadsNote::WhileSuspended),
|
||||
};
|
||||
assert_eq!(
|
||||
serde_json::to_value(JvmThreadsResult::Ready { dump }).unwrap(),
|
||||
serde_json::json!({
|
||||
"status": "ready",
|
||||
"dump": {"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3}
|
||||
"dump": {
|
||||
"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3,
|
||||
"virtualJson": null, "virtualNote": "whileSuspended"
|
||||
}
|
||||
})
|
||||
);
|
||||
assert_eq!(serde_json::to_value(VirtualThreadsNote::TooLarge).unwrap(), serde_json::json!("tooLarge"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -1479,7 +1622,7 @@ async fn threads_take_the_memory_lock() {
|
||||
let running = Suspension::default();
|
||||
let (classes, threads) = tokio::join!(
|
||||
snapshot(&state, &running, |_| probe.clone(), JvmTarget::Launched(pid as i32), None),
|
||||
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32))
|
||||
thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32), None)
|
||||
);
|
||||
assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. }));
|
||||
let threads = threads.unwrap();
|
||||
@@ -1493,12 +1636,14 @@ async fn threads_take_the_memory_lock() {
|
||||
async fn queued_thread_dump_reads_suspension_under_the_lock() {
|
||||
let pid = std::process::id();
|
||||
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
|
||||
let suspended = Suspension::default();
|
||||
let suspended = Arc::new(Suspension::default());
|
||||
let fake = Arc::new(dumping_threads(0, Vec::new()));
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
|
||||
let running = state.lock().await;
|
||||
let mut queued = Box::pin(thread_dump(&state, || suspended.get(), |_| probe, JvmTarget::Launched(pid as i32)));
|
||||
let stopped = suspended.clone();
|
||||
let target = JvmTarget::Launched(pid as i32);
|
||||
let mut queued = Box::pin(thread_dump(&state, move || stopped.get(), |_| probe, target, Some(json_dir().into())));
|
||||
assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err());
|
||||
// The program hits a breakpoint while the dump waits behind a class-table request.
|
||||
suspended.stopped(None, true);
|
||||
@@ -1515,12 +1660,27 @@ async fn attached_thread_dump_keeps_the_scanned_jvm() {
|
||||
fake.jdwp = Some((5005, 4242));
|
||||
let probe: Arc<dyn AttachProbe> = Arc::new(fake);
|
||||
let target = JvmTarget::Attached { pid: &jvm_pid, jdwp_port: Some(5005) };
|
||||
let r = thread_dump(&state, || false, |_| probe, target).await.unwrap();
|
||||
let r = thread_dump(&state, || false, |_| probe, target, None).await.unwrap();
|
||||
let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") };
|
||||
assert_eq!(dump.pid, 4242);
|
||||
assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn session_thread_dump_writes_the_json_into_the_given_directory() {
|
||||
let pid = std::process::id();
|
||||
let state = tokio::sync::Mutex::new(JvmMemoryState::default());
|
||||
let fake = dumping_threads(pid, vec![Ok(THREADS.into())]);
|
||||
*fake.json_dumps.lock() = vec![Ok(VIRTUAL_JSON.into())].into();
|
||||
let fake = Arc::new(fake);
|
||||
let probe: Arc<dyn AttachProbe> = fake.clone();
|
||||
let target = JvmTarget::Launched(pid as i32);
|
||||
let r = thread_dump(&state, || false, |_| probe, target, Some(json_dir().into())).await.unwrap();
|
||||
assert_eq!(ready_dump(r).virtual_json.as_deref(), Some(VIRTUAL_JSON));
|
||||
assert_eq!(*fake.json_dirs.lock(), [json_dir()]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capability_matches_memory() {
|
||||
for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) {
|
||||
|
||||
@@ -8,11 +8,15 @@ use super::{
|
||||
};
|
||||
use crate::session::Session;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_jvm_attach::AttachError;
|
||||
use ide_jvm_attach::{AttachError, JavaVersion};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The first release whose virtual threads are final and that writes the JSON dump.
|
||||
const VIRTUAL_THREADS_MAJOR: u32 = 21;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JvmThreadDump {
|
||||
@@ -23,6 +27,20 @@ pub struct JvmThreadDump {
|
||||
pub taken_while_suspended: bool,
|
||||
/// Wall time of the `Thread.print` request.
|
||||
pub elapsed_ms: u32,
|
||||
/// `Thread.dump_to_file -format=json`, which also lists virtual threads; JDK 21+ only.
|
||||
pub virtual_json: Option<String>,
|
||||
/// Why `virtual_json` is missing from a JDK 21+ dump; none below 21.
|
||||
pub virtual_note: Option<VirtualThreadsNote>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VirtualThreadsNote {
|
||||
/// A debugger holds the VM, which would hang the JSON request until it resumes.
|
||||
WhileSuspended,
|
||||
/// Over the attach reply limit (64 MiB).
|
||||
TooLarge,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -48,13 +66,17 @@ pub enum JvmThreadsResult {
|
||||
Unavailable { reason: JvmThreadsUnavailable },
|
||||
}
|
||||
|
||||
/// A thread dump of `pid`, a JVM no debugger holds. Blocking for up to the listener start and
|
||||
/// A thread dump of `pid`, a JVM no debugger holds; `json_dir` is an absolute, owner-only
|
||||
/// directory the JVM may write the JSON dump into. Blocking for up to the listener start and
|
||||
/// dump timeouts, so callers run it in `spawn_blocking`.
|
||||
pub fn run_jvm_thread_dump(pid: u32) -> JvmThreadsResult {
|
||||
dump_threads(&JdkProbe { suspended: false }, pid, false)
|
||||
pub fn run_jvm_thread_dump(pid: u32, json_dir: Option<&Path>) -> JvmThreadsResult {
|
||||
dump_threads(&JdkProbe { suspended: false }, pid, false, json_dir, &|| false)
|
||||
}
|
||||
|
||||
pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmThreadsResult> {
|
||||
pub(crate) async fn session_thread_dump(
|
||||
session: Arc<Session>,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
until_located(&session).await;
|
||||
let launched = histogram_pid(&session);
|
||||
// Detached, so a caller that gives up cannot release the lock while the JVM is still
|
||||
@@ -62,7 +84,9 @@ pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmT
|
||||
tokio::spawn(async move {
|
||||
let target = session_target(&session, launched);
|
||||
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
|
||||
thread_dump(&session.jvm_memory, || capture_suspended(&session), probe, target).await
|
||||
let stopped = session.clone();
|
||||
let suspended = move || capture_suspended(&stopped);
|
||||
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
|
||||
@@ -70,43 +94,53 @@ pub(crate) async fn session_thread_dump(session: Arc<Session>) -> IdeResult<JvmT
|
||||
|
||||
/// A thread dump of `pid`, a run's JVM that `session` debugs, taken as the session's own dump
|
||||
/// is: a JVM the debugger holds suspended is never asked to open a listener.
|
||||
pub(crate) async fn debugged_run_thread_dump(session: Arc<Session>, pid: u32) -> IdeResult<JvmThreadsResult> {
|
||||
pub(crate) async fn debugged_run_thread_dump(
|
||||
session: Arc<Session>,
|
||||
pid: u32,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
// Detached for the same reason as `session_thread_dump`.
|
||||
tokio::spawn(async move {
|
||||
let probe = |suspended| -> Arc<dyn AttachProbe> { Arc::new(JdkProbe { suspended }) };
|
||||
known_pid_dump(&session, probe, pid).await
|
||||
known_pid_dump(&session, probe, pid, json_dir).await
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?
|
||||
}
|
||||
|
||||
/// The session's suspension decides the JSON dump too: it is read again before that request.
|
||||
pub(super) async fn known_pid_dump(
|
||||
session: &Session,
|
||||
session: &Arc<Session>,
|
||||
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
|
||||
pid: u32,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
let target =
|
||||
i32::try_from(pid).map_or(JvmTarget::Unavailable(JvmMemoryUnavailable::NoJvmProcess), JvmTarget::Known);
|
||||
thread_dump(&session.jvm_memory, || capture_suspended(session), probe, target).await
|
||||
let stopped = session.clone();
|
||||
let suspended = move || capture_suspended(&stopped);
|
||||
thread_dump(&session.jvm_memory, suspended, probe, target, json_dir).await
|
||||
}
|
||||
|
||||
/// Takes the class-table lock, so a dump never runs beside a histogram or heap dump of the same
|
||||
/// session; `suspended` and then `probe` are read once it is held.
|
||||
/// session; `suspended_now` and then `probe` are read once it is held, and `suspended_now` again
|
||||
/// before the JSON dump.
|
||||
pub(super) async fn thread_dump(
|
||||
state: &tokio::sync::Mutex<JvmMemoryState>,
|
||||
suspended: impl FnOnce() -> bool,
|
||||
suspended_now: impl Fn() -> bool + Send + Sync + 'static,
|
||||
probe: impl FnOnce(bool) -> Arc<dyn AttachProbe>,
|
||||
target: JvmTarget<'_>,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> IdeResult<JvmThreadsResult> {
|
||||
let _turn = state.lock().await;
|
||||
let suspended = suspended();
|
||||
let suspended = suspended_now();
|
||||
let lookup = match lookup(target) {
|
||||
Ok(lookup) => lookup,
|
||||
Err(reason) => return Ok(jvm(reason)),
|
||||
};
|
||||
let probe = probe(suspended);
|
||||
let (found, outcome) = tokio::task::spawn_blocking(move || match resolve_jvm(lookup, &*probe, suspended) {
|
||||
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended)),
|
||||
Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended, json_dir.as_deref(), &suspended_now)),
|
||||
Err(reason) => (None, jvm(reason)),
|
||||
})
|
||||
.await
|
||||
@@ -118,19 +152,32 @@ pub(super) async fn thread_dump(
|
||||
/// `tree` starts with the session's reported pid, followed by its descendants: the JVM is the
|
||||
/// first with a listener, else the first application JVM (the reported pid may be a shell or a
|
||||
/// Gradle client), else the reported pid.
|
||||
pub(super) fn dump_tree(probe: &dyn AttachProbe, tree: &[i32], suspended: bool) -> JvmThreadsResult {
|
||||
pub(super) fn dump_tree(
|
||||
probe: &dyn AttachProbe,
|
||||
tree: &[i32],
|
||||
suspended: bool,
|
||||
json_dir: Option<&Path>,
|
||||
suspended_now: &dyn Fn() -> bool,
|
||||
) -> JvmThreadsResult {
|
||||
let jvm_pid = pick_jvm_pid(tree, |p| probe.has_listener(p))
|
||||
.or_else(|| pick_jvm_pid(tree, |p| probe.is_application_jvm(p)))
|
||||
.or_else(|| tree.first().and_then(|&p| u32::try_from(p).ok()).filter(|&p| p > 0));
|
||||
match jvm_pid {
|
||||
Some(pid) => dump_threads(probe, pid, suspended),
|
||||
Some(pid) => dump_threads(probe, pid, suspended, json_dir, suspended_now),
|
||||
None => jvm(JvmMemoryUnavailable::NoJvmProcess),
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocking. A JVM a debugger holds suspended cannot open a listener (its Signal Dispatcher is
|
||||
/// stopped), and one below 17 hangs even with one, so it is asked only when both are ruled out.
|
||||
pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -> JvmThreadsResult {
|
||||
/// The JSON dump follows a text dump that succeeded; its failure only sets the note.
|
||||
pub(crate) fn dump_threads(
|
||||
probe: &dyn AttachProbe,
|
||||
pid: u32,
|
||||
suspended: bool,
|
||||
json_dir: Option<&Path>,
|
||||
suspended_now: &dyn Fn() -> bool,
|
||||
) -> JvmThreadsResult {
|
||||
if suspended {
|
||||
if !probe.has_listener(pid) {
|
||||
return jvm(gone(probe, pid));
|
||||
@@ -149,6 +196,8 @@ pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -
|
||||
Err(e) => return failure(probe, pid, e),
|
||||
};
|
||||
let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
|
||||
let (virtual_json, virtual_note) =
|
||||
virtual_threads(probe, pid, version.as_ref(), suspended, json_dir, suspended_now);
|
||||
JvmThreadsResult::Ready {
|
||||
dump: JvmThreadDump {
|
||||
text,
|
||||
@@ -156,10 +205,40 @@ pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -
|
||||
java_version: version.map(|v| v.text).unwrap_or_default(),
|
||||
taken_while_suspended: suspended,
|
||||
elapsed_ms,
|
||||
virtual_json,
|
||||
virtual_note,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The program may have stopped during the text dump, so the suspension is read again.
|
||||
fn virtual_threads(
|
||||
probe: &dyn AttachProbe,
|
||||
pid: u32,
|
||||
version: Option<&JavaVersion>,
|
||||
suspended: bool,
|
||||
json_dir: Option<&Path>,
|
||||
suspended_now: &dyn Fn() -> bool,
|
||||
) -> (Option<String>, Option<VirtualThreadsNote>) {
|
||||
if version.is_none_or(|v| v.major < VIRTUAL_THREADS_MAJOR) {
|
||||
return (None, None);
|
||||
}
|
||||
if suspended || suspended_now() {
|
||||
return (None, Some(VirtualThreadsNote::WhileSuspended));
|
||||
}
|
||||
let Some(dir) = json_dir else {
|
||||
return (None, Some(VirtualThreadsNote::Failed));
|
||||
};
|
||||
match probe.thread_dump_json(pid, dir) {
|
||||
Ok(json) => (Some(json), None),
|
||||
Err(AttachError::TooLarge) => (None, Some(VirtualThreadsNote::TooLarge)),
|
||||
Err(e) => {
|
||||
tracing::warn!("JSON thread dump of JVM {pid}: {e}");
|
||||
(None, Some(VirtualThreadsNote::Failed))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult {
|
||||
let reason = match error {
|
||||
AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart,
|
||||
|
||||
@@ -12,6 +12,7 @@ pub mod adapter;
|
||||
pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
mod debugpy;
|
||||
mod exception_classes;
|
||||
pub mod jdwp;
|
||||
mod js_cdp;
|
||||
@@ -308,6 +309,14 @@ pub struct SessionInfo {
|
||||
pub parent: Option<DebugSessionId>,
|
||||
}
|
||||
|
||||
/// One owner's breakpoints, kept without a session and sent when one of its sessions starts.
|
||||
#[derive(Default)]
|
||||
struct OwnerBreakpoints {
|
||||
lines: BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
functions: Vec<FunctionBreakpoint>,
|
||||
data: Vec<DataBreakpoint>,
|
||||
}
|
||||
|
||||
/// Who started a session. Every event of the session, and of the child sessions
|
||||
/// its adapter starts, goes to `sink` only; `key` (e.g. a window label) scopes
|
||||
/// listings such as [`DebugManager::sessions`].
|
||||
@@ -336,13 +345,12 @@ pub struct DebugManager {
|
||||
sessions: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
/// Session start order, for "the first session" semantics.
|
||||
order: Mutex<Vec<DebugSessionId>>,
|
||||
breakpoints: Mutex<BTreeMap<PathBuf, Vec<Breakpoint>>>,
|
||||
/// Breakpoints by owner (window): each window's sessions get only its own.
|
||||
breakpoints: Mutex<HashMap<String, OwnerBreakpoints>>,
|
||||
states: Mutex<HashMap<PathBuf, Vec<BreakpointState>>>,
|
||||
/// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default.
|
||||
exception_choices: Mutex<BTreeMap<String, bool>>,
|
||||
exception_classes: Mutex<Vec<ExceptionClassBreakpoint>>,
|
||||
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
|
||||
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
|
||||
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
|
||||
stopping: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
jvm_finder: Mutex<jvm_memory::JvmFinder>,
|
||||
@@ -450,6 +458,21 @@ fn no_session(s: DebugSessionId) -> IdeError {
|
||||
IdeError::not_found(format!("no debug session {}", s.0))
|
||||
}
|
||||
|
||||
/// debugpy hands a subprocess (`subProcess: true`, forked or spawned) over as an `attach` whose
|
||||
/// `connect` is its own client listener: the child session is another connection to the running
|
||||
/// adapter, as VS Code makes it, not a new adapter that would take that port for a debug server.
|
||||
fn subprocess_connection(configuration: &Value, spec: &AdapterSpec) -> Option<(AdapterSpec, u16)> {
|
||||
configuration.get("subProcessId")?;
|
||||
let connect = configuration.get("connect")?;
|
||||
let port = u16::try_from(connect.get("port")?.as_u64()?).ok()?;
|
||||
let mut spec = spec.clone();
|
||||
if let Some(host) = connect.get("host").and_then(Value::as_str) {
|
||||
let loopback = host == "localhost" || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
|
||||
spec.server_host = (!loopback).then(|| host.to_owned());
|
||||
}
|
||||
Some((spec, port))
|
||||
}
|
||||
|
||||
/// The name of a child session: the adapter's, or the parent's when it gives none. js-debug
|
||||
/// names a browser page's session after the page the browser starts on, before the URL
|
||||
/// loads (`about:blank`, or nothing in a new profile), which says nothing about what is debugged.
|
||||
@@ -803,8 +826,6 @@ impl DebugManager {
|
||||
states: Mutex::default(),
|
||||
exception_choices: Mutex::default(),
|
||||
exception_classes: Mutex::default(),
|
||||
function_breakpoints: Mutex::default(),
|
||||
data_breakpoints: Mutex::default(),
|
||||
stopping: Mutex::default(),
|
||||
jvm_finder: Mutex::new(Arc::new(jvm_memory::find_local_jvm)),
|
||||
})
|
||||
@@ -824,8 +845,24 @@ impl DebugManager {
|
||||
self.order.lock().iter().filter_map(|id| sessions.get(id).cloned()).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn stored_breakpoints(&self, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(path).cloned().unwrap_or_default()
|
||||
pub(crate) fn stored_breakpoints(&self, owner: &str, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(owner).and_then(|b| b.lines.get(path).cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn function_breakpoints(&self, owner: &str) -> Vec<FunctionBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.functions.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn data_breakpoints(&self, owner: &str) -> Vec<DataBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.data.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `owner`'s sessions that take breakpoint requests.
|
||||
fn configured_sessions(&self, owner: &str) -> Vec<Arc<Session>> {
|
||||
self.live_sessions()
|
||||
.into_iter()
|
||||
.filter(|s| s.owner.key == owner && s.configured.load(Ordering::Acquire) && !s.conn.is_closed())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Live sessions of `owner` (all owners when `None`).
|
||||
@@ -865,6 +902,9 @@ impl DebugManager {
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
let mut arguments = launch_arguments(&config)?;
|
||||
if debugpy::listens(&config.adapter, &config.request, &arguments) {
|
||||
debugpy::require_free_port(&arguments).await?;
|
||||
}
|
||||
// An IDE-side marker (never sent to the adapter): the session is a Flutter
|
||||
// one regardless of what the working directory holds.
|
||||
let force_flutter =
|
||||
@@ -897,6 +937,21 @@ impl DebugManager {
|
||||
if config.adapter == "rdbg" {
|
||||
rdbg_command_line(&mut spec, &config, &cwd)?;
|
||||
}
|
||||
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
|
||||
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
|
||||
// is Flutter-only). Plain Dart projects keep the configured `dart`. Before
|
||||
// `custom_command`, which picks the Flutter SDK setting's `flutter`.
|
||||
if config.adapter == "dart" {
|
||||
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
|
||||
if force_flutter || is_flutter_project(&cwd, program) {
|
||||
if spec.command == "dart" {
|
||||
spec.command = "flutter".into();
|
||||
}
|
||||
if let Some(device) = flutter_device {
|
||||
add_flutter_device(&mut arguments, device);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(command) = custom_command(&spec.command) {
|
||||
spec.command = command;
|
||||
}
|
||||
@@ -912,20 +967,6 @@ impl DebugManager {
|
||||
spec.command = python;
|
||||
}
|
||||
}
|
||||
// Flutter: a project depending on the Flutter SDK needs `flutter debug_adapter`
|
||||
// (the Dart adapter cannot start a program importing `dart:ui`, and hot reload
|
||||
// is Flutter-only). Plain Dart projects keep the configured `dart`.
|
||||
if config.adapter == "dart" {
|
||||
let program = arguments.get("program").and_then(Value::as_str).map(Path::new);
|
||||
if force_flutter || is_flutter_project(&cwd, program) {
|
||||
if spec.command == "dart" {
|
||||
spec.command = "flutter".into();
|
||||
}
|
||||
if let Some(device) = flutter_device {
|
||||
add_flutter_device(&mut arguments, device);
|
||||
}
|
||||
}
|
||||
}
|
||||
let id = DebugSessionId::next();
|
||||
let debug_server = take_debug_server(&mut arguments)?;
|
||||
if let Some(server) = &debug_server {
|
||||
@@ -1031,6 +1072,13 @@ impl DebugManager {
|
||||
if let Some(obj) = configuration.as_object_mut() {
|
||||
obj.entry("request").or_insert_with(|| request.clone().into());
|
||||
}
|
||||
let (spec, port) = match parent.port {
|
||||
Some(port) => (parent.spec.clone(), Some(port)),
|
||||
None => match subprocess_connection(&configuration, &parent.spec) {
|
||||
Some((spec, port)) => (spec, Some(port)),
|
||||
None => (parent.spec.clone(), None),
|
||||
},
|
||||
};
|
||||
self.start_session(
|
||||
DebugSessionId::next(),
|
||||
parent.owner.clone(),
|
||||
@@ -1039,8 +1087,8 @@ impl DebugManager {
|
||||
Some(parent.id),
|
||||
request,
|
||||
configuration,
|
||||
parent.spec.clone(),
|
||||
parent.port,
|
||||
spec,
|
||||
port,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
@@ -1105,6 +1153,9 @@ impl DebugManager {
|
||||
});
|
||||
tokio::spawn(session::event_loop(self.me.clone(), session.clone(), incoming));
|
||||
|
||||
if debugpy::listens(&session.adapter, &session.request, &arguments) {
|
||||
session.debugpy_version_unchecked.store(true, Ordering::Release);
|
||||
}
|
||||
let configured = tokio::select! {
|
||||
biased;
|
||||
_ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
@@ -1268,8 +1319,10 @@ impl DebugManager {
|
||||
let (files, idle): (Vec<_>, Vec<_>) = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(p, b)| (p.clone(), b.clone()))
|
||||
.get(&s.owner.key)
|
||||
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.partition(|(_, b)| b.iter().any(|b| b.enabled));
|
||||
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
|
||||
// Breakpoint states follow the owner's first session.
|
||||
@@ -1287,14 +1340,14 @@ impl DebugManager {
|
||||
Err(e) => tracing::debug!("setBreakpoints for {} failed: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&s.owner.key);
|
||||
if !functions.is_empty()
|
||||
&& s.supports("supportsFunctionBreakpoints")
|
||||
&& let Err(e) = s.send_function_breakpoints(&functions).await
|
||||
{
|
||||
tracing::debug!("setFunctionBreakpoints failed: {e}");
|
||||
}
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&s.owner.key);
|
||||
if !data.is_empty()
|
||||
&& s.supports("supportsDataBreakpoints")
|
||||
&& let Err(e) = s.send_data_breakpoints(&data).await
|
||||
@@ -1447,26 +1500,59 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Breakpoints are kept per file even without a session and sent on start.
|
||||
/// Returns states from the first live session, or unverified states when none.
|
||||
/// `owner`'s breakpoints are kept per file even without a session and sent when one of
|
||||
/// its sessions starts. Returns states from its first live session, or unverified states.
|
||||
pub async fn set_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
{
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
if breakpoints.is_empty() {
|
||||
store.remove(&path);
|
||||
lines.remove(&path);
|
||||
} else {
|
||||
store.insert(path.clone(), breakpoints.clone());
|
||||
lines.insert(path.clone(), breakpoints.clone());
|
||||
}
|
||||
}
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of `owner`'s line breakpoints with `files` (the window's whole list), sending
|
||||
/// the files that changed to its sessions. A file the window no longer lists can't stay
|
||||
/// behind and be sent to every later session, whatever made the two lists diverge (#6116).
|
||||
pub async fn replace_breakpoints(&self, owner: &str, files: BTreeMap<PathBuf, Vec<Breakpoint>>) -> IdeResult<()> {
|
||||
let changed: Vec<(PathBuf, Vec<Breakpoint>)> = {
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
let files: BTreeMap<_, _> = files.into_iter().filter(|(_, b)| !b.is_empty()).collect();
|
||||
let removed = lines.keys().filter(|p| !files.contains_key(*p)).map(|p| (p.clone(), Vec::new()));
|
||||
let changed = files.iter().filter(|(p, b)| lines.get(*p) != Some(b)).map(|(p, b)| (p.clone(), b.clone()));
|
||||
let changed = removed.chain(changed).collect();
|
||||
*lines = files;
|
||||
changed
|
||||
};
|
||||
for (path, breakpoints) in changed {
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops `owner`'s breakpoints (its window closed).
|
||||
pub fn forget_breakpoints(&self, owner: &str) {
|
||||
self.breakpoints.lock().remove(owner);
|
||||
}
|
||||
|
||||
async fn send_file_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
let mut result: Option<Vec<BreakpointState>> = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() {
|
||||
continue;
|
||||
}
|
||||
for s in self.configured_sessions(owner) {
|
||||
match s.send_breakpoints(&path, &breakpoints, None).await {
|
||||
Ok(states) => {
|
||||
result.get_or_insert(states);
|
||||
@@ -1617,16 +1703,39 @@ impl DebugManager {
|
||||
}
|
||||
|
||||
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
|
||||
const MAX_FRAMES: u64 = 400;
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
let body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
let request = |start: u64, levels: u64| {
|
||||
session.conn.request_timeout(
|
||||
"stackTrace",
|
||||
json!({ "threadId": thread_id, "startFrame": 0, "levels": 400 }),
|
||||
json!({ "threadId": thread_id, "startFrame": start, "levels": levels }),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
};
|
||||
let frames_of = |mut body: Value| match body.get_mut("stackFrames").map(Value::take) {
|
||||
Some(Value::Array(frames)) => frames,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let raw = match request(0, MAX_FRAMES).await {
|
||||
Ok(body) => frames_of(body),
|
||||
// java-debug fails the whole request when one frame's source lookup throws (on Windows,
|
||||
// a CGLIB proxy's `<generated>` source against `sourcePaths`): the frames come one at a
|
||||
// time instead, without the ones it cannot describe.
|
||||
// ponytail: one request per frame; page around the failing ones if deep stacks get slow.
|
||||
Err(first @ DapError::Failed { .. }) => {
|
||||
let Ok(top) = request(0, 1).await else { return Err(first.into()) };
|
||||
let total = top.get("totalFrames").and_then(Value::as_u64).unwrap_or(MAX_FRAMES).min(MAX_FRAMES);
|
||||
let mut raw = frames_of(top);
|
||||
for start in 1..total {
|
||||
if let Ok(body) = request(start, 1).await {
|
||||
raw.extend(frames_of(body));
|
||||
}
|
||||
}
|
||||
raw
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let kotlin_lsp = session.kotlin_lsp_quirks().is_some();
|
||||
let frame = |f: &Value| {
|
||||
let mut frame = frame_from(f);
|
||||
@@ -1638,7 +1747,7 @@ impl DebugManager {
|
||||
}
|
||||
frame
|
||||
};
|
||||
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
|
||||
Ok(raw.iter().map(frame).collect())
|
||||
}
|
||||
|
||||
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
|
||||
@@ -1830,7 +1939,7 @@ impl DebugManager {
|
||||
if force {
|
||||
self.suspend_breakpoints(&session, Some(&path)).await?;
|
||||
}
|
||||
let stored = self.stored_breakpoints(&path);
|
||||
let stored = self.stored_breakpoints(&session.owner.key, &path);
|
||||
let sent: Vec<Breakpoint> =
|
||||
if force { stored.iter().map(|b| Breakpoint { enabled: false, ..b.clone() }).collect() } else { stored };
|
||||
session.send_breakpoints(&path, &sent, Some(line)).await?;
|
||||
@@ -1845,10 +1954,15 @@ impl DebugManager {
|
||||
let files: Vec<PathBuf> = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
.get(&session.owner.key)
|
||||
.map(|b| {
|
||||
b.lines
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await;
|
||||
let mut failed = None;
|
||||
for (path, result) in files.into_iter().zip(sent) {
|
||||
@@ -1862,11 +1976,12 @@ impl DebugManager {
|
||||
if let Some(e) = failed {
|
||||
return Err(e.into());
|
||||
}
|
||||
if !self.function_breakpoints.lock().is_empty() && session.supports("supportsFunctionBreakpoints") {
|
||||
if !self.function_breakpoints(&session.owner.key).is_empty() && session.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
session.send_function_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().functions = true;
|
||||
}
|
||||
if !self.data_breakpoints.lock().is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
if !self.data_breakpoints(&session.owner.key).is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
session.send_data_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().data = true;
|
||||
}
|
||||
@@ -1876,8 +1991,11 @@ impl DebugManager {
|
||||
/// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced.
|
||||
pub(crate) async fn restore_breakpoints(&self, session: &Arc<Session>) {
|
||||
let pending = std::mem::take(&mut *session.pending_restore.lock());
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
|
||||
pending.files.into_iter().map(|path| (path.clone(), self.stored_breakpoints(&path))).collect();
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> = pending
|
||||
.files
|
||||
.into_iter()
|
||||
.map(|path| (path.clone(), self.stored_breakpoints(&session.owner.key, &path)))
|
||||
.collect();
|
||||
let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await;
|
||||
for ((path, _), result) in files.iter().zip(sent) {
|
||||
if let Err(e) = result {
|
||||
@@ -1885,13 +2003,13 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
if pending.functions {
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_function_breakpoints(&functions).await {
|
||||
tracing::debug!("restoring function breakpoints failed: {e}");
|
||||
}
|
||||
}
|
||||
if pending.data {
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_data_breakpoints(&data).await {
|
||||
tracing::debug!("restoring data breakpoints failed: {e}");
|
||||
}
|
||||
@@ -1977,20 +2095,27 @@ impl DebugManager {
|
||||
jvm_memory::session_heap_dump(session, dir, cancel).await
|
||||
}
|
||||
|
||||
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn. A JVM the
|
||||
/// debugger holds suspended is asked only when it is 17 or later and its listener already
|
||||
/// runs: otherwise the request would hang until the program resumes.
|
||||
pub async fn jvm_thread_dump(&self, s: DebugSessionId) -> IdeResult<JvmThreadsResult> {
|
||||
/// `Thread.print -l` of the session's JVM, taking the session's class-table turn, and on JDK
|
||||
/// 21+ the JSON dump written into `json_dir`. A JVM the debugger holds suspended is asked
|
||||
/// only when it is 17 or later and its listener already runs: otherwise the request would hang
|
||||
/// until the program resumes.
|
||||
pub async fn jvm_thread_dump(&self, s: DebugSessionId, json_dir: Option<PathBuf>) -> IdeResult<JvmThreadsResult> {
|
||||
let session = self.session(s)?;
|
||||
jvm_memory::session_thread_dump(session).await
|
||||
jvm_memory::session_thread_dump(session, json_dir).await
|
||||
}
|
||||
|
||||
/// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build
|
||||
/// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes
|
||||
/// it, under that session's turn and suspension. `None` when no session debugs `pid`.
|
||||
pub async fn debugged_jvm_thread_dump(&self, run: RunId, pid: u32) -> Option<IdeResult<JvmThreadsResult>> {
|
||||
/// it, under that session's turn and suspension, so a suspended JVM is not asked for the JSON
|
||||
/// dump either. `None` when no session debugs `pid`.
|
||||
pub async fn debugged_jvm_thread_dump(
|
||||
&self,
|
||||
run: RunId,
|
||||
pid: u32,
|
||||
json_dir: Option<PathBuf>,
|
||||
) -> Option<IdeResult<JvmThreadsResult>> {
|
||||
let session = self.jvm_session_of(run, pid)?;
|
||||
Some(jvm_memory::debugged_run_thread_dump(session, pid).await)
|
||||
Some(jvm_memory::debugged_run_thread_dump(session, pid, json_dir).await)
|
||||
}
|
||||
|
||||
/// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan
|
||||
@@ -2094,14 +2219,17 @@ impl DebugManager {
|
||||
Ok(hot_swap_result(&body))
|
||||
}
|
||||
|
||||
/// Stores method breakpoints (kept without a session, sent on start) and sends them to
|
||||
/// every configured session whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(&self, list: Vec<FunctionBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.function_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s method breakpoints (kept without a session, sent on start) and sends them
|
||||
/// to each of its configured sessions whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().functions = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsFunctionBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_function_breakpoints(&list).await {
|
||||
@@ -2114,12 +2242,17 @@ impl DebugManager {
|
||||
Ok(result.unwrap_or_else(|| unverified(list.iter().map(|b| b.enabled))))
|
||||
}
|
||||
|
||||
/// Stores field watchpoints and sends them to every configured session that supports them.
|
||||
pub async fn set_data_breakpoints(&self, list: Vec<DataBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.data_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s field watchpoints and sends them to each of its configured sessions that
|
||||
/// supports them.
|
||||
pub async fn set_data_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().data = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsDataBreakpoints") {
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsDataBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_data_breakpoints(&list).await {
|
||||
|
||||
@@ -75,6 +75,8 @@ pub(crate) struct Session {
|
||||
pub jdwp_port: std::sync::OnceLock<u16>,
|
||||
/// The attach goes through the listen-mode relay of [`crate::jdwp::listen_for_jvm`].
|
||||
pub listen_relay: AtomicBool,
|
||||
/// A Python Debug Server session whose program's debugpy version is checked on its first stop.
|
||||
pub(crate) debugpy_version_unchecked: AtomicBool,
|
||||
pub suspended: Suspension,
|
||||
/// Pids signalled for the current stop: the reported pid and everything it started (an
|
||||
/// adapter may report the launcher shell, whose child is the program).
|
||||
@@ -316,6 +318,7 @@ impl Session {
|
||||
jvm_pid: AtomicI64::new(0),
|
||||
jdwp_port: std::sync::OnceLock::new(),
|
||||
listen_relay: AtomicBool::new(false),
|
||||
debugpy_version_unchecked: AtomicBool::new(false),
|
||||
suspended: Suspension::default(),
|
||||
stop_pids: parking_lot::Mutex::new(Vec::new()),
|
||||
#[cfg(windows)]
|
||||
@@ -854,6 +857,11 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
all_threads_stopped: all,
|
||||
});
|
||||
});
|
||||
if let Some(thread) = int("threadId")
|
||||
&& s.debugpy_version_unchecked.swap(false, Ordering::AcqRel)
|
||||
{
|
||||
tokio::spawn(crate::debugpy::check_version(s.clone(), thread));
|
||||
}
|
||||
}
|
||||
"continued" => {
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
|
||||
@@ -1017,6 +1025,13 @@ fn on_reverse_request(mgr: &Arc<DebugManager>, s: &Arc<Session>, seq: i64, comma
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` as a terminal sends it when typed: Enter is CR. A Unix terminal turns CR into the
|
||||
/// newline a line read waits for, but Windows' ConPTY reads LF as Ctrl+J, so a program blocked
|
||||
/// in `input()` never sees its line end (#6041).
|
||||
fn as_typed(text: &str) -> std::borrow::Cow<'_, str> {
|
||||
if text.contains('\n') { text.replace("\r\n", "\r").replace('\n', "\r").into() } else { text.into() }
|
||||
}
|
||||
|
||||
/// A `runInTerminal` program and the pseudo-terminal it runs in.
|
||||
pub(crate) struct ProgramTerminal {
|
||||
writer: Arc<ide_core::input::InputWriter>,
|
||||
@@ -1030,7 +1045,7 @@ pub(crate) struct ProgramTerminal {
|
||||
|
||||
impl ProgramTerminal {
|
||||
pub(crate) fn write(&mut self, text: &str) -> std::io::Result<()> {
|
||||
self.writer.write(text.as_bytes())
|
||||
self.writer.write(as_typed(text).as_bytes())
|
||||
}
|
||||
|
||||
/// The program's process id while it runs.
|
||||
@@ -1061,7 +1076,8 @@ fn reap_on_exit(mut child: Box<dyn portable_pty::Child + Send + Sync>, exited: A
|
||||
/// starts a launcher that gives the program its terminal, and the program reads input only from
|
||||
/// a terminal), forwards its output to the console, and keeps the terminal for typed input.
|
||||
pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, String> {
|
||||
use portable_pty::{CommandBuilder, PtySize, native_pty_system};
|
||||
use ide_core::pty::native_pty_system;
|
||||
use portable_pty::{CommandBuilder, PtySize};
|
||||
let argv: Vec<String> = args
|
||||
.get("args")
|
||||
.and_then(Value::as_array)
|
||||
@@ -1385,6 +1401,13 @@ fn parse_jdwp_port(line: &str) -> Option<u16> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn typed_input_ends_lines_with_enter() {
|
||||
assert_eq!(super::as_typed("42\n"), "42\r");
|
||||
assert_eq!(super::as_typed("a\r\nb\n"), "a\rb\r");
|
||||
assert_eq!(super::as_typed("no newline"), "no newline");
|
||||
}
|
||||
|
||||
use super::{Suspension, kotlin_jvm_args, parse_jdwp_port};
|
||||
|
||||
#[test]
|
||||
|
||||
Loaded 100 of 2053 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача