mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 09:01:00 -10:00
Compare commits
516
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31b076dd32 | ||
|
|
4074d079b1 | ||
|
|
2d0120f092 | ||
|
|
df470f93c6 | ||
|
|
764b6717e0 | ||
|
|
7aa6adb0ef | ||
|
|
7ebdf04e2f | ||
|
|
c0f7ec93d3 | ||
|
|
cc9089db11 | ||
|
|
62095b904e | ||
|
|
96c5e94975 | ||
|
|
97e9657fd3 | ||
|
|
1205ffecd2 | ||
|
|
51766249f9 | ||
|
|
ff55bcdf9a | ||
|
|
fd6d1d5d0e | ||
|
|
9ad5bad82e | ||
|
|
fec50f3925 | ||
|
|
8b3d9adcfe | ||
|
|
457174a442 | ||
|
|
de868f1677 | ||
|
|
e27fc0d867 | ||
|
|
c50c2ea629 | ||
|
|
3e9e86edf1 | ||
|
|
cb24be4c19 | ||
|
|
52e3276f93 | ||
|
|
fcf5406de0 | ||
|
|
aee72d994e | ||
|
|
397522e099 | ||
|
|
f7e1dbe5eb | ||
|
|
52096fc904 | ||
|
|
296c3d1477 | ||
|
|
c72a162b5c | ||
|
|
3989b2715c | ||
|
|
aa1b6c1ce0 | ||
|
|
2afd636314 | ||
|
|
de11bc02f1 | ||
|
|
2f8d5f5118 | ||
|
|
4b4c25d7b1 | ||
|
|
ca0f71bc39 | ||
|
|
b60b743843 | ||
|
|
e6461f4935 | ||
|
|
0ef62c4999 | ||
|
|
7d39ab693c | ||
|
|
71b4e1c367 | ||
|
|
90bba44ba7 | ||
|
|
68c4fe60ec | ||
|
|
558a98e74e | ||
|
|
8d701da584 | ||
|
|
bd0f28cd3b | ||
|
|
ea7ec41064 | ||
|
|
b1db1c6c3d | ||
|
|
33ffa6cac1 | ||
|
|
a8aefa57c8 | ||
|
|
1c24b77239 | ||
|
|
ae5c94e7d0 | ||
|
|
fe9ee6a7a7 | ||
|
|
b5bff2fdfa | ||
|
|
e5f078913c | ||
|
|
5006e1934d | ||
|
|
14d6d6892d | ||
|
|
080b7e80e7 | ||
|
|
92d94a7ac4 | ||
|
|
518a62ea6c | ||
|
|
d16a87cf58 | ||
|
|
f9fd1257c7 | ||
|
|
e57a709d19 | ||
|
|
abab90ca60 | ||
|
|
9d94b00911 | ||
|
|
cc1cc4cce5 | ||
|
|
2478f67066 | ||
|
|
dc2924db17 | ||
|
|
348f4c2a2e | ||
|
|
431b87c717 | ||
|
|
3a53d13315 | ||
|
|
23f591289c | ||
|
|
8684e95778 | ||
|
|
9d9e3f1c4f | ||
|
|
5eff75cab5 | ||
|
|
aec1382e79 | ||
|
|
999d84b189 | ||
|
|
9fda9b92c2 | ||
|
|
261eb03009 | ||
|
|
db8b553364 | ||
|
|
2494b2efdf | ||
|
|
d78ce7ec66 | ||
|
|
9df9499bf5 | ||
|
|
d4b5581441 | ||
|
|
d96060f08b | ||
|
|
507258daec | ||
|
|
dae402b966 | ||
|
|
39e803b8f9 | ||
|
|
d6b56856d2 | ||
|
|
8a84e8f473 | ||
|
|
f31aa29f3e | ||
|
|
639e4b3df9 | ||
|
|
01b9908898 | ||
|
|
7f201ed87d | ||
|
|
85344b86b5 | ||
|
|
12e85a7c1b | ||
|
|
861acabf77 | ||
|
|
96395c979f | ||
|
|
e9f768d8b5 | ||
|
|
d15abe54e2 | ||
|
|
b501f51526 | ||
|
|
50cd478773 | ||
|
|
2c63f0eb22 | ||
|
|
ed1730f273 | ||
|
|
d6d0cc7926 | ||
|
|
a21de32077 | ||
|
|
546ff9f314 | ||
|
|
a144208170 | ||
|
|
fda2d2ff69 | ||
|
|
0fdf37f1bf | ||
|
|
5c592bbc86 | ||
|
|
819ccb8bb5 | ||
|
|
ae893f059f | ||
|
|
fb2f567d5b | ||
|
|
22af0931dd | ||
|
|
4af81625b1 | ||
|
|
f3d18c0eb8 | ||
|
|
e662c915a2 | ||
|
|
f57a17ec14 | ||
|
|
0b8d9135aa | ||
|
|
290ef6956e | ||
|
|
8a4b8f45b4 | ||
|
|
31b265cb41 | ||
|
|
a6a05caa2e | ||
|
|
4690463c53 | ||
|
|
8200ce8b5e | ||
|
|
b524f738e5 | ||
|
|
1f871dc1c2 | ||
|
|
ceb3cef1af | ||
|
|
735a0157c1 | ||
|
|
82f26202ed | ||
|
|
a90a9b20e3 | ||
|
|
aad701ba16 | ||
|
|
46d4036038 | ||
|
|
19859b4ae2 | ||
|
|
f3f05f8b15 | ||
|
|
b0417c83f4 | ||
|
|
4a5d90a91e | ||
|
|
1e61b3b270 | ||
|
|
0809eb417c | ||
|
|
86531ee1ba | ||
|
|
54f0373acf | ||
|
|
137b1cc384 | ||
|
|
6c9d432504 | ||
|
|
2395c9544b | ||
|
|
4b55039e6e | ||
|
|
7264194b0f | ||
|
|
9ebdf0d68f | ||
|
|
0843dd8363 | ||
|
|
9935bfb7c6 | ||
|
|
db08dbc4f5 | ||
|
|
cfab86588b | ||
|
|
ba300ecbf9 | ||
|
|
1e79ccaf41 | ||
|
|
6815cb5f89 | ||
|
|
a79d551bd3 | ||
|
|
0284b7091b | ||
|
|
93143ce872 | ||
|
|
6cbb27ed82 | ||
|
|
74cf06505f | ||
|
|
d6d73e1072 | ||
|
|
bbea793adf | ||
|
|
f1c556e2ec | ||
|
|
2d99a79e69 | ||
|
|
ca778e2382 | ||
|
|
414353a5bd | ||
|
|
3080dc6100 | ||
|
|
1bb9f8d07c | ||
|
|
a539baec37 | ||
|
|
7dff6e1852 | ||
|
|
fc7fa85850 | ||
|
|
7e5a2cf051 | ||
|
|
c4e08a9676 | ||
|
|
2c0b76c9e6 | ||
|
|
4d1f51c607 | ||
|
|
2215239ecb | ||
|
|
43eeb080be | ||
|
|
03a19d4284 | ||
|
|
3aeee3fcfc | ||
|
|
471003a8c5 | ||
|
|
c109773d2a | ||
|
|
ed6b67faed | ||
|
|
ff7bfcaf1d | ||
|
|
91330a82d0 | ||
|
|
ce75c58a34 | ||
|
|
03b9070b9b | ||
|
|
f6f610516c | ||
|
|
cf49a91b66 | ||
|
|
e0a97e32f7 | ||
|
|
dd0eeeae29 | ||
|
|
4bb22df1fb | ||
|
|
aee087597a | ||
|
|
993a321dd0 | ||
|
|
381e66aca5 | ||
|
|
d7a05eea21 | ||
|
|
c61ddbff3d | ||
|
|
0c20d72cbf | ||
|
|
021f334c0c | ||
|
|
c61264cdf9 | ||
|
|
e4d6f50a0b | ||
|
|
0435e0330e | ||
|
|
13b5f9e575 | ||
|
|
dde4b28abd | ||
|
|
3817724637 | ||
|
|
26b5856ce0 | ||
|
|
6aeb733f20 | ||
|
|
29fcec6ab8 | ||
|
|
5d6c76cdda | ||
|
|
844c2f3145 | ||
|
|
76d67145f5 | ||
|
|
cf4273eeea | ||
|
|
81dd5f0dd2 | ||
|
|
36061abc91 | ||
|
|
b8a11df800 | ||
|
|
401c542647 | ||
|
|
a435be54e0 | ||
|
|
4b58b2a5a5 | ||
|
|
39068cffb3 | ||
|
|
bef9223913 | ||
|
|
f2b06bc376 | ||
|
|
08d719e03d | ||
|
|
aa849b9cf4 | ||
|
|
0cc8f90708 | ||
|
|
bc307fdea3 | ||
|
|
407f1c5235 | ||
|
|
ddf9cc3d70 | ||
|
|
6e4f536722 | ||
|
|
d3be99543d | ||
|
|
f0cc99a4c7 | ||
|
|
8db16dea32 | ||
|
|
6a7297519c | ||
|
|
08362db3ca | ||
|
|
b7f3df0472 | ||
|
|
c5824771c1 | ||
|
|
40e5f9b7b3 | ||
|
|
8bc82d08c6 | ||
|
|
b0473f17b5 | ||
|
|
21264641ba | ||
|
|
3ce4578600 | ||
|
|
e89b565a78 | ||
|
|
b2a1ee2204 | ||
|
|
828cb271d9 | ||
|
|
ed369c2a6d | ||
|
|
3103ec19f9 | ||
|
|
026ef8794f | ||
|
|
7e77c270b7 | ||
|
|
9abca932d1 | ||
|
|
ce6c61aa5e | ||
|
|
9e8722feb6 | ||
|
|
f2950defcf | ||
|
|
0130847bc0 | ||
|
|
b9f9e2668a | ||
|
|
1f39eb8e63 | ||
|
|
a4db4a9e3f | ||
|
|
c209e189e0 | ||
|
|
0b83b3ffbc | ||
|
|
7caec95fee | ||
|
|
3d56af936d | ||
|
|
0a3eac8652 | ||
|
|
70702934d1 | ||
|
|
8e541d5b45 | ||
|
|
87c4659547 | ||
|
|
3475dbd688 | ||
|
|
0800e8445f | ||
|
|
b7ac5f1bbb | ||
|
|
f473cd9927 | ||
|
|
9a3b97a5fa | ||
|
|
c632dfa01c | ||
|
|
88f494ca50 | ||
|
|
9b4ee2a6ff | ||
|
|
e75d438f70 | ||
|
|
a67b27c33a | ||
|
|
62028362d6 | ||
|
|
c57af26f9d | ||
|
|
ed6f264875 | ||
|
|
369f52d39e | ||
|
|
305ff382e7 | ||
|
|
92dbf0baa5 | ||
|
|
b02f212d3e | ||
|
|
ca7f26f484 | ||
|
|
bf4fff8fcf | ||
|
|
3cbe327a6a | ||
|
|
0311297886 | ||
|
|
a711c991b6 | ||
|
|
698cad2b3f | ||
|
|
581c64f544 | ||
|
|
77d6d81f8a | ||
|
|
ea62941bc6 | ||
|
|
00e044b66b | ||
|
|
1db368d2b4 | ||
|
|
db50b5df5b | ||
|
|
17fe162f6c | ||
|
|
0fc462350b | ||
|
|
ff80b4351a | ||
|
|
af2be518ec | ||
|
|
9f60e9b209 | ||
|
|
1838919f47 | ||
|
|
256d77c3f6 | ||
|
|
7ec2b18b63 | ||
|
|
f8ec222a0d | ||
|
|
aad0573fb9 | ||
|
|
8ea0052a7f | ||
|
|
b20e0b0902 | ||
|
|
e3fca1bb6f | ||
|
|
bfea07a30e | ||
|
|
4d5648c38d | ||
|
|
fbcbfb648c | ||
|
|
bf2478934e | ||
|
|
8f252398fe | ||
|
|
54c7cbc3b0 | ||
|
|
1fd9246ccc | ||
|
|
7b6ac0d5a8 | ||
|
|
d764f9cae1 | ||
|
|
3908b70b61 | ||
|
|
c1f0a85718 | ||
|
|
acdd88f0f7 | ||
|
|
1f8c869293 | ||
|
|
f3928b3553 | ||
|
|
5161d266ab | ||
|
|
b30b30311f | ||
|
|
c9c6d87a14 | ||
|
|
97ffd9aae9 | ||
|
|
5e39650886 | ||
|
|
444c315d57 | ||
|
|
a4bea25ae3 | ||
|
|
84b1770da4 | ||
|
|
88295ecca8 | ||
|
|
e87aee5969 | ||
|
|
84d8be1181 | ||
|
|
27cbdb1ba6 | ||
|
|
1005dc1363 | ||
|
|
3f3cdeba0d | ||
|
|
9b8c88e1ee | ||
|
|
392574fe2a | ||
|
|
41829e74db | ||
|
|
aee21233fb | ||
|
|
17f5889037 | ||
|
|
ff6c6eb13f | ||
|
|
ac015847a3 | ||
|
|
4c774d2e8e | ||
|
|
8adbbd1b05 | ||
|
|
c207e57686 | ||
|
|
ac0a56d1ec | ||
|
|
07cbb560df | ||
|
|
88936106ab | ||
|
|
78041f3745 | ||
|
|
d0eeb5e8c3 | ||
|
|
5a9783dbf0 | ||
|
|
74c2757a7a | ||
|
|
ff6187ebf9 | ||
|
|
708ceac09a | ||
|
|
5ba43e93e5 | ||
|
|
c552183924 | ||
|
|
f2adcccf2a | ||
|
|
158d11bd7f | ||
|
|
c6de070cba | ||
|
|
42b9106ade | ||
|
|
92a49f19af | ||
|
|
f58e6d1259 | ||
|
|
13a2356fa1 | ||
|
|
002751e524 | ||
|
|
ac87278ddd | ||
|
|
a62d4d11c3 | ||
|
|
0164e82e32 | ||
|
|
edb8f69024 | ||
|
|
ccfa4a1f22 | ||
|
|
8eb332aba7 | ||
|
|
0798582173 | ||
|
|
46883c413c | ||
|
|
840dddb897 | ||
|
|
ae51e195a5 | ||
|
|
205be89d4e | ||
|
|
ece9c7ef73 | ||
|
|
fe55a73e97 | ||
|
|
65b0cc45f0 | ||
|
|
aaab9a5dc6 | ||
|
|
4bc68d27cc | ||
|
|
50f0363669 | ||
|
|
0ff51fdae4 | ||
|
|
7df0880dcc | ||
|
|
312559e121 | ||
|
|
db8f9a72b0 | ||
|
|
0a7a292d82 | ||
|
|
a78d1fdc27 | ||
|
|
8681bfab0d | ||
|
|
2e7aab9ec6 | ||
|
|
c08b9b8d4d | ||
|
|
81b357cdce | ||
|
|
9eaa44e004 | ||
|
|
a3dc3c99a6 | ||
|
|
4c19b7d5b0 | ||
|
|
85edcf0660 | ||
|
|
49dd1bbef3 | ||
|
|
aa73f4c2b9 | ||
|
|
5375099042 | ||
|
|
2c47bd58bb | ||
|
|
d80aeb6e9e | ||
|
|
55a5e79c9f | ||
|
|
df4210f529 | ||
|
|
09d8e92e2c | ||
|
|
221b6c3098 | ||
|
|
d154dce4f7 | ||
|
|
83364c5423 | ||
|
|
fa33819afb | ||
|
|
5e6a59eae8 | ||
|
|
a9971905dc | ||
|
|
7e6296f0c6 | ||
|
|
31c169c889 | ||
|
|
13103fd5af | ||
|
|
50340219ac | ||
|
|
71000e15f2 | ||
|
|
042008f681 | ||
|
|
942e6cb237 | ||
|
|
674cdd3925 | ||
|
|
04666f5980 | ||
|
|
d335ba5fdd | ||
|
|
33d2f34e58 | ||
|
|
7646bc4746 | ||
|
|
2c161812a0 | ||
|
|
1778bf1ef3 | ||
|
|
1e7fe7605b | ||
|
|
67dcf5c978 | ||
|
|
20404d2f44 | ||
|
|
b44e552628 | ||
|
|
bc4e8e9655 | ||
|
|
c12799c973 | ||
|
|
0d4bd4a69a | ||
|
|
bf2f44d523 | ||
|
|
2b6fab3c1c | ||
|
|
37df909358 | ||
|
|
b51054daca | ||
|
|
57856f2d54 | ||
|
|
e06c16f547 | ||
|
|
7b893d2982 | ||
|
|
1cc8a361b8 | ||
|
|
a28f6ce331 | ||
|
|
5d27b4254b | ||
|
|
45d85f5721 | ||
|
|
fa7fcd0d90 | ||
|
|
6b2b4a96e7 | ||
|
|
d507e67123 | ||
|
|
5563345a8f | ||
|
|
bff0761c48 | ||
|
|
2811a438a0 | ||
|
|
d34252c80a | ||
|
|
a60a36f052 | ||
|
|
939222cdfb | ||
|
|
ec0370ec23 | ||
|
|
9243ff2eac | ||
|
|
143281d67e | ||
|
|
e1f25d2747 | ||
|
|
26fce11f94 | ||
|
|
c5c2fb7c98 | ||
|
|
31ca9daa61 | ||
|
|
d89991168e | ||
|
|
16496f8001 | ||
|
|
ce58c873da | ||
|
|
d069c3daff | ||
|
|
95b71e1ffc | ||
|
|
732cfd6002 | ||
|
|
189879f0fa | ||
|
|
f0a412f3e2 | ||
|
|
1a470e2a23 | ||
|
|
793c720f7f | ||
|
|
93c7f8b7fd | ||
|
|
3e37b60505 | ||
|
|
a5c8fe17fd | ||
|
|
0684795334 | ||
|
|
30cbb80f22 | ||
|
|
5cfb0d3311 | ||
|
|
bccf1bd7d6 | ||
|
|
3d79454be8 | ||
|
|
46e4af2b32 | ||
|
|
067edb7d60 | ||
|
|
0a4abf1705 | ||
|
|
d31699c86a | ||
|
|
9467c4ea1b | ||
|
|
7c12c58874 | ||
|
|
9f47ef0991 | ||
|
|
3b614dda7a | ||
|
|
5acd778340 | ||
|
|
7c682a580f | ||
|
|
dc07691279 | ||
|
|
2d04a3d9bc | ||
|
|
8f9b9b1016 | ||
|
|
096964c798 | ||
|
|
f1bfd5db52 | ||
|
|
a17af582f3 | ||
|
|
47f018d8b5 | ||
|
|
94aa62430c | ||
|
|
4242c94bfc | ||
|
|
8864ff595d | ||
|
|
0a08d9f4ce | ||
|
|
7dbfe8852e | ||
|
|
ae97d5f1c2 | ||
|
|
4340a96c59 | ||
|
|
0af7bcc7cf | ||
|
|
4f52f5ebfa | ||
|
|
f284633162 | ||
|
|
0ceda2c385 | ||
|
|
8b3f55dfb4 | ||
|
|
c0e888dd2f | ||
|
|
04bed01942 | ||
|
|
dfafe6c767 | ||
|
|
461c71a50b | ||
|
|
82085a227e | ||
|
|
c3f420374c | ||
|
|
6bf7bc8c2b | ||
|
|
34dfc166db | ||
|
|
64632dc4d7 | ||
|
|
f484fd6802 | ||
|
|
8121dc87f1 |
No files matched your search
Binary file not shown.
|
Before Width: | Height: | Size: 160 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 169 KiB |
@@ -65,8 +65,9 @@ jobs:
|
||||
plugin_web='^plugins/official/[^/]+/web-src/'
|
||||
# Paths the frontend checks never read...
|
||||
backend='^(crates/|src-tauri/|sdk/|wit/|java/|fixtures/|Cargo\.(toml|lock)$|deny\.toml$|rustfmt\.toml$|rust-toolchain(\.toml)?$|\.cargo/)'
|
||||
# ...except these, which frontend tests and e2e fixtures load.
|
||||
read_by_web='^(fixtures/(folding|django-app)/|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
|
||||
# ...except these, which frontend tests and e2e fixtures load (the crate manifests:
|
||||
# scripts/smoke-paths.test.ts, through cargo metadata).
|
||||
read_by_web='^(fixtures/(folding|django-app)/|(crates/[^/]+/)?Cargo\.toml$|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
|
||||
# What the browser app and its e2e tests are built from.
|
||||
app='^(src/|e2e/|public/|index\.html$|vite\.config\.ts$|tsconfig\.json$|playwright\.config\.ts$|package\.json$|pnpm-(lock|workspace)\.yaml$|crates/ide-plugin/tests/fixtures/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
|
||||
# The plugin workspaces: the SDK, the plugins, their interface and the host's fixture plugins.
|
||||
@@ -101,24 +102,44 @@ jobs:
|
||||
name: Rust (${{ matrix.os }})
|
||||
needs: changes
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
permissions:
|
||||
contents: read
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-latest, ubuntu-22.04, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ matrix.os == 'ubuntu-22.04' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { components: "clippy, rustfmt" }
|
||||
# Only main saves the cache (saving takes minutes on Windows); PRs restore main's.
|
||||
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
|
||||
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- uses: taiki-e/install-action@nextest
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
@@ -134,6 +155,12 @@ jobs:
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
docker pull busybox:latest
|
||||
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
|
||||
-E 'test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
|
||||
# nextest skips doctests; ide-command's are its compile-fail tests.
|
||||
- if: runner.os == 'Linux'
|
||||
run: cargo test --doc -p ide-command
|
||||
@@ -279,7 +306,7 @@ jobs:
|
||||
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
|
||||
|
||||
e2e:
|
||||
name: E2E (${{ matrix.shard }}/2)
|
||||
name: E2E (${{ matrix.shard }}/4)
|
||||
needs: changes
|
||||
if: needs.changes.outputs.e2e == 'true'
|
||||
timeout-minutes: 30
|
||||
@@ -287,7 +314,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2]
|
||||
shard: [1, 2, 3, 4]
|
||||
# Browsers and their system libraries are preinstalled; keep the tag in step with @playwright/test.
|
||||
container: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||
steps:
|
||||
@@ -297,7 +324,7 @@ jobs:
|
||||
- uses: actions/setup-node@v5
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/2
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/4
|
||||
env:
|
||||
HOME: /root
|
||||
- uses: actions/upload-artifact@v6
|
||||
|
||||
@@ -8,6 +8,9 @@ name: Language smoke
|
||||
# (Run, Run tests, the test tree, Rerun Failed Tests): smoke/run.test.ts; and debugging its
|
||||
# entry point with the debugger the IDE installs (breakpoint, frames, variables, evaluate,
|
||||
# Step Over, Resume): smoke/debug.test.ts.
|
||||
# The paths below and the Changes step's patterns must cover every file the smoke loads and
|
||||
# every crate it runs: scripts/smoke-paths.test.ts checks them (`node scripts/smoke-paths.ts
|
||||
# [file…]` lists what they miss, or the languages a change runs).
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
@@ -20,10 +23,32 @@ on:
|
||||
- "Cargo.lock"
|
||||
- "src/features/run/**"
|
||||
- "src/features/debugger/**"
|
||||
- "src/features/build-tools/**"
|
||||
- "src/platform/**"
|
||||
- "src/workbench/**"
|
||||
- "src/ui/**"
|
||||
- "src/editor/api.ts"
|
||||
- "src/editor/navigationProviders.ts"
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
- "src/editor/lsp/files.ts"
|
||||
- "src/editor/lsp/hint.ts"
|
||||
- "src/editor/lsp/lsp.ts"
|
||||
- "src/editor/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.yaml"
|
||||
- "pnpm-workspace.yaml"
|
||||
- "patches/**"
|
||||
- ".github/workflows/language-smoke.yml"
|
||||
- ".github/tool-versions.env"
|
||||
pull_request:
|
||||
@@ -40,6 +65,8 @@ concurrency:
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
# Line tables keep test backtraces readable and the binaries the build job hands on small.
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
|
||||
jobs:
|
||||
# The languages a pull request can affect: a change to one language's fixture, definition or
|
||||
@@ -70,10 +97,12 @@ jobs:
|
||||
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
|
||||
cat files.txt
|
||||
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
|
||||
# SDKs, build tools and the project model): cargo metadata, deps of ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-search|ide-spell|ide-ssh|ide-streams|ide-vcs|ide-web)/'
|
||||
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
|
||||
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-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)/|src/platform/|smoke/|package\.json$|pnpm-lock\.yaml$|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
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$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
@@ -105,10 +134,40 @@ jobs:
|
||||
done < files.txt
|
||||
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
smoke:
|
||||
name: Language smoke (${{ matrix.language }})
|
||||
# Builds the smoke test binaries and openidea-server once for every language below.
|
||||
build:
|
||||
name: Build
|
||||
needs: changes
|
||||
if: needs.changes.outputs.languages != '[]'
|
||||
# The tests find the fixtures through the checkout path compiled into them (CARGO_MANIFEST_DIR),
|
||||
# which is the same on every GitHub-hosted runner.
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
shared-key: language-smoke
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- run: |
|
||||
set -euo pipefail
|
||||
mkdir -p smoke-bin
|
||||
cargo test --locked -p ide-host --test language_smoke --test project_smoke --no-run --message-format=json \
|
||||
| jq -r 'select(.reason == "compiler-artifact" and .executable != null and .target.kind == ["test"]) | "\(.target.name) \(.executable)"' \
|
||||
| while read -r name exe; do cp "$exe" "smoke-bin/$name"; done
|
||||
cargo build --locked -p ide-host --bin openidea-server
|
||||
cp target/debug/openidea-server smoke-bin/
|
||||
ls -l smoke-bin
|
||||
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
|
||||
# A tar keeps the executable bits, which artifacts drop.
|
||||
tar -cf smoke-bin.tar smoke-bin
|
||||
- uses: actions/upload-artifact@v6
|
||||
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
|
||||
|
||||
smoke:
|
||||
name: Language smoke (${{ matrix.language }})
|
||||
needs: [changes, build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -122,11 +181,11 @@ jobs:
|
||||
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with: { components: "rust-analyzer, rustfmt" }
|
||||
# One build cache for every language; main saves it.
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
shared-key: language-smoke
|
||||
save-if: ${{ github.ref == 'refs/heads/main' && matrix.language == 'rust' }}
|
||||
- uses: actions/download-artifact@v6
|
||||
with: { name: smoke-bin }
|
||||
- run: |
|
||||
tar -xf smoke-bin.tar && rm smoke-bin.tar
|
||||
mkdir -p target/debug && mv smoke-bin/openidea-server target/debug/
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with: { version: 11 }
|
||||
@@ -182,17 +241,20 @@ jobs:
|
||||
- if: matrix.language == 'php'
|
||||
run: npm install --global "intelephense@$INTELEPHENSE"
|
||||
|
||||
- run: cargo test --locked -p ide-host --test language_smoke --no-run
|
||||
- run: cargo test --locked -p ide-host --test language_smoke -- --ignored --exact ${{ matrix.language }}
|
||||
# The binaries from the build job, run from the crate directory as `cargo test` does.
|
||||
- working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
|
||||
- if: matrix.language == 'java'
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
- if: matrix.language == 'kotlin'
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact gradle_sync
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
|
||||
- if: matrix.language == 'python'
|
||||
run: cargo test --locked -p ide-host --test project_smoke -- --ignored --exact python_venv
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: cargo build --locked -p ide-host --bin openidea-server
|
||||
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
|
||||
- run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$"
|
||||
# The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
|
||||
|
||||
@@ -73,10 +73,15 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
|
||||
|
||||
## Commands
|
||||
|
||||
- `pnpm tauri dev` — run the app with worktree isolation (Node 22.18+).
|
||||
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
|
||||
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
|
||||
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
|
||||
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
|
||||
this worktree's running MCP bridges and actual ports.
|
||||
- `pnpm build` — typecheck + bundle frontend.
|
||||
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
|
||||
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
|
||||
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
|
||||
Generated
+129
-152
@@ -1104,9 +1104,9 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.2"
|
||||
version = "0.18.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
|
||||
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
|
||||
dependencies = [
|
||||
"time",
|
||||
"version_check",
|
||||
@@ -1203,27 +1203,27 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-assembler-x64"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aecefa88696b62f833cc0c997d19c93246b0268e2aaf23e0e8692e527f6de088"
|
||||
checksum = "c19fba13ee427c4dd29488ea51127e945bf07fd9d79093f14c9cc57f74acf757"
|
||||
dependencies = [
|
||||
"cranelift-assembler-x64-meta",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-assembler-x64-meta"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1391a2546f5edf06a0ff5e9430d73c2713fd536aefec53200dc21846d1467f53"
|
||||
checksum = "dd88c766346fcc14bbadbd68cb11e9bc1e555e99f7e8f6b1f4c27a73ca659bec"
|
||||
dependencies = [
|
||||
"cranelift-srcgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-bforest"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9528915fbc2c950702329e08c6d72aaff8ece9b7ecdbd225742825c09a445227"
|
||||
checksum = "f19d43d75dd963d6b1a653f2e03d4eed4365ca2e598ec57e52c15afdad6c3276"
|
||||
dependencies = [
|
||||
"cranelift-entity",
|
||||
"wasmtime-internal-core",
|
||||
@@ -1231,9 +1231,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-bitset"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9dd69a6db85c1bcff989809e0e0b3b06506425f32b545c46aeafda5fe7775d6a"
|
||||
checksum = "45d0b93e50856858c89c61cbe3f6d4b07596da22eb5a03a95b19420e1d08a275"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_derive",
|
||||
@@ -1242,9 +1242,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-codegen"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24c2db6c26cd96393cf785c4b51b900738963cc7422aa0045416a7641ae2f6cd"
|
||||
checksum = "efbdff32d3b6b4f33f1ba8a4ac747b97ce569b1d6834c3089c1c0933b94e618c"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"cranelift-assembler-x64",
|
||||
@@ -1273,9 +1273,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-codegen-meta"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e284270142e7f1dcb73a992a62a8b3716b4062a65a52d8f2732c6ebf6f7f342f"
|
||||
checksum = "67fd11ff24916a2c1ff852ce4bb664fcf2c2970ed551de44dd5b573321123703"
|
||||
dependencies = [
|
||||
"cranelift-assembler-x64-meta",
|
||||
"cranelift-codegen-shared",
|
||||
@@ -1286,24 +1286,24 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-codegen-shared"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6595667b7d505cf85d5bdd014e6f57ad6128183238f8e372319d9384782472f5"
|
||||
checksum = "ba5d321229c3e00a17d7bb3633529ffdf97a13bcf4962fd2e92f1e0fd39360aa"
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-control"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f26ffdbfcd24c3833d730849e6d132af34a400a2b89b44446015c01eecbea21d"
|
||||
checksum = "71cd63450256d0f80f7a0527e133452f84fa6e1ca73c7db6ca2a9e8cc89d1c18"
|
||||
dependencies = [
|
||||
"arbitrary",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-entity"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ffb08ccd8a77fb31cdbbda2afa2333d8f85299b1bc0d1c194259ba66d160d74"
|
||||
checksum = "18d2f259130db1bbb89500d26944971a9beeb410de91ff14039203f055d7f9f0"
|
||||
dependencies = [
|
||||
"cranelift-bitset",
|
||||
"serde",
|
||||
@@ -1313,9 +1313,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-frontend"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b447e4f2bb44b1188185a77f478e5a91b7723a40b3b58c3e2d5b26df2ed5a665"
|
||||
checksum = "cf37a38d982d45fe2c065d55e4de76e596b443b6acceb3ca726c2072c8ba6d7b"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -1326,15 +1326,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-isle"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f0989e943f3a9d41989595826bba544df9fda64bcddd4df0c06fb2e26af3cb3"
|
||||
checksum = "8ce8f84e2d44326879e18016d763457a2cb5d775e4a5822cd7473fc171fca063"
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-native"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5fa10df59e776c42dae5b6ba5216ba5321707a2136abd2219e615c54b234fc1b"
|
||||
checksum = "df64a0392edac7b38fb2965ce8e205e7c5e219e4c531ed3cd1929c782f21853d"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"libc",
|
||||
@@ -1343,9 +1343,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cranelift-srcgen"
|
||||
version = "0.136.6"
|
||||
version = "0.136.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "36508559c8839a8b6ee091f9deaa9cfe620a82f1abb5e358a0a0c65290583622"
|
||||
checksum = "3748e3c77c0717359cd4c089e1dc057221eb8598a9c18b0b5afccb5685975abb"
|
||||
|
||||
[[package]]
|
||||
name = "crc"
|
||||
@@ -2154,7 +2154,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2361,9 +2361,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.2"
|
||||
version = "1.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
||||
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
@@ -2386,7 +2386,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
|
||||
dependencies = [
|
||||
"io-lifetimes 2.0.4",
|
||||
"rustix",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4144,8 +4144,9 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4171,7 +4172,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4179,24 +4180,21 @@ dependencies = [
|
||||
"rayon",
|
||||
"serde",
|
||||
"specta",
|
||||
"tracing",
|
||||
"tree-sitter",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"which",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4214,7 +4212,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4228,7 +4226,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4239,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4250,8 +4248,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
"libc",
|
||||
@@ -4267,7 +4266,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4276,12 +4275,11 @@ dependencies = [
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4310,12 +4308,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
"blake3",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"flate2",
|
||||
"futures",
|
||||
@@ -4348,7 +4345,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4361,7 +4358,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4375,13 +4372,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
"dunce",
|
||||
"ed25519-dalek",
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"semver",
|
||||
"serde",
|
||||
@@ -4396,7 +4392,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4407,7 +4403,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4419,7 +4415,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4432,10 +4428,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
"ide-heap",
|
||||
"libc",
|
||||
"memmap2",
|
||||
"proptest",
|
||||
@@ -4450,7 +4447,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4525,7 +4522,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4539,19 +4536,19 @@ dependencies = [
|
||||
"specta",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
"dunce",
|
||||
"globset",
|
||||
"ide-core",
|
||||
"ide-index",
|
||||
"ide-language",
|
||||
"ignore",
|
||||
"nucleo-matcher",
|
||||
@@ -4567,7 +4564,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4579,10 +4576,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
@@ -4596,7 +4592,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4605,7 +4601,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4616,7 +4612,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4675,7 +4671,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4704,7 +4700,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4723,9 +4719,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"jupyter-protocol",
|
||||
@@ -4738,7 +4733,6 @@ dependencies = [
|
||||
"specta-typescript",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"zeromq",
|
||||
@@ -4746,7 +4740,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4758,7 +4752,6 @@ dependencies = [
|
||||
"serde_json",
|
||||
"specta",
|
||||
"tempfile",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
@@ -4769,7 +4762,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4783,7 +4776,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4803,7 +4796,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4827,7 +4820,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4843,8 +4836,10 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"flate2",
|
||||
"ide-core",
|
||||
@@ -4855,6 +4850,7 @@ dependencies = [
|
||||
"quick-xml 0.42.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"specta",
|
||||
"tar",
|
||||
"tempfile",
|
||||
@@ -4866,7 +4862,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4887,7 +4883,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4900,7 +4896,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4925,7 +4921,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4938,7 +4934,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4953,7 +4949,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4967,7 +4963,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4980,7 +4976,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -5001,7 +4997,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5010,6 +5006,7 @@ dependencies = [
|
||||
"ide-core",
|
||||
"ignore",
|
||||
"libc",
|
||||
"notify",
|
||||
"redb",
|
||||
"regex-lite",
|
||||
"serde",
|
||||
@@ -5022,7 +5019,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5049,7 +5046,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5065,7 +5062,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5227,7 +5224,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
|
||||
dependencies = [
|
||||
"io-lifetimes 3.0.1",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5265,7 +5262,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6694,7 +6691,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -6703,14 +6700,11 @@ dependencies = [
|
||||
"dunce",
|
||||
"gtk",
|
||||
"ide-agent",
|
||||
"ide-analysis",
|
||||
"ide-android",
|
||||
"ide-build",
|
||||
"ide-cli",
|
||||
"ide-clipboard",
|
||||
"ide-command",
|
||||
"ide-core",
|
||||
"ide-coverage",
|
||||
"ide-dap",
|
||||
"ide-db",
|
||||
"ide-docker",
|
||||
@@ -6720,24 +6714,16 @@ dependencies = [
|
||||
"ide-github",
|
||||
"ide-host",
|
||||
"ide-http",
|
||||
"ide-index",
|
||||
"ide-jsonrpc",
|
||||
"ide-language",
|
||||
"ide-lsp",
|
||||
"ide-mcp",
|
||||
"ide-notebook",
|
||||
"ide-plugin",
|
||||
"ide-profiler",
|
||||
"ide-remote",
|
||||
"ide-run",
|
||||
"ide-scaffold",
|
||||
"ide-sdk",
|
||||
"ide-search",
|
||||
"ide-spell",
|
||||
"ide-ssh",
|
||||
"ide-syntax",
|
||||
"ide-terminal",
|
||||
"ide-text",
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
@@ -7424,9 +7410,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pulley-interpreter"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "335e459f9c7809af04768799880504d014d07e8e2fc6ae682fe2a105d8ced33f"
|
||||
checksum = "99ecf828c291348e4066f8e45bf37c35ea6012b07a9201e7911c21f03ad1af3e"
|
||||
dependencies = [
|
||||
"cranelift-bitset",
|
||||
"log",
|
||||
@@ -7436,9 +7422,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "pulley-macros"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dd492ac929a6ca0357362d9fa0a09e31290feac5914550ccfb539b21f89c4b9e"
|
||||
checksum = "20e35ece122b2e8bbd7ea9db0709b3d32f20555b73985efc3eaf6afa4ef2ecdf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -7968,7 +7954,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -8036,7 +8022,7 @@ dependencies = [
|
||||
"security-framework",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -9783,7 +9769,7 @@ dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -10824,9 +10810,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "url"
|
||||
version = "2.5.8"
|
||||
version = "2.5.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
||||
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
|
||||
dependencies = [
|
||||
"form_urlencoded",
|
||||
"idna",
|
||||
@@ -11117,9 +11103,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f32390bdc8d7cdb6259a1b855178bfed88226b4004b209fd48fb30e0deb01cd3"
|
||||
checksum = "263d6a66a772efff2c98a1aa367e8e61dae32d2ecf95f85f4776733762322aa7"
|
||||
dependencies = [
|
||||
"addr2line",
|
||||
"async-trait",
|
||||
@@ -11159,9 +11145,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-environ"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c10f8ef1c9ee5e0f125c775fe56a4d07b8525db30a96e6358c61d93bd11dee4"
|
||||
checksum = "5f2f0898bedc77f110dca6f70394780f89af68a8ca19e12559ee73d4187a6fe9"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"cpp_demangle",
|
||||
@@ -11190,9 +11176,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-component-macro"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "620c53182ebd26c9fff5b90dd53cf8ec3103c381403fd32f8d395da31a9e4a46"
|
||||
checksum = "b140c28283bd2255a4bb8834621f7200bbe7581cbca91d803b5ba4adf9119a5e"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"proc-macro2",
|
||||
@@ -11205,15 +11191,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-component-util"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "011e31ca343d9ba0ec623153cd94131b6f03973ef1a0ab791161f642e4a16a93"
|
||||
checksum = "853075a197694ba7f0749e7af78b59e12c0956dff5b16dafbfc49c3b90cdbc93"
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-core"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab15e50a060b746493e6e95ef3ce4e6e7ebfdd7cc336a7dff0f0277e01b447ef"
|
||||
checksum = "e6e13ab3aa598d863643ef9ec043d63fde7effca4465270446d5b868936b27a6"
|
||||
dependencies = [
|
||||
"hashbrown 0.17.1",
|
||||
"libm",
|
||||
@@ -11222,9 +11208,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-cranelift"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc3d27440a83fba26dd2784a997e13d9acb3606a75fb127c324929b52221c5c5"
|
||||
checksum = "660103cff91df46f9f06568f3889b8b59a6ae0f56756abfcc002a0a69974cc9f"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"cranelift-control",
|
||||
@@ -11248,9 +11234,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-fiber"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e54b28d0d453ca8932e4504065ae66a78f01fcb22b1a2ee287128d732fa9d6f"
|
||||
checksum = "c4d0e958516bdf283b83015283774e11c86b66f2f4bd7d2ea52e9799fa59cddb"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
@@ -11262,9 +11248,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-jit-debug"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9293e75a3048b900f7b7c524702abca16d8a2332f970324eefc519f454cd5d69"
|
||||
checksum = "ad61b1e661871bb7d11b5543202a05c44ed8682806b438f68ced629a22719463"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"wasmtime-internal-versioned-export-macros",
|
||||
@@ -11272,9 +11258,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-jit-icache-coherence"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b852e568831b913d410541bb37edc45a5002e472208fbdbaf844ed801dd4255f"
|
||||
checksum = "52c641b9e1bab449c7316896f01d4a0c426e2a502a5a8098e1af4a0392053e7a"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasmtime-internal-core",
|
||||
@@ -11283,9 +11269,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-unwinder"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a1f7349c9834a542275ad757340079e6453fccb429efce581454d23f85af92c0"
|
||||
checksum = "03303a9abd333edcbd44fee3b1e0905ad156d3bcec311323d061cdff92e7d1f3"
|
||||
dependencies = [
|
||||
"cranelift-codegen",
|
||||
"log",
|
||||
@@ -11295,9 +11281,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-versioned-export-macros"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "30b3e0768a450d9dea3e16b83f2498f0b08db0e32bad695e35564eef017be3f1"
|
||||
checksum = "8db0c7f417e5ca3ba92d127d17b980529455d01c141be99204e6d309630c42de"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -11306,9 +11292,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-internal-wit-bindgen"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9d085c540b95d0ffebf98c266e6f152e1acf96a9f676f224a74307b9d422c15"
|
||||
checksum = "6292ee4f797f9befb64aa2b3477ec8576501d6302ec21fd2785a8d3f94cf8717"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"bitflags 2.13.2",
|
||||
@@ -11320,9 +11306,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-wasi"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17f8ce6b9e77539b5f52d440346f876a84c513ec1b07162845282f8652f7f7f9"
|
||||
checksum = "3175ff29e2992269f51ec372f7757941f11f87b265a614761726960d42ef6e4d"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bitflags 2.13.2",
|
||||
@@ -11344,9 +11330,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasmtime-wasi-io"
|
||||
version = "49.0.6"
|
||||
version = "49.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da9f90eb7ce6edbead27dba3a58843398875defa73b8dce4bbc29d0ce3dc9b40"
|
||||
checksum = "3bb561839e32b61bf0cdd51efe3874fac5de1bd5775a5b7c41bdf70993e367ea"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes",
|
||||
@@ -11620,7 +11606,7 @@ version = "0.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -11788,15 +11774,6 @@ dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.59.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
|
||||
dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.60.2"
|
||||
@@ -12069,7 +12046,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"windows-sys 0.59.0",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+1
-3
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.49"
|
||||
version = "0.1.50"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -69,13 +69,11 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time"
|
||||
tokio-util = { version = "0.7", features = ["rt"] }
|
||||
parking_lot = "0.12"
|
||||
rayon = "1"
|
||||
dashmap = "6"
|
||||
futures = "0.3"
|
||||
tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "__rustls-tls"] }
|
||||
|
||||
# errors & diagnostics
|
||||
thiserror = "2"
|
||||
anyhow = "1"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src=".github/assets/wechat-group-3.png" alt="WeChat group QR code" width="200">
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
|
||||
- WeChat grubu, katılmak için kodu okut:
|
||||
|
||||
<img src=".github/assets/wechat-group-3.png" alt="WeChat grubu QR kodu" width="200">
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
|
||||
|
||||
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-3.png" alt="微信群二维码" width="200">
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
|
||||
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
|
||||
|
||||
|
||||
@@ -35,7 +35,8 @@ icon set, copied unmodified (some renamed) from JetBrains' open-source repositor
|
||||
→ `maven/`); `plugins/gradle` (`icons/expui/gradle` → `toolwindows/gradle`,
|
||||
`icons/expui/gradleLoadChanges` → `build/gradleLoadChanges`,
|
||||
`icons/expui/gradle`, `icons/gradleSubproject` → `gradle/`);
|
||||
`platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`).
|
||||
`platform/external-system-impl` (`icons/newui/task` → `externalSystem/task`);
|
||||
`platform/dvcs-impl` (`icons/new/cherryPick` → `vcs/cherryPick`).
|
||||
Copyright 2000-2026 JetBrains s.r.o. and contributors. Apache License 2.0 (below).
|
||||
- [intellij-plugins](https://github.com/JetBrains/intellij-plugins) (each plugin
|
||||
carries its own licence): `protobuf/protoeditor-core` (`newui/protoFile` →
|
||||
|
||||
@@ -7,6 +7,7 @@ license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
encoding_rs.workspace = true
|
||||
base64.workspace = true
|
||||
blake3.workspace = true
|
||||
ide-vfs.workspace = true
|
||||
ide-core.workspace = true
|
||||
|
||||
@@ -194,14 +194,14 @@ impl AgentCatalogs {
|
||||
(shared.paths.models_file.clone(), shared.paths.project_root.clone(), provider.to_owned())
|
||||
}
|
||||
|
||||
fn fallback(shared: &Shared, provider: &str) -> CatalogData {
|
||||
/// The catalog saved for this project, for before this run looked anything up.
|
||||
fn saved(shared: &Shared, provider: &str) -> CatalogData {
|
||||
let cache = shared.known.lock();
|
||||
let Some(known) = cache.get(provider) else { return CatalogData::default() };
|
||||
known.catalogs.get(&shared.root_key()).map(|saved| saved.catalog.clone()).unwrap_or_else(|| CatalogData {
|
||||
config: known.config.clone(),
|
||||
thought_levels: known.thought_levels.clone(),
|
||||
refreshed_at_ms: None,
|
||||
})
|
||||
cache
|
||||
.get(provider)
|
||||
.and_then(|known| known.catalogs.get(&shared.root_key()))
|
||||
.map(|saved| saved.catalog.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn cached(&self, shared: &Shared, provider: &str) -> CatalogData {
|
||||
@@ -210,32 +210,14 @@ impl AgentCatalogs {
|
||||
.entries
|
||||
.get(&Self::key(shared, provider))
|
||||
.and_then(|e| e.catalog.clone())
|
||||
.unwrap_or_else(|| Self::fallback(shared, provider))
|
||||
.unwrap_or_else(|| Self::saved(shared, provider))
|
||||
}
|
||||
|
||||
/// Availability for an explicit session switch must come from a recent discovery for this
|
||||
/// launch, not from the display fallback or a different project's session report.
|
||||
pub(super) fn fresh_model(
|
||||
&self,
|
||||
shared: &Shared,
|
||||
spec: &provider::ProviderSpec,
|
||||
model: &str,
|
||||
) -> Option<crate::AgentConfigValue> {
|
||||
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
|
||||
let select = |catalog: &CatalogData| {
|
||||
let age = self.epoch_ms() - catalog.refreshed_at_ms?;
|
||||
if !(0.0..FRESH_FOR.as_millis() as f64).contains(&age) {
|
||||
return None;
|
||||
}
|
||||
catalog.model_option()?.values.iter().find(|value| value.value == model).cloned()
|
||||
};
|
||||
let state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get(&Self::key(shared, &spec.id)) {
|
||||
return select(entry.catalog.as_ref().filter(|_| entry.context == context)?);
|
||||
}
|
||||
let cache = shared.known.lock();
|
||||
let saved = cache.get(&spec.id)?.catalogs.get(&shared.root_key())?;
|
||||
(saved.fingerprint == context.fingerprint()).then(|| select(&saved.catalog)).flatten()
|
||||
/// The entry a chat may switch to: exactly what the picker offers from the cached catalog,
|
||||
/// however long ago it was read. Refreshing keeps that catalog current; a listed model is
|
||||
/// never refused because the catalog aged.
|
||||
pub(super) fn listed_model(&self, shared: &Shared, provider: &str, model: &str) -> Option<crate::AgentConfigValue> {
|
||||
self.cached(shared, provider).model_option()?.values.iter().find(|value| value.value == model).cloned()
|
||||
}
|
||||
|
||||
pub(crate) fn levels(&self, shared: &Shared, provider: &str, model: &str) -> Option<Vec<AgentConfigOption>> {
|
||||
@@ -246,14 +228,7 @@ impl AgentCatalogs {
|
||||
}
|
||||
drop(state);
|
||||
let cache = shared.known.lock();
|
||||
let known = cache.get(provider)?;
|
||||
known
|
||||
.catalogs
|
||||
.get(&shared.root_key())
|
||||
.map(|saved| &saved.catalog.thought_levels)
|
||||
.unwrap_or(&known.thought_levels)
|
||||
.get(model)
|
||||
.cloned()
|
||||
cache.get(provider)?.catalogs.get(&shared.root_key())?.catalog.thought_levels.get(model).cloned()
|
||||
}
|
||||
|
||||
pub(super) async fn load_levels(
|
||||
@@ -297,7 +272,7 @@ impl AgentCatalogs {
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_else(|| Self::fallback(shared, provider));
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
let unknown_model = entry
|
||||
.requested_model
|
||||
@@ -382,12 +357,11 @@ impl AgentCatalogs {
|
||||
},
|
||||
);
|
||||
}
|
||||
let fallback =
|
||||
state.entries.get(&key).filter(|entry| entry.catalog.is_none()).map(|_| Self::fallback(shared, &spec.id));
|
||||
state.generation += 1;
|
||||
let generation = state.generation;
|
||||
let entry = state.entries.get_mut(&key).expect("catalog entry");
|
||||
let catalog = entry.catalog.as_ref().or(fallback.as_ref()).expect("cached catalog");
|
||||
let empty = CatalogData::default();
|
||||
let catalog = entry.catalog.as_ref().unwrap_or(&empty);
|
||||
let fresh = entry.successful.is_some_and(|at| now.duration_since(at) < FRESH_FOR);
|
||||
let target = model
|
||||
.filter(|model| {
|
||||
@@ -496,7 +470,7 @@ impl AgentCatalogs {
|
||||
entry.flight_model = None;
|
||||
let success = match result {
|
||||
Ok(found) => {
|
||||
let previous = entry.catalog.take().unwrap_or_else(|| Self::fallback(shared, &key.2));
|
||||
let previous = entry.catalog.take().unwrap_or_default();
|
||||
let mut cache = shared.known.lock();
|
||||
let known = cache.entry(key.2.clone()).or_default();
|
||||
let mut catalog = CatalogData {
|
||||
@@ -510,13 +484,9 @@ impl AgentCatalogs {
|
||||
catalog.thought_levels.insert(model, levels);
|
||||
}
|
||||
}
|
||||
known.config = catalog.config.clone();
|
||||
known.thought_levels = catalog.thought_levels.clone();
|
||||
if let Some(commands) = found.commands {
|
||||
known.commands.insert(shared.root_key(), commands);
|
||||
}
|
||||
known.authoritative = true;
|
||||
known.refreshed_at_ms = catalog.refreshed_at_ms;
|
||||
known.catalogs.insert(
|
||||
shared.root_key(),
|
||||
SavedCatalog { fingerprint: entry.context.fingerprint(), catalog: catalog.clone() },
|
||||
|
||||
@@ -169,9 +169,12 @@ fn make_manager_at(root: &Path, models_file: &Path, catalogs: Arc<AgentCatalogs>
|
||||
|
||||
fn events(manager: &AgentManager) -> mpsc::UnboundedReceiver<AgentEvent> {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
manager.subscribe(Arc::new(move |event| {
|
||||
let _ = tx.send(event);
|
||||
}));
|
||||
manager.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |event| {
|
||||
let _ = tx.send(event);
|
||||
}),
|
||||
);
|
||||
rx
|
||||
}
|
||||
|
||||
@@ -230,11 +233,9 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
|
||||
let manager = make_manager(tmp.path(), catalogs.clone(), &harness);
|
||||
let mut events = events(&manager);
|
||||
let old = config::options_of(&response(&["old", "retained"], &["low", "high"]));
|
||||
manager.shared.remember(PROVIDER, Some(&old), None, Some("old"));
|
||||
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
|
||||
assert!(cached.refreshing);
|
||||
assert_eq!(model_values(&cached), ["old", "retained"]);
|
||||
assert!(cached.refreshed_at_ms.is_none(), "session reports are not fresh discovery");
|
||||
assert!(model_values(&cached).is_empty(), "nothing is offered before the first discovery");
|
||||
let pending = harness.next().await;
|
||||
assert_eq!(pending.params["mcpServers"], json!([]));
|
||||
pending.reply.send(Ok(response(&["retained", "new"], &["medium"]))).unwrap();
|
||||
@@ -258,7 +259,10 @@ async fn successful_refresh_replaces_models_and_efforts_and_old_sessions_cannot_
|
||||
assert_eq!(provider.config, fresh.config);
|
||||
restored.shared.remember(PROVIDER, Some(&old), None, Some("old"));
|
||||
assert_eq!(restored.shared.known_config(PROVIDER), fresh.config);
|
||||
assert_eq!(restored.shared.known.lock()[PROVIDER].refreshed_at_ms, fresh.refreshed_at_ms);
|
||||
assert_eq!(
|
||||
restored.shared.paths.catalogs.cached(&restored.shared, PROVIDER).refreshed_at_ms,
|
||||
fresh.refreshed_at_ms
|
||||
);
|
||||
assert!(!tmp.path().join("store").exists(), "refresh never creates tasks");
|
||||
}
|
||||
|
||||
@@ -308,6 +312,11 @@ async fn discovered_model_reloads_the_same_session_on_the_next_message() {
|
||||
switch_chat_model(ChatSwitch::Resume).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovered_model_from_an_aged_catalog_can_still_be_selected() {
|
||||
switch_chat_model(ChatSwitch::Aged).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovered_model_leaves_the_original_session_intact_after_resume_failure() {
|
||||
switch_chat_model(ChatSwitch::ResumeFails).await;
|
||||
@@ -356,6 +365,7 @@ async fn discovered_model_lookup_does_not_overwrite_a_newer_selection() {
|
||||
#[derive(Clone, Copy)]
|
||||
enum ChatSwitch {
|
||||
Live,
|
||||
Aged,
|
||||
Resume,
|
||||
ResumeFails,
|
||||
Unavailable,
|
||||
@@ -376,7 +386,8 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
let mut harness = Harness::with_initialize(json!({
|
||||
"protocolVersion": 1, "agentCapabilities": { "loadSession": true }
|
||||
}));
|
||||
let mut manager = make_manager(tmp.path(), Arc::default(), &harness);
|
||||
let catalogs = Arc::new(AgentCatalogs::default());
|
||||
let mut manager = make_manager(tmp.path(), catalogs.clone(), &harness);
|
||||
let task = manager
|
||||
.create(NewAgentTask {
|
||||
prompt: AgentPrompt { text: "first".into(), ..Default::default() },
|
||||
@@ -443,7 +454,11 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
}
|
||||
assert_eq!(manager.task(&task.id).unwrap().state.lock().task.config, before_config);
|
||||
|
||||
let live = matches!(scenario, ChatSwitch::Live);
|
||||
let live = matches!(scenario, ChatSwitch::Live | ChatSwitch::Aged);
|
||||
if matches!(scenario, ChatSwitch::Aged) {
|
||||
// The catalog stays what the picker offers however long ago it was read.
|
||||
advance(&catalogs, 20 * 60);
|
||||
}
|
||||
let resumed_launch = if missing_settings { 3 } else { 2 };
|
||||
let load_fails = matches!(scenario, ChatSwitch::ResumeFails);
|
||||
let unavailable = matches!(scenario, ChatSwitch::Unavailable);
|
||||
@@ -477,7 +492,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
set.reply.send(Err("Sign in required".into())).unwrap();
|
||||
let error = switching.await.unwrap_err().to_string();
|
||||
assert!(error.contains("Sign in required"), "{error}");
|
||||
assert_eq!(manager.subscribe(Arc::new(|_| {})).remove(0).config, before_config);
|
||||
assert_eq!(manager.subscribe_as("", Arc::new(|_| {})).remove(0).config, before_config);
|
||||
assert!(harness.pending.try_recv().is_err());
|
||||
manager.shutdown();
|
||||
return;
|
||||
@@ -486,7 +501,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
manager.set_config(&task.id, "model", "old".into()).await.unwrap();
|
||||
set.reply.send(Ok(response(&["new", "old"], &["quick", "thorough"]))).unwrap();
|
||||
switching.await.unwrap();
|
||||
let task = manager.subscribe(Arc::new(|_| {})).remove(0);
|
||||
let task = manager.subscribe_as("", Arc::new(|_| {})).remove(0);
|
||||
assert_eq!(task.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("old"));
|
||||
assert_eq!(task.config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("low"));
|
||||
assert!(harness.pending.try_recv().is_err());
|
||||
@@ -517,7 +532,7 @@ async fn switch_chat_model(scenario: ChatSwitch) {
|
||||
let effort = update.config.iter().find(|o| o.id == "effort").unwrap();
|
||||
assert_eq!(effort.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["quick", "thorough"]);
|
||||
}
|
||||
let snapshot = |manager: &AgentManager| manager.subscribe(Arc::new(|_| {})).remove(0);
|
||||
let snapshot = |manager: &AgentManager| manager.subscribe_as("", Arc::new(|_| {})).remove(0);
|
||||
let current = snapshot(&manager);
|
||||
assert_eq!(current.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("new"));
|
||||
assert_eq!(current.model.as_deref(), Some(if live { "new" } else { "old" }));
|
||||
@@ -684,7 +699,7 @@ async fn next_chat_request(
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
|
||||
async fn a_cache_from_before_project_catalogs_offers_nothing_until_discovery_succeeds() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
configure(tmp.path(), "one");
|
||||
let options = config::options_of(&response(&["legacy"], &["low"]));
|
||||
@@ -700,12 +715,11 @@ async fn legacy_cache_loads_without_claiming_authoritative_freshness() {
|
||||
let manager = make_manager(tmp.path(), Arc::default(), &harness);
|
||||
let mut events = events(&manager);
|
||||
let cached = manager.refresh_models(PROVIDER, false, None).unwrap();
|
||||
assert_eq!(model_values(&cached), ["legacy"]);
|
||||
assert!(model_values(&cached).is_empty());
|
||||
assert!(cached.refreshing && cached.refreshed_at_ms.is_none());
|
||||
harness.next().await.reply.send(Err("Sign in required".into())).unwrap();
|
||||
let failed = completed(&mut events).await;
|
||||
assert_eq!(failed.config, cached.config);
|
||||
assert!(failed.error.as_deref().unwrap().contains("Sign in required"));
|
||||
harness.next().await.reply.send(Ok(response(&["current"], &["low"]))).unwrap();
|
||||
let found = completed(&mut events).await;
|
||||
assert_eq!(model_values(&found), ["current"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
+210
-120
@@ -23,6 +23,7 @@ mod provider;
|
||||
pub mod registry;
|
||||
pub mod security;
|
||||
mod shell;
|
||||
pub mod skill_installer;
|
||||
pub mod skills;
|
||||
mod timeline;
|
||||
mod worktree;
|
||||
@@ -31,9 +32,13 @@ pub use catalogs::AgentCatalogs;
|
||||
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
|
||||
pub use external::ExternalSession;
|
||||
pub use model::*;
|
||||
pub use skill_installer::{
|
||||
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
|
||||
SkillScanWarning, SkillScanWarningKind,
|
||||
};
|
||||
|
||||
use conversation::{Conversation, SavedSubagent, Session};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, error::ErrorKind};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use ide_vcs::Repo;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
@@ -54,6 +59,13 @@ pub type SecurityHook = Arc<dyn Fn() -> ide_core::settings::AgentSecuritySetting
|
||||
/// Returns the user's choice of the approvals new tasks start with.
|
||||
pub type NewTaskApprovalsHook = Arc<dyn Fn() -> ide_core::settings::NewTaskApprovals + Send + Sync>;
|
||||
|
||||
/// Returns the roots of the project's workspace an agent may work in: the project and the
|
||||
/// attached projects the user trusts.
|
||||
pub type WorkspaceRootsHook = Arc<dyn Fn() -> Vec<PathBuf> + Send + Sync>;
|
||||
|
||||
/// Returns the project's git executable (`None`: the default), which the tasks' git runs.
|
||||
pub type GitExecutableHook = Arc<dyn Fn() -> Option<PathBuf> + Send + Sync>;
|
||||
|
||||
/// Entry changes are batched for this long before they are sent.
|
||||
const FLUSH_DELAY: Duration = Duration::from_millis(40);
|
||||
/// Updates that arrive this late after `session/load` returns are still replayed history.
|
||||
@@ -83,6 +95,8 @@ const MAX_EMBED: u64 = 256 * 1024;
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// How long deleting a task waits for its agent to exit before removing the worktree.
|
||||
const EXIT_WAIT: Duration = Duration::from_secs(5);
|
||||
/// Change lists can each open several Git pipes; leave room for interactive VCS operations.
|
||||
const MAX_CHANGE_READS: usize = 4;
|
||||
|
||||
/// The agent tasks of one project.
|
||||
pub struct AgentManager {
|
||||
@@ -134,11 +148,27 @@ pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
|
||||
/// The `[agents.skills.<name>]` policies a session resolves against: the user's (global
|
||||
/// `settings.toml`), the workspace's (`.openidea/settings.toml`), and whether the workspace
|
||||
/// is trusted (an untrusted one can only turn skills off).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SkillsPolicy {
|
||||
pub user: BTreeMap<String, AgentSkillPolicy>,
|
||||
pub workspace: BTreeMap<String, AgentSkillPolicy>,
|
||||
pub workspace_trusted: bool,
|
||||
/// All workspace folders (the project root plus any multi-repo workspace members).
|
||||
pub workspace_roots: Vec<PathBuf>,
|
||||
/// Validated `<dir>` folders contributed by live OpenIDEA plugins (`[[contributes.skills]]`).
|
||||
pub plugin_dirs: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for SkillsPolicy {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
user: BTreeMap::new(),
|
||||
workspace: BTreeMap::new(),
|
||||
workspace_trusted: true,
|
||||
workspace_roots: Vec::new(),
|
||||
plugin_dirs: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the skill policies for this project.
|
||||
@@ -159,6 +189,9 @@ struct Shared {
|
||||
sinks: RwLock<HashMap<String, AgentSink>>,
|
||||
security: RwLock<Option<SecurityHook>>,
|
||||
new_task_approvals: RwLock<Option<NewTaskApprovalsHook>>,
|
||||
workspace_roots: RwLock<Option<WorkspaceRootsHook>>,
|
||||
git_executable: RwLock<Option<GitExecutableHook>>,
|
||||
change_reads: Arc<tokio::sync::Semaphore>,
|
||||
known: Arc<Mutex<HashMap<String, Known>>>,
|
||||
providers: RwLock<Vec<provider::ProviderSpec>>,
|
||||
/// Last probe of each provider.
|
||||
@@ -174,28 +207,36 @@ struct Shared {
|
||||
attention_seq: AtomicU64,
|
||||
}
|
||||
|
||||
/// What an agent offered in its last session, for the New Task page.
|
||||
/// What an agent offered, for the New Task page.
|
||||
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||
struct Known {
|
||||
#[serde(default)]
|
||||
config: Vec<AgentConfigOption>,
|
||||
/// Thinking levels reported for each model value, including its last choice.
|
||||
#[serde(default, rename = "thoughtLevels")]
|
||||
thought_levels: BTreeMap<String, Vec<AgentConfigOption>>,
|
||||
/// By project root: skills and custom commands differ per project.
|
||||
#[serde(default, rename = "projectCommands")]
|
||||
commands: HashMap<String, Vec<AgentCommand>>,
|
||||
/// Successful discovery, unlike a session report, owns availability.
|
||||
#[serde(default)]
|
||||
authoritative: bool,
|
||||
#[serde(default, rename = "refreshedAtMs")]
|
||||
refreshed_at_ms: Option<f64>,
|
||||
/// Authoritative availability and freshness are scoped to project and launch context.
|
||||
/// Model catalogs by project root, valid for the launch context they were read with.
|
||||
#[serde(default, rename = "projectCatalogs")]
|
||||
catalogs: HashMap<String, catalogs::SavedCatalog>,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// The workspace roots offered to a session besides its own directory and project, for an
|
||||
/// agent that takes them (`sessionCapabilities.additionalDirectories`).
|
||||
fn additional_directories(&self, init: &acp::Negotiated, cwd: &Path, project_root: Option<&Path>) -> Vec<String> {
|
||||
let Some(hook) = self.workspace_roots.read().clone().filter(|_| init.session("additionalDirectories")) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let canonical = |p: &Path| dunce::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
|
||||
let own: Vec<PathBuf> = std::iter::once(cwd).chain(project_root).map(canonical).collect();
|
||||
let mut roots = Vec::new();
|
||||
for root in hook().iter().map(|r| canonical(r)) {
|
||||
let root = root.to_string_lossy().into_owned();
|
||||
if !own.iter().any(|o| o.to_string_lossy() == root) && !roots.contains(&root) {
|
||||
roots.push(root);
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn spec(&self, id: &str) -> Option<provider::ProviderSpec> {
|
||||
self.providers.read().iter().find(|p| p.id == id).cloned()
|
||||
}
|
||||
@@ -308,7 +349,8 @@ impl Shared {
|
||||
self.paths.project_root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Cache levels only when `model` confirms which model the session reported them for.
|
||||
/// Keeps the commands a session offered and the effort levels it reported for `model`, the
|
||||
/// only model whose levels it describes.
|
||||
fn remember(
|
||||
&self,
|
||||
provider: &str,
|
||||
@@ -317,43 +359,22 @@ impl Shared {
|
||||
model: Option<&str>,
|
||||
) {
|
||||
let acp = self.spec(provider).is_some_and(|spec| spec.driver == provider::Driver::Acp);
|
||||
let mut cache = self.known.lock();
|
||||
let known = cache.entry(provider.to_owned()).or_default();
|
||||
let mut changed = false;
|
||||
// Running tasks retain their own reported settings. Once discovery has
|
||||
// succeeded, a session's older list/defaults cannot change New Task choices.
|
||||
if !known.authoritative
|
||||
&& let Some(config) = config.filter(|c| !c.is_empty())
|
||||
{
|
||||
if let Some(model) = model {
|
||||
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
|
||||
if known.thought_levels.get(model) != Some(&levels) {
|
||||
known.thought_levels.insert(model.to_owned(), levels);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if known.config != config {
|
||||
known.config = config.to_vec();
|
||||
if let Some(commands) = commands.filter(|c| !c.is_empty()) {
|
||||
let mut cache = self.known.lock();
|
||||
let known = cache.entry(provider.to_owned()).or_default();
|
||||
if known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands) {
|
||||
known.commands.insert(self.root_key(), commands.to_vec());
|
||||
self.persist_known(&cache);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
// Discovery reads one model's options; a session on another model reports that model's.
|
||||
let learned = model.filter(|_| acp && known.authoritative).zip(config).map(|(model, config)| {
|
||||
if acp && let Some((model, config)) = model.zip(config) {
|
||||
let levels: Vec<_> = config.iter().filter(|o| config::is_per_model_option(o)).cloned().collect();
|
||||
(model, levels)
|
||||
});
|
||||
if let Some(commands) = commands.filter(|c| !c.is_empty())
|
||||
&& known.commands.get(&self.root_key()).map(Vec::as_slice) != Some(commands)
|
||||
{
|
||||
known.commands.insert(self.root_key(), commands.to_vec());
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
self.persist_known(&cache);
|
||||
}
|
||||
drop(cache);
|
||||
if let Some((model, levels)) = learned.filter(|(_, levels)| !levels.is_empty()) {
|
||||
self.paths.catalogs.learn_levels(self, provider, model, levels);
|
||||
if !levels.is_empty() {
|
||||
self.paths.catalogs.learn_levels(self, provider, model, levels);
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.emit(AgentEvent::Providers);
|
||||
@@ -584,6 +605,9 @@ impl AgentManager {
|
||||
sinks: RwLock::new(HashMap::new()),
|
||||
security: RwLock::new(None),
|
||||
new_task_approvals: RwLock::new(None),
|
||||
workspace_roots: RwLock::new(None),
|
||||
git_executable: RwLock::new(None),
|
||||
change_reads: Arc::new(tokio::sync::Semaphore::new(MAX_CHANGE_READS)),
|
||||
known,
|
||||
providers,
|
||||
probes: Mutex::new(HashMap::new()),
|
||||
@@ -623,12 +647,8 @@ impl AgentManager {
|
||||
Self { shared, tasks: RwLock::new(tasks) }
|
||||
}
|
||||
|
||||
/// Routes events to `sink` (replacing the previous subscriber); returns every task.
|
||||
pub fn subscribe(&self, sink: AgentSink) -> Vec<AgentTask> {
|
||||
self.subscribe_as("", sink)
|
||||
}
|
||||
|
||||
/// Routes events to `sink` too, replacing only the sink `subscriber` (a view of the project) had.
|
||||
/// Routes events to `sink`, replacing only the sink `subscriber` (a view of the project) had;
|
||||
/// returns every task.
|
||||
pub fn subscribe_as(&self, subscriber: &str, sink: AgentSink) -> Vec<AgentTask> {
|
||||
self.shared.sinks.write().insert(subscriber.to_owned(), sink);
|
||||
let mut tasks: Vec<AgentTask> = self.tasks.read().values().map(|t| t.state.lock().snapshot()).collect();
|
||||
@@ -641,6 +661,15 @@ impl AgentManager {
|
||||
self.shared.sinks.write().remove(subscriber);
|
||||
}
|
||||
|
||||
pub fn has_live_work(&self) -> bool {
|
||||
self.tasks.read().values().any(|task| {
|
||||
let state = task.state.lock();
|
||||
state.busy
|
||||
|| !state.background_tasks.is_empty()
|
||||
|| matches!(state.task.status, AgentStatus::Starting | AgentStatus::Running | AgentStatus::NeedsInput)
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets the callback used to read the active command execution security policy.
|
||||
pub fn set_security_hook(&self, hook: SecurityHook) {
|
||||
*self.shared.security.write() = Some(hook);
|
||||
@@ -651,6 +680,16 @@ impl AgentManager {
|
||||
*self.shared.new_task_approvals.write() = Some(hook);
|
||||
}
|
||||
|
||||
/// Sets the callback that lists the workspace roots offered to agents besides a task's own.
|
||||
pub fn set_workspace_roots_hook(&self, hook: WorkspaceRootsHook) {
|
||||
*self.shared.workspace_roots.write() = Some(hook);
|
||||
}
|
||||
|
||||
/// Sets the callback that reads the project's git executable.
|
||||
pub fn set_git_executable_hook(&self, hook: GitExecutableHook) {
|
||||
*self.shared.git_executable.write() = Some(hook);
|
||||
}
|
||||
|
||||
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
|
||||
pub fn providers(&self) -> Vec<AgentProvider> {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
@@ -785,20 +824,22 @@ impl AgentManager {
|
||||
}
|
||||
let home = self.shared.paths.home_dir.clone();
|
||||
if provider == "hermes" || provider.starts_with("hermes-") {
|
||||
let hermes_home = home.clone();
|
||||
let hermes_provider = provider.clone();
|
||||
let found = blocking(move || {
|
||||
let profile = hermes::root(home.as_deref()).and_then(|root| hermes::profile_home(&root, &provider));
|
||||
let profile =
|
||||
hermes::root(hermes_home.as_deref()).and_then(|root| hermes::profile_home(&root, &hermes_provider));
|
||||
Ok(profile.map(|p| skills::hermes(&p)).unwrap_or_default())
|
||||
})
|
||||
.await?;
|
||||
return Ok(skills::merge(offered, found));
|
||||
}
|
||||
if provider == "claude" || provider == "claude-acp" {
|
||||
offered = skills::merge(offered, found);
|
||||
} else if provider == "claude" || provider == "claude-acp" {
|
||||
let claude_cwd = cwd.clone();
|
||||
let found = blocking(move || Ok(skills::discover(&claude_cwd, home.as_deref()))).await?;
|
||||
offered = skills::merge(offered, found);
|
||||
}
|
||||
// The hub's active skills complete on every agent; its `off` ones drop out here,
|
||||
// which is all the enforcement an ACP agent gets.
|
||||
// The hub's active skills complete on every agent; its `off` ones drop out here
|
||||
// (including entries `offered` already held), which is all the enforcement an ACP agent gets.
|
||||
let holder = self.task_for_commands(&provider, task);
|
||||
let states = match holder {
|
||||
Some(holder) => holder.skill_states().await,
|
||||
@@ -808,10 +849,12 @@ impl AgentManager {
|
||||
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
(policy, shared.paths.project_root.clone())
|
||||
};
|
||||
let roots = if policy.workspace_roots.is_empty() { vec![root] } else { policy.workspace_roots };
|
||||
let plugin_dirs = policy.plugin_dirs;
|
||||
let home = self.shared.paths.home_dir.clone();
|
||||
blocking(move || {
|
||||
Ok(skills::resolve(
|
||||
skills::discover_skills(&root, home.as_deref()),
|
||||
skills::discover_skills_with_plugins(&roots, home.as_deref(), &plugin_dirs),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
@@ -959,14 +1002,15 @@ impl AgentManager {
|
||||
}
|
||||
let dir = self.shared.paths.worktrees_dir.clone();
|
||||
let (t, b) = (title.clone(), req.base.clone());
|
||||
let c = blocking(move || worktree::create(&root, &dir, &t, b.as_deref())).await?;
|
||||
let c = vcs(&self.shared, move || worktree::create(&root, &dir, &t, b.as_deref())).await?;
|
||||
(c.path, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
|
||||
}
|
||||
Isolation::Local => {
|
||||
let r = root.clone();
|
||||
let (head, before) =
|
||||
blocking(move || Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default())))
|
||||
.await?;
|
||||
let (head, before) = vcs(&self.shared, move || {
|
||||
Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default()))
|
||||
})
|
||||
.await?;
|
||||
let (base, commit) = head.unzip();
|
||||
(root, None, base, commit, before)
|
||||
}
|
||||
@@ -1000,7 +1044,7 @@ impl AgentManager {
|
||||
} else {
|
||||
let name = format!("{id}.before");
|
||||
let (dir, at, files) = (self.shared.paths.store_dir.join(&name), cwd.clone(), before.clone());
|
||||
match blocking(move || worktree::save_before(&at, &files, &dir)).await {
|
||||
match vcs(&self.shared, move || worktree::save_before(&at, &files, &dir)).await {
|
||||
Ok(saved) => saved.then_some(name),
|
||||
Err(e) => {
|
||||
tracing::warn!("saving the changed files of agent task {id}: {e}");
|
||||
@@ -1133,35 +1177,14 @@ impl AgentManager {
|
||||
|
||||
/// Drops a queued message.
|
||||
pub fn unqueue(&self, id: &str, queued: &str) -> IdeResult<AgentQueued> {
|
||||
let task = self.task(id)?;
|
||||
let item = {
|
||||
let mut s = task.state.lock();
|
||||
let i =
|
||||
s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?;
|
||||
s.task.queue.remove(i)
|
||||
};
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
Ok(item)
|
||||
self.task(id)?.take_queued(queued, false).map(|(item, _)| item)
|
||||
}
|
||||
|
||||
/// Sends queued message `queued` now: into the running turn when the agent takes
|
||||
/// messages mid-turn, else next, cancelling the current turn if there is one.
|
||||
pub async fn send_queued_now(&self, id: &str, queued: &str) -> IdeResult<()> {
|
||||
let task = self.task(id)?;
|
||||
let (item, busy) = {
|
||||
let mut s = task.state.lock();
|
||||
let i =
|
||||
s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?;
|
||||
let item = s.task.queue.remove(i);
|
||||
let busy = s.busy;
|
||||
if !busy {
|
||||
s.busy = true;
|
||||
}
|
||||
(item, busy)
|
||||
};
|
||||
task.persist();
|
||||
task.emit_task();
|
||||
let (item, busy) = task.take_queued(queued, true)?;
|
||||
if !busy {
|
||||
self.shared.runtime.spawn(async move { task.run(item.prompt).await });
|
||||
return Ok(());
|
||||
@@ -1371,11 +1394,13 @@ impl AgentManager {
|
||||
if !live.capabilities.fork || (keep < total && !live.capabilities.rollback) {
|
||||
return Err(IdeError::invalid("this agent can't copy a conversation from there"));
|
||||
}
|
||||
let (cwd, provider_id, mcp_overrides) = {
|
||||
let (cwd, provider_id, mcp_overrides, project_root) = {
|
||||
let s = source.state.lock();
|
||||
(s.task.cwd.0.clone(), s.task.provider.clone(), s.task.mcp_overrides.clone())
|
||||
let t = &s.task;
|
||||
(t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0))
|
||||
};
|
||||
let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides);
|
||||
let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref());
|
||||
let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await;
|
||||
let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned();
|
||||
let reply: Value = live
|
||||
@@ -1383,7 +1408,7 @@ impl AgentManager {
|
||||
.request(
|
||||
"session/fork",
|
||||
{
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
params["sessionId"] = json!(live.session);
|
||||
params
|
||||
},
|
||||
@@ -1800,7 +1825,7 @@ impl AgentManager {
|
||||
let _ = tokio::time::timeout(EXIT_WAIT, peer.exited()).await;
|
||||
}
|
||||
let worktrees = self.shared.paths.worktrees_dir.clone();
|
||||
blocking(move || worktree::remove(&root, &worktrees, &cwd)).await?;
|
||||
vcs(&self.shared, move || worktree::remove(&root, &worktrees, &cwd)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1810,7 +1835,7 @@ impl AgentManager {
|
||||
let task = self.task(id)?;
|
||||
let at = task.base();
|
||||
let (before, touched) = task.attribution();
|
||||
blocking(move || Ok(worktree::made_by_task(at.changes(&before)?, touched.as_deref()))).await
|
||||
read_changes(&self.shared, move || at.changes(&before, touched.as_deref())).await
|
||||
}
|
||||
|
||||
/// The task's uncommitted changes and, for a worktree task, the commits made since it
|
||||
@@ -1819,7 +1844,7 @@ impl AgentManager {
|
||||
let task = self.task(id)?;
|
||||
let at = task.base();
|
||||
let (before, touched) = task.attribution();
|
||||
blocking(move || {
|
||||
read_changes(&self.shared, move || {
|
||||
let mut grouped = at.grouped_changes(&before)?;
|
||||
grouped.uncommitted = worktree::made_by_task(grouped.uncommitted, touched.as_deref());
|
||||
Ok(grouped)
|
||||
@@ -1832,7 +1857,7 @@ impl AgentManager {
|
||||
pub async fn turn_changes(&self, id: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
let (cwd, turn, dir) = self.task(id)?.last_turn();
|
||||
let Some(turn) = turn else { return Ok(Vec::new()) };
|
||||
blocking(move || {
|
||||
read_changes(&self.shared, move || {
|
||||
let changed = match &turn.changed {
|
||||
Some(changed) => changed.clone(),
|
||||
None => worktree::changed_in_turn(&cwd, &turn)?.1,
|
||||
@@ -1849,10 +1874,10 @@ impl AgentManager {
|
||||
if view == AgentChangesView::LastTurn {
|
||||
let (cwd, turn, dir) = task.last_turn();
|
||||
let Some(turn) = turn else { return Ok(None) };
|
||||
return blocking(move || worktree::turn_text(&cwd, &path, &turn, &dir)).await;
|
||||
return vcs(&self.shared, move || worktree::turn_text(&cwd, &path, &turn, &dir)).await;
|
||||
}
|
||||
let at = task.base();
|
||||
blocking(move || {
|
||||
vcs(&self.shared, move || {
|
||||
let rev = match view {
|
||||
AgentChangesView::Group => worktree::head_commit(at.cwd())?,
|
||||
_ => at.rev()?,
|
||||
@@ -1886,10 +1911,10 @@ impl AgentManager {
|
||||
let s = task.state.lock();
|
||||
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)), s.touched.clone())
|
||||
};
|
||||
let (restamped, restored) = blocking(move || {
|
||||
let (restamped, restored) = vcs(&self.shared, move || {
|
||||
let (changes, rev) = match view {
|
||||
AgentChangesView::Group => (at.grouped_changes(&before)?.uncommitted, worktree::head_commit(at.cwd())?),
|
||||
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before)?, at.rev()?),
|
||||
AgentChangesView::SinceStart | AgentChangesView::LastTurn => (at.changes(&before, None)?, at.rev()?),
|
||||
};
|
||||
let changes = worktree::made_by_task(changes, touched.as_deref());
|
||||
let sources = match rev.as_deref() {
|
||||
@@ -1942,7 +1967,7 @@ impl AgentManager {
|
||||
let s = task.state.lock();
|
||||
(s.before.clone(), s.saved.as_ref().map(|name| self.shared.paths.store_dir.join(name)))
|
||||
};
|
||||
let restamped = blocking(move || {
|
||||
let restamped = vcs(&self.shared, move || {
|
||||
let changed = match &turn.changed {
|
||||
Some(changed) => changed.clone(),
|
||||
None => worktree::changed_in_turn(&cwd, &turn)?.1,
|
||||
@@ -1999,7 +2024,7 @@ impl AgentManager {
|
||||
let Some(base) = base else {
|
||||
return Err(IdeError::invalid("the task has no base revision to accept from"));
|
||||
};
|
||||
blocking(move || {
|
||||
vcs(&self.shared, move || {
|
||||
let wanted: Vec<AgentChange> = worktree::without_untouched(worktree::changes(&cwd, &base)?, &before)
|
||||
.into_iter()
|
||||
.filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path)))
|
||||
@@ -2113,15 +2138,24 @@ impl Task {
|
||||
/// The skills offered in this project: every discovery resolved against the policies
|
||||
/// and the task's overrides.
|
||||
async fn skill_states(&self) -> Vec<AgentSkillState> {
|
||||
let (policy, overrides, home, root) = {
|
||||
let (policy, overrides, home, roots) = {
|
||||
let shared = &self.shared;
|
||||
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
let overrides = self.state.lock().task.skill_overrides.clone();
|
||||
(policy, overrides, shared.paths.home_dir.clone(), shared.paths.project_root.clone())
|
||||
let (overrides, task_root) = {
|
||||
let s = self.state.lock();
|
||||
(s.task.skill_overrides.clone(), s.task.project_root.as_ref().map(|p| p.0.clone()))
|
||||
};
|
||||
let mut roots = Vec::new();
|
||||
if let Some(tr) = task_root {
|
||||
roots.push(tr);
|
||||
}
|
||||
roots.extend(policy.workspace_roots.iter().cloned());
|
||||
roots.push(shared.paths.project_root.clone());
|
||||
(policy, overrides, shared.paths.home_dir.clone(), roots)
|
||||
};
|
||||
blocking(move || {
|
||||
Ok(skills::resolve(
|
||||
skills::discover_skills(&root, home.as_deref()),
|
||||
skills::discover_skills_with_plugins(&roots, home.as_deref(), &policy.plugin_dirs),
|
||||
Some(&overrides),
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
@@ -2245,7 +2279,7 @@ impl Task {
|
||||
/// Records the checkout as a turn starts: what the turn's changes are compared with.
|
||||
async fn checkout_before_turn(&self) {
|
||||
let (cwd, previous, dir) = self.last_turn();
|
||||
let turn = match blocking(move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
|
||||
let turn = match vcs(&self.shared, move || worktree::start_turn(&cwd, &dir, previous.as_deref())).await {
|
||||
Ok(turn) => Some(Arc::new(turn)),
|
||||
Err(e) => {
|
||||
tracing::warn!("recording the checkout as a turn of agent task {} starts: {e}", self.id);
|
||||
@@ -2262,7 +2296,9 @@ impl Task {
|
||||
let (cwd, turn, _) = self.last_turn();
|
||||
let Some(turn) = turn else { return };
|
||||
let start = turn.clone();
|
||||
let Ok((in_worktree, all)) = blocking(move || worktree::changed_in_turn(&cwd, &start)).await else { return };
|
||||
let Ok((in_worktree, all)) = vcs(&self.shared, move || worktree::changed_in_turn(&cwd, &start)).await else {
|
||||
return;
|
||||
};
|
||||
{
|
||||
let mut s = self.state.lock();
|
||||
if !in_worktree.is_empty()
|
||||
@@ -2293,6 +2329,23 @@ impl Task {
|
||||
self.shared.emit(AgentEvent::Task { task: Box::new(task) });
|
||||
}
|
||||
|
||||
/// Takes the item and, for Send now, claims an idle turn under the same lock.
|
||||
fn take_queued(&self, id: &str, for_send: bool) -> IdeResult<(AgentQueued, bool)> {
|
||||
let mut s = self.state.lock();
|
||||
let Some(index) = s.task.queue.iter().position(|item| item.id == id) else {
|
||||
drop(s);
|
||||
self.emit_task();
|
||||
return Err(IdeError::new(ErrorKind::OutOfSync, "Message is no longer queued"));
|
||||
};
|
||||
let item = s.task.queue.remove(index);
|
||||
let was_busy = s.busy;
|
||||
s.busy |= for_send;
|
||||
drop(s);
|
||||
self.persist();
|
||||
self.emit_task();
|
||||
Ok((item, was_busy))
|
||||
}
|
||||
|
||||
/// Shows (or clears) the agent's pending retry; emitted only when it changes.
|
||||
fn set_retry(&self, retry: Option<AgentRetry>) {
|
||||
{
|
||||
@@ -2470,6 +2523,8 @@ impl Task {
|
||||
/// the user stops one. The caller set `busy`.
|
||||
async fn run(self: Arc<Self>, mut prompt: AgentPrompt) {
|
||||
loop {
|
||||
// The message shows before the checkout is recorded, which can take a while in a large repository.
|
||||
self.show_prompt(&prompt);
|
||||
self.checkout_before_turn().await;
|
||||
let result = self.turn(&prompt).await;
|
||||
self.cancel_pending.store(false, Ordering::Release);
|
||||
@@ -2501,7 +2556,10 @@ impl Task {
|
||||
self.push_entry(AgentEntry::Error { message: "The agent declined to continue.".into() });
|
||||
}
|
||||
match (next, result) {
|
||||
(Some(queued), _) => prompt = queued.prompt,
|
||||
(Some(queued), _) => {
|
||||
self.emit_task();
|
||||
prompt = queued.prompt;
|
||||
}
|
||||
(None, Ok(stop)) => {
|
||||
self.set_status(AgentStatus::Ready, None);
|
||||
if stop != "cancelled" {
|
||||
@@ -2537,8 +2595,7 @@ impl Task {
|
||||
|
||||
async fn switch_discovered_model(&self, target: AgentConfigOption, value: String) -> IdeResult<()> {
|
||||
let provider = self.state.lock().task.provider.clone();
|
||||
let spec = self.shared.spec(&provider).ok_or_else(|| IdeError::not_found("no such agent"))?;
|
||||
let candidate = self.shared.paths.catalogs.fresh_model(&self.shared, &spec, &value).ok_or_else(|| {
|
||||
let candidate = self.shared.paths.catalogs.listed_model(&self.shared, &provider, &value).ok_or_else(|| {
|
||||
IdeError::invalid(format!("{} has no value {value} in the current model catalog", target.name))
|
||||
})?;
|
||||
let selection = {
|
||||
@@ -2781,11 +2838,8 @@ impl Task {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sends one prompt, starting the agent first if needed; returns the stop reason.
|
||||
async fn turn(self: &Arc<Self>, prompt: &AgentPrompt) -> Result<String, Failure> {
|
||||
self.turns.fetch_add(1, Ordering::AcqRel);
|
||||
self.turn_started.store(false, Ordering::Release);
|
||||
self.state.lock().task.resets_ms = None;
|
||||
/// Adds the user's message to the conversation and shows the task starting.
|
||||
fn show_prompt(self: &Arc<Self>, prompt: &AgentPrompt) {
|
||||
let attachments = prompt
|
||||
.files
|
||||
.iter()
|
||||
@@ -2803,6 +2857,13 @@ impl Task {
|
||||
// Launching the agent can take a while (`npx` fetches its adapter on first use).
|
||||
let starting = self.live.lock().as_ref().is_none_or(|l| l.peer.is_closed());
|
||||
self.set_status(if starting { AgentStatus::Starting } else { AgentStatus::Running }, None);
|
||||
}
|
||||
|
||||
/// Sends one prompt, starting the agent first if needed; returns the stop reason.
|
||||
async fn turn(self: &Arc<Self>, prompt: &AgentPrompt) -> Result<String, Failure> {
|
||||
self.turns.fetch_add(1, Ordering::AcqRel);
|
||||
self.turn_started.store(false, Ordering::Release);
|
||||
self.state.lock().task.resets_ms = None;
|
||||
let mut live = self.ensure_session().await.map_err(Failure::from)?;
|
||||
// Stopped while the agent started: the prompt is never sent.
|
||||
if self.cancel_pending.load(Ordering::Acquire) {
|
||||
@@ -3024,8 +3085,12 @@ impl Task {
|
||||
let sign_in_message = spec.sign_in_message(&init.auth_methods);
|
||||
let can_load = init.load_session();
|
||||
let (capabilities, embedded) = capabilities_of(&init);
|
||||
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
|
||||
let (mcp_overrides, project_root) = {
|
||||
let s = self.state.lock();
|
||||
(s.task.mcp_overrides.clone(), s.task.project_root.clone().map(|p| p.0))
|
||||
};
|
||||
let mcp_servers = self.shared.mcp_servers_for_session(provider_id, &init, &mcp_overrides);
|
||||
let roots = self.shared.additional_directories(&init, cwd, project_root.as_deref());
|
||||
let skills_delivery = self.stage_skills(stage_key(spec.driver), cwd).await;
|
||||
// Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`).
|
||||
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
|
||||
@@ -3041,7 +3106,7 @@ impl Task {
|
||||
}
|
||||
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
|
||||
self.replaying.store(true, Ordering::Release);
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
|
||||
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
params["sessionId"] = json!(&id);
|
||||
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
|
||||
tokio::time::sleep(REPLAY_GRACE).await;
|
||||
@@ -3081,7 +3146,7 @@ impl Task {
|
||||
let (session_id, result) = match session {
|
||||
Some(s) => s,
|
||||
None => {
|
||||
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref());
|
||||
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
|
||||
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|
||||
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
|
||||
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
|
||||
@@ -4071,9 +4136,12 @@ fn stage_key(driver: provider::Driver) -> &'static str {
|
||||
/// The session parameters `session/new`, `session/load` and `session/fork` share: the MCP
|
||||
/// servers, and the ones off for this session, so an agent that also loads its own
|
||||
/// configuration (Claude Code) can keep a same-named server of it off too — plus the
|
||||
/// session's staged skills for the drivers that take them.
|
||||
fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delivery>) -> Value {
|
||||
/// session's staged skills for the drivers that take them, and the workspace's other roots.
|
||||
fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delivery>, roots: &[String]) -> Value {
|
||||
let mut params = json!({ "cwd": cwd, "mcpServers": mcp.servers });
|
||||
if !roots.is_empty() {
|
||||
params["additionalDirectories"] = json!(roots);
|
||||
}
|
||||
let mut meta = json!({});
|
||||
if !mcp.off.is_empty() {
|
||||
meta["mcpServersOff"] = json!(mcp.off);
|
||||
@@ -4177,8 +4245,11 @@ fn file_uri(path: &Path) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// The title of a task: the first line of the prompt that says something. A pasted Markdown
|
||||
/// block opens with a code fence (```` ```text ````), which names no task.
|
||||
fn title_of(prompt: &AgentPrompt) -> String {
|
||||
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty());
|
||||
let is_fence = |l: &str| l.starts_with("```") || l.starts_with("~~~");
|
||||
let line = prompt.text.lines().map(str::trim).find(|l| !l.is_empty() && !is_fence(l));
|
||||
let line = match line {
|
||||
Some(l) => l.to_owned(),
|
||||
None => prompt.files.first().map(|f| file_name(&f.0)).unwrap_or_else(|| "Image".into()),
|
||||
@@ -4210,6 +4281,25 @@ async fn blocking<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + Send + '
|
||||
tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// [`blocking`] for work that runs git: the repositories it opens run the project's git.
|
||||
async fn vcs<T: Send + 'static>(shared: &Shared, f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
|
||||
let git = shared.git_executable.read().as_ref().and_then(|hook| hook());
|
||||
blocking(move || ide_vcs::with_git_executable(git.as_deref(), f)).await
|
||||
}
|
||||
|
||||
async fn read_changes<T: Send + 'static>(
|
||||
shared: &Shared,
|
||||
f: impl FnOnce() -> IdeResult<T> + Send + 'static,
|
||||
) -> IdeResult<T> {
|
||||
let permit = shared.change_reads.clone().acquire_owned().await.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
vcs(shared, move || {
|
||||
// Dropping the caller doesn't cancel a blocking job. Keep the slot with the work.
|
||||
let _permit = permit;
|
||||
f()
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod replay;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -941,107 +941,10 @@ fn normalize_agents_list(agents: Vec<String>) -> Vec<String> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Strips `//` line comments, `/* ... */` block comments, and trailing commas before `}` or `]`
|
||||
/// outside JSON string literals so JSONC config files parse cleanly with `serde_json`.
|
||||
pub(crate) fn strip_jsonc(input: &str) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut out = String::with_capacity(input.len());
|
||||
let mut i = 0;
|
||||
let mut in_str = false;
|
||||
while i < bytes.len() {
|
||||
if in_str {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
if ch == '\\' && i < bytes.len() {
|
||||
let next = input[i..].chars().next().unwrap();
|
||||
out.push(next);
|
||||
i += next.len_utf8();
|
||||
} else if ch == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'"' {
|
||||
in_str = true;
|
||||
out.push('"');
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
|
||||
i += 2;
|
||||
while i < bytes.len() && bytes[i] != b'\n' {
|
||||
i += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'*' {
|
||||
i += 2;
|
||||
while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
|
||||
if bytes[i] == b'\n' {
|
||||
out.push('\n');
|
||||
i += 1;
|
||||
} else {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
}
|
||||
i = (i + 2).min(bytes.len());
|
||||
continue;
|
||||
}
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
remove_trailing_commas(&out)
|
||||
}
|
||||
|
||||
fn remove_trailing_commas(input: &str) -> String {
|
||||
let bytes = input.as_bytes();
|
||||
let mut out = String::with_capacity(input.len());
|
||||
let mut i = 0;
|
||||
let mut in_str = false;
|
||||
while i < bytes.len() {
|
||||
if in_str {
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
if ch == '\\' && i < bytes.len() {
|
||||
let next = input[i..].chars().next().unwrap();
|
||||
out.push(next);
|
||||
i += next.len_utf8();
|
||||
} else if ch == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b'"' {
|
||||
in_str = true;
|
||||
out.push('"');
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if bytes[i] == b',' {
|
||||
let mut j = i + 1;
|
||||
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
|
||||
j += 1;
|
||||
}
|
||||
if j < bytes.len() && (bytes[j] == b'}' || bytes[j] == b']') {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let ch = input[i..].chars().next().unwrap();
|
||||
out.push(ch);
|
||||
i += ch.len_utf8();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn parse_jsonc_value(raw: &str) -> Result<Value, String> {
|
||||
let trimmed = raw.trim().trim_start_matches('\u{feff}');
|
||||
serde_json::from_str::<Value>(trimmed)
|
||||
.or_else(|_| serde_json::from_str::<Value>(&strip_jsonc(trimmed)))
|
||||
.or_else(|_| serde_json::from_str::<Value>(&ide_core::jsonc::strip(trimmed)))
|
||||
.map_err(|e| format!("Invalid JSON: {e}"))
|
||||
}
|
||||
|
||||
|
||||
@@ -536,6 +536,9 @@ pub enum AgentEntry {
|
||||
kind: String,
|
||||
status: AgentToolStatus,
|
||||
locations: Vec<IpcPath>,
|
||||
/// Images returned by the tool, kept separately from its truncated text.
|
||||
#[serde(default)]
|
||||
images: Vec<AgentImage>,
|
||||
/// Text the tool reported (command output…), truncated.
|
||||
output: Option<String>,
|
||||
diffs: Vec<AgentToolDiff>,
|
||||
@@ -711,6 +714,8 @@ pub struct AgentChange {
|
||||
pub removed: u32,
|
||||
/// Path before a rename; the left side of its diff reads this path.
|
||||
pub old_path: Option<String>,
|
||||
/// The repository the file is in, when the task's project holds nested repositories.
|
||||
pub repo: Option<IpcPath>,
|
||||
}
|
||||
|
||||
/// A commit made while the task ran, with the files it changed against its first parent.
|
||||
@@ -764,7 +769,7 @@ pub struct AgentModelCatalog {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Streamed to the window that subscribed (`AgentManager::subscribe`).
|
||||
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum AgentEvent {
|
||||
@@ -896,6 +901,8 @@ pub enum AgentSkillSource {
|
||||
Workspace,
|
||||
/// The user's `~/.agents/skills` (what `npx skills add` fills).
|
||||
User,
|
||||
/// Contributed by an enabled OpenIDEA plugin (`[[contributes.skills]]`).
|
||||
Plugin,
|
||||
/// The project's `.claude/skills`.
|
||||
ClaudeWorkspace,
|
||||
/// `~/.claude/skills`.
|
||||
@@ -918,7 +925,7 @@ impl AgentSkillSource {
|
||||
/// Whether skills of this source are only read, never delivered by OpenIDEA: the CLI
|
||||
/// discovers them itself, so "off" holds only where the CLI supports a native disable.
|
||||
pub fn discovered(&self) -> bool {
|
||||
!matches!(self, Self::Workspace | Self::User)
|
||||
!matches!(self, Self::Workspace | Self::User | Self::Plugin)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -929,9 +936,27 @@ pub struct AgentSkill {
|
||||
/// The frontmatter `name`, else the folder's name.
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
/// Optional `argument-hint` from frontmatter, completed in the `/` menu.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub hint: Option<String>,
|
||||
/// Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse).
|
||||
pub path: IpcPath,
|
||||
pub source: AgentSkillSource,
|
||||
/// Other skill roots whose symlinked entry resolved to this same canonical `path`.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub also_in: Vec<AgentSkillSource>,
|
||||
/// False when frontmatter sets `user-invocable: false` (omitted from `/` completion).
|
||||
#[serde(default = "default_true")]
|
||||
pub user_invocable: bool,
|
||||
/// True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`).
|
||||
#[serde(default)]
|
||||
pub disable_model_invocation: bool,
|
||||
/// True when frontmatter sets `context: fork` (passed through natively to supporting CLIs).
|
||||
#[serde(default)]
|
||||
pub context_fork: bool,
|
||||
/// Optional `paths` / `globs` patterns from frontmatter (passed through natively to supporting CLIs).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub paths: Vec<String>,
|
||||
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
|
||||
pub valid: bool,
|
||||
/// What validation found (`name` mismatch, missing or over-long description…).
|
||||
|
||||
@@ -174,6 +174,8 @@ struct Session {
|
||||
mcp_off: Vec<String>,
|
||||
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
|
||||
skills_add_dir: Option<PathBuf>,
|
||||
/// The workspace's other roots, each passed as `--add-dir`.
|
||||
additional_dirs: Vec<String>,
|
||||
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
|
||||
skills_settings: Option<String>,
|
||||
shim: Weak<Shim>,
|
||||
@@ -366,6 +368,7 @@ impl Shim {
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
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),
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
@@ -412,7 +415,7 @@ impl Shim {
|
||||
"agentCapabilities": {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "embeddedContext": true },
|
||||
"sessionCapabilities": { "fork": {} },
|
||||
"sessionCapabilities": { "fork": {}, "additionalDirectories": {} },
|
||||
"mcpCapabilities": { "stdio": true, "http": true, "sse": true },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true, "contextUsage": true } },
|
||||
},
|
||||
@@ -685,6 +688,9 @@ impl Session {
|
||||
if let Some(dir) = &self.skills_add_dir {
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
for dir in &self.additional_dirs {
|
||||
args.extend(["--add-dir".to_owned(), dir.clone()]);
|
||||
}
|
||||
if let Some(settings) = &self.skills_settings {
|
||||
args.extend(["--settings".to_owned(), settings.clone()]);
|
||||
}
|
||||
@@ -1001,11 +1007,16 @@ impl Session {
|
||||
let mut updates = Vec::new();
|
||||
let mut finished = None;
|
||||
let mut read_title = false;
|
||||
let mut refresh_usage = false;
|
||||
{
|
||||
let mut st = self.st.lock();
|
||||
let st = &mut *st;
|
||||
match kind {
|
||||
"system" => match msg.get("subtype").and_then(Value::as_str) {
|
||||
Some("compact_boundary") => {
|
||||
refresh_usage = msg.pointer("/compact_metadata/post_tokens").is_none_or(Value::is_null);
|
||||
updates.extend(st.tr.on_message(&msg));
|
||||
}
|
||||
Some("init") => {
|
||||
st.terminal_only = strings(msg.get("terminal_slash_commands"));
|
||||
}
|
||||
@@ -1109,6 +1120,31 @@ impl Session {
|
||||
if read_title {
|
||||
self.read_title();
|
||||
}
|
||||
if refresh_usage {
|
||||
self.refresh_usage();
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends what the context holds after a compaction that didn't report it, as Claude Code
|
||||
/// counts it (`get_context_usage`); until then the meter would show the count from before.
|
||||
fn refresh_usage(self: &Arc<Self>) {
|
||||
let me = self.clone();
|
||||
tokio::spawn(async move {
|
||||
let Some(proc) = me.st.lock().proc.clone() else { return };
|
||||
let usage = match proc.control(json!({ "subtype": "get_context_usage" })).await {
|
||||
Ok(usage) => usage,
|
||||
Err(e) => {
|
||||
tracing::debug!("reading claude context usage after compaction: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let n = |k: &str| usage.get(k).and_then(Value::as_u64);
|
||||
let (Some(used), Some(size)) = (n("totalTokens"), n("maxTokens").filter(|m| *m > 0)) else { return };
|
||||
let update = me.st.lock().tr.on_context_usage(used, size);
|
||||
if let Some(shim) = me.shim() {
|
||||
shim.notify(vec![update]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Sends the session's title once it has one: the one in its transcript, or else one
|
||||
@@ -1522,6 +1558,12 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
|
||||
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
|
||||
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
|
||||
/// Claude Code's own configuration stays off too.
|
||||
/// The session's `additionalDirectories`: the workspace's other roots.
|
||||
fn additional_dirs(params: &Value) -> Vec<String> {
|
||||
let dirs = params.get("additionalDirectories").and_then(Value::as_array);
|
||||
dirs.into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
fn mcp_off(params: &Value) -> Vec<String> {
|
||||
params
|
||||
.pointer("/_meta/openidea/mcpServersOff")
|
||||
|
||||
@@ -531,6 +531,38 @@ async fn sessions_without_a_title_get_one_generated() {
|
||||
assert_eq!(request["request"]["persist"], true);
|
||||
}
|
||||
|
||||
/// A compaction that doesn't report what the context holds now (no `post_tokens`): the
|
||||
/// driver asks Claude Code, and the meter shows that instead of the count from before.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_compaction_without_its_token_count_reads_the_context_usage() {
|
||||
let mut processes = load_fixture("simple");
|
||||
processes[0].extend([
|
||||
Frame::Cli(json!({"type": "system", "subtype": "compact_boundary",
|
||||
"compact_metadata": {"trigger": "manual", "pre_tokens": 120000}})),
|
||||
Frame::Shim(json!({"type": "control_request", "request_id": "req_3",
|
||||
"request": {"subtype": "get_context_usage"}})),
|
||||
Frame::Cli(json!({"type": "control_response", "response": {"subtype": "success", "request_id": "req_3",
|
||||
"response": {"categories": [], "totalTokens": 4200, "maxTokens": 200000, "model": "claude"}}})),
|
||||
]);
|
||||
let cli = replay_cli(processes);
|
||||
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 session = h.new_session().await;
|
||||
h.prompt(&session, "Reply with exactly: hello there").await.unwrap();
|
||||
let mut usage = Vec::new();
|
||||
for _ in 0..100 {
|
||||
usage = h.updates(&session, "usage_update");
|
||||
if usage.last().is_some_and(|u| u["used"] == 4200) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
assert!(cli.errors.lock().is_empty(), "{:?}", cli.errors.lock());
|
||||
assert_eq!(usage.last().map(|u| (u["used"].clone(), u["size"].clone())), Some((json!(4200), json!(200000))));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_multi_turn() {
|
||||
let r = replay("multi_turn").await;
|
||||
@@ -1098,6 +1130,24 @@ fn streamed_text_is_not_sent_twice() {
|
||||
assert_eq!(usage[0].update, json!({"sessionUpdate": "usage_update", "used": 15, "size": 1000}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_compaction_replaces_the_context_usage() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), true);
|
||||
let assistant = json!({"type": "assistant", "parent_tool_use_id": null,
|
||||
"message": {"id": "m1", "model": "x", "content": [], "usage": {"input_tokens": 900, "output_tokens": 50}}});
|
||||
t.on_message(&assistant);
|
||||
let result = json!({"modelUsage": {"x": {"contextWindow": 1000}}});
|
||||
assert_eq!(t.on_result(&result)[0].update["used"], 950);
|
||||
let boundary = |meta: Value| json!({"type": "system", "subtype": "compact_boundary", "compact_metadata": meta});
|
||||
let out = t.on_message(&boundary(json!({"trigger": "manual", "pre_tokens": 950, "post_tokens": 120})));
|
||||
assert_eq!(out[0].update, json!({"sessionUpdate": "usage_update", "used": 120, "size": 1000}));
|
||||
// The `/compact` turn's result reports what compaction left, not the count from before.
|
||||
assert_eq!(t.on_result(&result)[0].update["used"], 120);
|
||||
// Without `post_tokens` nothing is known yet (the driver asks): the stale count stays out.
|
||||
assert!(t.on_message(&boundary(json!({"trigger": "auto", "pre_tokens": 950}))).is_empty());
|
||||
assert!(t.on_result(&result).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rate_limits_and_cost() {
|
||||
let mut t = Translator::new("s", PathBuf::from("/w"), false);
|
||||
@@ -1275,3 +1325,10 @@ fn mcp_servers_become_an_mcp_config() {
|
||||
drop(path);
|
||||
assert!(!kept.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_directories_are_read_from_the_session_params() {
|
||||
let params = json!({ "cwd": "/w/api", "additionalDirectories": ["/w/web", 3, "/w/docs"] });
|
||||
assert_eq!(additional_dirs(¶ms), ["/w/web", "/w/docs"]);
|
||||
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
|
||||
}
|
||||
@@ -144,6 +144,22 @@ pub(super) fn result_fields(name: &str, input: &Value, block: &Value, structured
|
||||
content.push(text(&t));
|
||||
}
|
||||
}
|
||||
if let Some(blocks) = block.get("content").and_then(Value::as_array) {
|
||||
for block in blocks {
|
||||
if block.get("type").and_then(Value::as_str) != Some("image") {
|
||||
continue;
|
||||
}
|
||||
let Some(source) = block.get("source") else { continue };
|
||||
if source.get("type").and_then(Value::as_str) != Some("base64") {
|
||||
continue;
|
||||
}
|
||||
let data = source.get("data").and_then(Value::as_str).unwrap_or_default();
|
||||
let mime = source.get("media_type").and_then(Value::as_str).unwrap_or_default();
|
||||
if !data.is_empty() && mime.starts_with("image/") {
|
||||
content.push(json!({"type": "content", "content": {"type": "image", "mimeType": mime, "data": data}}));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = json!({ "status": if failed { "failed" } else { "completed" } });
|
||||
if !content.is_empty() {
|
||||
out["content"] = Value::Array(content);
|
||||
@@ -230,6 +246,43 @@ mod tests {
|
||||
assert_eq!(call_fields("WebSearch", &json!({"query": "q"}), cwd)["kind"], "fetch");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_tool_results_keep_text_and_inline_images() {
|
||||
let result = result_fields(
|
||||
"Read",
|
||||
&json!({"file_path": "/w/preview.png"}),
|
||||
&json!({"content": [
|
||||
{"type": "text", "text": "Preview ready"},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
|
||||
]}),
|
||||
None,
|
||||
);
|
||||
assert_eq!(result["status"], "completed");
|
||||
assert_eq!(
|
||||
result["content"],
|
||||
json!([
|
||||
text("Preview ready"),
|
||||
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "aW1hZ2U="}}
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_shell_tool_images_keep_fallback_error_text() {
|
||||
let result = result_fields(
|
||||
"Bash",
|
||||
&json!({}),
|
||||
&json!({"is_error": true, "content": [
|
||||
{"type": "text", "text": "Preview command failed"},
|
||||
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aW1hZ2U="}}
|
||||
]}),
|
||||
Some(&json!({"stdout": "", "stderr": ""})),
|
||||
);
|
||||
assert_eq!(result["status"], "failed");
|
||||
assert_eq!(result["content"][0], text("Preview command failed"));
|
||||
assert_eq!(result["content"][1]["content"]["type"], "image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results() {
|
||||
let input = json!({"file_path": "/w/n.txt", "content": "two"});
|
||||
|
||||
@@ -458,6 +458,13 @@ impl Translator {
|
||||
let last = self.children.get(&tool_use).map(|c| c.last_text.clone()).filter(|t| !t.is_empty());
|
||||
self.finish_child(&tool_use, stop, last.or(summary))
|
||||
}
|
||||
// Compaction replaced the conversation with its summary: the context now holds
|
||||
// `post_tokens`. Without it the stale count must not come back with the result;
|
||||
// the driver asks Claude Code instead (`Session::refresh_usage`).
|
||||
Some("compact_boundary") => {
|
||||
self.used = msg.pointer("/compact_metadata/post_tokens").and_then(Value::as_u64);
|
||||
self.usage_update().into_iter().collect()
|
||||
}
|
||||
// A turn's background tasks (`run_in_background`) outlive it: the task keeps
|
||||
// the list and stays up while it isn't empty (see `Task::release_when_idle`).
|
||||
Some("background_tasks_changed") => {
|
||||
@@ -561,6 +568,16 @@ impl Translator {
|
||||
self.usage_update().into_iter().collect()
|
||||
}
|
||||
|
||||
/// 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);
|
||||
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" });
|
||||
}
|
||||
Update { session: self.root.clone(), update }
|
||||
}
|
||||
|
||||
fn usage_update(&self) -> Option<Update> {
|
||||
let used = self.used?;
|
||||
let size = self
|
||||
|
||||
@@ -357,6 +357,13 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
|
||||
if !config.as_object().is_some_and(|m| m.is_empty()) {
|
||||
request["config"] = config;
|
||||
}
|
||||
// The workspace's other roots join the thread's own: they are where `workspace-write`
|
||||
// may write and what the model is told the workspace holds.
|
||||
if let Some(extra) = params.get("additionalDirectories").and_then(Value::as_array).filter(|a| !a.is_empty())
|
||||
&& let Some(cwd) = params.get("cwd").filter(|c| c.is_string())
|
||||
{
|
||||
request["runtimeWorkspaceRoots"] = std::iter::once(cwd).chain(extra).cloned().collect();
|
||||
}
|
||||
}
|
||||
|
||||
impl CodexShim {
|
||||
@@ -406,7 +413,7 @@ impl CodexShim {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": false, "sse": false, "stdio": true },
|
||||
"sessionCapabilities": { "fork": {}, "close": {} },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true } },
|
||||
},
|
||||
"agentInfo": { "name": "codex", "title": "Codex", "version": version },
|
||||
|
||||
@@ -1847,3 +1847,14 @@ fn skills_become_commands_with_their_invocation_names() {
|
||||
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
|
||||
assert!(skill_commands(&json!({})).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_roots_join_the_thread_roots() {
|
||||
let params = json!({ "cwd": "/w/api", "mcpServers": [], "additionalDirectories": ["/w/web"] });
|
||||
let mut request = json!({});
|
||||
apply_thread_config(¶ms, &mut request);
|
||||
assert_eq!(request["runtimeWorkspaceRoots"], json!(["/w/api", "/w/web"]));
|
||||
let mut request = json!({});
|
||||
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
|
||||
assert!(request.get("runtimeWorkspaceRoots").is_none());
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+700
-108
@@ -125,10 +125,9 @@ fn file_name(path: &Path) -> Option<String> {
|
||||
path.file_name()?.to_str().map(str::to_owned)
|
||||
}
|
||||
|
||||
/// The `key: value` lines between the leading `---` fences (folded `>` / `|` values joined).
|
||||
struct Frontmatter {
|
||||
fields: Vec<(String, String)>,
|
||||
/// Where the body starts.
|
||||
lists: Vec<(String, Vec<String>)>,
|
||||
body: usize,
|
||||
}
|
||||
|
||||
@@ -138,22 +137,42 @@ impl Frontmatter {
|
||||
let mut lines = text.split_inclusive('\n');
|
||||
let mut offset = 0;
|
||||
let mut fields: Vec<(String, String)> = Vec::new();
|
||||
let mut lists: Vec<(String, Vec<String>)> = Vec::new();
|
||||
match lines.next() {
|
||||
Some(first) if first.trim_end() == "---" => offset += first.len(),
|
||||
_ => return Self { fields, body: 0 },
|
||||
_ => return Self { fields, lists, body: 0 },
|
||||
}
|
||||
for line in lines {
|
||||
offset += line.len();
|
||||
let line = line.trim_end();
|
||||
if line == "---" {
|
||||
return Self { fields, body: offset };
|
||||
return Self { fields, lists, body: offset };
|
||||
}
|
||||
if line.starts_with([' ', '\t']) {
|
||||
let unindented_list_item = (line == "-" || line.starts_with("- ") || line.starts_with("-\t"))
|
||||
&& fields.last().is_some_and(|(_, v)| v.is_empty());
|
||||
if line.starts_with([' ', '\t']) || unindented_list_item {
|
||||
let trimmed = line.trim();
|
||||
if let Some(rest) = trimmed.strip_prefix('-')
|
||||
&& (rest.is_empty() || rest.starts_with([' ', '\t']))
|
||||
&& let Some((key, _)) = fields.last()
|
||||
{
|
||||
let item = unquote(rest.trim());
|
||||
if !item.is_empty() {
|
||||
if let Some((_, existing)) = lists.iter_mut().find(|(k, _)| k == key) {
|
||||
existing.push(item.to_owned());
|
||||
} else {
|
||||
lists.push((key.clone(), vec![item.to_owned()]));
|
||||
}
|
||||
}
|
||||
if unindented_list_item {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some((_, value)) = fields.last_mut() {
|
||||
if !value.is_empty() {
|
||||
value.push(' ');
|
||||
}
|
||||
value.push_str(line.trim());
|
||||
value.push_str(trimmed);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -164,11 +183,15 @@ impl Frontmatter {
|
||||
}
|
||||
}
|
||||
// No closing fence: not frontmatter.
|
||||
Self { fields: Vec::new(), body: 0 }
|
||||
Self { fields: Vec::new(), lists: Vec::new(), body: 0 }
|
||||
}
|
||||
|
||||
fn get(&self, key: &str) -> Option<&str> {
|
||||
self.fields.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
|
||||
self.fields.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
fn list(&self, key: &str) -> Option<&[String]> {
|
||||
self.lists.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_slice())
|
||||
}
|
||||
|
||||
/// `description`, else the body's first line.
|
||||
@@ -240,86 +263,327 @@ const HOME_ROOTS: &[(&str, AgentSkillSource)] = &[
|
||||
/// duplicates collapsed by canonical path: the first of a path wins, and so does the first
|
||||
/// of a name (the higher source), so a session never sees one skill twice.
|
||||
pub fn discover_skills(workspace: &Path, home: Option<&Path>) -> Vec<AgentSkill> {
|
||||
discover_skills_in(&[workspace.to_path_buf()], home)
|
||||
}
|
||||
|
||||
/// Every skill found across `workspaces` (a project and any workspace/monorepo member
|
||||
/// folders) and `home`, in source precedence order, symlinked duplicates collapsed by
|
||||
/// canonical path while recording secondary sources in [`AgentSkill::also_in`].
|
||||
pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<AgentSkill> {
|
||||
discover_skills_with_plugins(workspaces, home, &[])
|
||||
}
|
||||
|
||||
/// [`discover_skills_in`] plus the `<dir>` skill folders contributed by enabled OpenIDEA
|
||||
/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name
|
||||
/// clash; a plugin skill is never silently renamed.
|
||||
pub fn discover_skills_with_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
|
||||
let mut seen_names: HashSet<String> = HashSet::new();
|
||||
let mut roots: Vec<(PathBuf, AgentSkillSource)> = Vec::new();
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (workspace.join(rel), *source)));
|
||||
let mut plugin_roots = Vec::new();
|
||||
if let Some(home) = home {
|
||||
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
|
||||
// `copilot install` unpacks plugins under `installed-plugins/<plugin>/`, whose skills
|
||||
// sit in a `skills` folder (or directly in the plugin folder).
|
||||
let plugins = home.join(".copilot/installed-plugins");
|
||||
if let Ok(plugins) = plugins.read_dir() {
|
||||
for plugin in plugins.flatten() {
|
||||
if plugin.path().is_dir() {
|
||||
plugin_roots.push((plugin.path().join("skills"), AgentSkillSource::CopilotUser));
|
||||
plugin_roots.push((plugin.path(), AgentSkillSource::CopilotUser));
|
||||
}
|
||||
let mut seen_workspaces: HashSet<PathBuf> = HashSet::new();
|
||||
let mut all_workspaces: Vec<PathBuf> = Vec::new();
|
||||
for ws in workspaces {
|
||||
let canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.clone());
|
||||
if seen_workspaces.insert(canon) {
|
||||
all_workspaces.push(ws.clone());
|
||||
}
|
||||
}
|
||||
for ws in &all_workspaces {
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (ws.join(rel), *source)));
|
||||
}
|
||||
// Nested monorepo packages (up to two levels below each workspace root, e.g. `apps/web`).
|
||||
for ws in &all_workspaces {
|
||||
for sub in monorepo_subdirs(ws, 2) {
|
||||
let sub_canon = dunce::canonicalize(&sub).unwrap_or_else(|_| sub.clone());
|
||||
if seen_workspaces.insert(sub_canon) {
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (sub.join(rel), *source)));
|
||||
}
|
||||
}
|
||||
}
|
||||
roots.extend(plugin_roots);
|
||||
if let Some(home) = home {
|
||||
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
|
||||
}
|
||||
let mut push_skill = |skill: AgentSkill| {
|
||||
let path = dunce::canonicalize(&skill.path.0).unwrap_or_else(|_| skill.path.0.clone());
|
||||
if !seen_paths.insert(path.clone()) {
|
||||
if let Some(existing) = out.iter_mut().find(|s| s.path.0 == path)
|
||||
&& existing.source != skill.source
|
||||
&& !existing.also_in.contains(&skill.source)
|
||||
{
|
||||
existing.also_in.push(skill.source);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if !seen_names.insert(skill.name.to_ascii_lowercase()) {
|
||||
return;
|
||||
}
|
||||
out.push(AgentSkill { path: path.into(), ..skill });
|
||||
};
|
||||
for (root, source) in roots {
|
||||
for skill in skills_of(&root, source) {
|
||||
let path = dunce::canonicalize(&skill.path.0).unwrap_or_else(|_| skill.path.0.clone());
|
||||
if !seen_paths.insert(path.clone()) || !seen_names.insert(skill.name.clone()) {
|
||||
continue;
|
||||
push_skill(skill);
|
||||
}
|
||||
}
|
||||
for dir in plugin_skill_dirs {
|
||||
let Some(folder) = file_name(dir) else { continue };
|
||||
if !dir.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
|
||||
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
|
||||
}
|
||||
if let Some(home) = home {
|
||||
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
|
||||
for skill in skills_of(&root, source) {
|
||||
push_skill(skill);
|
||||
}
|
||||
out.push(AgentSkill { path: path.into(), ..skill });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The skills of one root: `<name>/SKILL.md` folders, validated.
|
||||
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(root) else { return out };
|
||||
for entry in entries.flatten() {
|
||||
let dir = entry.path();
|
||||
let Some(folder) = dir.file_name().and_then(|n| n.to_str()).map(str::to_owned) else { continue };
|
||||
if !dir.is_dir() || folder.starts_with('.') {
|
||||
/// Validates a plugin-contributed `<folder>/SKILL.md` against the hub's folder-name and
|
||||
/// frontmatter rules (`name` 1–64 `[a-z0-9-]`, matching `folder`, non-empty `description` ≤ 1024 chars).
|
||||
pub fn validate_plugin_skill(dir: &Path, folder: &str, text: &str) -> Result<AgentSkill, String> {
|
||||
if !valid_name(folder) {
|
||||
return Err(format!("skill folder `{folder}` must be 1-64 lowercase letters, digits or hyphens"));
|
||||
}
|
||||
let skill = parse_skill_file(dir, folder, text, AgentSkillSource::Plugin);
|
||||
if !skill.valid {
|
||||
return Err(skill.warnings.join("; "));
|
||||
}
|
||||
Ok(skill)
|
||||
}
|
||||
|
||||
const SKIP_MONOREPO_DIRS: &[&str] =
|
||||
&["node_modules", "target", "dist", "build", "out", "vendor", "coverage", ".git", ".openidea", ".idea"];
|
||||
|
||||
fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
|
||||
if max_depth == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for dir in sorted(root) {
|
||||
let Some(name) = file_name(&dir) else { continue };
|
||||
if SKIP_MONOREPO_DIRS.contains(&name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
|
||||
let meta = Frontmatter::parse(&text);
|
||||
let name = meta.get("name").filter(|n| !n.is_empty()).map(str::to_owned).unwrap_or_else(|| folder.clone());
|
||||
let mut warnings = Vec::new();
|
||||
if !valid_name(&name) {
|
||||
warnings.push(format!("`name: {name}` is not 1-64 lowercase letters, digits or hyphens"));
|
||||
let Ok(meta) = std::fs::symlink_metadata(&dir) else { continue };
|
||||
if !meta.file_type().is_dir() {
|
||||
continue;
|
||||
}
|
||||
if name != folder {
|
||||
warnings.push(format!("`name: {name}` does not match the folder `{folder}`"));
|
||||
if WORKSPACE_ROOTS.iter().any(|(rel, _)| dir.join(rel).is_dir()) {
|
||||
out.push(dir.clone());
|
||||
}
|
||||
let description = meta.get("description").unwrap_or_default();
|
||||
let description = strip_ansi(description).trim().to_owned();
|
||||
if description.is_empty() {
|
||||
warnings.push("no `description`: the model never sees when to use it".into());
|
||||
} else if description.chars().count() > MAX_SKILL_DESCRIPTION {
|
||||
warnings.push(format!("`description` is over {MAX_SKILL_DESCRIPTION} characters"));
|
||||
if max_depth > 1 {
|
||||
out.extend(monorepo_subdirs(&dir, max_depth - 1));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Discovers skill roots inside `~/.copilot/installed-plugins`, supporting both Copilot CLI's
|
||||
/// 2-level `<marketplace-or-_direct>/<plugin>` layout (and `config.json` `installedPlugins`
|
||||
/// enablement) and flat 1-level `<plugin>` folders.
|
||||
fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkillSource)> {
|
||||
let mut disabled_paths: HashSet<PathBuf> = HashSet::new();
|
||||
let mut plugin_dirs: Vec<PathBuf> = Vec::new();
|
||||
let mut seen_dirs: HashSet<PathBuf> = HashSet::new();
|
||||
let mut push_plugin = |dir: PathBuf, disabled: &HashSet<PathBuf>| {
|
||||
if !dir.is_dir() {
|
||||
return;
|
||||
}
|
||||
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
||||
if disabled.contains(&canon) || !seen_dirs.insert(canon) {
|
||||
return;
|
||||
}
|
||||
plugin_dirs.push(dir);
|
||||
};
|
||||
|
||||
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
|
||||
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
|
||||
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
|
||||
{
|
||||
for entry in installed {
|
||||
let Some(raw_cache) = entry.get("cache_path").and_then(serde_json::Value::as_str).map(str::trim) else {
|
||||
continue;
|
||||
};
|
||||
if raw_cache.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let dir =
|
||||
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
|
||||
if entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(false) {
|
||||
disabled_paths.insert(dunce::canonicalize(&dir).unwrap_or(dir));
|
||||
} else {
|
||||
push_plugin(dir, &disabled_paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let plugins_root = copilot_dir.join("installed-plugins");
|
||||
for entry in sorted(&plugins_root) {
|
||||
if !entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
if looks_like_plugin_dir(&entry) {
|
||||
push_plugin(entry, &disabled_paths);
|
||||
} else {
|
||||
// 2-level `<marketplace>/<plugin>` or `_direct/<plugin>`.
|
||||
for sub in sorted(&entry) {
|
||||
if sub.is_dir() {
|
||||
push_plugin(sub, &disabled_paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut roots = Vec::new();
|
||||
for plugin in plugin_dirs {
|
||||
let skills_sub = plugin.join("skills");
|
||||
if skills_sub.is_dir() {
|
||||
roots.push((skills_sub, AgentSkillSource::CopilotUser));
|
||||
} else {
|
||||
roots.push((plugin, AgentSkillSource::CopilotUser));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn looks_like_plugin_dir(dir: &Path) -> bool {
|
||||
dir.join("skills").is_dir()
|
||||
|| dir.join("plugin.json").is_file()
|
||||
|| dir.join(".plugin").is_dir()
|
||||
|| dir.join(".claude-plugin").is_dir()
|
||||
|| dir.join(".cursor-plugin").is_dir()
|
||||
|| dir.join("SKILL.md").is_file()
|
||||
}
|
||||
|
||||
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
|
||||
/// category folders, validated.
|
||||
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
// Warn when a user drops `SKILL.md` directly inside a `skills/` root instead of `<name>/SKILL.md`.
|
||||
if file_name(root).as_deref() == Some("skills")
|
||||
&& let Ok(text) = std::fs::read_to_string(root.join("SKILL.md"))
|
||||
{
|
||||
let mut misplaced = parse_skill_file(root, "skills", &text, source);
|
||||
misplaced.valid = false;
|
||||
misplaced
|
||||
.warnings
|
||||
.insert(0, "SKILL.md is directly inside `skills/`: move it into a `<name>/SKILL.md` subfolder".into());
|
||||
out.push(misplaced);
|
||||
}
|
||||
for dir in sorted(root) {
|
||||
let Some(folder) = file_name(&dir) else { continue };
|
||||
if !dir.is_dir() {
|
||||
continue;
|
||||
}
|
||||
if let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) {
|
||||
out.push(parse_skill_file(&dir, &folder, &text, source));
|
||||
continue;
|
||||
}
|
||||
// Category folder (`<root>/<category>/<skill>/SKILL.md`): only entered when `<dir>` itself
|
||||
// has no `SKILL.md`, so a skill's own subdirectories remain resources rather than skills.
|
||||
for sub in sorted(&dir) {
|
||||
let Some(sub_folder) = file_name(&sub) else { continue };
|
||||
if !sub.is_dir() {
|
||||
continue;
|
||||
}
|
||||
if let Ok(text) = std::fs::read_to_string(sub.join("SKILL.md")) {
|
||||
out.push(parse_skill_file(&sub, &sub_folder, &text, source));
|
||||
}
|
||||
}
|
||||
out.push(AgentSkill {
|
||||
name,
|
||||
description: truncate(&description),
|
||||
path: dir.into(),
|
||||
source,
|
||||
valid: warnings.is_empty(),
|
||||
warnings,
|
||||
});
|
||||
}
|
||||
out.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
out
|
||||
}
|
||||
|
||||
fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSource) -> AgentSkill {
|
||||
let meta = Frontmatter::parse(text);
|
||||
let name = meta
|
||||
.get("name")
|
||||
.map(|n| strip_ansi(n).trim().to_owned())
|
||||
.filter(|n| !n.is_empty())
|
||||
.unwrap_or_else(|| folder.to_owned());
|
||||
let mut warnings = Vec::new();
|
||||
if !valid_name(&name) {
|
||||
warnings.push(format!("`name: {name}` is not 1-64 lowercase letters, digits or hyphens"));
|
||||
}
|
||||
if name != folder {
|
||||
warnings.push(format!("`name: {name}` does not match the folder `{folder}`"));
|
||||
}
|
||||
let description = meta.get("description").unwrap_or_default();
|
||||
let description = strip_ansi(description).trim().to_owned();
|
||||
if description.is_empty() {
|
||||
warnings.push("no `description`: the model never sees when to use it".into());
|
||||
} else if description.chars().count() > MAX_SKILL_DESCRIPTION {
|
||||
warnings.push(format!("`description` is over {MAX_SKILL_DESCRIPTION} characters"));
|
||||
}
|
||||
let hint = meta.get("argument-hint").map(|h| strip_ansi(h).trim().to_owned()).filter(|h| !h.is_empty());
|
||||
let user_invocable = !meta.get("user-invocable").is_some_and(|v| v.eq_ignore_ascii_case("false"));
|
||||
let disable_model_invocation = meta.get("disable-model-invocation").is_some_and(|v| v.eq_ignore_ascii_case("true"));
|
||||
let context_fork = meta.get("context").is_some_and(|v| strip_ansi(v).trim().eq_ignore_ascii_case("fork"));
|
||||
let paths = parse_skill_paths(&meta);
|
||||
AgentSkill {
|
||||
name,
|
||||
description: truncate(&description),
|
||||
hint,
|
||||
path: dir.to_path_buf().into(),
|
||||
source,
|
||||
also_in: Vec::new(),
|
||||
user_invocable,
|
||||
disable_model_invocation,
|
||||
context_fork,
|
||||
paths,
|
||||
valid: warnings.is_empty(),
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_skill_paths(meta: &Frontmatter) -> Vec<String> {
|
||||
for key in ["paths", "globs"] {
|
||||
if let Some(items) = meta.list(key) {
|
||||
let cleaned: Vec<String> =
|
||||
items.iter().map(|s| strip_ansi(s).trim().to_owned()).filter(|s| !s.is_empty()).collect();
|
||||
if !cleaned.is_empty() {
|
||||
return cleaned;
|
||||
}
|
||||
}
|
||||
if let Some(raw) = meta.get(key) {
|
||||
let trimmed = strip_ansi(raw);
|
||||
let inner = trimmed.trim().strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(trimmed.trim());
|
||||
let cleaned: Vec<String> =
|
||||
inner.split(',').map(|p| unquote(p.trim()).trim().to_owned()).filter(|p| !p.is_empty()).collect();
|
||||
if !cleaned.is_empty() {
|
||||
return cleaned;
|
||||
}
|
||||
}
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// A skill's mode, as one policy layer of the settings has it.
|
||||
type Policies = BTreeMap<String, AgentSkillPolicy>;
|
||||
|
||||
fn lookup_mode(map: &BTreeMap<String, AgentSkillMode>, name: &str) -> Option<AgentSkillMode> {
|
||||
map.get(name).copied().or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| *v))
|
||||
}
|
||||
|
||||
fn lookup_policy<'a>(map: &'a Policies, name: &str) -> Option<&'a AgentSkillPolicy> {
|
||||
map.get(name).or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))
|
||||
}
|
||||
|
||||
/// Resolves every skill's mode: a session override, then the workspace's and the user's
|
||||
/// `[agents.skills.<name>]` policy, then the default `auto` — with an untrusted workspace
|
||||
/// able to turn skills off only: its own skills stay off (whatever the session chose), and
|
||||
/// its policies hold only when they turn a skill off.
|
||||
/// `[agents.skills.<name>]` policy, then the frontmatter default (`slashOnly` when
|
||||
/// `disable-model-invocation: true`, else `auto`) — with an untrusted workspace able to
|
||||
/// turn skills off only: its own skills stay off (whatever the session chose), and its
|
||||
/// policies hold only when they turn a skill off.
|
||||
pub fn resolve(
|
||||
skills: Vec<AgentSkill>,
|
||||
session: Option<&BTreeMap<String, AgentSkillMode>>,
|
||||
@@ -337,19 +601,21 @@ pub fn resolve(
|
||||
| AgentSkillSource::CodexWorkspace
|
||||
| AgentSkillSource::CursorWorkspace
|
||||
);
|
||||
let default_mode =
|
||||
if skill.disable_model_invocation { AgentSkillMode::SlashOnly } else { AgentSkillMode::Auto };
|
||||
let (mode, origin) = if workspace_skill && !workspace_trusted {
|
||||
// Workspace trust gates the workspace's own skills, whatever else says.
|
||||
(AgentSkillMode::Off, AgentSkillOrigin::Trust)
|
||||
} else if let Some(chosen) = session.and_then(|s| s.get(&skill.name)) {
|
||||
(*chosen, AgentSkillOrigin::Session)
|
||||
} else if let Some(chosen) = session.and_then(|s| lookup_mode(s, &skill.name)) {
|
||||
(chosen, AgentSkillOrigin::Session)
|
||||
} else if let Some(policy) =
|
||||
workspace.get(&skill.name).filter(|p| workspace_trusted || p.mode == AgentSkillMode::Off)
|
||||
lookup_policy(workspace, &skill.name).filter(|p| workspace_trusted || p.mode == AgentSkillMode::Off)
|
||||
{
|
||||
(policy.mode, AgentSkillOrigin::Workspace)
|
||||
} else if let Some(policy) = user.get(&skill.name) {
|
||||
} else if let Some(policy) = lookup_policy(user, &skill.name) {
|
||||
(policy.mode, AgentSkillOrigin::User)
|
||||
} else {
|
||||
(AgentSkillMode::Auto, AgentSkillOrigin::None)
|
||||
(default_mode, AgentSkillOrigin::None)
|
||||
};
|
||||
out.push(AgentSkillState { skill, mode, origin });
|
||||
}
|
||||
@@ -416,16 +682,24 @@ pub fn stage(
|
||||
for state in states {
|
||||
let name = state.skill.name.as_str();
|
||||
let path = state.skill.path.0.as_path();
|
||||
if file_name(path).as_deref() == Some("skills") && !state.skill.valid {
|
||||
continue;
|
||||
}
|
||||
match state.mode {
|
||||
AgentSkillMode::Off => {
|
||||
out.codex_off.push((name.to_owned(), state.skill.path.to_string_lossy().into_owned()));
|
||||
out.codex_off.push((name.to_owned(), codex_skill_md_path(path)));
|
||||
}
|
||||
// Claude Code runs a slash-only skill on `/name`, so it has to see the folder;
|
||||
// Copilot and Codex have no such mode and get it disabled or left out.
|
||||
// Copilot and Codex have no slash-only toggle and disable model auto-loading.
|
||||
AgentSkillMode::SlashOnly => {
|
||||
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
|
||||
if state.skill.user_invocable
|
||||
&& let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home))
|
||||
{
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if native_codex(&state.skill, &cwd, home) {
|
||||
out.codex_off.push((name.to_owned(), codex_skill_md_path(path)));
|
||||
}
|
||||
}
|
||||
AgentSkillMode::Auto => {
|
||||
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
|
||||
@@ -451,10 +725,16 @@ pub fn stage(
|
||||
}
|
||||
// Claude Code's `skillOverrides` and Copilot's `disabledSkills` take the names of the
|
||||
// off and slash-only skills — the native copies included.
|
||||
let off: Vec<&str> =
|
||||
states.iter().filter(|s| s.mode == AgentSkillMode::Off).map(|s| s.skill.name.as_str()).collect();
|
||||
let slash: Vec<&str> =
|
||||
states.iter().filter(|s| s.mode == AgentSkillMode::SlashOnly).map(|s| s.skill.name.as_str()).collect();
|
||||
let off: Vec<&str> = states
|
||||
.iter()
|
||||
.filter(|s| s.mode == AgentSkillMode::Off || (s.mode == AgentSkillMode::SlashOnly && !s.skill.user_invocable))
|
||||
.map(|s| s.skill.name.as_str())
|
||||
.collect();
|
||||
let slash: Vec<&str> = states
|
||||
.iter()
|
||||
.filter(|s| s.mode == AgentSkillMode::SlashOnly && s.skill.user_invocable)
|
||||
.map(|s| s.skill.name.as_str())
|
||||
.collect();
|
||||
if !off.is_empty() || !slash.is_empty() {
|
||||
let mut overrides = serde_json::Map::new();
|
||||
for (name, mode) in off.iter().map(|n| (*n, "off")).chain(slash.iter().map(|n| (*n, "user-invocable-only"))) {
|
||||
@@ -469,32 +749,94 @@ pub fn stage(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Claude Code sees this skill without the farm: its own `.claude/skills` of the working
|
||||
/// directory (a worktree lacks the untracked originals) or the home.
|
||||
/// Codex `[[skills.config]]` matches `path` against the canonical `SKILL.md` document path.
|
||||
fn codex_skill_md_path(skill_dir: &Path) -> String {
|
||||
let md = skill_dir.join("SKILL.md");
|
||||
let md = dunce::canonicalize(&md)
|
||||
.or_else(|_| dunce::canonicalize(skill_dir).map(|dir| dir.join("SKILL.md")))
|
||||
.unwrap_or(md);
|
||||
// Skill roots are joined as `.agents/skills`; rebuilding from components gives Windows
|
||||
// one separator when the path could not be canonicalized.
|
||||
md.components().collect::<PathBuf>().to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn direct_link_matches(root: &Path, name: &str, target: &Path) -> bool {
|
||||
let candidate = root.join(name);
|
||||
candidate == target || dunce::canonicalize(&candidate).ok().as_deref() == Some(target)
|
||||
}
|
||||
|
||||
/// Claude Code sees this skill without the farm when `<dir>/.claude/skills/<name>` in `cwd`
|
||||
/// (or `~/.claude/skills/<name>`) already resolves to `skill.path` — including when `.claude/skills/<name>`
|
||||
/// is a symlink to `.agents/skills/<name>`. Category-nested skills are not direct children, so
|
||||
/// they still get staged flat into the farm.
|
||||
fn native_claude(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
let target = skill.path.0.as_path();
|
||||
let home_canon = home.map(|h| dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf()));
|
||||
for ancestor in cwd.ancestors() {
|
||||
if home_canon.as_deref().is_some_and(|h| h == ancestor) {
|
||||
break;
|
||||
}
|
||||
if direct_link_matches(&ancestor.join(".claude/skills"), &skill.name, target) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if let Some(h) = home_canon.as_deref()
|
||||
&& direct_link_matches(&h.join(".claude/skills"), &skill.name, target)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
match skill.source {
|
||||
AgentSkillSource::ClaudeWorkspace => is_under(skill.path.0.as_path(), cwd),
|
||||
AgentSkillSource::ClaudeUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".claude"))),
|
||||
AgentSkillSource::ClaudeWorkspace => target.parent() == Some(cwd.join(".claude/skills").as_path()),
|
||||
AgentSkillSource::ClaudeUser => {
|
||||
home_canon.as_deref().is_some_and(|h| target.parent() == Some(h.join(".claude/skills").as_path()))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Copilot reads the repository's `.github/skills` and the home's `.copilot` itself.
|
||||
/// 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 {
|
||||
match skill.source {
|
||||
AgentSkillSource::GithubWorkspace => is_under(skill.path.0.as_path(), cwd),
|
||||
AgentSkillSource::CopilotUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".copilot"))),
|
||||
_ => false,
|
||||
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 reads its own folders itself.
|
||||
/// Codex natively scans `.codex/skills` and `.agents/skills` in `cwd` and `home`.
|
||||
fn native_codex(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
match skill.source {
|
||||
AgentSkillSource::CodexWorkspace => is_under(skill.path.0.as_path(), cwd),
|
||||
AgentSkillSource::CodexUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".codex"))),
|
||||
_ => false,
|
||||
let target = skill.path.0.as_path();
|
||||
for rel in [".codex/skills", ".agents/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(".codex/skills"))
|
||||
|| is_under(target, &h.join(".agents/skills"))
|
||||
|| direct_link_matches(&h.join(".codex/skills"), &skill.name, target)
|
||||
|| direct_link_matches(&h.join(".agents/skills"), &skill.name, target)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn is_under(path: &Path, root: &Path) -> bool {
|
||||
@@ -553,21 +895,48 @@ fn sanitized(id: &str) -> String {
|
||||
id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect()
|
||||
}
|
||||
|
||||
/// The `/` menu's skills: the active ones as commands (the agent's own listing wins on a
|
||||
/// name clash). `Off` ones drop out everywhere; an ACP agent gets no other enforcement, so
|
||||
/// `slashOnly` ones stay listed — there is nothing to hold them back with.
|
||||
fn bare_skill_name(name: &str) -> String {
|
||||
name.trim_start_matches('$').to_ascii_lowercase()
|
||||
}
|
||||
|
||||
/// The `/` menu's skills: active user-invocable skills as commands (the agent's own listing
|
||||
/// wins on a name clash, including Codex's `$name` spelling). `Off` and `user-invocable: false`
|
||||
/// skills are actively stripped from `offered` too, so previously cached or CLI-advertised
|
||||
/// entries cannot leak back into OpenIDEA's `/` completion.
|
||||
pub fn menu_commands(offered: Vec<AgentCommand>, states: &[AgentSkillState]) -> Vec<AgentCommand> {
|
||||
let extra = states
|
||||
let blocked: HashSet<String> = states
|
||||
.iter()
|
||||
.filter(|s| s.mode != AgentSkillMode::Off)
|
||||
.map(|s| AgentCommand {
|
||||
name: s.skill.name.clone(),
|
||||
description: s.skill.description.clone(),
|
||||
hint: None,
|
||||
source: AgentCommandSource::Skill,
|
||||
})
|
||||
.filter(|s| s.mode == AgentSkillMode::Off || !s.skill.user_invocable)
|
||||
.map(|s| bare_skill_name(&s.skill.name))
|
||||
.collect();
|
||||
merge(offered, extra)
|
||||
let mut out: Vec<AgentCommand> =
|
||||
offered.into_iter().filter(|c| !blocked.contains(&bare_skill_name(&c.name))).collect();
|
||||
for state in states {
|
||||
if state.mode == AgentSkillMode::Off
|
||||
|| !state.skill.user_invocable
|
||||
|| (file_name(&state.skill.path.0).as_deref() == Some("skills") && !state.skill.valid)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let target = bare_skill_name(&state.skill.name);
|
||||
if let Some(existing) = out.iter_mut().find(|c| bare_skill_name(&c.name) == target) {
|
||||
existing.source = AgentCommandSource::Skill;
|
||||
if existing.hint.is_none() {
|
||||
existing.hint = state.skill.hint.clone();
|
||||
}
|
||||
if existing.description.is_empty() {
|
||||
existing.description = state.skill.description.clone();
|
||||
}
|
||||
} else {
|
||||
out.push(AgentCommand {
|
||||
name: state.skill.name.clone(),
|
||||
description: state.skill.description.clone(),
|
||||
hint: state.skill.hint.clone(),
|
||||
source: AgentCommandSource::Skill,
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -708,8 +1077,14 @@ mod tests {
|
||||
AgentSkill {
|
||||
name: name.into(),
|
||||
description: format!("{name} does things"),
|
||||
hint: None,
|
||||
path: root.join(name).into(),
|
||||
source,
|
||||
also_in: Vec::new(),
|
||||
user_invocable: true,
|
||||
disable_model_invocation: false,
|
||||
context_fork: false,
|
||||
paths: Vec::new(),
|
||||
valid: true,
|
||||
warnings: Vec::new(),
|
||||
}
|
||||
@@ -857,7 +1232,16 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
|
||||
// Local (non-worktree) session: the project's GitHub skills are Copilot's own.
|
||||
//For a local session, `.github/skills`, `.agents/skills` and `~/.agents/skills` are
|
||||
// already scanned natively by Copilot; `.openidea/skills` and `~/.codex/skills` are staged.
|
||||
let mut states = states;
|
||||
std::fs::create_dir_all(repo.join(".openidea/skills/ideonly")).unwrap();
|
||||
states.push(AgentSkillState {
|
||||
skill: skill("ideonly", AgentSkillSource::Workspace, &repo.join(".openidea/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();
|
||||
assert_eq!(delivery.claude_add_dir.as_deref(), Some(farm.as_path()));
|
||||
@@ -865,7 +1249,7 @@ mod tests {
|
||||
let staged = listed(&claude_tree);
|
||||
assert_eq!(
|
||||
staged,
|
||||
["codexy", "gh", "lint", "muted", "tdd"],
|
||||
["codexy", "gh", "ideonly", "lint", "muted", "tdd"],
|
||||
"everything but the off one: none is native to Claude here, and slash-only needs the folder"
|
||||
);
|
||||
|
||||
@@ -873,18 +1257,31 @@ mod tests {
|
||||
assert_eq!(delivery.copilot_skill_directories, [farm.join("copilot").to_string_lossy().into_owned()]);
|
||||
assert_eq!(delivery.copilot_disabled_skills, ["muted", "off"]);
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert_eq!(copilot_staged, ["codexy", "lint", "tdd"], "`gh` is native to a local Copilot session");
|
||||
assert_eq!(
|
||||
copilot_staged,
|
||||
["codexy", "ideonly"],
|
||||
"`gh` (.github), `tdd` (.agents) and `lint` (~/.agents) are native to Copilot; `.openidea` & `~/.codex` are staged"
|
||||
);
|
||||
assert_eq!(
|
||||
delivery.codex_off,
|
||||
[("off".to_owned(), repo.join(".agents/skills").join("off").to_string_lossy().into_owned())]
|
||||
[
|
||||
(
|
||||
"muted".to_owned(),
|
||||
home.join(".agents").join("skills").join("muted").join("SKILL.md").to_string_lossy().into_owned(),
|
||||
),
|
||||
(
|
||||
"off".to_owned(),
|
||||
repo.join(".agents").join("skills").join("off").join("SKILL.md").to_string_lossy().into_owned(),
|
||||
),
|
||||
]
|
||||
);
|
||||
|
||||
// A worktree task: the repo's skills are untracked, so nothing is native any more.
|
||||
// A worktree task: the repo's skills are untracked, so workspace skills are staged now.
|
||||
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()));
|
||||
assert!(copilot_staged.contains(&"gh".to_string()) && copilot_staged.contains(&"tdd".to_string()));
|
||||
|
||||
// Slash-only reaches Claude as `user-invocable-only`, off as `off`.
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
@@ -902,7 +1299,7 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
stage(&farm, "claude", &restated, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(listed(&claude_tree), ["codexy", "gh", "muted", "tdd"]);
|
||||
assert_eq!(listed(&claude_tree), ["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");
|
||||
|
||||
@@ -918,16 +1315,211 @@ mod tests {
|
||||
#[test]
|
||||
fn hub_menu_filters_off_and_keeps_the_agents_own() {
|
||||
let root = PathBuf::from("/r");
|
||||
let mut hidden = skill("bg-only", AgentSkillSource::Workspace, &root);
|
||||
hidden.user_invocable = false;
|
||||
let mut with_hint = skill("verify", AgentSkillSource::Workspace, &root);
|
||||
with_hint.hint = Some("[flow]".into());
|
||||
with_hint.path = tempfile::tempdir().unwrap().path().to_path_buf().into();
|
||||
write(&with_hint.path.0.join("SKILL.md"), "---\nname: verify\ndescription: v\n---\n");
|
||||
let states = resolve(
|
||||
vec![skill("tdd", AgentSkillSource::Workspace, &root), skill("lint", AgentSkillSource::User, &root)],
|
||||
vec![
|
||||
skill("tdd", AgentSkillSource::Workspace, &root),
|
||||
skill("lint", AgentSkillSource::User, &root),
|
||||
hidden,
|
||||
with_hint,
|
||||
],
|
||||
Some(&BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)])),
|
||||
&BTreeMap::new(),
|
||||
&BTreeMap::new(),
|
||||
true,
|
||||
);
|
||||
let menu = menu_commands(vec![cmd("tdd", "from the agent itself")], &states);
|
||||
assert_eq!(names(&menu), ["tdd"]);
|
||||
assert_eq!(menu[0].description, "from the agent itself");
|
||||
// Even when the agent itself (or cached `known_commands` / Codex `$lint`) already offered
|
||||
// `lint` or `bg-only`, `menu_commands` strips them, and merges `$tdd` without duplicating `tdd`.
|
||||
let offered = vec![
|
||||
cmd("$tdd", "from codex itself"),
|
||||
AgentCommand { source: AgentCommandSource::Skill, ..cmd("lint", "offered before turning off") },
|
||||
cmd("$lint", "codex offered before turning off"),
|
||||
AgentCommand { source: AgentCommandSource::Skill, ..cmd("bg-only", "model only") },
|
||||
cmd("compact", "Compact context"),
|
||||
];
|
||||
let menu = menu_commands(offered, &states);
|
||||
assert_eq!(names(&menu), ["$tdd", "compact", "verify"]);
|
||||
assert_eq!(menu[0].description, "from codex itself");
|
||||
assert_eq!(menu[0].source, AgentCommandSource::Skill);
|
||||
assert_eq!(menu[2].hint.as_deref(), Some("[flow]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hub_discovers_copilot_two_level_plugins_categories_monorepos_and_frontmatter_flags() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let home = root.join("home");
|
||||
let ws_a = root.join("ws-a");
|
||||
let ws_b = root.join("ws-b");
|
||||
// Category subfolder in `.agents/skills/testing/coverage/SKILL.md`.
|
||||
write(
|
||||
&ws_a.join(".agents/skills/testing/coverage/SKILL.md"),
|
||||
"---\nname: coverage\ndescription: Coverage workflow\nargument-hint: \"[pkg]\"\ndisable-model-invocation: true\n---\n",
|
||||
);
|
||||
// Nested monorepo subpackage `apps/web/.agents/skills/web-e2e/SKILL.md`.
|
||||
write(
|
||||
&ws_a.join("apps/web/.agents/skills/web-e2e/SKILL.md"),
|
||||
"---\nname: web-e2e\ndescription: Web e2e\n---\n",
|
||||
);
|
||||
// Second workspace member root `ws-b`.
|
||||
write(&ws_b.join(".agents/skills/deploy/SKILL.md"), "---\nname: deploy\ndescription: Deploy\n---\n");
|
||||
// Misplaced top-level `SKILL.md` directly inside `.claude/skills/SKILL.md`.
|
||||
write(&ws_a.join(".claude/skills/SKILL.md"), "---\nname: misplaced\ndescription: Wrong level\n---\n");
|
||||
// Copilot 2-level marketplace & `_direct` plugins + disabled plugin in `config.json`.
|
||||
write(
|
||||
&home.join(".copilot/installed-plugins/awesome-copilot/db-tools/skills/pg-tune/SKILL.md"),
|
||||
"---\nname: pg-tune\ndescription: Tune Postgres\n---\n",
|
||||
);
|
||||
write(
|
||||
&home.join(".copilot/installed-plugins/_direct/muted-plug/skills/secret-op/SKILL.md"),
|
||||
"---\nname: secret-op\ndescription: Disabled plugin skill\n---\n",
|
||||
);
|
||||
write(
|
||||
&home.join(".copilot/config.json"),
|
||||
"// Managed by Copilot CLI\n{\"installedPlugins\":[{\"name\":\"muted-plug\",\"enabled\":false,\"cache_path\":\"installed-plugins/_direct/muted-plug\"}]}\n",
|
||||
);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::fs::create_dir_all(ws_a.join(".claude/skills")).unwrap();
|
||||
std::os::unix::fs::symlink(
|
||||
ws_a.join(".agents/skills/testing/coverage"),
|
||||
ws_a.join(".claude/skills/coverage"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let found = discover_skills_in(&[ws_a.clone(), ws_b], Some(&home));
|
||||
let by = |n: &str| found.iter().find(|s| s.name == n);
|
||||
let cov = by("coverage").expect("category skill discovered");
|
||||
assert_eq!(cov.hint.as_deref(), Some("[pkg]"));
|
||||
assert!(cov.disable_model_invocation);
|
||||
#[cfg(unix)]
|
||||
assert_eq!(cov.also_in, [AgentSkillSource::ClaudeWorkspace]);
|
||||
assert!(by("web-e2e").is_some(), "nested monorepo subpackage skill discovered");
|
||||
assert!(by("deploy").is_some(), "second workspace member skill discovered");
|
||||
assert!(by("pg-tune").is_some(), "2-level Copilot marketplace plugin skill discovered");
|
||||
assert!(by("secret-op").is_none(), "disabled Copilot plugin skipped");
|
||||
let misplaced = by("misplaced").expect("misplaced top-level SKILL.md surfaced");
|
||||
assert!(!misplaced.valid && misplaced.warnings[0].contains("subfolder"));
|
||||
|
||||
// `disable-model-invocation: true` resolves to `SlashOnly` by default, and because
|
||||
// `.claude/skills/coverage` symlinks to it in `ws_a`, Claude does not stage a duplicate.
|
||||
let states = resolve(found, None, &BTreeMap::new(), &BTreeMap::new(), true);
|
||||
let cov_state = states.iter().find(|s| s.skill.name == "coverage").unwrap();
|
||||
assert_eq!(cov_state.mode, AgentSkillMode::SlashOnly);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let farm = farm_dir(&root.join("store"), "task-symlink");
|
||||
let _ = stage(&farm, "claude", &states, &ws_a, Some(&home)).unwrap();
|
||||
let claude_staged = listed(&farm.join(".claude/skills"));
|
||||
assert!(
|
||||
!claude_staged.contains(&"coverage".to_string()),
|
||||
"symlinked `.claude/skills/coverage` not duplicated"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_skills_yield_to_workspace_and_user_and_stage_to_all_clis() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let ws = root.join("ws");
|
||||
let home = root.join("home");
|
||||
let plugin_pkg = root.join("plugins/acme.tools/1.0.0");
|
||||
|
||||
write(&ws.join(".agents/skills/clash-ws/SKILL.md"), "---\nname: clash-ws\ndescription: workspace copy\n---\n");
|
||||
write(&home.join(".agents/skills/clash-user/SKILL.md"), "---\nname: clash-user\ndescription: user copy\n---\n");
|
||||
write(&plugin_pkg.join("skills/clash-ws/SKILL.md"), "---\nname: clash-ws\ndescription: plugin copy\n---\n");
|
||||
write(&plugin_pkg.join("skills/clash-user/SKILL.md"), "---\nname: clash-user\ndescription: plugin copy\n---\n");
|
||||
write(
|
||||
&plugin_pkg.join("skills/release-notes/SKILL.md"),
|
||||
"---\nname: release-notes\ndescription: draft release notes\n---\n",
|
||||
);
|
||||
|
||||
let plugin_dirs = vec![
|
||||
plugin_pkg.join("skills/clash-ws"),
|
||||
plugin_pkg.join("skills/clash-user"),
|
||||
plugin_pkg.join("skills/release-notes"),
|
||||
];
|
||||
let found = discover_skills_with_plugins(std::slice::from_ref(&ws), Some(&home), &plugin_dirs);
|
||||
let summary: Vec<(&str, AgentSkillSource, &str)> =
|
||||
found.iter().map(|s| (s.name.as_str(), s.source, s.description.as_str())).collect();
|
||||
assert_eq!(
|
||||
summary,
|
||||
[
|
||||
("clash-ws", AgentSkillSource::Workspace, "workspace copy"),
|
||||
("clash-user", AgentSkillSource::User, "user copy"),
|
||||
("release-notes", AgentSkillSource::Plugin, "draft release notes"),
|
||||
],
|
||||
"workspace and user skills win on name clash without renaming plugin skills"
|
||||
);
|
||||
assert!(!AgentSkillSource::Plugin.discovered());
|
||||
|
||||
let states = resolve(found.clone(), None, &BTreeMap::new(), &BTreeMap::new(), true);
|
||||
for provider in ["claude", "copilot", "codex"] {
|
||||
let farm = farm_dir(&root.join("store"), &format!("plugin-{provider}"));
|
||||
let _ = stage(&farm, provider, &states, &ws, Some(&home)).unwrap();
|
||||
}
|
||||
assert!(
|
||||
listed(&farm_dir(&root.join("store"), "plugin-claude").join(".claude/skills"))
|
||||
.contains(&"release-notes".into())
|
||||
);
|
||||
assert!(
|
||||
listed(&farm_dir(&root.join("store"), "plugin-copilot").join("copilot")).contains(&"release-notes".into())
|
||||
);
|
||||
assert!(listed(&farm_dir(&root.join("store"), "plugin-codex").join("codex")).contains(&"release-notes".into()));
|
||||
|
||||
// Turning a plugin skill off omits it from every CLI's staged farm.
|
||||
let off_states = resolve(
|
||||
found,
|
||||
None,
|
||||
&BTreeMap::new(),
|
||||
&BTreeMap::from([("release-notes".to_owned(), policy(AgentSkillMode::Off).unwrap())]),
|
||||
true,
|
||||
);
|
||||
let farm = farm_dir(&root.join("store"), "plugin-off");
|
||||
let _ = stage(&farm, "claude", &off_states, &ws, Some(&home)).unwrap();
|
||||
assert!(!farm.join(".claude/skills/release-notes").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_context_fork_and_paths_frontmatter_and_preserves_file_on_stage() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let ws = root.join("ws");
|
||||
let raw_md = "---\n\
|
||||
name: verify-ux\n\
|
||||
description: Verify UX layouts in an isolated subagent\n\
|
||||
context: fork\n\
|
||||
paths:\n\
|
||||
- \"src/**/*.tsx\"\n\
|
||||
- crates/ide-agent/**/*.rs\n\
|
||||
---\n\nRun visual checks.\n";
|
||||
write(&ws.join(".openidea/skills/verify-ux/SKILL.md"), raw_md);
|
||||
write(
|
||||
&ws.join(".agents/skills/inline-globs/SKILL.md"),
|
||||
"---\nname: inline-globs\ndescription: Scoped by globs\nglobs: [\"e2e/*.spec.ts\", \"src/ui/*.tsx\"]\n---\n",
|
||||
);
|
||||
|
||||
let found = discover_skills(&ws, None);
|
||||
let verify = found.iter().find(|s| s.name == "verify-ux").unwrap();
|
||||
assert!(verify.context_fork);
|
||||
assert_eq!(verify.paths, ["src/**/*.tsx", "crates/ide-agent/**/*.rs"]);
|
||||
|
||||
let inline = found.iter().find(|s| s.name == "inline-globs").unwrap();
|
||||
assert!(!inline.context_fork);
|
||||
assert_eq!(inline.paths, ["e2e/*.spec.ts", "src/ui/*.tsx"]);
|
||||
|
||||
// Staging passes `SKILL.md` through untouched so native CLIs execute `context: fork` / `paths`.
|
||||
let states = resolve(found, None, &BTreeMap::new(), &BTreeMap::new(), true);
|
||||
let farm = farm_dir(&root.join("store"), "fork-passthrough");
|
||||
let _ = stage(&farm, "copilot", &states, &ws, None).unwrap();
|
||||
let staged_md = std::fs::read_to_string(farm.join("copilot/verify-ux/SKILL.md")).unwrap();
|
||||
assert_eq!(staged_md, raw_md);
|
||||
}
|
||||
}
|
||||
+346
-254
@@ -452,6 +452,57 @@ fn manager(dir: &Path, agent: Arc<FakeAgent>) -> AgentManager {
|
||||
manager_at(dir, &dir.join("models.json"), agent)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn change_reads_share_a_budget_until_the_blocking_work_finishes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::default());
|
||||
let submitted = Arc::new(AtomicU32::new(0));
|
||||
mgr.set_git_executable_hook(Arc::new({
|
||||
let submitted = submitted.clone();
|
||||
move || {
|
||||
submitted.fetch_add(1, Ordering::SeqCst);
|
||||
None
|
||||
}
|
||||
}));
|
||||
let (started, mut starts) = tokio::sync::mpsc::unbounded_channel();
|
||||
let (finished, mut finishes) = tokio::sync::mpsc::unbounded_channel();
|
||||
let mut releases = Vec::new();
|
||||
let mut reads = Vec::new();
|
||||
for job in 0..12 {
|
||||
let (release, gate) = tokio::sync::oneshot::channel::<()>();
|
||||
releases.push(release);
|
||||
let (started, finished) = (started.clone(), finished.clone());
|
||||
let mut read = Box::pin(read_changes(&mgr.shared, move || {
|
||||
started.send(()).unwrap();
|
||||
gate.blocking_recv().unwrap();
|
||||
finished.send(()).unwrap();
|
||||
Ok(())
|
||||
}));
|
||||
tokio::select! { biased; _ = &mut read => panic!("read finished before release"), _ = std::future::ready(()) => {} }
|
||||
reads.push(read);
|
||||
if job == 0 {
|
||||
// Cancelling the requester cannot stop the blocking job or free its slot.
|
||||
starts.recv().await.unwrap();
|
||||
drop(reads.pop());
|
||||
}
|
||||
}
|
||||
let admitted = submitted.load(Ordering::SeqCst);
|
||||
for _ in 1..admitted {
|
||||
starts.recv().await.unwrap();
|
||||
}
|
||||
for release in releases {
|
||||
release.send(()).unwrap();
|
||||
}
|
||||
for read in reads {
|
||||
read.await.unwrap();
|
||||
}
|
||||
for _ in 0..12 {
|
||||
finishes.recv().await.unwrap();
|
||||
}
|
||||
eprintln!("change-read fixture: peak active {admitted}; completed 12/12");
|
||||
assert_eq!(admitted, 4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn subscribers_do_not_replace_or_close_each_other() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -986,7 +1037,7 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
wait_for(&mgr_a, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert_eq!(names(mgr_a.commands("claude", None).await.unwrap()), ["review", "triage"]);
|
||||
assert_eq!(names(mgr_a.commands("claude", Some(&task.id)).await.unwrap()), ["review", "triage"]);
|
||||
// Other agents get only what they offered, plus verified native builtins.
|
||||
// Other agents also receive the project's active skills from the skills hub, plus verified native builtins.
|
||||
assert_eq!(
|
||||
names(mgr_a.commands("codex", None).await.unwrap()),
|
||||
[
|
||||
@@ -1001,6 +1052,7 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
"goal",
|
||||
"rename",
|
||||
"logout",
|
||||
"triage",
|
||||
]
|
||||
);
|
||||
mgr_a.cancel(&task.id, None).unwrap();
|
||||
@@ -1010,7 +1062,6 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
// Another project shares the settings but not the commands.
|
||||
let mgr_b = manager_at(&b, &models, Arc::new(FakeAgent::default()));
|
||||
let claude = mgr_b.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
assert_eq!(claude.config.len(), 2);
|
||||
assert!(claude.commands.is_empty());
|
||||
assert!(mgr_b.commands("claude", None).await.unwrap().is_empty());
|
||||
let mgr_a = manager_at(&a, &models, Arc::new(FakeAgent::default()));
|
||||
@@ -1102,7 +1153,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
|
||||
let sink = events.clone();
|
||||
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
|
||||
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
|
||||
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
@@ -1197,7 +1248,6 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
}
|
||||
let providers = mgr.providers();
|
||||
let claude = providers.iter().find(|p| p.id == "claude").unwrap();
|
||||
assert_eq!(claude.config.iter().map(|o| o.id.as_str()).collect::<Vec<_>>(), ["model", "mode"]);
|
||||
assert_eq!(claude.commands.len(), 1);
|
||||
|
||||
// A new manager (IDE restart) finds the task and resumes its session without duplicating history.
|
||||
@@ -1206,7 +1256,6 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
|
||||
let mgr2 = manager(tmp.path(), agent2.clone());
|
||||
assert_eq!(mgr2.entries(&task.id, None).unwrap().len(), 5);
|
||||
assert_eq!(mgr2.task(&task.id).unwrap().state.lock().task.title, "Lexer fix");
|
||||
assert_eq!(mgr2.providers().iter().find(|p| p.id == "claude").unwrap().config.len(), 2);
|
||||
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
|
||||
@@ -1377,6 +1426,49 @@ async fn steers_through_session_steering() {
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn stale_queue_actions_refresh_the_queue_without_starting_another_turn() {
|
||||
use ide_core::error::ErrorKind;
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("ask"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let queued = handle.state.lock().task.queue[0].id.clone();
|
||||
let permission = *handle.permissions.lock().keys().next().unwrap();
|
||||
let (tx, mut updates) = tokio::sync::mpsc::unbounded_channel();
|
||||
let weak = Arc::downgrade(&handle);
|
||||
mgr.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |event| {
|
||||
if let AgentEvent::Task { task } = event
|
||||
&& task.queue.is_empty()
|
||||
&& let Some(handle) = weak.upgrade()
|
||||
{
|
||||
let _ = tx.send(handle.turns.load(Ordering::Acquire));
|
||||
}
|
||||
}),
|
||||
);
|
||||
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(updates.try_recv().unwrap(), 1, "publish the dequeue before starting the second turn");
|
||||
while updates.try_recv().is_ok() {}
|
||||
|
||||
for error in
|
||||
[mgr.unqueue(&task.id, &queued).unwrap_err(), mgr.send_queued_now(&task.id, &queued).await.unwrap_err()]
|
||||
{
|
||||
assert_eq!(error.kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(updates.try_recv().unwrap(), 2, "a stale action gets the current queue");
|
||||
}
|
||||
assert!(!handle.state.lock().busy);
|
||||
assert_eq!(mgr.unqueue("missing-task", &queued).unwrap_err().kind, ErrorKind::NotFound);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -1642,6 +1734,8 @@ fn prompts_become_acp_content_blocks() {
|
||||
assert_eq!(old["entries"][0]["attachments"], json!([]));
|
||||
assert!(old["entries"][1].get("attachments").is_none());
|
||||
assert_eq!(title_of(&AgentPrompt { files: p.files.clone(), ..AgentPrompt::default() }), "my file.rs");
|
||||
let pasted = AgentPrompt { text: "```text\n\n ## Fix the tab title\n```".into(), ..AgentPrompt::default() };
|
||||
assert_eq!(title_of(&pasted), "## Fix the tab title");
|
||||
assert!(clean(text(" ")).is_none());
|
||||
}
|
||||
|
||||
@@ -2167,52 +2261,6 @@ async fn usage_limits_and_late_settings() {
|
||||
assert!(agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
|
||||
let config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
|
||||
assert_eq!(config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("high"));
|
||||
for _ in 0..100 {
|
||||
if mgr
|
||||
.shared
|
||||
.known
|
||||
.lock()
|
||||
.get("claude")
|
||||
.and_then(|k| k.thought_levels.get("big"))
|
||||
.and_then(|levels| levels.first())
|
||||
.and_then(|o| o.current.as_deref())
|
||||
== Some("high")
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"][0].current.as_deref(), Some("high"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn remembered_settings_drop_per_model_choices_for_the_next_task() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
// The effort list depends on the model: what the last session ran means nothing once
|
||||
// the user picks another model, so provider-wide defaults never include it.
|
||||
*agent.extra_options.lock() = vec![json!({"id": "effort", "category": "thought_level",
|
||||
"type": "select", "currentValue": "high",
|
||||
"options": [{"value": "low", "name": "Low"}, {"value": "high", "name": "High"}]})];
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let provider = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
assert!(provider.config.iter().all(|o| o.id != "effort"), "a per-model option isn't offered stale");
|
||||
let model = provider.config.iter().find(|o| o.id == "model").unwrap();
|
||||
assert_eq!(model.current.as_deref(), Some("big"), "the model choice survives");
|
||||
}
|
||||
|
||||
fn effort_options(levels: &[&str], current: &str) -> Vec<Value> {
|
||||
@@ -2220,51 +2268,6 @@ fn effort_options(levels: &[&str], current: &str) -> Vec<Value> {
|
||||
"options": levels.iter().map(|v| json!({"value": v, "name": v})).collect::<Vec<_>>()})]
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn thinking_levels_are_remembered_per_provider_and_model() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.model_options.lock() = HashMap::from([
|
||||
("big".into(), effort_options(&["low", "high"], "high")),
|
||||
("small".into(), effort_options(&["minimal", "medium"], "minimal")),
|
||||
("plain".into(), vec![]),
|
||||
]);
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
|
||||
mgr.set_config(&task.id, "effort", "medium".into()).await.unwrap();
|
||||
mgr.set_config(&task.id, "model", "plain".into()).await.unwrap();
|
||||
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
let big = &p.thought_levels["big"][0];
|
||||
assert_eq!(big.current.as_deref(), Some("high"));
|
||||
assert_eq!(big.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["low", "high"]);
|
||||
let small = &p.thought_levels["small"][0];
|
||||
assert_eq!(small.current.as_deref(), Some("medium"));
|
||||
assert_eq!(small.values.iter().map(|v| v.value.as_str()).collect::<Vec<_>>(), ["minimal", "medium"]);
|
||||
assert!(p.thought_levels["plain"].is_empty());
|
||||
assert!(!p.thought_levels.contains_key("unknown"));
|
||||
assert!(mgr.providers().iter().find(|p| p.id == "codex").unwrap().thought_levels.is_empty());
|
||||
let saved: HashMap<String, Known> =
|
||||
serde_json::from_slice(&std::fs::read(&mgr.shared.paths.models_file).unwrap()).unwrap();
|
||||
assert_eq!(saved["claude"].thought_levels, p.thought_levels);
|
||||
mgr.shutdown();
|
||||
let restored = manager(tmp.path(), agent);
|
||||
assert_eq!(restored.providers().into_iter().find(|p| p.id == "claude").unwrap().thought_levels, p.thought_levels);
|
||||
restored.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
|
||||
// Idle selections use cached model controls or discover them before the next prompt.
|
||||
@@ -2303,12 +2306,9 @@ async fn changing_an_idle_tasks_settings_keeps_its_models_effort_levels() {
|
||||
}
|
||||
restored.set_config(&task.id, "model", "big".into()).await.unwrap();
|
||||
restored.set_config(&task.id, option, value.into()).await.unwrap();
|
||||
let p = restored.providers().into_iter().find(|p| p.id == "claude-acp").unwrap();
|
||||
let big = p.thought_levels.get("big").and_then(|levels| levels.first());
|
||||
assert_eq!(big.map(|o| o.values.len()), Some(2), "{option}: {:?}", p.thought_levels);
|
||||
let saved: HashMap<String, Known> =
|
||||
serde_json::from_slice(&std::fs::read(&restored.shared.paths.models_file).unwrap()).unwrap();
|
||||
assert_eq!(saved["claude-acp"].thought_levels, p.thought_levels, "{option}");
|
||||
let levels = restored.shared.paths.catalogs.cached(&restored.shared, "claude-acp").thought_levels;
|
||||
let big = levels.get("big").and_then(|levels| levels.first());
|
||||
assert_eq!(big.map(|o| o.values.len()), Some(2), "{option}: {levels:?}");
|
||||
restored.shutdown();
|
||||
}
|
||||
}
|
||||
@@ -2541,100 +2541,6 @@ async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn unreported_model_switch_does_not_cache_the_previous_models_levels() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
|
||||
let mgr = manager(tmp.path(), agent);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.set_config(&task.id, "model", "small".into()).await.unwrap();
|
||||
let p = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
assert!(!p.thought_levels.contains_key("small"));
|
||||
assert_eq!(p.thought_levels["big"][0].current.as_deref(), Some("high"));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cached_effort_is_not_sent_without_real_session_options() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "low");
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let new = |config| NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config,
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
};
|
||||
let warm = mgr.create(new(vec![])).await.unwrap();
|
||||
wait_for(&mgr, &warm.id, AgentStatus::Ready).await;
|
||||
agent.calls.lock().clear();
|
||||
agent.empty_config.store(true, Ordering::Release);
|
||||
let task = mgr
|
||||
.create(new(vec![
|
||||
AgentConfigChoice { id: "model".into(), value: "big".into() },
|
||||
AgentConfigChoice { id: "effort".into(), value: "high".into() },
|
||||
]))
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(!agent.calls.lock().iter().any(|c| c == "session/set_config_option \"high\""));
|
||||
assert!(
|
||||
mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "effort"),
|
||||
"remembered session settings remain visible until the agent refreshes them"
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn reported_levels_refresh_even_without_a_model_option() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.extra_options.lock() = effort_options(&["low", "high"], "high");
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: vec![],
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
for levels in [effort_options(&["minimal", "medium"], "medium"), vec![]] {
|
||||
agent.update("s1", json!({"sessionUpdate": "config_option_update", "configOptions": levels}));
|
||||
let expected = config::parse_options(&json!(levels));
|
||||
for _ in 0..100 {
|
||||
if mgr.shared.known.lock()["claude"].thought_levels["big"] == expected {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(mgr.shared.known.lock()["claude"].thought_levels["big"], expected);
|
||||
}
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_updates_become_a_countdown() {
|
||||
let update =
|
||||
@@ -3137,7 +3043,7 @@ async fn reload_providers_updates_registry_install_clears_stale_probes_and_notif
|
||||
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let events_sink = events.clone();
|
||||
mgr.subscribe(Arc::new(move |ev| events_sink.lock().push(ev)));
|
||||
mgr.subscribe_as("", Arc::new(move |ev| events_sink.lock().push(ev)));
|
||||
|
||||
let toml = format!(
|
||||
"name = \"GitHub Copilot\"\ncommand = {:?}\nargs = [\"--acp\", \"--stdio\"]\n",
|
||||
@@ -3192,49 +3098,6 @@ async fn a_failed_probe_is_retried_instead_of_remembered() {
|
||||
assert!(!mgr.shared.probes.lock().contains_key("claude"));
|
||||
}
|
||||
|
||||
/// A session report that changes the cached provider config notifies subscribers,
|
||||
/// so the composer re-lists models without waiting for the next task (#1490).
|
||||
/// Reports that change nothing stay silent.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn remembered_config_changes_notify_subscribers_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
|
||||
events.lock().clear();
|
||||
|
||||
let reported = config::options_of(&json!({ "configOptions": [
|
||||
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
|
||||
"options": [{ "value": "default" }, { "value": "custom-opus" }] },
|
||||
] }));
|
||||
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
|
||||
assert!(
|
||||
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
|
||||
"a first report changing the cache notifies subscribers"
|
||||
);
|
||||
events.lock().clear();
|
||||
|
||||
// The same report again: the cache is unchanged, so subscribers hear nothing.
|
||||
mgr.shared.remember("claude", Some(&reported), None, Some("default"));
|
||||
assert!(events.lock().is_empty(), "an unchanged report must stay silent");
|
||||
|
||||
// A changed model list notifies again, and providers() serves the new list.
|
||||
let updated = config::options_of(&json!({ "configOptions": [
|
||||
{ "id": "model", "category": "model", "type": "select", "currentValue": "default",
|
||||
"options": [{ "value": "default" }, { "value": "custom-opus" }, { "value": "custom-sonnet" }] },
|
||||
] }));
|
||||
mgr.shared.remember("claude", Some(&updated), None, Some("default"));
|
||||
assert!(
|
||||
events.lock().iter().any(|ev| matches!(ev, AgentEvent::Providers)),
|
||||
"a changed model list notifies subscribers"
|
||||
);
|
||||
let claude = mgr.providers().into_iter().find(|p| p.id == "claude").unwrap();
|
||||
let model = claude.config.iter().find(|o| o.category.as_deref() == Some("model")).unwrap();
|
||||
let values: Vec<_> = model.values.iter().map(|v| v.value.as_str()).collect();
|
||||
assert_eq!(values, ["default", "custom-opus", "custom-sonnet"]);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn idle_agents_stop_and_resume_their_session_on_the_next_message() {
|
||||
let new = || NewAgentTask {
|
||||
@@ -3599,14 +3462,17 @@ async fn config_choice_shows_before_the_agent_answers() {
|
||||
let mgr = manager(tempfile::tempdir().unwrap().path(), agent.clone());
|
||||
let shown: Arc<Mutex<Option<std::time::Instant>>> = Arc::default();
|
||||
let mark = shown.clone();
|
||||
mgr.subscribe(Arc::new(move |e| {
|
||||
if let AgentEvent::Task { task } = e
|
||||
&& task.config.iter().any(|o| o.id == "fast" && o.current.as_deref() == Some("false"))
|
||||
&& mark.lock().is_none()
|
||||
{
|
||||
*mark.lock() = Some(std::time::Instant::now());
|
||||
}
|
||||
}));
|
||||
mgr.subscribe_as(
|
||||
"",
|
||||
Arc::new(move |e| {
|
||||
if let AgentEvent::Task { task } = e
|
||||
&& task.config.iter().any(|o| o.id == "fast" && o.current.as_deref() == Some("false"))
|
||||
&& mark.lock().is_none()
|
||||
{
|
||||
*mark.lock() = Some(std::time::Instant::now());
|
||||
}
|
||||
}),
|
||||
);
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
@@ -3868,6 +3734,123 @@ async fn turn_changed(mgr: &AgentManager, id: &str) -> Vec<(String, ide_vcs::Cha
|
||||
changes.into_iter().map(|c| (c.rel_path, c.kind, c.added, c.removed)).collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_task_lists_what_it_changed_in_a_nested_repository() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
for repo in [root.clone(), root.join("libs/validation")] {
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
for args in [&["init", "-q", "-b", "main"][..], &["add", "a.txt"], &["commit", "-q", "-m", "init"]] {
|
||||
let ok = std::process::Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.current_dir(&repo)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success();
|
||||
assert!(ok, "{args:?}");
|
||||
}
|
||||
}
|
||||
let mgr = manager(&base.join("ide"), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: Some(IpcPath(root.clone())),
|
||||
prompt: text("Hello"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
one_turn(&mgr, &task.id, None, || {
|
||||
std::fs::write(root.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(root.join("libs/validation/b.txt"), "new\n").unwrap();
|
||||
})
|
||||
.await;
|
||||
let changed: Vec<(String, Option<IpcPath>)> =
|
||||
mgr.changes(&task.id).await.unwrap().into_iter().map(|c| (c.rel_path, c.repo)).collect();
|
||||
assert_eq!(
|
||||
changed,
|
||||
[
|
||||
("a.txt".to_owned(), Some(IpcPath(root.clone()))),
|
||||
("libs/validation/b.txt".to_owned(), Some(IpcPath(root.join("libs/validation")))),
|
||||
]
|
||||
);
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::SinceStart).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), "one\n");
|
||||
assert!(!root.join("libs/validation/b.txt").exists());
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_last_turn_of_a_task_spans_nested_repositories() {
|
||||
use ide_vcs::ChangeKind::{Added, Modified};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
let nested = root.join("libs/validation");
|
||||
let git = |repo: &Path, args: &[&str]| {
|
||||
let ok = std::process::Command::new("git")
|
||||
.args(["-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"])
|
||||
.args(args)
|
||||
.current_dir(repo)
|
||||
.status()
|
||||
.unwrap()
|
||||
.success();
|
||||
assert!(ok, "{args:?}");
|
||||
};
|
||||
for repo in [&root, &nested] {
|
||||
std::fs::create_dir_all(repo).unwrap();
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(repo, &["init", "-q", "-b", "main"]);
|
||||
git(repo, &["add", "a.txt"]);
|
||||
git(repo, &["commit", "-q", "-m", "init"]);
|
||||
}
|
||||
let mgr = manager(&base.join("ide"), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: Some(IpcPath(root.clone())),
|
||||
prompt: text("Hello"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
one_turn(&mgr, &task.id, None, || std::fs::write(root.join("a.txt"), "two\n").unwrap()).await;
|
||||
one_turn(&mgr, &task.id, Some("more"), || {
|
||||
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
|
||||
// Committed in the nested repository: still the turn's.
|
||||
std::fs::write(nested.join("c.txt"), "committed\n").unwrap();
|
||||
git(&nested, &["add", "c.txt"]);
|
||||
git(&nested, &["commit", "-q", "-m", "c"]);
|
||||
})
|
||||
.await;
|
||||
|
||||
// Only the second turn's files, from the nested repository, named from the project.
|
||||
assert_eq!(
|
||||
turn_changed(&mgr, &task.id).await,
|
||||
[
|
||||
("libs/validation/a.txt".into(), Modified, 1, 1),
|
||||
("libs/validation/b.txt".into(), Added, 1, 0),
|
||||
("libs/validation/c.txt".into(), Added, 1, 0),
|
||||
]
|
||||
);
|
||||
let repos: Vec<_> = mgr.turn_changes(&task.id).await.unwrap().into_iter().map(|c| c.repo).collect();
|
||||
assert_eq!(repos, [Some(IpcPath(nested.clone())), Some(IpcPath(nested.clone())), Some(IpcPath(nested.clone()))]);
|
||||
let then = mgr.base_text(&task.id, nested.join("a.txt"), AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(then.as_deref(), Some("one\n"));
|
||||
|
||||
mgr.rollback_changes(&task.id, None, AgentChangesView::LastTurn).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(nested.join("a.txt")).unwrap(), "one\n");
|
||||
assert!(!nested.join("b.txt").exists());
|
||||
assert_eq!(std::fs::read_to_string(root.join("a.txt")).unwrap(), "two\n", "the first turn's change stays");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn the_last_turn_lists_and_rolls_back_only_its_own_changes() {
|
||||
use ide_vcs::ChangeKind::{Added, Deleted, Modified};
|
||||
@@ -4333,7 +4316,7 @@ async fn attention_finished_not_cancelled() {
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
|
||||
let sink = events.clone();
|
||||
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
|
||||
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
|
||||
|
||||
let done = mgr
|
||||
.create(NewAgentTask {
|
||||
@@ -4387,7 +4370,7 @@ async fn attention_failed() {
|
||||
let mgr = manager(tmp.path(), agent);
|
||||
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
|
||||
let sink = events.clone();
|
||||
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
|
||||
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
@@ -4412,7 +4395,7 @@ async fn attention_input_not_auto_bypass() {
|
||||
let mgr = manager(tmp.path(), agent);
|
||||
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
|
||||
let sink = events.clone();
|
||||
mgr.subscribe(Arc::new(move |e| sink.lock().push(e)));
|
||||
mgr.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
|
||||
|
||||
let asked = mgr
|
||||
.create(NewAgentTask {
|
||||
@@ -4477,7 +4460,7 @@ async fn attention_not_emitted_on_restore() {
|
||||
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let events = Arc::new(Mutex::new(Vec::<AgentEvent>::new()));
|
||||
let sink = events.clone();
|
||||
let tasks = restored.subscribe(Arc::new(move |e| sink.lock().push(e)));
|
||||
let tasks = restored.subscribe_as("", Arc::new(move |e| sink.lock().push(e)));
|
||||
assert!(tasks.iter().any(|t| t.id == task.id));
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
assert!(attention_reasons(&events.lock()).is_empty(), "snapshot restore must not re-notify: {:?}", *events.lock());
|
||||
@@ -4560,6 +4543,82 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idle() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir_all(root.join(".agents/skills/tdd")).unwrap();
|
||||
std::fs::write(root.join(".agents/skills/tdd/SKILL.md"), "---\nname: tdd\ndescription: TDD\n---\n").unwrap();
|
||||
std::fs::create_dir_all(root.join(".claude/skills/noisy")).unwrap();
|
||||
std::fs::write(root.join(".claude/skills/noisy/SKILL.md"), "---\nname: noisy\ndescription: Noisy\n---\n").unwrap();
|
||||
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(root, agent.clone());
|
||||
mgr.set_skills_policy_hook(Box::new({
|
||||
let root = root.to_path_buf();
|
||||
move || SkillsPolicy {
|
||||
user: BTreeMap::from([("tdd".into(), AgentSkillPolicy { mode: AgentSkillMode::Off })]),
|
||||
workspace_roots: vec![root.clone()],
|
||||
..SkillsPolicy::default()
|
||||
}
|
||||
}));
|
||||
|
||||
// Start task with `tdd` (default off) enabled for this session and `noisy` turned off.
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::from([
|
||||
("tdd".into(), AgentSkillMode::Auto),
|
||||
("noisy".into(), AgentSkillMode::Off),
|
||||
]),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let cmd_names: Vec<String> =
|
||||
mgr.commands("claude", Some(&task.id)).await.unwrap().into_iter().map(|c| c.name).collect();
|
||||
assert!(cmd_names.contains(&"tdd".to_string()), "{cmd_names:?}");
|
||||
assert!(
|
||||
!cmd_names.contains(&"noisy".to_string()),
|
||||
"`noisy` offered on disk must be stripped when off: {cmd_names:?}"
|
||||
);
|
||||
|
||||
// Flip overrides while idle -> recycles resumable session so next turn calls `session/load`.
|
||||
let updated = mgr
|
||||
.set_skill_overrides(
|
||||
&task.id,
|
||||
BTreeMap::from([("tdd".into(), AgentSkillMode::Off), ("noisy".into(), AgentSkillMode::Auto)]),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(updated.skill_overrides.get("tdd"), Some(&AgentSkillMode::Off));
|
||||
assert_eq!(updated.skill_overrides.get("noisy"), Some(&AgentSkillMode::Auto));
|
||||
|
||||
let cmd_names_after: Vec<String> =
|
||||
mgr.commands("claude", Some(&task.id)).await.unwrap().into_iter().map(|c| c.name).collect();
|
||||
assert!(!cmd_names_after.contains(&"tdd".to_string()), "{cmd_names_after:?}");
|
||||
assert!(cmd_names_after.contains(&"noisy".to_string()), "{cmd_names_after:?}");
|
||||
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.mcp_calls.lock().last().map(|c| c.0.as_str()), Some("session/load"));
|
||||
mgr.shutdown();
|
||||
|
||||
// Persisted task file preserves `skill_overrides` across restart.
|
||||
let restored_mgr = manager(root, Arc::new(FakeAgent::default()));
|
||||
let restored = restored_mgr.subscribe_as("", Arc::new(|_| {})).into_iter().find(|t| t.id == task.id).unwrap();
|
||||
assert_eq!(restored.skill_overrides.get("tdd"), Some(&AgentSkillMode::Off));
|
||||
assert_eq!(restored.skill_overrides.get("noisy"), Some(&AgentSkillMode::Auto));
|
||||
restored_mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails() {
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -4766,10 +4825,43 @@ done
|
||||
#[test]
|
||||
fn session_params_name_the_servers_off() {
|
||||
let mcp = McpForSession { servers: vec![json!({ "name": "docs" })], off: vec!["github".into()] };
|
||||
let params = session_params("/p", &mcp, None);
|
||||
let params = session_params("/p", &mcp, None, &[]);
|
||||
assert_eq!(params["cwd"], "/p");
|
||||
assert_eq!(params["mcpServers"][0]["name"], "docs");
|
||||
assert_eq!(params["_meta"]["openidea"]["mcpServersOff"], json!(["github"]));
|
||||
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
|
||||
assert!(session_params("/p", &none, None).get("_meta").is_none());
|
||||
assert!(session_params("/p", &none, None, &[]).get("_meta").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_params_offer_the_workspace_roots() {
|
||||
let none = McpForSession { servers: Vec::new(), off: Vec::new() };
|
||||
let params = session_params("/w/api", &none, None, &["/w/web".to_owned()]);
|
||||
assert_eq!(params["additionalDirectories"], json!(["/w/web"]));
|
||||
assert!(session_params("/w/api", &none, None, &[]).get("additionalDirectories").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn workspace_roots_go_to_agents_that_take_them() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let [api, web, worktree] = ["api", "web", "worktree"].map(|d| tmp.path().join(d));
|
||||
for d in [&api, &web, &worktree] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let hook_roots = [api.clone(), web.clone(), web.clone()];
|
||||
mgr.set_workspace_roots_hook(Arc::new(move || hook_roots.to_vec()));
|
||||
let init = |capabilities: Value| acp::Negotiated {
|
||||
generation: 1,
|
||||
capabilities,
|
||||
agent_info: None,
|
||||
auth_methods: Vec::new(),
|
||||
meta: None,
|
||||
};
|
||||
let takes = init(json!({ "sessionCapabilities": { "additionalDirectories": {} } }));
|
||||
let web = dunce::canonicalize(&web).unwrap().to_string_lossy().into_owned();
|
||||
assert_eq!(mgr.shared.additional_directories(&takes, &api, None), vec![web.clone()]);
|
||||
// A task in a worktree of `api` isn't offered the project's own checkout.
|
||||
assert_eq!(mgr.shared.additional_directories(&takes, &worktree, Some(&api)), vec![web]);
|
||||
assert!(mgr.shared.additional_directories(&init(json!({})), &api, None).is_empty());
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Folds ACP `session/update` notifications into a task's entries.
|
||||
|
||||
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
@@ -84,6 +84,7 @@ impl Timeline {
|
||||
status: tool_status(update.get("status")).unwrap_or(AgentToolStatus::Pending),
|
||||
locations: locations(update.get("locations")),
|
||||
output: None,
|
||||
images: Vec::new(),
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
@@ -150,7 +151,7 @@ impl Timeline {
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, diffs, ended_ms, .. } =
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
@@ -173,10 +174,20 @@ impl Timeline {
|
||||
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") => {
|
||||
if let Some(t) = content_text(item.get("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');
|
||||
}
|
||||
@@ -203,6 +214,9 @@ impl Timeline {
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
if !new_images.is_empty() {
|
||||
*images = new_images;
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
|
||||
@@ -439,6 +453,31 @@ mod tests {
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
let mut t = Timeline::default();
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "preview", "title": "Render", "kind": "execute"}));
|
||||
let mut old = serde_json::to_value(&t.entries[0]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("images");
|
||||
let legacy: AgentEntry = serde_json::from_value(old).unwrap();
|
||||
assert!(matches!(legacy, AgentEntry::Tool { images, .. } if images.is_empty()));
|
||||
let data = base64::engine::general_purpose::STANDARD.encode(vec![0; MAX_OUTPUT]);
|
||||
let update = json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "content": [
|
||||
{"type": "content", "content": {"type": "text", "text": "x".repeat(MAX_OUTPUT + 100)}},
|
||||
{"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": data}}
|
||||
]});
|
||||
t.apply(&update);
|
||||
t.apply(&update);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
|
||||
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
|
||||
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
|
||||
assert_eq!(*status, AgentToolStatus::Completed);
|
||||
let saved = serde_json::to_string(&t.entries[0]).unwrap();
|
||||
assert_eq!(serde_json::from_str::<AgentEntry>(&saved).unwrap(), t.entries[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunks_merge_into_one_message_until_another_entry_comes() {
|
||||
let mut t = Timeline::default();
|
||||
|
||||
@@ -25,6 +25,116 @@ fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
Ok(repo)
|
||||
}
|
||||
|
||||
/// The repositories of a project with nested ones (an own `.git` under the project root, not a
|
||||
/// submodule), with the folder their files are named from: the root of the repository holding
|
||||
/// `cwd`, else `cwd`. `None` when only the repository holding `cwd` (if any) is there.
|
||||
fn nested_repos(cwd: &Path) -> IdeResult<Option<(PathBuf, Vec<Repo>)>> {
|
||||
let Ok(cwd) = dunce::canonicalize(cwd) else { return Ok(None) };
|
||||
let found = ide_vcs::Repos::discover(&cwd, &|_| false)?;
|
||||
if found.all().iter().all(|r| cwd.starts_with(r.root())) {
|
||||
return Ok(None);
|
||||
}
|
||||
let base = found.all().iter().map(|r| r.root()).filter(|r| cwd.starts_with(r)).max().unwrap_or(&cwd).to_path_buf();
|
||||
let mut repos = Vec::new();
|
||||
for r in found.all() {
|
||||
repos.extend(discover(r.root())?);
|
||||
}
|
||||
Ok(Some((base, repos)))
|
||||
}
|
||||
|
||||
/// Whether the project at `cwd` holds repositories nested in it: its changes are each one's.
|
||||
pub(crate) fn spans_repos(cwd: &Path) -> bool {
|
||||
nested_repos(cwd).is_ok_and(|r| r.is_some())
|
||||
}
|
||||
|
||||
/// The repositories a turn's files are in, and the folder those files are named from.
|
||||
struct TurnRepos {
|
||||
base: PathBuf,
|
||||
repos: Vec<Repo>,
|
||||
/// The project holds nested repositories: each one's `HEAD` is recorded on its own.
|
||||
nested: bool,
|
||||
}
|
||||
|
||||
impl TurnRepos {
|
||||
fn of(cwd: &Path) -> IdeResult<Option<Self>> {
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
return Ok(Some(Self { base, repos, nested: true }));
|
||||
}
|
||||
Ok(discover(cwd)?.map(|repo| Self { base: repo.root().to_path_buf(), repos: vec![repo], nested: false }))
|
||||
}
|
||||
|
||||
/// The innermost repository holding `path`.
|
||||
fn owner(&self, path: &Path) -> Option<&Repo> {
|
||||
owning_repo(&self.repos, path)
|
||||
}
|
||||
|
||||
/// `repo`'s `HEAD` as the turn `start` began.
|
||||
fn head_then<'a>(&self, start: &'a TurnStart, repo: &Repo) -> Option<&'a str> {
|
||||
if self.nested { start.heads.get(&root_key(repo.root())) } else { start.head.as_ref() }.map(String::as_str)
|
||||
}
|
||||
}
|
||||
|
||||
fn root_key(root: &Path) -> String {
|
||||
root.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn owning_repo<'a>(repos: &'a [Repo], path: &Path) -> Option<&'a Repo> {
|
||||
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().as_os_str().len())
|
||||
}
|
||||
|
||||
/// `path` as a task in `base` names it, if it is not in a repository nested below `repo` (that
|
||||
/// one lists it itself; to `repo` its folder is untracked).
|
||||
fn nested_rel(base: &Path, repo: &Repo, roots: &[PathBuf], path: &Path) -> Option<String> {
|
||||
let rel = path.strip_prefix(base).ok()?;
|
||||
if path.is_dir()
|
||||
|| roots.iter().any(|n| n.as_path() != repo.root() && n.starts_with(repo.root()) && path.starts_with(n))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(rel.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
|
||||
/// The uncommitted changes in every repository of the project, against each one's `HEAD`.
|
||||
fn nested_changes(base: &Path, repos: &[Repo], touched: Option<&BTreeSet<String>>) -> IdeResult<Vec<AgentChange>> {
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
// Match deletions too: find the owner by path components, not by opening the file.
|
||||
// Display paths use slash separators and lossy Unicode (see nested_rel). If a checkout's
|
||||
// name cannot round-trip from that representation, keep the full-read fallback.
|
||||
let owners = touched
|
||||
.filter(|_| {
|
||||
roots.iter().all(|root| {
|
||||
root.strip_prefix(base).is_ok_and(|rel| base.join(rel.to_string_lossy().replace('\\', "/")) == *root)
|
||||
})
|
||||
})
|
||||
.map(|paths| {
|
||||
paths.iter().filter_map(|rel| owning_repo(repos, &base.join(rel)).map(Repo::root)).collect::<BTreeSet<_>>()
|
||||
});
|
||||
let mut out: Vec<AgentChange> = Vec::new();
|
||||
for repo in repos {
|
||||
if owners.as_ref().is_some_and(|owners| !owners.contains(repo.root())) {
|
||||
continue;
|
||||
}
|
||||
let listed = match repo.head()?.1 {
|
||||
Some(head) => changes(repo.root(), &head)?,
|
||||
None => {
|
||||
repo.status()?.into_iter().filter(|s| s.path.is_file()).map(|s| added(s.path, s.rel_path)).collect()
|
||||
}
|
||||
};
|
||||
for mut c in listed {
|
||||
let Some(rel) = nested_rel(base, repo, &roots, &c.path.0) else { continue };
|
||||
if out.iter().any(|o| o.path == c.path) {
|
||||
continue;
|
||||
}
|
||||
c.rel_path = rel;
|
||||
c.old_path = None;
|
||||
c.repo = Some(IpcPath(repo.root().to_path_buf()));
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn repo_at(path: &Path) -> IdeResult<Repo> {
|
||||
discover(path)?.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", path.display())))
|
||||
}
|
||||
@@ -38,6 +148,9 @@ pub(crate) fn head_of(path: &Path) -> IdeResult<(String, String)> {
|
||||
|
||||
/// `HEAD`'s commit in `cwd`, `None` outside a repository or before its first commit.
|
||||
pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
|
||||
if spans_repos(cwd) {
|
||||
return Ok(Some("HEAD".to_owned()));
|
||||
}
|
||||
match discover(cwd)? {
|
||||
Some(repo) => Ok(repo.head()?.1),
|
||||
None => Ok(None),
|
||||
@@ -127,6 +240,7 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -143,6 +257,9 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
/// Files renamed since `rev`, by their new repository-relative path: the old path, as a deletion
|
||||
/// to roll back along with the rename.
|
||||
pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String, AgentChange>> {
|
||||
if spans_repos(cwd) {
|
||||
return Ok(BTreeMap::new());
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
let root = repo.root().to_path_buf();
|
||||
Ok(repo
|
||||
@@ -157,6 +274,7 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
|
||||
added: 0,
|
||||
removed: 0,
|
||||
old_path: None,
|
||||
repo: None,
|
||||
};
|
||||
Some((f.path, source))
|
||||
})
|
||||
@@ -165,7 +283,7 @@ pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String
|
||||
|
||||
fn added(path: IpcPath, rel_path: String) -> AgentChange {
|
||||
let added = std::fs::read_to_string(&*path).map_or(0, |t| t.lines().count() as u32);
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None }
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0, old_path: None, repo: None }
|
||||
}
|
||||
|
||||
/// The commits from `base` (exclusive) to `head` (inclusive) in `cwd`, newest first, each
|
||||
@@ -201,6 +319,7 @@ pub(crate) fn commits(cwd: &Path, base: &str, head: &str) -> IdeResult<Vec<Agent
|
||||
added,
|
||||
removed,
|
||||
old_path: f.old_path,
|
||||
repo: None,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
@@ -263,10 +382,30 @@ impl TaskBase {
|
||||
}
|
||||
|
||||
/// The files the task changed, less those changed before it started and untouched since.
|
||||
pub(crate) fn changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<Vec<AgentChange>> {
|
||||
pub(crate) fn changes(
|
||||
&self,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
if touched.is_some_and(BTreeSet::is_empty) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(made_by_task(self.read_changes(before, touched)?, touched))
|
||||
}
|
||||
|
||||
fn read_changes(
|
||||
&self,
|
||||
before: &BTreeMap<String, Stamp>,
|
||||
touched: Option<&BTreeSet<String>>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { cwd, base } => return Ok(without_untouched(changes(cwd, base)?, before)),
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
Self::Local { cwd, start } => {
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
return Ok(without_untouched(nested_changes(&base, &repos, touched)?, before));
|
||||
}
|
||||
(cwd, start.as_deref())
|
||||
}
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
// What is uncommitted, as the Commit tool window lists it: commits made since the task
|
||||
@@ -324,6 +463,9 @@ impl TaskBase {
|
||||
/// reads cannot put a file in both lists.
|
||||
pub(crate) fn grouped_changes(&self, before: &BTreeMap<String, Stamp>) -> IdeResult<AgentChanges> {
|
||||
let cwd = self.cwd();
|
||||
if spans_repos(cwd) {
|
||||
return Ok(AgentChanges { uncommitted: self.changes(before, None)?, commits: Vec::new() });
|
||||
}
|
||||
let Some(repo) = discover(cwd)? else { return Ok(AgentChanges::default()) };
|
||||
let head = repo.head()?.1;
|
||||
let uncommitted = match &head {
|
||||
@@ -353,6 +495,8 @@ impl TaskBase {
|
||||
pub(crate) fn rev(&self) -> IdeResult<Option<String>> {
|
||||
let (cwd, start) = match self {
|
||||
Self::Worktree { base, .. } => return Ok(Some(base.clone())),
|
||||
// Each repository goes back to its own `HEAD`.
|
||||
Self::Local { cwd, .. } if spans_repos(cwd) => return Ok(Some("HEAD".to_owned())),
|
||||
Self::Local { cwd, start } => (cwd, start.as_deref()),
|
||||
};
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
@@ -545,6 +689,18 @@ pub(crate) fn stamp(path: &Path) -> Stamp {
|
||||
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
|
||||
// Paths and stamps only: no diff and no line counts, which read every untracked file
|
||||
// and held up starting a task in a checkout with many of them.
|
||||
if let Some((base, repos)) = nested_repos(cwd)? {
|
||||
let roots: Vec<PathBuf> = repos.iter().map(|r| r.root().to_path_buf()).collect();
|
||||
let mut out = BTreeMap::new();
|
||||
for repo in &repos {
|
||||
for s in repo.status()? {
|
||||
if let Some(rel) = nested_rel(&base, repo, &roots, &s.path) {
|
||||
out.insert(rel, stamp(&s.path));
|
||||
}
|
||||
}
|
||||
}
|
||||
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())
|
||||
}
|
||||
@@ -587,10 +743,16 @@ fn saved_name(rel: &str) -> String {
|
||||
/// into `dir`, so rolling back the task's changes to them restores the user's own edits.
|
||||
/// Whether anything was saved.
|
||||
pub(crate) fn save_before(cwd: &Path, before: &BTreeMap<String, Stamp>, dir: &Path) -> IdeResult<bool> {
|
||||
let Some(repo) = Repo::discover(cwd)? else { return Ok(false) };
|
||||
let root = match nested_repos(cwd)? {
|
||||
Some((base, _)) => base,
|
||||
None => match Repo::discover(cwd)? {
|
||||
Some(repo) => repo.root().to_path_buf(),
|
||||
None => return Ok(false),
|
||||
},
|
||||
};
|
||||
let mut saved = false;
|
||||
for (rel, stamp) in before {
|
||||
let path = repo.root().join(rel);
|
||||
let path = root.join(rel);
|
||||
if stamp.is_none() || !std::fs::metadata(&path).is_ok_and(|m| m.is_file() && m.len() <= SAVED_MAX) {
|
||||
continue;
|
||||
}
|
||||
@@ -625,7 +787,8 @@ pub(crate) fn restore(
|
||||
}
|
||||
None => match rev {
|
||||
Some(rev) => {
|
||||
let repo = Repo::discover(cwd)?.ok_or_else(|| IdeError::invalid("not in a git repository"))?;
|
||||
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,
|
||||
@@ -665,6 +828,9 @@ pub(crate) struct TurnStart {
|
||||
/// `HEAD` then (`None` outside a repository or before its first commit).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub head: Option<String>,
|
||||
/// With nested repositories, each one's `HEAD` then, by its root.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub heads: BTreeMap<String, String>,
|
||||
/// The files already changed then, stamped.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub before: BTreeMap<String, Stamp>,
|
||||
@@ -680,8 +846,16 @@ pub(crate) struct TurnStart {
|
||||
/// The copies `previous` saved of files unchanged since are kept 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(repo) = discover(cwd)? else { return Ok(TurnStart::default()) };
|
||||
let head = repo.head()?.1;
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(TurnStart::default()) };
|
||||
let mut heads = BTreeMap::new();
|
||||
let head = if at.nested {
|
||||
for repo in &at.repos {
|
||||
heads.extend(repo.head()?.1.map(|h| (root_key(repo.root()), h)));
|
||||
}
|
||||
None
|
||||
} else {
|
||||
at.repos[0].head()?.1
|
||||
};
|
||||
// As the turn's end is read, so the two compare.
|
||||
let before = snapshot(cwd)?;
|
||||
let mut saved = BTreeSet::new();
|
||||
@@ -702,7 +876,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
|
||||
}
|
||||
}
|
||||
for (rel, stamp) in &before {
|
||||
let path = repo.root().join(rel);
|
||||
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)
|
||||
@@ -715,7 +889,7 @@ pub(crate) fn start_turn(cwd: &Path, dir: &Path, previous: Option<&TurnStart>) -
|
||||
saved.insert(rel.clone());
|
||||
}
|
||||
}
|
||||
Ok(TurnStart { head, before, saved, changed: None })
|
||||
Ok(TurnStart { head, heads, before, saved, changed: None })
|
||||
}
|
||||
|
||||
/// The files that changed in `cwd` since the turn `start` began: in the working tree (as
|
||||
@@ -724,20 +898,25 @@ pub(crate) fn changed_in_turn(cwd: &Path, start: &TurnStart) -> IdeResult<(Vec<S
|
||||
let end = snapshot(cwd)?;
|
||||
let worktree = changed_between(&start.before, &end);
|
||||
let mut all: BTreeSet<String> = worktree.iter().cloned().collect();
|
||||
if let Some(repo) = discover(cwd)?
|
||||
&& let (Some(from), Some(to)) = (&start.head, repo.head()?.1)
|
||||
&& *from != to
|
||||
{
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok((worktree, all)) };
|
||||
for repo in &at.repos {
|
||||
let (Some(from), Some(to)) = (at.head_then(start, repo), repo.head()?.1) else { continue };
|
||||
if from == to {
|
||||
continue;
|
||||
}
|
||||
// Named from the base, as the working tree's files are.
|
||||
let prefix = rel_in(&at.base, repo.root())?;
|
||||
let named = |rel: String| if prefix.is_empty() { rel } else { format!("{prefix}/{rel}") };
|
||||
for f in repo.diff_revisions(from, &to)? {
|
||||
all.extend(f.old_path);
|
||||
all.insert(f.path);
|
||||
all.extend(f.old_path.map(named));
|
||||
all.insert(named(f.path));
|
||||
}
|
||||
}
|
||||
Ok((worktree, all))
|
||||
}
|
||||
|
||||
/// The content of `rel` as the turn `start` began (`None`: no file), its copies in `dir`.
|
||||
fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeResult<Option<Vec<u8>>> {
|
||||
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() {
|
||||
@@ -746,10 +925,13 @@ fn at_turn_start(repo: &Repo, rel: &str, start: &TurnStart, dir: &Path) -> IdeRe
|
||||
"{rel} had changes when the turn started that weren't saved; roll it back in Git instead"
|
||||
))),
|
||||
},
|
||||
None => match &start.head {
|
||||
Some(head) => repo.file_bytes_at(&repo.root().join(rel), Some(head)),
|
||||
None => Ok(None),
|
||||
},
|
||||
None => {
|
||||
let path = at.base.join(rel);
|
||||
match at.owner(&path).and_then(|repo| Some((repo, at.head_then(start, repo)?))) {
|
||||
Some((repo, head)) => repo.file_bytes_at(&path, Some(head)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -771,13 +953,13 @@ pub(crate) fn turn_changes(
|
||||
dir: &Path,
|
||||
changed: &BTreeSet<String>,
|
||||
) -> IdeResult<Vec<AgentChange>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(Vec::new()) };
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(Vec::new()) };
|
||||
let mut out = Vec::new();
|
||||
for rel in changed {
|
||||
let path = repo.root().join(rel);
|
||||
let path = at.base.join(rel);
|
||||
// A folder (a submodule, say) or a file that can't be read has nothing to compare.
|
||||
let Some(now) = existing(&path) else { continue };
|
||||
let (kind, (added, removed)) = match at_turn_start(&repo, rel, start, dir) {
|
||||
let (kind, (added, removed)) = match at_turn_start(&at, rel, start, dir) {
|
||||
Ok(then) if then == now => continue,
|
||||
Ok(then) => {
|
||||
let kind = match (&then, &now) {
|
||||
@@ -790,19 +972,29 @@ pub(crate) fn turn_changes(
|
||||
// Its start wasn't saved: listed, without counts.
|
||||
Err(_) => (ChangeKind::Modified, (0, 0)),
|
||||
};
|
||||
out.push(AgentChange { path: IpcPath(path), rel_path: rel.clone(), kind, added, removed, old_path: None });
|
||||
out.push(AgentChange {
|
||||
rel_path: rel.clone(),
|
||||
kind,
|
||||
added,
|
||||
removed,
|
||||
old_path: None,
|
||||
repo: at.nested.then(|| at.owner(&path).map(|r| IpcPath(r.root().to_path_buf()))).flatten(),
|
||||
path: IpcPath(path),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The text of `path` as the turn `start` began, `None` when there was no file.
|
||||
pub(crate) fn turn_text(cwd: &Path, path: &Path, start: &TurnStart, dir: &Path) -> IdeResult<Option<String>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
let rel = rel_in(repo.root(), path)?;
|
||||
if let (None, Some(head)) = (start.before.get(&rel), &start.head) {
|
||||
let Some(at) = TurnRepos::of(cwd)? else { return Ok(None) };
|
||||
let rel = rel_in(&at.base, path)?;
|
||||
if !start.before.contains_key(&rel)
|
||||
&& let Some(head) = at.owner(&at.base.join(&rel)).and_then(|repo| at.head_then(start, repo))
|
||||
{
|
||||
return file_at(cwd, path, head);
|
||||
}
|
||||
let Some(bytes) = at_turn_start(&repo, &rel, start, dir)? else { return Ok(None) };
|
||||
let Some(bytes) = at_turn_start(&at, &rel, start, dir)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&bytes, None),
|
||||
@@ -828,12 +1020,15 @@ fn rel_in(root: &Path, path: &Path) -> IdeResult<String> {
|
||||
|
||||
/// Puts `change` back as it was when the turn `start` began.
|
||||
pub(crate) fn restore_turn(cwd: &Path, start: &TurnStart, dir: &Path, change: &AgentChange) -> IdeResult<()> {
|
||||
let repo = repo_at(cwd)?;
|
||||
put(&change.path.0, at_turn_start(&repo, &change.rel_path, start, dir)?)
|
||||
let at = TurnRepos::of(cwd)?
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} is not in a git repository", cwd.display())))?;
|
||||
put(&change.path.0, at_turn_start(&at, &change.rel_path, start, dir)?)
|
||||
}
|
||||
|
||||
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(None) };
|
||||
// With nested repositories, the file's own one.
|
||||
let at = if spans_repos(cwd) { path.parent().unwrap_or(cwd) } else { cwd };
|
||||
let Some(repo) = discover(at)? else { return Ok(None) };
|
||||
let encoding = match ide_vfs::load_text(path) {
|
||||
Ok(loaded) => encoding_rs::Encoding::for_label(loaded.encoding.as_bytes()).unwrap_or(encoding_rs::UTF_8),
|
||||
Err(_) => ide_vfs::detect_encoding(&repo.file_bytes_at(path, Some(rev))?.unwrap_or_default(), None),
|
||||
@@ -962,6 +1157,111 @@ mod tests {
|
||||
assert!(ok, "git {args:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn attributed_changes_only_diff_the_owning_checkout() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||||
for n in 0..15 {
|
||||
let repo = root.join(format!("repo{n:02}"));
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(&repo, &["add", "a.txt"]);
|
||||
git(&repo, &["commit", "-q", "-m", "initial"]);
|
||||
std::fs::write(repo.join("a.txt"), "two\n").unwrap();
|
||||
}
|
||||
// Count real Git diff processes, not walks to discover the topology.
|
||||
let git = tmp.path().join("count-git");
|
||||
let log = tmp.path().join("count-git.log");
|
||||
std::fs::write(
|
||||
&git,
|
||||
"#!/bin/sh\nfor arg do\nif [ \"$arg\" = diff ]; then pwd >> \"$0.log\"; break; fi\ndone\nexec git \"$@\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&git, std::fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let at = TaskBase::Local { cwd: root, start: None };
|
||||
let before = BTreeMap::new();
|
||||
let one = BTreeSet::from(["repo07/a.txt".to_owned()]);
|
||||
let read = |touched: Option<&BTreeSet<String>>| {
|
||||
std::fs::write(&log, "").unwrap();
|
||||
let start = std::time::Instant::now();
|
||||
let changes = ide_vcs::with_git_executable(Some(&git), || at.changes(&before, touched).unwrap());
|
||||
let elapsed = start.elapsed();
|
||||
let calls = std::fs::read_to_string(&log).unwrap();
|
||||
eprintln!("change read: touched={:?} elapsed={elapsed:?}", touched.map(BTreeSet::len));
|
||||
(changes, calls.lines().count())
|
||||
};
|
||||
let (all, full_calls) = read(None);
|
||||
let (selected, selected_calls) = read(Some(&one));
|
||||
let (empty, empty_calls) = read(Some(&BTreeSet::new()));
|
||||
assert_eq!(all.len(), 15);
|
||||
assert_eq!(
|
||||
serde_json::to_value(selected).unwrap(),
|
||||
serde_json::to_value(made_by_task(all, Some(&one))).unwrap()
|
||||
);
|
||||
assert!(empty.is_empty());
|
||||
eprintln!("git diff children: full {full_calls}, one touched {selected_calls}, none touched {empty_calls}");
|
||||
assert!(selected_calls > 0);
|
||||
assert_eq!(selected_calls * 15, full_calls);
|
||||
assert_eq!(empty_calls, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_project_with_nested_repositories_sees_changes_in_each_one() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (nested, deeper) = (root.join("libs/validation"), root.join("libs/validation/pkg/sdk"));
|
||||
for repo in [&root, &nested, &deeper] {
|
||||
std::fs::create_dir_all(repo).unwrap();
|
||||
git(repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "one\n").unwrap();
|
||||
git(repo, &["add", "a.txt"]);
|
||||
git(repo, &["commit", "-q", "-m", "init"]);
|
||||
}
|
||||
assert!(spans_repos(&root));
|
||||
std::fs::write(root.join("mine.txt"), "the user's\n").unwrap();
|
||||
let before = snapshot(&root).unwrap();
|
||||
assert_eq!(before.keys().collect::<Vec<_>>(), ["mine.txt"]);
|
||||
|
||||
std::fs::write(root.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("a.txt"), "two\n").unwrap();
|
||||
std::fs::write(nested.join("b.txt"), "new\n").unwrap();
|
||||
std::fs::write(deeper.join("a.txt"), "two\n").unwrap();
|
||||
let at = TaskBase::Local { cwd: root.clone(), start: None };
|
||||
let changed = at.changes(&before, None).unwrap();
|
||||
let listed: Vec<(&str, &Path)> =
|
||||
changed.iter().map(|c| (c.rel_path.as_str(), c.repo.as_ref().unwrap().0.as_path())).collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
("a.txt", root.as_path()),
|
||||
("libs/validation/a.txt", nested.as_path()),
|
||||
("libs/validation/b.txt", nested.as_path()),
|
||||
("libs/validation/pkg/sdk/a.txt", deeper.as_path()),
|
||||
]
|
||||
);
|
||||
assert_eq!(at.grouped_changes(&before).unwrap().uncommitted.len(), 4);
|
||||
assert_eq!(file_at(&root, &nested.join("a.txt"), "HEAD").unwrap().as_deref(), Some("one\n"));
|
||||
|
||||
let rev = at.rev().unwrap();
|
||||
for change in &changed {
|
||||
restore(&root, rev.as_deref(), change, &before, None).unwrap();
|
||||
}
|
||||
for repo in [&root, &nested, &deeper] {
|
||||
assert_eq!(std::fs::read_to_string(repo.join("a.txt")).unwrap(), "one\n");
|
||||
}
|
||||
assert!(!nested.join("b.txt").exists());
|
||||
assert!(root.join("mine.txt").exists(), "the user's own change stays");
|
||||
// A deleted file cannot be canonicalized, but still belongs to its innermost repo.
|
||||
std::fs::remove_file(deeper.join("a.txt")).unwrap();
|
||||
let removed = at.changes(&before, Some(&BTreeSet::from(["libs/validation/pkg/sdk/a.txt".into()]))).unwrap();
|
||||
assert_eq!(removed.len(), 1);
|
||||
assert_eq!(removed[0].repo.as_ref().unwrap().0, deeper);
|
||||
assert_eq!(removed[0].kind, ChangeKind::Deleted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worktree_changes_are_listed_against_the_base() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -10,8 +10,6 @@ ide-core.workspace = true
|
||||
ide-language.workspace = true
|
||||
serde.workspace = true
|
||||
specta.workspace = true
|
||||
tree-sitter.workspace = true
|
||||
rayon.workspace = true
|
||||
tracing.workspace = true
|
||||
# Pinned: 0.40.2+ moves to tree-sitter 0.26, the workspace is on 0.25.
|
||||
ast-grep-core = "=0.40.1"
|
||||
@@ -10,6 +10,3 @@ ide-core.workspace = true
|
||||
serde.workspace = true
|
||||
specta.workspace = true
|
||||
which = "8"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -91,12 +91,6 @@ fn executable() -> IdeResult<PathBuf> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The directory holding adb, for command lines that expect `adb` on `PATH`.
|
||||
pub fn platform_tools_dir() -> Option<&'static Path> {
|
||||
static DIR: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
DIR.get_or_init(|| adb_executable().as_deref().and_then(Path::parent).map(Path::to_path_buf)).as_deref()
|
||||
}
|
||||
|
||||
/// Connected devices, online ones first; starting the adb daemon when needed.
|
||||
pub fn devices() -> IdeResult<Vec<AndroidDevice>> {
|
||||
let adb = executable()?;
|
||||
|
||||
+216
-134
@@ -1,101 +1,18 @@
|
||||
//! Child processes of the `adb` CLI: bounded runs, and cancellable line streams
|
||||
//! The `adb` CLI as a child process: bounded runs, and cancellable line streams
|
||||
//! that are handed over in batches (logcat is far too chatty for one message a line).
|
||||
|
||||
use ide_core::process::terminate_tree;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
pub(crate) use ide_core::cli_process::Output;
|
||||
use ide_core::cli_process::{CarriageReturn, CliTool, Decoding, Poll, Stream, keep_stderr_line};
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a cancelled child gets to exit on `SIGTERM` (and flush) before `SIGKILL`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
fn prepare(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::prepare(ide_core::process::own_group(cmd));
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run adb: {e}")))
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
ide_core::output_encoding::decode_tool_output(&buf)
|
||||
})
|
||||
}
|
||||
const ADB: CliTool = CliTool::new("adb", Decoding::ToolOutput);
|
||||
|
||||
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
|
||||
/// a non-zero exit is reported in [`Output::success`], not as an error.
|
||||
pub(crate) fn run(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
prepare(&mut cmd);
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
let out = child.stdout.take().map(read_all);
|
||||
let err = child.stderr.take().map(read_all);
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::unavailable("adb did not respond in time"));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(Output {
|
||||
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
success: status.success(),
|
||||
})
|
||||
}
|
||||
|
||||
enum Event {
|
||||
Line(bool, String),
|
||||
Closed,
|
||||
}
|
||||
|
||||
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stdout: bool) {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
let mut pending: Vec<u8> = Vec::new();
|
||||
let flush = |pending: &mut Vec<u8>| {
|
||||
if !pending.is_empty() {
|
||||
let line = ide_core::output_encoding::decode_tool_output(pending);
|
||||
pending.clear();
|
||||
let _ = tx.send(Event::Line(stdout, line.trim_end().to_string()));
|
||||
}
|
||||
};
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
for &b in &buf[..n] {
|
||||
if b == b'\n' {
|
||||
flush(&mut pending);
|
||||
} else if b != b'\r' {
|
||||
pending.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(&mut pending);
|
||||
let _ = tx.send(Event::Closed);
|
||||
});
|
||||
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
ADB.run(cmd, timeout, cancel)
|
||||
}
|
||||
|
||||
fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
|
||||
@@ -109,41 +26,22 @@ fn flush<T>(batch: &mut Vec<T>, on_batch: &mut dyn FnMut(Vec<T>)) {
|
||||
/// old, so neither a quiet nor a steady stream holds lines back. Stderr is kept as a
|
||||
/// tail for the error message. Returns whether the child exited successfully.
|
||||
pub(crate) fn stream_batched<T>(
|
||||
mut cmd: Command,
|
||||
cmd: Command,
|
||||
cancel: &CancellationToken,
|
||||
idle: Duration,
|
||||
max: usize,
|
||||
mut parse: impl FnMut(&str) -> Option<T>,
|
||||
on_batch: &mut dyn FnMut(Vec<T>),
|
||||
) -> IdeResult<(bool, Vec<String>)> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
prepare(&mut cmd);
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
let (tx, rx) = mpsc::channel::<Event>();
|
||||
let mut open = 0;
|
||||
if let Some(out) = child.stdout.take() {
|
||||
spawn_reader(out, tx.clone(), true);
|
||||
open += 1;
|
||||
}
|
||||
if let Some(err) = child.stderr.take() {
|
||||
spawn_reader(err, tx.clone(), false);
|
||||
open += 1;
|
||||
}
|
||||
drop(tx);
|
||||
let mut lines = ADB.lines(cmd, cancel, CarriageReturn::Dropped)?;
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
let mut batch: Vec<T> = Vec::with_capacity(max);
|
||||
// When the first line of the waiting batch arrived.
|
||||
let mut since = Instant::now();
|
||||
while open > 0 {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
loop {
|
||||
let wait = if batch.is_empty() { idle } else { idle.saturating_sub(since.elapsed()) };
|
||||
match rx.recv_timeout(wait) {
|
||||
Ok(Event::Line(true, line)) => {
|
||||
match lines.poll(cancel, wait)? {
|
||||
Poll::Line(Stream::Stdout, line) => {
|
||||
if let Some(item) = parse(&line) {
|
||||
if batch.is_empty() {
|
||||
since = Instant::now();
|
||||
@@ -154,36 +52,25 @@ pub(crate) fn stream_batched<T>(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Event::Line(false, line)) => {
|
||||
Poll::Line(Stream::Stderr, line) => {
|
||||
if !line.trim().is_empty() {
|
||||
stderr_tail.push(line);
|
||||
if stderr_tail.len() > 20 {
|
||||
stderr_tail.remove(0);
|
||||
}
|
||||
keep_stderr_line(&mut stderr_tail, line);
|
||||
}
|
||||
}
|
||||
Ok(Event::Closed) => open -= 1,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => flush(&mut batch, on_batch),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Poll::Closed => {}
|
||||
Poll::Timeout => flush(&mut batch, on_batch),
|
||||
Poll::Finished => break,
|
||||
}
|
||||
}
|
||||
flush(&mut batch, on_batch);
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok((status.success(), stderr_tail))
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::process::process_alive;
|
||||
|
||||
#[test]
|
||||
fn a_steady_stream_is_handed_over_while_it_runs() {
|
||||
@@ -203,4 +90,199 @@ mod tests {
|
||||
assert_eq!(sizes.iter().sum::<usize>(), 20);
|
||||
assert!(sizes.len() >= 3, "lines arriving every 20 ms waited for the end: {sizes:?}");
|
||||
}
|
||||
|
||||
const LONG: Duration = Duration::from_secs(30);
|
||||
|
||||
fn sh(script: &str) -> Command {
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.args(["-c", script]);
|
||||
cmd
|
||||
}
|
||||
|
||||
/// A script that records its pid in `name`'s file, then runs `rest`.
|
||||
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
|
||||
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_file(&file);
|
||||
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
|
||||
}
|
||||
|
||||
fn recorded_pid(file: &std::path::Path) -> u32 {
|
||||
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
|
||||
let _ = std::fs::remove_file(file);
|
||||
pid
|
||||
}
|
||||
|
||||
/// Cancels `cancel` once the script has recorded its pid.
|
||||
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
|
||||
let (file, cancel) = (file.to_owned(), cancel.clone());
|
||||
std::thread::spawn(move || {
|
||||
while !file.exists() {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
cancel.cancel();
|
||||
});
|
||||
}
|
||||
|
||||
fn assert_gone(pid: u32) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while process_alive(pid) {
|
||||
assert!(Instant::now() < deadline, "process {pid} survived");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_status_is_reported_not_raised() {
|
||||
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
|
||||
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_streams_are_captured_separately_and_in_order() {
|
||||
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout, "a\nb\nc\n");
|
||||
assert_eq!(out.stderr, "x\ny\n");
|
||||
assert!(out.success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_utf8_is_replaced_in_collected_output() {
|
||||
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
|
||||
assert_eq!(out.stderr, "a\u{FFFD}b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_is_closed() {
|
||||
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_program_is_unavailable() {
|
||||
let err = run(Command::new("/nonexistent/openidea-adb"), LONG, None).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("adb-timeout", "exec sleep 30");
|
||||
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "adb did not respond in time");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_run_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("adb-cancel", "exec sleep 30");
|
||||
let cancel = CancellationToken::new();
|
||||
cancel_when_recorded(&file, &cancel);
|
||||
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
/// Runs `script` batched by `max` lines (a long `idle`, so only `max` and the end flush),
|
||||
/// parsing stdout lines unless they are `skip`.
|
||||
fn batches(script: &str, max: usize) -> (bool, Vec<Vec<String>>, Vec<String>) {
|
||||
let mut batches = Vec::new();
|
||||
let (ok, tail) = stream_batched(
|
||||
sh(script),
|
||||
&CancellationToken::new(),
|
||||
LONG,
|
||||
max,
|
||||
|line| (line != "skip").then(|| line.to_owned()),
|
||||
&mut |batch| batches.push(batch),
|
||||
)
|
||||
.unwrap();
|
||||
(ok, batches, tail)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_batch_is_handed_over_as_soon_as_max_lines_are_ready() {
|
||||
let (ok, batches, _) = batches("printf '1\\n2\\n3\\n4\\n5\\n'", 2);
|
||||
assert!(ok);
|
||||
assert_eq!(batches, [vec!["1", "2"], vec!["3", "4"], vec!["5"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_the_parser_rejects_are_dropped() {
|
||||
let (_, batches, _) = batches("printf '1\\nskip\\n2\\n'", 10);
|
||||
assert_eq!(batches, [vec!["1", "2"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn carriage_returns_are_dropped_not_split_on_and_line_ends_are_trimmed() {
|
||||
let (_, batches, _) = batches("printf 'a\\r\\nb\\rc \\n\\n\\nd'", 10);
|
||||
assert_eq!(batches, [vec!["a", "bc", "d"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_replaces_invalid_utf8() {
|
||||
let (_, batches, _) = batches("printf 'a\\377b\\n'", 10);
|
||||
assert_eq!(batches, [vec!["a\u{FFFD}b"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_reports_the_exit_status() {
|
||||
assert!(batches("exit 0", 10).0);
|
||||
assert!(!batches("exit 2", 10).0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stderr_is_not_parsed_and_its_last_twenty_non_blank_lines_are_kept() {
|
||||
let (_, batches, tail) =
|
||||
batches("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done; echo out", 10);
|
||||
assert_eq!(batches, [vec!["out"]]);
|
||||
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
|
||||
assert_eq!(tail, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
let err = stream_batched(
|
||||
Command::new("/nonexistent/openidea-adb"),
|
||||
&cancel,
|
||||
LONG,
|
||||
10,
|
||||
|line| Some(line.to_owned()),
|
||||
&mut |_| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("adb-stream-cancel", "echo started; exec sleep 30");
|
||||
let cancel = CancellationToken::new();
|
||||
let err = stream_batched(cmd, &cancel, LONG, 1, |line| Some(line.to_owned()), &mut |_| cancel.cancel())
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_program_cannot_be_streamed() {
|
||||
let err = stream_batched(
|
||||
Command::new("/nonexistent/openidea-adb"),
|
||||
&CancellationToken::new(),
|
||||
LONG,
|
||||
10,
|
||||
|line| Some(line.to_owned()),
|
||||
&mut |_| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)");
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,4 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
dirs.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -15,8 +15,8 @@ pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
|
||||
pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, single_file_classpath,
|
||||
single_file_target,
|
||||
SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, module_classpaths,
|
||||
single_file_classpath, single_file_target,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan,
|
||||
@@ -483,11 +483,6 @@ fn go_module_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
vec![s]
|
||||
}
|
||||
|
||||
/// `pnpm` / `yarn` / `bun` / `npm`, from the lock file next to `package.json` or above it.
|
||||
fn package_manager(dir: &Path) -> &'static str {
|
||||
ide_core::project_roots::package_manager(dir)
|
||||
}
|
||||
|
||||
fn has_build_script(dir: &Path) -> bool {
|
||||
std::fs::read(dir.join("package.json"))
|
||||
.ok()
|
||||
@@ -525,7 +520,12 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
let script = has_build_script(dir);
|
||||
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
|
||||
return vec![BuildStep::new(package_manager(dir), &["run", "build"], dir, Format::Tsc)];
|
||||
return vec![BuildStep::new(
|
||||
ide_core::project_roots::package_manager(dir),
|
||||
&["run", "build"],
|
||||
dir,
|
||||
Format::Tsc,
|
||||
)];
|
||||
}
|
||||
let local = dir.ancestors().map(|d| d.join("node_modules/.bin/tsc")).find(|p| p.is_file());
|
||||
let program = local.map_or_else(|| "tsc".to_owned(), |p| p.to_string_lossy().into_owned());
|
||||
@@ -916,6 +916,47 @@ fn launch_plan(
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
/// Directory of the linked Maven reactor that builds the launch module at `module`;
|
||||
/// launches of one reactor can share a build ([`build_for_launches`]).
|
||||
pub fn launch_reactor(root: &Path, model: &BuildModel, module: &Path) -> Option<String> {
|
||||
maven_reactor(model.maven.as_ref()?, &rel_str(root, module)).map(|top| top.dir.clone())
|
||||
}
|
||||
|
||||
/// One Maven step building every module of `modules` (all of one reactor) with what they
|
||||
/// depend on: `-pl a,b -am`, so their shared upstream modules build once (#3971).
|
||||
fn merged_launch_plan(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
modules: &[PathBuf],
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<BuildPlan> {
|
||||
let mut plan = launch_plan(root, model, &modules[0], test, kind, cancel)?;
|
||||
if plan.system != BuildSystem::Maven || modules.len() == 1 {
|
||||
return Ok(plan);
|
||||
}
|
||||
let mut selection = Vec::new();
|
||||
for module in modules {
|
||||
let one = launch_plan(root, model, module, test, kind, cancel)?;
|
||||
if one.steps.len() != 1 || one.steps[0].cwd != plan.steps[0].cwd {
|
||||
return Err(IdeError::invalid("launch modules belong to different Maven reactors"));
|
||||
}
|
||||
match one.steps[0].args.iter().position(|a| a == "-pl") {
|
||||
Some(i) => selection.push(one.steps[0].args[i + 1].clone()),
|
||||
// The reactor root itself builds every module.
|
||||
None => return Ok(one),
|
||||
}
|
||||
}
|
||||
selection.sort();
|
||||
selection.dedup();
|
||||
let step = &mut plan.steps[0];
|
||||
if let Some(i) = step.args.iter().position(|a| a == "-pl") {
|
||||
step.args[i + 1] = selection.join(",");
|
||||
}
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LaunchBuild {
|
||||
pub class_dirs: Vec<PathBuf>,
|
||||
@@ -932,7 +973,21 @@ pub fn build_for_launch(
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<LaunchBuild> {
|
||||
let plan = launch_plan(root, model, module, test, kind, cancel)?;
|
||||
let mut built = build_for_launches(root, model, &[module.to_path_buf()], test, kind, cancel)?;
|
||||
Ok(built.pop().unwrap())
|
||||
}
|
||||
|
||||
/// [`build_for_launch`] of several modules of one Maven reactor in a single Maven run:
|
||||
/// one result per module, in order, sharing the build's failure.
|
||||
pub fn build_for_launches(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
modules: &[PathBuf],
|
||||
test: bool,
|
||||
kind: BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<LaunchBuild>> {
|
||||
let plan = merged_launch_plan(root, model, modules, test, kind, cancel)?;
|
||||
let result = run(root, &plan, cancel, &|_| {})?;
|
||||
let failure = if !result.success {
|
||||
let errors: Vec<String> = result
|
||||
@@ -949,17 +1004,70 @@ pub fn build_for_launch(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let class_dirs = if plan.system == BuildSystem::Maven
|
||||
&& let Some(m) = &model.maven
|
||||
{
|
||||
maven_launch_projects(root, m, module, test)
|
||||
.iter()
|
||||
.flat_map(|p| launch_class_dirs(plan.system, &subdir(root, &p.dir), test && subdir(root, &p.dir) == module))
|
||||
.collect()
|
||||
} else {
|
||||
launch_class_dirs(plan.system, module, test)
|
||||
let class_dirs = |module: &Path| {
|
||||
if plan.system == BuildSystem::Maven
|
||||
&& let Some(m) = &model.maven
|
||||
{
|
||||
maven_launch_output_dirs(root, m, module, test).into_iter().filter(|dir| dir.is_dir()).collect()
|
||||
} else {
|
||||
launch_class_dirs(plan.system, module, test)
|
||||
}
|
||||
};
|
||||
Ok(LaunchBuild { class_dirs, failure })
|
||||
Ok(modules.iter().map(|m| LaunchBuild { class_dirs: class_dirs(m), failure: failure.clone() }).collect())
|
||||
}
|
||||
|
||||
/// Maven output directories for a launch, including directories that have yet to be created.
|
||||
pub fn maven_launch_output_dirs(root: &Path, model: &maven::MavenModel, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
maven_launch_projects(root, model, module, test)
|
||||
.into_iter()
|
||||
.flat_map(|p| {
|
||||
let dir = subdir(root, &p.dir);
|
||||
maven_output_dirs(&dir, test && dir == module)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The class directories of a Maven launch that must hold classes after its build: those of
|
||||
/// the launch projects with sources in a conventional JVM source root. One that is missing
|
||||
/// or holds no class was caught mid-rewrite, e.g. cleaned by a concurrent `mvn` (#5404).
|
||||
pub fn launch_required_class_dirs(root: &Path, model: &BuildModel, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
fn has_sources(dir: &Path, depth: u32) -> bool {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return false };
|
||||
entries.flatten().any(|e| {
|
||||
let p = e.path();
|
||||
if p.is_dir() {
|
||||
depth > 0 && has_sources(&p, depth - 1)
|
||||
} else {
|
||||
// A package-info.java without annotations compiles to nothing.
|
||||
p.file_name() != Some("package-info.java".as_ref())
|
||||
&& p.extension().is_some_and(|x| x == "java" || x == "kt" || x == "groovy" || x == "scala")
|
||||
}
|
||||
})
|
||||
}
|
||||
let compiles = |dir: &Path, set: &str| {
|
||||
["java", "kotlin", "groovy", "scala"].iter().any(|lang| has_sources(&dir.join("src").join(set).join(lang), 32))
|
||||
};
|
||||
let Some(m) = &model.maven else { return Vec::new() };
|
||||
let mut dirs = Vec::new();
|
||||
for p in maven_launch_projects(root, m, module, test) {
|
||||
let dir = subdir(root, &p.dir);
|
||||
if test && dir == module && compiles(&dir, "test") {
|
||||
dirs.push(subdir(&dir, "target/test-classes"));
|
||||
}
|
||||
if compiles(&dir, "main") {
|
||||
dirs.push(subdir(&dir, "target/classes"));
|
||||
}
|
||||
}
|
||||
dirs
|
||||
}
|
||||
|
||||
fn maven_output_dirs(module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
if test {
|
||||
dirs.push(subdir(module, "target/test-classes"));
|
||||
}
|
||||
dirs.push(subdir(module, "target/classes"));
|
||||
dirs
|
||||
}
|
||||
|
||||
fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<PathBuf> {
|
||||
@@ -972,8 +1080,7 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
|
||||
.map(|d| subdir(module, &format!("build/{d}/{s}")))
|
||||
})
|
||||
.collect(),
|
||||
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
|
||||
BuildSystem::Maven => vec![subdir(module, "target/classes")],
|
||||
BuildSystem::Maven => maven_output_dirs(module, test),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
dirs.into_iter().filter(|d| d.is_dir()).collect()
|
||||
@@ -1659,6 +1766,46 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launches_of_one_reactor_merge_into_one_module_selection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["app", "lib", "unrelated"] {
|
||||
write(root, &format!("{dir}/pom.xml"), "<project/>");
|
||||
}
|
||||
let mut model = reactor_model();
|
||||
let cancel = CancellationToken::new();
|
||||
let modules = |dirs: &[&str]| dirs.iter().map(|d| root.join(d)).collect::<Vec<_>>();
|
||||
let selection = |plan: BuildPlan| {
|
||||
let args = &plan.steps[0].args;
|
||||
args.iter().position(|a| a == "-pl").map(|i| (args[i + 1].clone(), args[i + 2].clone(), args.len()))
|
||||
};
|
||||
assert_eq!(launch_reactor(root, &model, &root.join("lib")).as_deref(), Some(""));
|
||||
let plan = merged_launch_plan(root, &model, &modules(&["lib", "app", "lib"]), false, BuildKind::Build, &cancel)
|
||||
.unwrap();
|
||||
assert_eq!(plan.steps.len(), 1);
|
||||
assert_eq!(plan.steps[0].args.last().unwrap(), "compile");
|
||||
assert_eq!(selection(plan), Some(("app,lib".into(), "-am".into(), 10)));
|
||||
// One module: exactly the single launch's step.
|
||||
let single = merged_launch_plan(root, &model, &modules(&["app"]), true, BuildKind::Rebuild, &cancel).unwrap();
|
||||
let expected = launch_plan(root, &model, &root.join("app"), true, BuildKind::Rebuild, &cancel).unwrap();
|
||||
assert_eq!(single.steps[0].args, expected.steps[0].args);
|
||||
// The reactor root among them builds the whole reactor.
|
||||
model.maven.as_mut().unwrap().projects[0].packaging = "jar".into();
|
||||
let whole = merged_launch_plan(root, &model, &modules(&["app", ""]), false, BuildKind::Build, &cancel).unwrap();
|
||||
assert_eq!(selection(whole), None);
|
||||
// Another linked reactor can't join the step.
|
||||
let m = model.maven.as_mut().unwrap();
|
||||
m.projects[4].aggregated = false;
|
||||
m.projects[4].command = "other".into();
|
||||
m.projects[0].modules.retain(|p| p != "unrelated/pom.xml");
|
||||
assert_eq!(launch_reactor(root, &model, &root.join("unrelated")).as_deref(), Some("unrelated"));
|
||||
assert!(
|
||||
merged_launch_plan(root, &model, &modules(&["app", "unrelated"]), false, BuildKind::Build, &cancel)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
|
||||
|
||||
@@ -129,31 +129,73 @@ pub fn module_classpath(
|
||||
cache: &Path,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
let target = module_target(root, model, module, test)?;
|
||||
let fingerprint = launch_fingerprint(root, model, &target.module, test, local_repo, cancel)?;
|
||||
let cache_path = classpath_cache_path(root, cache, &target.module, test);
|
||||
if let (Some(fingerprint), Some(path)) = (&fingerprint, &cache_path)
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& cached.fingerprint == *fingerprint
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(cached.classpath);
|
||||
module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, 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.
|
||||
pub fn module_classpaths(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
modules: &[PathBuf],
|
||||
test: bool,
|
||||
local_repo: Option<PathBuf>,
|
||||
cache: &Path,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
let mut probes: Vec<Probe> = Vec::new();
|
||||
for (i, module) in modules.iter().enumerate() {
|
||||
let target = match module_target(root, model, module, test) {
|
||||
Ok(target) => target,
|
||||
Err(e) if i == 0 => return Err(e),
|
||||
Err(_) => continue,
|
||||
};
|
||||
if i > 0 && (target.top.dir != probes[0].0.top.dir || probes.iter().any(|p| p.0.module == target.module)) {
|
||||
continue;
|
||||
}
|
||||
let fingerprint = launch_fingerprint(root, model, &target.module, test, local_repo.clone(), cancel)?;
|
||||
let cache_path = classpath_cache_path(root, cache, &target.module, test);
|
||||
if let (Some(fingerprint), Some(path)) = (&fingerprint, &cache_path)
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& cached.fingerprint == *fingerprint
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
return Ok(cached.classpath);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
probes.push(Probe(target, fingerprint, cache_path));
|
||||
}
|
||||
let classpath = classpath(root, model, &target, if test { "test" } else { "runtime" }, true)?;
|
||||
let scope = if test { "test" } else { "runtime" };
|
||||
let targets: Vec<&SingleFileTarget> = probes.iter().map(|p| &p.0).collect();
|
||||
let classpaths = match classpaths(root, model, &targets, scope, true) {
|
||||
Ok(classpaths) => classpaths,
|
||||
// Another module's failure must not cost this launch its own probe.
|
||||
Err(_) if targets.len() > 1 && !cancel.is_cancelled() => classpaths(root, model, &targets[..1], scope, true)?,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
|
||||
let cached = CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
|
||||
if let Err(error) = cache_classpath(&path, &cached) {
|
||||
tracing::debug!(path = %path.display(), %error, "Cannot cache the Java launch classpath");
|
||||
for (Probe(_, fingerprint, cache_path), classpath) in probes.into_iter().zip(&classpaths) {
|
||||
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
|
||||
let cached =
|
||||
CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
|
||||
if let Err(error) = cache_classpath(&path, &cached) {
|
||||
tracing::debug!(path = %path.display(), %error, "Cannot cache the Java launch classpath");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(classpath)
|
||||
Ok(classpaths.into_iter().next().unwrap())
|
||||
}
|
||||
|
||||
/// A module whose classpath the Maven probe resolves, with its cache key and file.
|
||||
struct Probe(SingleFileTarget, Option<LaunchFingerprint>, Option<PathBuf>);
|
||||
|
||||
/// One cache file per module and scope. Mirroring the module path keeps nested
|
||||
/// modules and their different dependency scopes from overwriting each other.
|
||||
fn classpath_cache_path(root: &Path, cache: &Path, module: &Path, test: bool) -> Option<PathBuf> {
|
||||
@@ -195,6 +237,62 @@ fn classpath(
|
||||
scope: &str,
|
||||
compile_first: bool,
|
||||
) -> IdeResult<String> {
|
||||
Ok(classpaths(root, model, &[target], scope, compile_first)?.pop().unwrap())
|
||||
}
|
||||
|
||||
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
|
||||
fn classpaths(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
targets: &[&SingleFileTarget],
|
||||
scope: &str,
|
||||
compile_first: bool,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let top = &targets[0].top;
|
||||
let probe = CP_FILE;
|
||||
let mut args = vec!["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG];
|
||||
args.extend(top.options.iter().map(String::as_str));
|
||||
// The reactor root among them builds every module.
|
||||
let selection = if targets.iter().any(|t| t.pl.is_empty()) {
|
||||
String::new()
|
||||
} else {
|
||||
let mut pl: Vec<&str> = targets.iter().map(|t| t.pl.as_str()).collect();
|
||||
pl.sort();
|
||||
pl.dedup();
|
||||
pl.join(",")
|
||||
};
|
||||
if !selection.is_empty() {
|
||||
args.extend(["-pl", selection.as_str(), "-am"]);
|
||||
}
|
||||
let output_arg = format!("-Dmdep.outputFile={probe}");
|
||||
let scope_arg = format!("-Dmdep.includeScope={scope}");
|
||||
// A launch build may only have reached `compile`. Running `compile` in this
|
||||
// same Maven session lets the dependency plugin resolve Reactor siblings from
|
||||
// their target/classes without paying for package-phase plugins.
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let mut command = ProcCommand::new(&top.command);
|
||||
command.args(&args).envs(&top.env).current_dir(&top_dir);
|
||||
let status = ide_core::process::prepare(&mut command)
|
||||
.output()
|
||||
.map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
|
||||
if !status.status.success() {
|
||||
let stdout = String::from_utf8_lossy(&status.stdout);
|
||||
let stderr = String::from_utf8_lossy(&status.stderr);
|
||||
// Maven reports reactor/dependency failures on stdout, not only stderr.
|
||||
let tail: Vec<&str> = stdout.lines().chain(stderr.lines()).filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
|
||||
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
|
||||
}
|
||||
targets.iter().map(|target| target_classpath(root, model, target)).collect()
|
||||
}
|
||||
|
||||
/// The classpath of `target` after a probe: its reactor class directories, then
|
||||
/// the dependencies Maven wrote to the module's probe file.
|
||||
fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult<String> {
|
||||
let mut entries: Vec<String> = Vec::new();
|
||||
// The module's own classes first: the file almost always uses classes next to it.
|
||||
let own: &[&str] = if target.test { &["target/test-classes", "target/classes"] } else { &["target/classes"] };
|
||||
@@ -220,37 +318,8 @@ fn classpath(
|
||||
}
|
||||
}
|
||||
}
|
||||
let probe = CP_FILE;
|
||||
let mut args = vec!["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG];
|
||||
args.extend(target.top.options.iter().map(String::as_str));
|
||||
if !target.pl.is_empty() {
|
||||
args.extend(["-pl", target.pl.as_str(), "-am"]);
|
||||
}
|
||||
let output_arg = format!("-Dmdep.outputFile={probe}");
|
||||
let scope_arg = format!("-Dmdep.includeScope={scope}");
|
||||
// A launch build may only have reached `compile`. Running `compile` in this
|
||||
// same Maven session lets the dependency plugin resolve Reactor siblings from
|
||||
// their target/classes without paying for package-phase plugins.
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &target.top.dir);
|
||||
let mut command = ProcCommand::new(&target.top.command);
|
||||
command.args(&args).envs(&target.top.env).current_dir(&top_dir);
|
||||
let status = ide_core::process::prepare(&mut command)
|
||||
.output()
|
||||
.map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?;
|
||||
if !status.status.success() {
|
||||
let stdout = String::from_utf8_lossy(&status.stdout);
|
||||
let stderr = String::from_utf8_lossy(&status.stderr);
|
||||
// Maven reports reactor/dependency failures on stdout, not only stderr.
|
||||
let tail: Vec<&str> = stdout.lines().chain(stderr.lines()).filter(|l| !l.trim().is_empty()).collect();
|
||||
let tail = tail.iter().rev().take(5).rev().cloned().collect::<Vec<_>>().join("\n");
|
||||
return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}")));
|
||||
}
|
||||
// With `-am` every visited module writes its own file; only this module's counts.
|
||||
let cp_file = target.module.join(probe);
|
||||
let cp_file = target.module.join(CP_FILE);
|
||||
let content = fs::read_to_string(&cp_file).map_err(|e| {
|
||||
IdeError::internal(format!("cannot resolve the compile classpath: {} ({e})", cp_file.display()))
|
||||
})?;
|
||||
@@ -528,6 +597,47 @@ mod tests {
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
|
||||
}
|
||||
|
||||
/// Modules launched together resolve their classpaths in one Maven probe and leave
|
||||
/// the others' cached; a probe another module breaks still resolves the first one.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn launch_modules_share_one_classpath_probe() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
fixture(root);
|
||||
write(root, "lib/src/main/java/demo/Lib.java", "class Lib {}");
|
||||
let script = root.join("mvnw");
|
||||
fs::write(
|
||||
&script,
|
||||
"#!/bin/sh\necho \"$@\" >> calls.txt\npl='.'\nwhile [ $# -gt 0 ]; do\nif [ \"$1\" = \"-pl\" ]; then pl=\"$2\"; shift 2; else shift; fi\ndone\ncase \"$pl\" in *lib*) [ -f lib/broken ] && exit 1;; esac\nfor m in $(echo \"$pl\" | tr ',' ' '); do mkdir -p \"$m/target\" repo; touch \"repo/$m.jar\"; printf \"$PWD/repo/$m.jar\" > \"$m/target/ide-compile-cp.txt\"; done\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let cache = root.join("cache");
|
||||
let cancel = CancellationToken::new();
|
||||
let calls = || fs::read_to_string(root.join("calls.txt")).unwrap_or_default().lines().count();
|
||||
let modules = [root.join("app"), root.join("lib"), root.join("app")];
|
||||
let app = module_classpaths(root, &model, &modules, false, None, &cache, &cancel).unwrap();
|
||||
assert!(app.contains("/repo/app.jar") && !app.contains("repo/lib.jar"), "{app}");
|
||||
assert_eq!(calls(), 1);
|
||||
assert!(fs::read_to_string(root.join("calls.txt")).unwrap().contains("-pl app,lib -am compile"));
|
||||
let lib = module_classpath(root, &model, &root.join("lib"), false, None, &cache, &cancel).unwrap();
|
||||
assert!(lib.contains("/repo/lib.jar"), "{lib}");
|
||||
assert_eq!(calls(), 1, "lib's classpath came from the shared probe");
|
||||
// A probe another module breaks is retried for the first module alone.
|
||||
write(root, "lib/src/main/java/demo/Lib.java", "class Lib { int changed; }");
|
||||
write(root, "lib/broken", "");
|
||||
let app = module_classpaths(root, &model, &[root.join("app"), root.join("lib")], false, None, &cache, &cancel)
|
||||
.unwrap();
|
||||
assert!(app.contains("/repo/app.jar"), "{app}");
|
||||
assert_eq!(calls(), 3, "the shared probe failed, then app was probed alone");
|
||||
// The first module's own failure stays its failure.
|
||||
assert!(module_classpath(root, &model, &root.join("lib"), false, None, &cache, &cancel).is_err());
|
||||
}
|
||||
|
||||
/// The launch classpath follows the Maven runner JDK and is reused until that
|
||||
/// build input changes; the probe does not run packaging plugins.
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -31,40 +31,6 @@ pub const LOCAL_REPO_TRACKING_ARG: &str = "-Daether.enhancedLocalRepository.trac
|
||||
pub const LIFECYCLE: &[&str] =
|
||||
&["clean", "validate", "compile", "test", "package", "verify", "install", "site", "deploy"];
|
||||
|
||||
/// Every phase of the clean, default and site lifecycles (Execute Maven Goal completion).
|
||||
pub const ALL_PHASES: &[&str] = &[
|
||||
"pre-clean",
|
||||
"clean",
|
||||
"post-clean",
|
||||
"validate",
|
||||
"initialize",
|
||||
"generate-sources",
|
||||
"process-sources",
|
||||
"generate-resources",
|
||||
"process-resources",
|
||||
"compile",
|
||||
"process-classes",
|
||||
"generate-test-sources",
|
||||
"process-test-sources",
|
||||
"generate-test-resources",
|
||||
"process-test-resources",
|
||||
"test-compile",
|
||||
"process-test-classes",
|
||||
"test",
|
||||
"prepare-package",
|
||||
"package",
|
||||
"pre-integration-test",
|
||||
"integration-test",
|
||||
"post-integration-test",
|
||||
"verify",
|
||||
"install",
|
||||
"deploy",
|
||||
"pre-site",
|
||||
"site",
|
||||
"post-site",
|
||||
"site-deploy",
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MavenModel {
|
||||
|
||||
@@ -3,7 +3,13 @@
|
||||
use super::MavenProject;
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::collections::HashSet;
|
||||
use std::fs::{self, File};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
|
||||
const SOURCE_REFRESH_WORKERS: usize = 4;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Artifact {
|
||||
@@ -11,6 +17,29 @@ pub struct Artifact {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub sources: PathBuf,
|
||||
binary: PathBuf,
|
||||
}
|
||||
|
||||
fn valid_part(part: &str) -> bool {
|
||||
!part.is_empty()
|
||||
&& part != "."
|
||||
&& part != ".."
|
||||
&& part.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
|
||||
}
|
||||
|
||||
fn modified_file(path: &Path) -> Option<SystemTime> {
|
||||
let metadata = fs::metadata(path).ok()?;
|
||||
if metadata.is_file() { metadata.modified().ok() } else { None }
|
||||
}
|
||||
|
||||
impl Artifact {
|
||||
fn stale_binary(&self) -> Option<SystemTime> {
|
||||
if !self.version.ends_with("-SNAPSHOT") {
|
||||
return None;
|
||||
}
|
||||
let binary = modified_file(&self.binary)?;
|
||||
(modified_file(&self.sources)? < binary).then_some(binary)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve only jars inside the selected local repository, including custom repositories.
|
||||
@@ -28,16 +57,14 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
}
|
||||
let n = parts.len();
|
||||
let (name, version, file) = (parts[n - 3], parts[n - 2], parts[n - 1]);
|
||||
let valid = |s: &str| {
|
||||
!s.is_empty() && s != "." && s != ".." && s.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c))
|
||||
};
|
||||
if !parts[..n - 1].iter().all(|s| valid(s)) || file != format!("{name}-{version}.jar") {
|
||||
if !parts[..n - 1].iter().all(|s| valid_part(s)) || file != format!("{name}-{version}.jar") {
|
||||
return None;
|
||||
}
|
||||
Some(Artifact {
|
||||
group: parts[..n - 3].join("."),
|
||||
name: name.into(),
|
||||
version: version.into(),
|
||||
binary: jar.to_owned(),
|
||||
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
|
||||
})
|
||||
}
|
||||
@@ -48,26 +75,58 @@ pub fn download(
|
||||
artifact: &Artifact,
|
||||
repository: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
resolve(root, project, artifact, repository, &[], artifact.stale_binary(), cancel)
|
||||
}
|
||||
|
||||
fn resolve(
|
||||
root: &Path,
|
||||
project: &MavenProject,
|
||||
artifact: &Artifact,
|
||||
repository: &Path,
|
||||
profile_args: &[String],
|
||||
stale: Option<SystemTime>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if artifact.sources.is_file() {
|
||||
if stale.is_none() && artifact.sources.is_file() {
|
||||
return Ok(Some(artifact.sources.clone()));
|
||||
}
|
||||
let mut args = vec!["-B".into(), "-N".into(), "-Dstyle.color=never".into()];
|
||||
args.extend(project.options.clone());
|
||||
args.extend([
|
||||
format!("-Dmaven.repo.local={}", repository.display()),
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get".into(),
|
||||
format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version),
|
||||
"-Dtransitive=false".into(),
|
||||
]);
|
||||
args.extend(project.options.iter().cloned());
|
||||
args.extend(profile_args.iter().cloned());
|
||||
args.push(format!("-Dmaven.repo.local={}", repository.display()));
|
||||
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
|
||||
let stage = if let Some(binary) = stale {
|
||||
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
|
||||
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
|
||||
let stage =
|
||||
tempfile::Builder::new().prefix(".openidea-sources-").tempdir_in(artifact.sources.parent().unwrap())?;
|
||||
args.extend([
|
||||
"-U".into(),
|
||||
"-Daether.artifactResolver.snapshotNormalization=false".into(),
|
||||
format!("{DEPENDENCY_PLUGIN}:copy"),
|
||||
coordinate,
|
||||
"-Dmdep.useBaseVersion=true".into(),
|
||||
format!("-DoutputDirectory={}", stage.path().display()),
|
||||
]);
|
||||
Some((stage, binary))
|
||||
} else {
|
||||
args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]);
|
||||
None
|
||||
};
|
||||
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if artifact.sources.is_file() {
|
||||
if let Some((stage, binary)) = stage {
|
||||
let resolved = stage.path().join(artifact.sources.file_name().unwrap());
|
||||
if output.success && resolved.is_file() {
|
||||
return replace_stale_sources(artifact, &resolved, binary, cancel);
|
||||
}
|
||||
} else if artifact.sources.is_file() {
|
||||
return Ok(Some(artifact.sources.clone()));
|
||||
}
|
||||
let coordinate = format!("{}:{}:jar:sources:{}", artifact.group, artifact.name, artifact.version);
|
||||
@@ -83,6 +142,115 @@ pub fn download(
|
||||
))
|
||||
}
|
||||
|
||||
fn replace_stale_sources(
|
||||
artifact: &Artifact,
|
||||
resolved: &Path,
|
||||
binary: SystemTime,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<PathBuf>> {
|
||||
// Maven can fall back to a locally installed snapshot. Keep its timestamp if it returned
|
||||
// the same bytes so a later reload can retry when newer sources are available.
|
||||
let hash = |path| -> std::io::Result<_> { Ok(blake3::Hasher::new().update_reader(File::open(path)?)?.finalize()) };
|
||||
if hash(resolved)? == hash(&artifact.sources)? {
|
||||
return Ok(None);
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match artifact.stale_binary() {
|
||||
Some(current) if current == binary => {
|
||||
File::options().write(true).open(resolved)?.set_modified(SystemTime::now().max(binary))?;
|
||||
fs::rename(resolved, &artifact.sources)?;
|
||||
Ok(Some(artifact.sources.clone()))
|
||||
}
|
||||
None if artifact.sources.is_file() => Ok(Some(artifact.sources.clone())),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolved Maven dependencies with an existing attachment. Binaries may still be
|
||||
/// updating during import, so freshness is checked when the refresh runs.
|
||||
pub fn cached_snapshots<'a>(
|
||||
repository: &Path,
|
||||
projects: impl Iterator<Item = (usize, &'a MavenProject)>,
|
||||
) -> Vec<(usize, Artifact)> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut candidates = Vec::new();
|
||||
for (owner, project) in projects {
|
||||
let mut dependencies: Vec<_> = project.dependencies.iter().collect();
|
||||
while let Some(dep) = dependencies.pop() {
|
||||
if !dep.resolved() {
|
||||
continue;
|
||||
}
|
||||
dependencies.extend(&dep.children);
|
||||
let Some(version) = dep.version.as_deref().filter(|v| v.ends_with("-SNAPSHOT") && valid_part(v)) else {
|
||||
continue;
|
||||
};
|
||||
if dep.scope == "system"
|
||||
|| dep.classifier.is_some()
|
||||
|| !matches!(dep.kind.as_str(), "jar" | "bundle" | "maven-plugin" | "ejb")
|
||||
|| !valid_part(&dep.artifact_id)
|
||||
|| !dep.group_id.split('.').all(valid_part)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let name = &dep.artifact_id;
|
||||
let jar = repository
|
||||
.join(dep.group_id.replace('.', "/"))
|
||||
.join(name)
|
||||
.join(version)
|
||||
.join(format!("{name}-{version}.jar"));
|
||||
if let Some(artifact) = artifact(&jar, repository)
|
||||
&& artifact.sources.is_file()
|
||||
&& seen.insert(jar)
|
||||
{
|
||||
candidates.push((owner, artifact));
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
/// Refresh only previously attached snapshots. Maven subprocesses are bounded
|
||||
/// and share the build reload's cancellation token.
|
||||
pub fn refresh_snapshots(
|
||||
root: &Path,
|
||||
projects: &[MavenProject],
|
||||
repository: &Path,
|
||||
candidates: &[(usize, Artifact)],
|
||||
profiles: &[String],
|
||||
cancel: &CancellationToken,
|
||||
) -> Vec<PathBuf> {
|
||||
let profile_args = if profiles.is_empty() { vec![] } else { vec![format!("-P{}", profiles.join(","))] };
|
||||
let profile_args = &profile_args;
|
||||
let stale: Vec<_> = candidates.iter().filter(|(_, artifact)| artifact.stale_binary().is_some()).collect();
|
||||
let batch_size = stale.len().div_ceil(SOURCE_REFRESH_WORKERS).max(1);
|
||||
std::thread::scope(|scope| {
|
||||
let workers: Vec<_> = stale
|
||||
.chunks(batch_size)
|
||||
.map(|batch| {
|
||||
scope.spawn(move || {
|
||||
let mut refreshed = Vec::new();
|
||||
for (owner, artifact) in batch.iter().copied() {
|
||||
if cancel.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
let Some(binary) = artifact.stale_binary() else { continue };
|
||||
match resolve(root, &projects[*owner], artifact, repository, profile_args, Some(binary), cancel)
|
||||
{
|
||||
Ok(Some(_)) => refreshed.push(artifact.binary.clone()),
|
||||
Ok(None) => {}
|
||||
Err(e) => tracing::debug!(path = %artifact.sources.display(), "Maven sources refresh: {e}"),
|
||||
}
|
||||
}
|
||||
refreshed
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
workers.into_iter().flat_map(|worker| worker.join().expect("Maven sources worker")).collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -121,4 +289,86 @@ mod tests {
|
||||
assert_eq!(artifact(Path::new(path), repository), None, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
|
||||
use crate::maven::{MavenDependency, Omission};
|
||||
|
||||
let repo = tempfile::tempdir().unwrap();
|
||||
let dependency = |name: &str, version: &str, cached: bool| {
|
||||
if cached {
|
||||
let dir = repo.path().join("example").join(name).join(version);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(dir.join(format!("{name}-{version}-sources.jar")), b"cached").unwrap();
|
||||
}
|
||||
MavenDependency {
|
||||
group_id: "example".into(),
|
||||
artifact_id: name.into(),
|
||||
version: Some(version.into()),
|
||||
kind: "jar".into(),
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
let transitive = dependency("transitive", "1-SNAPSHOT", true);
|
||||
let direct = MavenDependency { children: vec![transitive.clone()], ..dependency("direct", "1-SNAPSHOT", true) };
|
||||
let omitted =
|
||||
MavenDependency { omitted: Some(Omission::Conflict), ..dependency("omitted", "1-SNAPSHOT", true) };
|
||||
let projects = [
|
||||
MavenProject {
|
||||
dependencies: vec![
|
||||
direct,
|
||||
omitted,
|
||||
dependency("missing", "1-SNAPSHOT", false),
|
||||
dependency("release", "1", true),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
MavenProject { dependencies: vec![transitive], ..Default::default() },
|
||||
];
|
||||
let mut found: Vec<_> = cached_snapshots(repo.path(), projects.iter().enumerate())
|
||||
.into_iter()
|
||||
.map(|(owner, artifact)| (owner, artifact.name))
|
||||
.collect();
|
||||
found.sort();
|
||||
assert_eq!(found, [(0, "direct".into()), (0, "transitive".into())]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn downloads_sources_again_when_the_snapshot_binary_is_newer() {
|
||||
use std::fs::FileTimes;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::Duration;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let repository = dir.path().join("repository");
|
||||
let jar = repository.join("example/lib/1-SNAPSHOT/lib-1-SNAPSHOT.jar");
|
||||
fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
fs::write(&jar, b"new binary").unwrap();
|
||||
let artifact = artifact(&jar, &repository).unwrap();
|
||||
fs::write(&artifact.sources, b"old sources").unwrap();
|
||||
File::open(&artifact.sources)
|
||||
.unwrap()
|
||||
.set_times(FileTimes::new().set_modified(SystemTime::now() - Duration::from_secs(60)))
|
||||
.unwrap();
|
||||
let launcher = dir.path().join("mvn");
|
||||
fs::write(
|
||||
&launcher,
|
||||
"#!/bin/sh\nfor arg do\n case \"$arg\" in\n -DoutputDirectory=*) out=\"${arg#*=}\" ;;\n esac\ndone\nprintf 'new sources' > \"$out/lib-1-SNAPSHOT-sources.jar\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&launcher, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
assert!(download(dir.path(), &MavenProject::default(), &artifact, &repository, &cancel).is_err());
|
||||
assert_eq!(fs::read(&artifact.sources).unwrap(), b"old sources");
|
||||
let project = MavenProject { command: launcher.to_string_lossy().into_owned(), ..Default::default() };
|
||||
let cancel = CancellationToken::new();
|
||||
let path = download(dir.path(), &project, &artifact, &repository, &cancel).unwrap().unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), b"new sources");
|
||||
assert_eq!(
|
||||
download(dir.path(), &MavenProject::default(), &artifact, &repository, &CancellationToken::new()).unwrap(),
|
||||
Some(path)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,21 @@ pub(crate) const MAX_LINE_BYTES: usize = 1024 * 1024;
|
||||
/// `Output::text` stops growing past this while the pipes keep draining: a chatty build can
|
||||
/// print far more than is ever parsed back out of the retained copy.
|
||||
pub(crate) const MAX_TEXT_BYTES: usize = 32 * 1024 * 1024;
|
||||
/// Lines the pipe readers may queue ahead of the consumer. A build printing faster than
|
||||
/// `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;
|
||||
/// What [`pump_bounded`] reads from a pipe at a time.
|
||||
const PUMP_CHUNK: usize = 64 * 1024;
|
||||
|
||||
/// One line of a child's output, with the stream it came from.
|
||||
type Line = (Stream, String);
|
||||
|
||||
/// The queue from the pipe readers to the consumer: bounded, so the readers wait while the
|
||||
/// consumer is behind.
|
||||
fn line_queue() -> (mpsc::SyncSender<Line>, mpsc::Receiver<Line>) {
|
||||
mpsc::sync_channel(LINE_QUEUE)
|
||||
}
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub success: bool,
|
||||
@@ -33,20 +48,20 @@ pub(crate) struct Output {
|
||||
pub truncated: bool,
|
||||
}
|
||||
|
||||
/// Bounded pump for callers that stream every line and only summarize errors: reads fixed
|
||||
/// 64 KiB chunks, splits newline-free runs at a UTF-8 char boundary at the line cap, and
|
||||
/// never grows one line buffer without bound.
|
||||
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::Sender<(Stream, String)>) {
|
||||
/// Bounded pump for callers that stream every line and only summarize errors: reads
|
||||
/// [`PUMP_CHUNK`] chunks, splits newline-free runs at a UTF-8 char boundary at the line cap,
|
||||
/// and never grows one line buffer without bound.
|
||||
fn pump_bounded(stream: Box<dyn Read + Send>, kind: Stream, tx: &mpsc::SyncSender<Line>) {
|
||||
let mut reader = BufReader::new(stream);
|
||||
// `terminated`: the buffer ends in the stream's newline. A segment cut from a
|
||||
// newline-free run at the line cap must keep a trailing `\r` — it is data.
|
||||
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::Sender<(Stream, String)>| {
|
||||
let send = |buf: &mut Vec<u8>, terminated: bool, tx: &mpsc::SyncSender<Line>| {
|
||||
let line = ide_core::output_encoding::decode_tool_output(buf);
|
||||
let line = if terminated { line.trim_end_matches(['\n', '\r']).to_owned() } else { line };
|
||||
buf.clear();
|
||||
tx.send((kind, line)).is_ok()
|
||||
};
|
||||
let mut chunk = vec![0u8; 64 * 1024];
|
||||
let mut chunk = vec![0u8; PUMP_CHUNK];
|
||||
let mut line: Vec<u8> = Vec::with_capacity(256);
|
||||
'read: loop {
|
||||
let n = match reader.read(&mut chunk) {
|
||||
@@ -179,8 +194,8 @@ fn run_with_env_capture(
|
||||
}
|
||||
let mut child =
|
||||
command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {}: {e}", program.display())))?;
|
||||
let (tx, rx) = mpsc::channel::<(Stream, String)>();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::SyncSender<Line>| {
|
||||
std::thread::spawn(move || {
|
||||
if bounded {
|
||||
pump_bounded(stream, kind, &tx);
|
||||
@@ -212,7 +227,8 @@ fn run_with_env_capture(
|
||||
// Retained copy of the output: the first half of the cap, then — once output overflows —
|
||||
// a rolling tail instead of the middle. Error summaries read the end of the output, while
|
||||
// listings parsed out of a successful run read from the start. The pipes keep draining
|
||||
// either way: `on_line` still sees every line, so the child never blocks on a full pipe.
|
||||
// either way: `on_line` still sees every line, and the child waits on its pipe only
|
||||
// while `on_line` is behind, never because the retained copy is full.
|
||||
let cap = MAX_TEXT_BYTES / 2;
|
||||
let mut head = String::new();
|
||||
let mut tail: std::collections::VecDeque<Vec<u8>> = Default::default();
|
||||
@@ -295,6 +311,9 @@ fn run_with_env_capture(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
#[test]
|
||||
fn a_model_line_over_one_mebibyte_is_kept_whole_for_the_parsers() {
|
||||
@@ -500,4 +519,124 @@ mod tests {
|
||||
assert!(out.text.starts_with("pad\n"));
|
||||
assert!(out.text.ends_with("FATAL: the real error\n"));
|
||||
}
|
||||
|
||||
/// Numbered lines of `LINE_LEN` bytes each, counting the bytes taken: a pipe stand-in that
|
||||
/// reports when it is dropped, which is when the pump owning it ends.
|
||||
const LINE_LEN: usize = 100;
|
||||
|
||||
struct NumberedLines {
|
||||
next: usize,
|
||||
lines: usize,
|
||||
taken: Arc<AtomicUsize>,
|
||||
gone: mpsc::Sender<()>,
|
||||
}
|
||||
|
||||
fn numbered(n: usize) -> String {
|
||||
format!("{n:0width$}", width = LINE_LEN - 1)
|
||||
}
|
||||
|
||||
impl Read for NumberedLines {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let mut n = 0;
|
||||
while self.next < self.lines && n + LINE_LEN <= buf.len() {
|
||||
buf[n..n + LINE_LEN - 1].copy_from_slice(numbered(self.next).as_bytes());
|
||||
buf[n + LINE_LEN - 1] = b'\n';
|
||||
self.next += 1;
|
||||
n += LINE_LEN;
|
||||
}
|
||||
self.taken.fetch_add(n, Ordering::SeqCst);
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for NumberedLines {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.gone.send(());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_consumer_holds_the_pump_back_instead_of_queueing_every_line() {
|
||||
const LINES: usize = 50_000;
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let (gone, _) = mpsc::channel();
|
||||
let pipe = NumberedLines { next: 0, lines: LINES, taken: taken.clone(), gone };
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
|
||||
let (mut count, mut peak) = (0usize, 0usize);
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok((stream, line)) => {
|
||||
assert_eq!(stream, Stream::Stdout);
|
||||
assert_eq!(line, numbered(count), "a line arrived out of order or damaged");
|
||||
// Read from the pipe but not yet handed over: the rest of the chunk the pump
|
||||
// is cutting into lines, and the queue.
|
||||
peak = peak.max(taken.load(Ordering::SeqCst) - count * LINE_LEN);
|
||||
count += 1;
|
||||
// A consumer that cannot keep up with the process.
|
||||
if count.is_multiple_of(LINE_QUEUE) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => panic!("the pump stalled"),
|
||||
}
|
||||
}
|
||||
pump.join().unwrap();
|
||||
assert_eq!(count, LINES);
|
||||
let bound = PUMP_CHUNK + (LINE_QUEUE + 2) * LINE_LEN;
|
||||
assert!(peak <= bound, "{peak} bytes read ahead of the consumer, more than {bound}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pump_blocked_on_a_full_queue_ends_when_the_consumer_is_gone() {
|
||||
let taken = Arc::new(AtomicUsize::new(0));
|
||||
let (gone_tx, gone) = mpsc::channel();
|
||||
// Far more than the queue and a few chunks hold.
|
||||
let pipe = NumberedLines { next: 0, lines: 100_000, taken: taken.clone(), gone: gone_tx };
|
||||
let (tx, rx) = line_queue();
|
||||
let pump = std::thread::spawn(move || pump_bounded(Box::new(pipe), Stream::Stdout, &tx));
|
||||
// A consumer that takes nothing: the queue fills, with the pump inside its first chunk.
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while taken.load(Ordering::SeqCst) == 0 {
|
||||
assert!(Instant::now() < deadline, "the pump never read");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
// Time for a pump that does not wait to run ahead.
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
assert!(taken.load(Ordering::SeqCst) <= PUMP_CHUNK, "the pump read past a full queue");
|
||||
assert!(gone.try_recv().is_err(), "the pump ended while its consumer was still there");
|
||||
drop(rx);
|
||||
gone.recv_timeout(Duration::from_secs(30)).expect("the pump stayed blocked after the consumer was gone");
|
||||
pump.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slow_on_line_still_sees_every_line_in_order_and_the_exit_status() {
|
||||
if cfg!(windows) {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let args = ["-c".into(), "awk 'BEGIN{for(i=1;i<=300000;i++)print i}'; exit 4".into()];
|
||||
for bounded in [false, true] {
|
||||
let mut next = 1usize;
|
||||
let on_line = |stream: Stream, line: &str| {
|
||||
assert_eq!(stream, Stream::Stdout);
|
||||
assert_eq!(line, next.to_string());
|
||||
next += 1;
|
||||
if next.is_multiple_of(1000) {
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
};
|
||||
let cancel = CancellationToken::new();
|
||||
let out = if bounded {
|
||||
run_bounded("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
|
||||
} else {
|
||||
run("sh", &args, tmp.path(), &BTreeMap::new(), &cancel, on_line)
|
||||
}
|
||||
.unwrap();
|
||||
assert!(!out.success);
|
||||
assert_eq!(next, 300_001, "lines were lost");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
dunce.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
//! Runs a tool's CLI (`docker`, `gh`, `adb`) as a child process: bounded runs that collect
|
||||
//! its output, and cancellable streams that hand over its output line by line.
|
||||
//!
|
||||
//! Every child leads its own process group ([`own_group`]), so cancelling or timing out
|
||||
//! reaches what it started in turn (`gh` → `git`, `docker` → CLI plugins such as compose).
|
||||
//! They get [`KILL_GRACE`] to exit on `SIGTERM` and clean up (git removes its lock files)
|
||||
//! before `SIGKILL`.
|
||||
|
||||
use crate::process::{own_group, prepare, terminate_tree};
|
||||
use crate::{CancellationToken, IdeError, IdeResult};
|
||||
use std::borrow::Cow;
|
||||
use std::io::{Read, Write};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a cancelled or timed-out child's process group gets to exit on `SIGTERM`
|
||||
/// before `SIGKILL`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
/// How many of a streamed child's last non-blank stderr lines are kept for its error message.
|
||||
const STDERR_TAIL: usize = 20;
|
||||
|
||||
/// How a tool's output bytes become text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Decoding {
|
||||
/// [`decode_tool_output`](crate::output_encoding::decode_tool_output): UTF-8, and on
|
||||
/// Windows the system code page for what is not.
|
||||
ToolOutput,
|
||||
/// UTF-8, invalid bytes replaced by U+FFFD.
|
||||
Utf8Lossy,
|
||||
}
|
||||
|
||||
impl Decoding {
|
||||
fn decode(self, bytes: &[u8]) -> Cow<'_, str> {
|
||||
match self {
|
||||
Decoding::ToolOutput => Cow::Owned(crate::output_encoding::decode_tool_output(bytes)),
|
||||
Decoding::Utf8Lossy => String::from_utf8_lossy(bytes),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a child's stdin is fed with, and how.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Input<'a> {
|
||||
/// Written before the output is read, then closed: only for input small enough
|
||||
/// (a password) to fit the pipe, as a full pipe blocks the caller.
|
||||
Inline(&'a str),
|
||||
/// Written by a thread of its own, then closed: a large body must not block on a full
|
||||
/// pipe while the child is not reading yet.
|
||||
Threaded(&'a str),
|
||||
}
|
||||
|
||||
/// How a streamed child's `\r` is read.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CarriageReturn {
|
||||
/// Ends a line like `\n`: progress output rewrites its line in place.
|
||||
EndsLine,
|
||||
/// Is dropped; only `\n` ends a line.
|
||||
Dropped,
|
||||
}
|
||||
|
||||
/// What a bounded run collected.
|
||||
pub struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
/// Which pipe a streamed line came from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Stream {
|
||||
Stdout,
|
||||
Stderr,
|
||||
}
|
||||
|
||||
/// One tool's CLI: its name for error messages and how its output is decoded.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CliTool {
|
||||
name: &'static str,
|
||||
decoding: Decoding,
|
||||
}
|
||||
|
||||
impl CliTool {
|
||||
pub const fn new(name: &'static str, decoding: Decoding) -> Self {
|
||||
Self { name, decoding }
|
||||
}
|
||||
|
||||
fn spawn(self, cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run {}: {e}", self.name)))
|
||||
}
|
||||
|
||||
/// Pipes stdout and stderr, closes stdin and starts the child in its own process group.
|
||||
fn configure(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
prepare(own_group(cmd));
|
||||
}
|
||||
|
||||
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
|
||||
/// a non-zero exit is reported in [`Output::success`], not as an error.
|
||||
pub fn run(self, cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
self.run_with_input(cmd, None, timeout, cancel)
|
||||
}
|
||||
|
||||
/// [`run`](Self::run) with `input` written to the child's stdin and then closed.
|
||||
pub fn run_with_input(
|
||||
self,
|
||||
mut cmd: Command,
|
||||
input: Option<Input>,
|
||||
timeout: Duration,
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> IdeResult<Output> {
|
||||
Self::configure(&mut cmd);
|
||||
if input.is_some() {
|
||||
cmd.stdin(Stdio::piped());
|
||||
}
|
||||
let mut child = self.spawn(&mut cmd)?;
|
||||
match (input, child.stdin.take()) {
|
||||
(Some(Input::Inline(text)), Some(mut stdin)) => {
|
||||
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
|
||||
let _ = stdin.write_all(text.as_bytes());
|
||||
}
|
||||
(Some(Input::Threaded(text)), Some(mut stdin)) => {
|
||||
let text = text.to_owned();
|
||||
std::thread::spawn(move || {
|
||||
let _ = stdin.write_all(text.as_bytes());
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let decoding = self.decoding;
|
||||
let out = child.stdout.take().map(|pipe| read_all(pipe, decoding));
|
||||
let err = child.stderr.take().map(|pipe| read_all(pipe, decoding));
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::unavailable(format!("{} did not respond in time", self.name)));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(Output {
|
||||
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
success: status.success(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
|
||||
/// fires. Returns whether it exited successfully plus the last stderr lines.
|
||||
pub fn stream(
|
||||
self,
|
||||
cmd: Command,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &mut dyn FnMut(Stream, String),
|
||||
) -> IdeResult<(bool, Vec<String>)> {
|
||||
let mut lines = self.lines(cmd, cancel, CarriageReturn::EndsLine)?;
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
loop {
|
||||
match lines.poll(cancel, Duration::from_millis(50))? {
|
||||
Poll::Line(stream, line) => {
|
||||
if stream == Stream::Stderr && !line.trim().is_empty() {
|
||||
keep_stderr_line(&mut stderr_tail, line.clone());
|
||||
}
|
||||
on_line(stream, line);
|
||||
}
|
||||
Poll::Closed | Poll::Timeout => {}
|
||||
Poll::Finished => break,
|
||||
}
|
||||
}
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
}
|
||||
|
||||
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
|
||||
/// (see [`Lines::poll`]). Fails when `cancel` has already fired, without starting it.
|
||||
pub fn lines(self, mut cmd: Command, cancel: &CancellationToken, cr: CarriageReturn) -> IdeResult<Lines> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
Self::configure(&mut cmd);
|
||||
let mut child = self.spawn(&mut cmd)?;
|
||||
let (tx, rx) = mpsc::channel::<Event>();
|
||||
let mut open = 0;
|
||||
if let Some(out) = child.stdout.take() {
|
||||
spawn_reader(out, tx.clone(), Stream::Stdout, self.decoding, cr);
|
||||
open += 1;
|
||||
}
|
||||
if let Some(err) = child.stderr.take() {
|
||||
spawn_reader(err, tx.clone(), Stream::Stderr, self.decoding, cr);
|
||||
open += 1;
|
||||
}
|
||||
drop(tx);
|
||||
Ok(Lines { child, rx, open })
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends a stderr line to `tail`, which keeps only the last [`STDERR_TAIL`].
|
||||
pub fn keep_stderr_line(tail: &mut Vec<String>, line: String) {
|
||||
tail.push(line);
|
||||
if tail.len() > STDERR_TAIL {
|
||||
tail.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static, decoding: Decoding) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
decoding.decode(&buf).into_owned()
|
||||
})
|
||||
}
|
||||
|
||||
enum Event {
|
||||
Line(Stream, String),
|
||||
Closed,
|
||||
}
|
||||
|
||||
fn spawn_reader(
|
||||
mut pipe: impl Read + Send + 'static,
|
||||
tx: mpsc::Sender<Event>,
|
||||
stream: Stream,
|
||||
decoding: Decoding,
|
||||
cr: CarriageReturn,
|
||||
) {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
let mut pending: Vec<u8> = Vec::new();
|
||||
let flush = |pending: &mut Vec<u8>| {
|
||||
if !pending.is_empty() {
|
||||
let line = decoding.decode(pending).trim_end().to_string();
|
||||
pending.clear();
|
||||
let _ = tx.send(Event::Line(stream, line));
|
||||
}
|
||||
};
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
for &b in &buf[..n] {
|
||||
if b == b'\n' || (b == b'\r' && cr == CarriageReturn::EndsLine) {
|
||||
flush(&mut pending);
|
||||
} else if b != b'\r' {
|
||||
pending.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(&mut pending);
|
||||
let _ = tx.send(Event::Closed);
|
||||
});
|
||||
}
|
||||
|
||||
/// A running child whose output lines are read by threads: see [`CliTool::lines`].
|
||||
pub struct Lines {
|
||||
child: Child,
|
||||
rx: mpsc::Receiver<Event>,
|
||||
/// Pipes whose reader has not reported its end yet.
|
||||
open: usize,
|
||||
}
|
||||
|
||||
/// What [`Lines::poll`] saw.
|
||||
pub enum Poll {
|
||||
Line(Stream, String),
|
||||
/// A pipe reached its end.
|
||||
Closed,
|
||||
/// Nothing arrived within the wait.
|
||||
Timeout,
|
||||
/// Every pipe is at its end.
|
||||
Finished,
|
||||
}
|
||||
|
||||
impl Lines {
|
||||
/// Waits up to `wait` for the next line. Fails, after killing the child, when `cancel` has fired.
|
||||
pub fn poll(&mut self, cancel: &CancellationToken, wait: Duration) -> IdeResult<Poll> {
|
||||
if self.open == 0 {
|
||||
return Ok(Poll::Finished);
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut self.child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match self.rx.recv_timeout(wait) {
|
||||
Ok(Event::Line(stream, line)) => Ok(Poll::Line(stream, line)),
|
||||
Ok(Event::Closed) => {
|
||||
self.open -= 1;
|
||||
Ok(Poll::Closed)
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => Ok(Poll::Timeout),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => {
|
||||
self.open = 0;
|
||||
Ok(Poll::Finished)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
|
||||
/// killing it, when `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
|
||||
let status = loop {
|
||||
if let Some(status) = self.child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut self.child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(status.success())
|
||||
}
|
||||
}
|
||||
@@ -288,6 +288,8 @@ pub struct SmartKeysSettings {
|
||||
pub pair_quotes: bool,
|
||||
pub surround_selection: bool,
|
||||
pub tab_out_of_pair: bool,
|
||||
/// A `;` typed before the closing `)` of a statement goes to the end of the statement.
|
||||
pub semicolon_at_statement_end: bool,
|
||||
/// Simultaneous `<tag></tag>` editing: renaming a tag renames its matching tag.
|
||||
pub simultaneous_tag_editing: bool,
|
||||
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
|
||||
@@ -309,6 +311,7 @@ impl Default for SmartKeysSettings {
|
||||
pair_quotes: true,
|
||||
surround_selection: true,
|
||||
tab_out_of_pair: true,
|
||||
semicolon_at_statement_end: true,
|
||||
simultaneous_tag_editing: true,
|
||||
reformat_on_paste: "indentEachLine".into(),
|
||||
escape_on_paste: true,
|
||||
@@ -435,6 +438,9 @@ pub struct TextAttributesOverride {
|
||||
pub effect: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub effect_color: Option<String>,
|
||||
/// IDEA's `ERROR_STRIPE_COLOR`: the diff overview-lane marker of a change type.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error_stripe_color: Option<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit).
|
||||
|
||||
@@ -20,7 +20,72 @@ pub struct IdeError {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum ErrorData {
|
||||
Tool { tool: String, missing: bool },
|
||||
Tool {
|
||||
tool: String,
|
||||
missing: bool,
|
||||
},
|
||||
/// A non-fast-forward push from the current branch to its configured upstream.
|
||||
PushRejected {
|
||||
source: String,
|
||||
upstream: String,
|
||||
divergence: Option<Box<PushDivergence>>,
|
||||
/// Other refs may already have been published in the same push.
|
||||
#[specta(optional)]
|
||||
report: Option<Box<PushReport>>,
|
||||
},
|
||||
/// Git updated some refs before a later ref or push URL failed.
|
||||
PushPartiallyApplied {
|
||||
report: Box<PushReport>,
|
||||
},
|
||||
/// A conflicted history replay left an amend commit ready to keep separately.
|
||||
AmendConflict {
|
||||
commit: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Git's reported result for each destination ref. A remote with several push URLs can
|
||||
/// report more than one result for the same ref.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct PushReport {
|
||||
pub remote: Option<String>,
|
||||
pub refs: Vec<PushRefResult>,
|
||||
}
|
||||
|
||||
impl PushReport {
|
||||
pub fn new(remote: Option<String>) -> Self {
|
||||
Self { remote, refs: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct PushRefResult {
|
||||
pub reference: String,
|
||||
pub status: PushRefStatus,
|
||||
/// The number of commits between the tips Git reports for a fast-forward.
|
||||
pub commits: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum PushRefStatus {
|
||||
FastForward,
|
||||
Forced,
|
||||
Created,
|
||||
UpToDate,
|
||||
Deleted,
|
||||
}
|
||||
|
||||
/// The two tips shown in the rejected-push dialog. A retry must use this lease
|
||||
/// even if a fetch advances the remote-tracking branch while the dialog is open.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PushDivergence {
|
||||
pub source: String,
|
||||
pub remote: String,
|
||||
pub target: String,
|
||||
pub local_tip: String,
|
||||
pub remote_tip: String,
|
||||
pub remote_commits: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -30,7 +95,7 @@ pub enum ErrorKind {
|
||||
AlreadyExists,
|
||||
PermissionDenied,
|
||||
InvalidInput,
|
||||
/// Document version mismatch; the UI must resync the full text.
|
||||
/// The requested state is stale; the UI must use the current snapshot.
|
||||
OutOfSync,
|
||||
Cancelled,
|
||||
TimedOut,
|
||||
@@ -115,4 +180,13 @@ mod tests {
|
||||
serde_json::json!({"kind":"unavailable","message":"no server","data":null})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_tracked_push_rejections_need_no_report() {
|
||||
let data: ErrorData = serde_json::from_str(
|
||||
r#"{"type":"pushRejected","source":"main","upstream":"origin/main","divergence":null}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(data, ErrorData::PushRejected { report: None, .. }));
|
||||
}
|
||||
}
|
||||
@@ -40,10 +40,11 @@ pub enum IdeEvent {
|
||||
McpBackgroundProjectsChanged,
|
||||
/// A window entered or left full screen, itself or as a member of a full-screen window group.
|
||||
WindowFullscreenChanged,
|
||||
/// This remote window's connection to its host ended on its own (network loss, the host or
|
||||
/// its server went away); the window's project is unreachable until it reconnects.
|
||||
/// This remote window's connection ended or another window took over the session.
|
||||
RemoteConnectionLost {
|
||||
host: String,
|
||||
#[serde(default)]
|
||||
taken_over: bool,
|
||||
},
|
||||
ProjectTrustChanged {
|
||||
root: crate::IpcPath,
|
||||
@@ -324,6 +325,8 @@ pub enum LspRefreshKind {
|
||||
InlayHints,
|
||||
SemanticTokens,
|
||||
CodeLens,
|
||||
/// An import or classpath update may have changed inheritance search results.
|
||||
Inheritance,
|
||||
/// The Dart server published a document's Flutter outline.
|
||||
FlutterOutline,
|
||||
}
|
||||
|
||||
@@ -71,6 +71,11 @@ pub struct SpellingSettings {
|
||||
pub project_words: Vec<String>,
|
||||
/// Custom dictionaries: plain word lists or Hunspell `.dic` files.
|
||||
pub custom_dictionaries: Vec<String>,
|
||||
/// Where "Save '…' to dictionary" writes: `project`, `application`, or a
|
||||
/// `spelling.customDictionaries` entry verbatim; empty (the default) is
|
||||
/// project when one is open, application otherwise.
|
||||
#[specta(optional)]
|
||||
pub default_dictionary: Option<String>,
|
||||
}
|
||||
|
||||
/// Changes to one inspection; absent fields keep the inspection's defaults.
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Binary arguments of IPC commands travel as base64 text: [`IpcBytes`] is a `Vec<u8>` that
|
||||
//! serializes as a standard padded base64 string and is a plain `string` in the generated
|
||||
//! bindings.
|
||||
//!
|
||||
//! A plain `Vec<u8>` is a JSON array of numbers, 3.6 times the size of the bytes, and parsing it
|
||||
//! into a `serde_json::Value` (the remote protocol and Tauri both do) takes about 50 times the
|
||||
//! bytes in memory: 20 MB become about 1 GB. Base64 is 1.33 times the size and one string.
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use serde::de::{self, Visitor};
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::fmt;
|
||||
use std::ops::Deref;
|
||||
|
||||
/// A binary argument or result of an IPC command.
|
||||
#[derive(Clone, Default, PartialEq, Eq, specta::Type)]
|
||||
#[specta(transparent)]
|
||||
pub struct IpcBytes(#[specta(type = String)] pub Vec<u8>);
|
||||
|
||||
impl IpcBytes {
|
||||
pub fn into_vec(self) -> Vec<u8> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for IpcBytes {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "IpcBytes({} bytes)", self.0.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for IpcBytes {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&STANDARD.encode(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for IpcBytes {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
struct Base64;
|
||||
impl Visitor<'_> for Base64 {
|
||||
type Value = IpcBytes;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("a base64 string")
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(self, v: &str) -> Result<IpcBytes, E> {
|
||||
STANDARD.decode(v).map(IpcBytes).map_err(|e| E::custom(format!("invalid base64: {e}")))
|
||||
}
|
||||
}
|
||||
d.deserialize_str(Base64)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for IpcBytes {
|
||||
type Target = [u8];
|
||||
fn deref(&self) -> &[u8] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Vec<u8>> for IpcBytes {
|
||||
fn from(bytes: Vec<u8>) -> Self {
|
||||
Self(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn round_trip(bytes: Vec<u8>) {
|
||||
let value = serde_json::to_value(IpcBytes(bytes.clone())).unwrap();
|
||||
let text = value.as_str().expect("serializes as a string");
|
||||
assert_eq!(text.len(), bytes.len().div_ceil(3) * 4);
|
||||
assert_eq!(serde_json::from_value::<IpcBytes>(value).unwrap().into_vec(), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_empty_every_byte_and_large_input() {
|
||||
round_trip(Vec::new());
|
||||
round_trip((0..=255).collect());
|
||||
round_trip((0..=255).rev().cycle().take(5 * 1024 * 1024 + 1).collect());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_a_json_document() {
|
||||
let bytes: Vec<u8> = (0..=255).collect();
|
||||
let text = serde_json::to_string(&json!({ "data": IpcBytes(bytes.clone()) })).unwrap();
|
||||
#[derive(Deserialize)]
|
||||
struct Args {
|
||||
data: IpcBytes,
|
||||
}
|
||||
assert_eq!(serde_json::from_str::<Args>(&text).unwrap().data.into_vec(), bytes);
|
||||
}
|
||||
|
||||
/// The old wire form of a `Vec<u8>`: 3.6 times the bytes. The string must stay near 4/3.
|
||||
#[test]
|
||||
fn serialized_form_is_a_string_about_a_third_larger_than_the_bytes() {
|
||||
let bytes: Vec<u8> = (0..=255).cycle().take(1_000_000).collect();
|
||||
let json = serde_json::to_string(&IpcBytes(bytes.clone())).unwrap();
|
||||
assert!(json.starts_with('"') && json.ends_with('"'));
|
||||
assert!(json.len() <= bytes.len().div_ceil(3) * 4 + 2, "{} bytes for {}", json.len(), bytes.len());
|
||||
let as_array = serde_json::to_string(&bytes).unwrap();
|
||||
assert!(json.len() * 2 < as_array.len(), "{} vs {}", json.len(), as_array.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_what_is_not_base64() {
|
||||
for bad in [json!([1, 2, 3]), json!(7), Value::Null, json!("not base64!"), json!("QQ"), json!("QQ=a")] {
|
||||
assert!(serde_json::from_value::<IpcBytes>(bad.clone()).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_does_not_print_the_bytes() {
|
||||
assert_eq!(format!("{:?}", IpcBytes(vec![0; 3])), "IpcBytes(3 bytes)");
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,10 @@ pub fn strip(src: &str) -> String {
|
||||
if prev == '*' && n == '/' {
|
||||
break;
|
||||
}
|
||||
// Keep the comment's line breaks so parse errors report the original line.
|
||||
if n == '\n' {
|
||||
out.push('\n');
|
||||
}
|
||||
prev = n;
|
||||
}
|
||||
}
|
||||
@@ -65,7 +69,7 @@ pub fn strip(src: &str) -> String {
|
||||
in_str = true;
|
||||
cleaned.push(c);
|
||||
} else if c == ',' {
|
||||
let next = bytes[i + 1..].iter().find(|ch| !ch.is_whitespace());
|
||||
let next = bytes[i + 1..].iter().find(|ch| !ch.is_ascii_whitespace());
|
||||
if !matches!(next, Some('}') | Some(']')) {
|
||||
cleaned.push(c);
|
||||
}
|
||||
@@ -95,4 +99,53 @@ mod tests {
|
||||
let v: serde_json::Value = serde_json::from_str(&strip("\u{feff}{ \"a\": 1 }")).unwrap();
|
||||
assert_eq!(v["a"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_line_breaks_of_block_comments_so_errors_report_the_original_line() {
|
||||
assert_eq!(strip("{\"a\"/*\n\n*/:x}"), "{\"a\"\n\n:x}");
|
||||
let err = serde_json::from_str::<serde_json::Value>(&strip("{\"a\"/*\n\n*/:x}")).unwrap_err();
|
||||
assert_eq!(err.line(), 3);
|
||||
// A comment is whitespace, not a join: `1 2` stays invalid.
|
||||
assert!(serde_json::from_str::<serde_json::Value>(&strip("1/*\n*/2")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_comments_keep_their_line_break_and_may_end_the_input() {
|
||||
assert_eq!(strip("{\"a\":1} // tail"), "{\"a\":1} ");
|
||||
assert_eq!(strip("// a\r\n{\"a\":1}"), "\n{\"a\":1}");
|
||||
assert_eq!(strip("[1, // c\n2]"), "[1, \n2]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unterminated_block_comment_drops_the_rest() {
|
||||
assert_eq!(strip("{\"a\":1}/* open"), "{\"a\":1}");
|
||||
assert_eq!(strip("/*"), "");
|
||||
assert_eq!(strip("/*/ x"), "");
|
||||
assert_eq!(strip("/**/{}"), "{}");
|
||||
assert_eq!(strip("/***/{}"), "{}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comment_markers_inside_strings_survive_including_after_escapes() {
|
||||
let src = "{\"a\":\"\\\\\",\"b\":\"//x\",\"c\":\"/*y*/\",\"d\":\"é,\u{1F600}\"} // é";
|
||||
let v: serde_json::Value = serde_json::from_str(&strip(src)).unwrap();
|
||||
assert_eq!(v, serde_json::json!({"a": "\\", "b": "//x", "c": "/*y*/", "d": "é,\u{1F600}"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_commas_are_dropped_across_whitespace_and_comments_only_before_a_closer() {
|
||||
assert_eq!(strip("[1,2, ]"), "[1,2 ]");
|
||||
assert_eq!(strip("[1,\r\n]"), "[1\r\n]");
|
||||
assert_eq!(strip("[1,/*c*/]"), "[1]");
|
||||
assert_eq!(strip("[1,//c\n]"), "[1\n]");
|
||||
assert_eq!(strip("[1,/*c*/ ,]"), "[1, ]");
|
||||
assert_eq!(strip("{\"a\":\"x,}\"}"), "{\"a\":\"x,}\"}");
|
||||
assert_eq!(strip("[1,2]"), "[1,2]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_json_whitespace_may_separate_a_trailing_comma_from_its_closer() {
|
||||
// U+00A0 is not JSON whitespace: the comma stays and serde_json reports it.
|
||||
assert_eq!(strip("[1,\u{a0}]"), "[1,\u{a0}]");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
//! feature crates depend on `ide-core` and never on each other's internals.
|
||||
//! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`.
|
||||
|
||||
pub mod cli_process;
|
||||
pub mod editor_settings;
|
||||
pub mod error;
|
||||
pub mod event;
|
||||
@@ -12,6 +13,7 @@ pub mod ids;
|
||||
pub mod ignored;
|
||||
pub mod input;
|
||||
pub mod inspection_settings;
|
||||
pub mod ipc_bytes;
|
||||
pub mod ipc_path;
|
||||
pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
@@ -30,6 +32,7 @@ pub mod task;
|
||||
pub mod text;
|
||||
pub mod tool_path;
|
||||
pub mod updates;
|
||||
pub mod utf8;
|
||||
pub mod version_managers;
|
||||
pub mod workflow_settings;
|
||||
pub mod wsl;
|
||||
@@ -37,6 +40,7 @@ pub mod wsl;
|
||||
pub use error::{IdeError, IdeResult};
|
||||
pub use event::{EventSink, IdeEvent, NullSink, SharedSink};
|
||||
pub use ids::*;
|
||||
pub use ipc_bytes::IpcBytes;
|
||||
pub use ipc_path::IpcPath;
|
||||
pub use text::*;
|
||||
pub use tokio_util::sync::CancellationToken;
|
||||
@@ -72,6 +72,16 @@ impl WindowButtonLayout {
|
||||
let right = side(parts.next());
|
||||
(!left.is_empty() || !right.is_empty()).then_some(Self { left, right })
|
||||
}
|
||||
|
||||
/// The layout on Linux: the desktop's `gtk-decoration-layout` when a desktop session is running.
|
||||
/// Without one (WSLg, a bare compositor) GTK reports its built-in fallback, close only, which
|
||||
/// leaves no way to minimise or maximise the frameless window, so the default applies.
|
||||
pub fn for_linux(gtk_layout: Option<&str>, var: impl Fn(&str) -> Option<String>) -> Self {
|
||||
let desktop = ["XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP", "DESKTOP_SESSION"]
|
||||
.iter()
|
||||
.any(|key| var(key).is_some_and(|value| !value.trim().is_empty()));
|
||||
gtk_layout.filter(|_| desktop).and_then(Self::from_gtk_decoration_layout).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -118,6 +128,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_layout_needs_a_desktop_session() {
|
||||
let env = |vars: &'static [(&'static str, &'static str)]| {
|
||||
move |key: &str| vars.iter().find(|(k, _)| *k == key).map(|(_, v)| v.to_string())
|
||||
};
|
||||
let gnome = env(&[("XDG_CURRENT_DESKTOP", "ubuntu:GNOME")]);
|
||||
assert_eq!(WindowButtonLayout::for_linux(Some("appmenu:close"), gnome), layout(&[], &[Close]).unwrap());
|
||||
let kde = env(&[("DESKTOP_SESSION", "plasma")]);
|
||||
assert_eq!(
|
||||
WindowButtonLayout::for_linux(Some("close,maximize,minimize:icon"), kde),
|
||||
layout(&[Close, Maximize, Minimize], &[]).unwrap()
|
||||
);
|
||||
// WSLg: no desktop session, GTK's fallback layout.
|
||||
let wslg = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("XDG_CURRENT_DESKTOP", " ")]);
|
||||
assert_eq!(WindowButtonLayout::for_linux(Some("menu:close"), wslg), WindowButtonLayout::default());
|
||||
let gnome = env(&[("XDG_SESSION_DESKTOP", "gnome")]);
|
||||
assert_eq!(WindowButtonLayout::for_linux(None, gnome), WindowButtonLayout::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_layout_is_on_the_right() {
|
||||
assert_eq!(WindowButtonLayout::default(), layout(&[], &[Minimize, Maximize, Close]).unwrap());
|
||||
|
||||
@@ -5,6 +5,10 @@ use std::path::Path;
|
||||
#[cfg(windows)]
|
||||
use std::process::Stdio;
|
||||
use std::process::{Child, Command};
|
||||
|
||||
pub const ASKPASS_PORT_ENV: &str = "OPENIDEA_ASKPASS_PORT";
|
||||
/// The IDE's askpass helper may answer with saved credentials only.
|
||||
pub const ASKPASS_SILENT_ENV: &str = "OPENIDEA_ASKPASS_SILENT";
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -1330,6 +1334,45 @@ mod tests {
|
||||
assert_eq!(cmd.get_envs().find(|(k, _)| *k == "PATH").and_then(|(_, v)| v), Some(OsStr::new("/custom")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unix_uses_the_name_as_is() {
|
||||
assert_eq!(executable_names("kotlinc", false, Some(".BAT")), ["kotlinc"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_appends_pathext_extensions() {
|
||||
assert_eq!(
|
||||
executable_names("kotlinc", true, None),
|
||||
["kotlinc.com", "kotlinc.exe", "kotlinc.bat", "kotlinc.cmd"]
|
||||
);
|
||||
assert_eq!(executable_names("npx", true, Some(".EXE;.CMD;;")), ["npx.exe", "npx.cmd"]);
|
||||
assert_eq!(executable_names("npx", true, Some(" ")), executable_names("npx", true, None));
|
||||
// Already has an executable extension (any case): only that file.
|
||||
assert_eq!(executable_names("rustc.EXE", true, None), ["rustc.EXE"]);
|
||||
assert_eq!(executable_names("gradlew.bat", true, None), ["gradlew.bat"]);
|
||||
// A dot that is not an executable extension (`clang++`, `python3.12`).
|
||||
assert_eq!(executable_names("python3.12", true, Some(".EXE")), ["python3.12.exe"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_batch_files_and_skips_extensionless_scripts_on_windows() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let a = dir.path().join("a");
|
||||
let b = dir.path().join("b");
|
||||
std::fs::create_dir_all(&a).unwrap();
|
||||
std::fs::create_dir_all(&b).unwrap();
|
||||
// `node_modules/.bin` style: a POSIX script next to its `.cmd` shim.
|
||||
std::fs::write(a.join("tsx"), "#!/bin/sh\n").unwrap();
|
||||
std::fs::write(b.join("tsx.cmd"), "@echo off\n").unwrap();
|
||||
std::fs::write(b.join("kotlinc.bat"), "@echo off\n").unwrap();
|
||||
let search = std::env::join_paths([&a, &b]).unwrap();
|
||||
assert_eq!(find_executable_in("tsx", &search, true, None), Some(b.join("tsx.cmd")));
|
||||
assert_eq!(find_executable_in("kotlinc", &search, true, None), Some(b.join("kotlinc.bat")));
|
||||
assert_eq!(find_executable_in("tsx", &search, false, None), Some(a.join("tsx")));
|
||||
assert_eq!(find_executable_in("kotlinc", &search, false, None), None);
|
||||
assert_eq!(find_executable_in("nope", &search, true, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_executable_finds_bare_names_on_the_given_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -4,6 +4,20 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// Tools › Remote Development. This is a user setting on the remote host.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct RemoteDevelopmentSettings {
|
||||
/// Zero disables idle shutdown. Positive values from older configurations keep their meaning.
|
||||
pub idle_timeout_minutes: u16,
|
||||
}
|
||||
|
||||
impl Default for RemoteDevelopmentSettings {
|
||||
fn default() -> Self {
|
||||
Self { idle_timeout_minutes: 180 }
|
||||
}
|
||||
}
|
||||
|
||||
/// How an SSH connection authenticates.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -60,6 +60,7 @@ pub struct Settings {
|
||||
pub spelling: SpellingSettings,
|
||||
/// Tools › SSH Configurations.
|
||||
pub ssh: SshSettings,
|
||||
pub remote_development: RemoteDevelopmentSettings,
|
||||
/// Build, Execution, Deployment › Deployment.
|
||||
pub deployment: DeploymentSettings,
|
||||
/// Build, Execution, Deployment › Run Targets.
|
||||
@@ -578,6 +579,7 @@ impl Default for Settings {
|
||||
inspections: InspectionSettings::default(),
|
||||
spelling: SpellingSettings::default(),
|
||||
ssh: SshSettings::default(),
|
||||
remote_development: RemoteDevelopmentSettings::default(),
|
||||
deployment: DeploymentSettings::default(),
|
||||
run_targets: Vec::new(),
|
||||
cmake: CMakeSettings::default(),
|
||||
@@ -1206,7 +1208,9 @@ pub struct LanguagesSettings {
|
||||
pub typescript: TypeScriptSettings,
|
||||
pub prettier: ExternalFormatterSettings,
|
||||
pub oxfmt: ExternalFormatterSettings,
|
||||
pub biome: ExternalFormatterSettings,
|
||||
pub ruff: ExternalFormatterSettings,
|
||||
pub black: ExternalFormatterSettings,
|
||||
pub java: JavaSettings,
|
||||
pub ruby: RubySettings,
|
||||
pub markdown: MarkdownSettings,
|
||||
@@ -1226,10 +1230,18 @@ impl Default for LanguagesSettings {
|
||||
typescript: TypeScriptSettings::default(),
|
||||
prettier: ExternalFormatterSettings::default(),
|
||||
oxfmt: ExternalFormatterSettings::default(),
|
||||
biome: ExternalFormatterSettings {
|
||||
languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(),
|
||||
..ExternalFormatterSettings::default()
|
||||
},
|
||||
ruff: ExternalFormatterSettings {
|
||||
languages: vec!["python".into()],
|
||||
..ExternalFormatterSettings::default()
|
||||
},
|
||||
black: ExternalFormatterSettings {
|
||||
languages: vec!["python".into()],
|
||||
..ExternalFormatterSettings::default()
|
||||
},
|
||||
java: JavaSettings::default(),
|
||||
ruby: RubySettings::default(),
|
||||
markdown: MarkdownSettings::default(),
|
||||
@@ -1254,6 +1266,7 @@ pub struct ArduinoSettings {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct MarkdownSettings {
|
||||
pub preview_layout: MarkdownPreviewLayout,
|
||||
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
|
||||
pub preview_font_size: Option<u32>,
|
||||
/// "Detect commands that can be run right from Markdown files": gutter run icons on
|
||||
@@ -1265,10 +1278,23 @@ pub struct MarkdownSettings {
|
||||
|
||||
impl Default for MarkdownSettings {
|
||||
fn default() -> Self {
|
||||
Self { preview_font_size: None, run_commands: true, command_directory: None }
|
||||
Self {
|
||||
preview_layout: MarkdownPreviewLayout::default(),
|
||||
preview_font_size: None,
|
||||
run_commands: true,
|
||||
command_directory: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MarkdownPreviewLayout {
|
||||
#[default]
|
||||
SideBySide,
|
||||
Stacked,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MarkdownCommandDirectory {
|
||||
@@ -1283,7 +1309,9 @@ impl LanguagesSettings {
|
||||
match tool {
|
||||
ExternalFormatter::Prettier => &self.prettier,
|
||||
ExternalFormatter::Oxfmt => &self.oxfmt,
|
||||
ExternalFormatter::Biome => &self.biome,
|
||||
ExternalFormatter::Ruff => &self.ruff,
|
||||
ExternalFormatter::Black => &self.black,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1294,7 +1322,9 @@ impl LanguagesSettings {
|
||||
pub enum ExternalFormatter {
|
||||
Prettier,
|
||||
Oxfmt,
|
||||
Biome,
|
||||
Ruff,
|
||||
Black,
|
||||
}
|
||||
|
||||
impl ExternalFormatter {
|
||||
@@ -1303,16 +1333,22 @@ impl ExternalFormatter {
|
||||
match self {
|
||||
Self::Prettier => "prettier",
|
||||
Self::Oxfmt => "oxfmt",
|
||||
Self::Biome => "biome",
|
||||
Self::Ruff => "ruff",
|
||||
Self::Black => "black",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An external formatter (Prettier, oxfmt, Ruff) and the languages it formats.
|
||||
/// The languages Biome formats (of those Prettier formats).
|
||||
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.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ExternalFormatterSettings {
|
||||
/// Empty path: project node_modules (Prettier/oxfmt), managed installation, then PATH.
|
||||
/// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH.
|
||||
pub path: String,
|
||||
/// Ruff only: directory containing its configuration, or a configuration file.
|
||||
pub configuration_directory: String,
|
||||
@@ -1370,6 +1406,9 @@ pub struct PythonSettings {
|
||||
pub hide_other_project_interpreters: bool,
|
||||
/// Show each interpreter's path under its name on the interpreters page.
|
||||
pub show_interpreter_paths: bool,
|
||||
/// 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>>,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1381,6 +1420,7 @@ impl Default for PythonSettings {
|
||||
hidden_interpreters: Vec::new(),
|
||||
hide_other_project_interpreters: false,
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1889,6 +1929,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_preview_layout_defaults_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"languages":{"markdown":{"previewFontSize":16}}}"#).unwrap();
|
||||
assert_eq!(old.languages.markdown.preview_layout, MarkdownPreviewLayout::SideBySide);
|
||||
assert_eq!(old.languages.markdown.preview_font_size, Some(16));
|
||||
|
||||
let stacked: Settings =
|
||||
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked"}}}"#).unwrap();
|
||||
assert_eq!(stacked.languages.markdown.preview_layout, MarkdownPreviewLayout::Stacked);
|
||||
let saved = serde_json::to_value(&stacked).unwrap();
|
||||
assert_eq!(saved["languages"]["markdown"]["previewLayout"], "stacked");
|
||||
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().languages.markdown, stacked.languages.markdown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmake_profile_argument_arrays_round_trip() {
|
||||
let mut settings = Settings::default();
|
||||
|
||||
@@ -48,6 +48,7 @@ impl Utf8Decoder {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
/// Convenience wrapper around [`Self::decode_into`].
|
||||
pub fn decode(&mut self, bytes: &[u8]) -> String {
|
||||
let mut out = String::new();
|
||||
@@ -65,6 +66,7 @@ impl Utf8Decoder {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn has_pending(&self) -> bool {
|
||||
!self.pending.is_empty()
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use std::collections::BTreeMap;
|
||||
pub struct VcsSettings {
|
||||
/// Colour folders that contain changed files (project tree, tabs).
|
||||
pub show_dirty_directories: bool,
|
||||
pub create_changelists_automatically: bool,
|
||||
/// Diffs the user opens show in an editor tab; off, in a separate window.
|
||||
pub diff_as_editor_tab: bool,
|
||||
/// Stop file history (Show History) after `history_limit` commits.
|
||||
@@ -57,6 +58,7 @@ impl Default for VcsSettings {
|
||||
Self {
|
||||
// IDEA's VcsConfiguration.SHOW_DIRTY_RECURSIVELY is off by default.
|
||||
show_dirty_directories: false,
|
||||
create_changelists_automatically: false,
|
||||
diff_as_editor_tab: true,
|
||||
limit_history: true,
|
||||
history_limit: 1000,
|
||||
@@ -70,9 +72,66 @@ impl Default for VcsSettings {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum EmptyCherryPickAction {
|
||||
#[default]
|
||||
Skip,
|
||||
CreateEmpty,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum StashDiffTarget {
|
||||
#[default]
|
||||
Local,
|
||||
Parent,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GitSaveChangesPolicy {
|
||||
#[default]
|
||||
Shelve,
|
||||
Stash,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum FetchTagsMode {
|
||||
#[default]
|
||||
Auto,
|
||||
Sync,
|
||||
Always,
|
||||
Never,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GitAnnotateMovement {
|
||||
#[default]
|
||||
None,
|
||||
WithinFile,
|
||||
AcrossFiles,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GitAnnotateSettings {
|
||||
pub ignore_whitespace: bool,
|
||||
pub movement: GitAnnotateMovement,
|
||||
}
|
||||
|
||||
impl Default for GitAnnotateSettings {
|
||||
fn default() -> Self {
|
||||
Self { ignore_whitespace: true, movement: GitAnnotateMovement::None }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GitSettings {
|
||||
pub annotate: GitAnnotateSettings,
|
||||
/// Show blame after the current editor line.
|
||||
pub inline_blame: bool,
|
||||
/// A click (or Enter / Space) on the inline blame label opens its commit; off, the
|
||||
@@ -83,20 +142,29 @@ pub struct GitSettings {
|
||||
pub sync_branch_operations: bool,
|
||||
/// Path to the git executable; empty = auto-detect.
|
||||
pub executable: String,
|
||||
/// Clone all submodules along with the root repository.
|
||||
pub clone_submodules: bool,
|
||||
/// Default of Update Project: `merge` | `rebase`.
|
||||
pub update_method: String,
|
||||
/// Where Git operations keep local changes temporarily.
|
||||
pub save_changes_policy: GitSaveChangesPolicy,
|
||||
/// Push rejected (non-fast-forward): update the branch and push again.
|
||||
pub auto_update_on_push_rejected: bool,
|
||||
pub warn_crlf: bool,
|
||||
pub warn_detached_head: bool,
|
||||
/// Background check for incoming commits: `auto` | `always` | `never`.
|
||||
/// Background check for incoming commits: `auto` | `always` | `check` | `never`.
|
||||
pub incoming_check: String,
|
||||
/// Minutes between background checks for incoming commits.
|
||||
pub incoming_check_interval: u32,
|
||||
/// How an explicit fetch or project update handles remote tags.
|
||||
pub fetch_tags_mode: FetchTagsMode,
|
||||
/// Branch name globs, `;`/`,`-separated; force push to them is prohibited.
|
||||
pub protected_branches: String,
|
||||
/// Initial state of Commit Options › Sign-off Commit.
|
||||
pub sign_off: bool,
|
||||
/// Add Git's origin line when cherry-picking commits from protected remote branches.
|
||||
pub add_cherry_pick_origin: bool,
|
||||
pub empty_cherry_pick: EmptyCherryPickAction,
|
||||
/// Ask before committing files larger than `large_file_mb`.
|
||||
pub warn_large_files: bool,
|
||||
pub large_file_mb: u32,
|
||||
@@ -108,6 +176,8 @@ pub struct GitSettings {
|
||||
pub push_dialog_only_protected: bool,
|
||||
/// Stashes and shelves share one tab.
|
||||
pub combine_stash_and_shelf: bool,
|
||||
/// What the stash browser compares its saved files against.
|
||||
pub stash_diff_target: StashDiffTarget,
|
||||
/// The non-modal Commit tool window works on the index: Staged / Unstaged groups,
|
||||
/// stage and unstage instead of inclusion checkboxes, and no change lists.
|
||||
pub staging_area: bool,
|
||||
@@ -119,25 +189,32 @@ pub struct GitSettings {
|
||||
impl Default for GitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
annotate: GitAnnotateSettings::default(),
|
||||
inline_blame: false,
|
||||
inline_blame_clickable: true,
|
||||
show_branch_in_project_view: false,
|
||||
sync_branch_operations: true,
|
||||
executable: String::new(),
|
||||
clone_submodules: true,
|
||||
update_method: "merge".into(),
|
||||
save_changes_policy: GitSaveChangesPolicy::default(),
|
||||
auto_update_on_push_rejected: false,
|
||||
warn_crlf: true,
|
||||
warn_detached_head: true,
|
||||
incoming_check: "auto".into(),
|
||||
incoming_check_interval: 15,
|
||||
fetch_tags_mode: FetchTagsMode::Auto,
|
||||
protected_branches: "master; main".into(),
|
||||
sign_off: false,
|
||||
add_cherry_pick_origin: true,
|
||||
empty_cherry_pick: EmptyCherryPickAction::Skip,
|
||||
warn_large_files: true,
|
||||
large_file_mb: 50,
|
||||
warn_bad_file_names: true,
|
||||
show_push_dialog: true,
|
||||
push_dialog_only_protected: false,
|
||||
combine_stash_and_shelf: false,
|
||||
stash_diff_target: StashDiffTarget::default(),
|
||||
staging_area: false,
|
||||
cli_status: false,
|
||||
}
|
||||
@@ -152,9 +229,11 @@ pub struct CommitSettings {
|
||||
/// window and a Commit dialog.
|
||||
pub non_modal: bool,
|
||||
pub include_changes_by_default: bool,
|
||||
pub commit_all_when_nothing_staged: bool,
|
||||
/// Start with an empty message instead of the last one / the changelist's.
|
||||
pub clear_initial_message: bool,
|
||||
pub analyze_code: bool,
|
||||
pub postpone_slow_checks: bool,
|
||||
pub check_todo: bool,
|
||||
pub reformat: bool,
|
||||
pub optimize_imports: bool,
|
||||
@@ -192,8 +271,10 @@ impl Default for CommitSettings {
|
||||
Self {
|
||||
non_modal: true,
|
||||
include_changes_by_default: true,
|
||||
commit_all_when_nothing_staged: true,
|
||||
clear_initial_message: false,
|
||||
analyze_code: true,
|
||||
postpone_slow_checks: true,
|
||||
check_todo: true,
|
||||
reformat: false,
|
||||
optimize_imports: false,
|
||||
@@ -622,6 +703,14 @@ impl Default for AgentSecuritySettings {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn clone_submodules_defaults_on_and_can_be_disabled() {
|
||||
let missing: GitSettings = serde_json::from_str("{}").unwrap();
|
||||
let off: GitSettings = serde_json::from_str(r#"{"cloneSubmodules":false}"#).unwrap();
|
||||
assert!(missing.clone_submodules);
|
||||
assert!(!off.clone_submodules);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_settings_without_sync_key_execute_on_all_repositories() {
|
||||
let missing: GitSettings = serde_json::from_str("{}").unwrap();
|
||||
|
||||
@@ -12,7 +12,6 @@ quick-xml = "0.42"
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Exception breakpoints on a chosen class. The manager keeps one list; a session given a backend
|
||||
//! for them at start arms it before `configurationDone`, so a throw in the program's first line
|
||||
//! stops, and again after each `setExceptionBreakpoints`, which drops them in java-debug.
|
||||
|
||||
use crate::session::Session;
|
||||
use crate::{DebugManager, jvm_memory};
|
||||
use ide_jvm_inspect::ExceptionClassSpec;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExceptionClassBreakpoint {
|
||||
pub id: String,
|
||||
/// Fully qualified binary name (`com.acme.Outer$Inner`); its subclasses stop too.
|
||||
pub class_name: String,
|
||||
pub caught: bool,
|
||||
pub uncaught: bool,
|
||||
pub enabled: bool,
|
||||
/// Patterns (`com.acme.*`, `*Test`, a full name) for the class whose code throws.
|
||||
pub class_filters: Vec<String>,
|
||||
pub class_exclusion_filters: Vec<String>,
|
||||
}
|
||||
|
||||
/// What a session's exception class breakpoints can do.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExceptionClassSupport {
|
||||
/// Whose class names the session takes: `java`.
|
||||
pub family: String,
|
||||
pub condition: bool,
|
||||
pub class_filters: bool,
|
||||
/// Filters on the class whose code catches the exception.
|
||||
pub catch_filters: bool,
|
||||
}
|
||||
|
||||
/// The JVM backends stop through java-debug's own exception events, which a condition or a
|
||||
/// catch-location filter cannot veto.
|
||||
pub(crate) fn support(s: &Session) -> Option<ExceptionClassSupport> {
|
||||
s.exception_classes.is_some().then(|| ExceptionClassSupport {
|
||||
family: "java".into(),
|
||||
condition: false,
|
||||
class_filters: true,
|
||||
catch_filters: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn spec(b: &ExceptionClassBreakpoint) -> ExceptionClassSpec {
|
||||
ExceptionClassSpec {
|
||||
id: b.id.clone(),
|
||||
class_name: b.class_name.clone(),
|
||||
caught: b.caught,
|
||||
uncaught: b.uncaught,
|
||||
enabled: b.enabled,
|
||||
class_filters: b.class_filters.clone(),
|
||||
class_exclusion_filters: b.class_exclusion_filters.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
impl DebugManager {
|
||||
/// Arms the manager's list in `s`; the caller holds `s.exception_turn`. `clear`: also when the
|
||||
/// list is empty, to take down what an earlier list armed.
|
||||
pub(crate) async fn arm_exception_classes(&self, s: &Session, clear: bool) {
|
||||
let Some(backend) = &s.exception_classes else { return };
|
||||
let specs: Vec<_> = self.exception_classes.lock().iter().map(spec).collect();
|
||||
// Without either, no VM is known yet: `configure` arms once it is.
|
||||
let target = jvm_memory::vm_target(s);
|
||||
if (specs.is_empty() && !clear) || (target.pid.is_none() && target.attach_port.is_none()) {
|
||||
return;
|
||||
}
|
||||
match backend.set(&target, &specs).await {
|
||||
Ok(states) => tracing::debug!("exception class breakpoints of session {}: {states:?}", s.id.0),
|
||||
Err(e) => tracing::debug!("exception class breakpoints of session {} failed: {e}", s.id.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores exception breakpoints on chosen classes (kept without a session, armed on start)
|
||||
/// and arms them in every session that takes them. Also in one still starting: one that has
|
||||
/// armed already would miss the list, and one that has not answers `vmNotFound` until then.
|
||||
pub async fn set_exception_class_breakpoints(&self, list: Vec<ExceptionClassBreakpoint>) {
|
||||
*self.exception_classes.lock() = list;
|
||||
for s in self.live_sessions() {
|
||||
if s.exception_classes.is_none() || s.conn.is_closed() {
|
||||
continue;
|
||||
}
|
||||
let _turn = s.exception_turn.lock().await;
|
||||
self.arm_exception_classes(&s, true).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
-14
@@ -12,6 +12,7 @@ pub mod adapter;
|
||||
pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
mod exception_classes;
|
||||
pub mod jdwp;
|
||||
mod js_cdp;
|
||||
mod js_debug;
|
||||
@@ -24,6 +25,7 @@ pub mod unity;
|
||||
|
||||
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
use connection::{Connection, DapError};
|
||||
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
|
||||
use futures::future::join_all;
|
||||
use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink};
|
||||
use ide_language::LanguageRegistry;
|
||||
@@ -283,6 +285,8 @@ pub struct SessionExceptionFilters {
|
||||
pub session: DebugSessionId,
|
||||
pub adapter: String,
|
||||
pub filters: Vec<ExceptionFilter>,
|
||||
/// Set when the session takes exception breakpoints on a chosen class.
|
||||
pub classes: Option<ExceptionClassSupport>,
|
||||
}
|
||||
|
||||
/// What triggered a hot reload; `flutter debug_adapter` takes it as `reason`.
|
||||
@@ -336,6 +340,7 @@ pub struct DebugManager {
|
||||
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.
|
||||
@@ -788,6 +793,7 @@ impl DebugManager {
|
||||
breakpoints: Mutex::default(),
|
||||
states: Mutex::default(),
|
||||
exception_choices: Mutex::default(),
|
||||
exception_classes: Mutex::default(),
|
||||
function_breakpoints: Mutex::default(),
|
||||
data_breakpoints: Mutex::default(),
|
||||
stopping: Mutex::default(),
|
||||
@@ -836,6 +842,18 @@ impl DebugManager {
|
||||
config: LaunchConfig,
|
||||
owner: SessionOwner,
|
||||
custom_command: impl FnOnce(&str) -> Option<String>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
self.start_with_exception_classes(config, owner, custom_command, None).await
|
||||
}
|
||||
|
||||
/// [`start_with`](Self::start_with), the session arming [`Self::set_exception_class_breakpoints`]
|
||||
/// through `exception_classes`.
|
||||
pub async fn start_with_exception_classes(
|
||||
&self,
|
||||
config: LaunchConfig,
|
||||
owner: SessionOwner,
|
||||
custom_command: impl FnOnce(&str) -> Option<String>,
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
let mut arguments = launch_arguments(&config)?;
|
||||
// An IDE-side marker (never sent to the adapter): the session is a Flutter
|
||||
@@ -977,7 +995,19 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
let port = debug_server.map(|s| s.port);
|
||||
self.start_session(id, owner, config.name, config.adapter, None, config.request, arguments, spec, port).await
|
||||
self.start_session(
|
||||
id,
|
||||
owner,
|
||||
config.name,
|
||||
config.adapter,
|
||||
None,
|
||||
config.request,
|
||||
arguments,
|
||||
spec,
|
||||
port,
|
||||
exception_classes,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// `startDebugging` reverse request: a child session on the same adapter.
|
||||
@@ -1002,6 +1032,7 @@ impl DebugManager {
|
||||
configuration,
|
||||
parent.spec.clone(),
|
||||
parent.port,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
@@ -1019,6 +1050,7 @@ impl DebugManager {
|
||||
arguments: Value,
|
||||
spec: AdapterSpec,
|
||||
reuse_port: Option<u16>,
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
if request != "launch" && request != "attach" {
|
||||
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
|
||||
@@ -1033,8 +1065,9 @@ impl DebugManager {
|
||||
let rdbg_pid = (adapter_name == "rdbg" && request == "launch")
|
||||
.then(|| io.child.as_ref().and_then(tokio::process::Child::id))
|
||||
.flatten();
|
||||
let session =
|
||||
Arc::new(Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child));
|
||||
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
|
||||
session.exception_classes = exception_classes;
|
||||
let session = Arc::new(session);
|
||||
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
|
||||
let _ = session.launch_type.set(launch_type.to_owned());
|
||||
}
|
||||
@@ -1259,8 +1292,12 @@ impl DebugManager {
|
||||
tracing::debug!("setDataBreakpoints failed: {e}");
|
||||
}
|
||||
let has_filters = s.caps.lock().get("exceptionBreakpointFilters").and_then(Value::as_array).is_some();
|
||||
if has_filters {
|
||||
let _ = self.send_exception_breakpoints(s).await;
|
||||
{
|
||||
let _turn = s.exception_turn.lock().await;
|
||||
if has_filters {
|
||||
let _ = self.send_exception_breakpoints(s).await;
|
||||
}
|
||||
self.arm_exception_classes(s, false).await;
|
||||
}
|
||||
if s.supports("supportsConfigurationDoneRequest") {
|
||||
if s.adapter == kotlin::ADAPTER {
|
||||
@@ -1481,6 +1518,7 @@ impl DebugManager {
|
||||
session: s.id,
|
||||
adapter: s.adapter.clone(),
|
||||
filters: exception_filters_from(&s.caps.lock()),
|
||||
classes: exception_classes::support(s),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1496,9 +1534,11 @@ impl DebugManager {
|
||||
if exception_filters_from(&s.caps.lock()).is_empty() {
|
||||
continue;
|
||||
}
|
||||
let _turn = s.exception_turn.lock().await;
|
||||
if let Err(e) = self.send_exception_breakpoints(&s).await {
|
||||
tracing::debug!("setExceptionBreakpoints on session {} failed: {e}", s.id.0);
|
||||
}
|
||||
self.arm_exception_classes(&s, false).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1712,9 +1752,7 @@ impl DebugManager {
|
||||
let body = session.conn.request_timeout("continue", json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await?;
|
||||
// DAP: a response without the flag continued every thread.
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool).unwrap_or(true);
|
||||
session.suspended.resumed(ticket, thread_id, all);
|
||||
stream_trace::release_done(&session);
|
||||
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: all });
|
||||
session.finish_resume(ticket, thread_id, all);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1761,9 +1799,7 @@ impl DebugManager {
|
||||
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await;
|
||||
step_settled(&session, sent)?;
|
||||
// A step runs its thread; other threads stopped by their own events stay stopped.
|
||||
session.suspended.resumed(ticket, thread_id, false);
|
||||
stream_trace::release_done(&session);
|
||||
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
|
||||
session.finish_resume(ticket, thread_id, false);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1873,9 +1909,7 @@ impl DebugManager {
|
||||
.request_timeout("stepIn", json!({ "threadId": thread_id, "targetId": target_id }), REQUEST_TIMEOUT)
|
||||
.await;
|
||||
step_settled(&session, sent)?;
|
||||
session.suspended.resumed(ticket, thread_id, false);
|
||||
stream_trace::release_done(&session);
|
||||
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: false });
|
||||
session.finish_resume(ticket, thread_id, false);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
+144
-16
@@ -118,6 +118,11 @@ pub(crate) struct Session {
|
||||
pub kotlin_mirror: Mutex<Option<crate::kotlin::SourceMirror>>,
|
||||
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
|
||||
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
|
||||
/// Given at start: the class breakpoints must be armed before `configurationDone`.
|
||||
pub(crate) exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
/// Held from `setExceptionBreakpoints`, which drops the class breakpoints, until they are
|
||||
/// armed again, so that the last list armed is the manager's.
|
||||
pub(crate) exception_turn: tokio::sync::Mutex<()>,
|
||||
pub(crate) stream_trace: parking_lot::Mutex<Option<crate::stream_trace::ActiveTrace>>,
|
||||
/// The last trace that finished, until the stop its records were read in ends.
|
||||
pub(crate) stream_trace_done: parking_lot::Mutex<Option<crate::stream_trace::DoneTrace>>,
|
||||
@@ -155,19 +160,36 @@ impl Stops {
|
||||
}
|
||||
|
||||
/// Ends the stops taken by ticket `upto` of `thread`, or of every thread.
|
||||
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) {
|
||||
/// Returns whether any stop was removed.
|
||||
fn release(&mut self, thread: Option<i64>, every: bool, upto: u64) -> bool {
|
||||
let latest = self.latest();
|
||||
let before = (self.all, self.threads.len());
|
||||
if every || thread.is_none() || self.all.is_some_and(|t| t <= upto) {
|
||||
self.all = self.all.filter(|&t| t > upto);
|
||||
self.threads.retain(|&(_, t)| t > upto);
|
||||
} else {
|
||||
self.threads.retain(|&(id, t)| Some(id) != thread || t > upto);
|
||||
}
|
||||
let changed = (self.all, self.threads.len()) != before;
|
||||
// Back on an earlier thread's stop, as the JDWP link moves to it with a new generation.
|
||||
let now = self.latest();
|
||||
if now.is_some() && now != latest {
|
||||
self.ticket += 1;
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
/// Whether a stop taken after `after` would be undone by a synthetic `continued` event for
|
||||
/// `thread` (or for every thread when `every` is set).
|
||||
fn superseded(&self, thread: i64, every: bool, after: u64) -> bool {
|
||||
if self.all.is_some_and(|t| t > after) {
|
||||
return true;
|
||||
}
|
||||
if every {
|
||||
self.threads.iter().any(|&(_, t)| t > after)
|
||||
} else {
|
||||
self.threads.iter().any(|&(id, t)| id == thread && t > after)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -192,12 +214,27 @@ impl Suspension {
|
||||
}
|
||||
}
|
||||
|
||||
/// A `continued` event; `all`: its `allThreadsContinued`.
|
||||
pub fn continued(&self, thread: Option<i64>, all: bool) {
|
||||
self.0.lock().release(thread, all, u64::MAX);
|
||||
/// Runs `emit` under the suspension lock so a synthetic `continued` from a resume reply cannot
|
||||
/// be emitted after a `stopped` event once that stop has been recorded.
|
||||
pub fn emit_synced(&self, emit: impl FnOnce()) {
|
||||
let _stops = self.0.lock();
|
||||
emit();
|
||||
}
|
||||
|
||||
/// Take before sending a resume-like request and pass to [`Self::resumed`].
|
||||
/// A `continued` event; `all`: its `allThreadsContinued`. Runs `emit` under the same lock so
|
||||
/// synthetic `continued` events from resume replies stay ordered against it.
|
||||
pub fn continued_and_emit(&self, thread: Option<i64>, all: bool, emit: impl FnOnce()) {
|
||||
let mut stops = self.0.lock();
|
||||
stops.release(thread, all, u64::MAX);
|
||||
emit();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn continued(&self, thread: Option<i64>, all: bool) {
|
||||
self.continued_and_emit(thread, all, || {});
|
||||
}
|
||||
|
||||
/// Take before sending a resume-like request and pass to [`Self::resumed_and_emit`].
|
||||
pub fn ticket(&self) -> u64 {
|
||||
self.0.lock().ticket
|
||||
}
|
||||
@@ -210,8 +247,19 @@ impl Suspension {
|
||||
}
|
||||
|
||||
/// After a successful resume-like request for `thread`; `all`: every thread ran.
|
||||
/// Runs `emit` under the lock only when a prior stop was ended and no newer stop superseded it.
|
||||
pub fn resumed_and_emit(&self, ticket: u64, thread: i64, all: bool, emit: impl FnOnce()) {
|
||||
let mut stops = self.0.lock();
|
||||
let superseded = stops.superseded(thread, all, ticket);
|
||||
let released = stops.release(Some(thread), all, ticket);
|
||||
if released && !superseded {
|
||||
emit();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn resumed(&self, ticket: u64, thread: i64, all: bool) {
|
||||
self.0.lock().release(Some(thread), all, ticket);
|
||||
self.resumed_and_emit(ticket, thread, all, || {});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,6 +334,8 @@ impl Session {
|
||||
kotlin_mirror: Mutex::new(None),
|
||||
jvm_memory: tokio::sync::Mutex::default(),
|
||||
stream_tracer: parking_lot::Mutex::new(None),
|
||||
exception_classes: None,
|
||||
exception_turn: tokio::sync::Mutex::default(),
|
||||
stream_trace: parking_lot::Mutex::new(None),
|
||||
stream_trace_done: parking_lot::Mutex::new(None),
|
||||
quirks: kotlin_lsp::Quirks::default(),
|
||||
@@ -309,6 +359,16 @@ impl Session {
|
||||
self.owner.sink.emit(IdeEvent::Debug { session: self.id, event });
|
||||
}
|
||||
|
||||
/// Completes a successful resume or step reply (`ticket` taken before the request): ends the
|
||||
/// prior stops and emits a synthetic `continued` event unless an adapter event already ended
|
||||
/// them or a newer `stopped` event superseded it.
|
||||
pub(crate) fn finish_resume(&self, ticket: u64, thread_id: i64, all: bool) {
|
||||
self.suspended.resumed_and_emit(ticket, thread_id, all, || {
|
||||
self.emit(DebugEvent::Continued { thread_id, all_threads_continued: all });
|
||||
});
|
||||
crate::stream_trace::release_done(self);
|
||||
}
|
||||
|
||||
/// `path` as sent to the adapter (resolved for [`RESOLVES_PATHS`] adapters).
|
||||
pub fn adapter_path(&self, path: &Path) -> PathBuf {
|
||||
if let Some(path) = self.kotlin_mirror.lock().as_ref().and_then(|m| m.adapter_path(path)) {
|
||||
@@ -782,23 +842,26 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
reason = quirks.stop_reason(reason);
|
||||
}
|
||||
mgr.restore_breakpoints(s).await;
|
||||
s.emit(DebugEvent::Stopped {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
reason,
|
||||
description: str_("description").or_else(|| str_("text")),
|
||||
all_threads_stopped: all,
|
||||
s.suspended.emit_synced(|| {
|
||||
s.emit(DebugEvent::Stopped {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
reason,
|
||||
description: str_("description").or_else(|| str_("text")),
|
||||
all_threads_stopped: all,
|
||||
});
|
||||
});
|
||||
}
|
||||
"continued" => {
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
|
||||
// DAP: an event without the flag continues its thread alone. The UI keeps treating
|
||||
// it as all threads; the suspension, which holds only threads that stopped, need not.
|
||||
s.suspended.continued(int("threadId"), all.unwrap_or(false));
|
||||
crate::stream_trace::release_done(s);
|
||||
s.emit(DebugEvent::Continued {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
all_threads_continued: all.unwrap_or(true),
|
||||
s.suspended.continued_and_emit(int("threadId"), all.unwrap_or(false), || {
|
||||
s.emit(DebugEvent::Continued {
|
||||
thread_id: int("threadId").unwrap_or(0),
|
||||
all_threads_continued: all.unwrap_or(true),
|
||||
});
|
||||
});
|
||||
crate::stream_trace::release_done(s);
|
||||
}
|
||||
"output" => {
|
||||
let category = str_("category").unwrap_or_else(|| "console".into());
|
||||
@@ -1458,6 +1521,71 @@ mod tests {
|
||||
assert!(!s.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_continued_is_suppressed_when_a_newer_stop_or_continued_already_landed() {
|
||||
let emit_if_resumed = |s: &Suspension, ticket, thread, all| {
|
||||
let mut emitted = false;
|
||||
s.resumed_and_emit(ticket, thread, all, || emitted = true);
|
||||
emitted
|
||||
};
|
||||
|
||||
// Normal step without an adapter `continued` event emits a synthetic one.
|
||||
let s = Suspension::default();
|
||||
s.stopped(Some(1), true);
|
||||
assert!(emit_if_resumed(&s, s.ticket(), 1, false));
|
||||
|
||||
// Next `stopped` (all-threads or single-thread) overtakes the reply: no synthetic `continued`.
|
||||
for next_all in [true, false] {
|
||||
let s = Suspension::default();
|
||||
s.stopped(Some(1), true);
|
||||
let ticket = s.ticket();
|
||||
s.stopped(Some(1), next_all);
|
||||
assert!(!emit_if_resumed(&s, ticket, 1, false), "next_all={next_all}");
|
||||
assert!(s.get());
|
||||
}
|
||||
|
||||
// Adapter's own `continued` event already ended the stop: no duplicate synthetic `continued`.
|
||||
let s = Suspension::default();
|
||||
s.stopped(Some(1), true);
|
||||
let ticket = s.ticket();
|
||||
s.continued(Some(1), true);
|
||||
assert!(!emit_if_resumed(&s, ticket, 1, true));
|
||||
|
||||
// Multi-thread: thread 7 steps while thread 9 stops alone -> thread 7 still emits `continued(all=false)`.
|
||||
let s = two_threads_stopped();
|
||||
let ticket = s.ticket();
|
||||
s.stopped(Some(9), false);
|
||||
assert!(emit_if_resumed(&s, ticket, 7, false));
|
||||
assert!(s.get());
|
||||
|
||||
// Multi-thread: `continue(all=true)` while thread 9 stops alone -> suppressed so thread 9 stays paused.
|
||||
let s = two_threads_stopped();
|
||||
let ticket = s.ticket();
|
||||
s.stopped(Some(9), false);
|
||||
assert!(!emit_if_resumed(&s, ticket, 7, true));
|
||||
assert!(s.get());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_stop_and_resume_never_emit_continued_after_the_new_stop() {
|
||||
for _ in 0..200 {
|
||||
let s = std::sync::Arc::new(Suspension::default());
|
||||
let log = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<&'static str>::new()));
|
||||
s.stopped(Some(1), true);
|
||||
let ticket = s.ticket();
|
||||
let s2 = s.clone();
|
||||
let log2 = log.clone();
|
||||
let stop = std::thread::spawn(move || {
|
||||
s2.stopped(Some(1), false);
|
||||
s2.emit_synced(|| log2.lock().push("stopped"));
|
||||
});
|
||||
s.resumed_and_emit(ticket, 1, false, || log.lock().push("continued"));
|
||||
stop.join().unwrap();
|
||||
let events = log.lock().clone();
|
||||
assert!(events == ["continued", "stopped"] || events == ["stopped"], "unexpected order: {events:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kotlin_launch_starts_attach_listener_first() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Protocol flow against an in-memory fake adapter.
|
||||
|
||||
mod exception_classes;
|
||||
mod jvm_inspect;
|
||||
mod stream_trace;
|
||||
|
||||
@@ -156,6 +157,11 @@ struct Script {
|
||||
breakpoints_after_continue: usize,
|
||||
/// The `reason` of the stop a `next` ends with (`step` when unset; kotlin-lsp says `breakpoint`).
|
||||
step_reason: Option<&'static str>,
|
||||
/// Send `stopped` before answering `next` / `stepIn` / `stepOut` / `continue` (like php-debug
|
||||
/// when Xdebug finishes a step before the DAP reply is handled).
|
||||
stop_before_reply: bool,
|
||||
/// Send `continued` before answering `next` / `continue`.
|
||||
continued_before_reply: bool,
|
||||
/// Refuse `next`, then stop at a breakpoint (one the program hit meanwhile).
|
||||
refuse_next: bool,
|
||||
/// Send `invalidated { areas: ["variables"] }` right after the first `stopped` event.
|
||||
@@ -212,6 +218,8 @@ impl Default for Script {
|
||||
refuse_continue: false,
|
||||
breakpoints_after_continue: 0,
|
||||
step_reason: None,
|
||||
stop_before_reply: false,
|
||||
continued_before_reply: false,
|
||||
refuse_next: false,
|
||||
invalidated_after_stop: false,
|
||||
stop_during_threads: false,
|
||||
@@ -413,6 +421,19 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1}}));
|
||||
}
|
||||
"next" if script.stop_before_reply => {
|
||||
let reason = script.step_reason.unwrap_or("step");
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": 1}}));
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, Value::Null);
|
||||
}
|
||||
"next" if script.continued_before_reply => {
|
||||
send!(
|
||||
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": false}})
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, Value::Null);
|
||||
}
|
||||
"next" => {
|
||||
ok!(msg, Value::Null);
|
||||
let reason = script.step_reason.unwrap_or("step");
|
||||
@@ -552,6 +573,20 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
"stepOut" if script.refuse_step_out => send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "stepOut", "success": false, "message": "Thread is not suspended"})
|
||||
),
|
||||
"continue" if script.stop_before_reply => {
|
||||
send!(
|
||||
json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 1, "allThreadsStopped": true}})
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, json!({"allThreadsContinued": true}));
|
||||
}
|
||||
"continue" if script.continued_before_reply => {
|
||||
send!(
|
||||
json!({"type": "event", "event": "continued", "body": {"threadId": 1, "allThreadsContinued": true}})
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, json!({"allThreadsContinued": true}));
|
||||
}
|
||||
"continue" if script.stop_after_continue => {
|
||||
ok!(msg, json!({"allThreadsContinued": true}));
|
||||
send!(
|
||||
@@ -574,6 +609,11 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": reason, "threadId": thread}}));
|
||||
}
|
||||
}
|
||||
"stepIn" | "stepOut" if script.stop_before_reply => {
|
||||
send!(json!({"type": "event", "event": "stopped", "body": {"reason": "step", "threadId": 1}}));
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
ok!(msg, Value::Null);
|
||||
}
|
||||
"stepIn" | "stepOut" | "pause" => ok!(msg, Value::Null),
|
||||
"hotReload" => {
|
||||
ok!(msg, Value::Null);
|
||||
@@ -2788,6 +2828,74 @@ async fn step_of_one_thread_keeps_the_others_suspended() {
|
||||
}
|
||||
}
|
||||
|
||||
/// When an adapter emits the next `stopped` event before replying to `next` / `stepIn` / `stepOut`
|
||||
/// / `continue` (as php-debug / Xdebug can on fast steps), no trailing synthetic `continued` may
|
||||
/// overwrite the new stop.
|
||||
#[tokio::test]
|
||||
async fn stop_before_reply_does_not_emit_trailing_continued() {
|
||||
let h = harness(Script { stop_before_reply: true, ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let session = h.manager.session(id).unwrap();
|
||||
|
||||
let run_events = |from: usize| {
|
||||
h.events
|
||||
.lock()
|
||||
.iter()
|
||||
.skip(from)
|
||||
.filter_map(|e| match e {
|
||||
IdeEvent::Debug { event: DebugEvent::Stopped { reason, .. }, .. } => Some(format!("stopped:{reason}")),
|
||||
IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. } => Some("continued".into()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
for (label, expected) in [
|
||||
("over", "stopped:step"),
|
||||
("into", "stopped:step"),
|
||||
("out", "stopped:step"),
|
||||
("target", "stopped:step"),
|
||||
("resume", "stopped:breakpoint"),
|
||||
] {
|
||||
let before = h.events.lock().len();
|
||||
match label {
|
||||
"over" => h.manager.step(id, 1, StepKind::Over).await.unwrap(),
|
||||
"into" => h.manager.step(id, 1, StepKind::Into).await.unwrap(),
|
||||
"out" => h.manager.step(id, 1, StepKind::Out).await.unwrap(),
|
||||
"target" => h.manager.step_in_target(id, 1, 1).await.unwrap(),
|
||||
"resume" => h.manager.resume(id, 1).await.unwrap(),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
assert!(session.suspended.get(), "{label}: session must remain suspended");
|
||||
assert_eq!(run_events(before), [expected], "{label}: must not emit continued after stopped");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn continued_event_before_reply_does_not_emit_duplicate_continued() {
|
||||
for is_resume in [false, true] {
|
||||
let h = harness(Script { continued_before_reply: true, ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
|
||||
let before = h.events.lock().len();
|
||||
if is_resume {
|
||||
h.manager.resume(id, 1).await.unwrap();
|
||||
} else {
|
||||
h.manager.step(id, 1, StepKind::Over).await.unwrap();
|
||||
}
|
||||
let continued = h
|
||||
.events
|
||||
.lock()
|
||||
.iter()
|
||||
.skip(before)
|
||||
.filter(|e| matches!(e, IdeEvent::Debug { event: DebugEvent::Continued { .. }, .. }))
|
||||
.count();
|
||||
assert_eq!(continued, 1, "is_resume={is_resume}: adapter continued event already reported it");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lazy_variables_are_resolved_when_the_adapter_declares_them_safe() {
|
||||
let h = harness(Script::default());
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
//! Exception breakpoints on a chosen class, armed through a session's backend.
|
||||
|
||||
use super::*;
|
||||
use ide_jvm_inspect::{ExceptionArmState, ExceptionClassBreakpoints, ExceptionClassSpec, InspectFuture, VmTarget};
|
||||
|
||||
/// The target, the list, and the DAP requests sent before it.
|
||||
type ArmCall = (VmTarget, Vec<ExceptionClassSpec>, Vec<String>);
|
||||
|
||||
/// Records each list it is given with the DAP requests sent before it.
|
||||
struct FakeArmer {
|
||||
log: Log,
|
||||
calls: Mutex<Vec<ArmCall>>,
|
||||
}
|
||||
|
||||
impl FakeArmer {
|
||||
fn new(h: &Harness) -> Arc<Self> {
|
||||
Arc::new(Self { log: h.log.clone(), calls: Mutex::default() })
|
||||
}
|
||||
|
||||
fn lists(&self) -> Vec<Vec<String>> {
|
||||
self.calls.lock().iter().map(|(_, specs, _)| specs.iter().map(|s| s.class_name.clone()).collect()).collect()
|
||||
}
|
||||
|
||||
/// The DAP requests sent before each call.
|
||||
fn before(&self) -> Vec<Vec<String>> {
|
||||
self.calls.lock().iter().map(|(_, _, sent)| sent.clone()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExceptionClassBreakpoints for FakeArmer {
|
||||
fn set<'a>(
|
||||
&'a self,
|
||||
target: &'a VmTarget,
|
||||
breakpoints: &'a [ExceptionClassSpec],
|
||||
) -> InspectFuture<'a, Vec<(String, ExceptionArmState)>> {
|
||||
let sent = self
|
||||
.log
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|m| m["type"] == "request")
|
||||
.map(|m| m["command"].as_str().unwrap().to_owned())
|
||||
.collect();
|
||||
self.calls.lock().push((target.clone(), breakpoints.to_vec(), sent));
|
||||
let states = breakpoints.iter().map(|b| (b.id.clone(), ExceptionArmState::Armed)).collect();
|
||||
Box::pin(async move { Ok(states) })
|
||||
}
|
||||
}
|
||||
|
||||
fn class_bp(id: &str, class_name: &str) -> ExceptionClassBreakpoint {
|
||||
ExceptionClassBreakpoint {
|
||||
id: id.into(),
|
||||
class_name: class_name.into(),
|
||||
caught: true,
|
||||
uncaught: true,
|
||||
enabled: true,
|
||||
class_filters: vec![],
|
||||
class_exclusion_filters: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// A java-debug attach to a JVM on another machine: the target is known from the request alone.
|
||||
fn attach() -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
extra_json: Some(json!({"hostName": "10.0.0.5", "port": 5005}).to_string()),
|
||||
..java_config("attach")
|
||||
}
|
||||
}
|
||||
|
||||
async fn start(h: &Harness, config: LaunchConfig, armer: &Arc<FakeArmer>) -> DebugSessionId {
|
||||
let backend: Arc<dyn ExceptionClassBreakpoints> = armer.clone();
|
||||
h.manager.start_with_exception_classes(config, h.owner.clone(), |_| None, Some(backend)).await.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn armed_after_the_exception_filters_and_before_configuration_done() {
|
||||
let h = harness(Script::default());
|
||||
let armer = FakeArmer::new(&h);
|
||||
let filtered = ExceptionClassBreakpoint {
|
||||
caught: false,
|
||||
enabled: false,
|
||||
class_filters: vec!["com.acme.*".into()],
|
||||
class_exclusion_filters: vec!["*Test".into()],
|
||||
..class_bp("b", "com.acme.Boom")
|
||||
};
|
||||
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "java.lang.IllegalStateException"), filtered]).await;
|
||||
start(&h, attach(), &armer).await;
|
||||
|
||||
assert_eq!(armer.before(), [["initialize", "attach", "setExceptionBreakpoints"]]);
|
||||
let (target, specs, _) = armer.calls.lock()[0].clone();
|
||||
assert_eq!((target.pid, target.attach_host.as_deref(), target.attach_port), (None, Some("10.0.0.5"), Some(5005)));
|
||||
assert_eq!(
|
||||
specs[1],
|
||||
ExceptionClassSpec {
|
||||
id: "b".into(),
|
||||
class_name: "com.acme.Boom".into(),
|
||||
caught: false,
|
||||
uncaught: true,
|
||||
enabled: false,
|
||||
class_filters: vec!["com.acme.*".into()],
|
||||
class_exclusion_filters: vec!["*Test".into()],
|
||||
}
|
||||
);
|
||||
assert!(h.commands().contains(&"configurationDone".to_owned()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn armed_again_after_every_set_exception_breakpoints() {
|
||||
let h = harness(Script::default());
|
||||
let armer = FakeArmer::new(&h);
|
||||
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await;
|
||||
start(&h, attach(), &armer).await;
|
||||
h.manager.set_exception_breakpoints(BTreeMap::from([("raised".into(), true)])).await.unwrap();
|
||||
|
||||
assert_eq!(armer.lists(), [["com.acme.Boom"], ["com.acme.Boom"]]);
|
||||
let last = armer.before().pop().unwrap();
|
||||
assert_eq!(last.iter().filter(|c| *c == "setExceptionBreakpoints").count(), 2, "{last:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_new_list_reaches_the_sessions_that_take_it() {
|
||||
let h = harness(Script::default());
|
||||
let armer = FakeArmer::new(&h);
|
||||
start(&h, attach(), &armer).await;
|
||||
let other = h.start(attach()).await.unwrap();
|
||||
assert!(armer.lists().is_empty(), "nothing to arm at start");
|
||||
|
||||
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await;
|
||||
h.manager.set_exception_class_breakpoints(vec![]).await;
|
||||
assert_eq!(armer.lists(), [vec!["com.acme.Boom".to_owned()], vec![]], "an empty list takes them down");
|
||||
|
||||
let filters = h.manager.exception_filters(None);
|
||||
let support = |id| filters.iter().find(|f| f.session == id).unwrap().classes.clone();
|
||||
assert_eq!(support(other), None);
|
||||
let java = filters.iter().find(|f| f.session != other).unwrap().session;
|
||||
assert_eq!(
|
||||
support(java),
|
||||
Some(ExceptionClassSupport {
|
||||
family: "java".into(),
|
||||
condition: false,
|
||||
class_filters: true,
|
||||
catch_filters: false
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn nothing_is_sent_before_the_jvm_is_known() {
|
||||
let h = harness(Script::default());
|
||||
let armer = FakeArmer::new(&h);
|
||||
h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await;
|
||||
// The fake adapter sends no `process` event before `configurationDone`: no pid to name.
|
||||
start(&h, java_config("launch"), &armer).await;
|
||||
assert!(armer.lists().is_empty());
|
||||
}
|
||||
@@ -27,7 +27,6 @@ tiberius.workspace = true
|
||||
oracledb.workspace = true
|
||||
bb8.workspace = true
|
||||
tokio-util = { workspace = true, features = ["compat"] }
|
||||
dirs.workspace = true
|
||||
ide-ssh.workspace = true
|
||||
ide-http.workspace = true
|
||||
reqwest = { workspace = true, features = ["query"] }
|
||||
|
||||
@@ -22,6 +22,9 @@ const LIMIT: usize = 16 * 1024 * 1024;
|
||||
pub struct DbJdbcDriver {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// Data source preset id; absent for a generic JDBC profile.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub vendor: Option<String>,
|
||||
pub jars: Vec<String>,
|
||||
pub class_name: String,
|
||||
pub url_template: String,
|
||||
@@ -146,7 +149,7 @@ impl DbManager {
|
||||
fn jdbc_approval(&self, source: &DataSource) -> IdeResult<(PathBuf, String)> {
|
||||
let registry = self.jdbc_registry()?;
|
||||
let key = serde_json::to_vec(&(&self.root, &source.id)).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let settings = serde_json::to_vec(&(
|
||||
let mut settings = serde_json::to_vec(&(
|
||||
&source.jdbc_driver,
|
||||
&source.url,
|
||||
&source.user,
|
||||
@@ -155,6 +158,9 @@ impl DbManager {
|
||||
&source.options,
|
||||
))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
if self.jdbc_password_isolated(source) {
|
||||
settings.extend_from_slice(b"\0jdbc-password");
|
||||
}
|
||||
Ok((
|
||||
registry.with_file_name("jdbc-approvals").join(blake3::hash(&key).to_hex().as_str()),
|
||||
blake3::hash(&settings).to_hex().to_string(),
|
||||
@@ -195,6 +201,9 @@ impl DbManager {
|
||||
.into_iter()
|
||||
.find(|d| d.id == source.jdbc_driver)
|
||||
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))?;
|
||||
if !source.vendor.is_empty() && driver.vendor.as_deref() != Some(source.vendor.as_str()) {
|
||||
return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type"));
|
||||
}
|
||||
JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc"))
|
||||
.await
|
||||
.map(Box::new)
|
||||
|
||||
+149
-15
@@ -25,8 +25,8 @@ pub use conn::{Held, Pool, QueryResult, ResultColumn};
|
||||
pub use history::HistoryEntry;
|
||||
pub use plan::{PlanNode, PlanProperty};
|
||||
pub use source::{
|
||||
DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSnowflake, DbSnowflakeAuth, DbSsh,
|
||||
DbSshAuth, DbSslMode, DbTxMode,
|
||||
DataSource, DbColor, DbDriver, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection, DbSnowflake,
|
||||
DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
|
||||
};
|
||||
pub use sql::{CellValue, DbRowEdit, SortKey};
|
||||
|
||||
@@ -475,6 +475,29 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
fn non_password_snowflake(source: &DataSource) -> Option<DbSnowflake> {
|
||||
let settings = match source.driver {
|
||||
DbDriver::Snowflake => source.resolved().map(|source| source.snowflake()).unwrap_or_default(),
|
||||
DbDriver::Jdbc => source.snowflake.clone()?,
|
||||
_ => return None,
|
||||
};
|
||||
(settings.auth != DbSnowflakeAuth::Password).then_some(settings)
|
||||
}
|
||||
|
||||
fn jdbc_password_isolated(&self, source: &DataSource) -> bool {
|
||||
source.driver == DbDriver::Jdbc
|
||||
&& (Self::non_password_snowflake(source).is_some()
|
||||
|| self
|
||||
.sources()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.any(|stored| stored.id == source.id && Self::non_password_snowflake(stored).is_some()))
|
||||
}
|
||||
|
||||
fn password_key(&self, source: &DataSource) -> String {
|
||||
if self.jdbc_password_isolated(source) { secrets::jdbc_key(&source.id) } else { source.id.clone() }
|
||||
}
|
||||
|
||||
/// The connection settings of target `target` ([`DataSource::resolved`]), with
|
||||
/// its database for `<id>:<database>`.
|
||||
pub fn source(&self, target: &str) -> IdeResult<DataSource> {
|
||||
@@ -495,15 +518,21 @@ impl DbManager {
|
||||
Ok(source)
|
||||
}
|
||||
|
||||
/// Saves the data source list; connections of removed or changed sources are closed.
|
||||
/// Saves the data source list, preserving connections when only visibility rules change.
|
||||
/// Global ones (`global`) go to the app-wide list, the others to the project's.
|
||||
pub async fn save_sources(&self, sources: Vec<DataSource>) -> IdeResult<()> {
|
||||
pub async fn save_sources(&self, mut sources: Vec<DataSource>) -> IdeResult<()> {
|
||||
if sources.iter().any(|s| s.global && s.plugin_owner.is_some()) {
|
||||
return Err(IdeError::invalid("plugin-owned data sources must stay project-scoped"));
|
||||
}
|
||||
let old = {
|
||||
let _guard = plugin::EDIT.lock();
|
||||
let old = self.sources().unwrap_or_default();
|
||||
for source in sources.iter_mut().filter(|s| s.driver == DbDriver::Jdbc) {
|
||||
// Retain the credential scope even when URL-only settings supplied the old authenticator.
|
||||
if let Some(settings) = old.iter().find(|s| s.id == source.id).and_then(Self::non_password_snowflake) {
|
||||
source.snowflake = Some(settings);
|
||||
}
|
||||
}
|
||||
let (global, project): (Vec<_>, Vec<_>) = sources.iter().cloned().partition(|s| s.global);
|
||||
match &self.global {
|
||||
// Rewritten only when it changes: other projects' windows edit the same file.
|
||||
@@ -522,9 +551,10 @@ impl DbManager {
|
||||
};
|
||||
for o in old {
|
||||
match sources.iter().find(|s| s.id == o.id) {
|
||||
Some(n) if *n == o => {}
|
||||
Some(n) if o.same_except_visibility(n) => {}
|
||||
gone_or_changed => {
|
||||
let keys = [o.id.clone(), secrets::ssh_key(&o.id), Self::sso_credential(&o.id)];
|
||||
let keys =
|
||||
[o.id.clone(), secrets::jdbc_key(&o.id), secrets::ssh_key(&o.id), Self::sso_credential(&o.id)];
|
||||
match gone_or_changed {
|
||||
None => {
|
||||
self.catalogs.forget(&o.id);
|
||||
@@ -555,6 +585,31 @@ impl DbManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Updates one scope of a source's visibility against its latest saved rules.
|
||||
pub fn save_source_visibility(&self, id: &str, available: &[String], change: DbVisibilityChange) -> IdeResult<()> {
|
||||
let _guard = plugin::EDIT.lock();
|
||||
let mut sources = source::load(&self.root)?;
|
||||
let scoped_global = self.global.as_ref().filter(|_| !sources.iter().any(|source| source.id == id));
|
||||
if let Some((dir, _)) = scoped_global {
|
||||
sources = source::load_global(dir)?;
|
||||
}
|
||||
let selected = sources
|
||||
.iter_mut()
|
||||
.find(|source| source.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("no data source {id}")))?;
|
||||
let previous = selected.introspection.clone();
|
||||
change.apply(&mut selected.introspection, available);
|
||||
if selected.introspection == previous {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some((dir, _)) = scoped_global {
|
||||
source::save_global(dir, &sources)?;
|
||||
} else {
|
||||
source::save(&self.root, &sources)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Watches the data source files (the project's and the global one) for edits made
|
||||
/// outside the IDE; `on_change` runs on a background thread once they settle, and
|
||||
/// should call [`DbManager::reconcile_sources`]. Stops when the result is dropped.
|
||||
@@ -563,9 +618,9 @@ impl DbManager {
|
||||
SourcesWatch::start(&self.root, self.global.as_ref().map(|(dir, _)| dir.as_path()), on_change)
|
||||
}
|
||||
|
||||
/// Re-reads the data sources after their files changed on disk: connections of
|
||||
/// removed or changed sources close, as on [`DbManager::save_sources`] (saved
|
||||
/// passwords stay, the source may come back). Returns whether the list the tree
|
||||
/// Re-reads the data sources after their files changed on disk and closes affected
|
||||
/// connections as on [`DbManager::save_sources`] (saved passwords stay, the source
|
||||
/// may come back). Returns whether the list the tree
|
||||
/// shows changed, or the files no longer parse (the tree reports the error).
|
||||
pub async fn reconcile_sources(&self) -> bool {
|
||||
let now = match self.sources() {
|
||||
@@ -580,7 +635,7 @@ impl DbManager {
|
||||
return false;
|
||||
}
|
||||
for o in &before {
|
||||
if now.iter().find(|s| s.id == o.id) != Some(o) {
|
||||
if now.iter().find(|s| s.id == o.id).is_none_or(|n| !o.same_except_visibility(n)) {
|
||||
self.disconnect_source(&o.id).await;
|
||||
}
|
||||
}
|
||||
@@ -590,7 +645,12 @@ impl DbManager {
|
||||
/// Remembers `password` for the session, and in the saved passwords when
|
||||
/// the data source saves passwords (`None` forgets it).
|
||||
pub async fn set_password(&self, id: &str, password: Option<String>, save: bool) -> IdeResult<()> {
|
||||
self.remember(id, id.to_owned(), password, save).await
|
||||
let source = self.sources()?.into_iter().find(|s| s.id == id);
|
||||
let (store, key) = match source.as_ref() {
|
||||
Some(source) => (self.store_of(source), self.password_key(source)),
|
||||
None => (&self.saved_passwords, id.to_owned()),
|
||||
};
|
||||
self.remember(store, key, password, save).await
|
||||
}
|
||||
|
||||
/// [`DbManager::set_password`] for the SSH password / key passphrase.
|
||||
@@ -602,10 +662,10 @@ impl DbManager {
|
||||
self.ssh.set_secret(&c, secret, save);
|
||||
return Ok(());
|
||||
}
|
||||
self.remember(id, secrets::ssh_key(id), secret, save).await
|
||||
self.remember(self.saved_for(id), secrets::ssh_key(id), secret, save).await
|
||||
}
|
||||
|
||||
async fn remember(&self, id: &str, key: String, secret: Option<String>, save: bool) -> IdeResult<()> {
|
||||
async fn remember(&self, store: &SecretStore, key: String, secret: Option<String>, save: bool) -> IdeResult<()> {
|
||||
match &secret {
|
||||
Some(p) => {
|
||||
self.session_passwords.lock().insert(key.clone(), p.clone());
|
||||
@@ -614,7 +674,6 @@ impl DbManager {
|
||||
self.session_passwords.lock().remove(&key);
|
||||
}
|
||||
}
|
||||
let store = self.saved_for(id);
|
||||
let result = match (secret, save) {
|
||||
(Some(p), true) => store.set(&key, &p),
|
||||
_ => {
|
||||
@@ -640,7 +699,10 @@ impl DbManager {
|
||||
}
|
||||
|
||||
async fn password(&self, source: &DataSource) -> Option<String> {
|
||||
match self.secret(source, source.id.clone(), source.driver != DbDriver::Sqlite && source.save_password).await {
|
||||
match self
|
||||
.secret(source, self.password_key(source), source.driver != DbDriver::Sqlite && source.save_password)
|
||||
.await
|
||||
{
|
||||
Some(p) => Some(p),
|
||||
None => source.url_password(),
|
||||
}
|
||||
@@ -1763,6 +1825,78 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn switching_from_snowflake_key_pair_keeps_the_jdbc_password_separate() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path()).with_global_sources(tmp.path().join("global"));
|
||||
let native = DataSource {
|
||||
id: "snowflake".into(),
|
||||
name: "Snowflake".into(),
|
||||
driver: DbDriver::Snowflake,
|
||||
save_password: true,
|
||||
url_only: true,
|
||||
url: "jdbc:snowflake://example.invalid/?authenticator=SNOWFLAKE_JWT".into(),
|
||||
..Default::default()
|
||||
};
|
||||
db.save_sources(vec![native.clone()]).await?;
|
||||
db.set_password(&native.id, Some("native-passphrase".into()), true).await?;
|
||||
let jdbc = DataSource { driver: DbDriver::Jdbc, url: "jdbc:fixture:".into(), ..native.clone() };
|
||||
|
||||
// Test Connection can use the JDBC draft before the user saves it.
|
||||
assert_eq!(db.password(&jdbc).await, None);
|
||||
assert_eq!(db.password(&native).await.as_deref(), Some("native-passphrase"));
|
||||
|
||||
db.approve_jdbc_source(&jdbc)?;
|
||||
db.save_sources(vec![jdbc.clone()]).await?;
|
||||
assert_eq!(db.password(&db.source(&jdbc.id)?).await, None);
|
||||
db.set_password(&jdbc.id, Some("jdbc-password".into()), true).await?;
|
||||
let reopened = manager(tmp.path()).with_global_sources(tmp.path().join("global"));
|
||||
let saved = reopened.source(&jdbc.id)?;
|
||||
assert_eq!(reopened.password(&saved).await.as_deref(), Some("jdbc-password"));
|
||||
let err = reopened.pool(&jdbc.id).await.err().expect("no JDBC profile installed");
|
||||
assert!(err.message.contains("Select an installed JDBC driver profile"));
|
||||
|
||||
source::save(&reopened.root, std::slice::from_ref(&jdbc))?;
|
||||
let err = reopened.pool(&jdbc.id).await.err().expect("edited settings need approval");
|
||||
assert!(err.message.contains("Review this project's JDBC URL and properties"));
|
||||
source::save(&reopened.root, std::slice::from_ref(&saved))?;
|
||||
|
||||
let global = DataSource { global: true, ..saved };
|
||||
reopened.save_sources(vec![global.clone()]).await?;
|
||||
assert_eq!(reopened.password(&reopened.source(&jdbc.id)?).await.as_deref(), Some("jdbc-password"));
|
||||
|
||||
let native = DataSource { global: true, ..native };
|
||||
reopened.save_sources(vec![native.clone()]).await?;
|
||||
assert_eq!(reopened.password(&native).await.as_deref(), Some("native-passphrase"));
|
||||
reopened.save_sources(Vec::new()).await?;
|
||||
assert_eq!(reopened.password(&native).await, None);
|
||||
assert_eq!(reopened.password(&global).await, None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn switching_from_snowflake_password_keeps_the_password() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let db = manager(tmp.path());
|
||||
let native = DataSource {
|
||||
id: "snowflake".into(),
|
||||
name: "Snowflake".into(),
|
||||
driver: DbDriver::Snowflake,
|
||||
save_password: true,
|
||||
url_only: true,
|
||||
url: "jdbc:snowflake://example.invalid/?authenticator=snowflake".into(),
|
||||
..Default::default()
|
||||
};
|
||||
db.save_sources(vec![native.clone()]).await?;
|
||||
db.set_password(&native.id, Some("existing-password".into()), true).await?;
|
||||
let jdbc = DataSource { driver: DbDriver::Jdbc, url: "jdbc:fixture:".into(), ..native };
|
||||
assert_eq!(db.password(&jdbc).await.as_deref(), Some("existing-password"));
|
||||
db.save_sources(vec![jdbc.clone()]).await?;
|
||||
let reopened = manager(tmp.path());
|
||||
assert_eq!(reopened.password(&reopened.source(&jdbc.id)?).await.as_deref(), Some("existing-password"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn moves_plaintext_passwords_of_older_versions_off_disk() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -18,6 +18,11 @@ pub fn ssh_key(id: &str) -> String {
|
||||
format!("{id}#ssh")
|
||||
}
|
||||
|
||||
/// JDBC password when the original credential is a Snowflake passphrase or token.
|
||||
pub fn jdbc_key(id: &str) -> String {
|
||||
format!("{id}#jdbc")
|
||||
}
|
||||
|
||||
fn file_key(project: &str, key: &str) -> String {
|
||||
format!("{project}|{key}")
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, project_dir};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) const FILE: &str = "data-sources.toml";
|
||||
@@ -101,6 +102,9 @@ pub struct DbIntrospection {
|
||||
pub databases: Vec<String>,
|
||||
pub all_schemas: bool,
|
||||
pub schemas: Vec<String>,
|
||||
/// A database can replace the source's schema rules with all schemas or a list of exact names.
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub schemas_by_database: BTreeMap<String, DbSchemaSelection>,
|
||||
/// `pg_catalog`, `information_schema`, `mysql`…, and service databases (`rdsadmin`…).
|
||||
pub show_system: bool,
|
||||
/// PostgreSQL template databases (`template0`, `template1`).
|
||||
@@ -117,6 +121,7 @@ impl Default for DbIntrospection {
|
||||
databases: Vec::new(),
|
||||
all_schemas: true,
|
||||
schemas: Vec::new(),
|
||||
schemas_by_database: BTreeMap::new(),
|
||||
show_system: false,
|
||||
show_templates: false,
|
||||
object_filter: String::new(),
|
||||
@@ -125,6 +130,18 @@ impl Default for DbIntrospection {
|
||||
}
|
||||
|
||||
impl DbIntrospection {
|
||||
pub(crate) fn with_visibility_from(self, source: &Self) -> Self {
|
||||
Self {
|
||||
all_databases: source.all_databases,
|
||||
databases: source.databases.clone(),
|
||||
all_schemas: source.all_schemas,
|
||||
schemas: source.schemas.clone(),
|
||||
schemas_by_database: source.schemas_by_database.clone(),
|
||||
object_filter: source.object_filter.clone(),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the tree shows this schema: every one with `all_schemas`, otherwise it has to
|
||||
/// match one of the `schemas` patterns. The completion model uses the same test, so it
|
||||
/// offers exactly the tables the tree lists (and does not read the ones it never shows).
|
||||
@@ -163,6 +180,60 @@ fn schema_matches(pattern: &str, name: &str) -> bool {
|
||||
p[pi..].iter().all(|&c| c == '*')
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default)]
|
||||
pub struct DbSchemaSelection {
|
||||
pub all: bool,
|
||||
pub names: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum DbVisibilityChange {
|
||||
Databases { selection: DbSchemaSelection },
|
||||
Schemas { selection: DbSchemaSelection },
|
||||
DatabaseSchemas { database: String, selection: Option<DbSchemaSelection> },
|
||||
}
|
||||
|
||||
impl DbVisibilityChange {
|
||||
pub(crate) fn apply(self, introspection: &mut DbIntrospection, available: &[String]) {
|
||||
let available: std::collections::HashSet<_> = available.iter().map(String::as_str).collect();
|
||||
let keep_names = |before: &mut Vec<String>, selection: DbSchemaSelection, exact: bool| {
|
||||
if selection.all || (!exact && before.iter().any(|name| name.contains(['*', '?']))) {
|
||||
return;
|
||||
}
|
||||
before.retain(|name| !available.contains(if exact { name.as_str() } else { name.trim() }));
|
||||
let mut seen: std::collections::HashSet<_> = before.iter().cloned().collect();
|
||||
before.extend(
|
||||
selection
|
||||
.names
|
||||
.into_iter()
|
||||
.filter(|name| (exact || !name.contains(['*', '?'])) && seen.insert(name.clone())),
|
||||
);
|
||||
};
|
||||
match self {
|
||||
Self::Databases { selection } => {
|
||||
introspection.all_databases = selection.all;
|
||||
keep_names(&mut introspection.databases, selection, false);
|
||||
}
|
||||
Self::Schemas { selection } => {
|
||||
introspection.all_schemas = selection.all;
|
||||
keep_names(&mut introspection.schemas, selection, false);
|
||||
}
|
||||
Self::DatabaseSchemas { database, selection } => match selection {
|
||||
Some(selection) => {
|
||||
let rule = introspection.schemas_by_database.entry(database).or_default();
|
||||
rule.all = selection.all;
|
||||
keep_names(&mut rule.names, selection, true);
|
||||
}
|
||||
None => {
|
||||
introspection.schemas_by_database.remove(&database);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Advanced tab: a driver property. PostgreSQL: run-time parameters (and
|
||||
/// `application_name`); MySQL: session variables (and `charset`, `collation`);
|
||||
/// SQLite: pragmas. See [`crate::conn`].
|
||||
@@ -430,6 +501,14 @@ pub fn parse_url(raw: &str) -> IdeResult<ParsedUrl> {
|
||||
}
|
||||
|
||||
impl DataSource {
|
||||
pub(crate) fn same_except_visibility(&self, other: &Self) -> bool {
|
||||
if self == other {
|
||||
return true;
|
||||
}
|
||||
let introspection = other.introspection.clone().with_visibility_from(&self.introspection);
|
||||
*self == Self { introspection, ..other.clone() }
|
||||
}
|
||||
|
||||
/// The settings to connect with: with [`DataSource::url_only`], host, port,
|
||||
/// database, user, SSL and driver properties come from the URL (properties
|
||||
/// of the Advanced tab still apply after the URL's).
|
||||
@@ -661,6 +740,81 @@ mod tests {
|
||||
assert_eq!(load(tmp.path()).unwrap(), vec![s]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visibility_change_preserves_patterns_unavailable_names_and_other_scopes() {
|
||||
let mut introspection = DbIntrospection {
|
||||
schemas: vec!["app_*".into(), "unavailable_?".into()],
|
||||
databases: vec!["reporting".into(), "offline".into()],
|
||||
schemas_by_database: BTreeMap::from([
|
||||
("reporting".into(), DbSchemaSelection { all: false, names: vec!["private".into()] }),
|
||||
("sandbox".into(), DbSchemaSelection { all: false, names: vec!["experiments".into()] }),
|
||||
]),
|
||||
show_system: true,
|
||||
..Default::default()
|
||||
};
|
||||
DbVisibilityChange::Schemas { selection: DbSchemaSelection { all: false, names: vec!["demo".into()] } }
|
||||
.apply(&mut introspection, &["app_sales".into(), "demo".into()]);
|
||||
assert_eq!(introspection.schemas, ["app_*", "unavailable_?"]);
|
||||
DbVisibilityChange::Databases { selection: DbSchemaSelection { all: false, names: vec!["sandbox".into()] } }
|
||||
.apply(&mut introspection, &["reporting".into(), "sandbox".into()]);
|
||||
assert_eq!(introspection.databases, ["offline", "sandbox"]);
|
||||
DbVisibilityChange::DatabaseSchemas {
|
||||
database: "reporting".into(),
|
||||
selection: Some(DbSchemaSelection {
|
||||
all: false,
|
||||
names: vec!["finance".into(), "finance".into(), "private".into()],
|
||||
}),
|
||||
}
|
||||
.apply(&mut introspection, &["public".into(), "finance".into()]);
|
||||
assert_eq!(introspection.schemas_by_database["reporting"].names, ["private", "finance"]);
|
||||
assert_eq!(introspection.schemas_by_database["sandbox"].names, ["experiments"]);
|
||||
assert!(introspection.show_system);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_override_can_omit_default_fields() {
|
||||
let introspection: DbIntrospection = toml::from_str(
|
||||
r#"
|
||||
[schemasByDatabase.reporting]
|
||||
all = true
|
||||
|
||||
[schemasByDatabase.sandbox]
|
||||
names = ["finance"]
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
introspection.schemas_by_database,
|
||||
BTreeMap::from([
|
||||
("reporting".into(), DbSchemaSelection { all: true, names: vec![] }),
|
||||
("sandbox".into(), DbSchemaSelection { all: false, names: vec!["finance".into()] }),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_database_schema_overrides() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let source = DataSource {
|
||||
id: "postgres".into(),
|
||||
name: "PostgreSQL Demo".into(),
|
||||
driver: DbDriver::Postgres,
|
||||
introspection: DbIntrospection {
|
||||
all_schemas: false,
|
||||
schemas: vec!["app_*".into()],
|
||||
schemas_by_database: BTreeMap::from([
|
||||
("analytics".into(), DbSchemaSelection { all: true, names: vec![] }),
|
||||
("reporting.eu".into(), DbSchemaSelection { all: false, names: vec!["public".into()] }),
|
||||
("sandbox".into(), DbSchemaSelection { all: false, names: vec![] }),
|
||||
]),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
save(tmp.path(), std::slice::from_ref(&source)).unwrap();
|
||||
assert_eq!(load(tmp.path()).unwrap(), vec![source]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlserver_defaults() {
|
||||
assert_eq!(DbDriver::SqlServer.default_port(), Some(1433));
|
||||
|
||||
@@ -46,23 +46,6 @@ pub fn databases(templates: bool) -> &'static str {
|
||||
/// Databases of managed services that their users cannot use (hidden unless connected to).
|
||||
pub const INTERNAL_DATABASES: &[&str] = &["rdsadmin", "azure_maintenance", "azure_sys", "cloudsqladmin"];
|
||||
|
||||
/// Oracle system accounts hidden unless `show_system` (see the Schemas tab).
|
||||
pub const ORACLE_SYSTEM_SCHEMAS: &[&str] = &[
|
||||
"CTXSYS",
|
||||
"DBSFWUSER",
|
||||
"DVSYS",
|
||||
"GSMADMIN_INTERNAL",
|
||||
"LBACSYS",
|
||||
"MDDATA",
|
||||
"MDSYS",
|
||||
"OLAPSYS",
|
||||
"OUTLN",
|
||||
"SYS",
|
||||
"SYSTEM",
|
||||
"XDB",
|
||||
"XS$NULL",
|
||||
];
|
||||
|
||||
/// Databases available to this login; offline/restoring databases cannot be selected.
|
||||
pub fn sqlserver_databases() -> &'static str {
|
||||
"SELECT name FROM sys.databases WHERE state = 0 AND HAS_DBACCESS(name) = 1 ORDER BY name"
|
||||
|
||||
@@ -17,12 +17,14 @@ async fn jdbc_profiles_persist_and_project_files_cannot_start_drivers() -> IdeRe
|
||||
db.save_jdbc_driver(DbJdbcDriver {
|
||||
id: "fixture".into(),
|
||||
name: "Test".into(),
|
||||
vendor: None,
|
||||
jars: vec![jar.display().to_string()],
|
||||
class_name: "test.Driver".into(),
|
||||
url_template: "jdbc:test:".into(),
|
||||
})?;
|
||||
let reopened = manager(tmp.path());
|
||||
assert_eq!(reopened.jdbc_drivers()?[0].class_name, "test.Driver");
|
||||
assert_eq!(reopened.jdbc_drivers()?[0].vendor, None);
|
||||
let source = DataSource {
|
||||
id: "local".into(),
|
||||
name: "local".into(),
|
||||
@@ -53,6 +55,40 @@ async fn jdbc_profiles_persist_and_project_files_cannot_start_drivers() -> IdeRe
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn named_jdbc_sources_persist_the_type_and_reject_a_profile_for_another_type() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let jar = tmp.path().join("fixture.jar");
|
||||
std::fs::write(&jar, [])?;
|
||||
let db = manager(tmp.path());
|
||||
db.save_jdbc_driver(DbJdbcDriver {
|
||||
id: "fixture".into(),
|
||||
name: "Test".into(),
|
||||
vendor: Some("tidb".into()),
|
||||
jars: vec![jar.display().to_string()],
|
||||
class_name: "test.Driver".into(),
|
||||
url_template: String::new(),
|
||||
})?;
|
||||
let source = DataSource {
|
||||
id: "local".into(),
|
||||
name: "local".into(),
|
||||
driver: DbDriver::Jdbc,
|
||||
vendor: "mariadb".into(),
|
||||
jdbc_driver: "fixture".into(),
|
||||
url: "jdbc:test:".into(),
|
||||
..Default::default()
|
||||
};
|
||||
db.save_sources(vec![source]).await?;
|
||||
let reopened = manager(tmp.path());
|
||||
let source = reopened.source("local")?;
|
||||
assert_eq!(reopened.jdbc_drivers()?[0].vendor.as_deref(), Some("tidb"));
|
||||
assert_eq!(source.driver, DbDriver::Jdbc);
|
||||
assert_eq!(source.vendor, "mariadb");
|
||||
let err = reopened.test(&source, None, None).await.unwrap_err();
|
||||
assert!(err.message.contains("not associated with this data source type"));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
@@ -63,6 +99,7 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
db.save_jdbc_driver(DbJdbcDriver {
|
||||
id: "duck".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: None,
|
||||
jars: vec![jar],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: "jdbc:duckdb:".into(),
|
||||
@@ -135,6 +172,7 @@ async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> {
|
||||
db.save_jdbc_driver(DbJdbcDriver {
|
||||
id: "clickhouse".into(),
|
||||
name: "ClickHouse JDBC".into(),
|
||||
vendor: Some("clickhouse".into()),
|
||||
jars,
|
||||
class_name: "com.clickhouse.jdbc.ClickHouseDriver".into(),
|
||||
url_template: "jdbc:clickhouse://".into(),
|
||||
@@ -143,6 +181,7 @@ async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> {
|
||||
id: "test".into(),
|
||||
name: "ClickHouse JDBC".into(),
|
||||
driver: DbDriver::Jdbc,
|
||||
vendor: "clickhouse".into(),
|
||||
jdbc_driver: "clickhouse".into(),
|
||||
url: format!("jdbc:clickhouse://127.0.0.1:{port}/default"),
|
||||
user: "fixture".into(),
|
||||
@@ -181,6 +220,7 @@ async fn unresponsive_driver_closes_before_reconnect() -> IdeResult<()> {
|
||||
db.save_jdbc_driver(DbJdbcDriver {
|
||||
id: "fixture".into(),
|
||||
name: "Fixture".into(),
|
||||
vendor: None,
|
||||
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
|
||||
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
|
||||
url_template: String::new(),
|
||||
@@ -229,6 +269,7 @@ async fn a_lost_session_reconnects_on_the_next_statement() -> IdeResult<()> {
|
||||
db.save_jdbc_driver(DbJdbcDriver {
|
||||
id: "fixture".into(),
|
||||
name: "Fixture".into(),
|
||||
vendor: None,
|
||||
jars: vec![std::env::var("JDBC_FIXTURE_JAR").unwrap()],
|
||||
class_name: "ai.openidea.jdbc.SelfTest$Fixture".into(),
|
||||
url_template: String::new(),
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use ide_db::{
|
||||
CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit, DbTableKind, QueryResult, SortKey,
|
||||
CellValue, DataSource, DbDriver, DbManager, DbOptions, DbProperty, DbRowEdit, DbSchemaSelection, DbTableKind,
|
||||
DbVisibilityChange, QueryResult, SortKey,
|
||||
};
|
||||
|
||||
async fn setup() -> (tempfile::TempDir, DbManager) {
|
||||
@@ -242,6 +243,72 @@ async fn manual_commit_keeps_a_transaction_until_commit_or_rollback() -> IdeResu
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn visibility_edits_preserve_the_held_transaction() -> IdeResult<()> {
|
||||
let (tmp, db) = setup().await;
|
||||
let c = CancellationToken::new();
|
||||
db.set_manual_commit("s1", true).await?;
|
||||
db.execute("s1", "INSERT INTO users (name) VALUES ('dee')", 1, &c).await?;
|
||||
assert_eq!(count(&db).await, "4");
|
||||
|
||||
let mut source = db.source("s1")?;
|
||||
source.introspection.all_schemas = false;
|
||||
source.introspection.schemas.clear();
|
||||
db.save_sources(vec![source.clone()]).await?;
|
||||
assert!(db.is_connected("s1"), "saving rules must keep the active connection");
|
||||
assert_eq!(count(&db).await, "4", "the held transaction must still see its uncommitted row");
|
||||
db.save_source_visibility(
|
||||
"s1",
|
||||
&["main".into()],
|
||||
DbVisibilityChange::Schemas { selection: DbSchemaSelection { all: true, names: vec![] } },
|
||||
)?;
|
||||
assert!(db.source("s1")?.introspection.all_schemas);
|
||||
assert_eq!(count(&db).await, "4", "the scoped save must keep the live transaction");
|
||||
|
||||
db.reconcile_sources().await;
|
||||
let root = tmp.path();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let other = DbManager::new(root.to_path_buf(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
source = db.source("s1")?;
|
||||
source.introspection.object_filter = "user*".into();
|
||||
other.save_sources(vec![source.clone()]).await?;
|
||||
assert!(db.reconcile_sources().await);
|
||||
assert_eq!(count(&db).await, "4", "a visibility edit from another window must keep the transaction");
|
||||
db.finish_transaction("s1", true).await?;
|
||||
assert_eq!(count(&db).await, "4");
|
||||
|
||||
source.introspection.show_system = true;
|
||||
db.save_sources(vec![source]).await?;
|
||||
assert!(!db.is_connected("s1"), "raw metadata option changes keep their invalidation path");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn visibility_save_does_not_mask_an_unreconciled_connection_edit() -> IdeResult<()> {
|
||||
let (tmp, db) = setup().await;
|
||||
let first = db.source("s1")?;
|
||||
let second = DataSource { id: "s2".into(), name: "Another source".into(), ..first.clone() };
|
||||
db.save_sources(vec![first.clone(), second.clone()]).await?;
|
||||
db.reconcile_sources().await;
|
||||
assert!(db.is_connected("s1"));
|
||||
|
||||
let root = tmp.path();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let external = DbManager::new(root.to_path_buf(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
external.save_sources(vec![DataSource { read_only: true, ..first }, second]).await?;
|
||||
db.save_source_visibility(
|
||||
"s2",
|
||||
&["main".into()],
|
||||
DbVisibilityChange::Schemas { selection: DbSchemaSelection { all: false, names: vec![] } },
|
||||
)?;
|
||||
|
||||
assert!(db.is_connected("s1"));
|
||||
assert!(db.reconcile_sources().await);
|
||||
assert!(!db.is_connected("s1"));
|
||||
assert!(!db.source("s2")?.introspection.all_schemas);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn targets_name_a_database_of_a_data_source() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
|
||||
@@ -143,6 +143,9 @@ pub struct DockerConnection {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub endpoint: DockerEndpoint,
|
||||
/// Whether the user explicitly disconnected this connection in Services.
|
||||
#[serde(default)]
|
||||
pub disconnected: bool,
|
||||
}
|
||||
|
||||
/// A registry to log in to (Docker Hub, GHCR, a private one). The password is stored separately.
|
||||
@@ -414,6 +417,7 @@ mod tests {
|
||||
id: "c1".into(),
|
||||
name: "Build box".into(),
|
||||
endpoint: DockerEndpoint::Tcp { host: "build:2376".into(), tls_cert_dir: None },
|
||||
disconnected: true,
|
||||
}],
|
||||
registries: vec![DockerRegistry {
|
||||
id: "r1".into(),
|
||||
@@ -435,12 +439,34 @@ mod tests {
|
||||
assert!(load_settings(dir).connections.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connection_intent_defaults_to_connected_and_round_trips() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
std::fs::write(
|
||||
dir.join(SETTINGS_FILE),
|
||||
r#"{"connections":[{"id":"box","name":"Box","endpoint":{"kind":"ssh","config":"build"}}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut settings = load_settings(dir);
|
||||
assert!(!settings.connections[0].disconnected);
|
||||
for disconnected in [true, false] {
|
||||
settings.connections[0].disconnected = disconnected;
|
||||
save_settings(dir, &settings).unwrap();
|
||||
assert_eq!(load_settings(dir), settings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_drops_the_injected_default_connection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path();
|
||||
let injected =
|
||||
|| DockerConnection { id: "default".into(), name: "Docker".into(), endpoint: DockerEndpoint::Default };
|
||||
let injected = || DockerConnection {
|
||||
id: "default".into(),
|
||||
name: "Docker".into(),
|
||||
endpoint: DockerEndpoint::Default,
|
||||
disconnected: false,
|
||||
};
|
||||
let registry =
|
||||
DockerRegistry { id: "r1".into(), name: "GHCR".into(), address: "ghcr.io".into(), username: "me".into() };
|
||||
// Saved untouched by an older version (e.g. along with a registry): dropped on load.
|
||||
|
||||
@@ -18,7 +18,7 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::{Condvar, Mutex, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Listing and lifecycle commands normally answer in well under a second; a
|
||||
@@ -315,9 +315,56 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContain
|
||||
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
|
||||
}
|
||||
|
||||
/// How long log lines collect before they are handed on together.
|
||||
const LOG_BATCH: Duration = Duration::from_millis(30);
|
||||
|
||||
/// Streams a container's logs (`tail` last lines, then follows while `follow`)
|
||||
/// until it ends or `cancel` fires.
|
||||
/// until it ends or `cancel` fires. Lines arrive in batches, at most one per
|
||||
/// [`LOG_BATCH`]: a webview delivers each IPC message on its own, so a message
|
||||
/// per line made a 1000-line tail take tens of seconds on Windows.
|
||||
pub fn logs(
|
||||
ep: &DockerEndpoint,
|
||||
id: &str,
|
||||
tail: u32,
|
||||
follow: bool,
|
||||
timestamps: bool,
|
||||
cancel: &CancellationToken,
|
||||
on_lines: &(dyn Fn(Vec<DockerLogLine>) + Sync),
|
||||
) -> IdeResult<()> {
|
||||
batched(LOG_BATCH, on_lines, |on_line| stream_logs(ep, id, tail, follow, timestamps, cancel, on_line))
|
||||
}
|
||||
|
||||
/// Runs `produce` with a per-item callback and hands the items to `emit` in order,
|
||||
/// collected over `every`, from a second thread so a quiet stream still flushes.
|
||||
fn batched<T: Send, R>(every: Duration, emit: &(dyn Fn(Vec<T>) + Sync), produce: impl FnOnce(&dyn Fn(T)) -> R) -> R {
|
||||
let pending = Mutex::new(Vec::new());
|
||||
let finished = (Mutex::new(false), Condvar::new());
|
||||
let flush = || {
|
||||
let items = std::mem::take(&mut *pending.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
if !items.is_empty() {
|
||||
emit(items);
|
||||
}
|
||||
};
|
||||
std::thread::scope(|scope| {
|
||||
scope.spawn(|| {
|
||||
let (done, wake) = &finished;
|
||||
let mut stop = done.lock().unwrap_or_else(|e| e.into_inner());
|
||||
loop {
|
||||
stop = wake.wait_timeout(stop, every).unwrap_or_else(|e| e.into_inner()).0;
|
||||
flush();
|
||||
if *stop {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let result = produce(&|item| pending.lock().unwrap_or_else(|e| e.into_inner()).push(item));
|
||||
*finished.0.lock().unwrap_or_else(|e| e.into_inner()) = true;
|
||||
finished.1.notify_one();
|
||||
result
|
||||
})
|
||||
}
|
||||
|
||||
fn stream_logs(
|
||||
ep: &DockerEndpoint,
|
||||
id: &str,
|
||||
tail: u32,
|
||||
@@ -606,6 +653,27 @@ pub fn cli(
|
||||
mod local_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn log_lines_arrive_in_order_as_few_batches() {
|
||||
let batches = Mutex::new(Vec::<Vec<u32>>::new());
|
||||
let result = batched(Duration::from_millis(30), &|b| batches.lock().unwrap().push(b), |line| {
|
||||
(0..1000).for_each(line);
|
||||
// Wait for the flusher to emit the whole burst rather than assuming a fixed
|
||||
// sleep outlasts its scheduling: a loaded runner can starve the thread
|
||||
// past the quiet spell and fold the trailing line into the burst.
|
||||
while batches.lock().unwrap().iter().map(Vec::len).sum::<usize>() < 1000 {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
line(1000);
|
||||
"done"
|
||||
});
|
||||
assert_eq!(result, "done");
|
||||
let batches = batches.into_inner().unwrap();
|
||||
assert_eq!(batches.concat(), (0..=1000).collect::<Vec<_>>(), "every line once, in order");
|
||||
assert!(batches.len() <= 3, "a burst is one message, not one per line: {} batches", batches.len());
|
||||
assert_eq!(batches.last().unwrap(), &[1000], "a line after a quiet spell is flushed on its own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selected_context_overrides_docker_host() {
|
||||
let local = "unix:///var/run/docker.sock";
|
||||
|
||||
+190
-154
@@ -1,180 +1,216 @@
|
||||
//! Child processes of the docker CLI: bounded runs and cancellable line streams.
|
||||
//! The docker CLI as a child process: bounded runs and cancellable line streams.
|
||||
|
||||
use ide_core::process::terminate_tree;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
use ide_core::cli_process::{CliTool, Decoding, Input};
|
||||
pub(crate) use ide_core::cli_process::{Output, Stream};
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
/// How long a cancelled or timed-out child's process group (CLI plugins such as compose)
|
||||
/// gets to exit on `SIGTERM`, and clean up, before `SIGKILL`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Stream {
|
||||
Stdout,
|
||||
Stderr,
|
||||
}
|
||||
|
||||
fn prepare(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::prepare(ide_core::process::own_group(cmd));
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run docker: {e}")))
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
ide_core::output_encoding::decode_tool_output(&buf)
|
||||
})
|
||||
}
|
||||
const DOCKER: CliTool = CliTool::new("docker", Decoding::ToolOutput);
|
||||
|
||||
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
|
||||
/// a non-zero exit is reported in [`Output::success`], not as an error.
|
||||
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
run_with_input(cmd, timeout, cancel, None)
|
||||
DOCKER.run(cmd, timeout, cancel)
|
||||
}
|
||||
|
||||
/// [`run`] with `input` written to the child's stdin (e.g. `--password-stdin`).
|
||||
pub(crate) fn run_with_input(
|
||||
mut cmd: Command,
|
||||
cmd: Command,
|
||||
timeout: Duration,
|
||||
cancel: Option<&CancellationToken>,
|
||||
input: Option<&str>,
|
||||
) -> IdeResult<Output> {
|
||||
prepare(&mut cmd);
|
||||
if input.is_some() {
|
||||
cmd.stdin(Stdio::piped());
|
||||
}
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
if let (Some(text), Some(mut stdin)) = (input, child.stdin.take()) {
|
||||
// Dropping `stdin` afterwards closes it, so the CLI sees EOF.
|
||||
let _ = std::io::Write::write_all(&mut stdin, text.as_bytes());
|
||||
}
|
||||
let out = child.stdout.take().map(read_all);
|
||||
let err = child.stderr.take().map(read_all);
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::unavailable("docker did not respond in time"));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(Output {
|
||||
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
success: status.success(),
|
||||
})
|
||||
}
|
||||
|
||||
enum Event {
|
||||
Line(Stream, String),
|
||||
Closed,
|
||||
}
|
||||
|
||||
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stream: Stream) {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
let mut pending: Vec<u8> = Vec::new();
|
||||
let flush = |pending: &mut Vec<u8>| {
|
||||
if !pending.is_empty() {
|
||||
let line = ide_core::output_encoding::decode_tool_output(pending).trim_end().to_string();
|
||||
pending.clear();
|
||||
let _ = tx.send(Event::Line(stream, line));
|
||||
}
|
||||
};
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
for &b in &buf[..n] {
|
||||
// `\r` too: pull / build progress rewrites its line in place.
|
||||
if b == b'\n' || b == b'\r' {
|
||||
flush(&mut pending);
|
||||
} else {
|
||||
pending.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(&mut pending);
|
||||
let _ = tx.send(Event::Closed);
|
||||
});
|
||||
DOCKER.run_with_input(cmd, input.map(Input::Inline), timeout, cancel)
|
||||
}
|
||||
|
||||
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
|
||||
/// fires. Returns whether it exited successfully plus the last stderr lines.
|
||||
pub(crate) fn stream(
|
||||
mut cmd: Command,
|
||||
cmd: Command,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &mut dyn FnMut(Stream, String),
|
||||
) -> IdeResult<(bool, Vec<String>)> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
prepare(&mut cmd);
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
let (tx, rx) = mpsc::channel::<Event>();
|
||||
let mut open = 0;
|
||||
if let Some(out) = child.stdout.take() {
|
||||
spawn_reader(out, tx.clone(), Stream::Stdout);
|
||||
open += 1;
|
||||
}
|
||||
if let Some(err) = child.stderr.take() {
|
||||
spawn_reader(err, tx.clone(), Stream::Stderr);
|
||||
open += 1;
|
||||
}
|
||||
drop(tx);
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
while open > 0 {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(50)) {
|
||||
Ok(Event::Line(stream, line)) => {
|
||||
if stream == Stream::Stderr && !line.trim().is_empty() {
|
||||
stderr_tail.push(line.clone());
|
||||
if stderr_tail.len() > 20 {
|
||||
stderr_tail.remove(0);
|
||||
}
|
||||
}
|
||||
on_line(stream, line);
|
||||
DOCKER.stream(cmd, cancel, on_line)
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::process::process_alive;
|
||||
use std::time::Instant;
|
||||
|
||||
const LONG: Duration = Duration::from_secs(30);
|
||||
|
||||
fn sh(script: &str) -> Command {
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.args(["-c", script]);
|
||||
cmd
|
||||
}
|
||||
|
||||
/// A script that records its pid in `name`'s file, then runs `rest`.
|
||||
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
|
||||
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_file(&file);
|
||||
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
|
||||
}
|
||||
|
||||
fn recorded_pid(file: &std::path::Path) -> u32 {
|
||||
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
|
||||
let _ = std::fs::remove_file(file);
|
||||
pid
|
||||
}
|
||||
|
||||
/// Cancels `cancel` once the script has recorded its pid.
|
||||
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
|
||||
let (file, cancel) = (file.to_owned(), cancel.clone());
|
||||
std::thread::spawn(move || {
|
||||
while !file.exists() {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Ok(Event::Closed) => open -= 1,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
cancel.cancel();
|
||||
});
|
||||
}
|
||||
|
||||
fn assert_gone(pid: u32) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while process_alive(pid) {
|
||||
assert!(Instant::now() < deadline, "process {pid} survived");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_status_is_reported_not_raised() {
|
||||
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
|
||||
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_streams_are_captured_separately_and_in_order() {
|
||||
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout, "a\nb\nc\n");
|
||||
assert_eq!(out.stderr, "x\ny\n");
|
||||
assert!(out.success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_utf8_is_replaced_in_collected_output() {
|
||||
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
|
||||
assert_eq!(out.stderr, "a\u{FFFD}b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_input_stdin_is_closed() {
|
||||
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_reaches_the_child_stdin_and_is_then_closed() {
|
||||
let out = run_with_input(sh("cat"), LONG, None, Some("secret\nmore")).unwrap();
|
||||
assert_eq!(out.stdout, "secret\nmore");
|
||||
assert!(out.success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_program_is_unavailable() {
|
||||
let err = run(Command::new("/nonexistent/openidea-docker"), LONG, None).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "could not run docker: No such file or directory (os error 2)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("docker-timeout", "exec sleep 30");
|
||||
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "docker did not respond in time");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_run_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("docker-cancel", "exec sleep 30");
|
||||
let cancel = CancellationToken::new();
|
||||
cancel_when_recorded(&file, &cancel);
|
||||
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok((status.success(), stderr_tail))
|
||||
|
||||
fn collect(script: &str) -> (bool, Vec<(Stream, String)>, Vec<String>) {
|
||||
let mut lines = Vec::new();
|
||||
let (ok, tail) = stream(sh(script), &CancellationToken::new(), &mut |s, l| lines.push((s, l))).unwrap();
|
||||
(ok, lines, tail)
|
||||
}
|
||||
|
||||
fn of(lines: &[(Stream, String)], which: Stream) -> Vec<&str> {
|
||||
lines.iter().filter(|(s, _)| *s == which).map(|(_, l)| l.as_str()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_splits_lines_at_lf_cr_and_crlf_and_trims_their_ends() {
|
||||
let (ok, lines, _) = collect("printf 'a\\nb\\r\\nc\\rd \\n\\n\\ne'");
|
||||
assert!(ok);
|
||||
assert_eq!(of(&lines, Stream::Stdout), ["a", "b", "c", "d", "e"]);
|
||||
assert!(of(&lines, Stream::Stderr).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_labels_each_line_with_its_pipe() {
|
||||
let (_, lines, _) = collect("echo out1; echo err1 >&2; echo out2");
|
||||
assert_eq!(of(&lines, Stream::Stdout), ["out1", "out2"]);
|
||||
assert_eq!(of(&lines, Stream::Stderr), ["err1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_reports_the_exit_status() {
|
||||
assert!(collect("exit 0").0);
|
||||
assert!(!collect("exit 2").0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_replaces_invalid_utf8() {
|
||||
let (_, lines, _) = collect("printf 'a\\377b\\n'");
|
||||
assert_eq!(of(&lines, Stream::Stdout), ["a\u{FFFD}b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_keeps_the_last_twenty_non_blank_stderr_lines() {
|
||||
let (_, lines, tail) = collect("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done");
|
||||
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
|
||||
assert_eq!(tail, expected);
|
||||
assert_eq!(of(&lines, Stream::Stderr).len(), 26, "blank lines are still handed over");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
let err = stream(Command::new("/nonexistent/openidea-docker"), &cancel, &mut |_, _| {}).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("docker-stream-cancel", "echo started; exec sleep 30");
|
||||
let cancel = CancellationToken::new();
|
||||
let err = stream(cmd, &cancel, &mut |_, _| cancel.cancel()).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_program_cannot_be_streamed() {
|
||||
let err = stream(Command::new("/nonexistent/openidea-docker"), &CancellationToken::new(), &mut |_, _| {})
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "could not run docker: No such file or directory (os error 2)");
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ide-core.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
|
||||
@@ -382,10 +382,6 @@ impl Ledger {
|
||||
}
|
||||
grant.binaries.get(&key).cloned()
|
||||
}
|
||||
|
||||
pub fn subjects(&self) -> impl Iterator<Item = (&Subject, &Grant)> {
|
||||
self.grants.iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a confirmation page shows: every capability with its risk, high risk first.
|
||||
|
||||
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.14.0";
|
||||
pub const ENGINE_VERSION: &str = "1.15.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
@@ -164,6 +164,7 @@ pub const EVENT_KINDS: &[&str] = &[
|
||||
"file-saved",
|
||||
"files-changed",
|
||||
"editor-focused",
|
||||
"caret-moved",
|
||||
"action-performed",
|
||||
"vcs-changed",
|
||||
"problems-changed",
|
||||
|
||||
@@ -122,13 +122,34 @@ pub struct Prepared {
|
||||
pub key: Option<String>,
|
||||
/// User-facing one-liner for the plugin details page ("Insert Date").
|
||||
pub label: String,
|
||||
/// When set, this entry is skipped with a plugin load warning instead of failing the plugin.
|
||||
pub warning: Option<String>,
|
||||
/// Makes it take effect. Must not fail for reasons `prepare` could have checked.
|
||||
pub commit: Commit,
|
||||
}
|
||||
|
||||
impl Prepared {
|
||||
pub fn new(label: impl Into<String>, commit: impl FnOnce() -> Result<Disposable, String> + Send + 'static) -> Self {
|
||||
Self { capabilities: Vec::new(), files: Vec::new(), key: None, label: label.into(), commit: Box::new(commit) }
|
||||
Self {
|
||||
capabilities: Vec::new(),
|
||||
files: Vec::new(),
|
||||
key: None,
|
||||
label: label.into(),
|
||||
warning: None,
|
||||
commit: Box::new(commit),
|
||||
}
|
||||
}
|
||||
|
||||
/// Skips an invalid declaration with a load warning while letting the rest of the plugin load.
|
||||
pub fn skipped(warning: impl Into<String>) -> Self {
|
||||
Self {
|
||||
capabilities: Vec::new(),
|
||||
files: Vec::new(),
|
||||
key: None,
|
||||
label: String::new(),
|
||||
warning: Some(warning.into()),
|
||||
commit: Box::new(|| Ok(Disposable::noop())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key(mut self, key: impl Into<String>) -> Self {
|
||||
|
||||
@@ -116,10 +116,6 @@ impl ExtensionRegistry {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn point_ids(&self) -> Vec<&'static str> {
|
||||
self.points.read().keys().copied().collect()
|
||||
}
|
||||
|
||||
pub fn placement(&self, point: &str) -> Option<Placement> {
|
||||
self.points.read().get(point).map(|p| p.placement())
|
||||
}
|
||||
@@ -270,6 +266,12 @@ impl ExtensionRegistry {
|
||||
let prepared = point
|
||||
.prepare(pkg, decl)
|
||||
.map_err(|e| format!("contributes.{point_id}[{i}]: {}", strip_prefix(&e, point_id)))?;
|
||||
if let Some(warning) = prepared.warning {
|
||||
let msg = format!("contributes.{point_id}[{i}]: {}", strip_prefix(&warning, point_id));
|
||||
tracing::warn!(plugin = %pkg.id(), "{msg}");
|
||||
set.warnings.push(msg);
|
||||
continue;
|
||||
}
|
||||
for cap in &prepared.capabilities {
|
||||
if !set.capabilities.contains(cap) {
|
||||
set.capabilities.push(cap.clone());
|
||||
|
||||
+196
-158
@@ -1,184 +1,222 @@
|
||||
//! Child processes of the gh CLI: bounded runs and cancellable line streams.
|
||||
//! The gh CLI as a child process: bounded runs and cancellable line streams.
|
||||
|
||||
use ide_core::process::terminate_tree;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use std::io::Read;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
use ide_core::cli_process::{CliTool, Decoding, Input};
|
||||
pub(crate) use ide_core::cli_process::{Output, Stream};
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
/// How long a cancelled or timed-out child's process group (gh spawns git and helpers)
|
||||
/// gets to exit on `SIGTERM` before `SIGKILL`: git removes its lock files on `SIGTERM`.
|
||||
const KILL_GRACE: Duration = Duration::from_millis(20);
|
||||
|
||||
pub(crate) struct Output {
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Stream {
|
||||
Stdout,
|
||||
Stderr,
|
||||
}
|
||||
|
||||
fn prepare(cmd: &mut Command) {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::prepare(ide_core::process::own_group(cmd));
|
||||
}
|
||||
|
||||
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run gh: {e}")))
|
||||
}
|
||||
|
||||
fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle<String> {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
String::from_utf8_lossy(&buf).into_owned()
|
||||
})
|
||||
}
|
||||
const GH: CliTool = CliTool::new("gh", Decoding::Utf8Lossy);
|
||||
|
||||
/// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires;
|
||||
/// a non-zero exit is reported in [`Output::success`], not as an error.
|
||||
pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult<Output> {
|
||||
run_with_input(cmd, None, timeout, cancel)
|
||||
GH.run(cmd, timeout, cancel)
|
||||
}
|
||||
|
||||
/// [`run`] with `input` written to the child's stdin (then closed).
|
||||
pub(crate) fn run_with_input(
|
||||
mut cmd: Command,
|
||||
cmd: Command,
|
||||
input: Option<&str>,
|
||||
timeout: Duration,
|
||||
cancel: Option<&CancellationToken>,
|
||||
) -> IdeResult<Output> {
|
||||
prepare(&mut cmd);
|
||||
if input.is_some() {
|
||||
cmd.stdin(Stdio::piped());
|
||||
}
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) {
|
||||
let input = input.to_owned();
|
||||
// A writer thread: a large body must not block on a full pipe while gh is not reading yet.
|
||||
std::thread::spawn(move || {
|
||||
use std::io::Write;
|
||||
let _ = stdin.write_all(input.as_bytes());
|
||||
});
|
||||
}
|
||||
let out = child.stdout.take().map(read_all);
|
||||
let err = child.stderr.take().map(read_all);
|
||||
let deadline = Instant::now() + timeout;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_some_and(CancellationToken::is_cancelled) {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::unavailable("gh did not respond in time"));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(Output {
|
||||
stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(),
|
||||
success: status.success(),
|
||||
})
|
||||
}
|
||||
|
||||
enum Event {
|
||||
Line(Stream, String),
|
||||
Closed,
|
||||
}
|
||||
|
||||
fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender<Event>, stream: Stream) {
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
let mut pending: Vec<u8> = Vec::new();
|
||||
let flush = |pending: &mut Vec<u8>| {
|
||||
if !pending.is_empty() {
|
||||
let line = String::from_utf8_lossy(pending).trim_end().to_string();
|
||||
pending.clear();
|
||||
let _ = tx.send(Event::Line(stream, line));
|
||||
}
|
||||
};
|
||||
loop {
|
||||
match pipe.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
for &b in &buf[..n] {
|
||||
// `\r` too: git progress rewrites its line in place.
|
||||
if b == b'\n' || b == b'\r' {
|
||||
flush(&mut pending);
|
||||
} else {
|
||||
pending.push(b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
flush(&mut pending);
|
||||
let _ = tx.send(Event::Closed);
|
||||
});
|
||||
GH.run_with_input(cmd, input.map(Input::Threaded), timeout, cancel)
|
||||
}
|
||||
|
||||
/// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel`
|
||||
/// fires. Returns whether it exited successfully plus the last stderr lines.
|
||||
pub(crate) fn stream(
|
||||
mut cmd: Command,
|
||||
cmd: Command,
|
||||
cancel: &CancellationToken,
|
||||
on_line: &mut dyn FnMut(Stream, String),
|
||||
) -> IdeResult<(bool, Vec<String>)> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
prepare(&mut cmd);
|
||||
let mut child = spawn(&mut cmd)?;
|
||||
let (tx, rx) = mpsc::channel::<Event>();
|
||||
let mut open = 0;
|
||||
if let Some(out) = child.stdout.take() {
|
||||
spawn_reader(out, tx.clone(), Stream::Stdout);
|
||||
open += 1;
|
||||
}
|
||||
if let Some(err) = child.stderr.take() {
|
||||
spawn_reader(err, tx.clone(), Stream::Stderr);
|
||||
open += 1;
|
||||
}
|
||||
drop(tx);
|
||||
let mut stderr_tail: Vec<String> = Vec::new();
|
||||
while open > 0 {
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(50)) {
|
||||
Ok(Event::Line(stream, line)) => {
|
||||
if stream == Stream::Stderr && !line.trim().is_empty() {
|
||||
stderr_tail.push(line.clone());
|
||||
if stderr_tail.len() > 20 {
|
||||
stderr_tail.remove(0);
|
||||
}
|
||||
}
|
||||
on_line(stream, line);
|
||||
GH.stream(cmd, cancel, on_line)
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::process::process_alive;
|
||||
use std::time::Instant;
|
||||
|
||||
const LONG: Duration = Duration::from_secs(30);
|
||||
|
||||
fn sh(script: &str) -> Command {
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.args(["-c", script]);
|
||||
cmd
|
||||
}
|
||||
|
||||
/// A script that records its pid in `name`'s file, then runs `rest`.
|
||||
fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) {
|
||||
let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_file(&file);
|
||||
(sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file)
|
||||
}
|
||||
|
||||
fn recorded_pid(file: &std::path::Path) -> u32 {
|
||||
let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap();
|
||||
let _ = std::fs::remove_file(file);
|
||||
pid
|
||||
}
|
||||
|
||||
/// Cancels `cancel` once the script has recorded its pid.
|
||||
fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) {
|
||||
let (file, cancel) = (file.to_owned(), cancel.clone());
|
||||
std::thread::spawn(move || {
|
||||
while !file.exists() {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
Ok(Event::Closed) => open -= 1,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
cancel.cancel();
|
||||
});
|
||||
}
|
||||
|
||||
fn assert_gone(pid: u32) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while process_alive(pid) {
|
||||
assert!(Instant::now() < deadline, "process {pid} survived");
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_exit_status_is_reported_not_raised() {
|
||||
assert!(run(sh("exit 0"), LONG, None).unwrap().success);
|
||||
assert!(!run(sh("exit 3"), LONG, None).unwrap().success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_streams_are_captured_separately_and_in_order() {
|
||||
let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout, "a\nb\nc\n");
|
||||
assert_eq!(out.stderr, "x\ny\n");
|
||||
assert!(out.success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_utf8_is_replaced_in_collected_output() {
|
||||
let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout, "ok\n\u{FFFD}\n");
|
||||
assert_eq!(out.stderr, "a\u{FFFD}b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_input_stdin_is_closed() {
|
||||
assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_reaches_the_child_stdin_and_is_then_closed() {
|
||||
let out = run_with_input(sh("cat"), Some("secret\nmore"), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout, "secret\nmore");
|
||||
assert!(out.success);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_larger_than_the_pipe_does_not_block_the_child_output() {
|
||||
let body = "0123456789abcdef".repeat(64 * 1024);
|
||||
let out = run_with_input(sh("cat"), Some(&body), LONG, None).unwrap();
|
||||
assert_eq!(out.stdout.len(), body.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_program_is_unavailable() {
|
||||
let err = run(Command::new("/nonexistent/openidea-gh"), LONG, None).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "could not run gh: No such file or directory (os error 2)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_past_its_timeout_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("gh-timeout", "exec sleep 30");
|
||||
let err = run(cmd, Duration::from_secs(1), None).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "gh did not respond in time");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
break status;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
terminate_tree(&mut child, KILL_GRACE);
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok((status.success(), stderr_tail))
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_run_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("gh-cancel", "exec sleep 30");
|
||||
let cancel = CancellationToken::new();
|
||||
cancel_when_recorded(&file, &cancel);
|
||||
let err = run(cmd, LONG, Some(&cancel)).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
fn collect(script: &str) -> (bool, Vec<(Stream, String)>, Vec<String>) {
|
||||
let mut lines = Vec::new();
|
||||
let (ok, tail) = stream(sh(script), &CancellationToken::new(), &mut |s, l| lines.push((s, l))).unwrap();
|
||||
(ok, lines, tail)
|
||||
}
|
||||
|
||||
fn of(lines: &[(Stream, String)], which: Stream) -> Vec<&str> {
|
||||
lines.iter().filter(|(s, _)| *s == which).map(|(_, l)| l.as_str()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_splits_lines_at_lf_cr_and_crlf_and_trims_their_ends() {
|
||||
let (ok, lines, _) = collect("printf 'a\\nb\\r\\nc\\rd \\n\\n\\ne'");
|
||||
assert!(ok);
|
||||
assert_eq!(of(&lines, Stream::Stdout), ["a", "b", "c", "d", "e"]);
|
||||
assert!(of(&lines, Stream::Stderr).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_labels_each_line_with_its_pipe() {
|
||||
let (_, lines, _) = collect("echo out1; echo err1 >&2; echo out2");
|
||||
assert_eq!(of(&lines, Stream::Stdout), ["out1", "out2"]);
|
||||
assert_eq!(of(&lines, Stream::Stderr), ["err1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_reports_the_exit_status() {
|
||||
assert!(collect("exit 0").0);
|
||||
assert!(!collect("exit 2").0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_replaces_invalid_utf8() {
|
||||
let (_, lines, _) = collect("printf 'a\\377b\\n'");
|
||||
assert_eq!(of(&lines, Stream::Stdout), ["a\u{FFFD}b"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_keeps_the_last_twenty_non_blank_stderr_lines() {
|
||||
let (_, lines, tail) = collect("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done");
|
||||
let expected: Vec<String> = (6..=25).map(|i| format!("e{i}")).collect();
|
||||
assert_eq!(tail, expected);
|
||||
assert_eq!(of(&lines, Stream::Stderr).len(), 26, "blank lines are still handed over");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_cancelled_before_it_starts_does_not_spawn() {
|
||||
let cancel = CancellationToken::new();
|
||||
cancel.cancel();
|
||||
let err = stream(Command::new("/nonexistent/openidea-gh"), &cancel, &mut |_, _| {}).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() {
|
||||
let (cmd, file) = recording_pid("gh-stream-cancel", "echo started; exec sleep 30");
|
||||
let cancel = CancellationToken::new();
|
||||
let err = stream(cmd, &cancel, &mut |_, _| cancel.cancel()).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Cancelled);
|
||||
assert_eq!(err.message, "cancelled");
|
||||
assert_gone(recorded_pid(&file));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_program_cannot_be_streamed() {
|
||||
let err =
|
||||
stream(Command::new("/nonexistent/openidea-gh"), &CancellationToken::new(), &mut |_, _| {}).err().unwrap();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(err.message, "could not run gh: No such file or directory (os error 2)");
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,13 @@ uuid.workspace = true
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[features]
|
||||
# `testing`: the `.hprof` fixture builders, for tests and benches of this crate and of crates built on it.
|
||||
testing = []
|
||||
|
||||
[dev-dependencies]
|
||||
# Self dev-dependency: turns `testing` on for this crate's benches, so a plain `cargo bench -p ide-heap` builds them.
|
||||
ide-heap = { workspace = true, features = ["testing"] }
|
||||
criterion = { version = "0.5", default-features = false }
|
||||
proptest.workspace = true
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -20,7 +20,7 @@ mod strings;
|
||||
#[cfg(test)]
|
||||
mod test_index;
|
||||
/// Fixture builders shared by this crate's tests and by dependants' tests and benches; not API.
|
||||
#[doc(hidden)]
|
||||
#[cfg(any(test, feature = "testing"))]
|
||||
pub mod testing;
|
||||
|
||||
pub use analysis::{AnalyzeOptions, analyze};
|
||||
|
||||
@@ -78,6 +78,7 @@ zip.workspace = true
|
||||
quick-xml = "0.42"
|
||||
|
||||
[dev-dependencies]
|
||||
ide-heap = { workspace = true, features = ["testing"] }
|
||||
ide-ssh = { workspace = true, features = ["testing"] }
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "io-util", "test-util"] }
|
||||
criterion = { version = "0.5", default-features = false }
|
||||
|
||||
@@ -33,7 +33,7 @@ impl AgentSecrets {
|
||||
)
|
||||
}
|
||||
|
||||
pub fn with_store(store: SecretFile, local: PathBuf) -> Self {
|
||||
fn with_store(store: SecretFile, local: PathBuf) -> Self {
|
||||
Self { store, local, lock: Mutex::new(()) }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! `openidea-server --stdio`: the IDE backend for remote development, serving
|
||||
//! one desktop client over stdin / stdout (started by the client over SSH).
|
||||
//! `openidea-server`: the IDE backend for remote development, either serving one
|
||||
//! desktop client over stdin / stdout (`--stdio`) or running as a persistent
|
||||
//! per-project daemon (`--attach <project>`).
|
||||
|
||||
use ide_host::catalogue::TrustClass;
|
||||
use ide_host::plugins::remote::{RemotePluginLanguages, SYNC_COMMAND};
|
||||
@@ -10,6 +11,12 @@ use ide_language::LanguageRegistry;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
enum Mode {
|
||||
Stdio,
|
||||
#[cfg(unix)]
|
||||
Daemon(PathBuf, ide_host::daemon::BuildId),
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let raw_args: Vec<String> = std::env::args().collect();
|
||||
if let Some(project) = ide_mcp::stdio_request(&raw_args) {
|
||||
@@ -35,18 +42,48 @@ fn main() {
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
if !args.iter().any(|a| a == "--stdio") {
|
||||
eprintln!(
|
||||
"usage: openidea-server --stdio | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
|
||||
);
|
||||
std::process::exit(2);
|
||||
let base = server_home();
|
||||
#[cfg(unix)]
|
||||
if args.first().is_some_and(|a| a == "--attach") {
|
||||
let Some(project_path) = args.get(1).filter(|p| !p.is_empty()) else {
|
||||
eprintln!("usage: openidea-server --attach <project-path>");
|
||||
std::process::exit(2);
|
||||
};
|
||||
let home = dirs::home_dir().unwrap_or_default();
|
||||
let code =
|
||||
match ide_host::daemon::attach(&base, &home, project_path, std::io::stdin(), std::io::stdout().lock()) {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
1
|
||||
}
|
||||
};
|
||||
std::process::exit(code);
|
||||
}
|
||||
let mode = match args.as_slice() {
|
||||
#[cfg(unix)]
|
||||
[flag, sock, build] if flag == "--daemon" => {
|
||||
let Ok(build) = build.as_bytes().try_into() else {
|
||||
eprintln!("invalid daemon build identifier");
|
||||
std::process::exit(2);
|
||||
};
|
||||
Mode::Daemon(PathBuf::from(sock), build)
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
[flag, _] if flag == "--attach" => Mode::Stdio,
|
||||
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
|
||||
_ => {
|
||||
eprintln!(
|
||||
"usage: openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
|
||||
);
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
// stdout carries the protocol: logs go to stderr.
|
||||
tracing_subscriber::fmt()
|
||||
.with_writer(std::io::stderr)
|
||||
.with_env_filter(tracing_subscriber::EnvFilter::try_from_env("OPENIDEA_LOG").unwrap_or_else(|_| "info".into()))
|
||||
.init();
|
||||
let base = server_home();
|
||||
// An SSH exec channel gets a minimal environment: take the login shell's, read
|
||||
// afresh on every start, plus the IDE-managed tools. Before any other thread starts.
|
||||
ide_host::shell_env::inherit_login_shell_env("openidea-server");
|
||||
@@ -55,7 +92,7 @@ fn main() {
|
||||
ide_dap::adapter::set_tools_root(ide_tools::tools_dir(&data_dir));
|
||||
ide_sdk::java::add_jdk_root(&ide_tools::jdk::jdks_dir(&data_dir));
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
|
||||
let code = runtime.block_on(run(base));
|
||||
let code = runtime.block_on(run(base, mode));
|
||||
std::process::exit(code);
|
||||
}
|
||||
|
||||
@@ -64,7 +101,7 @@ fn server_home() -> PathBuf {
|
||||
std::env::var_os("OPENIDEA_SERVER_HOME").map(PathBuf::from).unwrap_or_else(|| home.join(".openidea"))
|
||||
}
|
||||
|
||||
async fn run(base: PathBuf) -> i32 {
|
||||
async fn run(base: PathBuf, mode: Mode) -> i32 {
|
||||
let (config_dir, data_dir) = (base.join("config"), base.join("data"));
|
||||
for dir in [&config_dir, &data_dir] {
|
||||
if let Err(e) = std::fs::create_dir_all(dir) {
|
||||
@@ -82,40 +119,103 @@ async fn run(base: PathBuf) -> i32 {
|
||||
// The desktop's plugin languages (`plugin_sync_languages`); programs pinned on this machine.
|
||||
let plugin_languages = RemotePluginLanguages::new(Some(&data_dir));
|
||||
languages.attach_plugins(plugin_languages.store().clone());
|
||||
let peer = Arc::new(OnceLock::new());
|
||||
let sink_peer = peer.clone();
|
||||
let plugins_data = data_dir.clone();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir,
|
||||
local_data_dir: data_dir.clone(),
|
||||
data_dir,
|
||||
languages,
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: true,
|
||||
}));
|
||||
// A stable path for `--mcp-stdio` client configurations across server upgrades.
|
||||
match mode {
|
||||
Mode::Stdio => {
|
||||
let peer = Arc::new(OnceLock::new());
|
||||
let sink_peer = peer.clone();
|
||||
let plugins_data = data_dir.clone();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir,
|
||||
local_data_dir: data_dir.clone(),
|
||||
data_dir,
|
||||
languages,
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: true,
|
||||
}));
|
||||
start_mcp(&host, &base);
|
||||
let plugins = start_plugins(&plugins_data, &host, peer.clone());
|
||||
inherit_trust(&host);
|
||||
tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION"));
|
||||
let dispatcher = build_dispatcher(&plugins, plugin_languages);
|
||||
rpc::serve(host.clone(), dispatcher, peer, tokio::io::stdin(), tokio::io::stdout()).await;
|
||||
shutdown_all(&host, plugins.as_ref()).await;
|
||||
0
|
||||
}
|
||||
#[cfg(unix)]
|
||||
Mode::Daemon(socket, build) => {
|
||||
let peer = Arc::new(rpc::PeerSlot::default());
|
||||
let sink_peer = peer.clone();
|
||||
let plugins_data = data_dir.clone();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir,
|
||||
local_data_dir: data_dir.clone(),
|
||||
data_dir,
|
||||
languages,
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: true,
|
||||
}));
|
||||
start_mcp(&host, &base);
|
||||
let plugins = start_plugins(&plugins_data, &host, peer.clone());
|
||||
inherit_trust(&host);
|
||||
tracing::info!("openidea-server {} daemon ready at {}", env!("CARGO_PKG_VERSION"), socket.display());
|
||||
let dispatcher = build_dispatcher(&plugins, plugin_languages);
|
||||
let result = ide_host::daemon::serve(
|
||||
&socket,
|
||||
build,
|
||||
host.clone(),
|
||||
dispatcher,
|
||||
peer,
|
||||
shutdown_all(&host, plugins.as_ref()),
|
||||
)
|
||||
.await;
|
||||
match result {
|
||||
Ok(()) => 0,
|
||||
Err(e) => {
|
||||
eprintln!("daemon error: {e}");
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start_mcp(host: &Arc<Host>, base: &std::path::Path) {
|
||||
host.mcp.set_stdio_link(base.join("bin").join("openidea-server"));
|
||||
host.mcp_background.serve_none();
|
||||
host.mcp.apply(&host);
|
||||
// The desktop's code plugins run here, next to the project (`plugin_sync_packages`).
|
||||
let plugins = match RemotePlugins::start(&plugins_data, &host, peer.clone()) {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
|
||||
fn start_plugins<P: rpc::PeerHandle>(
|
||||
plugins_data: &std::path::Path,
|
||||
host: &Arc<Host>,
|
||||
peer: Arc<P>,
|
||||
) -> Option<Arc<RemotePlugins>> {
|
||||
match RemotePlugins::start(plugins_data, host, peer) {
|
||||
Ok(p) => Some(p),
|
||||
Err(e) => {
|
||||
tracing::warn!("plugins are unavailable: {e}");
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn inherit_trust(host: &Host) {
|
||||
if let Some(root) = std::env::var_os(ide_host::trust::TRUSTED_ROOT_ENV)
|
||||
&& let Err(e) = host.trust.inherit(std::path::Path::new(&root))
|
||||
{
|
||||
tracing::warn!("cannot trust {}: {e}", root.to_string_lossy());
|
||||
}
|
||||
tracing::info!("openidea-server {} ready", env!("CARGO_PKG_VERSION"));
|
||||
}
|
||||
|
||||
fn build_dispatcher(plugins: &Option<Arc<RemotePlugins>>, plugin_languages: Arc<RemotePluginLanguages>) -> Dispatcher {
|
||||
let mut dispatcher = Dispatcher::standard();
|
||||
if let Some(plugins) = &plugins {
|
||||
if let Some(plugins) = plugins {
|
||||
plugins.register(&mut dispatcher);
|
||||
}
|
||||
dispatcher.add(SYNC_COMMAND, TrustClass::Trusted, move |c| {
|
||||
@@ -126,14 +226,13 @@ async fn run(base: PathBuf) -> i32 {
|
||||
Ok(report)
|
||||
}
|
||||
});
|
||||
rpc::serve(host.clone(), dispatcher, peer, tokio::io::stdin(), tokio::io::stdout()).await;
|
||||
host.mcp.stop(&host);
|
||||
if let Some(plugins) = &plugins {
|
||||
dispatcher
|
||||
}
|
||||
|
||||
async fn shutdown_all(host: &Host, plugins: Option<&Arc<RemotePlugins>>) {
|
||||
host.mcp.stop(host);
|
||||
if let Some(plugins) = plugins {
|
||||
plugins.host().shutdown();
|
||||
}
|
||||
// `process::exit` skips destructors: nothing started for the client may outlive it.
|
||||
if tokio::time::timeout(std::time::Duration::from_secs(10), host.shutdown()).await.is_err() {
|
||||
tracing::warn!("language servers did not shut down in time");
|
||||
}
|
||||
0
|
||||
host.shutdown().await;
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
//! Persistent per-project `openidea-server` daemon over a local Unix domain socket.
|
||||
//!
|
||||
//! * `openidea-server --attach <project_path>` connects to the daemon for `<project_path>`
|
||||
//! (spawning it detached in a new session if none is listening) and bridges its own
|
||||
//! stdin / stdout to the Unix socket. Closing the desktop window ends the SSH / WSL /
|
||||
//! `docker exec` attach relay while the daemon — and its index, language servers,
|
||||
//! terminals, runs and agent sessions — keeps running.
|
||||
//! * `openidea-server --daemon <socket_path> <build>` is the process `--attach` starts.
|
||||
|
||||
use crate::Host;
|
||||
use crate::rpc::{self, Dispatcher, PeerSlot, RemoteIdlePolicy};
|
||||
use ide_core::CancellationToken;
|
||||
use rustix::fs::{FlockOperation, flock};
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::future::{Future, pending};
|
||||
use std::io::{self, Read, Seek, SeekFrom, Write};
|
||||
use std::net::Shutdown;
|
||||
use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt};
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::{Arc, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
|
||||
/// Keep socket paths well below macOS (104) and Linux (108) `sun_path` limits.
|
||||
const MAX_SUN_PATH: usize = 96;
|
||||
const STARTUP_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
const EOF_DRAIN: Duration = Duration::from_secs(2);
|
||||
const EMPTY_IDLE_EXIT: Duration = Duration::from_secs(30);
|
||||
const IDLE_ENV: &str = "OPENIDEA_SERVER_IDLE_TIMEOUT_SECONDS";
|
||||
pub type BuildId = [u8; 16];
|
||||
const ATTACHED: u8 = b'A';
|
||||
const RETIRING: u8 = b'R';
|
||||
const BUSY: u8 = b'B';
|
||||
|
||||
pub struct DaemonPaths {
|
||||
pub key: String,
|
||||
pub socket: PathBuf,
|
||||
pub lock: PathBuf,
|
||||
pub log: PathBuf,
|
||||
}
|
||||
|
||||
/// Resolves `raw_path` (`~`, `~/…`, symlinks) the same way `open_project` does so
|
||||
/// `~/repo` and `/home/user/repo` attach to the same daemon.
|
||||
pub fn normalize_project_path(raw_path: &str, home: &Path) -> PathBuf {
|
||||
let trimmed = raw_path.trim();
|
||||
let expanded = if trimmed.is_empty() || trimmed == "~" {
|
||||
home.to_path_buf()
|
||||
} else if let Some(rest) = trimmed.strip_prefix("~/") {
|
||||
home.join(rest)
|
||||
} else {
|
||||
PathBuf::from(trimmed)
|
||||
};
|
||||
let canonical = dunce::canonicalize(&expanded).unwrap_or(expanded);
|
||||
let text = canonical.to_string_lossy();
|
||||
if text.len() > 1 && text.ends_with('/') { PathBuf::from(text.trim_end_matches('/')) } else { canonical }
|
||||
}
|
||||
|
||||
/// Deterministic socket, lock and log paths for a project and server home, across builds.
|
||||
pub fn paths_for(base: &Path, home: &Path, raw_project_path: &str) -> io::Result<DaemonPaths> {
|
||||
let project = normalize_project_path(raw_project_path, home);
|
||||
std::fs::create_dir_all(base)?;
|
||||
let base_canon = dunce::canonicalize(base).unwrap_or_else(|_| base.to_path_buf());
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher.update(project.as_os_str().as_encoded_bytes());
|
||||
hasher.update(&[0]);
|
||||
hasher.update(base_canon.as_os_str().as_encoded_bytes());
|
||||
let key = hasher.finalize().to_hex()[..16].to_owned();
|
||||
|
||||
let sock_name = format!("s-{key}.sock");
|
||||
let lock_name = format!("s-{key}.lock");
|
||||
let preferred_dir = base.join("run");
|
||||
let run_dir = if preferred_dir.join(&sock_name).as_os_str().len() <= MAX_SUN_PATH {
|
||||
ensure_private_dir(&preferred_dir)?;
|
||||
preferred_dir
|
||||
} else {
|
||||
let uid = rustix::process::geteuid().as_raw();
|
||||
let fallback = PathBuf::from(format!("/tmp/openidea-{uid}"));
|
||||
ensure_private_dir(&fallback)?;
|
||||
fallback
|
||||
};
|
||||
|
||||
let log_dir = base.join("logs");
|
||||
std::fs::create_dir_all(&log_dir)?;
|
||||
Ok(DaemonPaths {
|
||||
socket: run_dir.join(sock_name),
|
||||
lock: run_dir.join(lock_name),
|
||||
log: log_dir.join(format!("server-{key}.log")),
|
||||
key,
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_private_dir(dir: &Path) -> io::Result<()> {
|
||||
if !dir.exists() {
|
||||
let mut builder = std::fs::DirBuilder::new();
|
||||
builder.recursive(true).mode(0o700);
|
||||
builder.create(dir)?;
|
||||
}
|
||||
let meta = std::fs::symlink_metadata(dir)?;
|
||||
if meta.file_type().is_symlink() || !meta.is_dir() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
format!("{} is not a private directory", dir.display()),
|
||||
));
|
||||
}
|
||||
let uid = rustix::process::geteuid().as_raw();
|
||||
if meta.uid() != uid {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
format!("{} is owned by uid {}, expected {uid}", dir.display(), meta.uid()),
|
||||
));
|
||||
}
|
||||
if meta.mode() & 0o077 != 0 {
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Connects to the daemon for `project_path` (spawning it if needed) and bridges
|
||||
/// `input` / `output` to its Unix socket.
|
||||
pub fn attach(
|
||||
base: &Path,
|
||||
home: &Path,
|
||||
project_path: &str,
|
||||
input: impl Read + Send + 'static,
|
||||
output: impl Write,
|
||||
) -> Result<(), String> {
|
||||
let exe = std::env::current_exe().map_err(|e| format!("cannot locate openidea-server: {e}"))?;
|
||||
let paths = paths_for(base, home, project_path).map_err(|e| format!("cannot prepare runtime dir: {e}"))?;
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher
|
||||
.update_reader(File::open(&exe).map_err(|e| format!("cannot open openidea-server: {e}"))?)
|
||||
.map_err(|e| format!("cannot identify openidea-server build: {e}"))?;
|
||||
let hex = hasher.finalize().to_hex();
|
||||
let build = &hex.as_str()[..16];
|
||||
let stream = connect_or_spawn(&exe, &paths, build)?;
|
||||
bridge(stream, input, output).map_err(|e| format!("daemon relay failed: {e}"))
|
||||
}
|
||||
|
||||
fn connect_or_spawn(exe: &Path, paths: &DaemonPaths, build: &str) -> Result<UnixStream, String> {
|
||||
let lock_file = OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.mode(0o600)
|
||||
.open(&paths.lock)
|
||||
.map_err(|e| format!("cannot open {}: {e}", paths.lock.display()))?;
|
||||
flock(&lock_file, FlockOperation::LockExclusive)
|
||||
.map_err(|e| format!("cannot lock {}: {e}", paths.lock.display()))?;
|
||||
|
||||
if let Some(stream) = existing_daemon(paths, build)? {
|
||||
return Ok(stream);
|
||||
}
|
||||
|
||||
match std::fs::remove_file(&paths.socket) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(format!("cannot remove stale socket {}: {e}", paths.socket.display())),
|
||||
}
|
||||
let mut log_file = OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.read(true)
|
||||
.mode(0o600)
|
||||
.open(&paths.log)
|
||||
.map_err(|e| format!("cannot open {}: {e}", paths.log.display()))?;
|
||||
let log_offset = log_file.metadata().map(|m| m.len()).unwrap_or(0);
|
||||
let stderr_file = log_file.try_clone().map_err(|e| format!("cannot clone log handle: {e}"))?;
|
||||
|
||||
let mut cmd = Command::new(exe);
|
||||
cmd.arg("--daemon")
|
||||
.arg(&paths.socket)
|
||||
.arg(build)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::from(stderr_file));
|
||||
// SAFETY: `setsid` is an async-signal-safe POSIX call that detaches the daemon into
|
||||
// a new session without a controlling terminal, outliving the SSH / WSL / docker exec call.
|
||||
unsafe {
|
||||
cmd.pre_exec(|| {
|
||||
let _ = rustix::process::setsid();
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let mut child = cmd.spawn().map_err(|e| format!("cannot spawn openidea-server daemon: {e}"))?;
|
||||
|
||||
let deadline = Instant::now() + STARTUP_TIMEOUT;
|
||||
loop {
|
||||
if let Some(stream) = existing_daemon(paths, build)? {
|
||||
return Ok(stream);
|
||||
}
|
||||
if let Ok(Some(status)) = child.try_wait() {
|
||||
let tail = read_log_tail(&mut log_file, log_offset);
|
||||
let detail = if tail.is_empty() { format!("exited with {status}") } else { tail };
|
||||
return Err(format!("openidea-server daemon failed to start: {detail}"));
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
let tail = read_log_tail(&mut log_file, log_offset);
|
||||
let detail = if tail.is_empty() { "timed out waiting for socket".to_owned() } else { tail };
|
||||
return Err(format!("openidea-server daemon did not start: {detail}"));
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(15));
|
||||
}
|
||||
}
|
||||
|
||||
fn existing_daemon(paths: &DaemonPaths, build: &str) -> Result<Option<UnixStream>, String> {
|
||||
let exchange = |mut stream: UnixStream| -> io::Result<Option<UnixStream>> {
|
||||
stream.set_read_timeout(Some(HANDSHAKE_TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(HANDSHAKE_TIMEOUT))?;
|
||||
stream.write_all(build.as_bytes())?;
|
||||
let mut reply = [0];
|
||||
stream.read_exact(&mut reply)?;
|
||||
match reply[0] {
|
||||
ATTACHED => {
|
||||
stream.set_read_timeout(None)?;
|
||||
stream.set_write_timeout(None)?;
|
||||
Ok(Some(stream))
|
||||
}
|
||||
RETIRING => {
|
||||
// This stream stays open until project cleanup and socket removal finish.
|
||||
stream.set_read_timeout(Some(rpc::SHUTDOWN_TIMEOUT))?;
|
||||
if stream.read(&mut reply)? == 0 {
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(io::Error::other("unexpected response from stopping daemon"))
|
||||
}
|
||||
}
|
||||
BUSY => Err(io::Error::other(
|
||||
"Another build of OpenIDEA still has this project open, is running tasks, or has unsaved changes. \
|
||||
Reconnect with that build, then stop the remote backend before upgrading.",
|
||||
)),
|
||||
_ => Err(io::Error::other("unrecognized remote backend response")),
|
||||
}
|
||||
};
|
||||
let stream = match UnixStream::connect(&paths.socket) {
|
||||
Ok(stream) => stream,
|
||||
Err(e) if matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused) => return Ok(None),
|
||||
Err(e) => return Err(format!("cannot connect to remote backend at {}: {e}", paths.socket.display())),
|
||||
};
|
||||
exchange(stream).map_err(|e| format!("cannot attach to {}: {e}", paths.socket.display()))
|
||||
}
|
||||
|
||||
fn read_log_tail(file: &mut File, offset: u64) -> String {
|
||||
if file.seek(SeekFrom::Start(offset)).is_err() {
|
||||
return String::new();
|
||||
}
|
||||
let mut text = String::new();
|
||||
let _ = file.read_to_string(&mut text);
|
||||
text.trim().to_owned()
|
||||
}
|
||||
|
||||
/// Copies `input` to `stream` and `stream` to `output`, returning promptly when either
|
||||
/// side closes.
|
||||
pub fn bridge(
|
||||
mut from_daemon: UnixStream,
|
||||
mut input: impl Read + Send + 'static,
|
||||
mut output: impl Write,
|
||||
) -> io::Result<()> {
|
||||
from_daemon.set_read_timeout(Some(Duration::from_millis(100)))?;
|
||||
let mut to_daemon = from_daemon.try_clone()?;
|
||||
let (eof_tx, eof_rx) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = [0u8; 16 * 1024];
|
||||
loop {
|
||||
match input.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
if to_daemon.write_all(&buf[..n]).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
let _ = to_daemon.shutdown(Shutdown::Write);
|
||||
let _ = eof_tx.send(Instant::now());
|
||||
});
|
||||
|
||||
let mut buf = [0u8; 16 * 1024];
|
||||
let mut input_closed: Option<Instant> = None;
|
||||
loop {
|
||||
if let Ok(at) = eof_rx.try_recv() {
|
||||
input_closed = Some(at);
|
||||
}
|
||||
if input_closed.is_some_and(|at| at.elapsed() >= EOF_DRAIN) {
|
||||
break;
|
||||
}
|
||||
match from_daemon.read(&mut buf) {
|
||||
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => continue,
|
||||
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
if output.write_all(&buf[..n]).and_then(|()| output.flush()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = from_daemon.shutdown(Shutdown::Both);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The socket remains bound until cleanup finishes, so an attach can't start a
|
||||
/// replacement while the previous backend is still stopping its processes.
|
||||
pub async fn serve(
|
||||
socket_path: &Path,
|
||||
build: BuildId,
|
||||
host: Arc<Host>,
|
||||
dispatcher: Dispatcher,
|
||||
slot: Arc<PeerSlot>,
|
||||
cleanup: impl Future<Output = ()>,
|
||||
) -> io::Result<()> {
|
||||
let start = || {
|
||||
if let Some(parent) = socket_path.parent() {
|
||||
ensure_private_dir(parent)?;
|
||||
}
|
||||
let terminate = signal(SignalKind::terminate())?;
|
||||
let listener = tokio::net::UnixListener::bind(socket_path)?;
|
||||
if let Err(e) = std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o600)) {
|
||||
let _ = std::fs::remove_file(socket_path);
|
||||
return Err(e);
|
||||
}
|
||||
Ok((listener, terminate))
|
||||
};
|
||||
let (listener, mut terminate) = match start() {
|
||||
Ok(started) => started,
|
||||
Err(e) => {
|
||||
cleanup.await;
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
let shutdown = CancellationToken::new();
|
||||
let idle_policy = RemoteIdlePolicy { override_seconds: idle_override() };
|
||||
let mut check = tokio::time::interval(Duration::from_secs(idle_policy.override_seconds.unwrap_or(5).min(5)));
|
||||
let mut idle = None;
|
||||
let mut retiring = None;
|
||||
let mut active: Option<ide_jsonrpc::Peer> = None;
|
||||
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => break Ok(()),
|
||||
_ = terminate.recv() => break Ok(()),
|
||||
_ = async {
|
||||
match &active {
|
||||
Some(peer) => { peer.closed().await; }
|
||||
None => pending().await,
|
||||
}
|
||||
} => {
|
||||
active = None;
|
||||
slot.remove();
|
||||
host.client_disconnected();
|
||||
idle = None;
|
||||
}
|
||||
accepted = listener.accept() => {
|
||||
let mut stream = match accepted {
|
||||
Ok((stream, _)) => stream,
|
||||
Err(e) => break Err(e),
|
||||
};
|
||||
let mut requested_build = [0; 16];
|
||||
if !matches!(
|
||||
tokio::time::timeout(HANDSHAKE_TIMEOUT, stream.read_exact(&mut requested_build)).await,
|
||||
Ok(Ok(_))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if active.as_ref().is_some_and(ide_jsonrpc::Peer::is_closed) {
|
||||
active = None;
|
||||
slot.remove();
|
||||
host.client_disconnected();
|
||||
idle = None;
|
||||
}
|
||||
if shutdown.is_cancelled() {
|
||||
break Ok(());
|
||||
}
|
||||
if requested_build != build {
|
||||
let busy = active.is_some() || has_live_work(&host);
|
||||
if busy {
|
||||
let _ = stream.write_u8(BUSY).await;
|
||||
} else if stream.write_u8(RETIRING).await.is_ok() {
|
||||
retiring = Some(stream);
|
||||
break Ok(());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if stream.write_u8(ATTACHED).await.is_err() {
|
||||
continue;
|
||||
}
|
||||
if let Some(old) = slot.remove() {
|
||||
// Await an acknowledgement before tearing down the old transport.
|
||||
let _ = tokio::time::timeout(
|
||||
Duration::from_millis(750),
|
||||
old.request::<_, ()>(rpc::SESSION_REPLACED, (), None),
|
||||
).await;
|
||||
old.kill();
|
||||
host.client_disconnected();
|
||||
}
|
||||
let (reader, writer) = stream.into_split();
|
||||
active = Some(rpc::connect_persistent(
|
||||
host.clone(), dispatcher.clone(), slot.clone(), shutdown.clone(), idle_policy, reader, writer,
|
||||
));
|
||||
idle = None;
|
||||
}
|
||||
_ = check.tick() => {
|
||||
if active.is_some() || has_live_work(&host) {
|
||||
idle = None;
|
||||
} else {
|
||||
if idle.is_none() {
|
||||
let since = Instant::now();
|
||||
let timeout = match disconnected_timeout(&host, idle_policy).await {
|
||||
Ok(timeout) => timeout,
|
||||
Err(e) => break Err(e),
|
||||
};
|
||||
idle = Some((since, timeout));
|
||||
}
|
||||
if let Some((since, Some(timeout))) = idle && since.elapsed() >= timeout {
|
||||
tracing::info!("idle openidea-server daemon exiting");
|
||||
break Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
shutdown.cancel();
|
||||
slot.remove();
|
||||
if let Some(peer) = &active {
|
||||
let _ = tokio::time::timeout(HANDSHAKE_TIMEOUT, peer.flush()).await;
|
||||
host.client_disconnected();
|
||||
}
|
||||
cleanup.await;
|
||||
if let Err(e) = std::fs::remove_file(socket_path) {
|
||||
tracing::warn!("cannot remove remote backend socket {}: {e}", socket_path.display());
|
||||
}
|
||||
if let Some(active) = active {
|
||||
active.kill();
|
||||
}
|
||||
drop(retiring);
|
||||
result
|
||||
}
|
||||
|
||||
fn idle_override() -> Option<u64> {
|
||||
if let Some(value) = std::env::var_os(IDLE_ENV) {
|
||||
if let Some(seconds) = value.to_str().and_then(|s| s.parse::<u64>().ok()).filter(|&n| n > 0) {
|
||||
return Some(seconds);
|
||||
}
|
||||
tracing::warn!("{IDLE_ENV} must be a positive number of seconds; using the host setting");
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn disconnected_timeout(host: &Arc<Host>, policy: RemoteIdlePolicy) -> io::Result<Option<Duration>> {
|
||||
let override_timeout = policy.override_seconds.map(Duration::from_secs);
|
||||
if host.projects().is_empty() {
|
||||
return Ok(Some(override_timeout.unwrap_or(EMPTY_IDLE_EXIT).min(EMPTY_IDLE_EXIT)));
|
||||
}
|
||||
if let Some(timeout) = override_timeout {
|
||||
return Ok(Some(timeout));
|
||||
}
|
||||
let minutes = crate::ops::project::remote_idle_timeout_minutes(host).await.map_err(io::Error::other)?;
|
||||
Ok((minutes != 0).then(|| Duration::from_secs(u64::from(minutes) * 60)))
|
||||
}
|
||||
|
||||
/// Keeps a disconnected daemon alive: expiring would end this work, or lose the unsaved
|
||||
/// edits a dropped connection left behind.
|
||||
fn has_live_work(host: &Host) -> bool {
|
||||
!host.terminals.list().is_empty()
|
||||
|| host.processes.has_live_runs()
|
||||
|| !host.debugger.sessions(None).is_empty()
|
||||
|| host
|
||||
.projects()
|
||||
.iter()
|
||||
.any(|project| project.agents.has_live_work() || project.documents.has_unsaved_changes())
|
||||
}
|
||||
@@ -66,9 +66,6 @@ impl EventSink for RecordingSink {
|
||||
}
|
||||
}
|
||||
|
||||
/// A sink whose diagnostics are recorded; the store outlives every project.
|
||||
pub type RecordSinkFactory = Box<dyn Fn(&str) -> SharedSink + Send + Sync>;
|
||||
|
||||
/// Wraps a sink factory so every sink it creates records diagnostics.
|
||||
pub fn recording_sink_factory(store: Arc<DiagnosticsStore>, inner: crate::SinkFactory) -> crate::SinkFactory {
|
||||
Box::new(move |window| {
|
||||
|
||||
@@ -21,7 +21,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
type Changes = Vec<(OsString, Option<OsString>)>;
|
||||
|
||||
@@ -355,20 +355,34 @@ fn run_post_start(cmd: &LifecycleCommand, root: &Path, sink: &SharedSink, cancel
|
||||
/// Runs `argv` in `root` with the children's environment, its stdout and stderr line by line
|
||||
/// to `on_line`; `Err` says how it failed.
|
||||
fn run_one(argv: &[String], root: &Path, cancel: &CancellationToken, on_line: &dyn Fn(String)) -> Result<(), String> {
|
||||
let (program, args) = argv.split_first().ok_or("empty command")?;
|
||||
let mut command = Command::new(program);
|
||||
command.args(args);
|
||||
run_command(command, root, cancel, None, on_line)
|
||||
}
|
||||
|
||||
pub(crate) fn run_command(
|
||||
mut command: Command,
|
||||
root: &Path,
|
||||
cancel: &CancellationToken,
|
||||
timeout: Option<Duration>,
|
||||
mut on_line: impl FnMut(String),
|
||||
) -> Result<(), String> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err("cancelled".into());
|
||||
}
|
||||
let (program, args) = argv.split_first().ok_or("empty command")?;
|
||||
let mut child = ide_core::process::prepare(&mut Command::new(program))
|
||||
.args(args)
|
||||
let program = command.get_program().to_string_lossy().into_owned();
|
||||
command
|
||||
.current_dir(root)
|
||||
.envs(ide_core::process::shell_env())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
let mut child = ide_core::process::prepare(ide_core::process::own_group(&mut command))
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start {program}: {e}"))?;
|
||||
let (tx, rx) = std::sync::mpsc::channel::<String>();
|
||||
let started = Instant::now();
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel::<String>(64);
|
||||
let pipes: [Option<Box<dyn Read + Send>>; 2] = [
|
||||
child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
|
||||
child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
|
||||
@@ -386,29 +400,31 @@ fn run_one(argv: &[String], root: &Path, cancel: &CancellationToken, on_line: &d
|
||||
}
|
||||
drop(tx);
|
||||
let status = loop {
|
||||
if cancel.is_cancelled() {
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
return Err("cancelled".into());
|
||||
}
|
||||
if timeout.is_some_and(|duration| started.elapsed() >= duration) {
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
return Err("timed out".into());
|
||||
}
|
||||
match rx.recv_timeout(Duration::from_millis(50)) {
|
||||
Ok(line) => on_line(line),
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break child.wait(),
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err("cancelled".into());
|
||||
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => std::thread::sleep(Duration::from_millis(50)),
|
||||
}
|
||||
// A process it started in the background may keep the pipes open: the command is done.
|
||||
if let Ok(Some(status)) = child.try_wait() {
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(1);
|
||||
if let Some(status) = child.try_wait().map_err(|e| e.to_string())? {
|
||||
let deadline = Instant::now() + Duration::from_secs(1);
|
||||
while let Ok(line) = rx.recv_timeout(Duration::from_millis(100)) {
|
||||
on_line(line);
|
||||
if std::time::Instant::now() > deadline {
|
||||
if Instant::now() > deadline {
|
||||
break;
|
||||
}
|
||||
}
|
||||
break Ok(status);
|
||||
break status;
|
||||
}
|
||||
}
|
||||
.map_err(|e| e.to_string())?;
|
||||
};
|
||||
match status.code() {
|
||||
Some(0) => Ok(()),
|
||||
Some(code) => Err(format!("exited with code {code}")),
|
||||
|
||||
@@ -2,27 +2,161 @@
|
||||
|
||||
use crate::Host;
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::settings::{ExternalFormatter, LanguagesSettings, Settings};
|
||||
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, Pos, Range, TextEdit};
|
||||
use ide_core::settings::{BIOME_LANGUAGES, ExternalFormatter, LanguagesSettings, Settings};
|
||||
use ide_core::{
|
||||
CancellationToken, ChangeSet, DocId, IdeError, IdeEvent, IdeResult, IpcPath, LanguageId, Pos, Range, TextEdit,
|
||||
};
|
||||
use ide_language::{LanguageConfig, PhpAlignment, Syntax};
|
||||
use ide_lsp::types::FormatOptions;
|
||||
use ide_tools::{Tools, formatter};
|
||||
use std::path::Path;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const OXFMT_CONFIGS: [&str; 4] = [".oxfmtrc.json", ".oxfmtrc.jsonc", "oxfmt.config.ts", "oxfmt.config.mts"];
|
||||
/// A Biome configuration, or Biome installed as a project dependency (it then uses its defaults).
|
||||
const BIOME_MARKERS: [&str; 3] = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome/package.json"];
|
||||
|
||||
/// Reformat Code uses Biome below a Biome configuration or installation, unless the nearest
|
||||
/// configuration turns its formatter off (Biome lints, another tool formats).
|
||||
fn biome_formats(file: &Path) -> bool {
|
||||
let config = ["biome.json", "biome.jsonc"]
|
||||
.iter()
|
||||
.filter_map(|name| formatter::find_up(file, Path::new(name)))
|
||||
.max_by_key(|path| path.components().count());
|
||||
match config {
|
||||
Some(config) => !std::fs::read_to_string(&config)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text)).ok())
|
||||
.is_some_and(|v| v.pointer("/formatter/enabled") == Some(&serde_json::Value::Bool(false))),
|
||||
None => BIOME_MARKERS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `pyproject.toml` Black reads for `file`, in the project root Black finds: the nearest folder
|
||||
/// with `.git`, `.hg`, or a `pyproject.toml` that has `[tool.black]` (one without it is skipped).
|
||||
/// `None` when that root has no `pyproject.toml`: Black then reads the user's configuration.
|
||||
fn black_pyproject(file: &Path) -> Option<PathBuf> {
|
||||
let mut dirs = file.parent()?.ancestors();
|
||||
let root = dirs
|
||||
.find(|d| {
|
||||
d.join(".git").exists()
|
||||
|| d.join(".hg").is_dir()
|
||||
|| ide_sdk::apply::toml_has_table(&d.join("pyproject.toml"), "tool.black")
|
||||
})
|
||||
.or_else(|| file.parent()?.ancestors().last())?;
|
||||
Some(root.join("pyproject.toml")).filter(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Black formats files whose project configures it (`[tool.black]`).
|
||||
fn black_configured(file: &Path) -> bool {
|
||||
black_pyproject(file).is_some_and(|p| ide_sdk::apply::toml_has_table(&p, "tool.black"))
|
||||
}
|
||||
|
||||
/// The single user configuration directory the formatter searches.
|
||||
fn user_config_dir(tool: &str, cwd: &Path) -> Option<PathBuf> {
|
||||
if cfg!(windows) {
|
||||
return if tool == "black" { dirs::home_dir() } else { dirs::config_dir() };
|
||||
}
|
||||
let xdg = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from);
|
||||
xdg_user_config_dir(tool, cwd, xdg.as_deref(), dirs::home_dir().as_deref())
|
||||
}
|
||||
|
||||
fn xdg_user_config_dir(tool: &str, cwd: &Path, xdg: Option<&Path>, home: Option<&Path>) -> Option<PathBuf> {
|
||||
if let Some(dir) = xdg.filter(|dir| tool == "black" || dir.is_absolute()) {
|
||||
if let Ok(relative) = dir.strip_prefix("~") {
|
||||
return home.map(|home| home.join(relative));
|
||||
}
|
||||
return Some(cwd.join(dir));
|
||||
}
|
||||
home.map(|home| home.join(".config"))
|
||||
}
|
||||
|
||||
fn user_configured(tool: &str, dir: Option<&Path>) -> bool {
|
||||
let Some(dir) = dir else { return false };
|
||||
let names: &[&str] = match tool {
|
||||
"ruff" => &["ruff/.ruff.toml", "ruff/ruff.toml", "ruff/pyproject.toml"],
|
||||
"black" if cfg!(windows) => &[".black"],
|
||||
"black" => &["black"],
|
||||
_ => &[],
|
||||
};
|
||||
names.iter().any(|name| dir.join(name).is_file())
|
||||
}
|
||||
|
||||
/// Whether Ruff finds a configuration of the project for `file`: `ruff.toml`, `.ruff.toml` or a
|
||||
/// `pyproject.toml` with `[tool.ruff]` in its folder or above.
|
||||
fn ruff_project_configured(file: &Path) -> bool {
|
||||
file.parent().into_iter().flat_map(Path::ancestors).any(|dir| {
|
||||
dir.join("ruff.toml").is_file()
|
||||
|| dir.join(".ruff.toml").is_file()
|
||||
|| ide_sdk::apply::toml_has_table(&dir.join("pyproject.toml"), "tool.ruff")
|
||||
})
|
||||
}
|
||||
|
||||
/// The indentation and line length for `tool`, unless a configuration of the project or the user
|
||||
/// decides them (or the Ruff configuration directory is set): the file's `.editorconfig`, then
|
||||
/// what was set on the Code Style › Python page, as the editor indents.
|
||||
fn python_style_for(
|
||||
tool: &str,
|
||||
file: &Path,
|
||||
configured: bool,
|
||||
settings: &Settings,
|
||||
editorconfig: Option<&ide_workspace::editorconfig::EditorConfigProps>,
|
||||
user_dir: Option<&Path>,
|
||||
) -> formatter::PythonStyle {
|
||||
let has_config = configured
|
||||
|| match tool {
|
||||
"ruff" => ruff_project_configured(file) || user_configured("ruff", user_dir),
|
||||
// Black reads the user's configuration only when its project root has no pyproject.toml.
|
||||
"black" => match black_pyproject(file) {
|
||||
Some(pyproject) => ide_sdk::apply::toml_has_table(&pyproject, "tool.black"),
|
||||
None => user_configured("black", user_dir),
|
||||
},
|
||||
_ => true,
|
||||
};
|
||||
if has_config {
|
||||
return formatter::PythonStyle::default();
|
||||
}
|
||||
// Only what was set: the global hard wrap (120) is not Ruff's or Black's default (88).
|
||||
let page = settings.editor.code_style.languages.get("python");
|
||||
let ec = editorconfig;
|
||||
formatter::PythonStyle {
|
||||
line_length: ec.and_then(|e| e.max_line_length).or(page.and_then(|s| s.hard_wrap_at)),
|
||||
indent_width: ec.and_then(|e| e.indent_size.or(e.tab_width)).or(page.and_then(|s| s.indent.or(s.tab_size))),
|
||||
use_tabs: ec
|
||||
.and_then(|e| e.indent_style)
|
||||
.map(|style| style == ide_workspace::editorconfig::IndentStyle::Tab)
|
||||
.or(page.and_then(|s| s.use_tab)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `tool` installed in the environment of the interpreter nearest to `near` (`svc/.venv/bin/ruff` or
|
||||
/// `svc/.venv/bin/black`), or in `Scripts` for conda and pixi environments on Windows.
|
||||
fn interpreter_tool(root: &Path, near: Option<&Path>, settings: &Settings, tool: &str) -> Option<PathBuf> {
|
||||
let python = ide_sdk::apply::python_interpreter_near(root, near, settings)?;
|
||||
let dir = python.parent()?;
|
||||
let exe = if cfg!(windows) { format!("{tool}.exe") } else { tool.to_owned() };
|
||||
[dir.join(&exe), dir.join("Scripts").join(&exe)].into_iter().find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// Formatters print nothing for a file their configuration excludes (Black's `force-exclude`):
|
||||
/// that output must not replace the file.
|
||||
fn excluded_output(text: &str, formatted: &str) -> bool {
|
||||
formatted.is_empty() && !text.trim().is_empty()
|
||||
}
|
||||
|
||||
fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter) -> bool {
|
||||
match language.formatter.as_ref().map(|f| f.tool.as_str()) {
|
||||
Some("prettier") if tool == ExternalFormatter::Biome => BIOME_LANGUAGES.contains(&language.id.as_str()),
|
||||
Some("prettier") => matches!(tool, ExternalFormatter::Prettier | ExternalFormatter::Oxfmt),
|
||||
Some("ruff") => tool == ExternalFormatter::Ruff,
|
||||
Some("ruff") => matches!(tool, ExternalFormatter::Ruff | ExternalFormatter::Black),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The external formatter of a file, for a language with an external formatter.
|
||||
/// `forced` names the tool (Reformat with Prettier, oxfmt, or Ruff). Ruff is
|
||||
/// the base formatter for Python; oxfmt can replace Prettier for its languages
|
||||
/// when configured or selected. A tool that cannot format the language is
|
||||
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
|
||||
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
|
||||
/// then oxfmt, can replace Prettier for their
|
||||
/// languages when configured or selected. A tool that cannot format the language is
|
||||
/// rejected even when explicitly requested.
|
||||
fn external_tool(
|
||||
forced: Option<ExternalFormatter>,
|
||||
@@ -30,7 +164,7 @@ fn external_tool(
|
||||
file: &Path,
|
||||
settings: &LanguagesSettings,
|
||||
) -> IdeResult<Option<ExternalFormatter>> {
|
||||
use ExternalFormatter::{Oxfmt, Prettier, Ruff};
|
||||
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
|
||||
let Some(language) = language.filter(|l| l.formatter.is_some()) else {
|
||||
return match forced {
|
||||
Some(tool) => Err(IdeError::invalid(format!(
|
||||
@@ -54,10 +188,17 @@ fn external_tool(
|
||||
}
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
|
||||
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
|
||||
return Ok(enabled(Ruff).then_some(Ruff));
|
||||
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
|
||||
Some(Black)
|
||||
} else {
|
||||
enabled(Ruff).then_some(Ruff)
|
||||
});
|
||||
}
|
||||
let oxfmt_config = || OXFMT_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some());
|
||||
Ok(if enabled(Oxfmt) && (settings.oxfmt.prefer || oxfmt_config()) {
|
||||
let found = |names: &[&str]| names.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some());
|
||||
let biome = enabled(Biome) && supports_external_format(language, Biome);
|
||||
Ok(if biome && (settings.biome.prefer || biome_formats(file)) {
|
||||
Some(Biome)
|
||||
} else if enabled(Oxfmt) && (settings.oxfmt.prefer || found(&OXFMT_CONFIGS)) {
|
||||
Some(Oxfmt)
|
||||
} else {
|
||||
enabled(Prettier).then_some(Prettier)
|
||||
@@ -151,10 +292,58 @@ pub async fn format(
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
let project = host.project(window)?;
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
let source = FormatSource {
|
||||
path: snap.path,
|
||||
language: snap.language,
|
||||
text: snap.text,
|
||||
doc: Some(doc),
|
||||
version: snap.version,
|
||||
read_only: snap.read_only,
|
||||
};
|
||||
format_source(host, window, &project, source, range, options).await
|
||||
}
|
||||
|
||||
/// Format a separate snapshot using the file's language, settings and formatter.
|
||||
pub async fn format_text(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
path: PathBuf,
|
||||
text: String,
|
||||
options: FormatOptions,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
let project = host.project(window)?;
|
||||
if !path.is_absolute() || path.file_name().is_none() {
|
||||
return Err(IdeError::invalid("formatting requires a file path"));
|
||||
}
|
||||
if text.len() as u64 > ide_vfs::LARGE_FILE_THRESHOLD {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let language = project.documents.language_of(&path, text.lines().next()).language;
|
||||
let source = FormatSource { path: path.into(), language, text, doc: None, version: 0, read_only: false };
|
||||
format_source(host, window, &project, source, None, options).await
|
||||
}
|
||||
|
||||
struct FormatSource {
|
||||
path: IpcPath,
|
||||
language: LanguageId,
|
||||
text: String,
|
||||
doc: Option<DocId>,
|
||||
version: u32,
|
||||
read_only: bool,
|
||||
}
|
||||
|
||||
async fn format_source(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
project: &crate::Project,
|
||||
snap: FormatSource,
|
||||
range: Option<Range>,
|
||||
options: FormatOptions,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
let settings = project.settings.effective();
|
||||
let alignment = php_alignment(&settings, &snap.language);
|
||||
let original = alignment.any().then(|| (snap.language.clone(), snap.text.clone()));
|
||||
let Some(edits) = provider_edits(host, window, &project, snap, settings, range, options).await? else {
|
||||
let Some(edits) = provider_edits(host, window, project, snap, settings, range, options).await? else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let Some((language, text)) = original else {
|
||||
@@ -235,12 +424,12 @@ async fn provider_edits(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
project: &crate::Project,
|
||||
snap: ide_workspace::documents::DocumentInfo,
|
||||
snap: FormatSource,
|
||||
settings: Settings,
|
||||
range: Option<Range>,
|
||||
options: FormatOptions,
|
||||
) -> IdeResult<Option<Vec<TextEdit>>> {
|
||||
let doc = snap.id;
|
||||
let doc = snap.doc;
|
||||
let language = project.languages.get(&snap.language);
|
||||
if options.tool.is_none()
|
||||
&& let Some(id) = settings.languages.plugin_formatters.get(snap.language.as_str()).filter(|s| !s.is_empty())
|
||||
@@ -304,10 +493,15 @@ async fn provider_edits(
|
||||
return Ok(Some(edits));
|
||||
}
|
||||
let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
|
||||
// Black is selected only when configured or preferred: the Ruff server's formatting doesn't replace it.
|
||||
if let Some(tool) = selected
|
||||
&& options.tool.is_none()
|
||||
&& tool != ExternalFormatter::Black
|
||||
&& !settings.languages.formatter(tool).prefer
|
||||
&& project.lsp.can_format(doc).await?
|
||||
&& match doc {
|
||||
Some(doc) => project.lsp.can_format(doc).await?,
|
||||
None => project.lsp.can_format_text(&snap.path, &snap.language).await,
|
||||
}
|
||||
{
|
||||
selected = None;
|
||||
}
|
||||
@@ -315,14 +509,20 @@ async fn provider_edits(
|
||||
if options.on_save && !settings.editor.format_on_save {
|
||||
return Ok(None);
|
||||
}
|
||||
let edits = project.lsp.format(doc, range, options).await?;
|
||||
let edits = match doc {
|
||||
Some(doc) => project.lsp.format(doc, range, options).await?,
|
||||
None => project.lsp.format_text(&snap.path, &snap.language, &snap.text, options).await?,
|
||||
};
|
||||
let text = snap.text;
|
||||
return tokio::task::spawn_blocking(move || Some(minimal_edits(&text, edits)))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()));
|
||||
};
|
||||
let tool_settings = settings.languages.formatter(selected);
|
||||
if options.on_save && !tool_settings.run_on_save {
|
||||
// Black takes over from the language server in its projects, so Format on save runs it too.
|
||||
let runs_on_save =
|
||||
tool_settings.run_on_save || (selected == ExternalFormatter::Black && settings.editor.format_on_save);
|
||||
if options.on_save && !runs_on_save {
|
||||
return Ok(None);
|
||||
}
|
||||
host.require_trust(window)?;
|
||||
@@ -332,12 +532,21 @@ async fn provider_edits(
|
||||
let config = language.and_then(|l| l.formatter).expect("external_tool selects languages with a formatter");
|
||||
let tool = selected.name();
|
||||
let name = formatter::display_name(tool);
|
||||
let custom = ide_sdk::apply::setting_path(&project.root, &tool_settings.path);
|
||||
let mut custom = ide_sdk::apply::setting_path(&project.root, &tool_settings.path);
|
||||
if custom.is_none() && matches!(selected, ExternalFormatter::Ruff | ExternalFormatter::Black) {
|
||||
let (root, near, settings) =
|
||||
(project.root.clone(), snap.path.parent().map(Path::to_path_buf), settings.clone());
|
||||
custom = tokio::task::spawn_blocking(move || interpreter_tool(&root, near.as_deref(), &settings, tool))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
}
|
||||
let tools = Tools::new(&host.local_data_dir);
|
||||
let whole_selection = range.is_some() && !formatter::supports_range(tool, &config);
|
||||
let unsupported_range = range.is_some() && !formatter::supports_range(tool, &config);
|
||||
let project_root = project.root.clone();
|
||||
let configuration_directory = settings.languages.ruff.configuration_directory.clone();
|
||||
let edits: IdeResult<Vec<TextEdit>> = tokio::task::spawn_blocking(move || {
|
||||
let style_settings = settings.clone();
|
||||
let documents = project.documents.clone();
|
||||
let result: IdeResult<(Vec<TextEdit>, bool, bool)> = tokio::task::spawn_blocking(move || {
|
||||
let text = ide_text::Document::new(&snap.text);
|
||||
let range = range.map(|range| format_range(&text, range));
|
||||
let config_file = if tool == "ruff" {
|
||||
@@ -345,47 +554,133 @@ async fn provider_edits(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut command = tools.formatter_command(tool, &snap.path, custom.as_deref())?;
|
||||
let dir = snap.path.parent().ok_or_else(|| IdeError::invalid(format!("{name}: file has no directory")))?;
|
||||
command.current_dir(dir);
|
||||
command.args(formatter::arguments(
|
||||
tool,
|
||||
&config,
|
||||
&snap.path,
|
||||
options.tab_size,
|
||||
options.insert_spaces,
|
||||
range,
|
||||
config_file.as_deref(),
|
||||
));
|
||||
let formatted = formatter::run(tool, command, &snap.text, &Default::default())?;
|
||||
Ok(text
|
||||
.diff(&formatted)
|
||||
.changes
|
||||
.into_iter()
|
||||
.map(|c| TextEdit {
|
||||
range: Range::new(text.offset_to_pos(c.from), text.offset_to_pos(c.to)),
|
||||
new_text: c.insert,
|
||||
})
|
||||
.collect())
|
||||
let style = if matches!(selected, ExternalFormatter::Ruff | ExternalFormatter::Black) {
|
||||
let editorconfig = style_settings
|
||||
.editor
|
||||
.code_style
|
||||
.editorconfig
|
||||
.then(|| documents.editorconfig().resolve(&snap.path))
|
||||
.flatten();
|
||||
python_style_for(
|
||||
tool,
|
||||
&snap.path,
|
||||
config_file.is_some(),
|
||||
&style_settings,
|
||||
editorconfig.as_ref(),
|
||||
user_config_dir(tool, dir).as_deref(),
|
||||
)
|
||||
} else {
|
||||
formatter::PythonStyle::default()
|
||||
};
|
||||
let run = |range| {
|
||||
let mut command = tools.formatter_command(tool, &snap.path, custom.as_deref())?;
|
||||
command.current_dir(dir);
|
||||
let args = formatter::arguments(
|
||||
tool,
|
||||
&config,
|
||||
&snap.path,
|
||||
options.tab_size,
|
||||
options.insert_spaces,
|
||||
range,
|
||||
config_file.as_deref(),
|
||||
);
|
||||
command.args(formatter::with_python_style(tool, args, style));
|
||||
formatter::run(tool, command, &snap.text, &Default::default())
|
||||
};
|
||||
let mut old_black = false;
|
||||
let formatted = match run(range) {
|
||||
// Black before 23.11 has no `--line-ranges`: format the whole file instead.
|
||||
Err(e) if tool == "black" && range.is_some() && e.message.contains("--line-ranges") => {
|
||||
old_black = true;
|
||||
run(None)?
|
||||
}
|
||||
result => result?,
|
||||
};
|
||||
if excluded_output(&snap.text, &formatted) {
|
||||
return Ok((Vec::new(), false, true));
|
||||
}
|
||||
let edits = diff_edits(&text, &formatted);
|
||||
Ok((edits, old_black, false))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
if edits.is_ok() && whole_selection {
|
||||
let (edits, old_black, excluded) = match result {
|
||||
Ok((edits, old_black, excluded)) => (Ok(edits), old_black, excluded),
|
||||
Err(e) => (Err(e), false, false),
|
||||
};
|
||||
// Notification titles are translated, and the catalog has "Black" as the colour.
|
||||
let title = if selected == ExternalFormatter::Black { "Black formatter" } else { name };
|
||||
if excluded && !options.on_save {
|
||||
project.sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Info,
|
||||
title: name.into(),
|
||||
body: Some(format!(
|
||||
"{name} does not support selection formatting for this language; formatted the whole file"
|
||||
)),
|
||||
title: title.into(),
|
||||
body: Some(format!("{name} left the file unchanged: its configuration excludes it")),
|
||||
});
|
||||
}
|
||||
let whole_selection = if old_black {
|
||||
Some("This Black cannot format a selection (Black 23.11 or later can); formatted the whole file".to_owned())
|
||||
} else {
|
||||
(edits.is_ok() && unsupported_range).then(|| {
|
||||
format!("{name} does not support selection formatting for this language; formatted the whole file")
|
||||
})
|
||||
};
|
||||
if let Some(body) = whole_selection {
|
||||
project.sink.emit(IdeEvent::Notify { level: NotifyLevel::Info, title: title.into(), body: Some(body) });
|
||||
}
|
||||
edits.map(Some).map_err(|e| e.with_tool(tool))
|
||||
}
|
||||
|
||||
/// The edits that turn `text` into `formatted`, one per changed region.
|
||||
fn diff_edits(text: &ide_text::Document, formatted: &str) -> Vec<TextEdit> {
|
||||
text.diff(formatted)
|
||||
.changes
|
||||
.into_iter()
|
||||
.map(|c| TextEdit {
|
||||
range: Range::new(text.offset_to_pos(c.from), text.offset_to_pos(c.to)),
|
||||
new_text: c.insert,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Optimize Imports for a Python document no language server organizes (the Ruff server starts
|
||||
/// only below a Ruff configuration): Ruff's CLI removes the unused imports and sorts the rest, with
|
||||
/// the project's Ruff settings when there are any. `None` for other documents and untrusted projects.
|
||||
pub async fn python_import_edits(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
cancel: CancellationToken,
|
||||
) -> IdeResult<Option<(ide_core::IpcPath, Vec<TextEdit>)>> {
|
||||
let project = host.project(window)?;
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.language.as_str() != "python" || snap.read_only || project.require_trust().is_err() {
|
||||
return Ok(None);
|
||||
}
|
||||
let settings = project.settings.effective();
|
||||
let custom = ide_sdk::apply::setting_path(&project.root, &settings.languages.ruff.path);
|
||||
let configured = settings.languages.ruff.configuration_directory.clone();
|
||||
let root = project.root.clone();
|
||||
let tools = Tools::new(&host.local_data_dir);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let config_file = ide_sdk::apply::ruff_configuration(&root, &configured)?;
|
||||
let custom = custom.or_else(|| interpreter_tool(&root, snap.path.parent(), &settings, "ruff"));
|
||||
let mut command = tools.formatter_command("ruff", &snap.path, custom.as_deref())?;
|
||||
if let Some(dir) = snap.path.parent() {
|
||||
command.current_dir(dir);
|
||||
}
|
||||
command.args(formatter::ruff_organize_imports_arguments(&snap.path, config_file.as_deref()));
|
||||
let fixed = formatter::run("ruff", command, &snap.text, &cancel)?;
|
||||
Ok(Some((snap.path, diff_edits(&ide_text::Document::new(&snap.text), &fixed))))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ExternalFormatter::{Oxfmt, Prettier, Ruff};
|
||||
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
|
||||
use ide_core::LanguageId;
|
||||
use ide_language::LanguageRegistry;
|
||||
|
||||
@@ -428,6 +723,211 @@ mod tests {
|
||||
assert_eq!(prettier.message, "Prettier cannot format Python files");
|
||||
let oxfmt = tool(Some(Oxfmt), "python", file, &settings).unwrap_err();
|
||||
assert_eq!(oxfmt.message, "oxfmt cannot format Python files");
|
||||
let biome = tool(Some(Biome), "python", file, &settings).unwrap_err();
|
||||
assert_eq!(biome.message, "Biome cannot format Python files");
|
||||
assert_eq!(tool(Some(Black), "python", file, &settings).unwrap(), Some(Black));
|
||||
let black = tool(Some(Black), "typescript", Path::new("/project/app.ts"), &settings).unwrap_err();
|
||||
assert_eq!(black.message, "Black cannot format TypeScript files");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(windows))]
|
||||
fn an_xdg_override_hides_fallback_python_formatter_configs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cwd = dir.path();
|
||||
let home = cwd.join("home");
|
||||
let fallback = home.join(".config");
|
||||
let xdg = cwd.join("config override");
|
||||
for (tool, name) in [("ruff", "ruff/ruff.toml"), ("black", "black")] {
|
||||
let config = fallback.join(name);
|
||||
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
|
||||
std::fs::write(config, "").unwrap();
|
||||
let probe = |xdg| xdg_user_config_dir(tool, cwd, xdg, Some(&home));
|
||||
assert!(user_configured(tool, probe(None).as_deref()), "{tool} should find its default config");
|
||||
assert!(!user_configured(tool, probe(Some(&xdg)).as_deref()), "{tool} should skip its default config");
|
||||
|
||||
let config = xdg.join(name);
|
||||
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
|
||||
std::fs::write(config, "").unwrap();
|
||||
assert!(user_configured(tool, probe(Some(&xdg)).as_deref()), "{tool} should find its XDG config");
|
||||
}
|
||||
|
||||
let relative = Some(Path::new("config override"));
|
||||
assert_eq!(xdg_user_config_dir("ruff", cwd, relative, Some(&home)), Some(fallback));
|
||||
assert_eq!(xdg_user_config_dir("black", cwd, relative, Some(&home)), Some(xdg));
|
||||
assert_eq!(xdg_user_config_dir("black", cwd, Some(Path::new("~/alt")), Some(&home)), Some(home.join("alt")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_style_reaches_ruff_and_black_only_without_their_configuration() {
|
||||
use ide_workspace::editorconfig::{EditorConfigProps, IndentStyle};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("repo");
|
||||
let user = dir.path().join("user config");
|
||||
std::fs::create_dir_all(root.join("app/src")).unwrap();
|
||||
std::fs::create_dir_all(root.join(".git")).unwrap();
|
||||
std::fs::create_dir_all(user.join("ruff")).unwrap();
|
||||
let file = root.join("app/src/main.py");
|
||||
let mut settings = Settings::default();
|
||||
let style = |tool, settings: &Settings, editorconfig: Option<&EditorConfigProps>| {
|
||||
python_style_for(tool, &file, false, settings, editorconfig, Some(&user))
|
||||
};
|
||||
let none = formatter::PythonStyle::default();
|
||||
// Nothing set: the tools keep their defaults.
|
||||
assert_eq!(style("ruff", &settings, None), none);
|
||||
let page = ide_core::editor_settings::LanguageCodeStyle {
|
||||
hard_wrap_at: Some(100),
|
||||
tab_size: Some(2),
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("python".into(), page);
|
||||
let set = formatter::PythonStyle { line_length: Some(100), indent_width: Some(2), use_tabs: None };
|
||||
assert_eq!(style("ruff", &settings, None), set);
|
||||
assert_eq!(style("black", &settings, None), set);
|
||||
assert_eq!(python_style_for("ruff", &file, true, &settings, None, Some(&user)), none);
|
||||
// The file's .editorconfig wins over the page, as in the editor.
|
||||
let editorconfig =
|
||||
EditorConfigProps { indent_size: Some(4), indent_style: Some(IndentStyle::Space), ..Default::default() };
|
||||
let indented = formatter::PythonStyle { line_length: Some(100), indent_width: Some(4), use_tabs: Some(false) };
|
||||
assert_eq!(style("ruff", &settings, Some(&editorconfig)), indented);
|
||||
|
||||
// The user's configurations: Ruff's always counts, Black's only when the project root
|
||||
// (here the repository) has no pyproject.toml.
|
||||
let (black_config, ignored_black_config) =
|
||||
if cfg!(windows) { (".black", "black") } else { ("black", ".black") };
|
||||
std::fs::write(user.join(ignored_black_config), "[tool.black]\n").unwrap();
|
||||
assert_eq!(style("black", &settings, None), set);
|
||||
std::fs::write(user.join(black_config), "[tool.black]\n").unwrap();
|
||||
assert_eq!(style("black", &settings, None), none);
|
||||
std::fs::write(root.join("pyproject.toml"), "[project]\nname = \"repo\"\n").unwrap();
|
||||
assert_eq!(style("black", &settings, None), set);
|
||||
std::fs::write(user.join("ruff/ruff.toml"), "").unwrap();
|
||||
assert_eq!(style("ruff", &settings, None), none);
|
||||
std::fs::remove_file(user.join("ruff/ruff.toml")).unwrap();
|
||||
|
||||
// The project's configurations.
|
||||
std::fs::write(root.join("app/pyproject.toml"), "[project]\nname = \"app\"\n").unwrap();
|
||||
assert_eq!(style("ruff", &settings, None), set);
|
||||
std::fs::write(root.join("pyproject.toml"), "[tool.black]\n").unwrap();
|
||||
assert_eq!(style("black", &settings, None), none);
|
||||
assert_eq!(style("ruff", &settings, None), set);
|
||||
std::fs::write(root.join(".ruff.toml"), "").unwrap();
|
||||
assert_eq!(style("ruff", &settings, None), none);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_output_for_a_file_with_code_is_an_exclusion_not_an_empty_file() {
|
||||
assert!(excluded_output("x = 1\n", ""));
|
||||
assert!(!excluded_output("\n\n", ""));
|
||||
assert!(!excluded_output("x = 1\n", "x = 1\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruff_comes_from_the_environment_of_the_files_own_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let bin = root.join(if cfg!(windows) { "svc/.venv/Scripts" } else { "svc/.venv/bin" });
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let exe = |name: &str| if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
|
||||
std::fs::write(bin.join(exe("python")), "").unwrap();
|
||||
std::fs::write(root.join("svc/.venv/pyvenv.cfg"), "").unwrap();
|
||||
let settings = Settings::default();
|
||||
let near = root.join("svc/src");
|
||||
assert_eq!(interpreter_tool(root, Some(&near), &settings, "ruff"), None);
|
||||
std::fs::write(bin.join(exe("ruff")), "").unwrap();
|
||||
assert_eq!(interpreter_tool(root, Some(&near), &settings, "ruff"), Some(bin.join(exe("ruff"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_comes_from_the_environment_of_the_files_own_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let bin = root.join(if cfg!(windows) { "svc/.venv/Scripts" } else { "svc/.venv/bin" });
|
||||
std::fs::create_dir_all(&bin).unwrap();
|
||||
let exe = |name: &str| if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
|
||||
std::fs::write(bin.join(exe("python")), "").unwrap();
|
||||
std::fs::write(root.join("svc/.venv/pyvenv.cfg"), "").unwrap();
|
||||
std::fs::write(root.join("svc/pyproject.toml"), "[tool.black]\n").unwrap();
|
||||
let settings = Settings::default();
|
||||
assert_eq!(interpreter_tool(root, Some(&root.join("svc/src")), &settings, "black"), None);
|
||||
std::fs::write(bin.join(exe("black")), "").unwrap();
|
||||
assert_eq!(
|
||||
interpreter_tool(root, Some(&root.join("svc/src")), &settings, "black"),
|
||||
Some(bin.join(exe("black")))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_config_or_preference_selects_black_for_python() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("svc/src")).unwrap();
|
||||
std::fs::create_dir_all(root.join("api")).unwrap();
|
||||
let (svc, api) = (root.join("svc/src/main.py"), root.join("api/main.py"));
|
||||
let mut settings = LanguagesSettings::default();
|
||||
std::fs::write(root.join("svc/pyproject.toml"), "[tool.ruff]\nline-length = 100\n").unwrap();
|
||||
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Ruff));
|
||||
std::fs::write(root.join("svc/pyproject.toml"), "[tool.black]\nline-length = 100\n").unwrap();
|
||||
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Black));
|
||||
assert_eq!(tool(None, "python", &api, &settings).unwrap(), Some(Ruff));
|
||||
settings.black.prefer = true;
|
||||
assert_eq!(tool(None, "python", &api, &settings).unwrap(), Some(Black));
|
||||
settings.black.languages.clear();
|
||||
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Ruff));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_finds_its_configuration_like_black_does() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let repo = dir.path().join("repo");
|
||||
std::fs::create_dir_all(repo.join(".git")).unwrap();
|
||||
std::fs::create_dir_all(repo.join("pkg/src")).unwrap();
|
||||
let file = repo.join("pkg/src/m.py");
|
||||
assert_eq!(black_pyproject(&file), None);
|
||||
// A pyproject without [tool.black] is passed over, up to the repository root.
|
||||
std::fs::write(repo.join("pkg/pyproject.toml"), "[project]\nname = \"pkg\"\n").unwrap();
|
||||
std::fs::write(repo.join("pyproject.toml"), "[tool.black]\nline-length = 100\n").unwrap();
|
||||
assert_eq!(black_pyproject(&file), Some(repo.join("pyproject.toml")));
|
||||
assert!(black_configured(&file));
|
||||
// The repository root's pyproject is Black's even without [tool.black]; nothing above counts.
|
||||
std::fs::write(repo.join("pyproject.toml"), "[project]\nname = \"repo\"\n").unwrap();
|
||||
std::fs::write(dir.path().join("pyproject.toml"), "[tool.black]\n").unwrap();
|
||||
assert_eq!(black_pyproject(&file), Some(repo.join("pyproject.toml")));
|
||||
assert!(!black_configured(&file));
|
||||
std::fs::write(repo.join("pkg/pyproject.toml"), "[tool.black]\n").unwrap();
|
||||
assert_eq!(black_pyproject(&file), Some(repo.join("pkg/pyproject.toml")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn biome_config_or_dependency_selects_biome_for_its_languages() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("web/src")).unwrap();
|
||||
let (web, api, readme) = (root.join("web/src/app.ts"), root.join("api/main.ts"), root.join("web/README.md"));
|
||||
let mut settings = LanguagesSettings::default();
|
||||
for marker in BIOME_MARKERS {
|
||||
let path = root.join("web").join(marker);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, "{}").unwrap();
|
||||
assert_eq!(tool(None, "typescript", &web, &settings).unwrap(), Some(Biome), "{marker}");
|
||||
assert_eq!(tool(None, "typescript", &api, &settings).unwrap(), Some(Prettier), "{marker}");
|
||||
// Biome doesn't format Markdown: Prettier keeps it.
|
||||
assert_eq!(tool(None, "markdown", &readme, &settings).unwrap(), Some(Prettier), "{marker}");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
}
|
||||
std::fs::write(root.join("web/biome.json"), "{}").unwrap();
|
||||
std::fs::write(root.join("web/.oxfmtrc.json"), "{}").unwrap();
|
||||
assert_eq!(tool(None, "css", &web, &settings).unwrap(), Some(Biome));
|
||||
settings.biome.languages.retain(|l| l != "css");
|
||||
assert_eq!(tool(None, "css", &web, &settings).unwrap(), Some(Oxfmt));
|
||||
// Biome only lints here: Prettier keeps formatting.
|
||||
std::fs::remove_file(root.join("web/.oxfmtrc.json")).unwrap();
|
||||
std::fs::write(root.join("web/biome.json"), r#"{ "formatter": { "enabled": false } }"#).unwrap();
|
||||
assert_eq!(tool(None, "typescript", &web, &settings).unwrap(), Some(Prettier));
|
||||
settings.biome.prefer = true;
|
||||
assert_eq!(tool(None, "typescript", &api, &settings).unwrap(), Some(Biome));
|
||||
let markdown = tool(Some(Biome), "markdown", &readme, &settings).unwrap_err();
|
||||
assert_eq!(markdown.message, "Biome cannot format Markdown files");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+76
-23
@@ -5,6 +5,8 @@
|
||||
|
||||
pub mod agent_secrets;
|
||||
pub mod catalogue;
|
||||
#[cfg(unix)]
|
||||
pub mod daemon;
|
||||
pub mod data_dirs;
|
||||
pub mod diagnostics_store;
|
||||
mod direnv;
|
||||
@@ -25,7 +27,7 @@ pub mod rpc;
|
||||
pub mod shell_env;
|
||||
pub mod trust;
|
||||
|
||||
pub use project::{Project, apply_git_executable, history_retention};
|
||||
pub use project::{Project, history_retention};
|
||||
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId, SharedSink};
|
||||
use ide_language::{LanguageRegistry, Syntax};
|
||||
@@ -34,7 +36,7 @@ use ide_terminal::TerminalManager;
|
||||
use ide_workspace::SettingsStore;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// Event sink for one window (by label).
|
||||
@@ -58,6 +60,27 @@ pub struct HostConfig {
|
||||
pub project_environment: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl HostConfig {
|
||||
/// A host under `base` for unit tests: `config`, `data` and `data` again for the machine-local
|
||||
/// directory, built-in languages, no grammars, a sink that drops events, the window as its own
|
||||
/// owner, the current tokio runtime and no project environment. Override fields with
|
||||
/// `HostConfig { sink_for: .., ..HostConfig::for_test(base) }`. Call it inside a runtime.
|
||||
pub(crate) fn for_test(base: &Path) -> Self {
|
||||
Self {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Host {
|
||||
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
|
||||
pub mcp: mcp::McpService,
|
||||
@@ -92,6 +115,7 @@ pub struct Host {
|
||||
/// The window that owns each open heap snapshot; its project's close closes them.
|
||||
pub(crate) heap_windows: Mutex<HashMap<ide_heap::HeapSnapshotId, String>>,
|
||||
pub(crate) heap_requests: ops::heap::HeapRequests,
|
||||
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
|
||||
/// SSH connections of Settings › SSH Configurations.
|
||||
pub ssh: Arc<ide_ssh::SshManager>,
|
||||
/// SFTP deployment, remote file editing and runs on run targets.
|
||||
@@ -190,6 +214,7 @@ impl Host {
|
||||
heap: Arc::new(ide_heap::HeapRegistry::new(ide_heap::snapshots_root(&local_data_dir))),
|
||||
heap_windows: Mutex::default(),
|
||||
heap_requests: Default::default(),
|
||||
rebase_editors: Default::default(),
|
||||
languages,
|
||||
syntax,
|
||||
config_dir,
|
||||
@@ -207,6 +232,7 @@ impl Host {
|
||||
};
|
||||
host.apply_proxy();
|
||||
host.apply_added_jdks();
|
||||
host.apply_git_executable();
|
||||
// Before any project starts jdtls; the deleting itself can take a while.
|
||||
let unused =
|
||||
ide_sdk::jdtls_workspaces::take_unused(&host.local_data_dir, ide_sdk::jdtls_workspaces::UNUSED_FOR);
|
||||
@@ -345,7 +371,7 @@ impl Host {
|
||||
}
|
||||
if let Some(plugins) = plugins::editor_plugin_host() {
|
||||
plugins.invalidate_client_navigation(&project.root, Some(window), None);
|
||||
plugins.set_active_file(window, None);
|
||||
plugins.set_active_file(window, None, None);
|
||||
}
|
||||
if !project.light {
|
||||
self.environment.project_closed();
|
||||
@@ -502,6 +528,25 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cleans up per-connection client state when a remote window disconnects from a
|
||||
/// persistent daemon, leaving the project, index, language servers, terminals,
|
||||
/// runs and agent sessions running.
|
||||
pub fn client_disconnected(&self) {
|
||||
let windows: Vec<String> = self.projects.read().keys().cloned().collect();
|
||||
for window in &windows {
|
||||
self.mcp_reports.forget_window(window);
|
||||
self.mcp_requests.forget_window(window);
|
||||
for request in self.project_requests.write().remove(self.owner_window(window)).unwrap_or_default() {
|
||||
self.cancel_request(request);
|
||||
}
|
||||
}
|
||||
self.terminals.detach_output();
|
||||
self.processes.detach_output();
|
||||
for project in self.projects() {
|
||||
project.documents.release_client_refs();
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops what this host started: heap snapshots, notebook kernels, language servers, agents,
|
||||
/// runs and terminals.
|
||||
/// For a process that exits without dropping the host (the remote server).
|
||||
@@ -509,7 +554,6 @@ impl Host {
|
||||
// A capture's dump may hold secrets from the debuggee's memory: delete it before exiting.
|
||||
ops::heap::shutdown(self).await;
|
||||
self.environment.shutdown();
|
||||
self.processes.kill_all();
|
||||
self.terminals.kill_all();
|
||||
let projects: Vec<_> = self.projects.write().drain().map(|(_, p)| p).collect();
|
||||
for project in &projects {
|
||||
@@ -529,22 +573,33 @@ impl Host {
|
||||
project.notebooks.stop_admission();
|
||||
project.agents.shutdown();
|
||||
}
|
||||
let stop_processes = async {
|
||||
for project in &projects {
|
||||
self.debugger.stop_under(&project.root).await;
|
||||
}
|
||||
self.processes.shutdown().await;
|
||||
};
|
||||
// Kernel cleanup owns its interrupt/termination/reaping deadlines. An
|
||||
// outer LSP timeout must never abort it before owned children are reaped.
|
||||
for project in &projects {
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.shutdown().await;
|
||||
let stop_kernels = async {
|
||||
for project in &projects {
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
bridge.shutdown().await;
|
||||
}
|
||||
project.notebooks.shutdown().await;
|
||||
}
|
||||
project.notebooks.shutdown().await;
|
||||
}
|
||||
};
|
||||
let stop_language_servers = async {
|
||||
for project in &projects {
|
||||
project.lsp.shutdown_all().await;
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(std::time::Duration::from_secs(10), stop_language_servers).await.is_err() {
|
||||
tracing::warn!("language servers did not shut down in time");
|
||||
}
|
||||
let stop_lsp = async {
|
||||
if tokio::time::timeout(std::time::Duration::from_secs(10), stop_language_servers).await.is_err() {
|
||||
tracing::warn!("language servers did not shut down in time");
|
||||
}
|
||||
};
|
||||
tokio::join!(stop_processes, stop_kernels, stop_lsp);
|
||||
}
|
||||
|
||||
// ---- cancellable requests: the UI allocates ids, `cancel_request` cancels ----
|
||||
@@ -598,6 +653,14 @@ impl Host {
|
||||
let homes = self.global_settings.effective().languages.java.added_jdks;
|
||||
ide_sdk::java::set_added_jdks(homes.into_iter().map(PathBuf::from));
|
||||
}
|
||||
|
||||
/// Global Settings › Version Control › Git › Path to Git executable, for git started outside
|
||||
/// a project's repositories (clone, init, agents, gh, plugins). A project's own value stays
|
||||
/// with its repositories ([`Project::repos`]).
|
||||
pub fn apply_git_executable(&self) {
|
||||
let exe = self.global_settings.read_effective(|s| s.vcs.git.executable.trim().to_owned());
|
||||
ide_vcs::set_default_git_executable((!exe.is_empty()).then(|| Path::new(&exe)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -611,17 +674,7 @@ mod tests {
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
std::fs::write(root.join("main.rs"), "fn main() {}\n").unwrap();
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("local"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(|_| {})),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
|
||||
let project = Arc::downgrade(&host.open_project("main", &root).unwrap());
|
||||
host.close_project_detached("main");
|
||||
assert!(host.project("main").is_err());
|
||||
|
||||
@@ -42,15 +42,9 @@ impl Fixture {
|
||||
}
|
||||
let syntax: Arc<std::sync::OnceLock<Arc<ide_language::Syntax>>> = Arc::default();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("local"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: syntax.clone(),
|
||||
sink_for: Box::new(|_| Arc::new(|_| {})),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
..HostConfig::for_test(&base)
|
||||
}));
|
||||
let fixture = Self { host, base, syntax, _tmp: tmp };
|
||||
fixture.set("enabled", json!(true));
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
use super::diff::{ChangedFileText, MAX_DIFF_LINES, build_unified_diff};
|
||||
use super::{edits_for, open_document, requested_files, whole_range};
|
||||
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
|
||||
use crate::ops::lsp::RUFF_ORGANIZE_IMPORTS;
|
||||
use ide_core::{DocId, IdeError, IdeResult};
|
||||
use std::path::Path;
|
||||
|
||||
@@ -157,7 +158,7 @@ async fn format(call: &Call, doc: DocId, info: &ide_workspace::DocumentInfo) ->
|
||||
.await
|
||||
}
|
||||
|
||||
/// Runs the `source.organizeImports` code action of the document's language server.
|
||||
/// Runs the document's `source.organizeImports` code action, including the host's Ruff fallback.
|
||||
/// Nothing offered: nothing to do, unless the server says it has no such action at all.
|
||||
pub(super) async fn organize_imports(call: &Call, doc: DocId, path: &Path) -> IdeResult<()> {
|
||||
let host = call.host();
|
||||
@@ -173,12 +174,20 @@ pub(super) async fn organize_imports(call: &Call, doc: DocId, path: &Path) -> Id
|
||||
}
|
||||
};
|
||||
let organizes = |kind: &str| kind == ORGANIZE_IMPORTS || kind.starts_with("source.organizeImports.");
|
||||
let ruff_unavailable = query
|
||||
.actions
|
||||
.iter()
|
||||
.find(|a| a.kind.as_deref() == Some(RUFF_ORGANIZE_IMPORTS))
|
||||
.and_then(|a| a.disabled_reason.clone());
|
||||
let action = query
|
||||
.actions
|
||||
.into_iter()
|
||||
.filter(|a| a.disabled_reason.is_none() && a.kind.as_deref().is_some_and(organizes))
|
||||
.max_by_key(|a| a.is_preferred);
|
||||
let Some(action) = action else {
|
||||
if let Some(reason) = ruff_unavailable {
|
||||
return Err(IdeError::unavailable(reason));
|
||||
}
|
||||
let offered = query.advertised_kinds.is_none_or(|kinds| kinds.iter().any(|k| k == "source" || organizes(k)));
|
||||
return if offered {
|
||||
Ok(())
|
||||
|
||||
@@ -23,7 +23,25 @@ const DEFAULT_TREE_DEPTH: i64 = 5;
|
||||
const TREE_LIMIT: usize = 100;
|
||||
|
||||
pub fn tools() -> Vec<Tool> {
|
||||
vec![read_file(), list_directory_tree()]
|
||||
vec![get_workspace_roots(), read_file(), list_directory_tree()]
|
||||
}
|
||||
|
||||
// --- get_workspace_roots ---------------------------------------------------------
|
||||
|
||||
fn get_workspace_roots() -> Tool {
|
||||
Tool::new(
|
||||
"get_workspace_roots",
|
||||
"Returns the root directories of the IDE workspace: this project and the trusted projects attached to it
|
||||
in the same window, as absolute paths. A task works in one directory, but its workspace can hold several projects.
|
||||
Call this when asked about the workspace, project or working directories, and before planning a change that may span
|
||||
projects. Other tools reach an attached project by its root as `projectPath`.",
|
||||
|call| async move {
|
||||
let root = call.root().to_path_buf();
|
||||
let mut roots = vec![root.clone()];
|
||||
roots.extend(crate::mcp::tool::trusted_attachments(&call.host.trust, &root));
|
||||
Output::json(json!({ "projectRoot": root, "roots": roots }))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// --- read_file -----------------------------------------------------------------
|
||||
@@ -184,10 +202,9 @@ marked directory are not marked again.",
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_millis(timeout.max(0) as u64);
|
||||
let cancel = call.cancel.clone();
|
||||
let marks = Marks {
|
||||
root: call.root().to_path_buf(),
|
||||
excludes: FileMask::new(&[], &call.project().search_excludes()).ok(),
|
||||
};
|
||||
// Matched from the root holding the directory: an attached project has its own exclusions.
|
||||
let root = call.project().root_of(&dir);
|
||||
let marks = Marks { excludes: FileMask::new(&[], &call.project().search_excludes_in(&root)).ok(), root };
|
||||
// The directory itself, when it or one above it is left out.
|
||||
let root_mark = marker(ide_index::walk_skips(call.root(), &dir), marks.ide_excluded(&dir, true));
|
||||
let mut tree = TreeRender {
|
||||
|
||||
@@ -16,6 +16,8 @@ mod search;
|
||||
pub mod service;
|
||||
mod symbols;
|
||||
mod tool;
|
||||
|
||||
pub(crate) use tool::trusted_attachments;
|
||||
mod util;
|
||||
|
||||
use crate::Host;
|
||||
|
||||
@@ -488,7 +488,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
|
||||
/// (compile errors are added to `errors`). Other configurations are returned as they are.
|
||||
async fn resolve_jvm_application(
|
||||
call: &Call,
|
||||
config: RunConfig,
|
||||
mut config: RunConfig,
|
||||
errors: &mut BuildErrors,
|
||||
) -> IdeResult<Result<RunConfig, String>> {
|
||||
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
|
||||
@@ -544,6 +544,7 @@ async fn resolve_jvm_application(
|
||||
(Some(exec), "java") => exec.clone(),
|
||||
_ => config.command.clone(),
|
||||
};
|
||||
config.extras.module = Some(module);
|
||||
Ok(Ok(RunConfig { command, args, ..config }))
|
||||
}
|
||||
|
||||
|
||||
@@ -837,8 +837,6 @@ async fn file_search(call: Call) -> IdeResult<Output> {
|
||||
.add(build_glob(&normalize_glob(&q, call.root(), &[])?)?)
|
||||
.build()
|
||||
.map_err(|_| IdeError::invalid(format!("Invalid glob pattern: {q}")))?;
|
||||
// Ignored names and "Exclude files" patterns, which `read_dir` does not flag.
|
||||
let excludes = if include_excluded { None } else { Some(FileMask::new(&[], &call.project().search_excludes())?) };
|
||||
let root = call.root().to_path_buf();
|
||||
let content = call.project().content_roots();
|
||||
// Where a folder's exclusions are matched from: the content root holding it, or the project.
|
||||
@@ -862,6 +860,15 @@ async fn file_search(call: Call) -> IdeResult<Output> {
|
||||
.map(|r| (r.clone(), r))
|
||||
.collect(),
|
||||
};
|
||||
// Ignored names and "Exclude files" patterns, which `read_dir` does not flag, by walked root.
|
||||
let mut excludes = Vec::new();
|
||||
if !include_excluded {
|
||||
for (_, base) in &roots {
|
||||
if !excludes.iter().any(|(b, _)| b == base) {
|
||||
excludes.push((base.clone(), FileMask::new(&[], &call.project().search_excludes_in(base))?));
|
||||
}
|
||||
}
|
||||
}
|
||||
let host = call.host();
|
||||
let walk = Walk {
|
||||
host: host.clone(),
|
||||
@@ -898,7 +905,7 @@ struct Walk {
|
||||
window: String,
|
||||
root: PathBuf,
|
||||
include_excluded: bool,
|
||||
excludes: Option<FileMask>,
|
||||
excludes: Vec<(PathBuf, FileMask)>,
|
||||
glob: GlobSet,
|
||||
scope: PathScope,
|
||||
limit: usize,
|
||||
@@ -931,7 +938,8 @@ impl Walk {
|
||||
continue;
|
||||
}
|
||||
let Ok(in_base) = entry.path.strip_prefix(base) else { continue };
|
||||
if self.excludes.as_ref().is_some_and(|m| !m.matches(&in_base.to_string_lossy().replace('\\', "/"))) {
|
||||
let mask = self.excludes.iter().find(|(b, _)| b == base).map(|(_, m)| m);
|
||||
if mask.is_some_and(|m| !m.matches(&in_base.to_string_lossy().replace('\\', "/"))) {
|
||||
continue;
|
||||
}
|
||||
match entry.kind {
|
||||
|
||||
@@ -65,10 +65,7 @@ impl Call {
|
||||
}
|
||||
/// The projects attached to this one that the user trusts (each is trusted on its own).
|
||||
fn trusted_attachments(&self) -> Vec<PathBuf> {
|
||||
attached_projects(self.root())
|
||||
.into_iter()
|
||||
.filter(|root| self.host.trust.trusted(root).unwrap_or(false))
|
||||
.collect()
|
||||
trusted_attachments(&self.host.trust, self.root())
|
||||
}
|
||||
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
|
||||
self.host.mcp_requests.ask(self, request).await
|
||||
@@ -327,6 +324,11 @@ pub fn ensure_inside(root: &Path, path: &Path) -> IdeResult<()> {
|
||||
resolve_inside(root, &path.to_string_lossy()).map(|_| ())
|
||||
}
|
||||
|
||||
/// The projects attached to the one at `root` that the user trusts (each is trusted on its own).
|
||||
pub(crate) fn trusted_attachments(trust: &crate::trust::TrustStore, root: &Path) -> Vec<PathBuf> {
|
||||
attached_projects(root).into_iter().filter(|p| trust.trusted(p).unwrap_or(false)).collect()
|
||||
}
|
||||
|
||||
/// The projects attached to the one at `root` (its workspace members), `root` itself left out.
|
||||
pub(crate) fn attached_projects(root: &Path) -> Vec<PathBuf> {
|
||||
ide_workspace::workspace::Workspace::load(root)
|
||||
|
||||
@@ -102,9 +102,7 @@ This is useful to detect all repositories in a multi-repository project.
|
||||
In OpenIDEA each root also tells its current `branch` (absent when HEAD is detached), `headCommit` and a merge, \
|
||||
rebase or cherry-pick in progress (`operationInProgress`).",
|
||||
|call| async move {
|
||||
let host = call.host();
|
||||
let window = call.window.clone();
|
||||
let roots = call.host.blocking(move || crate::ops::vcs::vcs_roots(&host, &window)).await?;
|
||||
let roots = crate::ops::vcs::vcs_roots(&call.host(), &call.window).await?;
|
||||
let list: Vec<Value> = roots
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
@@ -257,10 +255,7 @@ By default all Git repositories are returned.",
|
||||
let include_ignored = call.flag("includeIgnored", false)?;
|
||||
let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?;
|
||||
let host = call.host();
|
||||
let h = host.clone();
|
||||
let w = call.window.clone();
|
||||
let repos: Vec<(PathBuf, Option<String>)> = host
|
||||
.blocking(move || crate::ops::vcs::vcs_roots(&h, &w))
|
||||
let repos: Vec<(PathBuf, Option<String>)> = crate::ops::vcs::vcs_roots(&host, &call.window)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|r| (r.root.into_path_buf(), r.head))
|
||||
|
||||
@@ -8,8 +8,9 @@ use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CustomAgentInput, ExternalSession, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, McpServer,
|
||||
McpServerInput, McpTransport, NewAgentTask, SkillsPolicy,
|
||||
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection,
|
||||
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
|
||||
RemoteSkillPreview, SkillsPolicy,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -42,12 +43,19 @@ pub fn agent_unsubscribe(host: &Host, window: &str, subscriber: String) -> IdeRe
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads the ACP registry's install state for every provider from disk, so it runs on the
|
||||
/// blocking pool.
|
||||
#[command(trust = trusted)]
|
||||
pub fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
|
||||
pub async fn agent_providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
|
||||
host.require_trust(window)?;
|
||||
let mut providers = host.project(window)?.agents.providers();
|
||||
ide_agent::registry::mark_updates(®istry_paths(host), &mut providers);
|
||||
Ok(providers)
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
let paths = registry_paths(host);
|
||||
host.blocking(move || {
|
||||
let mut providers = agents.providers();
|
||||
ide_agent::registry::mark_updates(&paths, &mut providers);
|
||||
Ok(providers)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Hermes Agent profiles on this machine (`default` first); empty without Hermes.
|
||||
@@ -248,9 +256,15 @@ pub async fn agent_commands(
|
||||
host.project(window)?.agents.commands(&provider, task.as_deref()).await
|
||||
}
|
||||
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s.
|
||||
/// Entries of `task`'s conversation, or of its subagent `subagent`'s. Async so a long
|
||||
/// conversation is cloned and serialised off the main thread.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_entries(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
|
||||
pub async fn agent_entries(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
) -> IdeResult<Vec<AgentEntry>> {
|
||||
host.project(window)?.agents.entries(&task, subagent)
|
||||
}
|
||||
|
||||
@@ -1040,16 +1054,20 @@ pub fn agent_set_skill_overrides(
|
||||
host.project(window)?.agents.set_skill_overrides(&task, overrides)
|
||||
}
|
||||
|
||||
/// Every skill discovered in the project and the user's folders, with the mode a session
|
||||
/// of this project runs it with (without any session's own overrides).
|
||||
/// Every skill discovered in the project, the user's folders and enabled plugins, with
|
||||
/// the mode a session runs it with (without any session's own overrides).
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<AgentSkillState>> {
|
||||
let project = host.project(window)?;
|
||||
let root = project.root.clone();
|
||||
let (policy, home) = (skills_policy(&project), dirs::home_dir());
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
let policy = host_skills_policy(host, project.as_deref());
|
||||
let home = dirs::home_dir();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills(&root, home.as_deref()),
|
||||
ide_agent::skills::discover_skills_with_plugins(
|
||||
&policy.workspace_roots,
|
||||
home.as_deref(),
|
||||
&policy.plugin_dirs,
|
||||
),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
@@ -1101,21 +1119,123 @@ pub fn agent_skills_set_mode(
|
||||
}
|
||||
}
|
||||
}
|
||||
match project {
|
||||
Some(project) => {
|
||||
let root = project.root.clone();
|
||||
let policy = skills_policy(&project);
|
||||
let home = dirs::home_dir();
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills(&root, home.as_deref()),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
policy.workspace_trusted,
|
||||
))
|
||||
}
|
||||
None => Ok(Vec::new()),
|
||||
let policy = host_skills_policy(host, project.as_deref());
|
||||
let home = dirs::home_dir();
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills_with_plugins(&policy.workspace_roots, home.as_deref(), &policy.plugin_dirs),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
policy.workspace_trusted,
|
||||
))
|
||||
}
|
||||
|
||||
/// Resolves a GitHub `owner/repo[/path][@ref]` source and lists the `SKILL.md` skills in it.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_skills_browse(
|
||||
host: &Host,
|
||||
source: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<RemoteSkillBrowseResult> {
|
||||
let cancel = host.begin_request(request);
|
||||
let search_path = ide_core::tool_path::search_path();
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
|
||||
ide_agent::skill_installer::browse_skills(&fetcher, &source, &cancel)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
host.end_request(request);
|
||||
res?
|
||||
}
|
||||
|
||||
/// Fetches one skill's `SKILL.md`, file list, and static security scan warnings before installation.
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_skills_preview(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
owner: String,
|
||||
repo: String,
|
||||
git_ref: String,
|
||||
subpath: String,
|
||||
request: RequestId,
|
||||
) -> IdeResult<RemoteSkillPreview> {
|
||||
let cancel = host.begin_request(request);
|
||||
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
|
||||
let home = dirs::home_dir();
|
||||
let search_path = ide_core::tool_path::search_path();
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
|
||||
ide_agent::skill_installer::preview_skill(
|
||||
&fetcher,
|
||||
ide_agent::skill_installer::RepoRef { owner: &owner, repo: &repo, git_ref: &git_ref },
|
||||
&subpath,
|
||||
home.as_deref(),
|
||||
ws_root.as_deref(),
|
||||
&cancel,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
host.end_request(request);
|
||||
res?
|
||||
}
|
||||
|
||||
/// Installs the selected skill subtree into `~/.agents/skills` (User) or `<workspace>/.agents/skills` (Workspace).
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_skills_install(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
input: InstallRemoteSkillRequest,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<AgentSkillState>> {
|
||||
let project = host.project(window).ok().filter(|p| !p.light);
|
||||
if input.scope == McpScope::Workspace {
|
||||
host.require_trust(window)?;
|
||||
}
|
||||
let ws_root = project.as_ref().map(|p| p.root.clone());
|
||||
let home = dirs::home_dir();
|
||||
let cancel = host.begin_request(request);
|
||||
let search_path = ide_core::tool_path::search_path();
|
||||
let install_home = home.clone();
|
||||
let install_ws = ws_root.clone();
|
||||
let res = tokio::task::spawn_blocking(move || {
|
||||
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
|
||||
ide_agent::skill_installer::install_skill(
|
||||
&fetcher,
|
||||
&input,
|
||||
install_home.as_deref(),
|
||||
install_ws.as_deref(),
|
||||
&cancel,
|
||||
)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
host.end_request(request);
|
||||
res??;
|
||||
|
||||
let event = IdeEvent::SettingsChanged { key: "agents.skills".into() };
|
||||
for p in host.projects() {
|
||||
p.agents.notify_mcp_servers_changed();
|
||||
p.sink.emit(event.clone());
|
||||
}
|
||||
|
||||
let policy = host_skills_policy(host, project.as_deref());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills_with_plugins(
|
||||
&policy.workspace_roots,
|
||||
home.as_deref(),
|
||||
&policy.plugin_dirs,
|
||||
),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
policy.workspace_trusted,
|
||||
))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?
|
||||
}
|
||||
|
||||
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
|
||||
@@ -1162,12 +1282,51 @@ fn persist_skills_map(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The skill policies a session of `project` resolves against.
|
||||
fn skills_policy(project: &crate::Project) -> SkillsPolicy {
|
||||
SkillsPolicy {
|
||||
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(),
|
||||
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone(),
|
||||
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
|
||||
/// Workspace folders to scan for skills: the project root plus any multi-repo workspace members.
|
||||
pub(crate) fn workspace_skill_roots(root: &std::path::Path) -> Vec<std::path::PathBuf> {
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
if let Ok(Some(ws)) = ide_workspace::workspace::Workspace::load(root) {
|
||||
for member in ws.projects {
|
||||
if member.exists() && !roots.contains(&member) {
|
||||
roots.push(member);
|
||||
}
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
/// The skill policies a session of `project` (or global Settings without a project) resolves against.
|
||||
fn host_skills_policy(host: &Host, project: Option<&crate::Project>) -> SkillsPolicy {
|
||||
match project {
|
||||
Some(project) => {
|
||||
let workspace_trusted = project.trusted.load(std::sync::atomic::Ordering::Acquire);
|
||||
let plugin_dirs = host
|
||||
.plugin_host()
|
||||
.map(|plugins| plugins.skill_dirs(Some(&project.root), workspace_trusted))
|
||||
.unwrap_or_default();
|
||||
SkillsPolicy {
|
||||
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(),
|
||||
workspace: project
|
||||
.settings
|
||||
.layer(ide_workspace::settings::SettingsScope::Project)
|
||||
.agents
|
||||
.skills
|
||||
.clone(),
|
||||
workspace_trusted,
|
||||
workspace_roots: workspace_skill_roots(&project.root),
|
||||
plugin_dirs,
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let plugin_dirs = host.plugin_host().map(|plugins| plugins.skill_dirs(None, true)).unwrap_or_default();
|
||||
SkillsPolicy {
|
||||
user: host.global_settings.effective().agents.skills.clone(),
|
||||
workspace: Default::default(),
|
||||
workspace_trusted: true,
|
||||
workspace_roots: Vec::new(),
|
||||
plugin_dirs,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1327,7 +1486,10 @@ ide_command::domain!(
|
||||
agent_set_env,
|
||||
agent_set_mcp_overrides,
|
||||
agent_set_skill_overrides,
|
||||
agent_skills_browse,
|
||||
agent_skills_install,
|
||||
agent_skills_list,
|
||||
agent_skills_preview,
|
||||
agent_skills_set_mode,
|
||||
agent_stop_background,
|
||||
agent_subscribe,
|
||||
|
||||
@@ -81,12 +81,12 @@ pub(crate) fn sources_in(root: &Path, excludes: &[String]) -> Vec<StepSource> {
|
||||
/// Every Cucumber source of the project (its folder and the content roots outside it).
|
||||
pub fn cucumber_sources(host: &Host, window: &str) -> IdeResult<Vec<StepSource>> {
|
||||
let project = host.project(window)?;
|
||||
let mut excludes = project.search_excludes();
|
||||
// Cucumber's own sources (and every other package's) are not the project's steps.
|
||||
excludes.push("node_modules".to_owned());
|
||||
excludes.push("site-packages".to_owned());
|
||||
let mut out = Vec::new();
|
||||
for root in std::iter::once(project.root.clone()).chain(project.content_roots()) {
|
||||
let mut excludes = project.search_excludes_in(&root);
|
||||
// Cucumber's own sources (and every other package's) are not the project's steps.
|
||||
excludes.push("node_modules".to_owned());
|
||||
excludes.push("site-packages".to_owned());
|
||||
out.extend(sources_in(&root, &excludes));
|
||||
}
|
||||
out.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Maven / Gradle tool windows (the build model and its background sync) and
|
||||
//! Build › Build Project (compiling with the project's build system).
|
||||
mod workspace;
|
||||
pub(super) mod workspace;
|
||||
|
||||
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
|
||||
use crate::ops::Channel;
|
||||
@@ -9,13 +9,16 @@ use ide_command::command;
|
||||
|
||||
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
|
||||
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
|
||||
use ide_build::maven::sources;
|
||||
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
|
||||
use ide_build::pom_edit::{ArtifactKey, Exclusion};
|
||||
use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit};
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use ide_core::{
|
||||
CancellationToken, DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit,
|
||||
};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -181,7 +184,7 @@ fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings)
|
||||
|
||||
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
|
||||
/// the tool window do.
|
||||
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
|
||||
pub(super) fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
|
||||
let profiles = ide_build::maven_profiles(cache);
|
||||
if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) {
|
||||
for p in &mut m.projects {
|
||||
@@ -281,6 +284,35 @@ pub async fn gradle_unlink_projects(host: &Host, window: &str, paths: Vec<String
|
||||
set_gradle_projects(host, window, paths, false).await
|
||||
}
|
||||
|
||||
struct MavenSourceRefresh {
|
||||
root: PathBuf,
|
||||
repository: PathBuf,
|
||||
candidates: Vec<(usize, sources::Artifact)>,
|
||||
}
|
||||
|
||||
fn cached_maven_sources(
|
||||
model: &BuildModel,
|
||||
scopes: Vec<workspace::Scope>,
|
||||
window_root: &Path,
|
||||
build_dir: Option<&str>,
|
||||
) -> Vec<MavenSourceRefresh> {
|
||||
let Some(maven) = &model.maven else { return Vec::new() };
|
||||
scopes
|
||||
.into_iter()
|
||||
.filter(|scope| workspace::selected(scope, window_root, BuildTool::Maven, build_dir))
|
||||
.filter_map(|scope| {
|
||||
let repository = ide_sdk::apply::maven_local_repository(&scope.root, &scope.settings)
|
||||
.or_else(ide_build::maven::default_local_repo)?;
|
||||
let projects = maven.projects.iter().enumerate().filter(|(_, project)| {
|
||||
Path::new(project.project_root.as_deref().unwrap_or_default()) == scope.root
|
||||
|| (project.project_root.is_none() && scope.root == window_root)
|
||||
});
|
||||
let candidates = sources::cached_snapshots(&repository, projects);
|
||||
(!candidates.is_empty()).then_some(MavenSourceRefresh { root: scope.root, repository, candidates })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Runs Maven (`help:effective-pom dependency:tree`) or Gradle (`tasks --all`) in the
|
||||
/// background, reporting progress on `on_progress`; cancellable with `cancel_request(request)`.
|
||||
/// Returns the refreshed model; a failed build is reported in its `syncError`.
|
||||
@@ -377,72 +409,122 @@ pub async fn build_sync(
|
||||
let scopes = workspace::scopes(&p, &config)?;
|
||||
let model = workspace::load_scopes(&p.root, &scopes);
|
||||
let updates = workspace::update_files(&p.root, &scopes, &model, tool);
|
||||
Ok::<_, IdeError>((model, profiles_changed, offline_changed, updates))
|
||||
let snapshots = if tool == BuildTool::Maven && !offline {
|
||||
cached_maven_sources(&model, scopes, &p.root, build_dir.as_deref())
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
Ok::<_, IdeError>((model, profiles_changed || offline_changed, updates, snapshots))
|
||||
})
|
||||
.await
|
||||
.map_err(join_err);
|
||||
host.end_request(request);
|
||||
let (model, profiles_changed, offline_changed, updates) = result??;
|
||||
if completion_token.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
// Gradle may report project folders outside the project (`includeFlat`), and a Maven
|
||||
// reactor may have gained or dropped modules beside it: index and list them.
|
||||
project.refresh_index_scope();
|
||||
let p = project.clone();
|
||||
tokio::task::spawn_blocking(move || p.refresh_repositories());
|
||||
// New source folders and dependency versions: the Project view and External Libraries reload.
|
||||
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
|
||||
if tool == BuildTool::Maven
|
||||
&& model.maven.is_some()
|
||||
&& let Some(bridge) = &project.kotlin_bridge
|
||||
{
|
||||
bridge.configure_maven(offline, bridge_profiles);
|
||||
}
|
||||
// jdtls re-imports on pom changes but misses artifacts added to ~/.m2
|
||||
// meanwhile ("missing artifact" stays until Invalidate Caches); asking it
|
||||
// to update the project configurations re-resolves them (#436). The same
|
||||
// holds for Gradle: it reuses its cached classpath on restart, so a
|
||||
// dependency added to `build.gradle` stays unresolved until told to sync.
|
||||
let lsp = project.lsp.clone();
|
||||
let documents = project.documents.clone();
|
||||
tokio::spawn(async move {
|
||||
if profiles_changed || offline_changed {
|
||||
// jdtls takes the profiles and offline mode from its Maven settings (see `ide_sdk::maven_profiles`).
|
||||
lsp.reconfigure().await;
|
||||
let result = async {
|
||||
let (mut model, reconfigure, updates, snapshots) = result??;
|
||||
if completion_token.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let first = updates.first().cloned();
|
||||
for file in updates {
|
||||
let uri = ide_lsp::path_to_uri_string(&file);
|
||||
if let Err(e) = lsp.java_update_project_configs(&file, vec![uri]).await {
|
||||
tracing::debug!("java/projectConfigurationsUpdate: {e}");
|
||||
}
|
||||
}
|
||||
let changed = {
|
||||
let lsp = lsp.clone();
|
||||
tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default()
|
||||
};
|
||||
if let Some(file) = first
|
||||
&& let Err(e) = lsp.java_refresh_archives(&file, &changed).await
|
||||
// A reactor or Gradle build may have changed its external project folders.
|
||||
project.refresh_index_scope();
|
||||
let p = project.clone();
|
||||
tokio::task::spawn_blocking(move || p.refresh_repositories());
|
||||
project.sink.emit(IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
|
||||
if tool == BuildTool::Maven
|
||||
&& model.maven.is_some()
|
||||
&& let Some(bridge) = &project.kotlin_bridge
|
||||
{
|
||||
tracing::debug!("openidea.java.refreshArchives: {e}");
|
||||
bridge.configure_maven(offline, bridge_profiles.clone());
|
||||
}
|
||||
refresh_library_classes(&lsp, &documents).await;
|
||||
});
|
||||
Ok(model)
|
||||
let lsp = project.lsp.clone();
|
||||
let documents = project.documents.clone();
|
||||
if snapshots.is_empty() {
|
||||
tokio::spawn(async move {
|
||||
update_java_projects(&lsp, &updates, reconfigure, None).await;
|
||||
refresh_library_archives(&lsp, &documents, &updates, Vec::new()).await;
|
||||
});
|
||||
} else {
|
||||
// JDT LS resolves the binary jars while importing Maven projects.
|
||||
update_java_projects(&lsp, &updates, reconfigure, Some(&completion_token)).await;
|
||||
let cancel = completion_token.clone();
|
||||
let (updated, refreshed) = tokio::task::spawn_blocking(move || {
|
||||
let mut refreshed = Vec::new();
|
||||
if let Some(maven) = &model.maven {
|
||||
for batch in snapshots {
|
||||
if cancel.is_cancelled() {
|
||||
break;
|
||||
}
|
||||
refreshed.extend(sources::refresh_snapshots(
|
||||
&batch.root,
|
||||
&maven.projects,
|
||||
&batch.repository,
|
||||
&batch.candidates,
|
||||
&bridge_profiles,
|
||||
&cancel,
|
||||
));
|
||||
}
|
||||
}
|
||||
(model, refreshed)
|
||||
})
|
||||
.await
|
||||
.map_err(join_err)?;
|
||||
model = updated;
|
||||
tokio::spawn(async move {
|
||||
refresh_library_archives(&lsp, &documents, &updates, refreshed).await;
|
||||
});
|
||||
}
|
||||
if completion_token.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
Ok(model)
|
||||
}
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
/// Open library classes whose jar was replaced in place (a SNAPSHOT installed
|
||||
/// again keeps its path) show the new contents, like a reopened one.
|
||||
async fn refresh_library_classes(lsp: &Arc<ide_lsp::LspManager>, documents: &Arc<ide_workspace::Documents>) {
|
||||
async fn update_java_projects(
|
||||
lsp: &ide_lsp::LspManager,
|
||||
updates: &[PathBuf],
|
||||
reconfigure: bool,
|
||||
wait: Option<&CancellationToken>,
|
||||
) {
|
||||
if reconfigure {
|
||||
// jdtls takes the profiles and offline mode from its Maven settings.
|
||||
lsp.reconfigure().await;
|
||||
}
|
||||
// JDT LS caches its classpath and re-imports on build-file changes. Ask it to
|
||||
// re-resolve dependencies even when the build files stayed the same (#436).
|
||||
if let Err(e) = lsp.java_update_project_configs(updates, wait).await {
|
||||
tracing::debug!("Updating Java project configurations: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-read open library classes whose binary or attached sources changed in place.
|
||||
async fn refresh_library_archives(
|
||||
lsp: &Arc<ide_lsp::LspManager>,
|
||||
documents: &Arc<ide_workspace::Documents>,
|
||||
updates: &[PathBuf],
|
||||
refreshed: Vec<PathBuf>,
|
||||
) {
|
||||
let changed = {
|
||||
let lsp = lsp.clone();
|
||||
tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default()
|
||||
};
|
||||
let archives: HashSet<_> = changed.into_iter().chain(refreshed).collect();
|
||||
if let Err(e) = lsp.java_refresh_archives(updates, &archives).await {
|
||||
tracing::debug!("openidea.java.refreshArchives: {e}");
|
||||
}
|
||||
let changed = {
|
||||
let (lsp, documents) = (lsp.clone(), documents.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
lsp.invalidate_library_archives(&archives);
|
||||
documents
|
||||
.open_documents()
|
||||
.into_iter()
|
||||
.filter_map(|doc| Some((doc, documents.virtual_uri(doc).ok().flatten()?)))
|
||||
.filter(|(_, uri)| lsp.library_class_changed(uri))
|
||||
.filter(|(_, uri)| {
|
||||
lsp.library_class_changed(uri)
|
||||
|| ide_lsp::LspManager::library_archive(uri).is_some_and(|archive| archives.contains(&archive))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.await
|
||||
@@ -906,6 +988,7 @@ pub async fn build_run(
|
||||
let detected = project.detected_roots.read().clone();
|
||||
let config_dir = host.config_dir.clone();
|
||||
let token = host.begin_project_request(window, request);
|
||||
let launch_project = project.clone();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
// Fast path (#2476): an unchanged single-project Maven build skips
|
||||
// Maven entirely. Previous diagnostics stay: nothing changed, so they
|
||||
@@ -951,16 +1034,18 @@ pub async fn build_run(
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
let mut launch_caches = Vec::new();
|
||||
let plan = if let Some(id) = cmake {
|
||||
launch_caches.push(cache.clone());
|
||||
let configs = super::run::project_configs(&root, &settings, &config_dir)?;
|
||||
cmake_plan(&root, kind, &configs, &id)?
|
||||
} else if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
|
||||
let mut combined: Option<compile::BuildPlan> = None;
|
||||
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
|
||||
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
|
||||
let member_cache =
|
||||
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
|
||||
let member_cache = workspace::cache_at(&root, &cache, member);
|
||||
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
|
||||
launch_caches.push(member_cache);
|
||||
let plan = prepare_plan(
|
||||
compile::plan(
|
||||
member,
|
||||
@@ -984,6 +1069,7 @@ pub async fn build_run(
|
||||
plan
|
||||
} else {
|
||||
let model = with_profiles(load(&root, &cache, &settings), &cache);
|
||||
launch_caches.push(cache.clone());
|
||||
match compile::plan(
|
||||
&root,
|
||||
&model,
|
||||
@@ -1003,7 +1089,14 @@ pub async fn build_run(
|
||||
};
|
||||
let result = compile::run(&root, &plan, &token, &|e| {
|
||||
let _ = on_event.send(e);
|
||||
})?;
|
||||
});
|
||||
if kind == BuildKind::Rebuild {
|
||||
// The clean removed outputs that earlier launch snapshots still hold.
|
||||
for cache in launch_caches {
|
||||
launch_project.java_launches.for_cache(&cache).snapshots.lock().forget_reusable_snapshots();
|
||||
}
|
||||
}
|
||||
let result = result?;
|
||||
if result.success && single && kind == BuildKind::Build {
|
||||
let model = with_profiles(load(&root, &cache, &settings), &cache);
|
||||
compile::record_menu_build(&cache, &root, &model, file.as_deref(), &token);
|
||||
@@ -1353,17 +1446,8 @@ mod maven_completion_tests {
|
||||
let path = root.join("pom.xml");
|
||||
std::fs::write(&path, text).unwrap();
|
||||
|
||||
let host = Host::new(crate::HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("local"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(|_| {})),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
let host =
|
||||
Host::new(crate::HostConfig { local_data_dir: base.join("local"), ..crate::HostConfig::for_test(&base) });
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
let info = project.documents.open(&path).unwrap();
|
||||
|
||||
|
||||
@@ -1,12 +1,33 @@
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(super) struct Scope {
|
||||
pub(in crate::ops) struct Scope {
|
||||
pub root: PathBuf,
|
||||
pub cache: PathBuf,
|
||||
pub settings: Settings,
|
||||
}
|
||||
|
||||
pub(in crate::ops) fn scope_for(project: &Project, path: &Path) -> IdeResult<Scope> {
|
||||
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
|
||||
let root = workspace
|
||||
.as_ref()
|
||||
.and_then(|w| w.projects.iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count()))
|
||||
.unwrap_or(&project.root);
|
||||
Ok(Scope {
|
||||
cache: cache_at(&project.root, &project.build_cache_dir(), root),
|
||||
settings: if root == &project.root {
|
||||
project.settings.effective()
|
||||
} else {
|
||||
project.settings.for_project(root).effective()
|
||||
},
|
||||
root: root.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn cache_at(window_root: &Path, cache: &Path, root: &Path) -> PathBuf {
|
||||
if root == window_root { cache.to_owned() } else { cache.join(crate::project::project_key(root)) }
|
||||
}
|
||||
|
||||
pub(super) fn scopes(project: &Project, config: &Path) -> IdeResult<Vec<Scope>> {
|
||||
scopes_at(&project.root, &project.build_cache_dir(), config, project.settings.effective())
|
||||
}
|
||||
@@ -19,11 +40,7 @@ fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> Id
|
||||
.into_iter()
|
||||
.filter(|p| p.is_dir())
|
||||
.map(|root| Scope {
|
||||
cache: if root == window_root {
|
||||
cache.to_owned()
|
||||
} else {
|
||||
cache.join(crate::project::project_key(&root))
|
||||
},
|
||||
cache: cache_at(window_root, cache, &root),
|
||||
settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(),
|
||||
root,
|
||||
})
|
||||
|
||||
+152
-24
@@ -2,13 +2,14 @@
|
||||
//! remote server ([`crate::rpc`]). `db_export_file` stays in the desktop
|
||||
//! shell: its path comes from a local save dialog, so the export must land
|
||||
//! on the user's machine, not the side the project runs on.
|
||||
use super::Channel;
|
||||
use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
|
||||
use ide_db::split::SqlStatement;
|
||||
use ide_db::{
|
||||
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, HistoryEntry, PlanNode, QueryResult,
|
||||
SchemaObjects, SortKey, TableDetails, TableInfo, TablePage,
|
||||
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbVisibilityChange, HistoryEntry, PlanNode,
|
||||
QueryResult, SchemaObjects, SortKey, TableDetails, TableInfo, TablePage,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -24,6 +25,14 @@ pub struct StatementOutcome {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum ExecutionEvent {
|
||||
Started { index: u32 },
|
||||
Completed { index: u32, outcome: StatementOutcome },
|
||||
Done { error: Option<IdeError> },
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub fn db_approve_jdbc_source(host: &Host, window: &str, source: DataSource) -> IdeResult<()> {
|
||||
host.project(window)?.db.approve_jdbc_source(&source)
|
||||
@@ -63,6 +72,25 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
|
||||
// Replaces the project's data sources with `sources`.
|
||||
let db = host.project(window)?.db.clone();
|
||||
db.save_sources(sources).await?;
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_save_source_visibility(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
available: Vec<String>,
|
||||
change: DbVisibilityChange,
|
||||
) -> IdeResult<()> {
|
||||
let db = host.project(window)?.db.clone();
|
||||
tokio::task::spawn_blocking(move || db.save_source_visibility(&id, &available, change))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
sources_changed(host, window)
|
||||
}
|
||||
|
||||
fn sources_changed(host: &Host, window: &str) -> IdeResult<()> {
|
||||
let root = host.project(window)?.root.clone();
|
||||
for project in host.projects().into_iter().filter(|p| p.root == root) {
|
||||
project.sink.emit(ide_core::IdeEvent::DbSourcesChanged);
|
||||
@@ -357,36 +385,79 @@ pub async fn db_execute(
|
||||
max_rows: u32,
|
||||
schema: Option<String>,
|
||||
) -> IdeResult<Vec<StatementOutcome>> {
|
||||
// Runs `statements` in order on data source `id`, stopping at the first
|
||||
// error. Each result reads past its first `skip` rows (a later page) and keeps
|
||||
// `max_rows`. `schema` is the console's active context: the connection running
|
||||
// each statement is put in it first. Cancel with `cancel_request(request)`.
|
||||
let mut outcomes = Vec::new();
|
||||
execute_statements(host, window, request, &id, statements, skip, max_rows, schema.as_deref(), |event| {
|
||||
if let ExecutionEvent::Completed { outcome, .. } = event {
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
Ok(outcomes)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn db_execute_stream(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
id: String,
|
||||
statements: Vec<SqlStatement>,
|
||||
max_rows: u32,
|
||||
schema: Option<String>,
|
||||
on_progress: Channel<ExecutionEvent>,
|
||||
) -> IdeResult<()> {
|
||||
let result = execute_statements(host, window, request, &id, statements, 0, max_rows, schema.as_deref(), |event| {
|
||||
on_progress.send(event)
|
||||
})
|
||||
.await;
|
||||
// The invocation reply can reach the viewer before a large result frame.
|
||||
on_progress.send(ExecutionEvent::Done { error: result.err() })
|
||||
}
|
||||
|
||||
/// Runs in order on one request and stops on cancellation or the first error.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn execute_statements(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
request: RequestId,
|
||||
id: &str,
|
||||
statements: Vec<SqlStatement>,
|
||||
skip: u32,
|
||||
max_rows: u32,
|
||||
schema: Option<&str>,
|
||||
mut emit: impl FnMut(ExecutionEvent) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
let db = host.project(window)?.db.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let mut out = Vec::new();
|
||||
for statement in statements {
|
||||
match db
|
||||
.execute_from(&id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel, schema.as_deref())
|
||||
.await
|
||||
{
|
||||
Ok(result) => out.push(StatementOutcome { statement, result: Some(result), error: None }),
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => {
|
||||
host.end_request(request);
|
||||
return Err(e);
|
||||
let result = async {
|
||||
for (index, statement) in statements.into_iter().enumerate() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::PermissionDenied && out.is_empty() => {
|
||||
// Not connected for lack of a password: the UI asks and retries.
|
||||
host.end_request(request);
|
||||
return Err(e);
|
||||
}
|
||||
Err(e) => {
|
||||
out.push(StatementOutcome { statement, result: None, error: Some(e.message) });
|
||||
emit(ExecutionEvent::Started { index: index as u32 })?;
|
||||
let outcome = match db
|
||||
.execute_from(id, &statement.text, skip as usize, max_rows.max(1) as usize, &cancel, schema)
|
||||
.await
|
||||
{
|
||||
Ok(result) => StatementOutcome { statement, result: Some(result), error: None },
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => return Err(e),
|
||||
// The UI may retry a login failure only before any statement has completed.
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::PermissionDenied && index == 0 => return Err(e),
|
||||
Err(e) => StatementOutcome { statement, result: None, error: Some(e.message) },
|
||||
};
|
||||
let failed = outcome.error.is_some();
|
||||
emit(ExecutionEvent::Completed { index: index as u32, outcome })?;
|
||||
if failed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
host.end_request(request);
|
||||
Ok(out)
|
||||
result
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -539,6 +610,7 @@ ide_command::domain!(
|
||||
db_disconnect,
|
||||
db_drop_database,
|
||||
db_execute,
|
||||
db_execute_stream,
|
||||
db_explain,
|
||||
db_finish_transaction,
|
||||
db_history,
|
||||
@@ -550,6 +622,7 @@ ide_command::domain!(
|
||||
db_object_ddl,
|
||||
db_remove_history,
|
||||
db_retain_catalog,
|
||||
db_save_source_visibility,
|
||||
db_save_sources,
|
||||
db_saved_catalog,
|
||||
db_schema_objects,
|
||||
@@ -567,3 +640,58 @@ ide_command::domain!(
|
||||
db_test_tunnel,
|
||||
db_trust_ssh_host,
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::HostConfig;
|
||||
use ide_db::DbDriver;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn a_reporting_error_stops_the_batch_and_releases_the_request() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
|
||||
let window = "main";
|
||||
host.open_project(window, &root).unwrap();
|
||||
host.set_project_trust(&root, true, false).await.unwrap();
|
||||
let id = "test";
|
||||
let file = root.join("test.sqlite");
|
||||
std::fs::File::create(&file).unwrap();
|
||||
db_save_sources(
|
||||
&host,
|
||||
window,
|
||||
vec![DataSource { id: id.into(), name: id.into(), file: Some(file.into()), ..Default::default() }],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let statements =
|
||||
ide_db::split::split("CREATE TABLE items (n INTEGER); INSERT INTO items VALUES (1);", DbDriver::Sqlite);
|
||||
let request = RequestId(1);
|
||||
let error = execute_statements(&host, window, request, id, statements, 0, 10, None, |event| match event {
|
||||
ExecutionEvent::Started { index: 0 } => Ok(()),
|
||||
ExecutionEvent::Completed { index: 0, outcome } => {
|
||||
assert!(outcome.error.is_none(), "{:?}", outcome.error);
|
||||
Err(IdeError::internal("cannot report result"))
|
||||
}
|
||||
_ => panic!("the failed callback must stop execution"),
|
||||
})
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.message, "cannot report result");
|
||||
|
||||
// After cleanup, cancel is remembered for the next request with this id.
|
||||
host.cancel_request(request);
|
||||
assert!(host.begin_request(request).is_cancelled());
|
||||
|
||||
let query = ide_db::split::split(
|
||||
"SELECT 99 AS n UNION ALL SELECT count(*) FROM items ORDER BY n DESC",
|
||||
DbDriver::Sqlite,
|
||||
);
|
||||
let outcomes = db_execute(&host, window, RequestId(2), id.into(), query, 1, 10, None).await.unwrap();
|
||||
assert_eq!(outcomes[0].result.as_ref().unwrap().rows, vec![vec![Some("0".into())]]);
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,15 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
&& config.request == "launch"
|
||||
&& let Ok(project) = host.project(window)
|
||||
{
|
||||
super::python::prepare_debug(&mut config, &super::python::paths(&project))?;
|
||||
let python = super::python::debug_python(&config);
|
||||
let paths = super::python::with_user_paths(
|
||||
super::python::paths(&project),
|
||||
&host.config_dir,
|
||||
&project,
|
||||
python.as_deref(),
|
||||
config.cwd.as_deref(),
|
||||
);
|
||||
super::python::prepare_debug(&mut config, &paths)?;
|
||||
}
|
||||
let label = window;
|
||||
let (sink, flush_output) = output::coalescing_sink(host.window_sink(label));
|
||||
@@ -129,7 +137,8 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
};
|
||||
host.require_trust(window)?;
|
||||
let server_port = debug_server_port(&config);
|
||||
let result = host.debugger.start_with(config, owner, custom).await;
|
||||
let exception_classes = server_port.and_then(|port| exception_class_backend(host, window, port));
|
||||
let result = host.debugger.start_with_exception_classes(config, owner, custom, exception_classes).await;
|
||||
flush_output();
|
||||
if let Ok(id) = &result {
|
||||
let sink = host.window_sink(label);
|
||||
@@ -208,6 +217,18 @@ fn attach_jvm_inspector(host: &Host, window: &str, session: DebugSessionId, port
|
||||
}
|
||||
}
|
||||
|
||||
/// Given before the session starts, unlike the inspector: the breakpoints are armed before
|
||||
/// `configurationDone`, so a throw in `main`'s first line stops.
|
||||
fn exception_class_backend(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
port: u16,
|
||||
) -> Option<std::sync::Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>> {
|
||||
let project = host.project(window).ok()?;
|
||||
let module = project.lsp.java_debug_server_module(port)?;
|
||||
Some(std::sync::Arc::new(ide_lsp::JdtExceptionBreakpoints::new(project.lsp.clone(), module)))
|
||||
}
|
||||
|
||||
/// A JVM the debugger starts itself: an Application or Spring Boot configuration, launched by
|
||||
/// java-debug, java-analyzer or the Kotlin debugger (JAR Application debugs through a run with a
|
||||
/// JDWP agent).
|
||||
@@ -453,6 +474,16 @@ pub async fn debug_set_exception_breakpoints(
|
||||
host.debugger.set_exception_breakpoints(choices).await
|
||||
}
|
||||
|
||||
/// Exception breakpoints on chosen classes (all sessions that take them, and later ones).
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_exception_class_breakpoints(
|
||||
host: &Host,
|
||||
breakpoints: Vec<ExceptionClassBreakpoint>,
|
||||
) -> IdeResult<()> {
|
||||
host.debugger.set_exception_class_breakpoints(breakpoints).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_set_variable(
|
||||
@@ -849,6 +880,7 @@ ide_command::domain!(
|
||||
debug_set_breakpoints,
|
||||
debug_set_data_breakpoints,
|
||||
debug_set_exception_breakpoints,
|
||||
debug_set_exception_class_breakpoints,
|
||||
debug_set_function_breakpoints,
|
||||
debug_set_variable,
|
||||
debug_stack_trace,
|
||||
|
||||
Loaded 100 of 2097 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user