дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 14:22:34 +02:00
Порівняти коміти
571
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
468118df57 | ||
|
|
88a6bbca14 | ||
|
|
b9e555300f | ||
|
|
7ff223001b | ||
|
|
cc9279a6d6 | ||
|
|
1cfbb24b31 | ||
|
|
a8a0cdb315 | ||
|
|
8ab776ada6 | ||
|
|
88b463d888 | ||
|
|
ac88059d0f | ||
|
|
a09c9aa9ad | ||
|
|
7fef1e10a8 | ||
|
|
1748c98ac8 | ||
|
|
399ae25ab6 | ||
|
|
f28dd8125b | ||
|
|
d5f7e0a99b | ||
|
|
a66c9e6d05 | ||
|
|
59bcf7eac5 | ||
|
|
fe21c67537 | ||
|
|
c085f52b59 | ||
|
|
0104ed63c1 | ||
|
|
a441b2a906 | ||
|
|
c4f7fec86c | ||
|
|
37a8aae018 | ||
|
|
acc48a4816 | ||
|
|
8301326289 | ||
|
|
4c71299745 | ||
|
|
08249ca5fd | ||
|
|
edd6746439 | ||
|
|
695424beb2 | ||
|
|
9943d71d02 | ||
|
|
e03c5507f7 | ||
|
|
745099feaa | ||
|
|
6894d0a4e3 | ||
|
|
f80be658ea | ||
|
|
1c377b7f66 | ||
|
|
093cf6fdf8 | ||
|
|
9b578c2fad | ||
|
|
f5bb97babd | ||
|
|
e23088d558 | ||
|
|
7279f515db | ||
|
|
710d120689 | ||
|
|
38709947fe | ||
|
|
d9fbb19787 | ||
|
|
6aa613d4ec | ||
|
|
60ef498deb | ||
|
|
719b73ecd9 | ||
|
|
6c3284c300 | ||
|
|
69cec11761 | ||
|
|
6c76cfd316 | ||
|
|
66496221b9 | ||
|
|
e9f3aef5ae | ||
|
|
4ca46032c4 | ||
|
|
8d8f66dfe5 | ||
|
|
5229e44a9c | ||
|
|
7be55e4eec | ||
|
|
ce206f74af | ||
|
|
3c6bc1b29f | ||
|
|
f9a8ad3fa7 | ||
|
|
3d3ed6e120 | ||
|
|
61dbb2f863 | ||
|
|
79e5ddda3e | ||
|
|
53cc0059a4 | ||
|
|
6c945c73ad | ||
|
|
51b93d25bd | ||
|
|
c0b5789dd6 | ||
|
|
016240ac1b | ||
|
|
97598641be | ||
|
|
f220ceb117 | ||
|
|
263c95738e | ||
|
|
3a07f05a75 | ||
|
|
81d0ada2f3 | ||
|
|
04bea8718e | ||
|
|
7f32d04b19 | ||
|
|
4a714b2eff | ||
|
|
83b273ec4c | ||
|
|
37e2e250e9 | ||
|
|
16c2613cc0 | ||
|
|
e40a03c373 | ||
|
|
cf6d8fa510 | ||
|
|
73ee2117e9 | ||
|
|
1ec634619c | ||
|
|
18860f5f98 | ||
|
|
8e9c02cae6 | ||
|
|
28b879c668 | ||
|
|
19aef36354 | ||
|
|
c8efb2917d | ||
|
|
94ddb1807d | ||
|
|
27447d21a7 | ||
|
|
3edbcc0dcd | ||
|
|
782a0a98e3 | ||
|
|
bd0455bda5 | ||
|
|
13cd8ba006 | ||
|
|
9b413fde11 | ||
|
|
29e5571186 | ||
|
|
08eb9e3ff9 | ||
|
|
3d6ad2e254 | ||
|
|
55b23c90b8 | ||
|
|
3fb58cf69b | ||
|
|
3b6ee66b74 | ||
|
|
243b9ffa7a | ||
|
|
86fabc7d1b | ||
|
|
ae3405486f | ||
|
|
dfea6d2c1e | ||
|
|
b9a25462ea | ||
|
|
04e68f6a12 | ||
|
|
4cfc794f60 | ||
|
|
8105dfd41a | ||
|
|
fca497d246 | ||
|
|
5cb73c5fd1 | ||
|
|
2b435c8440 | ||
|
|
db266643aa | ||
|
|
4812d28614 | ||
|
|
7c9f343ca4 | ||
|
|
d815a8ef44 | ||
|
|
d22c42e471 | ||
|
|
a111b32e11 | ||
|
|
f7141f6515 | ||
|
|
2d14368d2c | ||
|
|
5cbc4134a1 | ||
|
|
5a92145ad9 | ||
|
|
4354839584 | ||
|
|
e1a1becadd | ||
|
|
ad685ea19e | ||
|
|
5fb8f21c60 | ||
|
|
68abe345cc | ||
|
|
32381cc740 | ||
|
|
d897236bd7 | ||
|
|
68e3adde99 | ||
|
|
b5aa21e791 | ||
|
|
652798bc53 | ||
|
|
85e417001a | ||
|
|
8488eda54e | ||
|
|
d02a3592b0 | ||
|
|
439b7940a8 | ||
|
|
de92f3b367 | ||
|
|
5b904f7896 | ||
|
|
511d3f21bb | ||
|
|
972f18331e | ||
|
|
77e669c189 | ||
|
|
f2641b9697 | ||
|
|
3811dfb512 | ||
|
|
9e2da77162 | ||
|
|
3a89b94624 | ||
|
|
df40f0befe | ||
|
|
f151498e07 | ||
|
|
d959a2a583 | ||
|
|
7ab456b1e7 | ||
|
|
f8a9b204c6 | ||
|
|
be7a0cfa5b | ||
|
|
f40b645c8e | ||
|
|
e4ec1978d8 | ||
|
|
10242d2e58 | ||
|
|
fad9135f7a | ||
|
|
703b19b526 | ||
|
|
c3de09be78 | ||
|
|
6b61b15f00 | ||
|
|
19948c1426 | ||
|
|
e30ae3f6b8 | ||
|
|
9ee8f67e9f | ||
|
|
5b486f1588 | ||
|
|
6f8e8501c6 | ||
|
|
27c7323c0b | ||
|
|
41cb8f993e | ||
|
|
6e37a1a977 | ||
|
|
e99fcb0c49 | ||
|
|
2f31544d04 | ||
|
|
cbcd84f1d2 | ||
|
|
a3a56ab10d | ||
|
|
3961f38f46 | ||
|
|
4c5f4fa1e1 | ||
|
|
90734775b9 | ||
|
|
b53915e4b6 | ||
|
|
d361d7239a | ||
|
|
77a03ac197 | ||
|
|
f28a11d043 | ||
|
|
cdb4f9ab15 | ||
|
|
c709844c04 | ||
|
|
2cce84ad2c | ||
|
|
91dcd1b7eb | ||
|
|
3d275d5a3d | ||
|
|
cc49827793 | ||
|
|
7b3813f9e2 | ||
|
|
ebc6dc86f1 | ||
|
|
0ae1628678 | ||
|
|
dc8c45c77c | ||
|
|
e5f93b8526 | ||
|
|
73ba36381c | ||
|
|
3bc75e1de0 | ||
|
|
633bef2e69 | ||
|
|
9aa0718cf9 | ||
|
|
836a4405d6 | ||
|
|
952bd0b24b | ||
|
|
ac5e4b7259 | ||
|
|
2ea7d6c41b | ||
|
|
16e5cb5763 | ||
|
|
611440f77f | ||
|
|
482143769f | ||
|
|
176859987b | ||
|
|
6cdd52d31a | ||
|
|
90a0fd9901 | ||
|
|
9d92f47f94 | ||
|
|
68abd00a7f | ||
|
|
4c01ce4443 | ||
|
|
9da53322bc | ||
|
|
720b18861c | ||
|
|
802d9d26e2 | ||
|
|
fb97cdac03 | ||
|
|
caf909cab3 | ||
|
|
c88a4f403f | ||
|
|
98f163da75 | ||
|
|
5952e36d8b | ||
|
|
ad56613901 | ||
|
|
3fae4c0417 | ||
|
|
99fdea5c9a | ||
|
|
8aeac949b5 | ||
|
|
fa625d8cc7 | ||
|
|
b7b5bd5c50 | ||
|
|
2174a7278a | ||
|
|
7bbc12382e | ||
|
|
4fb1cae917 | ||
|
|
23bbed8bfe | ||
|
|
1880ac541c | ||
|
|
d698b50361 | ||
|
|
d5ba63e333 | ||
|
|
8108b440a6 | ||
|
|
4401ed3119 | ||
|
|
dbbdc4a085 | ||
|
|
85456e6930 | ||
|
|
b4d2859277 | ||
|
|
ba880dac06 | ||
|
|
0b1a675fab | ||
|
|
0b06d3313f | ||
|
|
ddaee1f5ce | ||
|
|
623f1fa4e7 | ||
|
|
79f6476d52 | ||
|
|
bd396485c2 | ||
|
|
c04d9381be | ||
|
|
45f6366b92 | ||
|
|
fb0b2d6a5f | ||
|
|
ddea7e5ec5 | ||
|
|
3747a8a63f | ||
|
|
0a8fea1876 | ||
|
|
ccc0eb1f54 | ||
|
|
54dadc4605 | ||
|
|
6fba4671e6 | ||
|
|
d5058b930b | ||
|
|
44aab11296 | ||
|
|
fcd24885c1 | ||
|
|
4b3717618f | ||
|
|
8fd5ee382d | ||
|
|
3a3b2e424a | ||
|
|
b9d0e28f7a | ||
|
|
53627ea2e9 | ||
|
|
55366a2a31 | ||
|
|
0b9610fe69 | ||
|
|
43e3575eb2 | ||
|
|
bc4a422424 | ||
|
|
7ccaa10496 | ||
|
|
b5e45ca98b | ||
|
|
6faff1b1a8 | ||
|
|
1edfa9180b | ||
|
|
b15c56cdb0 | ||
|
|
91ff5c8a15 | ||
|
|
929b6837f9 | ||
|
|
d1af5f656a | ||
|
|
604e9348f2 | ||
|
|
9592b9ee1b | ||
|
|
c658b3eb88 | ||
|
|
cc5d9d95e4 | ||
|
|
75a15b7eed | ||
|
|
b2998cb37a | ||
|
|
5c131edb7e | ||
|
|
bb8906edb8 | ||
|
|
2e3b087db7 | ||
|
|
0c5f1ffabf | ||
|
|
0a9055b40d | ||
|
|
8776bf536f | ||
|
|
9cc781717d | ||
|
|
8f1e95e5a2 | ||
|
|
e49c634064 | ||
|
|
4e82599c49 | ||
|
|
e08de6771d | ||
|
|
d31a22b5dd | ||
|
|
cead5f08f7 | ||
|
|
1fc9a9f5d5 | ||
|
|
11a8152988 | ||
|
|
10b459268e | ||
|
|
382c22cfc3 | ||
|
|
7bb69e353d | ||
|
|
988f93be46 | ||
|
|
494dd61193 | ||
|
|
cbabb5e9b5 | ||
|
|
75997ae0ee | ||
|
|
81df8f2649 | ||
|
|
26992ec4ce | ||
|
|
2c22574be0 | ||
|
|
93368d4379 | ||
|
|
14741101bd | ||
|
|
db60deede5 | ||
|
|
ab2a7767c7 | ||
|
|
49c917880d | ||
|
|
f0db09aca5 | ||
|
|
979cce1175 | ||
|
|
faa7571038 | ||
|
|
264bf6969f | ||
|
|
66e17df216 | ||
|
|
4ff5739854 | ||
|
|
a0c03447a0 | ||
|
|
c4e0900485 | ||
|
|
a42f13edc2 | ||
|
|
18d6041f2f | ||
|
|
15c5e921df | ||
|
|
bc64188c38 | ||
|
|
a3c819e064 | ||
|
|
1f2e92b433 | ||
|
|
8dfca955a5 | ||
|
|
91aba61c97 | ||
|
|
1fb4135b5b | ||
|
|
24598e0dae | ||
|
|
2436ad6fe9 | ||
|
|
c2c6931f0e | ||
|
|
2e0c8dd527 | ||
|
|
f4be752dda | ||
|
|
a52a639b8e | ||
|
|
1b0bf4d741 | ||
|
|
13597e40a1 | ||
|
|
aa1aa91b0d | ||
|
|
032a3b0453 | ||
|
|
07750ad984 | ||
|
|
ba38f070d9 | ||
|
|
c77f4db777 | ||
|
|
d3067c8d3a | ||
|
|
7bf2702565 | ||
|
|
65c45ffe05 | ||
|
|
84b528f0cd | ||
|
|
8621764813 | ||
|
|
22e1c4b927 | ||
|
|
e2817656e8 | ||
|
|
306c71290c | ||
|
|
51ccb68b72 | ||
|
|
2e965810e9 | ||
|
|
31b70cf0ac | ||
|
|
d0989e2a4b | ||
|
|
d96ed8d154 | ||
|
|
6b41870368 | ||
|
|
660becbaa4 | ||
|
|
a0afc478c1 | ||
|
|
07a88c6fa4 | ||
|
|
46bd6fad3c | ||
|
|
f64dbe65b4 | ||
|
|
e2a5a5db81 | ||
|
|
6eb7abff9f | ||
|
|
b46112fe0b | ||
|
|
4507dc172d | ||
|
|
8442c0c339 | ||
|
|
8ffe3bd230 | ||
|
|
1babff55fc | ||
|
|
2ad95150eb | ||
|
|
fe3e647abb | ||
|
|
62cc6768fe | ||
|
|
2e93422270 | ||
|
|
3a1353cc0e | ||
|
|
c5eab0a4a3 | ||
|
|
581c8cf025 | ||
|
|
807c447792 | ||
|
|
217693a56f | ||
|
|
557295b1df | ||
|
|
7c674e70e5 | ||
|
|
1602a5d010 | ||
|
|
a6d135d66f | ||
|
|
924bf6d3b9 | ||
|
|
318c227b0c | ||
|
|
2ce7621abb | ||
|
|
7ecccb3b75 | ||
|
|
7cbf17b10e | ||
|
|
cb0d02620d | ||
|
|
d6ca43cba4 | ||
|
|
165d4f7d76 | ||
|
|
5785ebadd8 | ||
|
|
0c67a4eea2 | ||
|
|
5e2deed81e | ||
|
|
cae7c05fb1 | ||
|
|
be83458161 | ||
|
|
661124d0d4 | ||
|
|
0dae111b2d | ||
|
|
61d269045b | ||
|
|
266d85fa1a | ||
|
|
f964d79e10 | ||
|
|
4a3eacff62 | ||
|
|
aebc2fe02d | ||
|
|
9b63aa9526 | ||
|
|
df07073886 | ||
|
|
3433ee951b | ||
|
|
8f5b281486 | ||
|
|
43aee8058c | ||
|
|
4016c3c905 | ||
|
|
e6cb7df653 | ||
|
|
2a26c82357 | ||
|
|
66f0bce92f | ||
|
|
dfbd13e2af | ||
|
|
944b57dead | ||
|
|
5bcb37492f | ||
|
|
d5bde9af67 | ||
|
|
5b3e2b7a3d | ||
|
|
dbb6fa51c3 | ||
|
|
3d1769ef00 | ||
|
|
c966429f92 | ||
|
|
dfcc05dd41 | ||
|
|
d41feefc07 | ||
|
|
f0fe910017 | ||
|
|
b932220b41 | ||
|
|
bcad8f61cb | ||
|
|
2cdcb888cf | ||
|
|
9ed0fd9fa7 | ||
|
|
fe76dc4573 | ||
|
|
45a75f782a | ||
|
|
bd1fd011e4 | ||
|
|
b44015b2ce | ||
|
|
0cce0a9840 | ||
|
|
db8224f74e | ||
|
|
b075f5de2a | ||
|
|
3240164840 | ||
|
|
f70f362a3d | ||
|
|
806bb4c78d | ||
|
|
57094bc285 | ||
|
|
a5e0c41663 | ||
|
|
77071238a0 | ||
|
|
64097d3c20 | ||
|
|
cf0e57e5df | ||
|
|
703cf23296 | ||
|
|
a88073d6fb | ||
|
|
4b5745c1b6 | ||
|
|
4667c81e6b | ||
|
|
cea9d863f9 | ||
|
|
5fa953eddd | ||
|
|
031f1acd07 | ||
|
|
add23fe97f | ||
|
|
3d2b0946de | ||
|
|
6c7282b442 | ||
|
|
1f79a7f805 | ||
|
|
3d1eaf71e4 | ||
|
|
138209c627 | ||
|
|
b283d352b7 | ||
|
|
f7f9dabe2b | ||
|
|
787d4fbcfa | ||
|
|
3fbd0e05a5 | ||
|
|
2d021a3414 | ||
|
|
cd7582c5e5 | ||
|
|
d16b852054 | ||
|
|
06223d9bd7 | ||
|
|
dcd81d601b | ||
|
|
762ebecd86 | ||
|
|
fd4efff6e3 | ||
|
|
8968974f42 | ||
|
|
5f083ae47c | ||
|
|
83b14b4329 | ||
|
|
74eefd6116 | ||
|
|
a96c70f2a7 | ||
|
|
304503b9f1 | ||
|
|
06cf8fb16a | ||
|
|
521e00d075 | ||
|
|
b4cad6ec1b | ||
|
|
62e26fa7e3 | ||
|
|
1119467ab4 | ||
|
|
e1ce850a29 | ||
|
|
3e39368d43 | ||
|
|
b2a5ea1594 | ||
|
|
902d8ca257 | ||
|
|
92b5b5306f | ||
|
|
707cee9b0b | ||
|
|
d64be035c6 | ||
|
|
cb60c742fc | ||
|
|
b245335cc6 | ||
|
|
e13ed093ec | ||
|
|
aa0f8105af | ||
|
|
0adc816a56 | ||
|
|
ea29339b6b | ||
|
|
84854bed0e | ||
|
|
81b6cb7af6 | ||
|
|
ffe96c2ca2 | ||
|
|
33bd5372b6 | ||
|
|
44aeb95993 | ||
|
|
fa6b4be6f5 | ||
|
|
144cd90175 | ||
|
|
da3b621345 | ||
|
|
b301e2bbe1 | ||
|
|
feac919a1b | ||
|
|
0155d74084 | ||
|
|
130f75e7e8 | ||
|
|
2abd65aedd | ||
|
|
1b3e4fac6a | ||
|
|
72b0c7c48c | ||
|
|
25d1046af0 | ||
|
|
1cdb998532 | ||
|
|
b1ab5afa67 | ||
|
|
0101d11ac9 | ||
|
|
07d26722b1 | ||
|
|
df48d9271b | ||
|
|
cb6b7ccd3f | ||
|
|
13c0e8aa8d | ||
|
|
9f643af069 | ||
|
|
0c02a9e467 | ||
|
|
8c7bdc9bf2 | ||
|
|
a3f6d82391 | ||
|
|
bfde0ffc34 | ||
|
|
9067abf0cf | ||
|
|
4939b63c88 | ||
|
|
78d34af971 | ||
|
|
d47c9eb347 | ||
|
|
5348e42c59 | ||
|
|
a42eee29f4 | ||
|
|
a3e7142e4c | ||
|
|
d21fd65341 | ||
|
|
422f424b60 | ||
|
|
c10862b1a6 | ||
|
|
d4db49689e | ||
|
|
36ab40797c | ||
|
|
de7d62dce8 | ||
|
|
e3f9049e26 | ||
|
|
3e9f018cf4 | ||
|
|
e44d7fd396 | ||
|
|
dc490f1017 | ||
|
|
5289f44620 | ||
|
|
81aac31cc7 | ||
|
|
026163af9e | ||
|
|
ce03ae7c0f | ||
|
|
1cd8e8def5 | ||
|
|
a0b9fba2f2 | ||
|
|
1f6a3bbf0d | ||
|
|
5265455313 | ||
|
|
64cc72ba2e | ||
|
|
b79dbae83f | ||
|
|
e909c50fe4 | ||
|
|
da7125a944 | ||
|
|
e54e309d61 | ||
|
|
8c3371212c | ||
|
|
e08531c458 | ||
|
|
9c9e0e59cb | ||
|
|
1d5d33cf76 | ||
|
|
2bbba9b945 | ||
|
|
14f143b703 | ||
|
|
f2a372428c | ||
|
|
89524bd583 | ||
|
|
f90d94538d | ||
|
|
a4ad387085 | ||
|
|
f8a148c06d | ||
|
|
aa1a027162 | ||
|
|
b30716e22c | ||
|
|
7fb21003f3 | ||
|
|
ad8d32d9c7 | ||
|
|
08aef06844 | ||
|
|
3d5ec8a147 | ||
|
|
0f14314156 | ||
|
|
2413cc4b43 | ||
|
|
30291971e1 | ||
|
|
9f3d75976f | ||
|
|
72d9aad715 | ||
|
|
7264e7d66d | ||
|
|
10379a54f7 | ||
|
|
6564b9e6cb | ||
|
|
d437cd46f5 | ||
|
|
925d474274 | ||
|
|
89463afc18 | ||
|
|
c884aa4cc6 | ||
|
|
09108e02e3 | ||
|
|
2b6ca90457 | ||
|
|
3c3681ef2b | ||
|
|
b0d7bfef24 | ||
|
|
527add030a | ||
|
|
81c2fc9ace |
No files matched your search
@@ -0,0 +1,13 @@
|
||||
# Nextest runs tests in separate processes. These three tests write the same Windows clipboard.
|
||||
[test-groups.windows-clipboard]
|
||||
max-threads = 1
|
||||
|
||||
[[profile.default.overrides]]
|
||||
filter = '''
|
||||
package(=ide-clipboard) & (
|
||||
test(=tests::text_reads_on_one_thread_do_not_corrupt_the_heap)
|
||||
| test(=tests::text_reads_taking_turns_do_not_corrupt_the_heap)
|
||||
| test(=tests::concurrent_text_reads_do_not_corrupt_the_heap)
|
||||
)
|
||||
'''
|
||||
test-group = "windows-clipboard"
|
||||
@@ -0,0 +1,9 @@
|
||||
# Keeps the commit SHAs the workflows pin their actions to current (the trailing comment names
|
||||
# the release each SHA comes from).
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule: { interval: weekly }
|
||||
groups:
|
||||
actions: { patterns: ["*"] }
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
cancel:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v8
|
||||
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
script: |
|
||||
// A merged or closed PR's remaining CI only holds runners other PRs wait for.
|
||||
|
||||
@@ -106,7 +106,8 @@ jobs:
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
permissions:
|
||||
contents: read
|
||||
timeout-minutes: 60
|
||||
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run.
|
||||
timeout-minutes: ${{ matrix.os == 'windows-latest' && 75 || 60 }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -115,22 +116,24 @@ jobs:
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
with: { components: "clippy, rustfmt" }
|
||||
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
|
||||
# (only main saves it because saving takes minutes on Windows; PRs restore main's).
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
# A failing test run on main still saves it, so the next PR doesn't compile from scratch.
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
cache-on-failure: true
|
||||
# The persistent target dir makes incremental builds pay off; cap its size so it can't fill the disk.
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
@@ -142,7 +145,8 @@ jobs:
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
rm -rf "$CARGO_TARGET_DIR"
|
||||
fi
|
||||
- uses: taiki-e/install-action@nextest
|
||||
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with: { tool: nextest }
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
@@ -156,6 +160,47 @@ jobs:
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- name: Restore Maven artifacts for Java build tests
|
||||
id: jbuild-maven-cache
|
||||
if: runner.environment == 'github-hosted'
|
||||
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: jbuild-maven-v2-${{ runner.os }}-${{ hashFiles('crates/ide-build/tests/fixtures/jbuild-maven/**/pom.xml') }}
|
||||
- name: Prepare Maven artifacts for Java build tests
|
||||
id: jbuild-maven
|
||||
if: runner.environment == 'github-hosted'
|
||||
timeout-minutes: 5
|
||||
shell: bash
|
||||
env:
|
||||
CACHE_HIT: ${{ steps.jbuild-maven-cache.outputs.cache-hit }}
|
||||
run: |
|
||||
if [[ -z "${JAVA_HOME:-}" || ! -d "$JAVA_HOME/bin" ]] || ! command -v mvn >/dev/null; then
|
||||
exit 0
|
||||
fi
|
||||
export MAVEN_OPTS="${MAVEN_OPTS:+$MAVEN_OPTS }-Dmaven.repo.local=$RUNNER_TEMP/jbuild-maven-repository"
|
||||
echo "MAVEN_OPTS=$MAVEN_OPTS" >> "$GITHUB_ENV"
|
||||
if [[ "$CACHE_HIT" == true ]]; then
|
||||
exit 0
|
||||
fi
|
||||
# The Java tests read the compiler descriptor and run Maven launch and rebuild.
|
||||
for delay in 0 10 30; do
|
||||
sleep "$delay"
|
||||
if mvn -B -ntp -U -N -f crates/ide-build/tests/fixtures/jbuild-maven/pom.xml \
|
||||
clean resources:resources compiler:compile \
|
||||
org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get \
|
||||
-Dartifact=org.slf4j:slf4j-api:1.7.36; then
|
||||
echo "prepared=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
exit 1
|
||||
- name: Save Maven artifacts for Java build tests
|
||||
if: steps.jbuild-maven.outputs.prepared == 'true'
|
||||
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
|
||||
@@ -197,10 +242,10 @@ jobs:
|
||||
timeout-minutes: 40
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
with: { targets: x86_64-unknown-linux-musl }
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
if: runner.environment != 'self-hosted'
|
||||
with: { key: server-musl }
|
||||
- name: Persistent Cargo target dir
|
||||
@@ -226,13 +271,13 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
with: { targets: wasm32-wasip2, components: "clippy, rustfmt" }
|
||||
- if: runner.environment != 'self-hosted'
|
||||
shell: bash
|
||||
run: echo "CARGO_TARGET_DIR=$GITHUB_WORKSPACE/target-plugins" >> "$GITHUB_ENV"
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
key: plugins
|
||||
@@ -262,9 +307,9 @@ jobs:
|
||||
cargo test --locked --manifest-path "$dir/Cargo.toml"
|
||||
echo "::endgroup::"
|
||||
done
|
||||
- uses: pnpm/action-setup@v5
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with: { node-version: 22, package-manager-cache: false }
|
||||
# Plugin web pages (`web-src/`, their own pnpm projects): typecheck and test.
|
||||
- name: Web pages typecheck and test
|
||||
@@ -291,9 +336,10 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: taiki-e/install-action@cargo-deny
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with: { tool: cargo-deny }
|
||||
- run: cargo deny check
|
||||
|
||||
frontend:
|
||||
@@ -303,13 +349,13 @@ jobs:
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
if: runner.environment == 'self-hosted'
|
||||
- uses: pnpm/action-setup@v5
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
@@ -330,10 +376,10 @@ jobs:
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
@@ -352,10 +398,10 @@ jobs:
|
||||
matrix:
|
||||
shard: [1, 2, 3, 4]
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
@@ -363,7 +409,7 @@ jobs:
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm exec playwright install --with-deps chromium
|
||||
- run: pnpm e2e --shard=${{ matrix.shard }}/4
|
||||
- uses: actions/upload-artifact@v6
|
||||
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
if: failure()
|
||||
with:
|
||||
name: playwright-report-${{ matrix.shard }}
|
||||
|
||||
@@ -21,6 +21,7 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
mirror:
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
@@ -35,10 +36,10 @@ jobs:
|
||||
echo "::notice::CNB_TOKEN unset: not mirroring $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
with: { sparse-checkout: scripts }
|
||||
- uses: actions/setup-node@v5
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
if: steps.token.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Download release
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
name: Homebrew
|
||||
|
||||
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
|
||||
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
|
||||
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
|
||||
# and without the HOMEBREW_TAP_DEPLOY_KEY secret (the private half of a write deploy key on
|
||||
# l0ng-ai/homebrew-tap).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "Published stable release to write the cask for (e.g. v0.1.51)"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: homebrew-tap
|
||||
|
||||
jobs:
|
||||
cask:
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
TAP: l0ng-ai/homebrew-tap
|
||||
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check tag and deploy key
|
||||
id: check
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::notice::$TAG is not a stable release: the cask stays as is"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$HOMEBREW_TAP_DEPLOY_KEY" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { sparse-checkout: scripts }
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Download DMGs
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: gh release download "$TAG" -R "$GITHUB_REPOSITORY" -p '*.dmg' -D assets
|
||||
- name: Write the cask
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
run: node scripts/homebrew-cask.ts "$TAG" assets tap/Casks/openidea.rb
|
||||
- name: Push to the tap
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
working-directory: tap
|
||||
run: |
|
||||
git add Casks/openidea.rb
|
||||
if git diff --cached --quiet; then
|
||||
echo "the cask is already at ${TAG#v}"
|
||||
exit 0
|
||||
fi
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git commit -m "openidea ${TAG#v}"
|
||||
git push
|
||||
@@ -30,15 +30,18 @@ on:
|
||||
- "src/ui/**"
|
||||
- "src/editor/api.ts"
|
||||
- "src/editor/navigationProviders.ts"
|
||||
- "src/editor/refactorProviders.ts"
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/core/cm/localAppearance.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/editor/lsp/snippet.ts"
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
@@ -104,9 +107,9 @@ jobs:
|
||||
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
|
||||
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
@@ -152,9 +155,9 @@ jobs:
|
||||
# stripping local-variable debuginfo from fixtures debugged in the smoke job (CodeLLDB).
|
||||
CARGO_PROFILE_DEV_DEBUG: line-tables-only
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
if: runner.environment != 'self-hosted'
|
||||
with:
|
||||
shared-key: language-smoke
|
||||
@@ -181,7 +184,7 @@ jobs:
|
||||
test -x smoke-bin/language_smoke && test -x smoke-bin/project_smoke
|
||||
# A tar keeps the executable bits, which artifacts drop.
|
||||
tar -cf smoke-bin.tar smoke-bin
|
||||
- uses: actions/upload-artifact@v6
|
||||
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
|
||||
|
||||
smoke:
|
||||
@@ -200,20 +203,20 @@ jobs:
|
||||
env:
|
||||
CARGO_MANIFEST_DIR: ${{ github.workspace }}/crates/ide-host
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
# Tool versions, shared with the evals (pnpm eval).
|
||||
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
with: { components: "rust-analyzer, rustfmt" }
|
||||
- uses: actions/download-artifact@v6
|
||||
- uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
|
||||
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@v5
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
@@ -239,19 +242,19 @@ jobs:
|
||||
fi
|
||||
|
||||
- if: matrix.language == 'python'
|
||||
uses: actions/setup-python@v5
|
||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
with: { python-version: "3.12" }
|
||||
- if: matrix.language == 'python'
|
||||
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
|
||||
|
||||
- if: matrix.language == 'go'
|
||||
uses: actions/setup-go@v5
|
||||
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
|
||||
with: { go-version: "1.27", cache: false }
|
||||
- if: matrix.language == 'go'
|
||||
run: go install "golang.org/x/tools/gopls@$GOPLS"
|
||||
|
||||
- if: matrix.language == 'java' || matrix.language == 'kotlin'
|
||||
uses: actions/setup-java@v4
|
||||
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
||||
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
|
||||
- if: matrix.language == 'java'
|
||||
run: |
|
||||
@@ -263,7 +266,7 @@ jobs:
|
||||
|
||||
# The Kotlin fixture has no Gradle wrapper: the server imports it with the Gradle on PATH.
|
||||
- if: matrix.language == 'kotlin'
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
|
||||
with: { gradle-version: "${{ env.GRADLE }}" }
|
||||
- if: matrix.language == 'kotlin'
|
||||
run: |
|
||||
@@ -275,7 +278,7 @@ jobs:
|
||||
|
||||
# Xdebug for the debug smoke; Composer installs the fixture's Pest for the run smoke.
|
||||
- if: matrix.language == 'php'
|
||||
uses: shivammathur/setup-php@v2
|
||||
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
|
||||
with: { php-version: "8.5", coverage: xdebug, tools: composer }
|
||||
- if: matrix.language == 'php'
|
||||
run: npm install --global "intelephense@$INTELEPHENSE"
|
||||
@@ -283,6 +286,10 @@ jobs:
|
||||
# The binaries from the build job, run from the crate directory as `cargo test` does.
|
||||
- working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
|
||||
# Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in.
|
||||
- if: matrix.language == 'typescript'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style
|
||||
- if: matrix.language == 'java'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
name: Nightly
|
||||
|
||||
# Builds main every night, when it has moved since the last nightly, into a prerelease
|
||||
# v<next patch>-nightly.<date> (scripts/nightly-prepare.ts: the tag points at a commit on top of
|
||||
# main that only sets the version). Nightly apps update from the rolling `nightly` release, which
|
||||
# holds the newest nightly's latest.json; stable apps read releases/latest, which is never a
|
||||
# prerelease, so they never see a nightly. The newest 14 nightlies are kept.
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 18 * * *" # 02:00 Beijing
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
force:
|
||||
description: "Build even when main has not changed since the last nightly"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: nightly
|
||||
|
||||
jobs:
|
||||
prepare:
|
||||
if: github.repository == 'l0ng-ai/openidea'
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
tag: ${{ steps.tag.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with: { ref: main, fetch-depth: 0 }
|
||||
- id: changed
|
||||
env:
|
||||
FORCE: ${{ inputs.force == true }}
|
||||
run: |
|
||||
last="$(git tag --list 'v*-nightly.*' --sort=-creatordate | head -1)"
|
||||
if [ "$FORCE" != true ] && [ -n "$last" ] && [ "$(git rev-parse "$last^")" = "$(git rev-parse HEAD)" ]; then
|
||||
echo "::notice::main has not changed since $last"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
if: steps.changed.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
- name: Version commit and tag
|
||||
id: tag
|
||||
if: steps.changed.outputs.skip != 'true'
|
||||
env:
|
||||
BUILD: ${{ github.run_number }}
|
||||
run: |
|
||||
version="$(node scripts/nightly-prepare.ts --date "$(date -u +%Y%m%d)" --build "$BUILD" | tail -1)"
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add -A
|
||||
git commit -q -m "chore: v$version"
|
||||
git tag "v$version"
|
||||
# Pushed with GITHUB_TOKEN, the tag does not start release.yml: the job below calls it.
|
||||
git push origin "refs/tags/v$version"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
|
||||
release:
|
||||
needs: prepare
|
||||
if: needs.prepare.outputs.tag != ''
|
||||
permissions:
|
||||
contents: write
|
||||
uses: ./.github/workflows/release.yml
|
||||
with:
|
||||
tag: ${{ needs.prepare.outputs.tag }}
|
||||
nightly: true
|
||||
secrets: inherit
|
||||
|
||||
# Points the nightly channel at the new nightly and drops the old ones.
|
||||
channel:
|
||||
needs: [prepare, release]
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
TAG: ${{ needs.prepare.outputs.tag }}
|
||||
steps:
|
||||
- name: Nightly manifest
|
||||
run: |
|
||||
if ! gh release download "$TAG" -p latest.json -D "$RUNNER_TEMP/manifest"; then
|
||||
echo "::warning::$TAG has no latest.json (unsigned build): the nightly channel stays where it was"
|
||||
exit 0
|
||||
fi
|
||||
notes="The update channel of the [nightly builds](https://github.com/$GH_REPO/releases?q=nightly&expanded=true): its latest.json is the newest nightly's, [$TAG](https://github.com/$GH_REPO/releases/tag/$TAG)."
|
||||
if gh release view nightly >/dev/null 2>&1; then
|
||||
gh release edit nightly --notes "$notes"
|
||||
else
|
||||
gh release create nightly --prerelease --target main --title "OpenIDEA Nightly" --notes "$notes"
|
||||
fi
|
||||
gh release upload nightly "$RUNNER_TEMP/manifest/latest.json" --clobber
|
||||
- name: Drop old nightlies
|
||||
run: |
|
||||
gh release list --limit 200 --json tagName,createdAt \
|
||||
--jq '[.[] | select(.tagName | test("^v.*-nightly\\."))] | sort_by(.createdAt) | reverse | .[14:][] | .tagName' |
|
||||
while read -r old; do
|
||||
gh release delete "$old" --cleanup-tag --yes
|
||||
done
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
if: github.event.pull_request.user.type != 'Bot' && !github.event.pull_request.draft
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v8
|
||||
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
script: |
|
||||
const pr = context.payload.pull_request;
|
||||
|
||||
@@ -19,6 +19,7 @@ env:
|
||||
jobs:
|
||||
plugin-keys:
|
||||
permissions: {}
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
keys: ${{ steps.keys.outputs.keys }}
|
||||
@@ -43,6 +44,7 @@ jobs:
|
||||
contents: write
|
||||
needs: plugin-keys
|
||||
name: Build (${{ matrix.name }})
|
||||
environment: release
|
||||
env:
|
||||
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
|
||||
strategy:
|
||||
@@ -69,15 +71,15 @@ jobs:
|
||||
target: x86_64-pc-windows-msvc
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with: { ref: "${{ env.TAG }}" }
|
||||
- uses: pnpm/action-setup@v5
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
with: { targets: "${{ matrix.target }}" }
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with: { key: "${{ matrix.target }}", cache-on-failure: true }
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
@@ -85,40 +87,57 @@ jobs:
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf
|
||||
- run: pnpm install --frozen-lockfile
|
||||
# Signing is optional: only secrets that are set get exported, so forks and
|
||||
# unconfigured repos produce unsigned builds instead of failing.
|
||||
- name: Signing env
|
||||
# Signing is optional: forks and unconfigured repos produce unsigned builds instead of
|
||||
# failing. The secrets go only into the steps that sign (never $GITHUB_ENV), so the other
|
||||
# steps and the actions' post steps never see them. Tauri treats a set-but-empty key as a
|
||||
# key, so the unsigned build is a separate step without the secrets.
|
||||
- name: Signing configured
|
||||
id: signing
|
||||
shell: bash
|
||||
env:
|
||||
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
|
||||
run: |
|
||||
echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
|
||||
echo "apple=$([ -n "$APPLE_ID" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
|
||||
- name: Build (signed)
|
||||
if: steps.signing.outputs.updater == 'true'
|
||||
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
APPLE_CERTIFICATE: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE || '' }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_CERTIFICATE_PASSWORD || '' }}
|
||||
APPLE_SIGNING_IDENTITY: ${{ runner.os == 'macOS' && secrets.APPLE_SIGNING_IDENTITY || '' }}
|
||||
APPLE_ID: ${{ runner.os == 'macOS' && secrets.APPLE_ID || '' }}
|
||||
APPLE_PASSWORD: ${{ runner.os == 'macOS' && secrets.APPLE_PASSWORD || '' }}
|
||||
APPLE_TEAM_ID: ${{ runner.os == 'macOS' && secrets.APPLE_TEAM_ID || '' }}
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
run: |
|
||||
for v in APPLE_CERTIFICATE APPLE_CERTIFICATE_PASSWORD APPLE_SIGNING_IDENTITY APPLE_ID \
|
||||
APPLE_PASSWORD APPLE_TEAM_ID TAURI_SIGNING_PRIVATE_KEY TAURI_SIGNING_PRIVATE_KEY_PASSWORD; do
|
||||
[ -n "${!v}" ] && { echo "$v<<__EOF__"; echo "${!v}"; echo "__EOF__"; } >> "$GITHUB_ENV"
|
||||
done
|
||||
true
|
||||
- uses: tauri-apps/tauri-action@v0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
releaseId: ${{ inputs.release_id }}
|
||||
tagName: ${{ env.TAG }}
|
||||
args: --target ${{ matrix.target }}
|
||||
# The parallel builds would race on one latest.json; `updater-manifest` writes it once.
|
||||
uploadUpdaterJson: false
|
||||
- name: Build (unsigned)
|
||||
if: steps.signing.outputs.updater != 'true'
|
||||
uses: tauri-apps/tauri-action@84b9d35b5fc46c1e45415bdb6144030364f7ebc5 # v0.6.2
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
releaseId: ${{ inputs.release_id }}
|
||||
tagName: ${{ env.TAG }}
|
||||
args: --target ${{ matrix.target }}
|
||||
uploadUpdaterJson: false
|
||||
# tauri-action notarizes the .app but not the DMG around it; notarize and
|
||||
# staple the DMG too, then replace the uploaded asset.
|
||||
- name: Notarize DMG
|
||||
if: runner.os == 'macOS' && env.APPLE_ID != ''
|
||||
if: runner.os == 'macOS' && steps.signing.outputs.apple == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: |
|
||||
for dmg in target/${{ matrix.target }}/release/bundle/dmg/*.dmg; do
|
||||
xcrun notarytool submit "$dmg" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" \
|
||||
@@ -137,6 +156,8 @@ jobs:
|
||||
shell: pwsh
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
run: |
|
||||
$target = "${{ matrix.target }}"
|
||||
$arch = if ($target -like "x86_64*") { "x64" } else { "arm64" }
|
||||
@@ -176,11 +197,11 @@ jobs:
|
||||
- { runner: macos-latest, target: x86_64-apple-darwin, os: macos, arch: x86_64 }
|
||||
runs-on: ${{ matrix.runner }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with: { ref: "${{ env.TAG }}" }
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
with: { targets: "${{ matrix.target }}" }
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with: { key: "server-${{ matrix.target }}", cache-on-failure: true }
|
||||
- name: musl toolchain
|
||||
if: runner.os == 'Linux'
|
||||
@@ -201,6 +222,45 @@ jobs:
|
||||
if command -v sha256sum >/dev/null; then sha256sum "$ASSET"; else shasum -a 256 "$ASSET"; fi > "$ASSET.sha256"
|
||||
gh release upload "$TAG" "$ASSET" "$ASSET.sha256" --clobber
|
||||
|
||||
# Signs every server archive with the updater key (`<asset>.sig`), so the app verifies a
|
||||
# server from the CNB mirror as it does from GitHub (ide-tools `server::fetch`). Only this job
|
||||
# gets the key; without it the archives keep only their .sha256.
|
||||
server-signatures:
|
||||
permissions:
|
||||
contents: write
|
||||
needs: server
|
||||
environment: release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Signing configured
|
||||
id: signing
|
||||
env:
|
||||
UPDATER_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
run: echo "updater=$([ -n "$UPDATER_KEY" ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
if: steps.signing.outputs.updater == 'true'
|
||||
with: { ref: "${{ env.TAG }}" }
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
if: steps.signing.outputs.updater == 'true'
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
if: steps.signing.outputs.updater == 'true'
|
||||
with: { node-version: 22, cache: pnpm }
|
||||
- if: steps.signing.outputs.updater == 'true'
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Sign server archives
|
||||
if: steps.signing.outputs.updater == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
run: |
|
||||
gh release download "$TAG" -p 'openidea-server-*.gz' -D "$RUNNER_TEMP/server"
|
||||
for asset in "$RUNNER_TEMP"/server/*.gz; do
|
||||
pnpm exec tauri signer sign "$asset"
|
||||
done
|
||||
gh release upload "$TAG" "$RUNNER_TEMP"/server/*.gz.sig --clobber
|
||||
|
||||
# The updater manifest (latest.json), built once from the signed bundles every build uploaded.
|
||||
# Fails when a platform is missing, so a release never ships a manifest without it.
|
||||
updater-manifest:
|
||||
@@ -209,7 +269,7 @@ jobs:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v8
|
||||
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
env:
|
||||
RELEASE_ID: ${{ inputs.release_id }}
|
||||
with:
|
||||
|
||||
@@ -7,19 +7,27 @@ on:
|
||||
tag:
|
||||
description: "Tag to release (e.g. v0.1.0); must already exist"
|
||||
required: true
|
||||
# nightly.yml: a nightly is a prerelease whose notes start at the previous nightly, without the
|
||||
# official plugins, the CNB mirror or the Homebrew cask.
|
||||
workflow_call:
|
||||
inputs:
|
||||
tag: { type: string, required: true }
|
||||
nightly: { type: boolean, default: false }
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.event.inputs.tag || github.ref_name }}
|
||||
group: release-${{ inputs.tag || github.ref_name }}
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
CARGO_INCREMENTAL: 0
|
||||
TAG: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
TAG: ${{ inputs.tag || github.ref_name }}
|
||||
COMMUNITY_PLUGINS_INDEX: https://github.com/l0ng-ai/openidea-plugins/releases/download/index/index.json
|
||||
|
||||
# The jobs that read a signing key or token, here and in the workflows called below, run in
|
||||
# the `release` environment, which holds those secrets.
|
||||
jobs:
|
||||
# Creates (or reuses) one draft release that every platform build uploads into.
|
||||
create-release:
|
||||
@@ -29,7 +37,7 @@ jobs:
|
||||
outputs:
|
||||
release_id: ${{ steps.release.outputs.id }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with: { ref: "${{ env.TAG }}" }
|
||||
- name: Tag matches app version
|
||||
run: |
|
||||
@@ -49,7 +57,9 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
- id: release
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
env:
|
||||
NIGHTLY: ${{ inputs.nightly == true }}
|
||||
with:
|
||||
script: |
|
||||
const tag = process.env.TAG;
|
||||
@@ -61,8 +71,13 @@ jobs:
|
||||
core.setOutput("id", existing.id);
|
||||
return;
|
||||
}
|
||||
// Prereleases are skipped: the notes span stable release to stable release.
|
||||
const previous = releases.find((r) => !r.draft && !r.prerelease);
|
||||
// Prereleases are skipped: the notes span stable release to stable release. A
|
||||
// nightly's span from the newest published release, nightly or stable (not the
|
||||
// rolling `nightly` release, which only holds the channel's manifest).
|
||||
const nightly = process.env.NIGHTLY === "true";
|
||||
const previous = releases.find(
|
||||
(r) => !r.draft && r.tag_name !== "nightly" && (nightly || !r.prerelease),
|
||||
);
|
||||
const { data: notes } = await github.rest.repos.generateReleaseNotes({
|
||||
owner, repo, tag_name: tag, previous_tag_name: previous?.tag_name,
|
||||
});
|
||||
@@ -78,7 +93,7 @@ jobs:
|
||||
needs: create-release
|
||||
uses: ./.github/workflows/release-build.yml
|
||||
with:
|
||||
tag: ${{ github.event.inputs.tag || github.ref_name }}
|
||||
tag: ${{ inputs.tag || github.ref_name }}
|
||||
release_id: ${{ needs.create-release.outputs.release_id }}
|
||||
secrets: inherit
|
||||
|
||||
@@ -96,29 +111,34 @@ jobs:
|
||||
contents: write
|
||||
needs: create-release
|
||||
name: Official plugins
|
||||
environment: release
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
SIGNING_KEY: ${{ secrets.PLUGIN_SIGNING_KEY }}
|
||||
NIGHTLY: ${{ inputs.nightly == true }}
|
||||
steps:
|
||||
- id: key
|
||||
run: |
|
||||
if [ -z "$SIGNING_KEY" ]; then
|
||||
if [ "$NIGHTLY" = true ]; then
|
||||
echo "a nightly does not publish the official plugins"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$SIGNING_KEY" ]; then
|
||||
echo "::warning::PLUGIN_SIGNING_KEY is not set: the official plugins are not published"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
if: steps.key.outputs.skip != 'true'
|
||||
with: { ref: "${{ env.TAG }}" }
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
if: steps.key.outputs.skip != 'true'
|
||||
with: { targets: wasm32-wasip2 }
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
if: steps.key.outputs.skip != 'true'
|
||||
with: { key: release-plugins }
|
||||
- uses: pnpm/action-setup@v5
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
if: steps.key.outputs.skip != 'true'
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@v5
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
if: steps.key.outputs.skip != 'true'
|
||||
with: { node-version: 22 }
|
||||
# Builds the web pages; fails when a checked-in component isn't built from these sources.
|
||||
@@ -163,7 +183,7 @@ jobs:
|
||||
needs: [create-release, binaries, plugins]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/github-script@v8
|
||||
- uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
env:
|
||||
RELEASE_ID: ${{ needs.create-release.outputs.release_id }}
|
||||
with:
|
||||
@@ -175,6 +195,15 @@ jobs:
|
||||
# The China mirror the updater's CNB source reads; a failure here leaves the GitHub release as is.
|
||||
cnb-mirror:
|
||||
needs: publish
|
||||
if: ${{ !inputs.nightly }}
|
||||
uses: ./.github/workflows/cnb-mirror.yml
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
with: { tag: "${{ inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
if: ${{ !inputs.nightly }}
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
with: { tag: "${{ inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
Створено
+285
-201
File diff suppressed because it is too large.
Load diff
+3
-2
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.53"
|
||||
version = "0.1.56"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -24,6 +24,7 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
|
||||
ide-lsp = { path = "crates/ide-lsp" }
|
||||
ide-dap = { path = "crates/ide-dap" }
|
||||
ide-vcs = { path = "crates/ide-vcs" }
|
||||
ide-github = { path = "crates/ide-github" }
|
||||
ide-terminal = { path = "crates/ide-terminal" }
|
||||
ide-run = { path = "crates/ide-run" }
|
||||
ide-workspace = { path = "crates/ide-workspace" }
|
||||
@@ -108,7 +109,7 @@ jupyter-zmq-client = { version = "=2.0.0", default-features = false, features =
|
||||
jupyter-protocol = "=2.0.3"
|
||||
zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] }
|
||||
lsp-types = "0.97"
|
||||
gix = { version = "0.89", default-features = false }
|
||||
gix = { version = "0.90", default-features = false }
|
||||
portable-pty = "0.9"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
|
||||
@@ -33,6 +33,12 @@ its search-everything habits — to a native app with a Rust core.
|
||||
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
|
||||
for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
|
||||
On macOS you can also install it with Homebrew:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Benchmark
|
||||
|
||||
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
|
||||
|
||||
@@ -33,6 +33,12 @@ her şeyi arama alışkanlığını) çekirdeği Rust ile yazılmış yerel bir
|
||||
Editör, kod analizi, hata ayıklayıcı (debugger), Git, terminal, veritabanı ve HTTP istemcileri;
|
||||
60'tan fazla dil için. macOS, Windows ve Linux sürümleri var.
|
||||
|
||||
macOS'ta Homebrew ile de kurabilirsiniz:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Performans karşılaştırması
|
||||
|
||||
[freqtrade](https://github.com/freqtrade/freqtrade) projesini (Python, ~770 dosya)
|
||||
|
||||
@@ -35,6 +35,12 @@ OpenIDEA 把 IntelliJ IDEA 的使用方式(快捷键、工具窗口、随处
|
||||
编辑器、代码洞察、调试器、Git、终端、数据库客户端和 HTTP 客户端,支持 60 多种语言。
|
||||
提供 macOS、Windows 和 Linux 版本。
|
||||
|
||||
在 macOS 上也可以用 Homebrew 安装:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## 性能对比
|
||||
|
||||
在缓存已预热的情况下打开 [freqtrade](https://github.com/freqtrade/freqtrade)(Python,约 770 个文件),
|
||||
|
||||
@@ -6,6 +6,12 @@
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## DuckDB symbol
|
||||
|
||||
DuckDB is a trademark of the DuckDB Foundation. The data source icon uses the
|
||||
light and dark symbols from the [DuckDB Design Manual](https://duckdb.org/design/manual/#logo-usage).
|
||||
The SVG paths and colors are preserved. See the [DuckDB trademark guidelines](https://duckdb.org/trademark_guidelines.html).
|
||||
|
||||
## Agent logos
|
||||
|
||||
The `src/ui/openidea/agents/` logos of agents listed in the
|
||||
@@ -149,6 +155,7 @@ languages whose JetBrains icons are not open source (Go, Ruby, Dart, Lua, Zig,
|
||||
Svelte, …). Those using the page-with-corner-badge layout (`goMod`, `goWork`,
|
||||
`dotenv`, `readme`, `lock`, `license`) reuse the page outline of the Apache-2.0
|
||||
expui `fileTypes/h.svg`; that outline is modified from the original by JetBrains.
|
||||
`goTest` adds a scaled copy of the Apache-2.0 expui `nodes/test.svg` as its badge.
|
||||
`src/ui/openidea/runConfigurations/springBoot*.svg` (the Spring Boot run configuration
|
||||
leaf) is OpenIDEA's own drawing.
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ uuid.workspace = true
|
||||
tempfile.workspace = true
|
||||
which = "8"
|
||||
semver = "1"
|
||||
sha1 = "0.10"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { version = "1", features = ["fs"] }
|
||||
|
||||
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
let retry = run_once(shared, spec, true, model).await;
|
||||
|
||||
@@ -283,6 +283,20 @@ impl AgentCatalogs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
|
||||
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
|
||||
let key = Self::key(shared, provider);
|
||||
let mut state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get_mut(&key)
|
||||
&& entry.flight.is_none()
|
||||
&& entry.error.is_some()
|
||||
{
|
||||
entry.completed = None;
|
||||
entry.retry_at_ms = None;
|
||||
entry.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
@@ -613,6 +627,40 @@ impl crate::AgentManager {
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
|
||||
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
|
||||
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
|
||||
.into_iter()
|
||||
.find(|p| p.id == "copilot")
|
||||
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
|
||||
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
let account = account.trim();
|
||||
if !account.is_empty() {
|
||||
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
|
||||
}
|
||||
match discover(&self.shared, spec, model).await {
|
||||
Ok(found) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: self.shared.config_for_new_task(found.config, "copilot"),
|
||||
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
|
||||
retry_at_ms: None,
|
||||
error: None,
|
||||
}),
|
||||
Err(error) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: Vec::new(),
|
||||
thought_levels: BTreeMap::new(),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: None,
|
||||
retry_at_ms: None,
|
||||
error: Some(error),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover(
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! the agent reports them over ACP.
|
||||
|
||||
use crate::model::{
|
||||
AgentCommand, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia, AgentCost, AgentLimit,
|
||||
AgentModelPricing, AgentTokens, AgentUsage,
|
||||
AgentCommand, AgentCommandChoice, AgentCommandSource, AgentConfigOption, AgentConfigValue, AgentConfigVia,
|
||||
AgentCost, AgentLimit, AgentModelPricing, AgentTokens, AgentUsage,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -54,6 +54,21 @@ pub(crate) fn bypass_approvals(config: &[AgentConfigOption]) -> bool {
|
||||
.any(|category| selected(category).zip(bypass_value(category)).is_some_and(|(value, bypass)| bypass(value)))
|
||||
}
|
||||
|
||||
/// Canonical snapshot of approval-bearing config options (`mode`, `permissions`, `approval`)
|
||||
/// so auto-resume can refuse to run silently if permission policy drifted while closed.
|
||||
pub(crate) fn approval_fingerprint(config: &[AgentConfigOption]) -> Option<String> {
|
||||
let mut parts: Vec<String> = config
|
||||
.iter()
|
||||
.filter(|o| matches!(o.category.as_deref(), Some("mode" | "permissions" | "approval")))
|
||||
.filter_map(|o| Some(format!("{}={}", o.id, o.current.as_deref()?)))
|
||||
.collect();
|
||||
if parts.is_empty() {
|
||||
return None;
|
||||
}
|
||||
parts.sort();
|
||||
Some(parts.join(";"))
|
||||
}
|
||||
|
||||
/// For an option of `category` that can approve everything, what tells its approving values.
|
||||
fn bypass_value(category: &str) -> Option<fn(&str) -> bool> {
|
||||
match category {
|
||||
@@ -155,13 +170,14 @@ pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context`, `fast` and `service_tier`)
|
||||
/// rather than the provider as a whole.
|
||||
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|
||||
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
|| is_fast_option(&o.id)
|
||||
|| is_context_option(&o.id)
|
||||
|| o.id == "service_tier"
|
||||
}
|
||||
|
||||
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
|
||||
@@ -277,11 +293,30 @@ pub(crate) fn commands_of(update: &Value, provider: &str) -> Vec<AgentCommand> {
|
||||
} else {
|
||||
c.get("source").and_then(|s| serde_json::from_value(s.clone()).ok()).unwrap_or_default()
|
||||
};
|
||||
let mut seen_choices = std::collections::HashSet::new();
|
||||
let choices = c
|
||||
.pointer("/input/choices")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|ch| {
|
||||
let choice_name =
|
||||
ch.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty())?;
|
||||
if !seen_choices.insert(choice_name.to_ascii_lowercase()) {
|
||||
return None;
|
||||
}
|
||||
Some(AgentCommandChoice {
|
||||
name: choice_name.to_owned(),
|
||||
description: str_of(ch, "description").unwrap_or_default(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Some(AgentCommand {
|
||||
name: name.to_owned(),
|
||||
source,
|
||||
description: str_of(c, "description").unwrap_or_default(),
|
||||
hint: c.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty()).map(str::to_owned),
|
||||
choices,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
@@ -531,6 +566,15 @@ mod tests {
|
||||
assert_eq!(ids(&c), [("allow_all", Some("off")), ("approval", Some("ask"))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_tier_is_per_model() {
|
||||
let options = options_of(&json!({ "configOptions": [
|
||||
{ "id": "service_tier", "type": "select", "currentValue": "false",
|
||||
"options": [{ "value": "false" }, { "value": "true" }] }
|
||||
] }));
|
||||
assert!(is_per_model_option(&options[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effort_context_and_fast_are_per_model_options() {
|
||||
let mut c = options_of(&json!({
|
||||
@@ -644,6 +688,7 @@ mod tests {
|
||||
let old: AgentCommand =
|
||||
serde_json::from_value(json!({"name": "review", "description": "Review", "hint": null})).unwrap();
|
||||
assert_eq!(old.source, AgentCommandSource::Command);
|
||||
assert!(old.choices.is_empty());
|
||||
let skill = AgentCommand { source: AgentCommandSource::Skill, ..old };
|
||||
assert_eq!(serde_json::from_value::<AgentCommand>(serde_json::to_value(&skill).unwrap()).unwrap(), skill);
|
||||
}
|
||||
@@ -653,13 +698,30 @@ mod tests {
|
||||
let cmds = commands_of(
|
||||
&json!({"availableCommands": [
|
||||
{"name": "review", "description": "Review changes", "input": {"hint": "what to review"}},
|
||||
{"name": "/init", "description": "Write CLAUDE.md", "input": null}
|
||||
{"name": "/init", "description": "Write CLAUDE.md", "input": null},
|
||||
{"name": "skills", "description": "Manage skills", "input": {
|
||||
"hint": "[list|info]",
|
||||
"choices": [
|
||||
{"name": "list", "description": "List all available skills"},
|
||||
{"name": "LIST", "description": "Duplicate ignored"},
|
||||
{"name": " ", "description": "Blank ignored"},
|
||||
{"name": "info", "description": "Show details for a skill"}
|
||||
]
|
||||
}}
|
||||
]}),
|
||||
"claude",
|
||||
);
|
||||
assert_eq!(cmds[0].source, AgentCommandSource::Command);
|
||||
assert_eq!(cmds[0].hint.as_deref(), Some("what to review"));
|
||||
assert!(cmds[0].choices.is_empty());
|
||||
assert_eq!((cmds[1].name.as_str(), cmds[1].hint.as_ref()), ("init", None));
|
||||
assert_eq!(
|
||||
cmds[2].choices,
|
||||
vec![
|
||||
AgentCommandChoice { name: "list".into(), description: "List all available skills".into() },
|
||||
AgentCommandChoice { name: "info".into(), description: "Show details for a skill".into() },
|
||||
]
|
||||
);
|
||||
let u = usage_of(&json!({"used": 1200, "size": 200000, "cost": {"amount": 0.42, "currency": "USD"}})).unwrap();
|
||||
assert_eq!((u.used, u.size), (1200, 200000));
|
||||
assert!(usage_of(&json!({"used": 1, "size": 0})).is_none());
|
||||
|
||||
+2148
-306
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -49,6 +49,74 @@ pub struct AgentCapabilities {
|
||||
pub context_usage: bool,
|
||||
}
|
||||
|
||||
/// Why `AgentManager` is shutting down its live tasks.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum AgentShutdownReason {
|
||||
WindowClose,
|
||||
#[default]
|
||||
Quit,
|
||||
Restart,
|
||||
BackendUpgrade,
|
||||
BackendStop,
|
||||
}
|
||||
|
||||
/// Why an in-flight turn stopped before completing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum InterruptionReason {
|
||||
WindowClose,
|
||||
Quit,
|
||||
Restart,
|
||||
BackendUpgrade,
|
||||
BackendStop,
|
||||
UnexpectedExit,
|
||||
NetworkTimeout,
|
||||
}
|
||||
|
||||
impl From<AgentShutdownReason> for InterruptionReason {
|
||||
fn from(reason: AgentShutdownReason) -> Self {
|
||||
match reason {
|
||||
AgentShutdownReason::WindowClose => Self::WindowClose,
|
||||
AgentShutdownReason::Quit => Self::Quit,
|
||||
AgentShutdownReason::Restart => Self::Restart,
|
||||
AgentShutdownReason::BackendUpgrade => Self::BackendUpgrade,
|
||||
AgentShutdownReason::BackendStop => Self::BackendStop,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recovery metadata recorded when an active turn was interrupted before finishing.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentInterrupted {
|
||||
pub reason: InterruptionReason,
|
||||
pub at_ms: f64,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub was_waiting_for_input: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub approval_mode: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub auto_resume_once: bool,
|
||||
}
|
||||
|
||||
/// Summary returned when reconciling interrupted tasks for a connected project window.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentRecoveryReport {
|
||||
/// Unique identifier of this `AgentManager` process incarnation.
|
||||
pub instance_id: String,
|
||||
/// `true` on the first reconciliation of this `AgentManager` incarnation.
|
||||
pub first_reconcile: bool,
|
||||
/// Task IDs automatically resumed during this reconciliation.
|
||||
pub auto_resumed: Vec<String>,
|
||||
/// Task IDs remaining in `Interrupted` (`Ask to resume`).
|
||||
pub interrupted: Vec<String>,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Isolation {
|
||||
@@ -113,10 +181,24 @@ pub struct AgentTask {
|
||||
/// Per-session skill modes (`skill name` -> mode), on top of the settings' policies.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
|
||||
/// Per-session memory overrides (auto-memory mode and per-entry modes), boxed to keep `AgentEvent::Task` small.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub memory_overrides: Option<Box<AgentMemoryOverrides>>,
|
||||
/// Token counts of the last turn and context compressions, when the agent reports them.
|
||||
// Boxed so that `AgentEvent::Task` stays within clippy's `large_enum_variant` bound on Windows.
|
||||
#[serde(default)]
|
||||
pub stats: Box<AgentSessionStats>,
|
||||
/// Set when the task's last active turn was interrupted (window close, restart, crash, or
|
||||
/// expired network retry window) and has not been resumed or dismissed yet.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub interrupted: Option<Box<AgentInterrupted>>,
|
||||
/// Persisted unseen reply / input / failure state across window closes and remote reattaches.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub unread: bool,
|
||||
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recovery_window_mins: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -159,6 +241,9 @@ pub struct AgentRetry {
|
||||
/// When the next attempt starts (ms since the epoch).
|
||||
pub retry_at_ms: f64,
|
||||
pub error: Option<String>,
|
||||
/// Set when OpenIDEA holds an active turn in `Waiting for network` until `deadline_ms`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub deadline_ms: Option<f64>,
|
||||
}
|
||||
|
||||
/// Token pricing (Credits per 1M tokens) and context window capacity for one tier.
|
||||
@@ -255,6 +340,14 @@ pub enum AgentCommandSource {
|
||||
Skill,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentCommandChoice {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentCommand {
|
||||
@@ -265,6 +358,9 @@ pub struct AgentCommand {
|
||||
pub hint: Option<String>,
|
||||
#[serde(default)]
|
||||
pub source: AgentCommandSource,
|
||||
/// Fixed subcommand/argument choices advertised by the agent (e.g. `list`, `info` for `/skills`).
|
||||
#[serde(default)]
|
||||
pub choices: Vec<AgentCommandChoice>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -289,6 +385,9 @@ pub struct AgentContextUsage {
|
||||
pub model: String,
|
||||
pub is_auto_compact_enabled: Option<bool>,
|
||||
pub auto_compact_threshold: Option<u32>,
|
||||
/// Tokens reserved for model response / output buffer, when the agent reports it.
|
||||
#[serde(default)]
|
||||
pub reserved_tokens: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -296,13 +395,16 @@ pub struct AgentContextCategory {
|
||||
pub name: String,
|
||||
pub tokens: u32,
|
||||
pub kind: Option<String>,
|
||||
/// Visual section group (e.g. `"System"`, `"User Context"`).
|
||||
#[serde(default)]
|
||||
pub group: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentCost {
|
||||
pub amount: f64,
|
||||
/// ISO 4217 code, e.g. `USD`.
|
||||
/// ISO 4217 code (e.g. `USD`), or `"credits"` for AI-credit billing.
|
||||
pub currency: String,
|
||||
}
|
||||
|
||||
@@ -511,6 +613,9 @@ pub enum AgentEntry {
|
||||
/// Sent into a running turn rather than starting one.
|
||||
#[serde(default)]
|
||||
steered: bool,
|
||||
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
|
||||
#[serde(default)]
|
||||
recovery: Option<InterruptionReason>,
|
||||
},
|
||||
Agent {
|
||||
text: String,
|
||||
@@ -547,6 +652,9 @@ pub enum AgentEntry {
|
||||
started_ms: Option<f64>,
|
||||
#[serde(default)]
|
||||
ended_ms: Option<f64>,
|
||||
/// The command an `execute` call runs, from its structured input; `None` when the agent gave none.
|
||||
#[serde(default)]
|
||||
command: Option<String>,
|
||||
},
|
||||
Plan {
|
||||
items: Vec<AgentPlanItem>,
|
||||
@@ -612,6 +720,9 @@ pub struct AgentProvider {
|
||||
/// Executable and arguments actually launched, without flattening paths containing spaces.
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
/// Settings-managed suffix of `args`; absent for launches that cannot be edited.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub additional_args: Option<Vec<String>>,
|
||||
pub default_program: Option<String>,
|
||||
pub default_args: Vec<String>,
|
||||
pub login_hint: Option<String>,
|
||||
@@ -620,6 +731,9 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
|
||||
#[serde(default)]
|
||||
pub can_sign_in: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
@@ -644,6 +758,34 @@ pub enum AgentCommandReadOnlyReason {
|
||||
CustomAgent,
|
||||
}
|
||||
|
||||
/// An authenticated `github.com` account stored in GitHub CLI (`gh`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhAuthAccount {
|
||||
pub login: String,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
/// GitHub Copilot's default sign-in status alongside the accounts available through `gh`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CopilotAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
pub gh_installed: bool,
|
||||
pub gh_accounts: Vec<GhAuthAccount>,
|
||||
}
|
||||
|
||||
/// Output and completion of an interactive sign-in PTY started by the IDE.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum AgentLoginEvent {
|
||||
Output { data: String },
|
||||
Exited { code: Option<i32> },
|
||||
}
|
||||
|
||||
/// Where an agent comes from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
@@ -696,10 +838,18 @@ pub struct NewAgentTask {
|
||||
/// Per-session skill modes (`skill name` -> mode).
|
||||
#[serde(default)]
|
||||
pub skill_overrides: BTreeMap<String, AgentSkillMode>,
|
||||
/// Per-session memory overrides (auto-memory mode and per-entry modes).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub memory_overrides: Option<AgentMemoryOverrides>,
|
||||
/// Creates the task without sending `prompt` (it only names the task): the composer's
|
||||
/// `!` command runs in it first.
|
||||
#[serde(default)]
|
||||
pub idle: bool,
|
||||
/// A throwaway task (Generate Commit Message): it isn't saved, so it doesn't outlive a
|
||||
/// restart, and the agent keeps no session history of its own for it.
|
||||
#[serde(default)]
|
||||
pub ephemeral: bool,
|
||||
}
|
||||
|
||||
/// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
|
||||
@@ -833,7 +983,7 @@ pub enum AgentEvent {
|
||||
pub use ide_core::settings::{AgentMcpServer, McpTransport};
|
||||
|
||||
/// Where an MCP server configuration is stored (`settings.toml` vs `.openidea/settings.toml`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum McpScope {
|
||||
User,
|
||||
@@ -900,7 +1050,223 @@ fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{AgentSkillMode, AgentSkillPolicy};
|
||||
pub use ide_core::settings::{
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentProviderMemoryPolicy, AgentSkillMode,
|
||||
AgentSkillPolicy, AutoMemoryMode,
|
||||
};
|
||||
|
||||
/// Kind of discovered agent memory entry.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryKind {
|
||||
/// Always-loaded instruction document (`AGENTS.md`, `CLAUDE.md`, `copilot-instructions.md`, `GEMINI.md`).
|
||||
#[default]
|
||||
Instruction,
|
||||
/// Path-scoped or conditional rule (`.claude/rules/*.md`, `*.instructions.md`, `.cursor/rules/*.mdc`).
|
||||
Rule,
|
||||
/// Agent-authored cross-session memory note (`MEMORY.md`, Claude topic files, Codex summaries, Hermes `USER.md`).
|
||||
AutoNote,
|
||||
}
|
||||
|
||||
/// Which workspace, user, or CLI store a memory entry was discovered in.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemorySource {
|
||||
/// Portable workspace instructions: `AGENTS.md`, `AGENTS.override.md`.
|
||||
#[default]
|
||||
Workspace,
|
||||
/// `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md`, `.claude/rules/**`.
|
||||
ClaudeWorkspace,
|
||||
/// `~/.claude/CLAUDE.md`, `~/.claude/rules/**`.
|
||||
ClaudeUser,
|
||||
/// `~/.claude/projects/<repo>/memory/**` (or custom `autoMemoryDirectory`).
|
||||
ClaudeAuto,
|
||||
/// `.github/copilot-instructions.md`, `.github/instructions/**/*.instructions.md`.
|
||||
GithubWorkspace,
|
||||
/// `~/.copilot/copilot-instructions.md`, `~/.copilot/instructions/**/*.instructions.md`.
|
||||
CopilotUser,
|
||||
/// `~/.codex/AGENTS.md`, `~/.codex/AGENTS.override.md`.
|
||||
CodexUser,
|
||||
/// `~/.codex/memories/**` / `~/.codex/memories_v2/**`.
|
||||
CodexAuto,
|
||||
/// `.cursor/rules/**/*.mdc`, `.cursorrules`.
|
||||
CursorWorkspace,
|
||||
/// `GEMINI.md`.
|
||||
GeminiWorkspace,
|
||||
/// `~/.gemini/GEMINI.md`.
|
||||
GeminiUser,
|
||||
/// `<hermes_profile>/memories/{MEMORY.md,USER.md}`.
|
||||
HermesAuto,
|
||||
}
|
||||
|
||||
impl AgentMemorySource {
|
||||
/// True when the entry lives inside the current workspace and requires Workspace Trust.
|
||||
pub fn is_workspace(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Workspace
|
||||
| Self::ClaudeWorkspace
|
||||
| Self::GithubWorkspace
|
||||
| Self::CursorWorkspace
|
||||
| Self::GeminiWorkspace
|
||||
)
|
||||
}
|
||||
|
||||
/// True when the entry is an agent's learned cross-session auto-memory store.
|
||||
pub fn is_auto(self) -> bool {
|
||||
matches!(self, Self::ClaudeAuto | Self::CodexAuto | Self::HermesAuto)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which layer decided an [`AgentMemoryState::mode`] or [`AutoMemoryMode`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryOrigin {
|
||||
#[default]
|
||||
None,
|
||||
Session,
|
||||
Workspace,
|
||||
User,
|
||||
/// Locked `Off` because the workspace is untrusted.
|
||||
Trust,
|
||||
}
|
||||
|
||||
/// One discovered instruction file, rule file, or learned auto-memory note.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryEntry {
|
||||
/// Stable identifier (`"<source>::<rel_key>"`).
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub kind: AgentMemoryKind,
|
||||
pub source: AgentMemorySource,
|
||||
/// Secondary sources whose symlink or `@AGENTS.md` import resolved to this same canonical file.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub also_in: Vec<AgentMemorySource>,
|
||||
/// Canonical file path on disk.
|
||||
pub path: IpcPath,
|
||||
/// Normalized path-scoping globs (`paths:` in Claude, `applyTo:` in Copilot, `globs:` in Cursor).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub paths: Vec<String>,
|
||||
/// Optional memory category (`user`, `feedback`, `project`, `reference`, `profile`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub category: Option<String>,
|
||||
/// Approximate prompt token cost (~4 chars/token).
|
||||
pub approx_tokens: u32,
|
||||
pub line_count: u32,
|
||||
pub byte_len: u64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub modified_ms: Option<f64>,
|
||||
/// True when OpenIDEA allows deleting or promoting-and-removing this file (auto-memory notes).
|
||||
pub writable: bool,
|
||||
pub valid: bool,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryState {
|
||||
pub entry: AgentMemoryEntry,
|
||||
pub mode: AgentMemoryMode,
|
||||
/// Optional provider filter from `[agents.memory.entries.<id>]`; empty means all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
}
|
||||
|
||||
/// Live auto-memory status and capability summary for one agent family.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentAutoMemoryStatus {
|
||||
pub provider: String,
|
||||
pub label: String,
|
||||
pub mode: AutoMemoryMode,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
pub note_count: u32,
|
||||
pub rollout_count: u32,
|
||||
pub approx_tokens: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub storage_path: Option<IpcPath>,
|
||||
pub supports_auto_control: bool,
|
||||
pub supports_file_exclusion: bool,
|
||||
pub supports_reset: bool,
|
||||
}
|
||||
|
||||
/// Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryCatalog {
|
||||
pub entries: Vec<AgentMemoryState>,
|
||||
pub providers: Vec<AgentAutoMemoryStatus>,
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
pub auto_memory_origin: AgentMemoryOrigin,
|
||||
}
|
||||
|
||||
/// Per-session memory overrides stored on an [`AgentTask`].
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemoryOverrides {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub auto_memory: Option<AutoMemoryMode>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub entries: BTreeMap<String, AgentMemoryMode>,
|
||||
}
|
||||
|
||||
impl AgentMemoryOverrides {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.auto_memory.is_none() && self.entries.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Target format when creating a new memory or instruction file from Settings › Agents › Memory.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryCreateTarget {
|
||||
/// `<workspace>/AGENTS.md` (or `~/.codex/AGENTS.md` in User scope).
|
||||
#[default]
|
||||
AgentsMd,
|
||||
/// `<workspace>/.claude/rules/<slug>.md` or `~/.claude/rules/<slug>.md`.
|
||||
ClaudeRule,
|
||||
/// `<workspace>/.github/instructions/<slug>.instructions.md` or `~/.copilot/instructions/<slug>.instructions.md`.
|
||||
CopilotInstruction,
|
||||
/// `<workspace>/.cursor/rules/<slug>.mdc`.
|
||||
CursorRule,
|
||||
}
|
||||
|
||||
/// Payload for creating a new instruction or rule file.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CreateAgentMemoryInput {
|
||||
pub scope: McpScope,
|
||||
pub target: AgentMemoryCreateTarget,
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub description: Option<String>,
|
||||
#[serde(default)]
|
||||
pub paths: Vec<String>,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
/// Payload for promoting an auto-memory note into `AGENTS.md`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PromoteAgentMemoryInput {
|
||||
pub source_id: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub heading: Option<String>,
|
||||
#[serde(default)]
|
||||
pub remove_source: bool,
|
||||
}
|
||||
|
||||
/// Which CLI's own folders a skill was discovered in (Settings › Agents › Skills groups by it).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -30,6 +30,67 @@ pub(super) fn transcript(config_dir: &Path, cwd: &Path, id: &str) -> PathBuf {
|
||||
.unwrap_or(direct)
|
||||
}
|
||||
|
||||
/// Brings session `id` into `config_dir` when it is missing there but another Claude Code
|
||||
/// configuration directory beside it (`~/.claude`, `~/.claude-work`...) has it: switching
|
||||
/// `CLAUDE_CONFIG_DIR` (another account) would otherwise lose every earlier conversation.
|
||||
/// Copies the transcript and its folder (subagents, tool results) under the same project
|
||||
/// directory name. Returns whether the session is in `config_dir` now.
|
||||
pub(super) fn adopt(config_dir: &Path, cwd: &Path, id: &str) -> bool {
|
||||
if transcript(config_dir, cwd, id).exists() {
|
||||
return true;
|
||||
}
|
||||
let file = format!("{id}.jsonl");
|
||||
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
|
||||
let mut homes: Vec<PathBuf> = config_dir
|
||||
.parent()
|
||||
.into_iter()
|
||||
.chain(home.as_deref())
|
||||
.flat_map(|dir| std::fs::read_dir(dir).into_iter().flatten().flatten())
|
||||
.filter(|d| d.file_name().to_string_lossy().starts_with(".claude"))
|
||||
.map(|d| d.path())
|
||||
.filter(|p| p != config_dir && p.join("projects").is_dir())
|
||||
.collect();
|
||||
homes.sort();
|
||||
homes.dedup();
|
||||
let found = homes.iter().find_map(|other| {
|
||||
let projects = other.join("projects");
|
||||
let direct = projects.join(escape(cwd));
|
||||
std::iter::once(direct.clone())
|
||||
.chain(std::fs::read_dir(&projects).into_iter().flatten().flatten().map(|d| d.path()))
|
||||
.find(|dir| dir.join(&file).is_file())
|
||||
});
|
||||
let Some(source) = found else { return false };
|
||||
let Some(name) = source.file_name() else { return false };
|
||||
let target = config_dir.join("projects").join(name);
|
||||
let copied = std::fs::create_dir_all(&target)
|
||||
.and_then(|()| copy_tree(&source.join(id), &target.join(id)))
|
||||
.and_then(|()| std::fs::copy(source.join(&file), target.join(&file)).map(drop));
|
||||
match copied {
|
||||
Ok(()) => true,
|
||||
Err(e) => {
|
||||
tracing::warn!("claude session {id}: copying it from {}: {e}", source.display());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {
|
||||
if !from.is_dir() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::create_dir_all(to)?;
|
||||
for entry in std::fs::read_dir(from)? {
|
||||
let entry = entry?;
|
||||
let dest = to.join(entry.file_name());
|
||||
if entry.file_type()?.is_dir() {
|
||||
copy_tree(&entry.path(), &dest)?;
|
||||
} else if !dest.exists() {
|
||||
std::fs::copy(entry.path(), dest)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The project directory name Claude Code uses for `cwd`.
|
||||
pub(crate) fn escape(cwd: &Path) -> String {
|
||||
cwd.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()
|
||||
@@ -207,6 +268,26 @@ mod tests {
|
||||
json!({"type": "assistant", "uuid": id, "parentUuid": parent, "message": {"role": "assistant", "content": content}})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_from_another_config_dir_is_copied_in() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let (old, new) = (root.path().join(".claude-2"), root.path().join(".claude-3"));
|
||||
let cwd = Path::new("/work/app");
|
||||
let project = old.join("projects").join(escape(cwd));
|
||||
std::fs::create_dir_all(project.join("s1/subagents")).unwrap();
|
||||
std::fs::write(project.join("s1.jsonl"), "{}\n").unwrap();
|
||||
std::fs::write(project.join("s1/subagents/a.jsonl"), "{}\n").unwrap();
|
||||
std::fs::create_dir_all(new.join("projects")).unwrap();
|
||||
|
||||
assert!(!adopt(&new, cwd, "missing"));
|
||||
assert!(adopt(&new, cwd, "s1"));
|
||||
let copied = new.join("projects").join(escape(cwd));
|
||||
assert_eq!(transcript(&new, cwd, "s1"), copied.join("s1.jsonl"));
|
||||
assert!(copied.join("s1/subagents/a.jsonl").is_file());
|
||||
assert!(project.join("s1.jsonl").is_file(), "the original stays");
|
||||
assert!(adopt(&new, cwd, "s1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_branch_is_the_conversation() {
|
||||
let entries = vec![
|
||||
|
||||
@@ -174,10 +174,16 @@ struct Session {
|
||||
mcp_off: Vec<String>,
|
||||
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
|
||||
skills_add_dir: Option<PathBuf>,
|
||||
/// The staged memory rules folder passed as `--add-dir` (its `.claude/rules` holds shared rules).
|
||||
memory_add_dir: Option<PathBuf>,
|
||||
/// Load `.claude/rules` from `--add-dir` folders (`CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`).
|
||||
additional_dirs_claude_md: bool,
|
||||
/// The workspace's other roots, each passed as `--add-dir`.
|
||||
additional_dirs: Vec<String>,
|
||||
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
|
||||
skills_settings: Option<String>,
|
||||
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`).
|
||||
cli_settings: Option<String>,
|
||||
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
|
||||
ephemeral: bool,
|
||||
shim: Weak<Shim>,
|
||||
st: Mutex<State>,
|
||||
/// Serializes (re)starting the process.
|
||||
@@ -334,6 +340,12 @@ impl Shim {
|
||||
Some(history::transcript(self.config.config_dir.as_deref()?, cwd, id))
|
||||
}
|
||||
|
||||
/// Whether session `id` is in the configuration directory, copied there from another one
|
||||
/// if need be (see [`history::adopt`]).
|
||||
fn adopt(&self, cwd: &Path, id: &str) -> bool {
|
||||
self.config.config_dir.as_deref().is_some_and(|dir| history::adopt(dir, cwd, id))
|
||||
}
|
||||
|
||||
/// The conversation a session started with `start` begins with.
|
||||
fn base_chain(&self, cwd: &Path, start: &Start) -> Result<Vec<Value>, String> {
|
||||
let (id, at) = match start {
|
||||
@@ -363,13 +375,21 @@ impl Shim {
|
||||
}
|
||||
});
|
||||
let skills = params.pointer("/_meta/openidea/skills");
|
||||
let memory = params.pointer("/_meta/openidea/memory");
|
||||
let cli_settings = build_cli_settings(skills, memory);
|
||||
let session = Arc::new(Session {
|
||||
id: id.to_owned(),
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
memory_add_dir: memory.and_then(|m| m.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
additional_dirs_claude_md: memory
|
||||
.and_then(|m| m.get("claudeAdditionalDirsClaudeMd"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
additional_dirs: additional_dirs(params),
|
||||
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
|
||||
cli_settings,
|
||||
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
|
||||
shim: Arc::downgrade(self),
|
||||
st: Mutex::new(State {
|
||||
proc: None,
|
||||
@@ -435,10 +455,13 @@ impl Shim {
|
||||
let id = params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
|
||||
let cwd = self.cwd_of(¶ms);
|
||||
let (start, pending) = match self.load_pending(id) {
|
||||
Some(s) => (s, true),
|
||||
None if self.transcript(&cwd, id).is_some_and(|p| p.exists()) => {
|
||||
(Start::Resume { id: id.to_owned(), at: None }, false)
|
||||
Some(s) => {
|
||||
if let Start::Resume { id: from, .. } | Start::Fork { from, .. } = &s {
|
||||
self.adopt(&cwd, from);
|
||||
}
|
||||
(s, true)
|
||||
}
|
||||
None if self.adopt(&cwd, id) => (Start::Resume { id: id.to_owned(), at: None }, false),
|
||||
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
|
||||
};
|
||||
let chain = self.base_chain(&cwd, &start).map_err(internal)?;
|
||||
@@ -451,24 +474,43 @@ impl Shim {
|
||||
Ok(json!({ "configOptions": session.st.lock().settings.options() }))
|
||||
}
|
||||
"session/fork" => {
|
||||
let source = self.session(¶ms)?;
|
||||
let id = new_uuid(false);
|
||||
let (start, settings) = {
|
||||
let st = source.st.lock();
|
||||
let start = match &st.start {
|
||||
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
|
||||
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
|
||||
}
|
||||
Start::New { .. } => Start::New { id: id.clone() },
|
||||
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
|
||||
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
|
||||
}
|
||||
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
|
||||
};
|
||||
(start, st.settings.clone())
|
||||
let source_id =
|
||||
params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
|
||||
let source = self.sessions.lock().get(source_id).cloned();
|
||||
// The host names the fork's session id so the task knows it before the CLI
|
||||
// starts; only a canonical UUID is accepted.
|
||||
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
|
||||
if let Some(target) = requested
|
||||
&& !crate::canonical_uuid(target)
|
||||
{
|
||||
return Err(invalid("A fork session id must be a canonical UUID"));
|
||||
}
|
||||
let id = requested.map_or_else(|| new_uuid(false), str::to_owned);
|
||||
if self.sessions.lock().contains_key(&id) {
|
||||
return Err(invalid(format!("session {id} is already open")));
|
||||
}
|
||||
let cwd = source.as_ref().map_or_else(|| self.cwd_of(¶ms), |session| session.cwd.clone());
|
||||
let (start, settings) = match &source {
|
||||
Some(source) => {
|
||||
let st = source.st.lock();
|
||||
let start = match &st.start {
|
||||
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
|
||||
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
|
||||
}
|
||||
Start::New { .. } => Start::New { id: id.clone() },
|
||||
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
|
||||
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
|
||||
}
|
||||
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
|
||||
};
|
||||
(start, st.settings.clone())
|
||||
}
|
||||
// A recorded session is not open in this connection: the CLI forks it
|
||||
// from its transcript on disk when the task's first prompt starts it.
|
||||
None => (Start::Fork { from: source_id.to_owned(), id: id.clone(), at: None }, Settings::default()),
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, source.cwd.clone(), start, true, ¶ms);
|
||||
let session = self.add_session(&id, cwd, start, true, ¶ms);
|
||||
session.st.lock().settings = settings;
|
||||
let options = session.st.lock().settings.options();
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
@@ -697,15 +739,28 @@ impl Session {
|
||||
if let Some(dir) = &self.skills_add_dir {
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
if let Some(dir) = &self.memory_add_dir
|
||||
&& self.skills_add_dir.as_ref() != Some(dir)
|
||||
{
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
for dir in &self.additional_dirs {
|
||||
args.extend(["--add-dir".to_owned(), dir.clone()]);
|
||||
}
|
||||
if let Some(settings) = &self.skills_settings {
|
||||
if let Some(settings) = &self.cli_settings {
|
||||
args.extend(["--settings".to_owned(), settings.clone()]);
|
||||
}
|
||||
if self.ephemeral {
|
||||
args.push("--no-session-persistence".to_owned());
|
||||
}
|
||||
args.extend(start.args());
|
||||
let launch =
|
||||
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
|
||||
let mut env = shim.config.env.clone();
|
||||
if self.additional_dirs_claude_md
|
||||
&& !env.iter().any(|(k, _)| k == "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD")
|
||||
{
|
||||
env.push(("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD".to_owned(), "1".to_owned()));
|
||||
}
|
||||
let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env };
|
||||
let io = shim
|
||||
.cli
|
||||
.launch(&launch, shim.on_stderr.clone())
|
||||
@@ -1567,6 +1622,41 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
|
||||
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
|
||||
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
|
||||
/// Claude Code's own configuration stays off too.
|
||||
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with memory
|
||||
/// settings (`autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`) into one `--settings` JSON.
|
||||
fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<String> {
|
||||
let mut root = skills
|
||||
.and_then(|s| s.get("claudeSettings"))
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|raw| serde_json::from_str::<serde_json::Map<String, Value>>(raw).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Some(mem) = memory {
|
||||
if let Some(auto) = mem.get("claudeAutoMemory").and_then(Value::as_bool) {
|
||||
root.insert("autoMemoryEnabled".into(), json!(auto));
|
||||
}
|
||||
if let Some(excludes) = mem.get("claudeMdExcludes").and_then(Value::as_array) {
|
||||
let clean: Vec<Value> =
|
||||
excludes.iter().filter_map(Value::as_str).filter(|s| !s.is_empty()).map(|s| json!(s)).collect();
|
||||
if !clean.is_empty() {
|
||||
root.insert("claudeMdExcludes".into(), Value::Array(clean));
|
||||
}
|
||||
}
|
||||
if let Some(inst) = mem.get("claudeInstructionFiles").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
root.insert(
|
||||
"pluginConfigs".into(),
|
||||
json!({
|
||||
"cc-plugin-agents-md@builtin": {
|
||||
"options": { "instructionFiles": inst }
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
(!root.is_empty()).then(|| serde_json::to_string(&Value::Object(root)).expect("settings serialize"))
|
||||
}
|
||||
|
||||
/// The session's `additionalDirectories`: the workspace's other roots.
|
||||
fn additional_dirs(params: &Value) -> Vec<String> {
|
||||
let dirs = params.get("additionalDirectories").and_then(Value::as_array);
|
||||
|
||||
@@ -464,6 +464,7 @@ async fn replay_simple() {
|
||||
let args = r.cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--session-id", r.session.as_str()]), "{args:?}");
|
||||
assert!(args.contains(&"--permission-prompt-tool".to_owned()));
|
||||
assert!(!args.contains(&"--no-session-persistence".to_owned()));
|
||||
let user = r.sent(0).into_iter().find(|m| m["type"] == "user").unwrap();
|
||||
assert_eq!(user["message"]["content"][0]["text"], "Reply with exactly: hello there");
|
||||
}
|
||||
@@ -652,6 +653,84 @@ async fn replay_resume() {
|
||||
assert!(args.windows(2).any(|w| w == ["--resume", r.session.as_str()]), "{args:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() {
|
||||
/// Registering a fork must not start a process: its first prompt does.
|
||||
struct NoLaunch;
|
||||
impl Cli for NoLaunch {
|
||||
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
|
||||
panic!("session/fork must not launch the CLI")
|
||||
}
|
||||
}
|
||||
|
||||
let config = tempfile::tempdir().unwrap();
|
||||
let pending = tempfile::tempdir().unwrap();
|
||||
let h = Harness::connect(
|
||||
Arc::new(NoLaunch),
|
||||
config.path().to_path_buf(),
|
||||
pending.path().to_path_buf(),
|
||||
std::env::temp_dir(),
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
let source = "11111111-1111-4111-8111-111111111111";
|
||||
let target = "22222222-2222-4222-8222-222222222222";
|
||||
let reply = h
|
||||
.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": source,
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": target } }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(reply["sessionId"], target);
|
||||
// The host chose this id for the fork: the next process must fork the recorded
|
||||
// session under exactly it.
|
||||
let saved: Value =
|
||||
serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap();
|
||||
assert_eq!(saved, json!({ "fork": source, "id": target, "at": null }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_rejects_a_requested_id_that_is_not_canonical() {
|
||||
struct NoLaunch;
|
||||
impl Cli for NoLaunch {
|
||||
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
|
||||
panic!("no process")
|
||||
}
|
||||
}
|
||||
|
||||
let config = tempfile::tempdir().unwrap();
|
||||
let pending = tempfile::tempdir().unwrap();
|
||||
let h = Harness::connect(
|
||||
Arc::new(NoLaunch),
|
||||
config.path().to_path_buf(),
|
||||
pending.path().to_path_buf(),
|
||||
std::env::temp_dir(),
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
for rejected in ["../../x", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", ""] {
|
||||
let error = h
|
||||
.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": "11111111-1111-4111-8111-111111111111",
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": rejected } }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect_err("only a canonical id may name the fork");
|
||||
assert!(error.to_string().contains("canonical"), "{rejected}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- recording ----------
|
||||
|
||||
/// Passes the real CLI's stdio through, keeping what went over it.
|
||||
@@ -1350,3 +1429,58 @@ fn additional_directories_are_read_from_the_session_params() {
|
||||
assert_eq!(additional_dirs(¶ms), ["/w/web", "/w/docs"]);
|
||||
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_session_is_not_saved() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({ "cwd": h.cwd, "mcpServers": [], "_meta": { "openidea": { "ephemeral": true } } });
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"skills": {
|
||||
"claudeAddDir": "/tmp/farm-skills",
|
||||
"claudeSettings": "{\"skillOverrides\":{\"tdd\":\"user-invocable-only\"}}"
|
||||
},
|
||||
"memory": {
|
||||
"autoMemory": "readOnly",
|
||||
"claudeAutoMemory": false,
|
||||
"claudeMdExcludes": ["/repo/CLAUDE.local.md"],
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md",
|
||||
"claudeAddDir": "/tmp/farm-memory",
|
||||
"claudeAdditionalDirsClaudeMd": true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-memory"]), "{args:?}");
|
||||
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
|
||||
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
|
||||
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
|
||||
assert_eq!(parsed["autoMemoryEnabled"], false);
|
||||
assert_eq!(parsed["claudeMdExcludes"], json!(["/repo/CLAUDE.local.md"]));
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
}
|
||||
@@ -8,43 +8,80 @@ pub(crate) struct BuiltinCommandSpec {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub hint: Option<&'static str>,
|
||||
pub choices: &'static [(&'static str, &'static str)],
|
||||
}
|
||||
|
||||
pub(crate) const BUILTIN_COMMANDS: &[BuiltinCommandSpec] = &[
|
||||
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None },
|
||||
BuiltinCommandSpec { name: "plan", description: "Turn plan mode on or off.", hint: None, choices: &[] },
|
||||
BuiltinCommandSpec {
|
||||
name: "mcp",
|
||||
description: "Show the status of the MCP servers, or reconnect them.",
|
||||
hint: Some("[reconnect]"),
|
||||
choices: &[("reconnect", "Reload and reconnect MCP servers.")],
|
||||
},
|
||||
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None, choices: &[] },
|
||||
BuiltinCommandSpec {
|
||||
name: "memories",
|
||||
description: "Show, enable, disable, or reset cross-session Codex memories.",
|
||||
hint: Some("[show|on|off|reset]"),
|
||||
choices: &[
|
||||
("show", "Show consolidated memory summary for this thread."),
|
||||
("on", "Enable memory generation for this thread."),
|
||||
("off", "Disable memory generation for this thread."),
|
||||
("reset", "Clear local Codex memory files and summaries."),
|
||||
],
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "status",
|
||||
description: "Display session configuration and token usage.",
|
||||
hint: None,
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec { name: "skills", description: "List available skills.", hint: None },
|
||||
BuiltinCommandSpec { name: "status", description: "Display session configuration and token usage.", hint: None },
|
||||
BuiltinCommandSpec {
|
||||
name: "review",
|
||||
description: "Review uncommitted changes, or review with custom instructions.",
|
||||
hint: Some("optional review instructions"),
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "review-branch",
|
||||
description: "Review changes relative to a base branch.",
|
||||
hint: Some("branch name"),
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "review-commit",
|
||||
description: "Review a specific commit.",
|
||||
hint: Some("commit sha"),
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec { name: "review-commit", description: "Review a specific commit.", hint: Some("commit sha") },
|
||||
BuiltinCommandSpec {
|
||||
name: "compact",
|
||||
description: "Summarize conversation to avoid hitting the context limit.",
|
||||
hint: None,
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "goal",
|
||||
description: "Set a goal to keep pursuing.",
|
||||
hint: Some("[<objective>|clear|pause|resume]"),
|
||||
choices: &[
|
||||
("clear", "Clear the current goal."),
|
||||
("pause", "Pause the current goal."),
|
||||
("resume", "Resume a paused goal."),
|
||||
],
|
||||
},
|
||||
BuiltinCommandSpec {
|
||||
name: "rename",
|
||||
description: "Rename the current session.",
|
||||
hint: Some("new name"),
|
||||
choices: &[],
|
||||
},
|
||||
BuiltinCommandSpec { name: "rename", description: "Rename the current session.", hint: Some("new name") },
|
||||
BuiltinCommandSpec {
|
||||
name: "logout",
|
||||
description: "Sign out of Codex. This option is available when you are logged in via ChatGPT.",
|
||||
hint: None,
|
||||
choices: &[],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -53,6 +90,7 @@ pub(super) enum BuiltinCommand {
|
||||
Plan,
|
||||
Mcp,
|
||||
Skills,
|
||||
Memories,
|
||||
Status,
|
||||
Review,
|
||||
ReviewBranch,
|
||||
@@ -69,6 +107,7 @@ impl BuiltinCommand {
|
||||
"plan" => Self::Plan,
|
||||
"mcp" => Self::Mcp,
|
||||
"skills" => Self::Skills,
|
||||
"memories" => Self::Memories,
|
||||
"status" => Self::Status,
|
||||
"review" => Self::Review,
|
||||
"review-branch" => Self::ReviewBranch,
|
||||
@@ -124,6 +163,7 @@ mod tests {
|
||||
"plan",
|
||||
"mcp",
|
||||
"skills",
|
||||
"memories",
|
||||
"status",
|
||||
"review",
|
||||
"review-branch",
|
||||
|
||||
@@ -14,7 +14,7 @@ mod tests;
|
||||
use super::Shim;
|
||||
use crate::acp::AUTH_REQUIRED;
|
||||
use crate::provider::ProviderSpec;
|
||||
use crate::{AgentCommand, AgentCommandSource};
|
||||
use crate::{AgentCommand, AgentCommandChoice, AgentCommandSource};
|
||||
use commands::{BuiltinCommand, ParsedCommand};
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
|
||||
use parking_lot::Mutex;
|
||||
@@ -47,6 +47,14 @@ pub(crate) fn builtin_commands() -> Vec<AgentCommand> {
|
||||
description: command.description.to_owned(),
|
||||
hint: command.hint.map(str::to_owned),
|
||||
source: AgentCommandSource::Command,
|
||||
choices: command
|
||||
.choices
|
||||
.iter()
|
||||
.map(|(name, description)| AgentCommandChoice {
|
||||
name: (*name).to_owned(),
|
||||
description: (*description).to_owned(),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -108,7 +116,7 @@ pub(crate) async fn discover(
|
||||
let options = translate::config_options(&models, &settings);
|
||||
let levels = crate::config::options_of(&json!({ "configOptions": options }))
|
||||
.into_iter()
|
||||
.filter(|o| o.category.as_deref() == Some("thought_level"))
|
||||
.filter(|o| matches!(o.category.as_deref(), Some("thought_level" | "model_config")))
|
||||
.collect();
|
||||
(model.id.clone(), levels)
|
||||
})
|
||||
@@ -354,6 +362,23 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
|
||||
{
|
||||
map.insert("skills".into(), json!({ "config": off }));
|
||||
}
|
||||
if let Some(mem) = params.pointer("/_meta/openidea/memory")
|
||||
&& let Some(map) = config.as_object_mut()
|
||||
{
|
||||
let mut mem_cfg = serde_json::Map::new();
|
||||
if let Some(use_m) = mem.get("codexUseMemories").and_then(Value::as_bool) {
|
||||
mem_cfg.insert("use_memories".into(), json!(use_m));
|
||||
}
|
||||
if let Some(gen_m) = mem.get("codexGenerateMemories").and_then(Value::as_bool) {
|
||||
mem_cfg.insert("generate_memories".into(), json!(gen_m));
|
||||
}
|
||||
if !mem_cfg.is_empty() {
|
||||
map.insert("memories".into(), Value::Object(mem_cfg));
|
||||
}
|
||||
if let Some(dev) = mem.get("codexDeveloperInstructions").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
map.insert("developer_instructions".into(), json!(dev));
|
||||
}
|
||||
}
|
||||
if !config.as_object().is_some_and(|m| m.is_empty()) {
|
||||
request["config"] = config;
|
||||
}
|
||||
@@ -492,8 +517,14 @@ impl CodexShim {
|
||||
self.prepare_project_trust(params).await;
|
||||
let mut request = json!({ "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
// Not written to `~/.codex/sessions`, so it isn't listed among the past threads.
|
||||
if params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool) == Some(true) {
|
||||
request["ephemeral"] = json!(true);
|
||||
}
|
||||
let result = self.call("thread/start", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, None);
|
||||
let mut settings = Settings::of(&result, &models);
|
||||
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
|
||||
let (id, options) = self.open_thread(&result, &models, Some(settings));
|
||||
if id.is_empty() {
|
||||
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
|
||||
}
|
||||
@@ -510,7 +541,9 @@ impl CodexShim {
|
||||
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
|
||||
apply_thread_config(params, &mut request);
|
||||
let result = self.call("thread/resume", request).await?;
|
||||
let (_, options) = self.open_thread(&result, &models, None);
|
||||
let mut settings = Settings::of(&result, &models);
|
||||
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
|
||||
let (_, options) = self.open_thread(&result, &models, Some(settings));
|
||||
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
|
||||
let thread = result.get("thread").unwrap_or(&Value::Null);
|
||||
for update in translate::history(thread, cwd.as_deref()) {
|
||||
@@ -613,6 +646,9 @@ impl CodexShim {
|
||||
if let Some(effort) = &s.effort {
|
||||
request["effort"] = json!(effort);
|
||||
}
|
||||
if let Some(tier) = s.service_tier_override(&models) {
|
||||
request["serviceTier"] = json!(tier);
|
||||
}
|
||||
}
|
||||
self.call("turn/start", request).await
|
||||
}
|
||||
@@ -689,6 +725,7 @@ impl CodexShim {
|
||||
let found = self.call("skills/list", json!({ "cwds": [cwd] })).await?;
|
||||
self.say(session, skills_text(&found));
|
||||
}
|
||||
BuiltinCommand::Memories => self.memories_command(session, &command.rest).await?,
|
||||
BuiltinCommand::Mcp => match command.rest.as_str() {
|
||||
"" => self.say(session, self.mcp_text(session).await?),
|
||||
rest if rest.eq_ignore_ascii_case("reconnect") => {
|
||||
@@ -728,6 +765,36 @@ impl CodexShim {
|
||||
Ok(json!({ "stopReason": "end_turn" }))
|
||||
}
|
||||
|
||||
async fn memories_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
|
||||
let arg = rest.trim().to_ascii_lowercase();
|
||||
match arg.as_str() {
|
||||
"" | "show" => {
|
||||
let res = self.call("thread/memory/read", json!({ "threadId": session })).await?;
|
||||
let summary = res
|
||||
.get("summary")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or("No consolidated memories for this thread yet.");
|
||||
self.say(session, summary);
|
||||
}
|
||||
"on" => {
|
||||
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "enabled" })).await?;
|
||||
self.say(session, "Memory generation enabled for this thread.");
|
||||
}
|
||||
"off" => {
|
||||
self.call("thread/memoryMode/set", json!({ "threadId": session, "mode": "disabled" })).await?;
|
||||
self.say(session, "Memory generation disabled for this thread.");
|
||||
}
|
||||
"reset" => {
|
||||
self.call("memory/reset", Value::Null).await?;
|
||||
self.say(session, "Reset local Codex memories.");
|
||||
}
|
||||
_ => self.say(session, command_usage(BuiltinCommand::Memories)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn goal_command(&self, session: &str, rest: &str) -> Result<(), ResponseError> {
|
||||
let argument = rest.trim();
|
||||
if argument.is_empty() {
|
||||
@@ -1470,14 +1537,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
|
||||
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
|
||||
let message = translate::error_message(&e);
|
||||
return match translate::classify(&e, rate_limits) {
|
||||
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
|
||||
Failure::UsageLimit(resets) => Err(ResponseError {
|
||||
code: codes::INTERNAL_ERROR,
|
||||
message,
|
||||
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
|
||||
}),
|
||||
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
|
||||
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
};
|
||||
}
|
||||
_ => "end_turn",
|
||||
@@ -1500,6 +1566,7 @@ fn command_usage(command: BuiltinCommand) -> String {
|
||||
match command {
|
||||
BuiltinCommand::Plan => "Command \"/plan\" accepts no arguments.".to_owned(),
|
||||
BuiltinCommand::Mcp => "Command \"/mcp\" accepts no arguments, or `reconnect`.".to_owned(),
|
||||
BuiltinCommand::Memories => "Command \"/memories\" accepts `[show|on|off|reset]`.".to_owned(),
|
||||
BuiltinCommand::ReviewBranch => "Command \"/review-branch\" requires branch name.".to_owned(),
|
||||
BuiltinCommand::ReviewCommit => "Command \"/review-commit\" requires commit sha.".to_owned(),
|
||||
BuiltinCommand::Goal => "Command \"/goal\" requires [<objective>|clear|pause|resume].".to_owned(),
|
||||
@@ -1595,3 +1662,6 @@ fn mcp_text(response: &Value) -> String {
|
||||
.collect::<Vec<_>>();
|
||||
format!("MCP servers:\n{}", lines.join("\n"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod reconnect_tests;
|
||||
@@ -0,0 +1,217 @@
|
||||
//! User-facing task operations through the native shim, with a local app-server stand-in.
|
||||
use super::*;
|
||||
use crate::{AgentManager, AgentPrompt, AgentStatus, Isolation, NewAgentTask};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Runtime {
|
||||
models: Mutex<HashMap<String, String>>,
|
||||
hide_a: std::sync::atomic::AtomicBool,
|
||||
turns: Mutex<Vec<Value>>,
|
||||
tiers: Mutex<HashMap<String, Value>>,
|
||||
servers: Mutex<Vec<Peer>>,
|
||||
}
|
||||
struct Connection {
|
||||
runtime: Arc<Runtime>,
|
||||
peer: OnceLock<Peer>,
|
||||
}
|
||||
impl Handler for Connection {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
fn on_request(&self, method: &str, p: Value) -> Result<Value, (i64, String)> {
|
||||
match method {
|
||||
"initialize" => Ok(json!({})),
|
||||
"model/list" => {
|
||||
let mut data = vec![json!({"id":"b", "model":"b", "serviceTiers":[]})];
|
||||
if !self.runtime.hide_a.swap(false, std::sync::atomic::Ordering::SeqCst) {
|
||||
data.insert(0, json!({"id":"a", "model":"a", "isDefault":true, "serviceTiers":[{"id":"fast"}]}));
|
||||
}
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
"config/read" => Ok(json!({"layers":[]})),
|
||||
"skills/list" => Ok(json!({"data":[]})),
|
||||
"thread/start" | "thread/resume" => {
|
||||
let mut models = self.runtime.models.lock();
|
||||
let id = p["threadId"].as_str().map(str::to_owned).unwrap_or_else(|| format!("s{}", models.len()));
|
||||
let model = models.entry(id.clone()).or_insert_with(|| "a".into()).clone();
|
||||
Ok(json!({"thread":{"id":id,"name":"fixture","turns":[]}, "model":model,
|
||||
"serviceTier":self.runtime.tiers.lock().get(&id).cloned().unwrap_or(json!("fast"))}))
|
||||
}
|
||||
"turn/start" => {
|
||||
let id = p["threadId"].as_str().unwrap();
|
||||
self.runtime.models.lock().insert(id.into(), p["model"].as_str().unwrap().into());
|
||||
if let Some(tier) = p.get("serviceTier") {
|
||||
self.runtime.tiers.lock().insert(id.into(), tier.clone());
|
||||
}
|
||||
self.runtime.turns.lock().push(p.clone());
|
||||
self.peer
|
||||
.get()
|
||||
.unwrap()
|
||||
.notify(
|
||||
"turn/completed",
|
||||
json!({"threadId":id,
|
||||
"turn":{"id":"t","status":"completed"}}),
|
||||
)
|
||||
.unwrap();
|
||||
Ok(json!({"turn":{"id":"t"}}))
|
||||
}
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn manager(dir: &Path, runtime: Arc<Runtime>) -> AgentManager {
|
||||
let agents = dir.join("agents");
|
||||
crate::provider::set_builtin_command(&agents, None, "codex", Some("/missing/fixture-codex")).unwrap();
|
||||
AgentManager::with_connector(
|
||||
crate::AgentPaths {
|
||||
project_root: dir.into(),
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
custom_agents_dir: Some(agents),
|
||||
home_dir: Some(dir.into()),
|
||||
env_secrets: None,
|
||||
catalogs: Arc::default(),
|
||||
},
|
||||
tokio::runtime::Handle::current(),
|
||||
Arc::new(move |spec, _, client, _| {
|
||||
assert_eq!(spec.driver, crate::provider::Driver::Codex);
|
||||
let handler = Arc::new(Connection { runtime: runtime.clone(), peer: OnceLock::new() });
|
||||
let (a, b) = tokio::io::duplex(1 << 20);
|
||||
let (r, w) = tokio::io::split(b);
|
||||
let server = Peer::connect_framed(r, w, handler.clone(), Framing::Lines);
|
||||
handler.peer.set(server.clone()).ok().unwrap();
|
||||
runtime.servers.lock().push(server);
|
||||
attach(client, |events| {
|
||||
let (r, w) = tokio::io::split(a);
|
||||
Ok(Peer::connect_framed(r, w, events, Framing::Lines))
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
fn prompt() -> AgentPrompt {
|
||||
AgentPrompt { text: "fixture".into(), ..Default::default() }
|
||||
}
|
||||
async fn ready(mgr: &AgentManager, id: &str) {
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
let task = mgr.task(id).unwrap();
|
||||
let (status, busy) = {
|
||||
let s = task.state.lock();
|
||||
(s.task.status, s.busy)
|
||||
};
|
||||
assert_ne!(status, AgentStatus::Failed);
|
||||
if status == AgentStatus::Ready && !busy {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
async fn send(mgr: &AgentManager, id: &str) {
|
||||
mgr.prompt(id, prompt(), false).await.unwrap();
|
||||
ready(mgr, id).await;
|
||||
}
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn explicit_tier_survives_standard_only_reconnect_before_immediate_prompt() {
|
||||
for late_model in [0, 1, 2, 3] {
|
||||
for choice in [Some("true"), Some("false"), None] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let runtime = Arc::new(Runtime::default());
|
||||
let mgr = manager(tmp.path(), runtime.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "codex".into(),
|
||||
prompt: prompt(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
ready(&mgr, &task.id).await;
|
||||
let catalog_config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
|
||||
if let Some(value) = choice {
|
||||
mgr.set_config(&task.id, "service_tier", value.into()).await.unwrap();
|
||||
}
|
||||
send(&mgr, &task.id).await;
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
|
||||
);
|
||||
mgr.set_config(&task.id, "model", "b".into()).await.unwrap();
|
||||
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
|
||||
send(&mgr, &task.id).await;
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|_| json!("default")).as_ref()
|
||||
);
|
||||
mgr.shutdown();
|
||||
drop(mgr);
|
||||
runtime.hide_a.store(late_model >= 2, std::sync::atomic::Ordering::SeqCst);
|
||||
let mut mgr = manager(tmp.path(), runtime.clone());
|
||||
send(&mgr, &task.id).await; // Reconnect while still on Standard-only B.
|
||||
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|_| json!("default")).as_ref()
|
||||
);
|
||||
if late_model != 0 {
|
||||
// Catalog knows A, but the session's picker has not received it yet.
|
||||
let current = mgr.task(&task.id).unwrap();
|
||||
let mut s = current.state.lock();
|
||||
let catalog = serde_json::from_value(
|
||||
json!({"fingerprint":"fixture", "schema":2, "config":catalog_config, "thoughtLevels":{"a":catalog_config.iter().filter(|o|crate::config::is_per_model_option(o)).collect::<Vec<_>>() }}),
|
||||
)
|
||||
.unwrap();
|
||||
mgr.shared
|
||||
.known
|
||||
.lock()
|
||||
.entry("codex".into())
|
||||
.or_default()
|
||||
.catalogs
|
||||
.insert(mgr.shared.root_key(), catalog);
|
||||
s.task.config.iter_mut().find(|o| o.id == "model").unwrap().values.retain(|v| v.value != "a");
|
||||
}
|
||||
mgr.set_config(&task.id, "model", "a".into()).await.unwrap();
|
||||
if late_model == 3 {
|
||||
// An older saved pending switch has no retained intent field.
|
||||
mgr.task(&task.id).unwrap().state.lock().pending_model.as_mut().unwrap().retained_service_tier = None;
|
||||
mgr.shutdown();
|
||||
mgr = manager(tmp.path(), runtime.clone());
|
||||
}
|
||||
let displayed = mgr
|
||||
.task(&task.id)
|
||||
.unwrap()
|
||||
.state
|
||||
.lock()
|
||||
.snapshot()
|
||||
.config
|
||||
.iter()
|
||||
.find(|o| o.id == "service_tier")
|
||||
.unwrap()
|
||||
.current
|
||||
.clone();
|
||||
assert_eq!(displayed.as_deref(), Some(choice.unwrap_or("true")));
|
||||
send(&mgr, &task.id).await; // No sleeps/retries between selecting A and submitting.
|
||||
assert_eq!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier"),
|
||||
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
|
||||
);
|
||||
let other = mgr
|
||||
.create(NewAgentTask {
|
||||
provider: "codex".into(),
|
||||
prompt: prompt(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
ready(&mgr, &other.id).await;
|
||||
assert!(
|
||||
runtime.turns.lock().last().unwrap().get("serviceTier").is_none(),
|
||||
"choices must not leak to another task"
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,7 +110,8 @@ for line in sys.stdin:
|
||||
cursor = request['params']['cursor']
|
||||
model = 'one' if cursor is None else 'two'
|
||||
result = {'data': [{'id': model, 'isDefault': cursor is None,
|
||||
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}]}],
|
||||
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}],
|
||||
'serviceTiers': [{'id': 'fast', 'name': 'Fast', 'description': ''}] if cursor is None else []}],
|
||||
'nextCursor': 'second-page' if cursor is None else None}
|
||||
else:
|
||||
raise RuntimeError('must not create a thread or prompt: ' + method)
|
||||
@@ -125,6 +126,7 @@ for line in sys.stdin:
|
||||
driver: crate::provider::Driver::Codex,
|
||||
command: script.to_string_lossy().into_owned(),
|
||||
args: Vec::new(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: String::new(),
|
||||
source: crate::AgentSource::Builtin,
|
||||
@@ -138,6 +140,9 @@ for line in sys.stdin:
|
||||
.collect();
|
||||
assert_eq!(models, ["one", "two"]);
|
||||
assert_eq!(found.levels.keys().map(String::as_str).collect::<Vec<_>>(), ["one", "two"]);
|
||||
assert!(found.config.iter().any(|o| o.id == SERVICE_TIER));
|
||||
assert!(found.levels["one"].iter().any(|o| o.id == SERVICE_TIER));
|
||||
assert!(found.levels["two"].iter().all(|o| o.id != SERVICE_TIER));
|
||||
let requests = std::fs::read_to_string(tmp.path().join("requests")).unwrap();
|
||||
let requests: Vec<Value> = requests.lines().map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(
|
||||
@@ -162,6 +167,72 @@ for line in sys.stdin:
|
||||
|
||||
// ---- Pure translations -------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn fast_is_offered_only_when_the_model_advertises_it() {
|
||||
for capability in [
|
||||
json!({ "additionalSpeedTiers": ["fast"] }),
|
||||
json!({ "serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }] }),
|
||||
json!({ "serviceTiers": [{ "id": "priority", "name": "Fast", "description": "" }] }),
|
||||
] {
|
||||
let mut model = json!({ "id": "supported", "isDefault": true });
|
||||
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
|
||||
let models = models_of(&json!({ "data": [model, { "id": "unsupported" }] }));
|
||||
let mut settings = Settings::of(&json!({}), &models);
|
||||
let options = config_options(&models, &settings);
|
||||
let fast = options.as_array().unwrap().iter().find(|o| o["id"] == "service_tier").expect("Fast option");
|
||||
assert_eq!(fast["category"], "model_config");
|
||||
assert_eq!(fast["currentValue"], "false");
|
||||
assert!(settings.set(&models, "service_tier", "true").is_ok());
|
||||
assert!(settings.set(&models, "service_tier", "invalid").is_err());
|
||||
let selected = settings.service_tier_override(&models).map(str::to_owned);
|
||||
settings.set(&models, "model", "unsupported").unwrap();
|
||||
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
|
||||
assert!(settings.set(&models, "service_tier", "true").is_err());
|
||||
assert_eq!(settings.service_tier_override(&models), Some("default"));
|
||||
settings.set(&models, "model", "supported").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), selected.as_deref());
|
||||
let options = config_options(&models, &settings);
|
||||
assert_eq!(
|
||||
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
|
||||
"true"
|
||||
);
|
||||
}
|
||||
for capability in [json!({}), json!({ "additionalSpeedTiers": [] }), json!({ "serviceTiers": [] })] {
|
||||
let mut model = json!({ "id": "old", "isDefault": true });
|
||||
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
|
||||
let models = models_of(&json!({ "data": [model] }));
|
||||
let settings = Settings::of(&json!({}), &models);
|
||||
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_defaults_do_not_become_user_overrides() {
|
||||
let models = models_of(&json!({ "data": [{
|
||||
"id": "m", "isDefault": true, "defaultServiceTier": "fast",
|
||||
"serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }]
|
||||
}] }));
|
||||
for (reported, current) in [
|
||||
(json!({}), "true"),
|
||||
(json!({ "serviceTier": null }), "false"),
|
||||
(json!({ "serviceTier": "fast" }), "true"),
|
||||
(json!({ "serviceTier": "priority" }), "true"),
|
||||
(json!({ "serviceTier": "default" }), "false"),
|
||||
] {
|
||||
let mut settings = Settings::of(&reported, &models);
|
||||
let options = config_options(&models, &settings);
|
||||
assert_eq!(
|
||||
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
|
||||
current
|
||||
);
|
||||
assert_eq!(settings.service_tier_override(&models), None);
|
||||
settings.set(&models, SERVICE_TIER, "true").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), Some("fast"));
|
||||
settings.set(&models, SERVICE_TIER, "false").unwrap();
|
||||
assert_eq!(settings.service_tier_override(&models), Some("default"));
|
||||
}
|
||||
}
|
||||
|
||||
fn models() -> Vec<ModelInfo> {
|
||||
models_of(&json!({"data": [
|
||||
{"id": "big", "model": "big", "displayName": "Big", "description": "d", "hidden": false, "isDefault": true,
|
||||
@@ -185,6 +256,8 @@ fn settings_follow_the_thread_and_the_models() {
|
||||
Settings {
|
||||
model: "big".into(),
|
||||
effort: Some("low".into()),
|
||||
service_tier: None,
|
||||
fast_override: None,
|
||||
mode: Mode::Ask,
|
||||
collaboration_mode: DEFAULT_COLLABORATION_MODE.into(),
|
||||
collaboration_mode_override: None,
|
||||
@@ -382,6 +455,90 @@ fn failures_are_classified() {
|
||||
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turns_preserve_codex_error_diagnostics() {
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
|
||||
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
|
||||
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
|
||||
assert_eq!(failure.code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
// A completed turn's own error wins over an older error notification.
|
||||
let failure = stop_reason(
|
||||
&json!({ "status": "failed", "error": policy }),
|
||||
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
|
||||
for (value, expected) in [
|
||||
(
|
||||
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
|
||||
"Context is full.\nCodex error: contextWindowExceeded",
|
||||
),
|
||||
(
|
||||
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
|
||||
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
|
||||
),
|
||||
(
|
||||
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
|
||||
"Failed\nbecause",
|
||||
),
|
||||
(
|
||||
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
|
||||
"Codex failed\nDetails\nCodex error: cyberPolicy",
|
||||
),
|
||||
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
|
||||
(json!({}), "Codex failed"),
|
||||
] {
|
||||
assert_eq!(error_message(&value), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
|
||||
for notification_only in [false, true] {
|
||||
let mut transcript = load(Scenario::UsageLimit.file());
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
match frame["method"].as_str() {
|
||||
Some("error") => frame["params"]["error"] = policy.clone(),
|
||||
Some("turn/completed") => {
|
||||
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
|
||||
match result(&results, "prompt") {
|
||||
Err(RpcError::Server { code, message, .. }) => {
|
||||
assert_eq!(*code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(
|
||||
message,
|
||||
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
|
||||
);
|
||||
}
|
||||
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approvals_offer_what_codex_offers_and_always_a_decline() {
|
||||
let params = json!({"availableDecisions": ["accept",
|
||||
@@ -648,6 +805,7 @@ enum Scenario {
|
||||
Steer,
|
||||
Simple,
|
||||
MultiTurn,
|
||||
ServiceTier { first: Option<bool>, second: Option<bool> },
|
||||
Approvals,
|
||||
UsageLimit,
|
||||
Subagent,
|
||||
@@ -666,6 +824,7 @@ impl Scenario {
|
||||
Scenario::Steer => "steer",
|
||||
Scenario::Simple => "simple",
|
||||
Scenario::MultiTurn => "multi_turn",
|
||||
Scenario::ServiceTier { .. } => "multi_turn",
|
||||
Scenario::Approvals => "approvals",
|
||||
Scenario::UsageLimit => "usage_limit",
|
||||
Scenario::Subagent => "subagent",
|
||||
@@ -772,6 +931,16 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa
|
||||
out.push(("effort", request(acp, "session/set_config_option", set(EFFORT, "high")).await));
|
||||
out.push(("second", request(acp, "session/prompt", prompt("Reply with: two")).await));
|
||||
}
|
||||
Scenario::ServiceTier { first, second } => {
|
||||
for (label, choice) in [("first", first), ("second", second)] {
|
||||
if let Some(fast) = choice {
|
||||
request(acp, "session/set_config_option", set(SERVICE_TIER, if fast { "true" } else { "false" }))
|
||||
.await
|
||||
.expect("the model advertises Fast");
|
||||
}
|
||||
out.push((label, request(acp, "session/prompt", prompt("Reply with: hi")).await));
|
||||
}
|
||||
}
|
||||
Scenario::Approvals => {
|
||||
client.answers.lock().extend([Some("accept"), None]);
|
||||
out.push(("prompt", request(acp, "session/prompt", prompt("Run `touch b.txt`, then write a.txt.")).await));
|
||||
@@ -1304,6 +1473,44 @@ fn thread_names_are_the_first_line_of_the_reply() {
|
||||
assert_eq!(thread_name(&"x".repeat(100)).map(|n| n.chars().count()), Some(80));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fast_selection_reaches_the_first_and_next_turn_and_standard_clears_it() {
|
||||
for (first, second, expected) in [
|
||||
(Some(true), Some(false), [Some("fast"), Some("default")]),
|
||||
(Some(false), Some(true), [Some("default"), Some("fast")]),
|
||||
(Some(true), None, [Some("fast"), Some("fast")]),
|
||||
(None, None, [None, None]),
|
||||
] {
|
||||
let scenario = Scenario::ServiceTier { first, second };
|
||||
let mut transcript = load(scenario.file());
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
if let Some(models) = frame.pointer_mut("/result/data").and_then(Value::as_array_mut) {
|
||||
for model in models {
|
||||
model["serviceTiers"] = json!([{ "id": "fast", "name": "Fast", "description": "" }]);
|
||||
model["defaultServiceTier"] = json!("fast");
|
||||
}
|
||||
}
|
||||
if frame.pointer("/result/thread").is_some() {
|
||||
frame["result"]["serviceTier"] = json!("fast");
|
||||
}
|
||||
}
|
||||
let (results, _client, frames, _meta, _codex) = replay_transcript(scenario, transcript).await;
|
||||
assert!(result(&results, "first").is_ok());
|
||||
assert!(result(&results, "second").is_ok());
|
||||
let starts = sent(&frames, "turn/start");
|
||||
assert_eq!(starts.len(), 2);
|
||||
for (start, expected) in starts.iter().zip(expected) {
|
||||
assert_eq!(start["params"].get("serviceTier"), expected.map(|value| json!(value)).as_ref());
|
||||
assert!(start["params"].get("serviceTierForTurn").is_none());
|
||||
}
|
||||
assert!(sent(&frames, "turn/settings/update").is_empty());
|
||||
assert!(sent(&frames, "config/value/write").is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn settings_apply_to_the_next_turn() {
|
||||
let (results, client, frames, _) = replay(Scenario::MultiTurn).await;
|
||||
@@ -1488,6 +1695,57 @@ async fn goal_commands_set_pause_resume_and_clear_through_app_server() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn memories_commands_read_toggle_and_reset_through_app_server() {
|
||||
for (prompt, method, has_thread_id, expected_params, result, expected_text) in [
|
||||
(
|
||||
"/memories",
|
||||
"thread/memory/read",
|
||||
true,
|
||||
json!({ "threadId": "s" }),
|
||||
json!({ "summary": "Remembered: run targeted tests first." }),
|
||||
"Remembered: run targeted tests first.",
|
||||
),
|
||||
(
|
||||
"/memories show",
|
||||
"thread/memory/read",
|
||||
true,
|
||||
json!({ "threadId": "s" }),
|
||||
json!({ "summary": null }),
|
||||
"No consolidated memories for this thread yet.",
|
||||
),
|
||||
(
|
||||
"/memories on",
|
||||
"thread/memoryMode/set",
|
||||
true,
|
||||
json!({ "threadId": "s", "mode": "enabled" }),
|
||||
json!({}),
|
||||
"Memory generation enabled for this thread.",
|
||||
),
|
||||
(
|
||||
"/memories off",
|
||||
"thread/memoryMode/set",
|
||||
true,
|
||||
json!({ "threadId": "s", "mode": "disabled" }),
|
||||
json!({}),
|
||||
"Memory generation disabled for this thread.",
|
||||
),
|
||||
("/memories reset", "memory/reset", false, Value::Null, json!({}), "Reset local Codex memories."),
|
||||
] {
|
||||
let (results, client, frames, _meta, _codex) =
|
||||
replay_transcript(Scenario::Command(prompt), command_transcript(&[(method, result)])).await;
|
||||
let session = session_of(&results, "new");
|
||||
let sent = sent(&frames, method);
|
||||
assert_eq!(sent.len(), 1, "{prompt}");
|
||||
let mut expected = expected_params;
|
||||
if has_thread_id {
|
||||
expected["threadId"] = json!(session);
|
||||
assert_eq!(sent[0]["params"], expected, "{prompt}");
|
||||
}
|
||||
assert_eq!(client.text(&session, "agent_message_chunk"), expected_text, "{prompt}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn missing_review_arguments_print_usage_without_starting_a_turn() {
|
||||
for prompt in ["/review-branch", "/review-commit", "/rename", "/goal"] {
|
||||
@@ -1877,6 +2135,13 @@ fn skills_become_commands_with_their_invocation_names() {
|
||||
let commands = crate::config::commands_of(&update, "codex");
|
||||
assert!(commands.iter().all(|c| c.source == crate::AgentCommandSource::Skill));
|
||||
assert_eq!(commands[0].name, "$review");
|
||||
let builtins = builtin_commands();
|
||||
let goal = builtins.iter().find(|c| c.name == "goal").unwrap();
|
||||
assert_eq!(goal.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["clear", "pause", "resume"]);
|
||||
let memories = builtins.iter().find(|c| c.name == "memories").unwrap();
|
||||
assert_eq!(memories.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["show", "on", "off", "reset"]);
|
||||
let mcp = builtins.iter().find(|c| c.name == "mcp").unwrap();
|
||||
assert_eq!(mcp.choices.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["reconnect"]);
|
||||
assert!(skill_commands(&json!({"data": []})).unwrap()["availableCommands"].as_array().unwrap().is_empty());
|
||||
assert!(skill_commands(&json!({})).is_none());
|
||||
}
|
||||
@@ -1890,4 +2155,63 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
let mut request = json!({});
|
||||
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
|
||||
assert!(request.get("runtimeWorkspaceRoots").is_none());
|
||||
|
||||
let mut mem_req = json!({});
|
||||
apply_thread_config(
|
||||
&json!({
|
||||
"cwd": "/w/api",
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"skills": { "codexOff": [["noisy", "/repo/.agents/skills/noisy/SKILL.md"]] },
|
||||
"memory": {
|
||||
"codexUseMemories": true,
|
||||
"codexGenerateMemories": false,
|
||||
"codexDeveloperInstructions": "## Memory (style)\nUse targeted selectors."
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
&mut mem_req,
|
||||
);
|
||||
assert_eq!(mem_req["config"]["memories"], json!({ "use_memories": true, "generate_memories": false }));
|
||||
assert_eq!(mem_req["config"]["developer_instructions"], "## Memory (style)\nUse targeted selectors.");
|
||||
assert_eq!(mem_req["config"]["skills"]["config"][0]["enabled"], false);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_ephemeral_session_starts_an_ephemeral_thread() {
|
||||
for ephemeral in [true, false] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cwd = tmp.path().to_string_lossy().into_owned();
|
||||
let server = Arc::new(TrustServer {
|
||||
cwd: cwd.clone(),
|
||||
disabled: false,
|
||||
other_project: false,
|
||||
write_error: false,
|
||||
overridden: false,
|
||||
calls: Mutex::default(),
|
||||
});
|
||||
let client = Arc::new(Client::default());
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
|
||||
let acp = attach(client.clone(), |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
request(&acp, "initialize", json!({})).await.unwrap();
|
||||
let mut params = json!({"cwd": cwd, "mcpServers": []});
|
||||
if ephemeral {
|
||||
params["_meta"] = json!({"openidea": {"ephemeral": true}});
|
||||
}
|
||||
request(&acp, "session/new", params).await.unwrap();
|
||||
let calls = server.calls.lock();
|
||||
let (_, start) = calls.iter().find(|(m, _)| m == "thread/start").unwrap();
|
||||
assert_eq!(start.get("ephemeral"), ephemeral.then_some(&Value::Bool(true)), "{start}");
|
||||
drop(calls);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,8 @@ pub(super) struct ModelInfo {
|
||||
/// `(effort, description)`.
|
||||
pub efforts: Vec<(String, String)>,
|
||||
pub default_effort: Option<String>,
|
||||
pub fast_tier: Option<String>,
|
||||
pub default_service_tier: Option<String>,
|
||||
pub is_default: bool,
|
||||
pub hidden: bool,
|
||||
}
|
||||
@@ -123,6 +125,22 @@ pub(super) fn models_of(list: &Value) -> Vec<ModelInfo> {
|
||||
})
|
||||
.collect(),
|
||||
default_effort: str_of(m, "defaultReasoningEffort"),
|
||||
fast_tier: m
|
||||
.get("serviceTiers")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|tier| tier.get("id").and_then(Value::as_str))
|
||||
.chain(
|
||||
m.get("additionalSpeedTiers")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str),
|
||||
)
|
||||
.find(|tier| is_fast_tier(tier))
|
||||
.map(str::to_owned),
|
||||
default_service_tier: str_of(m, "defaultServiceTier"),
|
||||
is_default: m.get("isDefault").and_then(Value::as_bool) == Some(true),
|
||||
hidden: m.get("hidden").and_then(Value::as_bool) == Some(true),
|
||||
id,
|
||||
@@ -137,6 +155,9 @@ pub(super) struct Settings {
|
||||
/// A model id from `model/list`, or the one the thread reported.
|
||||
pub model: String,
|
||||
pub effort: Option<String>,
|
||||
pub service_tier: Option<String>,
|
||||
/// No choice preserves the runtime's default; false explicitly selects Standard.
|
||||
pub fast_override: Option<bool>,
|
||||
pub mode: Mode,
|
||||
/// Codex's Default/Plan collaboration mode. It is sent with each turn because it is
|
||||
/// part of the turn contract rather than the sandbox permission mode above.
|
||||
@@ -158,6 +179,12 @@ impl Settings {
|
||||
let mut s = Settings {
|
||||
model,
|
||||
effort: str_of(result, "reasoningEffort"),
|
||||
service_tier: match result.get("serviceTier") {
|
||||
// A live thread can explicitly report Standard even when the catalog defaults to Fast.
|
||||
Some(Value::Null) => Some("default".into()),
|
||||
_ => str_of(result, "serviceTier"),
|
||||
},
|
||||
fast_override: None,
|
||||
mode: Mode::of(
|
||||
result.get("approvalPolicy").unwrap_or(&Value::Null),
|
||||
result.get("sandbox").unwrap_or(&Value::Null),
|
||||
@@ -205,6 +232,16 @@ impl Settings {
|
||||
}
|
||||
self.effort = Some(value.to_owned());
|
||||
}
|
||||
SERVICE_TIER => {
|
||||
if !models.iter().any(|m| m.id == self.model && m.fast_tier.is_some()) {
|
||||
return Err(format!("{} has no Fast mode", self.model));
|
||||
}
|
||||
self.fast_override = Some(match value {
|
||||
"true" => true,
|
||||
"false" => false,
|
||||
_ => return Err(format!("unknown Fast mode {value}")),
|
||||
});
|
||||
}
|
||||
MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?,
|
||||
COLLABORATION_MODE => {
|
||||
if !matches!(value, DEFAULT_COLLABORATION_MODE | PLAN_COLLABORATION_MODE) {
|
||||
@@ -217,16 +254,32 @@ impl Settings {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `turn/start.serviceTier`: omission inherits; "default" explicitly resets Fast.
|
||||
pub fn service_tier_override<'a>(&self, models: &'a [ModelInfo]) -> Option<&'a str> {
|
||||
match self.fast_override {
|
||||
Some(true) => Some(
|
||||
models.iter().find(|m| m.id == self.model).and_then(|m| m.fast_tier.as_deref()).unwrap_or("default"),
|
||||
),
|
||||
Some(false) => Some("default"),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const MODEL: &str = "model";
|
||||
pub(super) const EFFORT: &str = "reasoning_effort";
|
||||
pub(super) const SERVICE_TIER: &str = "service_tier";
|
||||
pub(super) const MODE: &str = "mode";
|
||||
pub(super) const COLLABORATION_MODE: &str = "collaboration_mode";
|
||||
pub(super) const DEFAULT_COLLABORATION_MODE: &str = "default";
|
||||
pub(super) const PLAN_COLLABORATION_MODE: &str = "plan";
|
||||
|
||||
/// ACP `configOptions`: model, reasoning effort (for models that have it) and mode.
|
||||
fn is_fast_tier(tier: &str) -> bool {
|
||||
matches!(tier, "fast" | "priority")
|
||||
}
|
||||
|
||||
/// ACP `configOptions`: model, its supported settings and session modes.
|
||||
pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
let mut model_values: Vec<Value> = models
|
||||
.iter()
|
||||
@@ -253,6 +306,16 @@ pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
|
||||
"currentValue": effort, "options": values,
|
||||
}));
|
||||
}
|
||||
if let Some(model) = models.iter().find(|m| m.id == s.model && m.fast_tier.is_some()) {
|
||||
let fast = s.fast_override.unwrap_or_else(|| {
|
||||
s.service_tier.as_deref().or(model.default_service_tier.as_deref()).is_some_and(is_fast_tier)
|
||||
});
|
||||
out.push(json!({
|
||||
"id": SERVICE_TIER, "name": "Fast", "category": "model_config", "type": "select",
|
||||
"currentValue": if fast { "true" } else { "false" },
|
||||
"options": [select_value("false", "Standard", None), select_value("true", "Fast", None)],
|
||||
}));
|
||||
}
|
||||
out.push(json!({
|
||||
"id": MODE, "name": "Mode", "category": "mode", "type": "select", "currentValue": s.mode.id(),
|
||||
"options": Mode::ALL.iter().map(|m| select_value(m.id(), m.name(), Some(m.description()))).collect::<Vec<_>>(),
|
||||
@@ -677,7 +740,7 @@ pub(super) enum Failure {
|
||||
UsageLimit(Option<f64>),
|
||||
/// Signed out or refused.
|
||||
Auth,
|
||||
/// The model declined.
|
||||
/// The server blocked the turn under a safety policy.
|
||||
Refusal,
|
||||
Other,
|
||||
}
|
||||
@@ -717,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
|
||||
exhausted.map(|s| s * 1000.0)
|
||||
}
|
||||
|
||||
/// The text a failed turn reports: codex's message, with its details.
|
||||
/// The text a failed turn reports: Codex's message, details and diagnostic code.
|
||||
pub(super) fn error_message(error: &Value) -> String {
|
||||
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
|
||||
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
|
||||
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
|
||||
_ => message.to_owned(),
|
||||
let original =
|
||||
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
|
||||
let mut message = original.to_owned();
|
||||
if let Some(details) =
|
||||
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
|
||||
&& !original.contains(details)
|
||||
{
|
||||
message.push('\n');
|
||||
message.push_str(details);
|
||||
}
|
||||
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
|
||||
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
|
||||
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
|
||||
message.push_str(&format!("\nCodex error: {code}"));
|
||||
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
|
||||
message.push_str(&format!(" (HTTP {status})"));
|
||||
}
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
/// One choice of an approval: what ACP shows and what codex gets back.
|
||||
|
||||
@@ -114,7 +114,7 @@ pub(crate) fn is_missing_binary_error(err: &std::io::Error) -> bool {
|
||||
pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discovered, DiscoverError> {
|
||||
tokio::time::timeout(DISCOVER_TIMEOUT, async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
match discover_once(spec.clone(), cwd.clone(), prefer_stored).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
@@ -185,6 +185,78 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
|
||||
res
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct CliAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
}
|
||||
|
||||
/// Queries `auth.getStatus` on Copilot's headless server (ignoring any IDE-selected `gh`
|
||||
/// account override so the UI can show what the "Default" account resolves to).
|
||||
pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> Option<CliAuthStatus> {
|
||||
spec.env.retain(|(name, _)| name != crate::provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
tokio::time::timeout(Duration::from_secs(8), async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await;
|
||||
if !prefer_stored
|
||||
&& has_ambient
|
||||
&& first.as_ref().is_none_or(|s| !s.authenticated)
|
||||
&& let Some(retry) = probe_auth_once(spec, cwd, true).await
|
||||
{
|
||||
if retry.authenticated {
|
||||
crate::provider::mark_prefer_stored_copilot_auth();
|
||||
}
|
||||
return Some(retry);
|
||||
}
|
||||
first
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
async fn probe_auth_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) -> Option<CliAuthStatus> {
|
||||
let launch = tokio::task::spawn_blocking({
|
||||
let cwd = cwd.clone();
|
||||
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
|
||||
})
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
|
||||
let args = headless_args(&launch.args);
|
||||
let peer = Peer::spawn_framed(
|
||||
&launch.command,
|
||||
&args,
|
||||
&cwd,
|
||||
&launch.env,
|
||||
Arc::new(ide_jsonrpc::NoopHandler),
|
||||
Box::new(|_| {}),
|
||||
Framing::ContentLength,
|
||||
)
|
||||
.ok()?;
|
||||
let res = async {
|
||||
handshake(&peer).await.ok()?;
|
||||
let auth: Value = peer.request("auth.getStatus", json!({}), None).await.ok()?;
|
||||
let authenticated = auth.get("isAuthenticated").and_then(Value::as_bool).unwrap_or(false);
|
||||
let str_field = |key: &str| {
|
||||
auth.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
|
||||
};
|
||||
Some(CliAuthStatus {
|
||||
authenticated,
|
||||
login: str_field("login"),
|
||||
auth_type: str_field("authType"),
|
||||
status_message: str_field("statusMessage"),
|
||||
})
|
||||
}
|
||||
.await;
|
||||
peer.kill();
|
||||
res
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn attach(
|
||||
client: Arc<dyn Handler>,
|
||||
@@ -390,6 +462,38 @@ fn apply_skills(params: &Value, req: &mut Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `_meta.openidea.memory` to Copilot's `session.create` / `session.resume` payload:
|
||||
/// gates `store_memory` when auto-memory is `ReadOnly` or `Off`, disables custom instructions
|
||||
/// when all workspace/user instructions are muted, and appends shared OpenIDEA memories.
|
||||
fn apply_memory(params: &Value, req: &mut Value) {
|
||||
let Some(mem) = params.pointer("/_meta/openidea/memory") else {
|
||||
return;
|
||||
};
|
||||
if mem.get("copilotExcludeStoreMemory").and_then(Value::as_bool) == Some(true) {
|
||||
let mut excluded: Vec<String> = req
|
||||
.get("excludedTools")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if !excluded.iter().any(|t| t == "store_memory") {
|
||||
excluded.push("store_memory".into());
|
||||
}
|
||||
req["excludedTools"] = json!(excluded);
|
||||
}
|
||||
if mem.get("copilotDisableCustomInstructions").and_then(Value::as_bool) == Some(true) {
|
||||
req["customInstructions"] = json!(false);
|
||||
}
|
||||
if let Some(sys) = mem.get("copilotSystemMessage").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
req["systemMessage"] = json!({
|
||||
"mode": "append",
|
||||
"content": sys,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> ResponseError {
|
||||
error(codes::INVALID_PARAMS, message)
|
||||
}
|
||||
@@ -450,6 +554,7 @@ impl CopilotShim {
|
||||
"session/set_config_option" => self.set_config(¶ms).await,
|
||||
"session/prompt" => self.prompt(¶ms, false).await,
|
||||
"_openidea/steer" => self.prompt(¶ms, true).await,
|
||||
"_openidea/context_usage" => self.context_usage(¶ms).await,
|
||||
"_openidea/stop_task" => self.stop_task(¶ms).await,
|
||||
"session/close" => self.close_session(¶ms).await,
|
||||
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
|
||||
@@ -465,7 +570,7 @@ impl CopilotShim {
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
|
||||
"sessionCapabilities": { "close": {}, "list": {} },
|
||||
"_meta": { "openidea": { "steer": true, "backgroundTasks": true } },
|
||||
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
|
||||
},
|
||||
"agentInfo": {
|
||||
"name": "copilot",
|
||||
@@ -515,6 +620,7 @@ impl CopilotShim {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let created = self.call("session.create", req).await?;
|
||||
let session_id = created
|
||||
@@ -566,6 +672,7 @@ impl CopilotShim {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
|
||||
@@ -583,12 +690,47 @@ impl CopilotShim {
|
||||
let options = models::config_options(&catalog, &settings);
|
||||
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
|
||||
self.publish_commands(&actual_id, cwd);
|
||||
self.sync_usage_metrics(&actual_id);
|
||||
Ok(json!({
|
||||
"sessionId": actual_id,
|
||||
"configOptions": options,
|
||||
}))
|
||||
}
|
||||
|
||||
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
|
||||
let shim = self.clone();
|
||||
let sid = session_id.to_owned();
|
||||
self.runtime.spawn(async move {
|
||||
let Ok(metrics) = shim.call("session.usage.getMetrics", json!({ "sessionId": sid })).await else {
|
||||
return;
|
||||
};
|
||||
let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64) else {
|
||||
return;
|
||||
};
|
||||
let catalog = shim.catalog.try_lock().ok().and_then(|g| g.clone());
|
||||
let update = {
|
||||
let mut st = shim.state.lock();
|
||||
st.sessions.get_mut(&sid).and_then(|entry| {
|
||||
entry.translator.set_total_nano_aiu(nano_aiu);
|
||||
let used = entry.translator.last_used_tokens?;
|
||||
let size = entry
|
||||
.translator
|
||||
.last_usage_snapshot
|
||||
.as_ref()
|
||||
.map(|s| s.token_limit)
|
||||
.filter(|&s| s > 0)
|
||||
.or_else(|| {
|
||||
catalog.as_deref().and_then(|m| entry.settings.active_context_tokens(m)).filter(|&s| s > 0)
|
||||
})?;
|
||||
Some(entry.translator.usage_update(used, size))
|
||||
})
|
||||
};
|
||||
if let Some(update) = update {
|
||||
shim.send_update(&sid, update);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn publish_commands(self: &Arc<Self>, session_id: &str, cwd: &str) {
|
||||
let shim = self.clone();
|
||||
let sid = session_id.to_owned();
|
||||
@@ -663,25 +805,152 @@ impl CopilotShim {
|
||||
|
||||
let new_limit = next_settings.active_context_tokens(&catalog);
|
||||
let options = models::config_options(&catalog, &next_settings);
|
||||
{
|
||||
let usage_update = {
|
||||
let mut st = self.state.lock();
|
||||
if let Some(entry) = st.sessions.get_mut(session_id) {
|
||||
entry.settings = next_settings;
|
||||
if matches!(option, MODEL | CONTEXT_TIER)
|
||||
&& let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0))
|
||||
{
|
||||
Some(entry.translator.usage_update(used, size))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
if matches!(option, MODEL | CONTEXT_TIER)
|
||||
&& let (Some(used), Some(size)) = (last_used, new_limit.filter(|&s| s > 0))
|
||||
{
|
||||
self.send_update(session_id, json!({ "sessionUpdate": "usage_update", "used": used, "size": size }));
|
||||
};
|
||||
if let Some(update) = usage_update {
|
||||
self.send_update(session_id, update);
|
||||
}
|
||||
Ok(json!({ "configOptions": options }))
|
||||
}
|
||||
|
||||
async fn context_usage(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session_id = str_param(params, "sessionId")?;
|
||||
let catalog = self.models().await.ok();
|
||||
let (model_id, fallback_limit, snapshot) = {
|
||||
let st = self.state.lock();
|
||||
let entry = st.sessions.get(session_id).ok_or_else(|| invalid(format!("unknown session {session_id}")))?;
|
||||
let limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
|
||||
(entry.settings.model.clone(), limit, entry.translator.last_usage_snapshot.clone())
|
||||
};
|
||||
|
||||
let (attr_res, metrics_res) = tokio::join!(
|
||||
self.call("session.metadata.getContextAttribution", json!({ "sessionId": session_id })),
|
||||
self.call("session.usage.getMetrics", json!({ "sessionId": session_id })),
|
||||
);
|
||||
|
||||
if let Ok(metrics) = metrics_res
|
||||
&& let Some(nano_aiu) = metrics.get("totalNanoAiu").and_then(Value::as_f64)
|
||||
&& let Some(entry) = self.state.lock().sessions.get_mut(session_id)
|
||||
{
|
||||
entry.translator.set_total_nano_aiu(nano_aiu);
|
||||
}
|
||||
|
||||
let mut usage =
|
||||
attr_res.ok().and_then(|v| translate::context_usage_from_attribution(&v, &model_id, fallback_limit));
|
||||
|
||||
if usage.is_none()
|
||||
&& !model_id.is_empty()
|
||||
&& let Ok(info) = self
|
||||
.call("session.metadata.contextInfo", json!({ "sessionId": session_id, "modelName": model_id }))
|
||||
.await
|
||||
{
|
||||
usage = translate::context_usage_from_context_info(&info, &model_id, fallback_limit);
|
||||
}
|
||||
|
||||
let usage = usage
|
||||
.or_else(|| snapshot.as_ref().map(|snap| translate::context_usage_from_snapshot(snap, &model_id)))
|
||||
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Context details are not available yet"))?;
|
||||
|
||||
let meter_update = {
|
||||
let mut st = self.state.lock();
|
||||
st.sessions.get_mut(session_id).map(|entry| {
|
||||
entry.translator.last_used_tokens = Some(usage.total_tokens);
|
||||
entry.translator.usage_update(usage.total_tokens, usage.max_tokens)
|
||||
})
|
||||
};
|
||||
if let Some(update) = meter_update {
|
||||
self.send_update(session_id, update);
|
||||
}
|
||||
|
||||
serde_json::to_value(usage).map_err(|e| error(codes::INTERNAL_ERROR, e.to_string()))
|
||||
}
|
||||
|
||||
async fn compact_session(&self, session_id: &str, instructions: Option<&str>) -> Result<Value, ResponseError> {
|
||||
let mut req = json!({
|
||||
"sessionId": session_id,
|
||||
"trigger": "manual",
|
||||
});
|
||||
if let Some(text) = instructions.map(str::trim).filter(|s| !s.is_empty()) {
|
||||
req["customInstructions"] = json!(text);
|
||||
}
|
||||
let res = self.call("session.history.compact", req).await?;
|
||||
let success = res.get("success").and_then(Value::as_bool).unwrap_or(true);
|
||||
if !success {
|
||||
let msg = res.get("error").and_then(Value::as_str).unwrap_or("Conversation compaction failed");
|
||||
return Err(error(codes::INTERNAL_ERROR, msg));
|
||||
}
|
||||
|
||||
let catalog = self.models().await.ok();
|
||||
let meter_update = {
|
||||
let mut st = self.state.lock();
|
||||
st.sessions.get_mut(session_id).and_then(|entry| {
|
||||
let cw = res.get("contextWindow")?;
|
||||
let used = cw.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())?;
|
||||
let fallback_limit = catalog.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
|
||||
let size = cw
|
||||
.get("tokenLimit")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.filter(|&n| n > 0)
|
||||
.or(fallback_limit.filter(|&n| n > 0))?;
|
||||
let u32_field = |k: &str| cw.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
|
||||
entry.translator.record_snapshot(translate::UsageSnapshot {
|
||||
current_tokens: used,
|
||||
token_limit: size,
|
||||
system_tokens: u32_field("systemTokens"),
|
||||
tool_definitions_tokens: u32_field("toolDefinitionsTokens"),
|
||||
conversation_tokens: u32_field("conversationTokens"),
|
||||
});
|
||||
Some(entry.translator.usage_update(used, size))
|
||||
})
|
||||
};
|
||||
if let Some(update) = meter_update {
|
||||
self.send_update(session_id, update);
|
||||
}
|
||||
|
||||
let tokens_removed = res.get("tokensRemoved").and_then(Value::as_u64).unwrap_or(0);
|
||||
let messages_removed = res.get("messagesRemoved").and_then(Value::as_u64).unwrap_or(0);
|
||||
let summary = if tokens_removed > 0 || messages_removed > 0 {
|
||||
format!("Compacted conversation ({tokens_removed} tokens, {messages_removed} messages removed).")
|
||||
} else {
|
||||
"Conversation compacted.".to_owned()
|
||||
};
|
||||
self.send_update(
|
||||
session_id,
|
||||
json!({ "sessionUpdate": "agent_message_chunk", "content": { "type": "text", "text": summary } }),
|
||||
);
|
||||
if let Some(entry) = self.state.lock().sessions.get_mut(session_id) {
|
||||
entry.early_cancel = None;
|
||||
}
|
||||
Ok(json!({ "stopReason": "end_turn" }))
|
||||
}
|
||||
|
||||
async fn prompt(&self, params: &Value, steer: bool) -> Result<Value, ResponseError> {
|
||||
let session_id = str_param(params, "sessionId")?.to_owned();
|
||||
let blocks = params.get("prompt").and_then(Value::as_array).ok_or_else(|| invalid("missing prompt"))?;
|
||||
let (text, attachments, temp_files) = build_prompt_payload(&session_id, blocks);
|
||||
|
||||
if !steer
|
||||
&& attachments.is_empty()
|
||||
&& let Some(instructions) = parse_compact_command(&text)
|
||||
{
|
||||
cleanup_files(&temp_files);
|
||||
return self.compact_session(&session_id, instructions).await;
|
||||
}
|
||||
|
||||
if steer {
|
||||
let (is_running, main_busy) = {
|
||||
let st = self.state.lock();
|
||||
@@ -998,6 +1267,21 @@ impl CopilotShim {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_compact_command(text: &str) -> Option<Option<&str>> {
|
||||
let trimmed = text.trim();
|
||||
if trimmed == "/compact" {
|
||||
return Some(None);
|
||||
}
|
||||
let rest = trimmed.strip_prefix("/compact")?;
|
||||
let first = rest.chars().next()?;
|
||||
if first.is_whitespace() {
|
||||
let focus = rest.trim();
|
||||
Some((!focus.is_empty()).then_some(focus))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Value>, Vec<PathBuf>) {
|
||||
let mut text_parts = Vec::new();
|
||||
let mut attachments = Vec::new();
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
use super::models::{self, CONTEXT_TIER, EFFORT, MODEL, Mode, Settings, UserDefaults};
|
||||
use super::translate::{
|
||||
self, EventTranslator, UsageSnapshot, context_usage_from_attribution, context_usage_from_context_info,
|
||||
context_usage_from_snapshot,
|
||||
};
|
||||
use super::{acp_args, acp_fallback_spec, attach, headless_args};
|
||||
use crate::config;
|
||||
use crate::model::{AgentContextCategory, AgentContextUsage};
|
||||
use crate::provider::Driver;
|
||||
use ide_jsonrpc::{Framing, Handler, Peer, codes};
|
||||
use parking_lot::Mutex;
|
||||
@@ -443,6 +448,38 @@ impl Handler for FakeCopilotServer {
|
||||
] })),
|
||||
"session.tasks.cancel" => Ok(json!({ "cancelled": true })),
|
||||
"session.abort" => Ok(json!({})),
|
||||
"session.usage.getMetrics" => Ok(json!({
|
||||
"totalNanoAiu": 4_211_400_000_000.0,
|
||||
"totalPremiumRequestCost": 12.0,
|
||||
})),
|
||||
"session.metadata.getContextAttribution" => Ok(json!({
|
||||
"contextAttribution": {
|
||||
"totalTokens": 405_200,
|
||||
"limit": 1_000_000,
|
||||
"promptTokenLimit": 936_000,
|
||||
"bufferTokens": 64_000,
|
||||
"compactionThreshold": 800_000,
|
||||
"modelId": "gemini-4-carbon",
|
||||
"entries": [
|
||||
{ "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 },
|
||||
{ "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" },
|
||||
{ "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 203_000, "parentId": "system:root" },
|
||||
{ "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 }
|
||||
]
|
||||
}
|
||||
})),
|
||||
"session.history.compact" => Ok(json!({
|
||||
"success": true,
|
||||
"tokensRemoved": 250_000,
|
||||
"messagesRemoved": 12,
|
||||
"contextWindow": {
|
||||
"currentTokens": 155_200,
|
||||
"tokenLimit": 1_000_000,
|
||||
"systemTokens": 20_000,
|
||||
"toolDefinitionsTokens": 100_000,
|
||||
"conversationTokens": 35_200
|
||||
}
|
||||
})),
|
||||
"session.send" if self.background_shell => {
|
||||
if let Some(peer) = self.peer.get().cloned() {
|
||||
let sid = params["sessionId"].as_str().unwrap_or("cop-sess-1").to_owned();
|
||||
@@ -795,3 +832,325 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
|
||||
assert!(params.get("enableConfigDiscovery").is_none(), "{method} must not auto-enable workspace MCP discovery");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn session_new_and_load_apply_copilot_memory_gating_and_system_message() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates, move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
let meta = json!({
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"autoMemory": "readOnly",
|
||||
"copilotExcludeStoreMemory": true,
|
||||
"copilotDisableCustomInstructions": true,
|
||||
"copilotSystemMessage": "## Memory (shared)\nRun targeted tests."
|
||||
}
|
||||
}
|
||||
});
|
||||
let _: Value =
|
||||
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
|
||||
let _: Value = client
|
||||
.request(
|
||||
"session/load",
|
||||
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calls = server.calls.lock();
|
||||
for method in ["session.create", "session.resume"] {
|
||||
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
|
||||
assert_eq!(params["excludedTools"], json!(["store_memory"]), "{method}: {params}");
|
||||
assert_eq!(params["customInstructions"], json!(false), "{method}: {params}");
|
||||
assert_eq!(
|
||||
params["systemMessage"],
|
||||
json!({ "mode": "append", "content": "## Memory (shared)\nRun targeted tests." }),
|
||||
"{method}: {params}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translates_context_attribution_without_double_counting_parent_rollups() {
|
||||
let payload = json!({
|
||||
"contextAttribution": {
|
||||
"totalTokens": 405_200,
|
||||
"limit": 1_000_000,
|
||||
"bufferTokens": 64_000,
|
||||
"compactionThreshold": 800_000,
|
||||
"modelId": "gemini-4-carbon",
|
||||
"entries": [
|
||||
{ "kind": "system", "id": "system:root", "label": "System", "tokens": 223_000 },
|
||||
{ "kind": "system", "id": "system:prompt", "label": "System Prompt", "tokens": 20_000, "parentId": "system:root" },
|
||||
{ "kind": "toolDefinition", "id": "toolDefinition:bash", "label": "bash", "tokens": 120_000, "parentId": "system:root" },
|
||||
{ "kind": "toolDefinition", "id": "toolDefinition:view", "label": "view", "tokens": 83_000, "parentId": "system:root" },
|
||||
{ "kind": "tool", "id": "tool:bash", "label": "bash", "tokens": 69_000 },
|
||||
{ "kind": "plugin", "id": "plugin:git", "label": "git", "tokens": 5_000 },
|
||||
{ "kind": "skill", "id": "skill:pr", "label": "pr", "tokens": 5_000, "parentId": "plugin:git" }
|
||||
]
|
||||
}
|
||||
});
|
||||
let usage = context_usage_from_attribution(&payload, "fallback", None).unwrap();
|
||||
assert_eq!(usage.total_tokens, 405_200);
|
||||
assert_eq!(usage.max_tokens, 1_000_000);
|
||||
assert_eq!(usage.reserved_tokens, Some(64_000));
|
||||
assert_eq!(usage.auto_compact_threshold, Some(800_000));
|
||||
assert_eq!(usage.is_auto_compact_enabled, Some(true));
|
||||
assert_eq!(
|
||||
usage.categories,
|
||||
vec![
|
||||
AgentContextCategory {
|
||||
name: "System prompt".into(),
|
||||
tokens: 20_000,
|
||||
kind: Some("used".into()),
|
||||
group: Some("System".into()),
|
||||
},
|
||||
AgentContextCategory {
|
||||
name: "Tool Definitions".into(),
|
||||
tokens: 203_000,
|
||||
kind: Some("used".into()),
|
||||
group: Some("System".into()),
|
||||
},
|
||||
AgentContextCategory {
|
||||
name: "Tool Results".into(),
|
||||
tokens: 69_000,
|
||||
kind: Some("used".into()),
|
||||
group: Some("User Context".into()),
|
||||
},
|
||||
AgentContextCategory {
|
||||
name: "Messages".into(),
|
||||
tokens: 108_200,
|
||||
kind: Some("used".into()),
|
||||
group: Some("User Context".into()),
|
||||
},
|
||||
AgentContextCategory {
|
||||
name: "Skills".into(),
|
||||
tokens: 5_000,
|
||||
kind: Some("used".into()),
|
||||
group: Some("User Context".into()),
|
||||
},
|
||||
AgentContextCategory { name: "Free space".into(), tokens: 530_800, kind: Some("free".into()), group: None },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translates_context_info_and_usage_snapshot_fallbacks() {
|
||||
let info = json!({
|
||||
"contextInfo": {
|
||||
"modelName": "claude-sonnet-4.5",
|
||||
"systemTokens": 12_000,
|
||||
"toolDefinitionsTokens": 48_000,
|
||||
"conversationTokens": 40_000,
|
||||
"totalTokens": 100_000,
|
||||
"limit": 200_000,
|
||||
"bufferTokens": 20_000,
|
||||
"compactionThreshold": 160_000
|
||||
}
|
||||
});
|
||||
let from_info = context_usage_from_context_info(&info, "fallback", None).unwrap();
|
||||
assert_eq!(from_info.reserved_tokens, Some(20_000));
|
||||
assert_eq!(
|
||||
from_info.categories.iter().map(|c| (c.name.as_str(), c.tokens, c.group.as_deref())).collect::<Vec<_>>(),
|
||||
vec![
|
||||
("System prompt", 12_000, Some("System")),
|
||||
("Tool Definitions", 48_000, Some("System")),
|
||||
("Messages", 40_000, Some("User Context")),
|
||||
("Free space", 80_000, None),
|
||||
]
|
||||
);
|
||||
|
||||
let from_snap = context_usage_from_snapshot(
|
||||
&UsageSnapshot {
|
||||
current_tokens: 50_000,
|
||||
token_limit: 200_000,
|
||||
system_tokens: Some(10_000),
|
||||
tool_definitions_tokens: Some(25_000),
|
||||
conversation_tokens: Some(15_000),
|
||||
},
|
||||
"gpt-5.6-sol",
|
||||
);
|
||||
assert_eq!(from_snap.total_tokens, 50_000);
|
||||
assert_eq!(from_snap.max_tokens, 200_000);
|
||||
assert_eq!(from_snap.categories.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accumulates_copilot_credits_across_turns_subagents_and_compaction() {
|
||||
let mut tr = EventTranslator::default();
|
||||
let first = tr.translate(
|
||||
"s1",
|
||||
&json!({
|
||||
"type": "session.usage_info",
|
||||
"data": { "currentTokens": 40_000, "tokenLimit": 200_000, "systemTokens": 10_000, "toolDefinitionsTokens": 20_000, "conversationTokens": 10_000 }
|
||||
}),
|
||||
Some(200_000),
|
||||
);
|
||||
assert_eq!(first.updates[0].1["used"], 40_000);
|
||||
assert!(first.updates[0].1.get("cost").is_none());
|
||||
|
||||
// Main-agent usage reports 1.5 credits; subagent usage adds 0.5 credits -> 2.0 credits total.
|
||||
let main_usage = tr.translate(
|
||||
"s1",
|
||||
&json!({
|
||||
"type": "assistant.usage",
|
||||
"data": { "inputTokens": 45_000, "copilotUsage": { "totalNanoAiu": 1_500_000_000.0 } }
|
||||
}),
|
||||
Some(200_000),
|
||||
);
|
||||
assert_eq!(main_usage.updates[0].1["cost"]["currency"], "credits");
|
||||
assert!((main_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 1.5).abs() < 1e-6);
|
||||
|
||||
let sub_usage = tr.translate(
|
||||
"s1",
|
||||
&json!({
|
||||
"type": "assistant.usage",
|
||||
"agentId": "sub-1",
|
||||
"data": { "inputTokens": 12_000, "copilotUsage": { "totalNanoAiu": 500_000_000.0 } }
|
||||
}),
|
||||
Some(200_000),
|
||||
);
|
||||
assert_eq!(sub_usage.updates[0].1["used"], 45_000);
|
||||
assert!((sub_usage.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6);
|
||||
|
||||
// Compaction updates token count while keeping accumulated credits.
|
||||
let compacted = tr.translate(
|
||||
"s1",
|
||||
&json!({
|
||||
"type": "session.compaction_complete",
|
||||
"data": { "success": true, "postCompactionTokens": 22_000, "tokenLimit": 200_000 }
|
||||
}),
|
||||
Some(200_000),
|
||||
);
|
||||
assert_eq!(compacted.updates[0].1["used"], 22_000);
|
||||
assert!((compacted.updates[0].1["cost"]["amount"].as_f64().unwrap() - 2.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn available_commands_includes_compact_when_omitted_by_server() {
|
||||
let cmds = translate::available_commands(Some(&json!({ "commands": [{ "name": "review" }] })), None);
|
||||
assert!(cmds.iter().any(|c| c["name"] == "compact"));
|
||||
assert!(cmds.iter().any(|c| c["name"] == "review"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn context_usage_rpc_and_compact_command_work_end_to_end() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates.clone(), move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["contextUsage"], true);
|
||||
let _: Value = client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [] }), None).await.unwrap();
|
||||
|
||||
let ctx: AgentContextUsage =
|
||||
client.request("_openidea/context_usage", json!({ "sessionId": "cop-sess-1" }), None).await.unwrap();
|
||||
assert_eq!(ctx.total_tokens, 405_200);
|
||||
assert_eq!(ctx.max_tokens, 1_000_000);
|
||||
assert_eq!(ctx.reserved_tokens, Some(64_000));
|
||||
assert!(ctx.categories.iter().any(|c| c.name == "System prompt" && c.group.as_deref() == Some("System")));
|
||||
assert!(ctx.categories.iter().any(|c| c.name == "Tool Definitions" && c.group.as_deref() == Some("System")));
|
||||
assert!(ctx.categories.iter().any(|c| c.name == "Tool Results" && c.group.as_deref() == Some("User Context")));
|
||||
assert!(ctx.categories.iter().any(|c| c.name == "Messages" && c.group.as_deref() == Some("User Context")));
|
||||
|
||||
// Syncing metrics updated usage_update with credits cost.
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
assert!(updates.0.lock().iter().any(|u| {
|
||||
u["sessionUpdate"] == "usage_update"
|
||||
&& u["used"] == 405_200
|
||||
&& u["cost"]["currency"] == "credits"
|
||||
&& (u["cost"]["amount"].as_f64().unwrap_or(0.0) - 4211.4).abs() < 0.01
|
||||
}));
|
||||
|
||||
// `/compact` invokes `session.history.compact` instead of `session.send`.
|
||||
let res: Value = client
|
||||
.request(
|
||||
"session/prompt",
|
||||
json!({ "sessionId": "cop-sess-1", "prompt": [{ "type": "text", "text": "/compact keep PR notes" }] }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(res["stopReason"], "end_turn");
|
||||
assert!(server.calls.lock().iter().any(|(m, p)| {
|
||||
m == "session.history.compact"
|
||||
&& p["sessionId"] == "cop-sess-1"
|
||||
&& p["trigger"] == "manual"
|
||||
&& p["customInstructions"] == "keep PR notes"
|
||||
}));
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
assert!(updates.0.lock().iter().any(|u| u["sessionUpdate"] == "usage_update" && u["used"] == 155_200));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn available_commands_preserves_input_choices() {
|
||||
let cmds = json!({
|
||||
"commands": [
|
||||
{
|
||||
"name": "skills",
|
||||
"description": "Manage skills for enhanced capabilities",
|
||||
"input": {
|
||||
"hint": "[list|info|reload]",
|
||||
"choices": [
|
||||
{ "name": "list", "description": "List all available skills" },
|
||||
{ "name": "info", "description": "Show details for a skill" },
|
||||
{ "name": "INFO", "description": "Duplicate ignored" },
|
||||
{ "name": "", "description": "Empty ignored" },
|
||||
{ "name": "reload", "description": "Reload skills from disk" }
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "subconscious",
|
||||
"description": "Manage memory",
|
||||
"input": {
|
||||
"choices": [{ "name": "run", "description": "Consolidate now" }]
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
let list = super::translate::available_commands(Some(&cmds), None);
|
||||
let parsed = crate::config::commands_of(&json!({ "availableCommands": list }), "copilot");
|
||||
// Then the built-in /compact.
|
||||
assert_eq!(parsed.len(), 3);
|
||||
assert_eq!(parsed[2].name, "compact");
|
||||
assert_eq!(parsed[0].name, "skills");
|
||||
assert_eq!(parsed[0].hint.as_deref(), Some("[list|info|reload]"));
|
||||
assert_eq!(
|
||||
parsed[0].choices,
|
||||
vec![
|
||||
crate::AgentCommandChoice { name: "list".into(), description: "List all available skills".into() },
|
||||
crate::AgentCommandChoice { name: "info".into(), description: "Show details for a skill".into() },
|
||||
crate::AgentCommandChoice { name: "reload".into(), description: "Reload skills from disk".into() },
|
||||
]
|
||||
);
|
||||
assert_eq!(parsed[1].name, "subconscious");
|
||||
assert_eq!(parsed[1].hint, None);
|
||||
assert_eq!(
|
||||
parsed[1].choices,
|
||||
vec![crate::AgentCommandChoice { name: "run".into(), description: "Consolidate now".into() }]
|
||||
);
|
||||
}
|
||||
@@ -2,11 +2,22 @@
|
||||
//! permissions, slash commands, MCP servers) and ACP v1.
|
||||
|
||||
use crate::LIMITS_UPDATE;
|
||||
use crate::model::{AgentContextCategory, AgentContextUsage};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::path::Path;
|
||||
|
||||
const MAX_OUTPUT: usize = 64 * 1024;
|
||||
const NANO_AIU_PER_CREDIT: f64 = 1_000_000_000.0;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) struct UsageSnapshot {
|
||||
pub current_tokens: u32,
|
||||
pub token_limit: u32,
|
||||
pub system_tokens: Option<u32>,
|
||||
pub tool_definitions_tokens: Option<u32>,
|
||||
pub conversation_tokens: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct EventTranslator {
|
||||
@@ -18,6 +29,11 @@ pub(super) struct EventTranslator {
|
||||
subagents: HashMap<String, String>,
|
||||
/// Last reported prompt token count, used when updating context size.
|
||||
pub last_used_tokens: Option<u32>,
|
||||
/// Last reported `session.usage_info` / compaction breakdown, used as fallback when RPC metadata is absent.
|
||||
pub last_usage_snapshot: Option<UsageSnapshot>,
|
||||
/// Accumulated session AI-credit spend in nano-AIU (across main agent and subagents).
|
||||
total_nano_aiu: f64,
|
||||
has_nano_aiu: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -46,6 +62,29 @@ impl EventTranslator {
|
||||
self.streamed_messages.clear();
|
||||
}
|
||||
|
||||
pub fn set_total_nano_aiu(&mut self, nano_aiu: f64) {
|
||||
if nano_aiu.is_finite() && nano_aiu > 0.0 {
|
||||
self.total_nano_aiu = nano_aiu;
|
||||
self.has_nano_aiu = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn record_snapshot(&mut self, snapshot: UsageSnapshot) {
|
||||
self.last_used_tokens = Some(snapshot.current_tokens);
|
||||
self.last_usage_snapshot = Some(snapshot);
|
||||
}
|
||||
|
||||
pub fn usage_update(&self, used: u32, size: u32) -> Value {
|
||||
let mut update = json!({ "sessionUpdate": "usage_update", "used": used, "size": size });
|
||||
if self.has_nano_aiu && self.total_nano_aiu > 0.0 {
|
||||
update["cost"] = json!({
|
||||
"amount": self.total_nano_aiu / NANO_AIU_PER_CREDIT,
|
||||
"currency": "credits",
|
||||
});
|
||||
}
|
||||
update
|
||||
}
|
||||
|
||||
pub fn translate(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
|
||||
let mut out = Translated { updates: Vec::new(), terminal: None };
|
||||
let event_type = str_of(event, "type").unwrap_or_default();
|
||||
@@ -239,36 +278,75 @@ impl EventTranslator {
|
||||
}
|
||||
}
|
||||
"session.usage_info" => {
|
||||
let used = data.get("currentTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
|
||||
let limit = data
|
||||
.get("tokenLimit")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
.filter(|&n| n > 0)
|
||||
.or(fallback_limit);
|
||||
let used = u32_of(data, "currentTokens");
|
||||
let limit = u32_of(data, "tokenLimit").filter(|&n| n > 0).or(fallback_limit);
|
||||
if let (Some(used), Some(size)) = (used, limit) {
|
||||
self.last_used_tokens = Some(used);
|
||||
out.updates.push((
|
||||
main_session.to_owned(),
|
||||
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
|
||||
));
|
||||
self.record_snapshot(UsageSnapshot {
|
||||
current_tokens: used,
|
||||
token_limit: size,
|
||||
system_tokens: u32_of(data, "systemTokens"),
|
||||
tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"),
|
||||
conversation_tokens: u32_of(data, "conversationTokens"),
|
||||
});
|
||||
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
|
||||
}
|
||||
}
|
||||
"assistant.usage" => {
|
||||
let added_credits = data
|
||||
.pointer("/copilotUsage/totalNanoAiu")
|
||||
.and_then(Value::as_f64)
|
||||
.filter(|n| n.is_finite() && *n > 0.0);
|
||||
if let Some(nano_aiu) = added_credits {
|
||||
self.total_nano_aiu += nano_aiu;
|
||||
self.has_nano_aiu = true;
|
||||
}
|
||||
if agent_id.is_none() {
|
||||
let used = data.get("inputTokens").and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok());
|
||||
if let (Some(used), Some(size)) = (used, fallback_limit.filter(|&s| s > 0)) {
|
||||
let used = u32_of(data, "inputTokens").or(self.last_used_tokens);
|
||||
let size = self
|
||||
.last_usage_snapshot
|
||||
.as_ref()
|
||||
.map(|s| s.token_limit)
|
||||
.filter(|&s| s > 0)
|
||||
.or(fallback_limit.filter(|&s| s > 0));
|
||||
if let (Some(used), Some(size)) = (used, size) {
|
||||
self.last_used_tokens = Some(used);
|
||||
out.updates.push((
|
||||
main_session.to_owned(),
|
||||
json!({ "sessionUpdate": "usage_update", "used": used, "size": size }),
|
||||
));
|
||||
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
|
||||
}
|
||||
} else if added_credits.is_some()
|
||||
&& let (Some(used), Some(size)) = (
|
||||
self.last_used_tokens,
|
||||
self.last_usage_snapshot
|
||||
.as_ref()
|
||||
.map(|s| s.token_limit)
|
||||
.filter(|&s| s > 0)
|
||||
.or(fallback_limit.filter(|&s| s > 0)),
|
||||
)
|
||||
{
|
||||
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
|
||||
}
|
||||
if let Some(limits) = quota_limits(data.get("quotaSnapshots")) {
|
||||
out.updates.push((main_session.to_owned(), limits));
|
||||
}
|
||||
}
|
||||
"session.compaction_complete" if agent_id.is_none() => {
|
||||
if data.get("success").and_then(Value::as_bool) == Some(true) {
|
||||
let used = u32_of(data, "postCompactionTokens");
|
||||
let size = u32_of(data, "tokenLimit")
|
||||
.filter(|&n| n > 0)
|
||||
.or_else(|| self.last_usage_snapshot.as_ref().map(|s| s.token_limit).filter(|&n| n > 0))
|
||||
.or(fallback_limit.filter(|&n| n > 0));
|
||||
if let (Some(used), Some(size)) = (used, size) {
|
||||
self.record_snapshot(UsageSnapshot {
|
||||
current_tokens: used,
|
||||
token_limit: size,
|
||||
system_tokens: u32_of(data, "systemTokens"),
|
||||
tool_definitions_tokens: u32_of(data, "toolDefinitionsTokens"),
|
||||
conversation_tokens: u32_of(data, "conversationTokens"),
|
||||
});
|
||||
out.updates.push((main_session.to_owned(), self.usage_update(used, size)));
|
||||
}
|
||||
}
|
||||
}
|
||||
"session.idle" if agent_id.is_none() => {
|
||||
let mode = str_of(data, "mode").unwrap_or_default();
|
||||
if mode != "autopilot" {
|
||||
@@ -542,11 +620,34 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
|
||||
continue;
|
||||
}
|
||||
let hint = cmd.pointer("/input/hint").and_then(Value::as_str).filter(|h| !h.is_empty());
|
||||
let mut seen_choices = HashSet::new();
|
||||
let choices: Vec<Value> = cmd
|
||||
.pointer("/input/choices")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|ch| {
|
||||
let choice_name = str_of(ch, "name").map(str::trim).filter(|n| !n.is_empty())?;
|
||||
if !seen_choices.insert(choice_name.to_ascii_lowercase()) {
|
||||
return None;
|
||||
}
|
||||
Some(json!({
|
||||
"name": choice_name,
|
||||
"description": str_of(ch, "description").unwrap_or_default(),
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
let input = match (hint, choices.is_empty()) {
|
||||
(Some(h), false) => Some(json!({ "hint": h, "choices": choices })),
|
||||
(Some(h), true) => Some(json!({ "hint": h })),
|
||||
(None, false) => Some(json!({ "choices": choices })),
|
||||
(None, true) => None,
|
||||
};
|
||||
out.push(json!({
|
||||
"name": name,
|
||||
"description": str_of(cmd, "description").unwrap_or_default(),
|
||||
"source": "command",
|
||||
"input": hint.map(|h| json!({ "hint": h })),
|
||||
"input": input,
|
||||
}));
|
||||
}
|
||||
for skill in skills_res.and_then(|v| v.get("skills")).and_then(Value::as_array).into_iter().flatten() {
|
||||
@@ -573,9 +674,252 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
|
||||
"input": hint.map(|h| json!({ "hint": h })),
|
||||
}));
|
||||
}
|
||||
if seen.insert("compact".to_owned()) {
|
||||
out.push(json!({
|
||||
"name": "compact",
|
||||
"description": "Compact conversation history to free context window space",
|
||||
"source": "command",
|
||||
"input": { "hint": "optional focus instructions" },
|
||||
}));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Converts Copilot's `session.metadata.getContextAttribution` payload into [`AgentContextUsage`],
|
||||
/// grouping items into `System` (`System prompt`, `Tool Definitions`, …) and `User Context`
|
||||
/// (`Tool Results`, `Messages`, `Skills`, …) without double-counting parent rollup entries.
|
||||
pub(super) fn context_usage_from_attribution(
|
||||
res: &Value,
|
||||
fallback_model: &str,
|
||||
fallback_limit: Option<u32>,
|
||||
) -> Option<AgentContextUsage> {
|
||||
let attr = res.get("contextAttribution").unwrap_or(res);
|
||||
if !attr.is_object() {
|
||||
return None;
|
||||
}
|
||||
let total_tokens = u32_of(attr, "totalTokens")?;
|
||||
let max_tokens = u32_of(attr, "limit")
|
||||
.filter(|&n| n > 0)
|
||||
.or_else(|| u32_of(attr, "promptTokenLimit").filter(|&n| n > 0))
|
||||
.or_else(|| fallback_limit.filter(|&n| n > 0))?;
|
||||
let reserved_tokens = u32_of(attr, "bufferTokens").filter(|&n| n > 0);
|
||||
let model = str_of(attr, "modelId").filter(|s| !s.is_empty()).unwrap_or(fallback_model).to_owned();
|
||||
let auto_compact_threshold = u32_of(attr, "compactionThreshold").filter(|&n| n > 0);
|
||||
let is_auto_compact_enabled = auto_compact_threshold.map(|_| true);
|
||||
|
||||
let mut categories = Vec::new();
|
||||
let entries = attr.get("entries").and_then(Value::as_array).filter(|e| !e.is_empty());
|
||||
|
||||
if let Some(entries) = entries {
|
||||
// Any entry referenced via `parentId` is a rollup parent whose children are accounted for individually.
|
||||
let parent_ids: HashSet<&str> = entries.iter().filter_map(|e| str_of(e, "parentId")).collect();
|
||||
let mut system_rows: Vec<(String, u32)> = Vec::new();
|
||||
let mut tool_definitions: u32 = 0;
|
||||
let mut tool_results: u32 = 0;
|
||||
let mut skills: u32 = 0;
|
||||
let mut subagents: u32 = 0;
|
||||
let mut mcp_tools: u32 = 0;
|
||||
let mut plugins: u32 = 0;
|
||||
let mut other_user: BTreeMap<String, u32> = BTreeMap::new();
|
||||
let mut accounted: u32 = 0;
|
||||
|
||||
for entry in entries {
|
||||
if let Some(id) = str_of(entry, "id")
|
||||
&& parent_ids.contains(id)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let tokens = u32_of(entry, "tokens").unwrap_or(0);
|
||||
if tokens == 0 {
|
||||
continue;
|
||||
}
|
||||
accounted = accounted.saturating_add(tokens);
|
||||
match str_of(entry, "kind").unwrap_or_default() {
|
||||
"system" => {
|
||||
let label = normalize_system_label(str_of(entry, "label").unwrap_or("System prompt"));
|
||||
if let Some((_, existing)) = system_rows.iter_mut().find(|(k, _)| k == &label) {
|
||||
*existing = existing.saturating_add(tokens);
|
||||
} else {
|
||||
system_rows.push((label, tokens));
|
||||
}
|
||||
}
|
||||
"toolDefinition" => tool_definitions = tool_definitions.saturating_add(tokens),
|
||||
"tool" => tool_results = tool_results.saturating_add(tokens),
|
||||
"skill" => skills = skills.saturating_add(tokens),
|
||||
"subagent" => subagents = subagents.saturating_add(tokens),
|
||||
"mcpServer" => mcp_tools = mcp_tools.saturating_add(tokens),
|
||||
"plugin" => plugins = plugins.saturating_add(tokens),
|
||||
kind => {
|
||||
let label = str_of(entry, "label").filter(|s| !s.is_empty()).unwrap_or(kind).to_owned();
|
||||
let slot = other_user.entry(label).or_insert(0);
|
||||
*slot = slot.saturating_add(tokens);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (name, tokens) in system_rows {
|
||||
categories.push(used_category(name, tokens, "System"));
|
||||
}
|
||||
if tool_definitions > 0 {
|
||||
categories.push(used_category("Tool Definitions", tool_definitions, "System"));
|
||||
}
|
||||
if tool_results > 0 {
|
||||
categories.push(used_category("Tool Results", tool_results, "User Context"));
|
||||
}
|
||||
let messages = total_tokens.saturating_sub(accounted);
|
||||
if messages > 0 {
|
||||
categories.push(used_category("Messages", messages, "User Context"));
|
||||
}
|
||||
if skills > 0 {
|
||||
categories.push(used_category("Skills", skills, "User Context"));
|
||||
}
|
||||
if subagents > 0 {
|
||||
categories.push(used_category("Sub-agents", subagents, "User Context"));
|
||||
}
|
||||
if mcp_tools > 0 {
|
||||
categories.push(used_category("MCP tools", mcp_tools, "User Context"));
|
||||
}
|
||||
if plugins > 0 {
|
||||
categories.push(used_category("Plugins", plugins, "User Context"));
|
||||
}
|
||||
for (name, tokens) in other_user {
|
||||
categories.push(used_category(name, tokens, "User Context"));
|
||||
}
|
||||
} else if let Some(cats) = attr.get("categories").and_then(Value::as_object) {
|
||||
let get = |k: &str| cats.get(k).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok()).unwrap_or(0);
|
||||
let sys_prompt = get("systemPrompt");
|
||||
let custom_inst = get("customInstructions");
|
||||
let tool_defs = get("systemTools").saturating_add(get("mcpTools"));
|
||||
let messages = get("messages");
|
||||
if sys_prompt > 0 {
|
||||
categories.push(used_category("System prompt", sys_prompt, "System"));
|
||||
}
|
||||
if custom_inst > 0 {
|
||||
categories.push(used_category("Custom instructions", custom_inst, "System"));
|
||||
}
|
||||
if tool_defs > 0 {
|
||||
categories.push(used_category("Tool Definitions", tool_defs, "System"));
|
||||
}
|
||||
if messages > 0 {
|
||||
categories.push(used_category("Messages", messages, "User Context"));
|
||||
}
|
||||
}
|
||||
|
||||
push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens);
|
||||
Some(AgentContextUsage {
|
||||
categories,
|
||||
total_tokens,
|
||||
max_tokens,
|
||||
model,
|
||||
is_auto_compact_enabled,
|
||||
auto_compact_threshold,
|
||||
reserved_tokens,
|
||||
})
|
||||
}
|
||||
|
||||
/// Converts Copilot's `session.metadata.contextInfo` payload into [`AgentContextUsage`].
|
||||
pub(super) fn context_usage_from_context_info(
|
||||
res: &Value,
|
||||
fallback_model: &str,
|
||||
fallback_limit: Option<u32>,
|
||||
) -> Option<AgentContextUsage> {
|
||||
let info = res.get("contextInfo").unwrap_or(res);
|
||||
if !info.is_object() {
|
||||
return None;
|
||||
}
|
||||
let total_tokens = u32_of(info, "totalTokens")?;
|
||||
let max_tokens = u32_of(info, "limit")
|
||||
.filter(|&n| n > 0)
|
||||
.or_else(|| u32_of(info, "promptTokenLimit").filter(|&n| n > 0))
|
||||
.or_else(|| fallback_limit.filter(|&n| n > 0))?;
|
||||
let reserved_tokens = u32_of(info, "bufferTokens").filter(|&n| n > 0);
|
||||
let model = str_of(info, "displayModelName")
|
||||
.or_else(|| str_of(info, "modelName"))
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or(fallback_model)
|
||||
.to_owned();
|
||||
let auto_compact_threshold = u32_of(info, "compactionThreshold").filter(|&n| n > 0);
|
||||
let is_auto_compact_enabled = auto_compact_threshold.map(|_| true);
|
||||
|
||||
let mut categories = Vec::new();
|
||||
if let Some(sys) = u32_of(info, "systemTokens").filter(|&n| n > 0) {
|
||||
categories.push(used_category("System prompt", sys, "System"));
|
||||
}
|
||||
if let Some(tools) = u32_of(info, "toolDefinitionsTokens").filter(|&n| n > 0) {
|
||||
categories.push(used_category("Tool Definitions", tools, "System"));
|
||||
}
|
||||
if let Some(conv) = u32_of(info, "conversationTokens").filter(|&n| n > 0) {
|
||||
categories.push(used_category("Messages", conv, "User Context"));
|
||||
}
|
||||
push_free_space(&mut categories, total_tokens, max_tokens, reserved_tokens);
|
||||
Some(AgentContextUsage {
|
||||
categories,
|
||||
total_tokens,
|
||||
max_tokens,
|
||||
model,
|
||||
is_auto_compact_enabled,
|
||||
auto_compact_threshold,
|
||||
reserved_tokens,
|
||||
})
|
||||
}
|
||||
|
||||
/// Fallback breakdown from the latest `session.usage_info` / compaction snapshot.
|
||||
pub(super) fn context_usage_from_snapshot(snap: &UsageSnapshot, model: &str) -> AgentContextUsage {
|
||||
let mut categories = Vec::new();
|
||||
if let Some(sys) = snap.system_tokens.filter(|&n| n > 0) {
|
||||
categories.push(used_category("System prompt", sys, "System"));
|
||||
}
|
||||
if let Some(tools) = snap.tool_definitions_tokens.filter(|&n| n > 0) {
|
||||
categories.push(used_category("Tool Definitions", tools, "System"));
|
||||
}
|
||||
if let Some(conv) = snap.conversation_tokens.filter(|&n| n > 0) {
|
||||
categories.push(used_category("Messages", conv, "User Context"));
|
||||
}
|
||||
push_free_space(&mut categories, snap.current_tokens, snap.token_limit, None);
|
||||
AgentContextUsage {
|
||||
categories,
|
||||
total_tokens: snap.current_tokens,
|
||||
max_tokens: snap.token_limit,
|
||||
model: model.to_owned(),
|
||||
is_auto_compact_enabled: None,
|
||||
auto_compact_threshold: None,
|
||||
reserved_tokens: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn used_category(name: impl Into<String>, tokens: u32, group: &str) -> AgentContextCategory {
|
||||
AgentContextCategory { name: name.into(), tokens, kind: Some("used".to_owned()), group: Some(group.to_owned()) }
|
||||
}
|
||||
|
||||
fn push_free_space(
|
||||
categories: &mut Vec<AgentContextCategory>,
|
||||
total_tokens: u32,
|
||||
max_tokens: u32,
|
||||
reserved_tokens: Option<u32>,
|
||||
) {
|
||||
let free = max_tokens.saturating_sub(total_tokens.saturating_add(reserved_tokens.unwrap_or(0)));
|
||||
if free > 0 {
|
||||
categories.push(AgentContextCategory {
|
||||
name: "Free space".to_owned(),
|
||||
tokens: free,
|
||||
kind: Some("free".to_owned()),
|
||||
group: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_system_label(raw: &str) -> String {
|
||||
match raw.trim().to_ascii_lowercase().as_str() {
|
||||
"system prompt" | "system" | "system instructions" => "System prompt".to_owned(),
|
||||
"custom instructions" => "Custom instructions".to_owned(),
|
||||
_ => raw.trim().to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn u32_of(v: &Value, key: &str) -> Option<u32> {
|
||||
v.get(key).and_then(Value::as_u64).and_then(|n| u32::try_from(n).ok())
|
||||
}
|
||||
|
||||
/// The running entries of a `session.tasks.list` result, in the background-task shape the
|
||||
/// app shows (`task_id`, `task_type`, `description`).
|
||||
pub(super) fn background_tasks(list: &Value) -> Vec<Value> {
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
//! `<config>/agents/<id>.toml` (written by hand, or by installing one from the ACP
|
||||
//! Registry, see `registry`).
|
||||
|
||||
use crate::{AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets};
|
||||
use crate::{
|
||||
AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets,
|
||||
GhAuthAccount,
|
||||
};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -33,6 +36,8 @@ pub(crate) struct ProviderSpec {
|
||||
pub driver: Driver,
|
||||
pub command: String,
|
||||
pub args: Vec<String>,
|
||||
/// Number of trailing arguments added by the built-in agent's settings.
|
||||
pub additional_args_len: usize,
|
||||
pub env: Vec<(String, String)>,
|
||||
/// How to sign in when the agent reports it needs authentication.
|
||||
pub login_hint: String,
|
||||
@@ -71,7 +76,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
"GitHub Copilot",
|
||||
Driver::Copilot,
|
||||
&["copilot", "--headless", "--no-auto-update", "--stdio"],
|
||||
"Run `copilot` in a terminal and sign in.",
|
||||
"Run `copilot login` in a terminal.",
|
||||
),
|
||||
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
|
||||
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
|
||||
@@ -96,6 +101,7 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
driver: *driver,
|
||||
command: cmd[0].into(),
|
||||
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: (*hint).into(),
|
||||
source: AgentSource::Builtin,
|
||||
@@ -148,12 +154,26 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
|
||||
let explicit_copilot_token =
|
||||
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
|
||||
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
|
||||
if let Some(account) = account {
|
||||
let token = github_token_for_account(&account)?;
|
||||
// Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's
|
||||
// shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`.
|
||||
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
|
||||
} else if is_copilot
|
||||
&& !strip_ambient_tokens
|
||||
&& !explicit_copilot_token
|
||||
&& ide_core::project_env::github_token(cwd).is_some()
|
||||
&& let Some(default_token) = default_github_token()
|
||||
{
|
||||
// A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model
|
||||
// billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present.
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token));
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
@@ -163,7 +183,7 @@ impl ProviderSpec {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
|
||||
@@ -173,6 +193,80 @@ impl ProviderSpec {
|
||||
.into_owned();
|
||||
self
|
||||
}
|
||||
|
||||
/// Resolves the executable, arguments, and environment to run this agent's interactive
|
||||
/// sign-in flow directly in an IDE PTY without shell quoting.
|
||||
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
|
||||
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
|
||||
let candidate =
|
||||
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
|
||||
if candidate.is_absolute() && is_executable(&candidate) {
|
||||
return Some(candidate);
|
||||
}
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
_ => None,
|
||||
} {
|
||||
let program = resolve_exe(separate_cmd, &self.env)?;
|
||||
return Some(LoginLaunch {
|
||||
program,
|
||||
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
|
||||
env: self.env.iter().cloned().collect(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
.or_else(|| builtin_login_args(&builtin))?;
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
|
||||
if is_copilot_provider(&self.id) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
}
|
||||
return Some(LoginLaunch { program, args, env });
|
||||
}
|
||||
|
||||
let args = terminal_auth_args?.to_vec();
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
|
||||
}
|
||||
|
||||
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
|
||||
self.login_launch(cwd, terminal_auth_args).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LoginLaunch {
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
|
||||
match rest {
|
||||
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
|
||||
let (args, _) = after_space.split_once('`')?;
|
||||
Some(args.split_whitespace().map(str::to_owned).collect())
|
||||
}
|
||||
Some(_) => Some(Vec::new()),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
@@ -191,16 +285,26 @@ pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String>
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn is_valid_github_login(account: &str) -> bool {
|
||||
let bytes = account.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
let path = ide_core::process::shell_env()
|
||||
.find(|(name, _)| name == "PATH")
|
||||
.map(|(_, value)| value)
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"));
|
||||
let program = path
|
||||
.as_deref()
|
||||
.and_then(|path| ide_core::process::find_executable("gh", path))
|
||||
if !is_valid_github_login(account) {
|
||||
return Err(format!("Invalid GitHub account login: {account}"));
|
||||
}
|
||||
let program = find_gh_executable()
|
||||
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
@@ -226,6 +330,140 @@ fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
Ok(token.to_owned())
|
||||
}
|
||||
|
||||
/// Interactive `gh auth login` launch for adding/switching GitHub CLI accounts in-IDE,
|
||||
/// with ambient `GITHUB_TOKEN` / `GH_TOKEN` cleared so `gh` does not refuse to run.
|
||||
pub fn gh_login_launch() -> IdeResult<LoginLaunch> {
|
||||
let program = find_gh_executable().ok_or_else(|| IdeError::unavailable("GitHub CLI (`gh`) is not installed"))?;
|
||||
let mut env = BTreeMap::new();
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
Ok(LoginLaunch {
|
||||
program,
|
||||
args: vec!["auth".into(), "login".into(), "--hostname".into(), "github.com".into()],
|
||||
env,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns `(gh_installed, authenticated_accounts)` for `github.com` from `gh auth status`,
|
||||
/// ignoring ambient token environment variables so keyring accounts remain visible.
|
||||
pub fn gh_authenticated_accounts() -> (bool, Vec<GhAuthAccount>) {
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return (false, Vec::new());
|
||||
};
|
||||
let run_gh = |args: &[&str]| -> Option<std::process::Output> {
|
||||
let mut command = std::process::Command::new(&program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command
|
||||
.args(args)
|
||||
.envs(ide_core::process::shell_env())
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1");
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
command.output().ok()
|
||||
};
|
||||
if let Some(output) = run_gh(&["auth", "status", "--json", "hosts"]) {
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
if let Some(accounts) = parse_gh_auth_status_json(&stdout) {
|
||||
return (true, accounts);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.contains("unknown flag: --json") {
|
||||
return (true, Vec::new());
|
||||
}
|
||||
}
|
||||
let fallback = run_gh(&["auth", "status", "--hostname", "github.com"])
|
||||
.map(|out| format!("{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
|
||||
.map(|text| parse_gh_auth_status_text(&text))
|
||||
.unwrap_or_default();
|
||||
(true, fallback)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_json(text: &str) -> Option<Vec<GhAuthAccount>> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Entry {
|
||||
#[serde(default)]
|
||||
state: Option<String>,
|
||||
#[serde(default)]
|
||||
active: bool,
|
||||
#[serde(default)]
|
||||
login: String,
|
||||
#[serde(default)]
|
||||
token_source: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
#[serde(default)]
|
||||
hosts: BTreeMap<String, Vec<Entry>>,
|
||||
}
|
||||
let parsed: Response = serde_json::from_str(text.trim()).ok()?;
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
if let Some(entries) = parsed.hosts.get("github.com") {
|
||||
for entry in entries {
|
||||
let login = entry.login.trim();
|
||||
if login.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if entry.state.as_deref().is_some_and(|s| s != "success") {
|
||||
continue;
|
||||
}
|
||||
// Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts.
|
||||
if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") {
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
|
||||
existing.active |= entry.active;
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: entry.active });
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(accounts)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
let mut current: Option<usize> = None;
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") {
|
||||
let login = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
current = None;
|
||||
if !login.is_empty() && !rest.contains("_TOKEN") {
|
||||
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
|
||||
current = Some(idx);
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: false });
|
||||
current = Some(accounts.len() - 1);
|
||||
}
|
||||
}
|
||||
} else if trimmed.starts_with("- Active account: true")
|
||||
&& let Some(idx) = current
|
||||
{
|
||||
accounts[idx].active = true;
|
||||
}
|
||||
}
|
||||
accounts
|
||||
}
|
||||
|
||||
fn default_github_token() -> Option<String> {
|
||||
let program = find_gh_executable()?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
let output = command.output().ok().filter(|out| out.status.success())?;
|
||||
let token = String::from_utf8(output.stdout).ok()?;
|
||||
let token = token.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn prefer_stored_copilot_auth() -> bool {
|
||||
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -234,18 +472,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() {
|
||||
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool {
|
||||
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
|
||||
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
|
||||
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
|
||||
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
ide_core::process::shell_env()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
|
||||
fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option<String> {
|
||||
ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| {
|
||||
ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds child environment overrides for `copilot`:
|
||||
@@ -256,9 +493,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
|
||||
pub(crate) fn sanitized_copilot_env(
|
||||
spec_env: &[(String, String)],
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Vec<(String, String)> {
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd))
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_copilot_env_with(
|
||||
@@ -347,16 +585,28 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
|
||||
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
|
||||
}
|
||||
|
||||
fn uses_package_runner(command: &str) -> bool {
|
||||
matches!(command, "npx" | "bunx" | "uvx")
|
||||
}
|
||||
|
||||
fn allows_additional_args(builtin: &ProviderSpec, driver: Driver) -> bool {
|
||||
builtin.driver == Driver::Acp && driver == Driver::Acp && !uses_package_runner(&builtin.command)
|
||||
}
|
||||
|
||||
/// Public launch metadata, keeping the built-in defaults separate from agent-file overrides.
|
||||
pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
let builtin = builtin_spec(&spec.id);
|
||||
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
|
||||
Some(AgentCommandReadOnlyReason::Registry)
|
||||
} else if let Some(default) = &builtin {
|
||||
matches!(default.command.as_str(), "npx" | "bunx" | "uvx").then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
} else {
|
||||
Some(AgentCommandReadOnlyReason::CustomAgent)
|
||||
};
|
||||
let additional_args = builtin
|
||||
.as_ref()
|
||||
.filter(|b| reason.is_none() && allows_additional_args(b, spec.driver))
|
||||
.map(|_| spec.args[spec.args.len() - spec.additional_args_len..].to_vec());
|
||||
AgentProvider {
|
||||
id: spec.id.clone(),
|
||||
name: spec.name.clone(),
|
||||
@@ -366,6 +616,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
.join(" "),
|
||||
program: spec.command.clone(),
|
||||
args: spec.args.clone(),
|
||||
additional_args,
|
||||
default_program: builtin.as_ref().map(|b| b.command.clone()),
|
||||
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
|
||||
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))),
|
||||
@@ -373,6 +624,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
@@ -391,7 +643,24 @@ pub(crate) fn set_builtin_command(
|
||||
command: Option<&str>,
|
||||
) -> IdeResult<()> {
|
||||
update_builtin(custom_dir, secrets, id, |agent, builtin| {
|
||||
agent.command = command.unwrap_or(&builtin.command).to_owned()
|
||||
agent.command = command.unwrap_or(&builtin.command).to_owned();
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Appends arguments to a directly launched built-in ACP agent; an empty list resets them.
|
||||
pub(crate) fn set_builtin_additional_args(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
args: Vec<String>,
|
||||
) -> IdeResult<()> {
|
||||
update_builtin(custom_dir, secrets, id, |agent, builtin| {
|
||||
if !allows_additional_args(builtin, agent.driver) {
|
||||
return Err(IdeError::invalid(format!("{id} does not support additional arguments")));
|
||||
}
|
||||
agent.additional_args = args;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -427,7 +696,10 @@ pub(crate) fn set_builtin_env(
|
||||
return agent.write(&file).map_err(Into::into);
|
||||
}
|
||||
}
|
||||
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
|
||||
update_builtin(custom_dir, secrets, id, |agent, _| {
|
||||
agent.env = env;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
|
||||
@@ -435,7 +707,7 @@ fn update_builtin(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
change: impl FnOnce(&mut CustomAgent, &ProviderSpec),
|
||||
change: impl FnOnce(&mut CustomAgent, &ProviderSpec) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
let Some(builtin) = builtin_spec(id) else {
|
||||
return Err(IdeError::invalid(format!("{id} is not a built-in agent")));
|
||||
@@ -449,6 +721,7 @@ fn update_builtin(
|
||||
driver: builtin.driver,
|
||||
command: builtin.command.clone(),
|
||||
args: builtin.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: None,
|
||||
}
|
||||
@@ -456,11 +729,12 @@ fn update_builtin(
|
||||
if agent.registry.is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
|
||||
}
|
||||
change(&mut agent, &builtin);
|
||||
change(&mut agent, &builtin)?;
|
||||
if agent.command == builtin.command
|
||||
&& agent.name.as_deref() == Some(builtin.name.as_str())
|
||||
&& agent.driver == builtin.driver
|
||||
&& agent.args == builtin.args
|
||||
&& agent.additional_args.is_empty()
|
||||
&& agent.env.is_empty()
|
||||
{
|
||||
match std::fs::remove_file(&file) {
|
||||
@@ -502,6 +776,7 @@ pub(crate) fn save_custom(
|
||||
driver: Driver::Acp,
|
||||
command: input.command.clone(),
|
||||
args: input.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: input.env.clone(),
|
||||
registry: None,
|
||||
}
|
||||
@@ -572,6 +847,7 @@ pub(crate) fn import_acp(
|
||||
driver: Driver::Acp,
|
||||
command: server.command,
|
||||
args: server.args,
|
||||
additional_args: Vec::new(),
|
||||
env: server.env,
|
||||
registry: None,
|
||||
}
|
||||
@@ -615,6 +891,9 @@ pub(crate) struct CustomAgent {
|
||||
pub command: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub args: Vec<String>,
|
||||
/// Kept separate from `args` so Settings reset does not erase a hand-written launch line.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub additional_args: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Set when the agent was installed from the ACP Registry.
|
||||
@@ -746,6 +1025,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
driver: agent.driver,
|
||||
command: agent.command,
|
||||
args: agent.args,
|
||||
additional_args_len: 0,
|
||||
env,
|
||||
login_hint: "Sign in with the agent's own command line first.".into(),
|
||||
source,
|
||||
@@ -763,6 +1043,10 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
spec.args = crate::native::copilot::headless_args(&spec.args);
|
||||
}
|
||||
if spec.source == AgentSource::Custom {
|
||||
if allows_additional_args(existing, spec.driver) {
|
||||
spec.additional_args_len = agent.additional_args.len();
|
||||
spec.args.extend(agent.additional_args);
|
||||
}
|
||||
spec.source = AgentSource::Builtin;
|
||||
}
|
||||
*existing = spec;
|
||||
@@ -853,6 +1137,22 @@ mod tests {
|
||||
assert_eq!(reset.env, custom.env);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
|
||||
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
|
||||
for spec in builtins() {
|
||||
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
|
||||
continue;
|
||||
}
|
||||
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
|
||||
}
|
||||
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
|
||||
for spec in builtins() {
|
||||
@@ -1043,6 +1343,53 @@ mod tests {
|
||||
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_args_append_and_reset_without_replacing_agent_file_overrides() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let omp = || load(Some(root), None).into_iter().find(|spec| spec.id == "omp").unwrap();
|
||||
assert_eq!(describe(&omp()).additional_args, Some(vec![]));
|
||||
set_builtin_additional_args(root, None, "omp", vec!["--extra".into()]).unwrap();
|
||||
assert_eq!(omp().args, ["acp", "--extra"]);
|
||||
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
|
||||
assert!(!root.join("omp.toml").exists());
|
||||
|
||||
let file = root.join("omp.toml");
|
||||
std::fs::write(
|
||||
&file,
|
||||
"name = \"My OMP\"\ncommand = \"/opt/my tools/omp\"\nargs = [\"acp\", \"--manual\"]\n[env]\nKEEP = \"value\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
let original = omp();
|
||||
let extra = vec!["--label".into(), "two words".into(), String::new()];
|
||||
set_builtin_additional_args(root, None, "omp", extra.clone()).unwrap();
|
||||
let configured = omp();
|
||||
assert_eq!(configured.args, ["acp", "--manual", "--label", "two words", ""]);
|
||||
assert_eq!(describe(&configured).additional_args, Some(extra));
|
||||
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
|
||||
assert_eq!(omp(), original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additional_args_cannot_modify_managed_or_non_acp_launches() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::write(
|
||||
root.join("gemini.toml"),
|
||||
"command = \"gemini\"\nargs = [\"--experimental-acp\"]\n[registry]\nid = \"gemini\"\nversion = \"1\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(root.join("mine.toml"), "command = \"mine\"\n").unwrap();
|
||||
std::fs::write(root.join("omp.toml"), "command = \"omp\"\ndriver = \"codex\"\n").unwrap();
|
||||
let before = load(Some(root), None);
|
||||
for id in ["gemini", "mine", "omp", "codex", "claude-acp"] {
|
||||
let spec = before.iter().find(|spec| spec.id == id).unwrap();
|
||||
assert!(describe(spec).additional_args.is_none());
|
||||
assert!(set_builtin_additional_args(root, None, id, vec!["--extra".into()]).is_err());
|
||||
}
|
||||
assert_eq!(load(Some(root), None), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_copilot_allows_only_the_github_account_override() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1052,6 +1399,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/tools/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
|
||||
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
|
||||
}
|
||||
@@ -1064,12 +1412,12 @@ mod tests {
|
||||
"copilot",
|
||||
BTreeMap::from([
|
||||
("REGISTRY_SETTING".into(), "kept".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("alice-work"));
|
||||
|
||||
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
|
||||
.unwrap_err();
|
||||
@@ -1078,7 +1426,7 @@ mod tests {
|
||||
#[test]
|
||||
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()));
|
||||
let resolved = spec.resolve_for_launch(Path::new("."));
|
||||
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
|
||||
}
|
||||
@@ -1108,6 +1456,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "amp".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "amp-acp".into(), version: "1.0.0".into() }),
|
||||
}
|
||||
@@ -1133,6 +1482,7 @@ mod tests {
|
||||
driver: Driver::Claude,
|
||||
command: "/old/claude".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: None,
|
||||
};
|
||||
@@ -1186,6 +1536,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
|
||||
args: vec!["acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
|
||||
registry: Some(RegistryRef { id: "amp-acp".into(), version: "0.10.0".into() }),
|
||||
};
|
||||
@@ -1359,4 +1710,68 @@ mod tests {
|
||||
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() {
|
||||
let raw = r#"{
|
||||
"hosts": {
|
||||
"github.com": [
|
||||
{"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"},
|
||||
{"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"}
|
||||
],
|
||||
"ghe.example.com": [
|
||||
{"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"}
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_json(raw),
|
||||
Some(vec![
|
||||
GhAuthAccount { login: "alice".into(), active: true },
|
||||
GhAuthAccount { login: "alice-work".into(), active: false },
|
||||
])
|
||||
);
|
||||
|
||||
let text = "\
|
||||
github.com
|
||||
✓ Logged in to github.com account env_user (GH_TOKEN)
|
||||
- Active account: true
|
||||
✓ Logged in to github.com account alice (keyring)
|
||||
- Active account: false
|
||||
✓ Logged in to github.com account alice-work (keyring)
|
||||
- Active account: true
|
||||
";
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_text(text),
|
||||
vec![
|
||||
GhAuthAccount { login: "alice".into(), active: false },
|
||||
GhAuthAccount { login: "alice-work".into(), active: true },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let app_support = dir.path().join("Application Support/copilot");
|
||||
std::fs::create_dir_all(&app_support).unwrap();
|
||||
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.command = bin.to_string_lossy().into_owned();
|
||||
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert_eq!(launch.args, ["login"]);
|
||||
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
}
|
||||
}
|
||||
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
|
||||
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
|
||||
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
|
||||
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
|
||||
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
|
||||
}
|
||||
|
||||
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
|
||||
let tag = format!("v{}", entry.version.trim_start_matches('v'));
|
||||
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
|
||||
let sha256_url = format!("{base}/SHA256SUMS.txt");
|
||||
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
Some(p) => (p.args.clone(), p.env.clone()),
|
||||
None => (vec!["--acp".into()], BTreeMap::new()),
|
||||
};
|
||||
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
|
||||
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
|
||||
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
|
||||
let linux_arm = format!(
|
||||
"copilot-{}-arm64.tar.gz",
|
||||
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
|
||||
);
|
||||
let linux_x64 =
|
||||
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
|
||||
let targets = [
|
||||
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
|
||||
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
|
||||
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
|
||||
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
|
||||
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
|
||||
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
|
||||
let (glibc_rel, musl_rel) = match arch {
|
||||
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
|
||||
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
|
||||
};
|
||||
let glibc = root.join(glibc_rel);
|
||||
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
|
||||
let points_to_musl =
|
||||
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
|
||||
let has_glibc = glibc.exists() && !points_to_musl;
|
||||
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
|
||||
}
|
||||
|
||||
fn safe_segment(s: &str) -> bool {
|
||||
!s.is_empty()
|
||||
&& !s.starts_with('.')
|
||||
@@ -443,7 +467,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
|
||||
/// Installs (or updates to) the registry's current version of `id`, streaming progress
|
||||
/// through `emit`, and points the agent file at it.
|
||||
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
/// Installs agent `id`; an npm package retries against the public npm registry when the
|
||||
/// configured one misses it only with `public_npm_fallback`.
|
||||
pub fn install(
|
||||
paths: &RegistryPaths,
|
||||
id: &str,
|
||||
public_npm_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let id = canonical_id(id);
|
||||
// The saved index is what the user picked from; fetch only when there is none.
|
||||
let text = match fs::read_to_string(&paths.cache_file) {
|
||||
@@ -455,9 +487,14 @@ pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit
|
||||
.iter()
|
||||
.find(|e| e.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("{id} is not in the ACP Registry")))?;
|
||||
install_entry(paths, entry, Platform::current(), &on_path, cancel, emit)
|
||||
let npm_installer =
|
||||
move |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, public_npm_fallback, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, Platform::current(), &on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn install_entry(
|
||||
paths: &RegistryPaths,
|
||||
entry: &Entry,
|
||||
@@ -466,7 +503,10 @@ fn install_entry(
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
|
||||
let npm_installer = |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, true, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, platform, on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
|
||||
@@ -550,6 +590,7 @@ fn install_entry_with(
|
||||
driver: Driver::Acp,
|
||||
command: exe.to_string_lossy().into_owned(),
|
||||
args,
|
||||
additional_args: Vec::new(),
|
||||
env,
|
||||
registry: Some(RegistryRef { id: entry.id.clone(), version: entry.version.clone() }),
|
||||
};
|
||||
@@ -662,20 +703,23 @@ fn install_npm(
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn install_npm_with(
|
||||
npm: &Path,
|
||||
p: &Package,
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
@@ -703,6 +747,7 @@ fn install_npm_with(
|
||||
},
|
||||
&specs,
|
||||
false,
|
||||
public_fallback,
|
||||
cancel,
|
||||
emit,
|
||||
)?;
|
||||
@@ -941,6 +986,7 @@ mod tests {
|
||||
driver: Driver::Acp,
|
||||
command: "/x".into(),
|
||||
args: vec![],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: id.into(), version: version.into() }),
|
||||
};
|
||||
@@ -1002,7 +1048,7 @@ mod tests {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss_unless_registries_are_configured_only() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let install_dir = dir.path().join("acme/1.2.0");
|
||||
fs::create_dir_all(&install_dir).unwrap();
|
||||
@@ -1041,8 +1087,8 @@ esac
|
||||
]}"#;
|
||||
let entry = parse(index).unwrap().remove(0);
|
||||
let pkg = entry.distribution.npx.as_ref().unwrap();
|
||||
let exe =
|
||||
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let exe = install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, true, &CancellationToken::new(), &|_| {})
|
||||
.unwrap();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
@@ -1050,6 +1096,15 @@ esac
|
||||
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
|
||||
assert!(exe.is_file());
|
||||
// Only the configured registries: the miss is the error, and npmjs is never asked.
|
||||
let only = dir.path().join("acme-only/1.2.0");
|
||||
fs::create_dir_all(&only).unwrap();
|
||||
let err =
|
||||
install_npm_with(&npm, pkg, &entry, &only, MAC_ARM, false, &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 3, "{calls:?}");
|
||||
assert!(!calls[2].contains("--registry="), "{calls:?}");
|
||||
assert!(err.message.contains("notarget"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1168,6 +1223,7 @@ esac
|
||||
driver: Driver::Acp,
|
||||
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.104".into() }),
|
||||
}
|
||||
@@ -1180,7 +1236,7 @@ esac
|
||||
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
|
||||
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(spec.name, "GitHub Copilot");
|
||||
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
|
||||
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
|
||||
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
|
||||
|
||||
let mut providers = vec![provider::describe(&spec)];
|
||||
@@ -1272,4 +1328,96 @@ esac
|
||||
assert!(npm_bin.is_file());
|
||||
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
|
||||
let index = r#"{"agents":[
|
||||
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
|
||||
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
|
||||
]}"#;
|
||||
let archives_for = |root: &Path| -> (String, String) {
|
||||
let mut entry = parse(index).unwrap().remove(0);
|
||||
entry.distribution.binary.clear();
|
||||
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
|
||||
(
|
||||
entry.distribution.binary["linux-x86_64"].archive.clone(),
|
||||
entry.distribution.binary["linux-aarch64"].archive.clone(),
|
||||
)
|
||||
};
|
||||
let touch = |path: PathBuf| {
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, b"").unwrap();
|
||||
};
|
||||
|
||||
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
assert_eq!(
|
||||
archives_for(empty.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
|
||||
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
|
||||
let glibc = tempfile::tempdir().unwrap();
|
||||
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
|
||||
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(glibc.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
|
||||
let musl = tempfile::tempdir().unwrap();
|
||||
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
|
||||
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
|
||||
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
fs::create_dir_all(musl.path().join("lib64")).unwrap();
|
||||
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
|
||||
.unwrap();
|
||||
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
|
||||
assert_eq!(
|
||||
archives_for(musl.path()),
|
||||
(
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
|
||||
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let parsed = parse(index).unwrap().remove(0);
|
||||
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
|
||||
assert!(
|
||||
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
|
||||
"unexpected linux-x86_64 archive: {}",
|
||||
parsed.distribution.binary["linux-x86_64"].archive
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ pub fn widens_access(params: &Value) -> bool {
|
||||
tool.and_then(|t| t.pointer("/rawInput/networkApprovalContext")).is_some_and(|c| !c.is_null())
|
||||
}
|
||||
|
||||
fn command_from_value(val: &Value) -> Option<String> {
|
||||
pub(crate) fn command_from_value(val: &Value) -> Option<String> {
|
||||
match val {
|
||||
Value::String(s) => {
|
||||
let trimmed = s.trim();
|
||||
|
||||
@@ -15,6 +15,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use ide_tools::Http;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -106,6 +107,9 @@ pub struct InstallRemoteSkillRequest {
|
||||
pub owner: String,
|
||||
pub repo: String,
|
||||
pub git_ref: String,
|
||||
/// Root tree SHA returned by the preview. The install reads exactly this tree, so commits pushed
|
||||
/// to `git_ref` after the user reviewed the preview are never installed.
|
||||
pub tree_sha: String,
|
||||
pub subpath: String,
|
||||
pub scope: McpScope,
|
||||
/// Must be `true` when the static security scan produces any warnings.
|
||||
@@ -246,13 +250,13 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
validate_git_ref(git_ref)?;
|
||||
if blob_sha.is_empty() || !blob_sha.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
if !is_git_object_id(blob_sha) {
|
||||
return Err(IdeError::invalid("invalid Git blob SHA"));
|
||||
}
|
||||
// Base64 expands by ~4/3 plus JSON wrapper.
|
||||
let json_limit = max_bytes.saturating_mul(2).saturating_add(4096);
|
||||
let blob_url = format!("https://api.github.com/repos/{owner}/{repo}/git/blobs/{blob_sha}");
|
||||
match self.get_github_json(&blob_url, json_limit, cancel) {
|
||||
let bytes = match self.get_github_json(&blob_url, json_limit, cancel) {
|
||||
Ok(text) => {
|
||||
let parsed: BlobResponse = serde_json::from_str(&text)
|
||||
.map_err(|e| IdeError::new(ErrorKind::Protocol, format!("invalid Git blob JSON: {e}")))?;
|
||||
@@ -269,7 +273,7 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
|
||||
if bytes.len() as u64 > max_bytes {
|
||||
return Err(IdeError::invalid(format!("{repo_path}: exceeds {} KiB limit", max_bytes >> 10)));
|
||||
}
|
||||
Ok(bytes)
|
||||
bytes
|
||||
}
|
||||
Err(api_err) => {
|
||||
if cancel.is_cancelled() {
|
||||
@@ -286,12 +290,34 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
|
||||
if bytes.len() as u64 > max_bytes {
|
||||
return Err(IdeError::invalid(format!("{repo_path}: exceeds {} KiB limit", max_bytes >> 10)));
|
||||
}
|
||||
Ok(bytes)
|
||||
bytes
|
||||
}
|
||||
};
|
||||
// The raw fallback reads `git_ref`, which may have moved since the tree was listed.
|
||||
if !git_blob_id(&bytes).eq_ignore_ascii_case(blob_sha) {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Protocol,
|
||||
format!("{repo_path}: downloaded content does not match Git blob {blob_sha}"),
|
||||
));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// A 40-digit hex SHA-1 Git object id (GitHub does not host SHA-256 repositories).
|
||||
fn is_git_object_id(id: &str) -> bool {
|
||||
id.len() == 40 && id.bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// Git's object id for a blob holding `bytes`.
|
||||
fn git_blob_id(bytes: &[u8]) -> String {
|
||||
use sha1::Digest as _;
|
||||
let mut hasher = sha1::Sha1::new();
|
||||
hasher.update(format!("blob {}\0", bytes.len()).as_bytes());
|
||||
hasher.update(bytes);
|
||||
hasher.finalize().iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
fn encode_url_segment(seg: &str) -> String {
|
||||
let mut out = String::with_capacity(seg.len());
|
||||
for b in seg.bytes() {
|
||||
@@ -603,10 +629,12 @@ struct PreparedSkillBundle {
|
||||
in_root_symlinks: Vec<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
|
||||
fn fetch_and_scan_bundle(
|
||||
fetcher: &dyn SkillSourceFetcher,
|
||||
target: RepoRef<'_>,
|
||||
subpath: &str,
|
||||
pinned_tree_sha: Option<&str>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PreparedSkillBundle> {
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
@@ -615,7 +643,23 @@ fn fetch_and_scan_bundle(
|
||||
validate_git_ref(git_ref)?;
|
||||
let normalized_subpath = normalize_subpath(subpath)?.unwrap_or_default();
|
||||
|
||||
let tree = fetcher.git_tree(target, cancel)?;
|
||||
let tree = match pinned_tree_sha {
|
||||
Some(sha) => {
|
||||
if !is_git_object_id(sha) {
|
||||
return Err(IdeError::invalid("Preview the skill again before installing it"));
|
||||
}
|
||||
// The Git trees API accepts a tree SHA in place of a ref.
|
||||
let tree = fetcher.git_tree(RepoRef { owner, repo, git_ref: sha }, cancel)?;
|
||||
if !tree.sha.eq_ignore_ascii_case(sha) {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Protocol,
|
||||
format!("{owner}/{repo}: GitHub returned tree {} instead of the previewed tree {sha}", tree.sha),
|
||||
));
|
||||
}
|
||||
tree
|
||||
}
|
||||
None => fetcher.git_tree(target, cancel)?,
|
||||
};
|
||||
let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") };
|
||||
|
||||
let subtree_entries: Vec<&GitTreeEntry> = tree
|
||||
@@ -647,7 +691,7 @@ fn fetch_and_scan_bundle(
|
||||
let mut files = Vec::with_capacity(subtree_entries.len());
|
||||
let mut scan_warnings = Vec::new();
|
||||
let mut regular_files = Vec::new();
|
||||
let mut in_root_symlinks = Vec::new();
|
||||
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
|
||||
let mut skill_markdown: Option<String> = None;
|
||||
let mut actual_total = 0u64;
|
||||
|
||||
@@ -675,18 +719,7 @@ fn fetch_and_scan_bundle(
|
||||
|
||||
if is_symlink {
|
||||
let target_raw = String::from_utf8_lossy(&bytes).trim().to_owned();
|
||||
match resolve_in_root_symlink(&rel_path, &target_raw) {
|
||||
Some(safe_target) => {
|
||||
in_root_symlinks.push((rel_path.clone(), safe_target));
|
||||
}
|
||||
None => {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::OutOfRootSymlink,
|
||||
file: rel_str.to_owned(),
|
||||
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
symlinks.push((rel_path, rel_str.to_owned(), target_raw));
|
||||
files.push(RemoteSkillFile {
|
||||
path: rel_str.to_owned(),
|
||||
size: bytes.len() as u64,
|
||||
@@ -734,6 +767,31 @@ fn fetch_and_scan_bundle(
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
// Symlinks are judged together: one link may point through another, and an entry placed beneath
|
||||
// a symlink would be written wherever that link points.
|
||||
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
|
||||
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
|
||||
if let Some(link) = graph.symlink_ancestor(path) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Skill entry {:?} is inside symlink {link:?}; the repository tree is malformed",
|
||||
path.display().to_string()
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut in_root_symlinks = Vec::new();
|
||||
for (rel_path, rel_str, target_raw) in symlinks {
|
||||
if graph.stays_inside(&rel_path, &target_raw) {
|
||||
in_root_symlinks.push((rel_path, PathBuf::from(target_raw)));
|
||||
} else {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::OutOfRootSymlink,
|
||||
file: rel_str,
|
||||
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
in_root_symlinks.sort();
|
||||
|
||||
let Some(skill_markdown) = skill_markdown else {
|
||||
return Err(IdeError::invalid("Selected folder does not contain a regular SKILL.md file"));
|
||||
};
|
||||
@@ -775,50 +833,30 @@ struct ParsedSkillMetadata {
|
||||
fn parse_skill_markdown_metadata(folder_hint: &str, markdown: &str) -> IdeResult<ParsedSkillMetadata> {
|
||||
let mut name: Option<String> = None;
|
||||
let mut description: Option<String> = None;
|
||||
let mut allowed_tools_raw: Vec<String> = Vec::new();
|
||||
|
||||
let normalized = markdown.strip_prefix('\u{feff}').unwrap_or(markdown);
|
||||
if let Some(after_open) = normalized.strip_prefix("---\n").or_else(|| normalized.strip_prefix("---\r\n")) {
|
||||
let mut current_list_key: Option<String> = None;
|
||||
for raw_line in after_open.lines() {
|
||||
let trimmed_end = raw_line.trim_end_matches('\r');
|
||||
if matches!(trimmed_end.trim(), "---" | "...") {
|
||||
break;
|
||||
}
|
||||
let trimmed = trimmed_end.trim();
|
||||
if trimmed.is_empty() || trimmed.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
if (trimmed_end.starts_with(' ') || trimmed_end.starts_with('\t'))
|
||||
&& let Some(item) = trimmed.strip_prefix('-')
|
||||
if trimmed.is_empty()
|
||||
|| trimmed.starts_with('#')
|
||||
|| trimmed_end.starts_with(' ')
|
||||
|| trimmed_end.starts_with('\t')
|
||||
{
|
||||
if matches!(current_list_key.as_deref(), Some("allowed-tools" | "allowed_tools")) {
|
||||
let val = unquote(item.trim());
|
||||
if !val.is_empty() {
|
||||
allowed_tools_raw.push(val.to_owned());
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
current_list_key = None;
|
||||
if let Some((k, v)) = trimmed.split_once(':') {
|
||||
let key = k.trim().to_ascii_lowercase();
|
||||
let val = unquote(v.trim());
|
||||
match key.as_str() {
|
||||
"name" if !val.is_empty() => name = Some(val.to_owned()),
|
||||
"description" if !val.is_empty() && !matches!(val, ">" | "|" | ">-" | "|-") => {
|
||||
"description" if !val.is_empty() && !is_block_scalar_header(val) => {
|
||||
description = Some(val.to_owned());
|
||||
}
|
||||
"allowed-tools" | "allowed_tools" => {
|
||||
if val.is_empty() {
|
||||
current_list_key = Some(key);
|
||||
} else {
|
||||
let inner = val.strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(val);
|
||||
for token in split_allowed_tools(inner) {
|
||||
allowed_tools_raw.push(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -832,15 +870,86 @@ fn parse_skill_markdown_metadata(folder_hint: &str, markdown: &str) -> IdeResult
|
||||
)));
|
||||
}
|
||||
let description = description.unwrap_or_default();
|
||||
let shell_tools = allowed_tools_raw.into_iter().filter(|t| is_shell_tool_entry(t)).collect();
|
||||
Ok(ParsedSkillMetadata { name: skill_name, description, shell_tools })
|
||||
Ok(ParsedSkillMetadata { name: skill_name, description, shell_tools: frontmatter_shell_tools(markdown) })
|
||||
}
|
||||
|
||||
fn split_allowed_tools(raw: &str) -> Vec<String> {
|
||||
/// `|`, `>`, and their chomping/indentation variants (`>-`, `|+`, `|2-`, ...).
|
||||
fn is_block_scalar_header(val: &str) -> bool {
|
||||
let mut chars = val.chars();
|
||||
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '+' | '-' | '1'..='9'))
|
||||
}
|
||||
|
||||
/// Shell-capable entries granted by `allowed-tools` in the frontmatter.
|
||||
///
|
||||
/// This deliberately over-approximates YAML instead of parsing it: every token of the value — inline,
|
||||
/// block scalar, flow or block sequence, continuation lines — is checked, and tokens a YAML loader could
|
||||
/// turn into something else (aliases, escape sequences) count as grants. A false positive only adds a
|
||||
/// warning; a missed grant hides one.
|
||||
fn frontmatter_shell_tools(markdown: &str) -> Vec<String> {
|
||||
let text = markdown.strip_prefix('\u{feff}').unwrap_or(markdown);
|
||||
let mut lines = text.lines().skip_while(|l| l.trim().is_empty());
|
||||
if lines.next().map(str::trim) != Some("---") {
|
||||
return Vec::new();
|
||||
}
|
||||
let lines: Vec<&str> = lines.take_while(|l| !matches!(l.trim(), "---" | "...")).collect();
|
||||
let mut tools: Vec<String> = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < lines.len() {
|
||||
let Some(rest) = after_allowed_tools_key(lines[i]) else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
let mut value = rest.to_owned();
|
||||
i += 1;
|
||||
while i < lines.len() && !is_plain_top_level_key(lines[i]) {
|
||||
value.push('\n');
|
||||
value.push_str(lines[i]);
|
||||
i += 1;
|
||||
}
|
||||
for token in value_tokens(&value) {
|
||||
let grants_shell = is_shell_tool_entry(&token) || token.starts_with('*') || token.contains('\\');
|
||||
if grants_shell && !tools.contains(&token) {
|
||||
tools.push(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
tools
|
||||
}
|
||||
|
||||
/// The text after an `allowed-tools` / `allowed_tools` / `allowedTools` key anywhere on `line`
|
||||
/// (quoted keys and flow mappings included).
|
||||
fn after_allowed_tools_key(line: &str) -> Option<&str> {
|
||||
let lower = line.to_ascii_lowercase();
|
||||
["allowed-tools", "allowed_tools", "allowedtools", "allowed tools"]
|
||||
.iter()
|
||||
.filter_map(|key| lower.find(key).map(|pos| pos + key.len()))
|
||||
.min()
|
||||
.map(|end| &line[end..])
|
||||
}
|
||||
|
||||
/// An unindented `key:` line whose key is a plain word, which ends the previous key's value.
|
||||
fn is_plain_top_level_key(line: &str) -> bool {
|
||||
if !line.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_') {
|
||||
return false;
|
||||
}
|
||||
let Some((key, rest)) = line.split_once(':') else { return false };
|
||||
key.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | ' '))
|
||||
&& (rest.is_empty() || rest.starts_with([' ', '\t']))
|
||||
}
|
||||
|
||||
/// Splits a YAML value into candidate tool entries, keeping `Tool(args with spaces, commas)` whole.
|
||||
fn value_tokens(value: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut depth = 0usize;
|
||||
for ch in raw.chars() {
|
||||
let mut flush = |cur: &mut String| {
|
||||
let tok = cur.trim_start_matches([':', '-', '?', '&', '!', '|', '>']);
|
||||
if !tok.is_empty() && !is_block_scalar_header(tok) {
|
||||
out.push(tok.to_owned());
|
||||
}
|
||||
cur.clear();
|
||||
};
|
||||
for ch in value.chars() {
|
||||
match ch {
|
||||
'(' => {
|
||||
depth += 1;
|
||||
@@ -850,20 +959,13 @@ fn split_allowed_tools(raw: &str) -> Vec<String> {
|
||||
depth = depth.saturating_sub(1);
|
||||
cur.push(ch);
|
||||
}
|
||||
',' | ' ' if depth == 0 => {
|
||||
let tok = unquote(cur.trim());
|
||||
if !tok.is_empty() {
|
||||
out.push(tok.to_owned());
|
||||
}
|
||||
cur.clear();
|
||||
c if depth == 0 && (c.is_whitespace() || matches!(c, ',' | '[' | ']' | '{' | '}' | '"' | '\'')) => {
|
||||
flush(&mut cur)
|
||||
}
|
||||
_ => cur.push(ch),
|
||||
}
|
||||
}
|
||||
let tok = unquote(cur.trim());
|
||||
if !tok.is_empty() {
|
||||
out.push(tok.to_owned());
|
||||
}
|
||||
flush(&mut cur);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -905,8 +1007,68 @@ fn validate_rel_skill_file(rel: &str) -> IdeResult<PathBuf> {
|
||||
Ok(path.to_path_buf())
|
||||
}
|
||||
|
||||
/// Returns `Some(target_path)` only when `target_raw` is a relative link that stays strictly inside the skill root.
|
||||
fn resolve_in_root_symlink(link_rel: &Path, target_raw: &str) -> Option<PathBuf> {
|
||||
/// The symlinks of one skill bundle, keyed by case-folded path so a link named `Dir` is also found as
|
||||
/// `dir` (macOS and Windows file systems ignore case).
|
||||
struct SymlinkGraph {
|
||||
links: HashMap<Vec<String>, String>,
|
||||
}
|
||||
|
||||
/// Maximum symlinks followed while resolving one target (Linux's `MAXSYMLINKS`).
|
||||
const MAX_SYMLINK_HOPS: usize = 40;
|
||||
|
||||
impl SymlinkGraph {
|
||||
fn new<'a>(links: impl Iterator<Item = (&'a Path, &'a str)>) -> Self {
|
||||
Self { links: links.map(|(path, target)| (fold_path(path), target.to_owned())).collect() }
|
||||
}
|
||||
|
||||
/// The nearest symlink among `path`'s ancestors, if any.
|
||||
fn symlink_ancestor(&self, path: &Path) -> Option<String> {
|
||||
let folded = fold_path(path);
|
||||
(1..folded.len()).find(|&len| self.links.contains_key(&folded[..len])).map(|len| folded[..len].join("/"))
|
||||
}
|
||||
|
||||
/// Whether `target_raw`, read from the link at `link_rel`, resolves strictly inside the skill root,
|
||||
/// following every other symlink of the bundle it passes through.
|
||||
fn stays_inside(&self, link_rel: &Path, target_raw: &str) -> bool {
|
||||
let mut dir = fold_path(link_rel);
|
||||
dir.pop();
|
||||
let Some(mut pending) = relative_link_segments(target_raw) else { return false };
|
||||
let mut hops = 0;
|
||||
while let Some(seg) = pending.pop_front() {
|
||||
if seg == ".." {
|
||||
if dir.pop().is_none() {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
dir.push(seg);
|
||||
if let Some(next) = self.links.get(&dir) {
|
||||
hops += 1;
|
||||
let Some(mut next_segments) = relative_link_segments(next) else { return false };
|
||||
if hops > MAX_SYMLINK_HOPS {
|
||||
return false;
|
||||
}
|
||||
dir.pop();
|
||||
next_segments.extend(pending);
|
||||
pending = next_segments;
|
||||
}
|
||||
}
|
||||
!dir.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Case-folded normal components of a validated relative path.
|
||||
fn fold_path(path: &Path) -> Vec<String> {
|
||||
path.components()
|
||||
.filter_map(|c| match c {
|
||||
Component::Normal(s) => Some(s.to_string_lossy().to_lowercase()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Case-folded segments of a relative symlink target without `.`; `None` for absolute or Windows-style targets.
|
||||
fn relative_link_segments(target_raw: &str) -> Option<VecDeque<String>> {
|
||||
if target_raw.is_empty()
|
||||
|| target_raw.starts_with('/')
|
||||
|| target_raw.starts_with('~')
|
||||
@@ -915,30 +1077,7 @@ fn resolve_in_root_symlink(link_rel: &Path, target_raw: &str) -> Option<PathBuf>
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut stack: Vec<&std::ffi::OsStr> = link_rel
|
||||
.parent()
|
||||
.map(|p| {
|
||||
p.components()
|
||||
.filter_map(|c| match c {
|
||||
Component::Normal(s) => Some(s),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
for seg in target_raw.split('/') {
|
||||
match seg {
|
||||
"" | "." => {}
|
||||
".." => {
|
||||
stack.pop()?;
|
||||
}
|
||||
_ => stack.push(std::ffi::OsStr::new(seg)),
|
||||
}
|
||||
}
|
||||
if stack.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(PathBuf::from(target_raw))
|
||||
Some(target_raw.split('/').filter(|s| !s.is_empty() && *s != ".").map(str::to_lowercase).collect())
|
||||
}
|
||||
|
||||
fn is_executable_or_script_path(rel: &Path) -> bool {
|
||||
@@ -979,6 +1118,69 @@ fn scan_hidden_unicode(file: &str, text: &str, warnings: &mut Vec<SkillScanWarni
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates the missing parent directories of `rel` under `root`, refusing to pass through a symlink or
|
||||
/// anything else that is not a real directory.
|
||||
fn create_parent_dirs_no_follow(root: &Path, rel: &Path) -> IdeResult<()> {
|
||||
let mut dir = root.to_path_buf();
|
||||
let Some(parent) = rel.parent() else { return Ok(()) };
|
||||
for component in parent.components() {
|
||||
dir.push(component);
|
||||
match std::fs::symlink_metadata(&dir) {
|
||||
Ok(meta) if meta.is_dir() => {}
|
||||
Ok(_) => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Skill path {:?} passes through a symlink or file",
|
||||
rel.display().to_string()
|
||||
)));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => std::fs::create_dir(&dir)?,
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the symlink at `link` resolves strictly inside `root` (canonical), following links on disk.
|
||||
/// Components that do not exist are resolved lexically.
|
||||
#[cfg(unix)]
|
||||
fn link_resolves_inside(root: &Path, link: &Path) -> bool {
|
||||
let (Some(parent), Ok(target)) = (link.parent(), std::fs::read_link(link)) else { return false };
|
||||
let Ok(mut dir) = std::fs::canonicalize(parent) else { return false };
|
||||
if !dir.starts_with(root) || target.is_absolute() {
|
||||
return false;
|
||||
}
|
||||
let mut pending: VecDeque<PathBuf> = target.components().map(|c| PathBuf::from(c.as_os_str())).collect();
|
||||
let mut hops = 0;
|
||||
while let Some(seg) = pending.pop_front() {
|
||||
match seg.to_str() {
|
||||
Some(".") => continue,
|
||||
Some("..") => {
|
||||
if dir == root {
|
||||
return false;
|
||||
}
|
||||
dir.pop();
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let next = dir.join(&seg);
|
||||
match std::fs::symlink_metadata(&next) {
|
||||
Ok(meta) if meta.file_type().is_symlink() => {
|
||||
hops += 1;
|
||||
let Ok(next_target) = std::fs::read_link(&next) else { return false };
|
||||
if hops > MAX_SYMLINK_HOPS || next_target.is_absolute() {
|
||||
return false;
|
||||
}
|
||||
for c in next_target.components().rev() {
|
||||
pending.push_front(PathBuf::from(c.as_os_str()));
|
||||
}
|
||||
}
|
||||
_ => dir = next,
|
||||
}
|
||||
}
|
||||
dir != root
|
||||
}
|
||||
|
||||
/// Previews a single skill from `target` (`subpath`) and runs the static security scan.
|
||||
pub fn preview_skill(
|
||||
fetcher: &dyn SkillSourceFetcher,
|
||||
@@ -989,7 +1191,7 @@ pub fn preview_skill(
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<RemoteSkillPreview> {
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
let bundle = fetch_and_scan_bundle(fetcher, target, subpath, cancel)?;
|
||||
let bundle = fetch_and_scan_bundle(fetcher, target, subpath, None, cancel)?;
|
||||
let already_installed_user = user_home.is_some_and(|h| h.join(".agents/skills").join(&bundle.skill_name).exists());
|
||||
let already_installed_workspace =
|
||||
workspace_root.is_some_and(|w| w.join(".agents/skills").join(&bundle.skill_name).exists());
|
||||
@@ -1034,6 +1236,7 @@ pub fn install_skill(
|
||||
fetcher,
|
||||
RepoRef { owner: &req.owner, repo: &req.repo, git_ref: &req.git_ref },
|
||||
&req.subpath,
|
||||
Some(&req.tree_sha),
|
||||
cancel,
|
||||
)?;
|
||||
if !bundle.scan_warnings.is_empty() && !req.confirm_warnings {
|
||||
@@ -1056,10 +1259,8 @@ pub fn install_skill(
|
||||
let write_res = (|| -> IdeResult<()> {
|
||||
std::fs::create_dir_all(&staging)?;
|
||||
for (rel_path, bytes, is_exec) in &bundle.regular_files {
|
||||
create_parent_dirs_no_follow(&staging, rel_path)?;
|
||||
let dest = staging.join(rel_path);
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
std::fs::write(&dest, bytes)?;
|
||||
#[cfg(unix)]
|
||||
if *is_exec {
|
||||
@@ -1070,10 +1271,8 @@ pub fn install_skill(
|
||||
let _ = is_exec;
|
||||
}
|
||||
for (rel_link, target) in &bundle.in_root_symlinks {
|
||||
create_parent_dirs_no_follow(&staging, rel_link)?;
|
||||
let dest = staging.join(rel_link);
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(target, &dest)?;
|
||||
#[cfg(not(unix))]
|
||||
@@ -1084,6 +1283,20 @@ pub fn install_skill(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Backstop for the scan's graph check: resolve every created link on disk, where the file
|
||||
// system's own case and Unicode folding apply.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let root = std::fs::canonicalize(&staging)?;
|
||||
for (rel_link, _) in &bundle.in_root_symlinks {
|
||||
if !link_resolves_inside(&root, &staging.join(rel_link)) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Symlink {:?} leaves the skill folder",
|
||||
rel_link.display().to_string()
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let backup = if final_dir.exists() {
|
||||
let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name));
|
||||
std::fs::rename(&final_dir, &bak)?;
|
||||
@@ -1128,8 +1341,8 @@ mod tests {
|
||||
|
||||
fn add_tree(&mut self, git_ref: &str, entries: Vec<(&str, &str, &[u8])>) {
|
||||
let mut tree_entries = Vec::new();
|
||||
for (idx, (path, mode, content)) in entries.into_iter().enumerate() {
|
||||
let sha = format!("{idx:040x}");
|
||||
for (path, mode, content) in entries {
|
||||
let sha = git_blob_id(content);
|
||||
self.blobs.insert(sha.clone(), content.to_vec());
|
||||
tree_entries.push(GitTreeEntry {
|
||||
path: path.to_owned(),
|
||||
@@ -1139,10 +1352,14 @@ mod tests {
|
||||
size: Some(content.len() as u64),
|
||||
});
|
||||
}
|
||||
self.trees.insert(
|
||||
git_ref.to_owned(),
|
||||
GitTree { sha: "deadbeef".repeat(5), truncated: false, tree: tree_entries },
|
||||
);
|
||||
let sha = git_blob_id(format!("{git_ref}:{}", self.trees.len()).as_bytes());
|
||||
let tree = GitTree { sha: sha.clone(), truncated: false, tree: tree_entries };
|
||||
self.trees.insert(sha.clone(), tree.clone());
|
||||
self.trees.insert(git_ref.to_owned(), tree);
|
||||
}
|
||||
|
||||
fn tree_sha(&self, git_ref: &str) -> String {
|
||||
self.trees[git_ref].sha.clone()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1251,6 +1468,7 @@ mod tests {
|
||||
owner: "acme".into(),
|
||||
repo: "skills".into(),
|
||||
git_ref: "main".into(),
|
||||
tree_sha: fetcher.tree_sha("main"),
|
||||
subpath: "skills/clean-skill".into(),
|
||||
scope: McpScope::User,
|
||||
confirm_warnings: false,
|
||||
@@ -1273,6 +1491,7 @@ mod tests {
|
||||
owner: "acme".into(),
|
||||
repo: "skills".into(),
|
||||
git_ref: "main".into(),
|
||||
tree_sha: fetcher.tree_sha("main"),
|
||||
subpath: "skills/clean-skill".into(),
|
||||
scope: McpScope::User,
|
||||
confirm_warnings: false,
|
||||
@@ -1307,6 +1526,7 @@ mod tests {
|
||||
owner: "acme".into(),
|
||||
repo: "skills".into(),
|
||||
git_ref: "main".into(),
|
||||
tree_sha: fetcher.tree_sha("main"),
|
||||
subpath: "skills/risky-skill".into(),
|
||||
scope: McpScope::Workspace,
|
||||
confirm_warnings: false,
|
||||
@@ -1325,6 +1545,7 @@ mod tests {
|
||||
owner: "acme".into(),
|
||||
repo: "skills".into(),
|
||||
git_ref: "main".into(),
|
||||
tree_sha: fetcher.tree_sha("main"),
|
||||
subpath: "skills/risky-skill".into(),
|
||||
scope: McpScope::Workspace,
|
||||
confirm_warnings: true,
|
||||
@@ -1341,6 +1562,199 @@ mod tests {
|
||||
assert!(!ws_installed.join("escape-link").exists(), "out-of-root symlink omitted on disk");
|
||||
}
|
||||
|
||||
fn install_req(fetcher: &FakeFetcher, git_ref: &str, tree_sha: Option<String>) -> InstallRemoteSkillRequest {
|
||||
InstallRemoteSkillRequest {
|
||||
owner: "acme".into(),
|
||||
repo: "skills".into(),
|
||||
git_ref: git_ref.into(),
|
||||
tree_sha: tree_sha.unwrap_or_else(|| fetcher.tree_sha(git_ref)),
|
||||
subpath: String::new(),
|
||||
scope: McpScope::User,
|
||||
confirm_warnings: true,
|
||||
overwrite: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn preview_main(fetcher: &FakeFetcher, home: &Path) -> IdeResult<RemoteSkillPreview> {
|
||||
preview_skill(
|
||||
fetcher,
|
||||
RepoRef { owner: "acme", repo: "skills", git_ref: "main" },
|
||||
"",
|
||||
Some(home),
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
}
|
||||
|
||||
const SKILL_MD: &[u8] = b"---\nname: linky\ndescription: Links\n---\nBody\n";
|
||||
|
||||
#[test]
|
||||
fn rejects_entries_nested_under_a_symlink() {
|
||||
let mut fetcher = FakeFetcher::new();
|
||||
fetcher.add_tree(
|
||||
"main",
|
||||
vec![
|
||||
("SKILL.md", "100644", SKILL_MD),
|
||||
("sub2/keep.md", "100644", b"x"),
|
||||
("d1/d2/d3/sub", "120000", b"../../../sub2"),
|
||||
("d1/d2/d3/sub/escape", "120000", b"../../../outside"),
|
||||
("d1/d2/d3/sub/escape/deeper", "120000", b"x"),
|
||||
],
|
||||
);
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let err = preview_main(&fetcher, tmp.path()).unwrap_err();
|
||||
assert!(err.message.contains("inside symlink"), "{err:?}");
|
||||
let err = install_skill(
|
||||
&fetcher,
|
||||
&install_req(&fetcher, "main", None),
|
||||
Some(tmp.path()),
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(err.message.contains("inside symlink"), "{err:?}");
|
||||
assert!(!tmp.path().join(".agents/outside").exists());
|
||||
|
||||
// Case-only differences still count on case-insensitive file systems.
|
||||
let mut fetcher = FakeFetcher::new();
|
||||
fetcher.add_tree(
|
||||
"main",
|
||||
vec![("SKILL.md", "100644", SKILL_MD), ("Link", "120000", b"refs"), ("link/x", "120000", b"../..")],
|
||||
);
|
||||
assert!(preview_main(&fetcher, tmp.path()).unwrap_err().message.contains("inside symlink"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symlink_targets_are_resolved_through_other_links() {
|
||||
let mut fetcher = FakeFetcher::new();
|
||||
fetcher.add_tree(
|
||||
"main",
|
||||
vec![
|
||||
("SKILL.md", "100644", SKILL_MD),
|
||||
("a/b/doc.md", "100644", b"doc"),
|
||||
("a/b/up", "120000", b".."),
|
||||
("a/b/Up2", "120000", b".."),
|
||||
("ok", "120000", b"a/b/up/b/doc.md"),
|
||||
("escape", "120000", b"a/b/up/x/../../.."),
|
||||
("escape-case", "120000", b"a/b/up2/x/../../.."),
|
||||
("loop1", "120000", b"loop2/x"),
|
||||
("loop2", "120000", b"loop1"),
|
||||
],
|
||||
);
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let preview = preview_main(&fetcher, tmp.path()).unwrap();
|
||||
let mut flagged: Vec<&str> = preview
|
||||
.scan_warnings
|
||||
.iter()
|
||||
.filter(|w| w.kind == SkillScanWarningKind::OutOfRootSymlink)
|
||||
.map(|w| w.file.as_str())
|
||||
.collect();
|
||||
flagged.sort();
|
||||
assert_eq!(flagged, ["escape", "escape-case", "loop1", "loop2"]);
|
||||
|
||||
let dir = install_skill(
|
||||
&fetcher,
|
||||
&install_req(&fetcher, "main", None),
|
||||
Some(tmp.path()),
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
#[cfg(unix)]
|
||||
assert_eq!(std::fs::read_to_string(dir.join("ok")).unwrap(), "doc");
|
||||
for omitted in ["escape", "escape-case", "loop1", "loop2"] {
|
||||
assert!(std::fs::symlink_metadata(dir.join(omitted)).is_err(), "{omitted}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn install_writes_refuse_to_pass_through_symlinks_on_disk() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("root");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::os::unix::fs::symlink(tmp.path(), root.join("out")).unwrap();
|
||||
let err = create_parent_dirs_no_follow(&root, Path::new("out/escaped/file")).unwrap_err();
|
||||
assert!(err.message.contains("symlink"), "{err:?}");
|
||||
assert!(!tmp.path().join("escaped").exists());
|
||||
|
||||
let canonical = std::fs::canonicalize(&root).unwrap();
|
||||
std::fs::create_dir_all(root.join("a")).unwrap();
|
||||
std::os::unix::fs::symlink("..", root.join("a/up")).unwrap();
|
||||
std::os::unix::fs::symlink("up/a", root.join("a/ok")).unwrap();
|
||||
std::os::unix::fs::symlink("up/a/up/..", root.join("a/bad")).unwrap();
|
||||
assert!(link_resolves_inside(&canonical, &root.join("a/ok")));
|
||||
assert!(!link_resolves_inside(&canonical, &root.join("a/up")), "link to the root itself");
|
||||
assert!(!link_resolves_inside(&canonical, &root.join("a/bad")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowed_tools_shell_grants_are_found_in_any_yaml_form() {
|
||||
let shell = |fm: &str| frontmatter_shell_tools(&format!("---\nname: x\n{fm}\n---\nbody\n"));
|
||||
for fm in [
|
||||
"allowed-tools: >\n Bash",
|
||||
"allowed-tools: |-\n Read\n Bash(git:*)",
|
||||
"allowed-tools: >2+\n Bash",
|
||||
"allowed-tools: Read\n Bash",
|
||||
"allowed-tools: [Read,\n Bash]",
|
||||
"allowed-tools:\n- Read\n- Bash",
|
||||
"allowed-tools:\n - Read\n - \"Bash(git commit:*)\"",
|
||||
"\"allowed-tools\": Bash",
|
||||
"'allowed_tools':Bash",
|
||||
"allowedTools: Read, Bash",
|
||||
"allowed-tools: Read # comment\n Bash",
|
||||
"tools: &t Bash\nallowed-tools: *t",
|
||||
"allowed-tools: \"\\x42ash\"",
|
||||
"allowed-tools: '*'",
|
||||
] {
|
||||
assert!(!shell(fm).is_empty(), "missed shell grant in {fm:?}");
|
||||
}
|
||||
for fm in ["allowed-tools: Read Grep", "allowed-tools:\n - Read\n - Edit\ndescription: >\n Bash in prose"] {
|
||||
assert!(shell(fm).is_empty(), "false positive for {fm:?}: {:?}", shell(fm));
|
||||
}
|
||||
// Leniently opened fences still count.
|
||||
assert!(!frontmatter_shell_tools("\n--- \nallowed-tools: >\n Bash\n---\n").is_empty());
|
||||
|
||||
let mut fetcher = FakeFetcher::new();
|
||||
fetcher.add_tree(
|
||||
"main",
|
||||
vec![("SKILL.md", "100644", b"---\nname: benign\ndescription: x\nallowed-tools: >\n Bash\n---\n")],
|
||||
);
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let preview = preview_main(&fetcher, tmp.path()).unwrap();
|
||||
assert!(preview.scan_warnings.iter().any(|w| w.kind == SkillScanWarningKind::AllowedToolsShell));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn install_uses_the_previewed_tree_even_after_the_ref_moves() {
|
||||
let mut fetcher = FakeFetcher::new();
|
||||
fetcher.add_tree("main", vec![("SKILL.md", "100644", SKILL_MD)]);
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let preview = preview_main(&fetcher, tmp.path()).unwrap();
|
||||
assert!(preview.scan_warnings.is_empty());
|
||||
|
||||
// `main` moves to a tree with a script after the user reviewed the preview.
|
||||
fetcher.add_tree(
|
||||
"main",
|
||||
vec![("SKILL.md", "100644", SKILL_MD), ("scripts/payload.sh", "100755", b"#!/bin/sh\nid\n")],
|
||||
);
|
||||
assert_ne!(fetcher.tree_sha("main"), preview.tree_sha);
|
||||
let mut req = install_req(&fetcher, "main", Some(preview.tree_sha.clone()));
|
||||
req.confirm_warnings = false;
|
||||
let dir = install_skill(&fetcher, &req, Some(tmp.path()), None, &CancellationToken::new()).unwrap();
|
||||
assert!(dir.join("SKILL.md").is_file());
|
||||
assert!(!dir.join("scripts").exists());
|
||||
|
||||
let bad = install_req(&fetcher, "main", Some("not-a-sha".into()));
|
||||
assert!(install_skill(&fetcher, &bad, Some(tmp.path()), None, &CancellationToken::new()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_blob_id_matches_git() {
|
||||
assert_eq!(git_blob_id(b""), "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391");
|
||||
assert_eq!(git_blob_id(b"hello\n"), "ce013625030ba8dba906f756967f9e9ca394464a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "hits live GitHub API"]
|
||||
fn live_github_browse_preview_and_install_smoke() {
|
||||
@@ -1369,6 +1783,7 @@ mod tests {
|
||||
owner: browsed.owner,
|
||||
repo: browsed.repo,
|
||||
git_ref: browsed.git_ref,
|
||||
tree_sha: preview.tree_sha,
|
||||
subpath: browsed.skills[0].subpath.clone(),
|
||||
scope: McpScope::User,
|
||||
confirm_warnings: true,
|
||||
|
||||
@@ -209,6 +209,7 @@ impl Frontmatter {
|
||||
source,
|
||||
description: truncate(&description),
|
||||
hint: self.get("argument-hint").filter(|h| !h.is_empty()).map(str::to_owned),
|
||||
choices: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -913,6 +914,7 @@ pub fn menu_commands(offered: Vec<AgentCommand>, states: &[AgentSkillState]) ->
|
||||
description: state.skill.description.clone(),
|
||||
hint: state.skill.hint.clone(),
|
||||
source: AgentCommandSource::Skill,
|
||||
choices: Vec::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -938,6 +940,7 @@ mod tests {
|
||||
description: description.into(),
|
||||
hint: None,
|
||||
source: AgentCommandSource::Command,
|
||||
choices: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -91,6 +91,7 @@ impl Timeline {
|
||||
diffs: Vec::new(),
|
||||
started_ms: Some(crate::now_ms()),
|
||||
ended_ms: None,
|
||||
command: None,
|
||||
};
|
||||
let index = match self.tools.get(&id) {
|
||||
Some(&i) => {
|
||||
@@ -154,7 +155,7 @@ impl Timeline {
|
||||
}
|
||||
|
||||
fn merge_tool(&mut self, index: usize, update: &Value) {
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
|
||||
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, command, .. } =
|
||||
&mut self.entries[index]
|
||||
else {
|
||||
return;
|
||||
@@ -171,6 +172,11 @@ impl Timeline {
|
||||
*ended_ms = Some(crate::now_ms());
|
||||
}
|
||||
}
|
||||
if let Some(raw) = update.pointer("/rawInput/command").or_else(|| update.pointer("/rawInput/cmd"))
|
||||
&& let Some(cmd) = crate::security::command_from_value(raw)
|
||||
{
|
||||
*command = Some(crate::shell_script(&cmd).unwrap_or(cmd));
|
||||
}
|
||||
if update.get("locations").is_some_and(Value::is_array) {
|
||||
*locs = locations(update.get("locations"));
|
||||
}
|
||||
@@ -471,6 +477,34 @@ mod tests {
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_execute_call_keeps_the_command_from_its_structured_input() {
|
||||
let mut t = Timeline::default();
|
||||
let command = |t: &Timeline, i: usize| match &t.entries[i] {
|
||||
AgentEntry::Tool { command, .. } => command.clone(),
|
||||
_ => panic!(),
|
||||
};
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "a", "title": "Run command", "kind": "execute",
|
||||
"rawInput": {"command": "python hello_world.py"}}));
|
||||
assert_eq!(command(&t, 0).as_deref(), Some("python hello_world.py"));
|
||||
// An argv array whose shell wraps the script, sent with a later update.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "b", "title": "Run command", "kind": "execute"}));
|
||||
assert_eq!(command(&t, 1), None);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "b",
|
||||
"rawInput": {"cmd": ["bash", "-lc", "cargo test -p ide-agent"]}}));
|
||||
assert_eq!(command(&t, 1).as_deref(), Some("cargo test -p ide-agent"));
|
||||
// One shell line, unwrapped as the permission card does.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "kind": "execute",
|
||||
"rawInput": {"command": "/bin/zsh -lc 'node hello.js'"}}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
// A later update without one keeps it; tasks saved before the field load without it.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c", "status": "completed"}));
|
||||
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
|
||||
let mut old = serde_json::to_value(&t.entries[2]).unwrap();
|
||||
old.as_object_mut().unwrap().remove("command");
|
||||
assert!(matches!(serde_json::from_value(old).unwrap(), AgentEntry::Tool { command: None, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_images_survive_updates_text_truncation_and_serialization() {
|
||||
use base64::Engine;
|
||||
@@ -611,6 +645,7 @@ mod tests {
|
||||
sent_ms: Some(sent),
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
recovery: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0));
|
||||
@@ -632,6 +667,7 @@ mod tests {
|
||||
sent_ms: Some(sent),
|
||||
done_ms: None,
|
||||
steered,
|
||||
recovery: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0, false));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-android"
|
||||
description = "Android devices and logcat for the Logcat tool window, driven through the adb CLI"
|
||||
description = "Android devices and iOS Simulators and their logs for the Logcat tool window, driven through adb and simctl"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -8,6 +8,7 @@ license.workspace = true
|
||||
[dependencies]
|
||||
ide-core.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
which = "8"
|
||||
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
//! iOS Simulators and their unified log, driven through `xcrun simctl` (macOS only).
|
||||
//!
|
||||
//! A simulator's log is followed with `simctl spawn <udid> log stream --style ndjson`
|
||||
//! and parsed into the same [`LogcatLine`] the Android log uses, so the Logcat tool
|
||||
//! window shows both with one level filter and one filter language.
|
||||
|
||||
use crate::model::{LogcatLevel, LogcatLine};
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const LIST: Duration = Duration::from_secs(20);
|
||||
const BATCH_IDLE: Duration = Duration::from_millis(60);
|
||||
const BATCH_MAX: usize = 300;
|
||||
|
||||
/// A booted simulator, as `simctl list devices booted -j` reports it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BootedSimulator {
|
||||
pub udid: String,
|
||||
pub name: String,
|
||||
/// e.g. `iOS 27.0`.
|
||||
pub runtime: String,
|
||||
}
|
||||
|
||||
/// Booted simulators; empty off macOS or without Xcode, so nothing iOS-related shows there.
|
||||
pub fn booted_simulators() -> IdeResult<Vec<BootedSimulator>> {
|
||||
if !cfg!(target_os = "macos") {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut cmd = Command::new("xcrun");
|
||||
cmd.args(["simctl", "list", "devices", "booted", "-j"]);
|
||||
match process::run(cmd, LIST, None) {
|
||||
Ok(out) if out.success => Ok(parse_simulators(&out.stdout)),
|
||||
// No Xcode (only the Command Line Tools, or none): there are no simulators.
|
||||
_ => Ok(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses `simctl list devices -j`, keeping booted devices.
|
||||
pub fn parse_simulators(json: &str) -> Vec<BootedSimulator> {
|
||||
#[derive(Deserialize)]
|
||||
struct List {
|
||||
devices: std::collections::BTreeMap<String, Vec<Device>>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Device {
|
||||
udid: String,
|
||||
name: String,
|
||||
state: String,
|
||||
}
|
||||
let Ok(list) = serde_json::from_str::<List>(json) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (runtime, devices) in list.devices {
|
||||
// "com.apple.CoreSimulator.SimRuntime.iOS-27-0" → "iOS 27.0"
|
||||
let short = runtime.rsplit('.').next().unwrap_or(&runtime);
|
||||
let runtime = short.split_once('-').map_or(short.to_owned(), |(os, v)| format!("{os} {}", v.replace('-', ".")));
|
||||
for d in devices.into_iter().filter(|d| d.state == "Booted") {
|
||||
out.push(BootedSimulator { udid: d.udid, name: d.name, runtime: runtime.clone() });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Message type of the unified log → the logcat level the window filters and colors by.
|
||||
fn level(message_type: &str) -> LogcatLevel {
|
||||
match message_type {
|
||||
"Debug" => LogcatLevel::Debug,
|
||||
"Info" | "Default" => LogcatLevel::Info,
|
||||
"Error" => LogcatLevel::Error,
|
||||
"Fault" => LogcatLevel::Fatal,
|
||||
_ => LogcatLevel::Verbose,
|
||||
}
|
||||
}
|
||||
|
||||
/// One NDJSON entry of `log stream --style ndjson`; `None` for anything that is not a
|
||||
/// log message (activities, the trailing "terminated" notice). Unknown fields are ignored.
|
||||
pub fn parse_ndjson(line: &str) -> Option<LogcatLine> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Entry {
|
||||
event_type: String,
|
||||
#[serde(default)]
|
||||
message_type: String,
|
||||
#[serde(default)]
|
||||
timestamp: String,
|
||||
#[serde(default)]
|
||||
process_image_path: String,
|
||||
#[serde(rename = "processID", default)]
|
||||
pid: i64,
|
||||
#[serde(rename = "threadID", default)]
|
||||
tid: i64,
|
||||
#[serde(default)]
|
||||
subsystem: String,
|
||||
#[serde(default)]
|
||||
category: String,
|
||||
#[serde(default)]
|
||||
event_message: String,
|
||||
}
|
||||
let e: Entry = serde_json::from_str(line).ok()?;
|
||||
if e.event_type != "logEvent" {
|
||||
return None;
|
||||
}
|
||||
let process = e.process_image_path.rsplit('/').next().unwrap_or_default();
|
||||
let tag = match (e.subsystem.is_empty(), e.category.is_empty()) {
|
||||
(true, _) => process.to_owned(),
|
||||
(false, true) => format!("{process} ({})", e.subsystem),
|
||||
(false, false) => format!("{process} ({}:{})", e.subsystem, e.category),
|
||||
};
|
||||
// "2026-11-29 14:39:31.696480+0900" → "11-29 14:39:31.696", logcat's shape.
|
||||
let time = e.timestamp.get(5..23).unwrap_or(&e.timestamp).to_owned();
|
||||
Some(LogcatLine {
|
||||
time,
|
||||
pid: e.pid as i32,
|
||||
tid: e.tid as i32,
|
||||
level: level(&e.message_type),
|
||||
tag,
|
||||
message: e.event_message,
|
||||
})
|
||||
}
|
||||
|
||||
/// Follows simulator `udid`'s log until `cancel` fires or the simulator shuts down.
|
||||
pub fn simulator_log(
|
||||
udid: &str,
|
||||
cancel: &CancellationToken,
|
||||
on_batch: &mut dyn FnMut(Vec<LogcatLine>),
|
||||
) -> IdeResult<()> {
|
||||
let mut cmd = Command::new("xcrun");
|
||||
cmd.args(["simctl", "spawn", udid, "log", "stream", "--style", "ndjson", "--level", "debug"]);
|
||||
match process::stream_batched(cmd, cancel, BATCH_IDLE, BATCH_MAX, parse_ndjson, on_batch) {
|
||||
Ok((ok, _)) if ok || cancel.is_cancelled() => Ok(()),
|
||||
// `log stream` is killed when the simulator shuts down: that is an end, not a failure.
|
||||
Ok((_, stderr)) if stderr.iter().any(|l| l.contains("terminated with signal")) => Ok(()),
|
||||
Ok((_, stderr)) => Err(IdeError::unavailable(format!("log stream on {udid} stopped: {}", stderr.join("\n")))),
|
||||
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => Ok(()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ENTRY: &str = r#"{"timezoneName":"","messageType":"Error","eventType":"logEvent","source":null,"subsystem":"com.apple.network","category":"endpoint","threadID":90176044,"processImagePath":"\/usr\/libexec\/remindd","timestamp":"2026-11-29 14:39:31.696480+0900","eventMessage":"endpoint has nothing to cleanup","processID":64339,"someFutureField":{"x":[1,2]}}"#;
|
||||
|
||||
#[test]
|
||||
fn parses_an_entry_and_ignores_unknown_fields() {
|
||||
let line = parse_ndjson(ENTRY).unwrap();
|
||||
assert_eq!(line.time, "11-29 14:39:31.696");
|
||||
assert_eq!(line.pid, 64339);
|
||||
assert_eq!(line.tid, 90176044);
|
||||
assert_eq!(line.level, LogcatLevel::Error);
|
||||
assert_eq!(line.tag, "remindd (com.apple.network:endpoint)");
|
||||
assert_eq!(line.message, "endpoint has nothing to cleanup");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_a_multi_line_message_whole() {
|
||||
let entry = r#"{"eventType":"logEvent","messageType":"Default","processImagePath":"/a/MyApp","processID":7,"eventMessage":"first\nsecond"}"#;
|
||||
let line = parse_ndjson(entry).unwrap();
|
||||
assert_eq!(line.message, "first\nsecond");
|
||||
assert_eq!(line.tag, "MyApp");
|
||||
assert_eq!(line.level, LogcatLevel::Info);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_what_is_not_a_log_message() {
|
||||
assert!(parse_ndjson(r#"{"eventType":"activityCreateEvent","eventMessage":"x"}"#).is_none());
|
||||
assert!(parse_ndjson("Child process terminated with signal 15: Terminated").is_none());
|
||||
assert!(parse_ndjson("").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_message_types_to_levels() {
|
||||
assert_eq!(level("Debug"), LogcatLevel::Debug);
|
||||
assert_eq!(level("Info"), LogcatLevel::Info);
|
||||
assert_eq!(level("Default"), LogcatLevel::Info);
|
||||
assert_eq!(level("Error"), LogcatLevel::Error);
|
||||
assert_eq!(level("Fault"), LogcatLevel::Fatal);
|
||||
assert_eq!(level("Signpost"), LogcatLevel::Verbose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_booted_simulators() {
|
||||
let json = r#"{"devices":{"com.apple.CoreSimulator.SimRuntime.iOS-27-0":[
|
||||
{"udid":"A","name":"iPhone Air","state":"Booted","isAvailable":true},
|
||||
{"udid":"B","name":"iPhone 18","state":"Shutdown"}]}}"#;
|
||||
assert_eq!(
|
||||
parse_simulators(json),
|
||||
vec![BootedSimulator { udid: "A".into(), name: "iPhone Air".into(), runtime: "iOS 27.0".into() }]
|
||||
);
|
||||
assert!(parse_simulators("not json").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,11 @@
|
||||
//!
|
||||
//! Every function blocks; callers run them off the UI / command threads.
|
||||
|
||||
mod ios;
|
||||
mod model;
|
||||
mod process;
|
||||
|
||||
pub use ios::{BootedSimulator, booted_simulators, parse_ndjson, parse_simulators, simulator_log};
|
||||
pub use model::*;
|
||||
|
||||
use ide_core::process::{own_group, prepare};
|
||||
|
||||
@@ -9,6 +9,7 @@ mod modules;
|
||||
mod parse;
|
||||
mod single;
|
||||
mod structure;
|
||||
mod tsc_watch;
|
||||
mod up_to_date;
|
||||
|
||||
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
|
||||
@@ -16,16 +17,19 @@ pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
|
||||
single_file_classpath, single_file_target,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
|
||||
};
|
||||
pub use tsc_watch::{tsc_watch, tsc_watch_roots};
|
||||
pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
|
||||
use crate::process::{self, Stream};
|
||||
use crate::{BuildModel, maven};
|
||||
use ide_core::build_jobs::append_default_jobs;
|
||||
use ide_core::settings::CMakeProfile;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeError, IdeResult, Pos, Range, Severity};
|
||||
use parse::{ColUnit, Format, OutputParser, RawMessage};
|
||||
@@ -417,7 +421,8 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
}
|
||||
|
||||
/// CLion's Build Project for a CMake project: configures the build directory when it has no
|
||||
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild). The directory and
|
||||
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per
|
||||
/// logical CPU unless the profile's build arguments choose a count. The directory and
|
||||
/// options come from the CMake profile; without one, a configured directory of the project
|
||||
/// (the first by name), else `build`, as the generated run configurations use.
|
||||
fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec<BuildStep> {
|
||||
@@ -455,6 +460,7 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
|
||||
build.args.push("--clean-first".into());
|
||||
}
|
||||
build.args.extend(profile.map(|p| p.build_args.clone()).unwrap_or_default());
|
||||
append_default_jobs(&mut build.args);
|
||||
build.env = env;
|
||||
steps.push(build);
|
||||
steps
|
||||
@@ -809,8 +815,81 @@ pub fn run(
|
||||
})
|
||||
}
|
||||
|
||||
/// Messages of an `xcodebuild` whose output arrives line by line (an Xcode run configuration),
|
||||
/// each reported once: xcodebuild prints a message for every architecture and again on retries.
|
||||
pub struct XcodebuildMessages {
|
||||
parser: OutputParser,
|
||||
cwd: PathBuf,
|
||||
paths: PathMap,
|
||||
lines: Lines,
|
||||
seen: HashSet<(Option<PathBuf>, Option<Range>, String)>,
|
||||
/// xcodebuild printed its result (`** BUILD SUCCEEDED **`); what follows is the app's console.
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl XcodebuildMessages {
|
||||
/// Relative paths resolve against `cwd`; paths under `root`'s canonical form map back to `root`.
|
||||
pub fn new(root: &Path, cwd: &Path) -> Self {
|
||||
XcodebuildMessages {
|
||||
parser: OutputParser::new(Format::Xcode),
|
||||
cwd: cwd.to_path_buf(),
|
||||
paths: PathMap::new(root),
|
||||
lines: Lines::default(),
|
||||
seen: HashSet::new(),
|
||||
done: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Messages completed by `line` (without its line break).
|
||||
pub fn feed(&mut self, line: &str) -> Vec<BuildMessage> {
|
||||
if self.done {
|
||||
return Vec::new();
|
||||
}
|
||||
let result = parse::strip_ansi(line);
|
||||
let result = result.trim();
|
||||
if result.len() > 6 && result.starts_with("** ") && result.ends_with(" **") {
|
||||
self.done = true;
|
||||
return self.finish();
|
||||
}
|
||||
let raws = self.parser.feed(line).messages;
|
||||
self.resolve(raws)
|
||||
}
|
||||
|
||||
/// The message still waiting for detail lines.
|
||||
pub fn finish(&mut self) -> Vec<BuildMessage> {
|
||||
let raws = self.parser.finish();
|
||||
self.resolve(raws)
|
||||
}
|
||||
|
||||
fn resolve(&mut self, raws: Vec<RawMessage>) -> Vec<BuildMessage> {
|
||||
raws.into_iter()
|
||||
.map(|raw| {
|
||||
let mut m = resolve(raw, &self.cwd, &self.paths, &mut self.lines);
|
||||
// xcodebuild prints the folder it was started in, which may be a symlink to the project.
|
||||
if let Some(path) = m.path.clone().map(PathBuf::from)
|
||||
&& !path.starts_with(&self.paths.root)
|
||||
&& let Ok(real) = dunce::canonicalize(&path)
|
||||
&& let Some(real) = real.to_str()
|
||||
{
|
||||
let mapped = self.paths.resolve(real, &self.cwd, None);
|
||||
if mapped.starts_with(&self.paths.root) {
|
||||
m.path = Some(mapped.into());
|
||||
}
|
||||
}
|
||||
m
|
||||
})
|
||||
.filter(|m| self.seen.insert((m.path.clone().map(Into::into), m.range, m.text.clone())))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-file editor / Problems diagnostics of the messages that have a position.
|
||||
pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
|
||||
diagnostics_from(messages, DIAGNOSTICS_SOURCE)
|
||||
}
|
||||
|
||||
/// [`diagnostics`] reported by `source`.
|
||||
pub fn diagnostics_from(messages: &[BuildMessage], source: &str) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
|
||||
let mut out: BTreeMap<PathBuf, Vec<Diagnostic>> = BTreeMap::new();
|
||||
for m in messages {
|
||||
let (Some(path), Some(range)) = (&m.path, m.range) else { continue };
|
||||
@@ -818,11 +897,11 @@ pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnosti
|
||||
range,
|
||||
severity: m.severity,
|
||||
message: m.text.clone(),
|
||||
source: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
source: Some(source.to_owned()),
|
||||
code: m.code.clone(),
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
server: Some(DIAGNOSTICS_SOURCE.to_owned()),
|
||||
server: Some(source.to_owned()),
|
||||
});
|
||||
}
|
||||
out
|
||||
@@ -1325,6 +1404,73 @@ mod tests {
|
||||
}
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn xcodebuild_messages_once_per_build() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let file = tmp.path().join("Warn.swift");
|
||||
std::fs::write(&file, "func f() -> Int {\n var count = 1\n return count\n}\n").unwrap();
|
||||
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
|
||||
let warning = format!("{}:2:9: warning: variable 'count' was never mutated", file.display());
|
||||
let mut out = Vec::new();
|
||||
// One copy per architecture, then the linker's per-architecture lists.
|
||||
for line in [
|
||||
warning.as_str(),
|
||||
"SwiftCompile normal arm64 Compiling\\ Warn.swift",
|
||||
warning.as_str(),
|
||||
"Undefined symbols for architecture x86_64:",
|
||||
" \"_sym\", referenced from:",
|
||||
"ld: symbol(s) not found for architecture x86_64",
|
||||
"Undefined symbols for architecture arm64:",
|
||||
" \"_sym\", referenced from:",
|
||||
] {
|
||||
out.extend(x.feed(line));
|
||||
}
|
||||
out.extend(x.finish());
|
||||
assert_eq!(out.len(), 2, "{out:?}");
|
||||
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(file));
|
||||
// `count`, 0-based, underlined.
|
||||
assert_eq!(out[0].range, Some(Range::new(Pos::new(1, 8), Pos::new(1, 13))));
|
||||
assert_eq!(
|
||||
(out[1].path.is_none(), out[1].text.as_str()),
|
||||
(true, "Undefined symbols\n\"_sym\", referenced from:")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xcodebuild_messages_stop_at_the_build_result() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut x = XcodebuildMessages::new(tmp.path(), tmp.path());
|
||||
let mut out = Vec::new();
|
||||
// An Xcode run configuration's output: the build, then the app's own console.
|
||||
for line in [
|
||||
"/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities'",
|
||||
"** BUILD SUCCEEDED **",
|
||||
"error: request failed",
|
||||
"warning: low memory",
|
||||
"Demo/ContentView.swift:12: Fatal error: Unexpectedly found nil while unwrapping an Optional value",
|
||||
] {
|
||||
out.extend(x.feed(line));
|
||||
}
|
||||
out.extend(x.finish());
|
||||
let texts: Vec<_> = out.iter().map(|m| m.text.as_str()).collect();
|
||||
assert_eq!(texts, ["Could not find or use auto-linked framework 'UIUtilities'"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn xcodebuild_paths_through_a_symlink_map_to_the_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("Demo");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
std::fs::write(root.join("A.swift"), "let x = y\n").unwrap();
|
||||
let link = tmp.path().join("link");
|
||||
std::os::unix::fs::symlink(&root, &link).unwrap();
|
||||
let mut x = XcodebuildMessages::new(&root, &root);
|
||||
x.feed(&format!("{}/A.swift:1:9: error: cannot find 'y' in scope", link.display()));
|
||||
let out = x.finish();
|
||||
assert_eq!(out[0].path.clone().map(PathBuf::from), Some(root.join("A.swift")));
|
||||
}
|
||||
|
||||
/// Launch outputs use the platform separator throughout, so they compare equal to
|
||||
/// the same directories as JDT LS reports them.
|
||||
#[test]
|
||||
@@ -1500,14 +1646,15 @@ mod tests {
|
||||
let cm = tmp.path().join("cm");
|
||||
write(&cm, "CMakeLists.txt", "project(app)");
|
||||
let args = |p: &BuildPlan| p.steps.iter().map(|s| s.args.join(" ")).collect::<Vec<_>>();
|
||||
let jobs = format!("-j {}", ide_core::build_jobs::default_jobs());
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Build, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(p.system, BuildSystem::CMake);
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
[
|
||||
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
|
||||
"--build build --config Debug"
|
||||
"-S . -B build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
|
||||
format!("--build build --config Debug {jobs}"),
|
||||
],
|
||||
"an unconfigured project is configured first"
|
||||
);
|
||||
@@ -1516,7 +1663,7 @@ mod tests {
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
["--build cmake-build-release --config Debug --clean-first"],
|
||||
[format!("--build cmake-build-release --config Debug --clean-first {jobs}")],
|
||||
"a configured directory is reused"
|
||||
);
|
||||
let profile = CMakeProfile {
|
||||
|
||||
@@ -27,6 +27,10 @@ pub(crate) enum Format {
|
||||
Gcc,
|
||||
/// MSBuild (`dotnet build`): `C:\p\A.cs(12,5): error CS1002: msg [C:\p\App.csproj]`.
|
||||
Msbuild,
|
||||
/// `xcodebuild`: swiftc / clang lines like [`Format::Gcc`], their notes (`path:3:6: note:` or
|
||||
/// Swift's `` `- note: `` in the code excerpt), `App.xcodeproj: App: ld: warning: msg` and
|
||||
/// `Undefined symbols for architecture arm64:` with its indented details.
|
||||
Xcode,
|
||||
}
|
||||
|
||||
/// What a printed column counts.
|
||||
@@ -331,6 +335,59 @@ fn gcc_line(line: &str) -> Option<RawMessage> {
|
||||
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte).at(path, ln, col))
|
||||
}
|
||||
|
||||
const UNDEFINED_SYMBOLS: &str = "Undefined symbols";
|
||||
|
||||
/// An `xcodebuild` message: a compiler line, a linker / build-system line without a location, or
|
||||
/// the start of an undefined symbols list. Its architecture is dropped: every one prints the same.
|
||||
fn xcode_line(line: &str) -> Option<RawMessage> {
|
||||
if let Some(m) = gcc_line(line) {
|
||||
return Some(m);
|
||||
}
|
||||
if line.starts_with("Undefined symbols for architecture ") {
|
||||
return Some(RawMessage::new(Severity::Error, UNDEFINED_SYMBOLS, ColUnit::Byte));
|
||||
}
|
||||
// `/p/App.xcodeproj: App: ld: warning: msg`, `error: msg`, `xcodebuild: error: msg`.
|
||||
let rest = [".xcodeproj: ", ".xcworkspace: "]
|
||||
.into_iter()
|
||||
.find_map(|c| line.find(c).map(|i| &line[i + c.len()..]))
|
||||
.or_else(|| (!line.starts_with(char::is_whitespace)).then_some(line))?;
|
||||
let (severity, msg) =
|
||||
[("error: ", Severity::Error), ("warning: ", Severity::Warning)].into_iter().find_map(|(word, severity)| {
|
||||
let at = rest.match_indices(word).map(|(i, _)| i).find(|&i| i == 0 || rest[..i].ends_with(": "))?;
|
||||
// Only `tool: ` / `target: ` words may come before the severity, not a sentence.
|
||||
rest[..at].split(": ").all(|w| !w.contains(' ')).then(|| (severity, rest[at + word.len()..].trim()))
|
||||
})?;
|
||||
(!msg.is_empty()).then(|| RawMessage::new(severity, msg, ColUnit::Byte))
|
||||
}
|
||||
|
||||
/// Whether `line` belongs to the pending `xcodebuild` message (and is folded into it).
|
||||
fn xcode_detail(msg: &mut RawMessage, line: &str) -> bool {
|
||||
let t = line.trim_start();
|
||||
// A `note:` with a location, as clang and `-diagnostic-style llvm` print it.
|
||||
if let Some((_, _, _, rest)) = path_line_col(line)
|
||||
&& let Some(note) = rest.strip_prefix(':').and_then(|r| r.trim_start().strip_prefix("note:"))
|
||||
{
|
||||
msg.text.push_str("\nnote: ");
|
||||
msg.text.push_str(note.trim());
|
||||
return true;
|
||||
}
|
||||
// The code excerpt: ` 9 | switch s {`, ` | `- note: add missing case`.
|
||||
let excerpt = t.trim_start_matches(|c: char| c.is_ascii_digit()).trim_start().starts_with('|');
|
||||
if excerpt {
|
||||
if let Some(i) = t.find("- note: ") {
|
||||
msg.text.push_str("\nnote: ");
|
||||
msg.text.push_str(t[i + "- note: ".len()..].trim());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if msg.text.starts_with(UNDEFINED_SYMBOLS) && t.len() < line.len() && !t.is_empty() {
|
||||
msg.text.push('\n');
|
||||
msg.text.push_str(t);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// rustc's JSON diagnostic (`reason: compiler-message`) → message and its rendered text.
|
||||
fn cargo_json(v: &Value) -> Option<(Option<RawMessage>, String)> {
|
||||
if v.get("reason")?.as_str()? != "compiler-message" {
|
||||
@@ -412,6 +469,9 @@ impl OutputParser {
|
||||
.map_or(line, |r| r.strip_prefix(' ').unwrap_or(r)),
|
||||
_ => line,
|
||||
};
|
||||
if format == Format::Xcode {
|
||||
return xcode_detail(&mut p.msg, line);
|
||||
}
|
||||
if matches!(format, Format::Maven | Format::Gradle | Format::Tsc)
|
||||
&& body.starts_with(" ")
|
||||
&& !body.trim().is_empty()
|
||||
@@ -447,6 +507,7 @@ impl OutputParser {
|
||||
Format::Go => go_line(&line),
|
||||
Format::Gcc => gcc_line(&line),
|
||||
Format::Msbuild => msbuild_line(&line),
|
||||
Format::Xcode => xcode_line(&line),
|
||||
Format::Cargo => None,
|
||||
};
|
||||
if let Some(msg) = parsed {
|
||||
@@ -678,6 +739,103 @@ mod tests {
|
||||
assert_eq!(out[2].text, "'missing.h' file not found");
|
||||
}
|
||||
|
||||
// Real `xcodebuild build` output (Xcode 27.1, iOS Simulator, two architectures), paths shortened.
|
||||
#[test]
|
||||
fn xcodebuild_swift_error_warning_and_note() {
|
||||
let out = parse(
|
||||
Format::Xcode,
|
||||
"SwiftCompile normal x86_64 Compiling\\ Warn.swift /p/Demo/Warn.swift (in target 'Demo' from project 'Demo')\n\
|
||||
/p/Demo/Warn.swift:2:9: warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
|
||||
\x201 | func warnMe() -> Int {\n\
|
||||
\x202 | var count = 1\n\
|
||||
\x20 | `- warning: variable 'count' was never mutated; consider changing to 'let' constant [#VariableNeverMutated]\n\
|
||||
\x203 | return count\n\
|
||||
\x204 | }\n\
|
||||
\n\
|
||||
/p/Demo/Warn.swift:9:5: error: switch must be exhaustive\n\
|
||||
\x207 | \n\
|
||||
\x208 | func name(_ s: Shade) -> String {\n\
|
||||
\x209 | switch s {\n\
|
||||
\x20 | |- error: switch must be exhaustive\n\
|
||||
\x20 | `- note: add missing case: '.dark'\n\
|
||||
10 | case .light: return \"light\"\n\
|
||||
11 | }\n\
|
||||
\n\
|
||||
[#VariableNeverMutated]: <https://docs.swift.org/compiler/documentation/diagnostics/variable-never-mutated>\n\
|
||||
Failed frontend command:\n\
|
||||
note: Removed stale file '/p/dd/Demo.swiftmodule'\n",
|
||||
);
|
||||
assert_eq!(out.len(), 2, "{out:?}");
|
||||
assert_eq!(out[0].severity, Severity::Warning);
|
||||
assert_eq!((out[0].path.as_deref(), out[0].line, out[0].col), (Some("/p/Demo/Warn.swift"), Some(2), Some(9)));
|
||||
assert!(out[0].text.starts_with("variable 'count' was never mutated"), "{}", out[0].text);
|
||||
assert_eq!(out[1].severity, Severity::Error);
|
||||
assert_eq!(out[1].text, "switch must be exhaustive\nnote: add missing case: '.dark'");
|
||||
assert_eq!((out[1].line, out[1].col), (Some(9), Some(5)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xcodebuild_clang_errors_with_note() {
|
||||
let out = parse(
|
||||
Format::Xcode,
|
||||
"/p/Demo/Legacy.m:2:29: error: use of undeclared identifier 'undeclared_thing'\n\
|
||||
\x20 2 | void legacy(void) { int x = undeclared_thing; }\n\
|
||||
\x20 | ^~~~~~~~~~~~~~~~\n\
|
||||
/p/Demo/Legacy.m:4:6: error: redefinition of 'twice'\n\
|
||||
\x20 4 | void twice(void) {}\n\
|
||||
\x20 | ^\n\
|
||||
/p/Demo/Legacy.m:3:6: note: previous definition is here\n\
|
||||
\x20 3 | void twice(void) {}\n\
|
||||
\x20 | ^\n\
|
||||
2 errors generated.\n",
|
||||
);
|
||||
assert_eq!(out.len(), 2, "{out:?}");
|
||||
assert_eq!(out[0].text, "use of undeclared identifier 'undeclared_thing'");
|
||||
assert_eq!((out[0].line, out[0].col), (Some(2), Some(29)));
|
||||
assert_eq!(out[1].text, "redefinition of 'twice'\nnote: previous definition is here");
|
||||
assert_eq!((out[1].line, out[1].col), (Some(4), Some(6)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xcodebuild_linker_errors_without_location() {
|
||||
let out = parse(
|
||||
Format::Xcode,
|
||||
"Ld /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
|
||||
\x20 cd /p/Demo\n\
|
||||
\x20 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -Xlinker -reproducible -target arm64-apple-ios16.0-simulator -ferror-limit 19\n\
|
||||
/p/Demo/Demo.xcodeproj: Demo: ld: warning: Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found\n\
|
||||
Undefined symbols for architecture arm64:\n\
|
||||
\x20 \"_missing_symbol_xyz\", referenced from:\n\
|
||||
\x20 Demo.callMissing() -> () in Missing.o\n\
|
||||
ld: symbol(s) not found for architecture arm64\n\
|
||||
/p/Demo/Demo.xcodeproj: Demo: clang: error: linker command failed with exit code 1 (use -v to see invocation)\n\
|
||||
\n\
|
||||
** BUILD FAILED **\n\
|
||||
\n\
|
||||
The following build commands failed:\n\
|
||||
\tLd /p/dd/Demo.debug.dylib normal arm64 (in target 'Demo' from project 'Demo')\n\
|
||||
xcodebuild: error: Unable to find a destination matching the provided destination specifier\n",
|
||||
);
|
||||
let found: Vec<_> = out.iter().map(|m| (m.severity, m.text.as_str(), m.path.is_none())).collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
(
|
||||
Severity::Warning,
|
||||
"Could not find or use auto-linked framework 'UIUtilities': framework 'UIUtilities' not found",
|
||||
true
|
||||
),
|
||||
(
|
||||
Severity::Error,
|
||||
"Undefined symbols\n\"_missing_symbol_xyz\", referenced from:\nDemo.callMissing() -> () in Missing.o",
|
||||
true
|
||||
),
|
||||
(Severity::Error, "linker command failed with exit code 1 (use -v to see invocation)", true),
|
||||
(Severity::Error, "Unable to find a destination matching the provided destination specifier", true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn go_errors() {
|
||||
let out = parse(
|
||||
|
||||
@@ -94,12 +94,12 @@ pub(super) fn build_javac_step(
|
||||
Ok(step)
|
||||
}
|
||||
|
||||
/// The resolved dependency classpath for one module and scope, tied to the same
|
||||
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
|
||||
/// The last resolved dependency classpath for one module and scope. A fingerprint
|
||||
/// permits reuse during a build; NoBuild also uses records without one.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct CachedClasspath {
|
||||
version: u32,
|
||||
fingerprint: LaunchFingerprint,
|
||||
fingerprint: Option<LaunchFingerprint>,
|
||||
classpath: String,
|
||||
}
|
||||
|
||||
@@ -162,9 +162,6 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
|
||||
.iter()
|
||||
.find(|p| root.join(&p.dir) == module)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
if project.packaging == "pom" {
|
||||
return Err(IdeError::not_found("the launch module is a Maven aggregator without sources"));
|
||||
}
|
||||
let top = maven_reactor(m, &project.dir)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
@@ -217,6 +214,30 @@ pub fn module_classpath(
|
||||
module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, cancel)
|
||||
}
|
||||
|
||||
/// Uses the last launch classpath, or probes dependencies without invoking the compile lifecycle.
|
||||
pub fn module_classpath_without_build(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
cache: &Path,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let target = module_target(root, model, module, test)?;
|
||||
if let Some(path) = classpath_cache_path(root, cache, module, test)
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(cached.classpath);
|
||||
}
|
||||
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
|
||||
}
|
||||
|
||||
/// [`module_classpath`] of `modules[0]`. The other modules, launched together with it
|
||||
/// (#3971), share its Maven probe when they have no cached classpath, which leaves
|
||||
/// theirs cached for their own launches.
|
||||
@@ -245,7 +266,7 @@ pub fn module_classpaths(
|
||||
&& let Ok(bytes) = fs::read(path)
|
||||
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& cached.fingerprint == *fingerprint
|
||||
&& cached.fingerprint.as_ref() == Some(fingerprint)
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
@@ -269,7 +290,7 @@ pub fn module_classpaths(
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
for (Probe(_, fingerprint, cache_path), classpath) in probes.into_iter().zip(&classpaths) {
|
||||
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
|
||||
if let Some(path) = cache_path {
|
||||
let cached =
|
||||
CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
|
||||
if let Err(error) = cache_classpath(&path, &cached) {
|
||||
@@ -675,6 +696,81 @@ mod tests {
|
||||
assert!(single_file_target(root, &model, &root.join("other/Main.java")).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn pom_launch_resolves_dependencies_without_compiling_for_no_build() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
fixture(&root);
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
|
||||
);
|
||||
let script = root.join("mvnw");
|
||||
write(
|
||||
&root,
|
||||
"mvnw",
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target\nprintf '/repo/runtime.jar' > app/target/ide-compile-cp.txt\n",
|
||||
);
|
||||
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(&root, &root.join("cache"), None);
|
||||
let cancel = CancellationToken::new();
|
||||
let cp = module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
|
||||
.unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert!(paths.contains(&root.join("lib/target/classes")), "{cp}");
|
||||
assert!(paths.contains(&root.join("shared/target/classes")), "{cp}");
|
||||
assert!(paths.contains(&PathBuf::from("/repo/runtime.jar")), "{cp}");
|
||||
assert!(!paths.contains(&root.join("app/target/classes")), "{cp}");
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(!args.lines().any(|a| matches!(a, "compile" | "package" | "test-compile")), "{args}");
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=runtime"), "{args}");
|
||||
|
||||
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
|
||||
let args = fs::read_to_string(root.join("args.txt")).unwrap();
|
||||
assert!(args.lines().any(|a| a == "compile"), "{args}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn no_build_keeps_the_last_launch_classpath_after_a_pom_change() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
fixture(&root);
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"mvnw",
|
||||
"#!/bin/sh\necho called >> calls.txt\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target repo\ntouch repo/runtime.jar repo/runtime-v2.jar\nif grep -q changed app/pom.xml; then printf \"$PWD/repo/runtime-v2.jar\" > app/target/ide-compile-cp.txt; else printf \"$PWD/repo/runtime.jar\" > app/target/ide-compile-cp.txt; fi\n",
|
||||
);
|
||||
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let model = crate::load(&root, &root.join("cache"), None);
|
||||
let cancel = CancellationToken::new();
|
||||
let previous =
|
||||
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
|
||||
assert!(previous.contains("repo/runtime.jar"), "{previous}");
|
||||
|
||||
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
|
||||
write(&root, "app/pom.xml", &pom.replace("</project>", "<description>changed</description></project>"));
|
||||
let launch =
|
||||
module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
|
||||
.unwrap();
|
||||
assert!(launch.contains("repo/runtime.jar"), "{launch}");
|
||||
assert!(!launch.contains("runtime-v2.jar"), "{launch}");
|
||||
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap().lines().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -0,0 +1,451 @@
|
||||
//! Problems › TypeScript project errors: the project's own `tsc --watch` on each root
|
||||
//! `tsconfig.json`, its output parsed like Build's tsc step, one compilation at a time.
|
||||
//!
|
||||
//! A background check never writes into the project. A plain project runs `tsc --noEmit -p`
|
||||
//! with its `.tsbuildinfo` (written by `composite` / `incremental` even without emit) moved to a
|
||||
//! scratch folder. `tsc -b` cannot check without emitting (`--noEmit` fails with TS6310 on
|
||||
//! composite references), and plain `tsc -p` on a project with references needs their built
|
||||
//! `.d.ts` (TS6305). So a solution runs `tsc -b` on scratch copies of its configurations: each
|
||||
//! `extends` the real one and only sends the outputs and `.tsbuildinfo` to the scratch folder,
|
||||
//! keeping every option, file list and source position of the project.
|
||||
|
||||
use super::parse::{Format, OutputParser, RawMessage};
|
||||
use super::{BuildMessage, Lines, PathMap, resolve};
|
||||
use crate::process;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
// ponytail: one `tsc` per root; past this the shallowest roots win. Raise it, or watch
|
||||
// on demand, if monorepos without a solution tsconfig need more.
|
||||
const MAX_ROOTS: usize = 8;
|
||||
|
||||
/// The configurations among `found` (the `tsconfig.json` files of the project) that no other
|
||||
/// one references: the ones a watcher runs on. Referenced projects are checked by their solution.
|
||||
pub fn tsc_watch_roots(found: Vec<PathBuf>) -> Vec<PathBuf> {
|
||||
let referenced: BTreeSet<PathBuf> = found.iter().flat_map(|c| references(c)).collect();
|
||||
let mut roots: Vec<PathBuf> = found.into_iter().filter(|c| !referenced.contains(c)).collect();
|
||||
roots.sort_by_key(|c| (c.components().count(), c.clone()));
|
||||
roots.truncate(MAX_ROOTS);
|
||||
roots
|
||||
}
|
||||
|
||||
fn read_json(path: &Path) -> Option<Value> {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
serde_json::from_str(&ide_core::jsonc::strip(&text)).ok()
|
||||
}
|
||||
|
||||
/// The configurations `config` lists in `references` (a folder means its `tsconfig.json`).
|
||||
fn references(config: &Path) -> Vec<PathBuf> {
|
||||
let Some(json) = read_json(config) else { return Vec::new() };
|
||||
let dir = config.parent().unwrap_or(Path::new(""));
|
||||
let refs = json.get("references").and_then(|r| r.as_array()).into_iter().flatten();
|
||||
refs.filter_map(|r| r.get("path")?.as_str())
|
||||
.map(|p| {
|
||||
let p = super::normalize(&dir.join(p));
|
||||
if p.extension().is_some_and(|e| e == "json") { p } else { p.join("tsconfig.json") }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A configuration and the ones it `extends`, most derived first, each with its folder (the
|
||||
/// base of its relative paths). A package base (`@tsconfig/node20/tsconfig.json`) is looked up
|
||||
/// in `node_modules` above the configuration.
|
||||
fn chain(config: &Path) -> Vec<(PathBuf, Value)> {
|
||||
let mut out = Vec::new();
|
||||
let mut next = vec![config.to_path_buf()];
|
||||
// A cycle or a deep chain ends here.
|
||||
while let Some(path) = next.pop().filter(|_| out.len() < 16) {
|
||||
let Some(json) = read_json(&path) else { continue };
|
||||
let dir = path.parent().unwrap_or(Path::new("")).to_path_buf();
|
||||
let bases: Vec<String> = match json.get("extends") {
|
||||
Some(Value::String(s)) => vec![s.clone()],
|
||||
Some(Value::Array(a)) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
// Later bases override earlier ones: visit them first.
|
||||
next.extend(bases.iter().filter_map(|b| resolve_base(&dir, b)));
|
||||
out.push((dir, json));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn resolve_base(dir: &Path, base: &str) -> Option<PathBuf> {
|
||||
let with_json = |p: PathBuf| {
|
||||
if p.is_dir() {
|
||||
p.join("tsconfig.json")
|
||||
} else if p.extension().is_some_and(|e| e == "json") {
|
||||
p
|
||||
} else {
|
||||
let mut s = p.into_os_string();
|
||||
s.push(".json");
|
||||
PathBuf::from(s)
|
||||
}
|
||||
};
|
||||
if base.starts_with('.') || Path::new(base).is_absolute() {
|
||||
return Some(with_json(super::normalize(&dir.join(base))));
|
||||
}
|
||||
dir.ancestors().map(|a| with_json(a.join("node_modules").join(base))).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// The first value of `key` (a top-level key, or `compilerOptions.<key>`) along `chain`, with the
|
||||
/// folder it is relative to.
|
||||
fn lookup<'a>(chain: &'a [(PathBuf, Value)], key: &str) -> Option<(&'a Path, &'a Value)> {
|
||||
chain.iter().find_map(|(dir, json)| {
|
||||
let value = match key.strip_prefix("compilerOptions.") {
|
||||
Some(option) => json.get("compilerOptions")?.get(option)?,
|
||||
None => json.get(key)?,
|
||||
};
|
||||
Some((dir.as_path(), value))
|
||||
})
|
||||
}
|
||||
|
||||
/// The scratch copy of `config` for `tsc -b`: the real configuration with its outputs and
|
||||
/// `.tsbuildinfo` in `scratch` (file `<n>`), referencing the scratch copies `refs`. Settings that
|
||||
/// default relative to the configuration's own folder are spelled out, since the copy lives
|
||||
/// elsewhere: the files (`**/*`), their exclusions (`node_modules`, the output folder) and the
|
||||
/// `rootDir` of a composite project.
|
||||
fn scratch_config(config: &Path, scratch: &Path, n: usize, refs: &[PathBuf]) -> Value {
|
||||
let chain = chain(config);
|
||||
let dir = config.parent().unwrap_or(Path::new(""));
|
||||
let out = scratch.join(n.to_string());
|
||||
let mut options = json!({ "outDir": out, "tsBuildInfoFile": scratch.join(format!("{n}.tsbuildinfo")) });
|
||||
if lookup(&chain, "compilerOptions.declarationDir").is_some() {
|
||||
options["declarationDir"] = json!(out);
|
||||
}
|
||||
if lookup(&chain, "compilerOptions.outFile").is_some() {
|
||||
options["outFile"] = json!(out.join("out.js"));
|
||||
}
|
||||
if lookup(&chain, "compilerOptions.composite").is_some_and(|(_, v)| v == &json!(true))
|
||||
&& lookup(&chain, "compilerOptions.rootDir").is_none()
|
||||
{
|
||||
options["rootDir"] = json!(dir);
|
||||
}
|
||||
let mut copy = json!({
|
||||
"extends": config,
|
||||
"compilerOptions": options,
|
||||
"references": refs.iter().map(|r| json!({ "path": r })).collect::<Vec<_>>(),
|
||||
});
|
||||
if lookup(&chain, "include").is_none() && lookup(&chain, "files").is_none() {
|
||||
copy["include"] = json!([dir.join("**/*")]);
|
||||
}
|
||||
if lookup(&chain, "exclude").is_none() {
|
||||
let mut exclude = vec![dir.join("node_modules")];
|
||||
if let Some((base, Value::String(out_dir))) = lookup(&chain, "compilerOptions.outDir") {
|
||||
exclude.push(super::normalize(&base.join(out_dir)));
|
||||
}
|
||||
copy["exclude"] = json!(exclude);
|
||||
}
|
||||
copy
|
||||
}
|
||||
|
||||
/// The `tsc` arguments that watch `config` without writing into the project, writing the
|
||||
/// scratch configurations a solution needs into `scratch`.
|
||||
fn watch_args(config: &Path, scratch: &Path) -> std::io::Result<Vec<String>> {
|
||||
let path = |p: &Path| p.to_string_lossy().into_owned();
|
||||
let mut args: Vec<String> = if references(config).is_empty() {
|
||||
let name = config.file_name().map_or_else(|| "tsconfig.json".into(), |n| n.to_string_lossy().into_owned());
|
||||
let info = path(&scratch.join("tsconfig.tsbuildinfo"));
|
||||
["--noEmit", "-p", &name, "--incremental", "--tsBuildInfoFile", &info].map(String::from).to_vec()
|
||||
} else {
|
||||
// Every configuration the solution reaches gets a number: the solution 0, then in order.
|
||||
let mut numbers: BTreeMap<PathBuf, usize> = BTreeMap::from([(config.to_path_buf(), 0)]);
|
||||
let mut queue = vec![config.to_path_buf()];
|
||||
let mut i = 0;
|
||||
while i < queue.len() {
|
||||
let current = queue[i].clone();
|
||||
let refs: Vec<PathBuf> = references(¤t)
|
||||
.into_iter()
|
||||
.map(|r| {
|
||||
let next = numbers.len();
|
||||
let n = *numbers.entry(r.clone()).or_insert_with(|| {
|
||||
queue.push(r);
|
||||
next
|
||||
});
|
||||
scratch.join(format!("{n}.json"))
|
||||
})
|
||||
.collect();
|
||||
let copy = scratch_config(¤t, scratch, numbers[¤t], &refs);
|
||||
std::fs::write(scratch.join(format!("{}.json", numbers[¤t])), copy.to_string())?;
|
||||
i += 1;
|
||||
}
|
||||
vec!["-b".into(), path(&scratch.join("0.json"))]
|
||||
};
|
||||
args.extend(["--watch", "--pretty", "false", "--preserveWatchOutput"].map(String::from));
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
/// The project's own `tsc` (`node_modules/.bin` from the configuration's folder up to `root`).
|
||||
fn local_tsc(root: &Path, dir: &Path) -> Option<PathBuf> {
|
||||
dir.ancestors()
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find_map(|d| ide_core::tool_path::find_command("tsc", d.join("node_modules/.bin").as_os_str(), dir))
|
||||
}
|
||||
|
||||
/// The messages of one compilation at a time: tsc ends each with
|
||||
/// `… - Found 2 errors. Watching for file changes.` `tsc -b` reports the errors of every
|
||||
/// project of the solution that has some, rebuilt this time or not ("out of date because it had
|
||||
/// errors"), so each compilation's list replaces the last.
|
||||
#[derive(Default)]
|
||||
struct Compilations {
|
||||
parser: Option<OutputParser>,
|
||||
raws: Vec<RawMessage>,
|
||||
}
|
||||
|
||||
impl Compilations {
|
||||
fn feed(&mut self, line: &str) -> Option<Vec<RawMessage>> {
|
||||
let parser = self.parser.get_or_insert_with(|| OutputParser::new(Format::Tsc));
|
||||
if line.contains("Watching for file changes.") {
|
||||
self.raws.extend(parser.finish());
|
||||
return Some(std::mem::take(&mut self.raws));
|
||||
}
|
||||
self.raws.extend(parser.feed(line).messages);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A scratch folder of this process for `config`, removed when dropped.
|
||||
struct Scratch(PathBuf);
|
||||
|
||||
impl Scratch {
|
||||
fn new(config: &Path) -> std::io::Result<Self> {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hash = std::collections::hash_map::DefaultHasher::new();
|
||||
config.hash(&mut hash);
|
||||
let dir = std::env::temp_dir().join("openidea-tsc-watch").join(format!(
|
||||
"{}-{:016x}",
|
||||
std::process::id(),
|
||||
hash.finish()
|
||||
));
|
||||
// Fresh: a `.tsbuildinfo` left by an earlier run would make tsc skip unchanged projects.
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(Scratch(dir))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Scratch {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the project's `tsc --watch` on `config` until `cancel` fires or tsc exits, handing the
|
||||
/// messages of every finished compilation (all of them, an empty list when it passes) to
|
||||
/// `on_compilation`. Not found when the project has no TypeScript of its own.
|
||||
pub fn tsc_watch(
|
||||
root: &Path,
|
||||
config: &Path,
|
||||
cancel: &CancellationToken,
|
||||
mut on_compilation: impl FnMut(Vec<BuildMessage>),
|
||||
) -> IdeResult<()> {
|
||||
let dir = config.parent().ok_or_else(|| IdeError::invalid("no tsconfig folder"))?;
|
||||
let tsc = local_tsc(root, dir).ok_or_else(|| IdeError::not_found("no local typescript"))?;
|
||||
let scratch = Scratch::new(config)?;
|
||||
let args = watch_args(config, &scratch.0)?;
|
||||
let paths = PathMap::new(root);
|
||||
let mut compilations = Compilations::default();
|
||||
let program = tsc.to_string_lossy();
|
||||
process::run_bounded(&program, &args, dir, &BTreeMap::new(), cancel, |_, line| {
|
||||
if let Some(raws) = compilations.feed(line) {
|
||||
// Fresh file texts each time: the files changed since the last compilation.
|
||||
let mut lines = Lines::default();
|
||||
on_compilation(raws.into_iter().map(|r| resolve(r, dir, &paths, &mut lines)).collect());
|
||||
}
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(dir: &Path, rel: &str, text: &str) {
|
||||
let p = dir.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roots_are_the_configurations_no_other_one_references() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
// A solution with references (one by folder, one by file), plus an unrelated package.
|
||||
write(
|
||||
root,
|
||||
"tsconfig.json",
|
||||
r#"{ "files": [], // solution
|
||||
"references": [{ "path": "./packages/a" }, { "path": "packages/b/tsconfig.json" },] }"#,
|
||||
);
|
||||
write(root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(root, "packages/b/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(root, "tools/cli/tsconfig.json", "{}");
|
||||
let found = ["tools/cli", "packages/b", "", "packages/a"].map(|d| root.join(d).join("tsconfig.json"));
|
||||
assert_eq!(tsc_watch_roots(found.to_vec()), [root.join("tsconfig.json"), root.join("tools/cli/tsconfig.json")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_solution_is_checked_through_scratch_copies_of_its_configurations() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
|
||||
std::fs::create_dir_all(&scratch).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"tsconfig.json",
|
||||
r#"{"files": [], "references": [{"path": "./packages/a"}, {"path": "./packages/b"}]}"#,
|
||||
);
|
||||
// a: composite, every setting by default.
|
||||
write(&root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
// b: references a, settles its files, outputs and root in a shared base.
|
||||
write(
|
||||
&root,
|
||||
"packages/b/tsconfig.json",
|
||||
r#"{"extends": "../../tsconfig.base", "references": [{"path": "../a"}], "compilerOptions": {"outFile": "b.js"}}"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"tsconfig.base.json",
|
||||
r#"{"compilerOptions": {"composite": true, "rootDir": ".", "outDir": "dist", "declarationDir": "types"},
|
||||
"include": ["packages/*/src"]}"#,
|
||||
);
|
||||
let args = watch_args(&root.join("tsconfig.json"), &scratch).unwrap();
|
||||
let s = |p: &str| scratch.join(p).to_string_lossy().into_owned();
|
||||
assert_eq!(args, ["-b", &s("0.json"), "--watch", "--pretty", "false", "--preserveWatchOutput"]);
|
||||
let copy = |n: usize| read_json(&scratch.join(format!("{n}.json"))).unwrap();
|
||||
let path = |p: &Path| json!(p);
|
||||
assert_eq!(
|
||||
copy(0),
|
||||
json!({
|
||||
"extends": path(&root.join("tsconfig.json")),
|
||||
"compilerOptions": {"outDir": path(&scratch.join("0")), "tsBuildInfoFile": s("0.tsbuildinfo")},
|
||||
"references": [{"path": s("1.json")}, {"path": s("2.json")}],
|
||||
"exclude": [path(&root.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
// Chained joins: the configurations name native paths, `packages/a` would mix separators on Windows.
|
||||
let a = root.join("packages").join("a");
|
||||
assert_eq!(
|
||||
copy(1),
|
||||
json!({
|
||||
"extends": path(&a.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("1")), "tsBuildInfoFile": s("1.tsbuildinfo"), "rootDir": path(&a),
|
||||
},
|
||||
"references": [],
|
||||
"include": [path(&a.join("**/*"))],
|
||||
"exclude": [path(&a.join("node_modules"))],
|
||||
})
|
||||
);
|
||||
let b = root.join("packages").join("b");
|
||||
assert_eq!(
|
||||
copy(2),
|
||||
json!({
|
||||
"extends": path(&b.join("tsconfig.json")),
|
||||
"compilerOptions": {
|
||||
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
|
||||
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2").join("out.js")),
|
||||
},
|
||||
"references": [{"path": s("1.json")}],
|
||||
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_composite_package_base_gets_its_root_folder() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
|
||||
write(&root, "node_modules/@acme/tsconfig/base.json", r#"{"compilerOptions": {"composite": true}}"#);
|
||||
write(&root, "app/tsconfig.json", r#"{"extends": "@acme/tsconfig/base", "include": ["src"]}"#);
|
||||
let copy = scratch_config(&root.join("app/tsconfig.json"), &scratch, 3, &[]);
|
||||
assert_eq!(copy["compilerOptions"]["rootDir"], json!(root.join("app")));
|
||||
assert_eq!(copy.get("include"), None, "the files come from the real configuration");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_compilation_reports_its_own_messages() {
|
||||
// `tsc --noEmit --watch --pretty false --preserveWatchOutput`, as printed.
|
||||
let output = "\
|
||||
2:14:08 PM - Starting compilation in watch mode...
|
||||
|
||||
2:14:09 PM - Found 0 errors. Watching for file changes.
|
||||
2:14:12 PM - File change detected. Starting incremental compilation...
|
||||
|
||||
src/b.ts(1,37): error TS2322: Type 'string' is not assignable to type 'number'.
|
||||
src/c.ts(2,1): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
|
||||
Type 'string' is not assignable to type 'number'.
|
||||
|
||||
2:14:12 PM - Found 2 errors. Watching for file changes.
|
||||
2:14:15 PM - File change detected. Starting incremental compilation...
|
||||
|
||||
2:14:15 PM - Found 0 errors. Watching for file changes.";
|
||||
let mut compilations = Compilations::default();
|
||||
let found: Vec<Vec<(String, Option<String>)>> = output
|
||||
.lines()
|
||||
.filter_map(|l| compilations.feed(l))
|
||||
.map(|raws| raws.into_iter().map(|r| (r.path.unwrap_or_default(), r.code)).collect())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[
|
||||
vec![],
|
||||
vec![("src/b.ts".into(), Some("TS2322".into())), ("src/c.ts".into(), Some("TS2345".into()))],
|
||||
vec![]
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn the_projects_tsc_reports_until_cancelled() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(root, "app/tsconfig.json", "{}");
|
||||
write(root, "app/src/b.ts", "export const b: number = a;\n");
|
||||
// A watcher that prints one compilation and keeps running, like `tsc --watch`.
|
||||
write(
|
||||
root,
|
||||
"node_modules/.bin/tsc",
|
||||
"#!/bin/sh\necho \"$@\" > args.txt\n\
|
||||
echo 'src/b.ts(1,26): error TS2322: Type string is not assignable to type number.'\n\
|
||||
echo '1:00:00 PM - Found 1 error. Watching for file changes.'\nexec sleep 30\n",
|
||||
);
|
||||
let bin = root.join("node_modules/.bin/tsc");
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let mut compilations = Vec::new();
|
||||
let started = std::time::Instant::now();
|
||||
let result = tsc_watch(root, &root.join("app/tsconfig.json"), &cancel, |messages| {
|
||||
compilations.push(messages);
|
||||
cancel.cancel();
|
||||
});
|
||||
assert_eq!(result.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
|
||||
assert!(started.elapsed().as_secs() < 10, "cancelling stops the watcher");
|
||||
let [messages] = &compilations[..] else { panic!("{compilations:?}") };
|
||||
let paths: Vec<_> = messages.iter().map(|m| (m.path.clone().map(PathBuf::from), m.range)).collect();
|
||||
let at = |l, c| ide_core::Pos::new(l, c);
|
||||
assert_eq!(paths, [(Some(root.join("app/src/b.ts")), Some(ide_core::Range::new(at(0, 25), at(0, 26))))]);
|
||||
let args = std::fs::read_to_string(root.join("app/args.txt")).unwrap();
|
||||
let (check, rest) = args.trim().split_once(" --tsBuildInfoFile ").unwrap();
|
||||
assert_eq!(check, "--noEmit -p tsconfig.json --incremental");
|
||||
let (info, watch) = rest.split_once(' ').unwrap();
|
||||
assert_eq!(watch, "--watch --pretty false --preserveWatchOutput");
|
||||
// The `.tsbuildinfo` goes to a scratch folder outside the project, gone with the watcher.
|
||||
let scratch = Path::new(info).parent().unwrap();
|
||||
assert!(scratch.starts_with(std::env::temp_dir()) && !scratch.starts_with(root), "{info}");
|
||||
assert!(!scratch.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_local_typescript_runs_nothing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write(tmp.path(), "tsconfig.json", "{}");
|
||||
let err = tsc_watch(tmp.path(), &tmp.path().join("tsconfig.json"), &CancellationToken::new(), |_| {
|
||||
panic!("no compilation without typescript")
|
||||
})
|
||||
.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,10 @@
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const SETTINGS_FILES: &[&str] = &["settings.gradle.kts", "settings.gradle"];
|
||||
pub const BUILD_FILES: &[&str] = &["build.gradle.kts", "build.gradle"];
|
||||
@@ -227,9 +229,41 @@ pub fn build_dir(root: &Path) -> Option<PathBuf> {
|
||||
build_dirs(root).into_iter().next()
|
||||
}
|
||||
|
||||
/// How long [`cached_build_dirs`] reuses a walk. Project roots, content roots and the index
|
||||
/// ask for the builds many times while a project opens; on a network share each walk is
|
||||
/// thousands of round trips. A build file changing in a project calls [`forget_build_dirs`].
|
||||
const BUILD_DIRS_TTL: Duration = Duration::from_secs(30);
|
||||
|
||||
type BuildDirsCache = HashMap<PathBuf, (Instant, Vec<PathBuf>)>;
|
||||
|
||||
static BUILD_DIRS: Mutex<Option<BuildDirsCache>> = Mutex::new(None);
|
||||
|
||||
/// Walks for builds now; the result also refreshes [`cached_build_dirs`].
|
||||
fn build_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
let markers: Vec<_> = SETTINGS_FILES.iter().chain(BUILD_FILES).copied().collect();
|
||||
ide_core::project_roots::discover(root, &markers)
|
||||
let dirs = ide_core::project_roots::discover(root, &markers);
|
||||
let now = Instant::now();
|
||||
let mut guard = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let map = guard.get_or_insert_with(HashMap::new);
|
||||
map.retain(|_, (at, _)| now.duration_since(*at) < BUILD_DIRS_TTL);
|
||||
map.insert(root.to_path_buf(), (now, dirs.clone()));
|
||||
dirs
|
||||
}
|
||||
|
||||
fn cached_build_dirs(root: &Path) -> Vec<PathBuf> {
|
||||
let cached = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(root)).cloned();
|
||||
match cached {
|
||||
Some((at, dirs)) if at.elapsed() < BUILD_DIRS_TTL => dirs,
|
||||
_ => build_dirs(root),
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets the discovered Gradle builds of `root`, and of folders above or below it
|
||||
/// (after a build or settings script appeared, changed or was removed there).
|
||||
pub fn forget_build_dirs(root: &Path) {
|
||||
if let Some(map) = BUILD_DIRS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
|
||||
map.retain(|dir, _| !dir.starts_with(root) && !root.starts_with(dir));
|
||||
}
|
||||
}
|
||||
|
||||
fn wrapper(dir: &Path) -> String {
|
||||
@@ -506,10 +540,23 @@ pub fn linked_project_key(root: &Path, dir: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linked build identities without reading their scripts (also used by index hot paths).
|
||||
/// Linked build identities without reading their scripts, as of now (a sync, a build).
|
||||
pub(crate) fn linked_dirs(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
linked_dirs_from(root, settings, build_dirs)
|
||||
}
|
||||
|
||||
/// [`linked_dirs`] for hot paths (project and index roots): discovered builds are reused for a while.
|
||||
pub(crate) fn linked_dirs_cached(root: &Path, settings: &ide_core::settings::GradleSettings) -> Vec<String> {
|
||||
linked_dirs_from(root, settings, cached_build_dirs)
|
||||
}
|
||||
|
||||
fn linked_dirs_from(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
discover: fn(&Path) -> Vec<PathBuf>,
|
||||
) -> Vec<String> {
|
||||
match &settings.linked_projects {
|
||||
None => build_dirs(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
None => discover(root).iter().map(|dir| rel(root, dir)).collect(),
|
||||
Some(dirs) => {
|
||||
let mut out = Vec::new();
|
||||
for dir in dirs {
|
||||
@@ -1047,6 +1094,27 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn discovered_builds_are_reused_until_forgotten() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
std::fs::create_dir_all(root.join("a")).unwrap();
|
||||
std::fs::write(root.join("a/settings.gradle"), "").unwrap();
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
|
||||
std::fs::create_dir_all(root.join("b")).unwrap();
|
||||
std::fs::write(root.join("b/build.gradle"), "").unwrap();
|
||||
// A walk per call is thousands of round trips on a network share.
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a")]);
|
||||
super::forget_build_dirs(&root.join("b"));
|
||||
assert_eq!(super::cached_build_dirs(root), vec![root.join("a"), root.join("b")]);
|
||||
// A sync sees a new build at once, and so does every later lookup.
|
||||
std::fs::create_dir_all(root.join("c")).unwrap();
|
||||
std::fs::write(root.join("c/build.gradle"), "").unwrap();
|
||||
let all = vec![root.join("a"), root.join("b"), root.join("c")];
|
||||
assert_eq!(super::build_dirs(root), all);
|
||||
assert_eq!(super::cached_build_dirs(root), all);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_linkage_discovers_all_shallow_builds() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -46,6 +46,16 @@ fn subdir(root: &Path, rel: &str) -> PathBuf {
|
||||
root.join(rel).components().collect()
|
||||
}
|
||||
|
||||
/// The `-pl` value selecting `projects` in their Maven reactor, by `groupId:artifactId`. Their
|
||||
/// directories are the absolute `basedir`s Maven reported, which need not share a spelling with the
|
||||
/// opened folder (drive letter case, separators, links), so a path selector could miss the reactor.
|
||||
fn maven_project_selection<'a>(projects: impl Iterator<Item = &'a ProjectModel>) -> String {
|
||||
let mut selection: Vec<String> = projects.map(|p| format!("{}:{}", p.group_id, p.artifact_id)).collect();
|
||||
selection.sort();
|
||||
selection.dedup();
|
||||
selection.join(",")
|
||||
}
|
||||
|
||||
/// The resident part of the build: javac servers and one lock per reactor.
|
||||
#[derive(Default)]
|
||||
pub struct JavaBuildService {
|
||||
@@ -441,7 +451,7 @@ impl JavaBuild<'_> {
|
||||
let record = model::load_record(&model::reactor_dir(self.cache, &top.key()))?;
|
||||
let project = record.model.projects.iter().find(|p| p.dir == module)?;
|
||||
let paths = class_paths(project, test);
|
||||
paths.first().is_some_and(|p| p.is_dir()).then_some(paths)
|
||||
paths.first().is_some_and(|p| p.exists()).then_some(paths)
|
||||
}
|
||||
|
||||
/// Builds `target`. A launch gets the classpath to run with; the others an empty one.
|
||||
@@ -691,17 +701,8 @@ impl JavaBuild<'_> {
|
||||
let out = model::output_root(self.cache, &top.key());
|
||||
let step = match top {
|
||||
Reactor::Maven(top) => {
|
||||
let top_dir = subdir(self.root, &top.dir);
|
||||
let mut selection: Vec<String> = changed
|
||||
.iter()
|
||||
.map(|(p, _, _)| {
|
||||
let rel = p.dir.strip_prefix(&top_dir).unwrap_or(&p.dir).to_string_lossy().replace('\\', "/");
|
||||
if rel.is_empty() { ".".to_owned() } else { rel }
|
||||
})
|
||||
.collect();
|
||||
selection.sort();
|
||||
selection.dedup();
|
||||
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection.join(",")];
|
||||
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
|
||||
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection];
|
||||
extra.push("resources:resources".into());
|
||||
if changed.iter().any(|(_, test, _)| *test) {
|
||||
extra.push("resources:testResources".into());
|
||||
@@ -1039,7 +1040,7 @@ fn launch_projects<'a>(model: &'a ReactorModel, target: &'a ProjectModel, test:
|
||||
if test {
|
||||
visit(project, false, by_output, by_test_output, seen, out);
|
||||
}
|
||||
for entry in &project.set(test).classpath {
|
||||
for entry in project.set(test).classpath.iter().chain(&project.set(test).runtime_classpath) {
|
||||
if let Some(upstream) = by_output.get(entry.as_path()).filter(|p| p.dir != project.dir) {
|
||||
visit(upstream, false, by_output, by_test_output, seen, out);
|
||||
} else if let Some(upstream) = by_test_output.get(entry.as_path()).filter(|p| p.dir != project.dir) {
|
||||
@@ -1061,10 +1062,12 @@ fn class_paths(target: &ProjectModel, test: bool) -> Vec<PathBuf> {
|
||||
out.push(p.clone());
|
||||
}
|
||||
};
|
||||
if test {
|
||||
push(&target.test.output);
|
||||
if target.packaging != "pom" {
|
||||
if test {
|
||||
push(&target.test.output);
|
||||
}
|
||||
push(&target.main.output);
|
||||
}
|
||||
push(&target.main.output);
|
||||
for entry in &target.set(test).runtime_classpath {
|
||||
push(entry);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,50 @@ fn write(root: &Path, rel: &str, text: &str) {
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
fn build_output_tail(events: &[BuildEvent]) -> String {
|
||||
let mut lines: Vec<_> = events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
BuildEvent::Output { text, .. } => Some(text.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(str::lines)
|
||||
.rev()
|
||||
.take(150)
|
||||
.collect();
|
||||
lines.reverse();
|
||||
lines.join("\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_output_tail_keeps_the_last_150_lines_across_streams() {
|
||||
let lines = |range: std::ops::Range<usize>| range.map(|n| n.to_string()).collect::<Vec<_>>().join("\n");
|
||||
let events = [
|
||||
BuildEvent::Output { text: lines(0..100), stderr: false },
|
||||
BuildEvent::Progress { message: "building".into(), fraction: None },
|
||||
BuildEvent::Output { text: lines(100..155), stderr: true },
|
||||
];
|
||||
assert_eq!(build_output_tail(&events), lines(5..155));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
|
||||
// Maven reports absolute basedirs whose spelling can differ from the opened folder on Windows
|
||||
// (`D:/worktree/jxc/organ` against `d:\\worktree\\jxc`); coordinates always name a reactor project.
|
||||
let project = |dir: &str, artifact: &str| ProjectModel {
|
||||
dir: PathBuf::from(dir),
|
||||
group_id: "org.starry".into(),
|
||||
artifact_id: artifact.into(),
|
||||
..Default::default()
|
||||
};
|
||||
let projects = [
|
||||
project("D:/worktree/jxc/organ", "organ"),
|
||||
project("D:/worktree/jxc", "cloud"),
|
||||
project("D:/worktree/jxc/organ", "organ"),
|
||||
];
|
||||
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
|
||||
}
|
||||
|
||||
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
|
||||
fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
|
||||
@@ -18,15 +62,9 @@ fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
Some((home, mvn))
|
||||
}
|
||||
|
||||
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
|
||||
<modules><module>lib</module><module>app</module></modules>
|
||||
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
|
||||
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
|
||||
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
|
||||
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
|
||||
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
|
||||
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
|
||||
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
|
||||
const ROOT_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/pom.xml");
|
||||
const LIB_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/lib/pom.xml");
|
||||
const APP_POM: &str = include_str!("../../tests/fixtures/jbuild-maven/app/pom.xml");
|
||||
|
||||
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
|
||||
struct Fixture {
|
||||
@@ -145,7 +183,10 @@ impl Fixture {
|
||||
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
@@ -216,7 +257,7 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{steps:?}");
|
||||
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl t:app"), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
|
||||
|
||||
// A deleted source leaves no class behind.
|
||||
|
||||
@@ -91,12 +91,14 @@ fn plan(root: &Path, model: &BuildModel, cancel: &CancellationToken) -> IdeResul
|
||||
|
||||
/// Run the project's configured wrapper/settings/JDK and lifecycle, with an output
|
||||
/// redirector loaded before Maven calculates its lifecycle execution plans.
|
||||
/// Builds the Kotlin libraries; `on_progress` gets Maven's progress (message, fraction 0..1).
|
||||
pub fn build(
|
||||
root: &Path,
|
||||
model: &BuildModel,
|
||||
bundle: &Path,
|
||||
generation: &Path,
|
||||
cancel: &CancellationToken,
|
||||
on_progress: &(dyn Fn(&str, Option<f32>) + Sync),
|
||||
) -> IdeResult<Outcome> {
|
||||
std::fs::create_dir_all(generation)?;
|
||||
let mut plan = plan(root, model, cancel)?;
|
||||
@@ -124,10 +126,10 @@ pub fn build(
|
||||
for step in &plan.steps {
|
||||
let mut reactor = plan.clone();
|
||||
reactor.steps = vec![step.clone()];
|
||||
let result = compile::run(root, &reactor, cancel, &|event| {
|
||||
if let BuildEvent::Output { text, .. } = event {
|
||||
tracing::debug!("kotlin bridge: {}", text.trim_end());
|
||||
}
|
||||
let result = compile::run(root, &reactor, cancel, &|event| match event {
|
||||
BuildEvent::Output { text, .. } => tracing::debug!("kotlin bridge: {}", text.trim_end()),
|
||||
BuildEvent::Progress { message, fraction } => on_progress(&message, fraction),
|
||||
_ => {}
|
||||
})?;
|
||||
messages.extend(result.messages);
|
||||
}
|
||||
@@ -456,6 +458,7 @@ mod tests {
|
||||
Path::new("unused.jar"),
|
||||
&directory.path().join("private"),
|
||||
&CancellationToken::new(),
|
||||
&|_, _| {},
|
||||
)
|
||||
.err()
|
||||
.unwrap();
|
||||
|
||||
@@ -129,7 +129,7 @@ pub fn gradle_external_roots(
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<PathBuf> {
|
||||
let builds = gradle::linked_dirs(root, settings);
|
||||
let builds = gradle::linked_dirs_cached(root, settings);
|
||||
let dirs: Vec<String> = builds
|
||||
.iter()
|
||||
.flat_map(|dir| {
|
||||
@@ -171,7 +171,7 @@ pub fn gradle_source_roots(
|
||||
cache_dir: &Path,
|
||||
settings: &ide_core::settings::GradleSettings,
|
||||
) -> Vec<(PathBuf, gradle::ReportedRoot, PathBuf)> {
|
||||
let reported = gradle::linked_dirs(root, settings)
|
||||
let reported = gradle::linked_dirs_cached(root, settings)
|
||||
.iter()
|
||||
.flat_map(|dir| sync::reported_gradle_projects(&gradle::cache_dir(cache_dir, dir)).as_ref().clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -4461,4 +4461,58 @@ mod linkage_tests {
|
||||
assert_eq!(poms, expected.map(|e| e.iter().map(|s| s.to_string()).collect::<Vec<_>>()), "{unlinked:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn child_module_inherits_parent_declared_plugin_prefix_and_coordinates() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir_all(root.join("child")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>parent</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<modules><module>child</module></modules>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>io.spring.javaformat</groupId>
|
||||
<artifactId>spring-javaformat-maven-plugin</artifactId>
|
||||
<version>0.0.38</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
root.join("child/pom.xml"),
|
||||
r#"<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>parent</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>child</artifactId>
|
||||
</project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let model = load_with_repo(root, None);
|
||||
for pom in ["pom.xml", "child/pom.xml"] {
|
||||
let proj = model.projects.iter().find(|p| p.pom == pom).expect(pom);
|
||||
let plugin = proj
|
||||
.plugins
|
||||
.iter()
|
||||
.find(|p| p.prefix == "spring-javaformat")
|
||||
.unwrap_or_else(|| panic!("spring-javaformat plugin missing on {pom}: {:?}", proj.plugins));
|
||||
assert_eq!(plugin.group_id, "io.spring.javaformat");
|
||||
assert_eq!(plugin.artifact_id, "spring-javaformat-maven-plugin");
|
||||
assert_eq!(plugin.version.as_deref(), Some("0.0.38"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
<artifactId>app</artifactId>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>lib</artifactId>
|
||||
<version>1</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,9 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
<artifactId>lib</artifactId>
|
||||
</project>
|
||||
@@ -0,0 +1,35 @@
|
||||
<project>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>t</groupId>
|
||||
<artifactId>root</artifactId>
|
||||
<version>1</version>
|
||||
<packaging>pom</packaging>
|
||||
<modules>
|
||||
<module>lib</module>
|
||||
<module>app</module>
|
||||
</modules>
|
||||
<properties>
|
||||
<maven.compiler.release>11</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.4.0</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<parameters>true</parameters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
</project>
|
||||
@@ -260,8 +260,8 @@ pub fn decode(bytes: &[u8]) -> Vec<PathBuf> {
|
||||
/// may be larger than the text, and a malformed one may lack the NUL.
|
||||
#[cfg(any(windows, test))]
|
||||
fn unicode_text(bytes: &[u8]) -> String {
|
||||
let units: Vec<u16> =
|
||||
bytes.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).take_while(|&unit| unit != 0).collect();
|
||||
let (pairs, _) = bytes.as_chunks::<2>();
|
||||
let units: Vec<u16> = pairs.iter().map(|&pair| u16::from_le_bytes(pair)).take_while(|&unit| unit != 0).collect();
|
||||
String::from_utf16_lossy(&units)
|
||||
}
|
||||
|
||||
@@ -340,6 +340,18 @@ mod imp {
|
||||
const OPEN_ATTEMPTS: usize = 10;
|
||||
const OPEN_RETRY: Duration = Duration::from_millis(20);
|
||||
|
||||
/// WARNING: reading or writing the clipboard from two threads at once crashes the whole
|
||||
/// process. `OpenClipboard(NULL)` does not keep the other threads of this process out, and
|
||||
/// a second `GetClipboardData` can free the block the first thread is still reading, so
|
||||
/// `GlobalSize` finds a corrupted heap and Windows ends the app with 0xc0000374 (#6388:
|
||||
/// restoring a minimized window starts several reads). Every function below that opens the
|
||||
/// clipboard holds this lock from before `OpenClipboard` until after `CloseClipboard`.
|
||||
static CLIPBOARD: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
CLIPBOARD.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
#[link(name = "user32")]
|
||||
unsafe extern "system" {
|
||||
fn OpenClipboard(owner: Handle) -> i32;
|
||||
@@ -389,6 +401,7 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn png() -> Option<Vec<u8>> {
|
||||
let _clipboard = lock();
|
||||
if !open() {
|
||||
return None;
|
||||
}
|
||||
@@ -405,6 +418,7 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn text() -> Option<String> {
|
||||
let _clipboard = lock();
|
||||
// Empty rather than None: a None falls back to the WebView, which prompts the user.
|
||||
if unsafe { IsClipboardFormatAvailable(CF_UNICODETEXT) } == 0 {
|
||||
return Some(String::new());
|
||||
@@ -447,6 +461,7 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn files() -> std::io::Result<Vec<PathBuf>> {
|
||||
let _clipboard = lock();
|
||||
if !open() {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
}
|
||||
@@ -528,6 +543,7 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn set_text(text: &str, owner: usize) -> std::io::Result<()> {
|
||||
let _clipboard = lock();
|
||||
let (memory, _) = global_text(text);
|
||||
if memory.is_null() {
|
||||
return Err(std::io::Error::last_os_error());
|
||||
@@ -551,6 +567,7 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn set_png(png: &[u8], owner: usize) -> std::io::Result<()> {
|
||||
let _clipboard = lock();
|
||||
let dib = super::image::png_to_dib(png)?;
|
||||
let format = png_format();
|
||||
if format == 0 {
|
||||
@@ -593,6 +610,7 @@ mod imp {
|
||||
}
|
||||
|
||||
pub fn set_files(paths: &[PathBuf]) -> bool {
|
||||
let _clipboard = lock();
|
||||
let bytes = encode(paths);
|
||||
if bytes.len() <= HEADER {
|
||||
return false;
|
||||
@@ -923,6 +941,104 @@ mod tests {
|
||||
assert_eq!(unicode_text(&bytes), "héllo\r\n世界");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
const READ_TEXT: &str = "clipboard read test";
|
||||
|
||||
/// Reads the clipboard's text for 5 s from `threads` threads, one at a time when
|
||||
/// `serialized`, in a child process: heap corruption ends a process, and the test
|
||||
/// keeps the result. Replaces the clipboard with text and writes the earlier text
|
||||
/// back afterwards; skipped where no clipboard can be written.
|
||||
#[cfg(windows)]
|
||||
fn reads_survive(test: &str, threads: usize, serialized: bool) {
|
||||
use std::process::Command;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
const STAGE: &str = "IDE_CLIPBOARD_READ_STAGE";
|
||||
if std::env::var_os(STAGE).is_some() {
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn WerSetFlags(flags: u32) -> i32;
|
||||
}
|
||||
// WER_FAULT_REPORTING_NO_UI: a crash ends the child instead of waiting on a dialog.
|
||||
unsafe { WerSetFlags(0x20) };
|
||||
let stop = Instant::now() + Duration::from_secs(5);
|
||||
let turn = Arc::new(Mutex::new(()));
|
||||
let readers: Vec<_> = (0..threads)
|
||||
.map(|_| {
|
||||
let turn = turn.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut reads = 0usize;
|
||||
while Instant::now() < stop {
|
||||
let _turn = serialized.then(|| turn.lock().unwrap());
|
||||
// None: another reader kept the clipboard open through every retry.
|
||||
let read = text();
|
||||
assert!(matches!(read.as_deref(), None | Some(READ_TEXT)), "read {read:?}");
|
||||
reads += 1;
|
||||
}
|
||||
reads
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let reads: usize = readers.into_iter().map(|reader| reader.join().unwrap()).sum();
|
||||
println!("reads: {reads}");
|
||||
return;
|
||||
}
|
||||
// The tests share the one clipboard: one at a time, so none rewrites it under another.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
let _serial = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let earlier = text();
|
||||
if let Err(error) = set_text(READ_TEXT, 0) {
|
||||
eprintln!("skipped: the clipboard cannot be written here ({error})");
|
||||
return;
|
||||
}
|
||||
let mut child = Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", test, "--test-threads=1", "--nocapture"])
|
||||
.env(STAGE, "1")
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait().unwrap() {
|
||||
break Some(status);
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
let _ = child.kill();
|
||||
break None;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
};
|
||||
if let Some(earlier) = earlier.filter(|earlier| !earlier.is_empty()) {
|
||||
let _ = set_text(&earlier, 0);
|
||||
}
|
||||
let status = status.expect("the reads did not finish within 60 s");
|
||||
assert!(
|
||||
status.success(),
|
||||
"clipboard reads ended the process: exit code {:#x}",
|
||||
status.code().unwrap_or_default() as u32
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn text_reads_on_one_thread_do_not_corrupt_the_heap() {
|
||||
reads_survive("tests::text_reads_on_one_thread_do_not_corrupt_the_heap", 1, false);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn text_reads_taking_turns_do_not_corrupt_the_heap() {
|
||||
reads_survive("tests::text_reads_taking_turns_do_not_corrupt_the_heap", 8, true);
|
||||
}
|
||||
|
||||
/// The project view reads the clipboard's text whenever a window gains focus, on
|
||||
/// whichever worker thread the command lands, so restoring a minimized window can
|
||||
/// start several reads at once (#6388).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn concurrent_text_reads_do_not_corrupt_the_heap() {
|
||||
reads_survive("tests::concurrent_text_reads_do_not_corrupt_the_heap", 8, false);
|
||||
}
|
||||
|
||||
fn paths(list: &[&str]) -> Vec<PathBuf> {
|
||||
list.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
|
||||
@@ -27,4 +27,4 @@ libc = "0.2"
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -0,0 +1,74 @@
|
||||
//! Parallelism for build tools whose default is one compiler process at a time.
|
||||
//!
|
||||
//! `cmake --build` with a Makefile generator (the default) compiles one file at a
|
||||
//! time unless it is given `-j N`; the IDE asks for one job per logical CPU. A count
|
||||
//! the user wrote into the build arguments is left alone.
|
||||
|
||||
/// Jobs a native build tool gets when the user did not choose a count.
|
||||
pub fn default_jobs() -> usize {
|
||||
std::thread::available_parallelism().map_or(1, |jobs| jobs.get())
|
||||
}
|
||||
|
||||
/// Appends `-j <jobs>` unless `args` already carries the user's own count. The count
|
||||
/// goes before a `--` separator, so cmake's own options stay cmake's and the native
|
||||
/// build tool's options stay last.
|
||||
pub fn append_default_jobs(args: &mut Vec<String>) {
|
||||
if args.iter().any(|arg| is_jobs_flag(arg)) {
|
||||
return;
|
||||
}
|
||||
let jobs = default_jobs().to_string();
|
||||
let at = args.iter().position(|arg| arg == "--").unwrap_or(args.len());
|
||||
args.splice(at..at, ["-j".to_owned(), jobs]);
|
||||
}
|
||||
|
||||
/// `-j`, `-j8`, `--parallel`, `--parallel=8`, `--jobs`, `--jobs=8`.
|
||||
fn is_jobs_flag(arg: &str) -> bool {
|
||||
let count = |rest: &str| rest.chars().all(|c| c.is_ascii_digit());
|
||||
arg.strip_prefix("-j").is_some_and(count)
|
||||
|| arg.strip_prefix("--parallel=").is_some_and(count)
|
||||
|| arg.strip_prefix("--jobs=").is_some_and(count)
|
||||
|| arg == "--parallel"
|
||||
|| arg == "--jobs"
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args_of(values: &[&str]) -> Vec<String> {
|
||||
values.iter().map(|value| (*value).to_owned()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_is_one_job_per_logical_cpu() {
|
||||
let expected = std::thread::available_parallelism().map_or(1, |jobs| jobs.get());
|
||||
assert_eq!(default_jobs(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_build_without_a_count_gets_one() {
|
||||
let mut argv = args_of(&["--build", "build", "--config", "Debug"]);
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, args_of(&["--build", "build", "--config", "Debug", "-j", &default_jobs().to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_count_the_user_chose_is_left_alone() {
|
||||
let own: [&[&str]; 6] =
|
||||
[&["-j", "2"], &["-j8"], &["-j", "2"], &["--parallel", "2"], &["--parallel=2"], &["--jobs=2"]];
|
||||
for flags in own {
|
||||
let mut argv = args_of(&["--build", "build"]);
|
||||
argv.extend(flags.iter().map(|value| (*value).to_owned()));
|
||||
let expected = argv.clone();
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, expected, "the build arguments set the count");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_count_stays_before_native_build_tool_options() {
|
||||
let mut argv = args_of(&["--build", "build", "--", "VERBOSE=1"]);
|
||||
append_default_jobs(&mut argv);
|
||||
assert_eq!(argv, args_of(&["--build", "build", "-j", &default_jobs().to_string(), "--", "VERBOSE=1"]));
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,10 @@ pub struct EditorGeneralSettings {
|
||||
pub remove_trailing_blank_lines: bool,
|
||||
/// Copy as rich text (HTML with syntax colours) by default.
|
||||
pub rich_text_copy: bool,
|
||||
/// Gutter › Highlight modified lines in the gutter: the VCS change bars next to the line numbers.
|
||||
pub highlight_modified_lines: bool,
|
||||
/// Gutter › Highlight modified lines in error stripe on the scrollbar (with `highlight_modified_lines`).
|
||||
pub highlight_modified_lines_in_scrollbar: bool,
|
||||
}
|
||||
|
||||
impl Default for EditorGeneralSettings {
|
||||
@@ -51,6 +55,8 @@ impl Default for EditorGeneralSettings {
|
||||
keep_trailing_on_caret_line: true,
|
||||
remove_trailing_blank_lines: false,
|
||||
rich_text_copy: true,
|
||||
highlight_modified_lines: true,
|
||||
highlight_modified_lines_in_scrollbar: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -296,6 +302,12 @@ pub struct SmartKeysSettings {
|
||||
pub simultaneous_tag_editing: bool,
|
||||
/// Reformat on paste: `none` | `indentBlock` | `indentEachLine`.
|
||||
pub reformat_on_paste: String,
|
||||
/// Advanced Settings: Copy/Cut without a selection copies the whole caret lines.
|
||||
pub copy_line_when_no_selection: bool,
|
||||
/// Advanced Settings: Copy selects the lines copied without a selection.
|
||||
pub select_copied_line: bool,
|
||||
/// Advanced Settings: linewise paste `above` the caret | `caret` | `trim` at mid-line.
|
||||
pub line_paste_mode: String,
|
||||
pub escape_on_paste: bool,
|
||||
pub smart_indent: bool,
|
||||
/// Enter › Insert documentation comment stub: Enter after `/**` closes the comment.
|
||||
@@ -316,6 +328,9 @@ impl Default for SmartKeysSettings {
|
||||
semicolon_at_statement_end: true,
|
||||
simultaneous_tag_editing: true,
|
||||
reformat_on_paste: "indentEachLine".into(),
|
||||
copy_line_when_no_selection: true,
|
||||
select_copied_line: true,
|
||||
line_paste_mode: "above".into(),
|
||||
escape_on_paste: true,
|
||||
smart_indent: true,
|
||||
insert_doc_stub: true,
|
||||
@@ -486,6 +501,38 @@ pub struct LanguageCodeStyle {
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
/// Java: organize imports switches to a wildcard import once this many
|
||||
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
/// 5; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub class_count_to_use_import_with_star: Option<u32>,
|
||||
/// Java: organize imports switches to a wildcard static import once this
|
||||
/// many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
/// IDEA's default 3; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub names_count_to_use_static_import_with_star: Option<u32>,
|
||||
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub semicolons: Option<String>,
|
||||
/// JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub quotes: Option<String>,
|
||||
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub spaces: BTreeMap<String, bool>,
|
||||
/// JavaScript / TypeScript › Imports › Import paths:
|
||||
/// `shortest` | `relative` | `non-relative` | `project-relative`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier_ending: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_file_exclude_patterns: Vec<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_specifier_exclude_regexes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
@@ -543,6 +590,25 @@ pub struct EncodingSettings {
|
||||
pub native_to_ascii: bool,
|
||||
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
|
||||
pub utf8_bom: String,
|
||||
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
|
||||
/// relative to the project with `/` separators. The status bar's choice is kept here.
|
||||
#[serde(deserialize_with = "labels")]
|
||||
#[specta(type = BTreeMap<String, String>)]
|
||||
pub mappings: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
|
||||
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
|
||||
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
|
||||
return Ok(BTreeMap::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter_map(|(path, label)| match label {
|
||||
serde_json::Value::String(label) => Some((path, label)),
|
||||
_ => None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
impl Default for EncodingSettings {
|
||||
@@ -553,10 +619,30 @@ impl Default for EncodingSettings {
|
||||
properties: "iso-8859-1".into(),
|
||||
native_to_ascii: false,
|
||||
utf8_bom: "never".into(),
|
||||
mappings: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod encoding_mappings_tests {
|
||||
use super::EncodingSettings;
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_keep_the_entries_that_are_labels() {
|
||||
let json = serde_json::json!({
|
||||
"project": "gbk",
|
||||
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
|
||||
});
|
||||
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(settings.project, "gbk");
|
||||
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
|
||||
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
|
||||
assert!(not_a_table.mappings.is_empty());
|
||||
assert!(EncodingSettings::default().mappings.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod auto_import_tests {
|
||||
use super::{AutoImportSettings, ImportsOnPaste};
|
||||
|
||||
@@ -46,6 +46,8 @@ pub enum ErrorData {
|
||||
JavaBuildProblems {
|
||||
problems: Vec<String>,
|
||||
},
|
||||
/// A remote backend of another OpenIDEA build still serves the project and refused to retire.
|
||||
RemoteBackendBusy,
|
||||
}
|
||||
|
||||
/// Git's reported result for each destination ref. A remote with several push URLs can
|
||||
|
||||
@@ -13,13 +13,66 @@ use std::sync::Arc;
|
||||
|
||||
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
|
||||
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
|
||||
/// started or failed to.
|
||||
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
|
||||
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
|
||||
/// Run would, answered the same way. `DebugConfiguration` does the same in Debug mode, so
|
||||
/// the window's own Debug action builds the launch. `Breakpoints` replaces the window's
|
||||
/// breakpoints, which the editor owns, persists and mirrors to the backend.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum McpUiRequest {
|
||||
Confirm { client: String, tool: String, subject: String, project: String, detail: Option<String> },
|
||||
OpenFile { path: crate::IpcPath, line: Option<u32>, column: Option<u32> },
|
||||
AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap<String, String> },
|
||||
Confirm {
|
||||
client: String,
|
||||
tool: String,
|
||||
subject: String,
|
||||
project: String,
|
||||
detail: Option<String>,
|
||||
},
|
||||
OpenFile {
|
||||
path: crate::IpcPath,
|
||||
line: Option<u32>,
|
||||
column: Option<u32>,
|
||||
},
|
||||
AgentRun {
|
||||
name: String,
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
config: serde_json::Value,
|
||||
},
|
||||
/// Start a run configuration in Debug mode as the IDE's Debug action would.
|
||||
DebugConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
config: serde_json::Value,
|
||||
},
|
||||
/// Sets one line breakpoint in the window's own list, by absolute editor path. The window
|
||||
/// applies the edit to its current list, so a user's pending edit is not overwritten.
|
||||
SetBreakpoint {
|
||||
path: String,
|
||||
breakpoint: McpBreakpoint,
|
||||
},
|
||||
/// Removes breakpoints from the window's own list. With no path, removes every line
|
||||
/// breakpoint; with a path but no line, removes all of that file's breakpoints.
|
||||
RemoveBreakpoints {
|
||||
path: Option<String>,
|
||||
line: Option<u32>,
|
||||
},
|
||||
/// Flushes the editor's pending breakpoint syncs before an agent reads the backend list.
|
||||
FlushBreakpoints,
|
||||
}
|
||||
|
||||
/// A line breakpoint in an MCP request, with a 1-based line like every other MCP tool.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct McpBreakpoint {
|
||||
pub line: u32,
|
||||
pub enabled: bool,
|
||||
pub condition: Option<String>,
|
||||
pub hit_condition: Option<String>,
|
||||
pub log_message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -27,6 +80,10 @@ pub enum McpUiRequest {
|
||||
pub enum IdeEvent {
|
||||
/// Project data source settings changed; reload the Database tree.
|
||||
DbSourcesChanged,
|
||||
/// A Python run saved a matplotlib figure for the Plots tool window (a PNG file).
|
||||
PlotAdded {
|
||||
path: String,
|
||||
},
|
||||
McpRequest {
|
||||
id: u32,
|
||||
request: McpUiRequest,
|
||||
@@ -98,6 +155,8 @@ pub enum IdeEvent {
|
||||
DocDiskConflict {
|
||||
doc: DocId,
|
||||
path: String,
|
||||
/// The file no longer exists: saving recreates it, and there is nothing to load.
|
||||
deleted: bool,
|
||||
},
|
||||
/// A complete workspace edit can be undone as one operation.
|
||||
WorkspaceEditApplied {
|
||||
@@ -117,6 +176,15 @@ pub enum IdeEvent {
|
||||
/// See `DocumentInfo::ui_mode`.
|
||||
ui_mode: Option<String>,
|
||||
},
|
||||
/// A reload from disk changed an open document's encoding, BOM or line ending (the file
|
||||
/// was rewritten by another program), which the editor only learns when it opens.
|
||||
DocEncoding {
|
||||
doc: DocId,
|
||||
encoding: String,
|
||||
has_bom: bool,
|
||||
/// A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`.
|
||||
line_ending: String,
|
||||
},
|
||||
/// Full replacement of diagnostics for one file from one producer.
|
||||
Diagnostics {
|
||||
path: crate::IpcPath,
|
||||
@@ -179,6 +247,15 @@ pub enum IdeEvent {
|
||||
message: String,
|
||||
actions: Vec<String>,
|
||||
},
|
||||
/// A language server asked to show a document (`window/showDocument`), e.g. the
|
||||
/// expansion file of sourcekit-lsp's Expand Macro. `path` is set for a file to open in
|
||||
/// an editor, at `selection` when given; without it `uri` is a web link for the browser.
|
||||
LspShowDocument {
|
||||
uri: String,
|
||||
path: Option<crate::IpcPath>,
|
||||
selection: Option<crate::Range>,
|
||||
take_focus: bool,
|
||||
},
|
||||
/// The request was answered or timed out; every window drops its dialog.
|
||||
LspMessageRequestDone {
|
||||
id: u32,
|
||||
|
||||
@@ -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 build_jobs;
|
||||
pub mod cli_process;
|
||||
pub mod editor_settings;
|
||||
pub mod error;
|
||||
@@ -18,6 +19,7 @@ pub mod ipc_path;
|
||||
pub mod java_runtime;
|
||||
pub mod jsonc;
|
||||
pub mod memory;
|
||||
pub mod network_path;
|
||||
pub mod output_encoding;
|
||||
pub mod output_rate;
|
||||
pub mod platform;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Whether a path is on a network file system, where every stat is a round trip to a server.
|
||||
|
||||
use std::path::{Component, Path, Prefix};
|
||||
|
||||
/// A UNC path (`\\server\share`, `\\wsl.localhost\…`) or a drive letter mapped to a network
|
||||
/// share (`Z:\`). Always `false` off Windows: there a mount point is not visible in the path.
|
||||
pub fn is_network_path(path: &Path) -> bool {
|
||||
match path.components().next() {
|
||||
Some(Component::Prefix(prefix)) => match prefix.kind() {
|
||||
Prefix::UNC(..) | Prefix::VerbatimUNC(..) => true,
|
||||
Prefix::Disk(letter) | Prefix::VerbatimDisk(letter) => is_remote_drive(letter),
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn is_remote_drive(letter: u8) -> bool {
|
||||
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
|
||||
/// `DRIVE_REMOTE` (WindowsProgramming).
|
||||
const DRIVE_REMOTE: u32 = 4;
|
||||
let root = [u16::from(letter), u16::from(b':'), u16::from(b'\\'), 0];
|
||||
// SAFETY: `root` is a NUL-terminated wide string that outlives the call.
|
||||
unsafe { GetDriveTypeW(root.as_ptr()) == DRIVE_REMOTE }
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn is_remote_drive(_letter: u8) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::is_network_path;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn unc_paths_are_on_the_network() {
|
||||
if cfg!(windows) {
|
||||
assert!(is_network_path(Path::new(r"\\server\share\repo")));
|
||||
assert!(is_network_path(Path::new(r"\\?\UNC\server\share\repo")));
|
||||
assert!(is_network_path(Path::new(r"\\wsl.localhost\Ubuntu\home")));
|
||||
}
|
||||
assert!(!is_network_path(Path::new("relative/path")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_local_directory_is_not() {
|
||||
let dir = std::env::temp_dir();
|
||||
assert!(!is_network_path(&dir), "{}", dir.display());
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,33 @@ pub type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
|
||||
|
||||
struct Entry {
|
||||
root: PathBuf,
|
||||
direnv: Vec<(OsString, Option<OsString>)>,
|
||||
github_token: Option<OsString>,
|
||||
changes: Changes,
|
||||
loading: bool,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn new(root: PathBuf) -> Self {
|
||||
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
|
||||
}
|
||||
|
||||
fn rebuild(&mut self) {
|
||||
let mut combined = Vec::with_capacity(self.direnv.len() + usize::from(self.github_token.is_some()));
|
||||
if let Some(token) = &self.github_token {
|
||||
combined.push(("GH_TOKEN".into(), Some(token.clone())));
|
||||
}
|
||||
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
|
||||
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
|
||||
combined.extend(self.direnv.iter().cloned());
|
||||
self.changes = Arc::new(combined);
|
||||
}
|
||||
|
||||
fn is_idle_empty(&self) -> bool {
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
static ENTRIES: Mutex<Vec<Entry>> = Mutex::new(Vec::new());
|
||||
static SETTLED: Condvar = Condvar::new();
|
||||
|
||||
@@ -31,35 +54,103 @@ pub fn begin_loading(root: &Path) {
|
||||
let mut entries = entries();
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => entry.loading = true,
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }),
|
||||
None => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.loading = true;
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What children started in `root` (or below it) get on top of the IDE's own environment
|
||||
/// (`None`: removed). Ends a [`begin_loading`].
|
||||
/// What children started in `root` (or below it) get from direnv on top of the IDE's own
|
||||
/// environment (`None`: removed). Ends a [`begin_loading`].
|
||||
pub fn set(root: &Path, changes: Vec<(OsString, Option<OsString>)>) {
|
||||
let mut entries = entries();
|
||||
let changes = Arc::new(changes);
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => {
|
||||
entry.changes = changes;
|
||||
match entries.iter_mut().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv = changes;
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }),
|
||||
None if !changes.is_empty() => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.direnv = changes;
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays.
|
||||
pub fn settle(root: &Path) {
|
||||
if let Some(entry) = entries().iter_mut().find(|e| e.root == root) {
|
||||
entry.loading = false;
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
entries[idx].loading = false;
|
||||
if entries[idx].is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// `root` has no environment of its own any more (closed, or not trusted).
|
||||
/// `root` has no direnv environment of its own any more (no `.envrc`, closed, or not trusted).
|
||||
/// Preserves any project-scoped GitHub token until [`remove_all`] or [`set_github_token`].
|
||||
pub fn remove(root: &Path) {
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv.clear();
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Sets or clears the project-scoped `GH_TOKEN` injected for children started in `root`
|
||||
/// (unless overridden by `root`'s direnv `.envrc`). Returns whether the effective token changed.
|
||||
pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
|
||||
let token = token.filter(|t| !t.is_empty());
|
||||
let mut entries = entries();
|
||||
match entries.iter().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
if entries[idx].github_token == token {
|
||||
return false;
|
||||
}
|
||||
let entry = &mut entries[idx];
|
||||
entry.github_token = token;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
true
|
||||
}
|
||||
None => {
|
||||
let Some(token) = token else { return false };
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.github_token = Some(token);
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
|
||||
pub fn github_token(dir: &Path) -> Option<OsString> {
|
||||
find(&entries(), dir).and_then(|e| e.github_token.clone())
|
||||
}
|
||||
|
||||
/// Removes both direnv and project GitHub token entries for `root` (project closed or untrusted).
|
||||
pub fn remove_all(root: &Path) {
|
||||
entries().retain(|e| e.root != root);
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
@@ -135,4 +226,26 @@ mod tests {
|
||||
assert_eq!(*for_dir(root), [change("NEW", Some("2"))]);
|
||||
remove(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_token_survives_direnv_absence_and_yields_to_explicit_envrc_override() {
|
||||
let root = Path::new("/openidea-test-env/gh-project");
|
||||
let worktrees = Path::new("/openidea-test-env/gh-project.worktrees");
|
||||
assert!(set_github_token(root, Some("gho_work".into())));
|
||||
assert!(!set_github_token(root, Some("gho_work".into())), "idempotent");
|
||||
assert!(set_github_token(worktrees, Some("gho_work".into())));
|
||||
remove(root); // no `.envrc` in `root`
|
||||
assert_eq!(*for_dir(&root.join("src")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(*for_dir(&worktrees.join("task-1")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(github_token(&worktrees.join("task-1")), Some("gho_work".into()));
|
||||
|
||||
// An explicit `.envrc` GH_TOKEN overrides the project GitHub account token.
|
||||
set(root, vec![change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
assert_eq!(*for_dir(root), [change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
|
||||
remove_all(root);
|
||||
remove_all(worktrees);
|
||||
assert!(for_dir(root).is_empty());
|
||||
assert!(for_dir(worktrees).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,8 @@ pub struct Settings {
|
||||
/// Per language server, by name (`rust-analyzer`): launch and protocol
|
||||
/// options on top of the language definition, or a server defined here.
|
||||
pub language_servers: BTreeMap<String, LanguageServerSettings>,
|
||||
/// Languages & Frameworks › JSON Schema Mappings: schemas for JSON and YAML files.
|
||||
pub json_schemas: Vec<JsonSchemaMapping>,
|
||||
/// Tools › Download sources: a mirror prefix for the release archives the installer fetches.
|
||||
pub tool_downloads: ToolDownloadSettings,
|
||||
/// Editor › Inspections profiles.
|
||||
@@ -78,6 +80,8 @@ pub struct Settings {
|
||||
pub file_colors: FileColorSettings,
|
||||
/// Database › Query Execution, Languages & Frameworks › SQL Resolution Scopes.
|
||||
pub database: DatabaseSettings,
|
||||
/// Settings › Settings Sync (global only, never synced itself).
|
||||
pub settings_sync: SettingsSyncSettings,
|
||||
/// Plugin settings (`[contributes.settings]`): plugin id → its values by key.
|
||||
#[specta(type = BTreeMap<String, BTreeMap<String, specta_typescript::Unknown>>)]
|
||||
pub plugins: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
|
||||
@@ -99,6 +103,20 @@ pub struct AgentSettings {
|
||||
pub smooth_text: bool,
|
||||
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
|
||||
pub fit_window_width: bool,
|
||||
/// Chat text follows the interface font (Appearance › Use custom font).
|
||||
pub chat_use_ui_font: bool,
|
||||
/// Chat text family when it does not follow the interface font.
|
||||
pub chat_font_family: String,
|
||||
/// Covers characters the chat font lacks.
|
||||
pub chat_font_fallback: String,
|
||||
pub chat_font_size: u32,
|
||||
/// Code in chat follows the built-in code font.
|
||||
pub code_use_default_font: bool,
|
||||
/// Code family when it does not follow the built-in code font.
|
||||
pub code_font_family: String,
|
||||
/// Covers characters the code font lacks.
|
||||
pub code_font_fallback: String,
|
||||
pub code_font_size: u32,
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ThinkingDisplay)]
|
||||
pub thinking: ThinkingDisplay,
|
||||
@@ -120,6 +138,19 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = NewTaskApprovals)]
|
||||
pub new_task_approvals: NewTaskApprovals,
|
||||
/// How long an in-flight turn hit by a transient network outage waits and probes for
|
||||
/// connectivity before degrading to a manual Resume prompt.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = NetworkRetryWindow)]
|
||||
pub network_retry_window: NetworkRetryWindow,
|
||||
/// What opening a project does with tasks interrupted when OpenIDEA closed or restarted.
|
||||
/// User settings only.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = ResumeInterruptedPolicy)]
|
||||
pub resume_interrupted: ResumeInterruptedPolicy,
|
||||
/// Warn before closing a local window whose project still has running agent tasks.
|
||||
/// User settings only.
|
||||
pub confirm_terminate_on_close: bool,
|
||||
/// Settings new tasks of an agent start with: agent id → option id → value.
|
||||
#[serde(deserialize_with = "agent_defaults")]
|
||||
#[specta(type = BTreeMap<String, BTreeMap<String, String>>)]
|
||||
@@ -134,6 +165,11 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, AgentSkillPolicy>)]
|
||||
pub skills: BTreeMap<String, AgentSkillPolicy>,
|
||||
/// Agent memory policies (`[agents.memory]`): cross-session auto-memory mode, built-in
|
||||
/// MCP memory bridge, and per-entry modes; tracked files on disk are never modified.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentMemorySettings)]
|
||||
pub memory: AgentMemorySettings,
|
||||
}
|
||||
|
||||
impl Default for AgentSettings {
|
||||
@@ -145,15 +181,27 @@ impl Default for AgentSettings {
|
||||
show_cost: false,
|
||||
smooth_text: true,
|
||||
fit_window_width: false,
|
||||
chat_use_ui_font: true,
|
||||
chat_font_family: "Inter".into(),
|
||||
chat_font_fallback: String::new(),
|
||||
chat_font_size: 13,
|
||||
code_use_default_font: true,
|
||||
code_font_family: "JetBrains Mono".into(),
|
||||
code_font_fallback: String::new(),
|
||||
code_font_size: 13,
|
||||
thinking: ThinkingDisplay::Auto,
|
||||
tool_calls: ToolCallDisplay::Grouped,
|
||||
expand_tool_output: false,
|
||||
send_with: SendKey::Enter,
|
||||
while_running: WhileRunning::Queue,
|
||||
new_task_approvals: NewTaskApprovals::Bypass,
|
||||
network_retry_window: NetworkRetryWindow::Hour1,
|
||||
resume_interrupted: ResumeInterruptedPolicy::Ask,
|
||||
confirm_terminate_on_close: true,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
skills: BTreeMap::new(),
|
||||
memory: AgentMemorySettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -237,6 +285,79 @@ impl Default for AgentSkillPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// How an agent instruction, rule, or memory entry may load (`[agents.memory.entries.<id>] mode = …`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryMode {
|
||||
/// Load according to its native rules (always for instructions, matching files for path-scoped rules).
|
||||
#[default]
|
||||
Auto,
|
||||
/// Force-load into every session regardless of path scoping.
|
||||
Always,
|
||||
/// Exclude from sessions where the harness supports it.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// How an agent's automatic cross-session memory runs (`[agents.memory] autoMemory = …`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutoMemoryMode {
|
||||
/// Leave the agent's own configuration untouched.
|
||||
#[default]
|
||||
Inherit,
|
||||
/// Read past memories and record new ones.
|
||||
ReadWrite,
|
||||
/// Read past memories without recording new ones.
|
||||
ReadOnly,
|
||||
/// Neither read nor record cross-session auto-memories.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// One memory or instruction entry's policy in Settings › Agents › Memory.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemoryEntryPolicy {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentMemoryMode)]
|
||||
pub mode: AgentMemoryMode,
|
||||
/// Agent provider ids this entry applies to; empty means all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for AgentMemoryEntryPolicy {
|
||||
fn default() -> Self {
|
||||
Self { mode: AgentMemoryMode::Auto, agents: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-provider auto-memory policy (`[agents.memory.providers.<id>]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentProviderMemoryPolicy {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutoMemoryMode)]
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
}
|
||||
|
||||
/// Agent memory settings (`[agents.memory]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemorySettings {
|
||||
/// Default cross-session auto-memory policy across agents.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutoMemoryMode)]
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
/// Optional per-provider auto-memory overrides (`[agents.memory.providers.<provider>]`).
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentProviderMemoryPolicy>)]
|
||||
pub providers: BTreeMap<String, AgentProviderMemoryPolicy>,
|
||||
/// Per-entry modes (`[agents.memory.entries.<id>]`).
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentMemoryEntryPolicy>)]
|
||||
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
}
|
||||
|
||||
/// A hand-edited value these settings don't know reads as the default, rather than
|
||||
/// failing the whole settings file.
|
||||
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
|
||||
@@ -338,6 +459,49 @@ pub enum NewTaskApprovals {
|
||||
Ask,
|
||||
}
|
||||
|
||||
/// Default auto-retry window for transient network outages during an active agent turn.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub enum NetworkRetryWindow {
|
||||
#[serde(rename = "off")]
|
||||
Off,
|
||||
#[serde(rename = "15m")]
|
||||
Minutes15,
|
||||
#[default]
|
||||
#[serde(rename = "1h")]
|
||||
Hour1,
|
||||
#[serde(rename = "4h")]
|
||||
Hours4,
|
||||
#[serde(rename = "24h")]
|
||||
Hours24,
|
||||
}
|
||||
|
||||
impl NetworkRetryWindow {
|
||||
pub fn minutes(self) -> u32 {
|
||||
match self {
|
||||
Self::Off => 0,
|
||||
Self::Minutes15 => 15,
|
||||
Self::Hour1 => 60,
|
||||
Self::Hours4 => 240,
|
||||
Self::Hours24 => 1440,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How interrupted agent tasks are handled when a project reopens.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ResumeInterruptedPolicy {
|
||||
/// Show Interrupted markers, banner and balloon; wait for the user to click Resume.
|
||||
#[default]
|
||||
Ask,
|
||||
/// Auto-resume tasks interrupted by an IDE restart or backend upgrade within 15 minutes.
|
||||
Restart,
|
||||
/// Auto-resume tasks interrupted by close, quit or restart within the session recovery window.
|
||||
Window,
|
||||
/// Settle quietly to Ready with no Interrupted markers or balloons.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// Which folders without an open window the MCP server still serves tools for.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -432,6 +596,53 @@ pub struct ToolDownloadSettings {
|
||||
/// commas or whitespace and tried in order before the official host; empty keeps every
|
||||
/// download on its official host.
|
||||
pub github_mirror: String,
|
||||
/// Package registries only as configured (a company Nexus or Artifactory): npm and pnpm
|
||||
/// installs and update checks never retry against the public npm registry, and the IDE
|
||||
/// fetches nothing from public package registries itself (the JUnit Platform launcher from
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
}
|
||||
|
||||
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SettingsSyncSettings {
|
||||
/// Clone URL (a secret GitHub Gist's works too, though anyone with its link can read it);
|
||||
/// empty = sync off.
|
||||
pub repository: String,
|
||||
/// Sync on startup and after the settings change, besides Sync Now.
|
||||
pub auto: bool,
|
||||
pub appearance: bool,
|
||||
/// Editor settings, color schemes, code style, inspections and spelling.
|
||||
pub editor: bool,
|
||||
pub keymaps: bool,
|
||||
/// Every other setting that is not machine-specific.
|
||||
pub other: bool,
|
||||
/// Live, file and postfix templates.
|
||||
pub templates: bool,
|
||||
pub macros: bool,
|
||||
/// Tool window layouts and view options.
|
||||
pub ui: bool,
|
||||
/// The list of installed plugins: missing ones are offered, never installed or removed.
|
||||
pub plugins: bool,
|
||||
}
|
||||
|
||||
impl Default for SettingsSyncSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
repository: String::new(),
|
||||
auto: true,
|
||||
appearance: true,
|
||||
editor: true,
|
||||
keymaps: true,
|
||||
other: true,
|
||||
templates: true,
|
||||
macros: true,
|
||||
ui: true,
|
||||
plugins: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Absent profiles retain automatic discovery for existing projects.
|
||||
@@ -585,8 +796,10 @@ impl Default for Settings {
|
||||
mcp_server: McpServerSettings::default(),
|
||||
agent_security: AgentSecuritySettings::default(),
|
||||
scopes: Vec::new(),
|
||||
json_schemas: Vec::new(),
|
||||
file_colors: FileColorSettings::default(),
|
||||
database: DatabaseSettings::default(),
|
||||
settings_sync: SettingsSyncSettings::default(),
|
||||
plugins: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -606,6 +819,17 @@ pub struct NamedScope {
|
||||
pub pattern: String,
|
||||
}
|
||||
|
||||
/// A schema for the JSON and YAML files matching `files`; wins over a built-in SchemaStore mapping.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct JsonSchemaMapping {
|
||||
pub name: String,
|
||||
/// A URL, or a file path relative to the project.
|
||||
pub schema: String,
|
||||
/// Project-relative paths or glob patterns (`config/*.json`, `**/*.app.yaml`).
|
||||
pub files: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FileColorSettings {
|
||||
@@ -834,6 +1058,8 @@ pub struct AppearanceSettings {
|
||||
pub smooth_scrolling: bool,
|
||||
pub full_path_in_title: bool,
|
||||
pub project_colors_in_toolbar: bool,
|
||||
/// Strength of the project colour tint in the window header, in percent (10–70).
|
||||
pub project_color_strength: u8,
|
||||
pub dnd_with_alt_only: bool,
|
||||
pub menu_icons: bool,
|
||||
/// `hamburger` | `merged` | `toolbar` (a separate row): main menu presentation in the frameless title bar.
|
||||
@@ -852,6 +1078,8 @@ pub struct AppearanceSettings {
|
||||
pub widescreen_tool_windows: bool,
|
||||
/// Each tool window keeps its own size; off, the windows of a side share one.
|
||||
pub remember_tool_window_sizes: bool,
|
||||
/// Tool window shortcuts hide an open unfocused window right away instead of focusing it first.
|
||||
pub toggle_tool_windows_on_shortcut: bool,
|
||||
/// View › Appearance › Toolbar; hidden leaves IDEA's compact window header.
|
||||
pub show_main_toolbar: bool,
|
||||
pub show_status_bar: bool,
|
||||
@@ -973,6 +1201,7 @@ impl Default for AppearanceSettings {
|
||||
smooth_scrolling: true,
|
||||
full_path_in_title: false,
|
||||
project_colors_in_toolbar: true,
|
||||
project_color_strength: 22,
|
||||
dnd_with_alt_only: false,
|
||||
menu_icons: true,
|
||||
main_menu_style: "hamburger".into(),
|
||||
@@ -985,6 +1214,7 @@ impl Default for AppearanceSettings {
|
||||
show_tool_window_badges: true,
|
||||
widescreen_tool_windows: false,
|
||||
remember_tool_window_sizes: false,
|
||||
toggle_tool_windows_on_shortcut: false,
|
||||
show_main_toolbar: true,
|
||||
show_status_bar: true,
|
||||
navigation_bar: NavigationBarPosition::StatusBar,
|
||||
@@ -1212,6 +1442,8 @@ pub struct LanguagesSettings {
|
||||
pub prettier: ExternalFormatterSettings,
|
||||
pub oxfmt: ExternalFormatterSettings,
|
||||
pub biome: ExternalFormatterSettings,
|
||||
/// dprint formats every file its configuration covers: `languages` is unused.
|
||||
pub dprint: ExternalFormatterSettings,
|
||||
pub ruff: ExternalFormatterSettings,
|
||||
pub black: ExternalFormatterSettings,
|
||||
pub java: JavaSettings,
|
||||
@@ -1238,6 +1470,7 @@ impl Default for LanguagesSettings {
|
||||
languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(),
|
||||
..ExternalFormatterSettings::default()
|
||||
},
|
||||
dprint: ExternalFormatterSettings { languages: Vec::new(), ..ExternalFormatterSettings::default() },
|
||||
ruff: ExternalFormatterSettings {
|
||||
languages: vec!["python".into()],
|
||||
..ExternalFormatterSettings::default()
|
||||
@@ -1315,6 +1548,7 @@ impl LanguagesSettings {
|
||||
ExternalFormatter::Prettier => &self.prettier,
|
||||
ExternalFormatter::Oxfmt => &self.oxfmt,
|
||||
ExternalFormatter::Biome => &self.biome,
|
||||
ExternalFormatter::Dprint => &self.dprint,
|
||||
ExternalFormatter::Ruff => &self.ruff,
|
||||
ExternalFormatter::Black => &self.black,
|
||||
}
|
||||
@@ -1328,6 +1562,7 @@ pub enum ExternalFormatter {
|
||||
Prettier,
|
||||
Oxfmt,
|
||||
Biome,
|
||||
Dprint,
|
||||
Ruff,
|
||||
Black,
|
||||
}
|
||||
@@ -1339,6 +1574,7 @@ impl ExternalFormatter {
|
||||
Self::Prettier => "prettier",
|
||||
Self::Oxfmt => "oxfmt",
|
||||
Self::Biome => "biome",
|
||||
Self::Dprint => "dprint",
|
||||
Self::Ruff => "ruff",
|
||||
Self::Black => "black",
|
||||
}
|
||||
@@ -1349,11 +1585,11 @@ impl ExternalFormatter {
|
||||
pub const BIOME_LANGUAGES: [&str; 8] =
|
||||
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
|
||||
|
||||
/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats.
|
||||
/// An external formatter (Prettier, oxfmt, Biome, dprint, Ruff, Black) and the languages it formats.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ExternalFormatterSettings {
|
||||
/// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH.
|
||||
/// Empty path: project node_modules (Prettier/oxfmt/Biome/dprint), managed installation, then PATH.
|
||||
pub path: String,
|
||||
/// Ruff only: directory containing its configuration, or a configuration file.
|
||||
pub configuration_directory: String,
|
||||
@@ -1361,6 +1597,8 @@ pub struct ExternalFormatterSettings {
|
||||
/// Prefer this formatter even when a language server offers formatting.
|
||||
pub prefer: bool,
|
||||
pub run_on_save: bool,
|
||||
/// Ruff only: apply safe lint fixes (`ruff check --fix-only`) on save, independently of formatting.
|
||||
pub fix_on_save: bool,
|
||||
}
|
||||
|
||||
impl Default for ExternalFormatterSettings {
|
||||
@@ -1389,6 +1627,7 @@ impl Default for ExternalFormatterSettings {
|
||||
.collect(),
|
||||
prefer: false,
|
||||
run_on_save: false,
|
||||
fix_on_save: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1414,6 +1653,15 @@ pub struct PythonSettings {
|
||||
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
|
||||
/// by interpreter executable; absolute or `~/`.
|
||||
pub interpreter_paths: BTreeMap<String, Vec<String>>,
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
|
||||
/// is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
|
||||
pub profiler: String,
|
||||
/// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND`
|
||||
/// unless the run sets it); off: matplotlib's own window.
|
||||
pub show_plots_in_tool_window: bool,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1426,6 +1674,9 @@ impl Default for PythonSettings {
|
||||
hide_other_project_interpreters: false,
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
test_runner: "auto".into(),
|
||||
profiler: "auto".into(),
|
||||
show_plots_in_tool_window: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1724,11 +1975,14 @@ pub struct TypeScriptSettings {
|
||||
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
|
||||
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
|
||||
pub tsserver_max_memory: u32,
|
||||
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
|
||||
/// `tsconfig.json` reports the errors of files that are not open.
|
||||
pub watch_problems: bool,
|
||||
}
|
||||
|
||||
impl Default for TypeScriptSettings {
|
||||
fn default() -> Self {
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0 }
|
||||
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1904,6 +2158,16 @@ impl Settings {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ruff_safe_fixes_on_save_default_off_and_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"runOnSave":true}}}"#).unwrap();
|
||||
assert!(old.languages.ruff.run_on_save);
|
||||
assert!(!old.languages.ruff.fix_on_save);
|
||||
let on: Settings = serde_json::from_str(r#"{"languages":{"ruff":{"fixOnSave":true}}}"#).unwrap();
|
||||
assert!(on.languages.ruff.fix_on_save);
|
||||
assert_eq!(serde_json::to_value(&on).unwrap()["languages"]["ruff"]["fixOnSave"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_interpreter_may_name_a_run_target() {
|
||||
let python = |interpreter: &str| PythonSettings { interpreter: interpreter.into(), ..Default::default() };
|
||||
@@ -1937,6 +2201,19 @@ mod tests {
|
||||
assert_eq!(json["appearance"]["smoothScrolling"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn database_output_destination_defaults_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"database":{"inEditorResults":true}}"#).unwrap();
|
||||
assert_eq!(old.database.output_destination, DatabaseOutputDestination::DatabaseOutput);
|
||||
assert!(old.database.in_editor_results);
|
||||
|
||||
let services: Settings = serde_json::from_str(r#"{"database":{"outputDestination":"services"}}"#).unwrap();
|
||||
assert_eq!(services.database.output_destination, DatabaseOutputDestination::Services);
|
||||
let saved = serde_json::to_value(&services).unwrap();
|
||||
assert_eq!(saved["database"]["outputDestination"], "services");
|
||||
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().database, services.database);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_close_settings_default_off_and_round_trip() {
|
||||
for old in [r#"{}"#, r#"{"general":{"confirmExit":false}}"#] {
|
||||
@@ -2098,6 +2375,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggle_tool_windows_on_shortcut_defaults_off_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
|
||||
assert!(!old.appearance.toggle_tool_windows_on_shortcut);
|
||||
assert!(!Settings::default().appearance.toggle_tool_windows_on_shortcut);
|
||||
for enabled in [true, false] {
|
||||
let mut settings = Settings::default();
|
||||
settings.appearance.toggle_tool_windows_on_shortcut = enabled;
|
||||
let json = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(json["appearance"]["toggleToolWindowsOnShortcut"], enabled);
|
||||
let restored: Settings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(restored.appearance.toggle_tool_windows_on_shortcut, enabled);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn double_click_opens_diff_is_unset_by_default_and_round_trips() {
|
||||
let old: Settings = serde_json::from_str(r#"{"vcs":{"commit":{"nonModal":true}}}"#).unwrap();
|
||||
|
||||
@@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
|
||||
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
|
||||
}
|
||||
|
||||
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
|
||||
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
|
||||
/// only when installed, then the user's `PATH`), and standard OS install locations.
|
||||
pub fn find_gh_executable() -> Option<PathBuf> {
|
||||
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
|
||||
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
|
||||
}
|
||||
|
||||
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
|
||||
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
|
||||
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
|
||||
return Some(explicit);
|
||||
}
|
||||
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
|
||||
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
|
||||
return Some(explicit.to_path_buf());
|
||||
}
|
||||
if let Some(found) = find_command("gh", search, Path::new("")) {
|
||||
return Some(found);
|
||||
}
|
||||
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
fn is_executable(path: &Path) -> bool {
|
||||
let Ok(metadata) = path.metadata() else { return false };
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -25,6 +25,17 @@ pub struct VcsSettings {
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
/// Directory Mappings: repository roots added to or excluded from the detected ones.
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GithubSettings {
|
||||
/// GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project.
|
||||
/// Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected).
|
||||
pub account: String,
|
||||
}
|
||||
|
||||
/// Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
@@ -68,6 +79,7 @@ impl Default for VcsSettings {
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -131,6 +143,9 @@ impl Default for GitAnnotateSettings {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GitSettings {
|
||||
/// Git integration on: off, the IDE finds no repositories and runs no git at all
|
||||
/// (no status, log, blame, fetch, clone or agent worktrees), and hides its Git UI.
|
||||
pub enabled: bool,
|
||||
pub annotate: GitAnnotateSettings,
|
||||
/// Show blame after the current editor line.
|
||||
pub inline_blame: bool,
|
||||
@@ -189,6 +204,7 @@ pub struct GitSettings {
|
||||
impl Default for GitSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
annotate: GitAnnotateSettings::default(),
|
||||
inline_blame: false,
|
||||
inline_blame_clickable: true,
|
||||
@@ -238,6 +254,8 @@ pub struct CommitSettings {
|
||||
pub reformat: bool,
|
||||
pub optimize_imports: bool,
|
||||
pub cleanup: bool,
|
||||
/// Apply Ruff's safe lint fixes before composing the commit, independently of formatting.
|
||||
pub fix_on_commit: bool,
|
||||
pub blank_line_after_subject: bool,
|
||||
pub limit_subject: bool,
|
||||
pub subject_limit: u32,
|
||||
@@ -279,6 +297,7 @@ impl Default for CommitSettings {
|
||||
reformat: false,
|
||||
optimize_imports: false,
|
||||
cleanup: false,
|
||||
fix_on_commit: false,
|
||||
blank_line_after_subject: true,
|
||||
limit_subject: true,
|
||||
subject_limit: 72,
|
||||
@@ -390,13 +409,24 @@ impl Default for LogLevelColors {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct DatabaseSettings {
|
||||
/// A console's result sets show under the statements that produced them, in the editor,
|
||||
/// instead of in the Services view's result tabs.
|
||||
/// instead of in the output window's result tabs.
|
||||
pub in_editor_results: bool,
|
||||
/// The tool window that receives SQL query output and plans.
|
||||
pub output_destination: DatabaseOutputDestination,
|
||||
/// Languages & Frameworks › SQL Resolution Scopes: the data source SQL in a file or folder
|
||||
/// resolves against (completion, inspections, navigation), most specific path first.
|
||||
pub resolution_scopes: Vec<SqlResolutionScope>,
|
||||
}
|
||||
|
||||
/// Database › Query Output: where SQL results open.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DatabaseOutputDestination {
|
||||
#[default]
|
||||
DatabaseOutput,
|
||||
Services,
|
||||
}
|
||||
|
||||
/// One row of SQL Resolution Scopes.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -587,10 +617,14 @@ pub struct TerminalSettings {
|
||||
pub mouse_reporting: bool,
|
||||
pub copy_on_selection: bool,
|
||||
pub paste_on_middle_click: bool,
|
||||
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
|
||||
pub right_click_paste: bool,
|
||||
pub override_ide_shortcuts: bool,
|
||||
pub shell_integration: bool,
|
||||
pub highlight_hyperlinks: bool,
|
||||
pub highlight_selection: bool,
|
||||
/// Highlights typed commands the IDE recognises; Run Highlighted Command runs them with it.
|
||||
pub run_commands_using_ide: bool,
|
||||
pub option_as_meta: bool,
|
||||
/// Escape moves focus to the editor instead of reaching the shell.
|
||||
pub escape_to_editor: bool,
|
||||
@@ -623,10 +657,12 @@ impl Default for TerminalSettings {
|
||||
mouse_reporting: true,
|
||||
copy_on_selection: false,
|
||||
paste_on_middle_click: true,
|
||||
right_click_paste: false,
|
||||
override_ide_shortcuts: true,
|
||||
shell_integration: true,
|
||||
highlight_hyperlinks: true,
|
||||
highlight_selection: true,
|
||||
run_commands_using_ide: true,
|
||||
option_as_meta: false,
|
||||
escape_to_editor: false,
|
||||
cursor_shape: "block".into(),
|
||||
@@ -716,6 +752,24 @@ impl Default for AgentSecuritySettings {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ruff_safe_fixes_on_commit_default_off_and_round_trip() {
|
||||
let old: CommitSettings = serde_json::from_str(r#"{"reformat":true}"#).unwrap();
|
||||
assert!(old.reformat);
|
||||
assert!(!old.fix_on_commit);
|
||||
let on: CommitSettings = serde_json::from_str(r#"{"fixOnCommit":true}"#).unwrap();
|
||||
assert!(on.fix_on_commit);
|
||||
assert_eq!(serde_json::to_value(&on).unwrap()["fixOnCommit"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_defaults_enabled_and_can_be_disabled() {
|
||||
let missing: GitSettings = serde_json::from_str("{}").unwrap();
|
||||
let off: GitSettings = serde_json::from_str(r#"{"enabled":false}"#).unwrap();
|
||||
assert!(missing.enabled);
|
||||
assert!(!off.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_submodules_defaults_on_and_can_be_disabled() {
|
||||
let missing: GitSettings = serde_json::from_str("{}").unwrap();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ide-coverage"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo XML)"
|
||||
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Cobertura XML reports (`coverage xml` of coverage.py, and many other tools):
|
||||
//!
|
||||
//! ```xml
|
||||
//! <coverage>
|
||||
//! <sources><source>/home/runner/work/app/app</source></sources>
|
||||
//! <packages><package name="calc"><classes>
|
||||
//! <class filename="src/calc/__init__.py">
|
||||
//! <methods/>
|
||||
//! <lines>
|
||||
//! <line number="2" hits="1" branch="true" condition-coverage="50% (1/2)"/>
|
||||
//! ```
|
||||
//!
|
||||
//! A relative `filename` belongs to the first `<source>` it exists under, else to the
|
||||
//! first `<source>` (whose path may be another machine's; the importer relocates it).
|
||||
//! Lines repeated under `<methods>` are skipped so their hits don't count twice.
|
||||
|
||||
use crate::Accumulator;
|
||||
use quick_xml::events::{BytesStart, Event};
|
||||
use quick_xml::{Reader, XmlVersion};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
fn attr(e: &BytesStart, name: &str) -> Option<String> {
|
||||
e.attributes()
|
||||
.flatten()
|
||||
.find(|a| a.key.as_ref() == name)
|
||||
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok())
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
/// `"50% (1/2)"` → `(1, 2)`.
|
||||
fn conditions(text: &str) -> Option<(u32, u32)> {
|
||||
let (_, rest) = text.split_once('(')?;
|
||||
let (covered, total) = rest.trim_end_matches(')').split_once('/')?;
|
||||
Some((covered.trim().parse().ok()?, total.trim().parse().ok()?))
|
||||
}
|
||||
|
||||
/// `sources` pairs each `<source>` with whether it exists here (asked once: another
|
||||
/// machine's `/home/…` is slow to look up on macOS).
|
||||
fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf {
|
||||
let p = Path::new(filename);
|
||||
if p.has_root() {
|
||||
return p.to_path_buf();
|
||||
}
|
||||
sources
|
||||
.iter()
|
||||
.filter(|(_, here)| *here)
|
||||
.map(|(s, _)| s.join(p))
|
||||
.find(|c| c.is_file())
|
||||
.unwrap_or_else(|| sources.first().map_or_else(|| base.join(p), |(s, _)| s.join(p)))
|
||||
}
|
||||
|
||||
/// Relative sources (and filenames without sources) resolve against `base`.
|
||||
pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Error> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut acc = Accumulator::default();
|
||||
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
|
||||
let mut source: Option<String> = None;
|
||||
let mut file: Option<PathBuf> = None;
|
||||
let mut in_methods = false;
|
||||
loop {
|
||||
match reader.read_event()? {
|
||||
Event::Start(e) if e.name().as_ref() == "methods" => in_methods = true,
|
||||
Event::Start(e) | Event::Empty(e) => match e.name().as_ref() {
|
||||
"source" => source = Some(String::new()),
|
||||
"class" => {
|
||||
let path = resolve(&attr(&e, "filename").unwrap_or_default(), &sources, base);
|
||||
acc.file(&path);
|
||||
file = Some(path);
|
||||
}
|
||||
"line" if !in_methods => {
|
||||
let Some(path) = &file else { continue };
|
||||
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().ok()) else { continue };
|
||||
let line = number.saturating_sub(1);
|
||||
acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0));
|
||||
if attr(&e, "branch").as_deref() == Some("true")
|
||||
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
|
||||
{
|
||||
acc.has_branches = true;
|
||||
for i in 0..total {
|
||||
acc.branch(path, line, i.to_string(), i < covered);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Event::Text(t) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push_str(t.as_ref());
|
||||
}
|
||||
}
|
||||
Event::GeneralRef(r) => {
|
||||
if let Some(s) = &mut source {
|
||||
s.push('&');
|
||||
s.push_str(r.as_ref());
|
||||
s.push(';');
|
||||
}
|
||||
}
|
||||
Event::End(e) => match e.name().as_ref() {
|
||||
"source" => {
|
||||
let raw = source.take().unwrap_or_default();
|
||||
let text = quick_xml::escape::unescape(raw.trim()).map(|t| t.into_owned()).unwrap_or(raw);
|
||||
if !text.is_empty() {
|
||||
let path = Path::new(&text);
|
||||
// Joining a drive-less foreign root on Windows would add the checkout's drive.
|
||||
let dir = if path.has_root() { path.to_path_buf() } else { base.join(path) };
|
||||
let here = dir.is_dir();
|
||||
sources.push((dir, here));
|
||||
}
|
||||
}
|
||||
"methods" => in_methods = false,
|
||||
"class" => file = None,
|
||||
_ => {}
|
||||
},
|
||||
Event::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(acc)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_lines_branches_and_skips_method_lines() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let second = tmp.path().join("b&c");
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
std::fs::write(second.join("m.py"), "").unwrap();
|
||||
let xml = format!(
|
||||
r#"<?xml version="1.0" ?>
|
||||
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">
|
||||
<coverage><sources><source>/elsewhere/a</source><source>{}</source></sources>
|
||||
<packages><package name="p"><classes>
|
||||
<class name="m" filename="m.py">
|
||||
<methods><method name="f"><lines><line number="2" hits="5"/></lines></method></methods>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="5" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
<class name="n" filename="n.py"><lines><line number="1" hits="0"/></lines></class>
|
||||
<class name="abs" filename="/abs/x.py"><lines><line number="7" hits="2"/></lines></class>
|
||||
</classes></package></packages></coverage>"#,
|
||||
tmp.path().join("b&c").display()
|
||||
);
|
||||
let suite = parse(&xml, tmp.path()).unwrap().finish("Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
assert_eq!(suite.files.len(), 3);
|
||||
let file = |path: &Path| suite.files.iter().find(|f| f.path.as_ref() as &Path == path).unwrap();
|
||||
// `m.py` exists under the second source; `n.py` falls back to the first.
|
||||
let m = file(&second.join("m.py"));
|
||||
assert_eq!(file(Path::new("/elsewhere/a/n.py")).lines[0].hits, 0);
|
||||
assert_eq!(
|
||||
m.lines.iter().map(|l| (l.line, l.hits, l.branches_total, l.branches_covered)).collect::<Vec<_>>(),
|
||||
[(0, 1, 0, 0), (1, 5, 2, 1), (2, 0, 0, 0)]
|
||||
);
|
||||
assert!(m.lines[1].partial());
|
||||
assert_eq!(file(Path::new("/abs/x.py")).lines[0].line, 6);
|
||||
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filenames_without_sources_resolve_against_the_base() {
|
||||
let xml = r#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
|
||||
let suite = parse(xml, Path::new("/root")).unwrap().finish("Cobertura");
|
||||
assert_eq!(suite.files[0].path.as_ref() as &Path, Path::new("/root/a/b.py"));
|
||||
assert!(!suite.has_branches);
|
||||
assert_eq!(conditions("100% (4/4)"), Some((4, 4)));
|
||||
assert_eq!(conditions("100%"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! coverage.py data files (`.coverage`, and `.coverage.*` of parallel runs): SQLite databases of
|
||||
//! executed lines and arcs. Which lines are statements, excluded or branches only comes from
|
||||
//! analysing the source, so coverage.py in the project's interpreter combines the data into a
|
||||
//! scratch file (`[paths]` of the project's configuration applies) and writes Cobertura XML.
|
||||
|
||||
use crate::{CoverageSuite, cobertura};
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::ffi::OsStr;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
const COVERAGE_PY: CliTool = CliTool::new("coverage.py", Decoding::ToolOutput);
|
||||
/// Analysing a large project's sources takes a while; a `[run] plugins` that hangs must not
|
||||
/// block the import for good.
|
||||
const TIMEOUT: Duration = Duration::from_secs(600);
|
||||
/// Files of the combined data (`relative_files` keeps them relative to the directory it ran in).
|
||||
const MEASURED: &str = "import sys, json, coverage\n\
|
||||
d = coverage.CoverageData(sys.argv[1]); d.read(); print(json.dumps(sorted(d.measured_files())))";
|
||||
/// The files coverage.py reads its configuration from, in the directory it runs in.
|
||||
const CONFIG_FILES: [&str; 4] = [".coveragerc", "setup.cfg", "tox.ini", "pyproject.toml"];
|
||||
|
||||
/// Whether `path` is an SQLite database (coverage.py 5+ data).
|
||||
pub fn is_data_file(path: &Path) -> bool {
|
||||
let mut head = [0u8; 16];
|
||||
std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && &head == b"SQLite format 3\0"
|
||||
}
|
||||
|
||||
/// `path`, or every `.coverage.*` file next to it when it is one of a parallel run's.
|
||||
fn inputs(path: &Path) -> Vec<PathBuf> {
|
||||
let parallel = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage."));
|
||||
let mut files: Vec<PathBuf> = match (parallel, path.parent()) {
|
||||
(true, Some(dir)) => std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| {
|
||||
p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage.")) && is_data_file(p)
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
if files.is_empty() {
|
||||
files.push(path.to_path_buf());
|
||||
}
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
/// Where coverage.py ran: the nearest directory of `path` inside `root` with a coverage.py
|
||||
/// configuration file (a monorepo's `backend/pyproject.toml`), else `root`.
|
||||
fn run_dir(path: &Path, root: &Path) -> PathBuf {
|
||||
path.ancestors()
|
||||
.skip(1)
|
||||
.take_while(|d| d.starts_with(root))
|
||||
.find(|d| CONFIG_FILES.iter().any(|f| d.join(f).is_file()))
|
||||
.unwrap_or(root)
|
||||
.to_path_buf()
|
||||
}
|
||||
|
||||
/// Runs `python -W ignore <args>` in `dir` and returns its stdout. Python warnings are
|
||||
/// ignored so `PYTHONWARNINGS=error` can't turn coverage.py's warnings into failures.
|
||||
fn python(python: &Path, dir: &Path, args: &[&OsStr]) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(python);
|
||||
cmd.current_dir(dir).args(["-W", "ignore"]).args(args);
|
||||
let out = COVERAGE_PY.run(cmd, TIMEOUT, None)?;
|
||||
if out.success {
|
||||
return Ok(out.stdout);
|
||||
}
|
||||
let text = if out.stderr.trim().is_empty() { out.stdout } else { out.stderr };
|
||||
let text = text.trim();
|
||||
if text.contains("No module named coverage") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py in the project's interpreter ({}). Install it, or import the output of `coverage xml`.",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
if text.contains("no such option") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"Reading a .coverage data file needs coverage.py 6.3 or later in the project's interpreter ({}): {text}",
|
||||
python.display()
|
||||
)));
|
||||
}
|
||||
Err(IdeError::invalid(format!("coverage.py could not read the data: {text}")))
|
||||
}
|
||||
|
||||
/// Reads the data file at `path` with `python`'s coverage.py, run where the project's coverage.py
|
||||
/// configuration is; `out` holds the scratch files. Blocking.
|
||||
pub(crate) fn import(path: &Path, root: &Path, python_path: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
let dir = run_dir(path, root);
|
||||
let data = out.join(".coverage");
|
||||
let xml = out.join("coverage.xml");
|
||||
let coverage = |args: &[&OsStr]| {
|
||||
let mut all: Vec<&OsStr> = vec!["-m".as_ref(), "coverage".as_ref()];
|
||||
all.extend(args);
|
||||
python(python_path, &dir, &all)
|
||||
};
|
||||
let inputs = inputs(path);
|
||||
let mut args: Vec<&OsStr> = vec!["combine".as_ref(), "--keep".as_ref(), "--data-file".as_ref(), data.as_ref()];
|
||||
args.extend(inputs.iter().map(|p| p.as_os_str()));
|
||||
coverage(&args)?;
|
||||
// `-i`: report what has source here instead of failing on the first file that has none.
|
||||
// `--fail-under=0`: a `[report] fail_under` the data misses must not fail the import.
|
||||
coverage(&[
|
||||
"xml".as_ref(),
|
||||
"-i".as_ref(),
|
||||
"--fail-under=0".as_ref(),
|
||||
"--data-file".as_ref(),
|
||||
data.as_ref(),
|
||||
"-o".as_ref(),
|
||||
xml.as_ref(),
|
||||
])?;
|
||||
let text = std::fs::read_to_string(&xml)?;
|
||||
let mut acc = cobertura::parse(&text, &dir).map_err(|e| IdeError::invalid(format!("{}: {e}", xml.display())))?;
|
||||
// The files the report left out (no source here): listed without lines.
|
||||
let measured = python(python_path, &dir, &["-c".as_ref(), MEASURED.as_ref(), data.as_ref()])?;
|
||||
let measured: Vec<PathBuf> = serde_json::from_str(measured.trim())
|
||||
.map_err(|e| IdeError::invalid(format!("coverage.py listed the measured files unreadably: {e}")))?;
|
||||
for file in measured {
|
||||
acc.file(&dir.join(file));
|
||||
}
|
||||
Ok(acc.finish("coverage.py"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_the_files_of_a_parallel_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let db = |name: &str| {
|
||||
let p = tmp.path().join(name);
|
||||
std::fs::write(&p, b"SQLite format 3\0rest").unwrap();
|
||||
p
|
||||
};
|
||||
let a = db(".coverage.host.1.x");
|
||||
let b = db(".coverage.host.2.y");
|
||||
let single = db(".coverage");
|
||||
std::fs::write(tmp.path().join(".coverage.notes"), "text").unwrap();
|
||||
std::fs::write(tmp.path().join(".coveragerc"), "[run]\n").unwrap();
|
||||
assert!(is_data_file(&a) && !is_data_file(&tmp.path().join(".coveragerc")));
|
||||
assert_eq!(inputs(&a), [a.clone(), b]);
|
||||
assert_eq!(inputs(&single), [single]);
|
||||
}
|
||||
|
||||
/// Two parallel runs recorded on another machine (`…/ci/app`), mapped by the project's `[paths]`.
|
||||
/// Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn combines_parallel_data_with_the_projects_paths() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
// coverage.py reports real paths (`/private/var/…` for macOS's `/var/…`).
|
||||
let base = tmp.path().canonicalize().unwrap();
|
||||
let ci = base.join("ci/app");
|
||||
let root = base.join("project");
|
||||
let calc = "def sign(n):\n if n < 0:\n return -1\n return 1\n";
|
||||
for dir in [&ci, &root] {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join("calc.py"), calc).unwrap();
|
||||
}
|
||||
std::fs::write(ci.join("gone.py"), "x = 1\n").unwrap();
|
||||
std::fs::write(ci.join("neg.py"), "import calc, gone\ncalc.sign(-1)\n").unwrap();
|
||||
std::fs::write(ci.join("pos.py"), "import calc\ncalc.sign(1)\n").unwrap();
|
||||
for script in ["neg.py", "pos.py"] {
|
||||
let ok = Command::new("python3")
|
||||
.current_dir(&ci)
|
||||
.args(["-m", "coverage", "run", "--branch", "--parallel-mode", script])
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(ok.success());
|
||||
}
|
||||
let data = root.join("data");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
for e in std::fs::read_dir(&ci).unwrap().flatten() {
|
||||
if e.file_name().to_string_lossy().starts_with(".coverage.") {
|
||||
std::fs::rename(e.path(), data.join(e.file_name())).unwrap();
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&ci).unwrap();
|
||||
std::fs::write(root.join(".coveragerc"), "[paths]\nsource =\n ./\n */ci/app/\n").unwrap();
|
||||
let first = std::fs::read_dir(&data).unwrap().flatten().next().unwrap().path();
|
||||
let out = base.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&first, &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("calc.py")).unwrap();
|
||||
// Both runs together take both branches of line 2.
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (4, 4, 2, 2));
|
||||
// The scripts and `gone.py` have no source in the project: listed without lines.
|
||||
let empty: Vec<&str> = suite
|
||||
.files
|
||||
.iter()
|
||||
.filter(|f| f.lines.is_empty())
|
||||
.filter_map(|f| (f.path.as_ref() as &Path).file_name()?.to_str())
|
||||
.collect();
|
||||
assert_eq!(empty, ["gone.py", "neg.py", "pos.py"]);
|
||||
// They keep the recorded path, so the import notification counts them as not in the project.
|
||||
assert!(suite.files.iter().filter(|f| f.lines.is_empty()).all(|f| (f.path.as_ref() as &Path).starts_with(&ci)));
|
||||
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 2, "the user's data files are kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_where_the_coverage_configuration_is() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir_all(root.join("backend/reports")).unwrap();
|
||||
std::fs::create_dir_all(root.join("data")).unwrap();
|
||||
std::fs::write(root.join("backend/pyproject.toml"), "").unwrap();
|
||||
assert_eq!(run_dir(&root.join("backend/reports/.coverage"), root), root.join("backend"));
|
||||
assert_eq!(run_dir(&root.join("data/.coverage"), root), root);
|
||||
// A data file outside the project runs in the project.
|
||||
assert_eq!(run_dir(Path::new("/elsewhere/.coverage"), root), root);
|
||||
}
|
||||
|
||||
/// A stand-in interpreter that prints `stderr` and exits with `code`.
|
||||
#[cfg(unix)]
|
||||
fn fake_python(dir: &Path, stderr: &str, code: i32) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let p = dir.join("python");
|
||||
std::fs::write(&p, format!("#!/bin/sh\necho '{stderr}' >&2\nexit {code}\n")).unwrap();
|
||||
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
p
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn reports_why_coverage_py_failed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let data = tmp.path().join(".coverage");
|
||||
let err = |stderr: &str| {
|
||||
let python = fake_python(tmp.path(), stderr, 1);
|
||||
import(&data, tmp.path(), &python, tmp.path()).unwrap_err().to_string()
|
||||
};
|
||||
assert!(err("No module named coverage").contains("needs coverage.py in the project's interpreter"));
|
||||
assert!(err("no such option: --data-file").contains("needs coverage.py 6.3 or later"));
|
||||
assert!(err("No usable data files").contains("coverage.py could not read the data: No usable data files"));
|
||||
}
|
||||
|
||||
/// A monorepo member's data recorded with `relative_files`, below its `fail_under`, with
|
||||
/// coverage.py's warnings turned off. Needs coverage.py in `python3`; skipped without it.
|
||||
#[test]
|
||||
fn reads_a_members_relative_data_below_fail_under() {
|
||||
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
|
||||
if !has_coverage.is_ok_and(|o| o.status.success()) {
|
||||
eprintln!("skipped: no coverage.py in python3");
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().canonicalize().unwrap();
|
||||
let member = root.join("backend");
|
||||
std::fs::create_dir_all(member.join("app")).unwrap();
|
||||
std::fs::write(
|
||||
member.join("pyproject.toml"),
|
||||
"[tool.coverage.run]\nrelative_files = true\nbranch = true\ndisable_warnings = [\"couldnt-parse\"]\n\
|
||||
[tool.coverage.report]\nfail_under = 90\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(member.join("app/x.py"), "def f(n):\n if n:\n return 1\n return 2\n").unwrap();
|
||||
std::fs::write(member.join("t.py"), "from app import x\nx.f(1)\n").unwrap();
|
||||
let ok = Command::new("python3").current_dir(&member).args(["-m", "coverage", "run", "t.py"]).status().unwrap();
|
||||
assert!(ok.success());
|
||||
std::fs::remove_file(member.join("t.py")).unwrap();
|
||||
let out = root.join("out");
|
||||
std::fs::create_dir_all(&out).unwrap();
|
||||
let suite = import(&member.join(".coverage"), &root, Path::new("python3"), &out).unwrap();
|
||||
|
||||
let x = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("app/x.py")).unwrap();
|
||||
assert_eq!((x.lines_total, x.lines_covered, x.branches_total, x.branches_covered), (4, 3, 2, 1));
|
||||
// `t.py` has no source any more and its warning is off: still listed, without lines.
|
||||
let t = suite.files.iter().find(|f| f.path.as_ref() as &Path == member.join("t.py")).unwrap();
|
||||
assert!(t.lines.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
//! "Import a report collected in CI from disk": the format is sniffed from the
|
||||
//! content (lcov, Go cover profile, JaCoCo XML, SimpleCov resultset) and paths recorded on another
|
||||
//! content (lcov, Go cover profile, JaCoCo or Cobertura XML, SimpleCov resultset) and paths recorded on another
|
||||
//! machine are mapped into the project by their longest existing suffix.
|
||||
|
||||
use crate::{Accumulator, CoverageSuite, goprofile, jacoco, lcov, simplecov};
|
||||
use crate::{Accumulator, CoverageSuite, cobertura, goprofile, jacoco, lcov, simplecov};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -11,13 +12,19 @@ pub(crate) enum Format {
|
||||
Lcov,
|
||||
GoProfile,
|
||||
Jacoco,
|
||||
Cobertura,
|
||||
SimpleCov,
|
||||
}
|
||||
|
||||
pub(crate) fn detect(text: &str) -> Option<Format> {
|
||||
let head = text.trim_start_matches('\u{feff}').trim_start();
|
||||
if head.starts_with('<') {
|
||||
return head.contains("<report").then_some(Format::Jacoco);
|
||||
// The root element, after any prolog or DOCTYPE naming it.
|
||||
return match (head.find("<report"), head.find("<coverage")) {
|
||||
(Some(r), c) if c.is_none_or(|c| r < c) => Some(Format::Jacoco),
|
||||
(_, Some(_)) => Some(Format::Cobertura),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if head.starts_with('{') {
|
||||
return head.contains("\"coverage\"").then_some(Format::SimpleCov);
|
||||
@@ -39,6 +46,9 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
let (module, module_dir) = go_module_for(root, &text);
|
||||
goprofile::parse(&text, &module, &module_dir).finish("go test -cover")
|
||||
}
|
||||
Some(Format::Cobertura) => cobertura::parse(&text, root)
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?
|
||||
.finish("Cobertura"),
|
||||
Some(Format::Jacoco) => {
|
||||
// A report inside the project (`<module>/target/site/jacoco/…`) knows its module.
|
||||
let module = jacoco::module_dir(path);
|
||||
@@ -53,18 +63,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
|
||||
acc.finish("JaCoCo")
|
||||
}
|
||||
None if text.starts_with("!coverage.py: This is a private format") => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is coverage.py 4 data, which current coverage.py can't read. Import the output of `coverage xml` instead.",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
None => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo XML report or SimpleCov resultset",
|
||||
"{} is not an lcov tracefile, Go cover profile, JaCoCo or Cobertura XML report or SimpleCov resultset",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
let mut dirs = HashMap::new();
|
||||
for f in &mut suite.files {
|
||||
let p: &Path = f.path.as_ref();
|
||||
if !p.exists()
|
||||
&& let Some(found) = relocate(p, root)
|
||||
{
|
||||
let present = p.parent().is_none_or(|d| dir_exists(d, &mut dirs)) && p.exists();
|
||||
if !present && let Some(found) = relocate(p, root) {
|
||||
f.path = found.into();
|
||||
}
|
||||
}
|
||||
@@ -72,6 +88,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
|
||||
Ok(suite)
|
||||
}
|
||||
|
||||
/// Reads a coverage.py data file (see [`crate::is_data_file`]) with the coverage.py of `python`,
|
||||
/// run in `root`; `out` is an empty scratch directory. Blocking.
|
||||
pub fn import_data(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult<CoverageSuite> {
|
||||
crate::coveragepy::import(path, root, python, out)
|
||||
}
|
||||
|
||||
/// Whether `dir` exists, without asking again below a directory known to be missing: every
|
||||
/// lookup under macOS's `/home` (autofs) takes tens of milliseconds, and CI reports
|
||||
/// (`/home/runner/work/…`) name thousands of files there.
|
||||
fn dir_exists(dir: &Path, known: &mut HashMap<PathBuf, bool>) -> bool {
|
||||
if let Some(&e) = known.get(dir) {
|
||||
return e;
|
||||
}
|
||||
let e = dir.parent().is_none_or(|p| dir_exists(p, known)) && dir.is_dir();
|
||||
known.insert(dir.to_path_buf(), e);
|
||||
e
|
||||
}
|
||||
|
||||
/// `/home/runner/work/app/app/src/lib.rs` → `<root>/src/lib.rs`: the longest suffix of
|
||||
/// `path` that exists under `root`.
|
||||
pub(crate) fn relocate(path: &Path, root: &Path) -> Option<PathBuf> {
|
||||
@@ -129,12 +163,30 @@ mod tests {
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE report><report name=\"x\"></report>"),
|
||||
Some(Format::Jacoco)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), None);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), Some(Format::Cobertura));
|
||||
assert_eq!(
|
||||
detect("<?xml version=\"1.0\"?><!DOCTYPE coverage SYSTEM \"x.dtd\"><coverage/>"),
|
||||
Some(Format::Cobertura)
|
||||
);
|
||||
assert_eq!(detect("<?xml version=\"1.0\"?><html/>"), None);
|
||||
assert_eq!(detect("{\"RSpec\": {\"coverage\": {}}}"), Some(Format::SimpleCov));
|
||||
assert_eq!(detect("{\"name\": \"package.json\"}"), None);
|
||||
assert_eq!(detect("hello"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_directories_are_looked_up_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut known = HashMap::new();
|
||||
assert!(dir_exists(tmp.path(), &mut known));
|
||||
let gone = tmp.path().join("gone");
|
||||
assert!(!dir_exists(&gone.join("a/b"), &mut known));
|
||||
std::fs::create_dir_all(gone.join("a/c")).unwrap();
|
||||
// Known to be missing, so its subdirectories are not looked up.
|
||||
assert!(!dir_exists(&gone.join("a/c"), &mut known));
|
||||
assert_eq!(known.get(&gone), Some(&false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_ci_simplecov_with_foreign_paths() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -168,8 +220,75 @@ mod tests {
|
||||
assert!(import(&tmp.path().join("missing"), &root).is_err());
|
||||
std::fs::write(&report, "nothing").unwrap();
|
||||
assert!(import(&report, &root).is_err());
|
||||
std::fs::write(&report, "!coverage.py: This is a private format, don't read it directly!{\"lines\":{}}")
|
||||
.unwrap();
|
||||
assert!(import(&report, &root).unwrap_err().to_string().contains("coverage.py 4 data"));
|
||||
}
|
||||
|
||||
/// `coverage xml` (coverage.py 7.17, `--branch`) of a project checked out on a CI runner.
|
||||
#[test]
|
||||
fn imports_coverage_py_xml_with_foreign_sources() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("app");
|
||||
std::fs::create_dir_all(root.join("src/calc")).unwrap();
|
||||
std::fs::write(root.join("src/calc/__init__.py"), "").unwrap();
|
||||
let report = tmp.path().join("coverage.xml");
|
||||
std::fs::write(&report, COVERAGE_PY_XML).unwrap();
|
||||
let suite = import(&report, &root).unwrap();
|
||||
assert_eq!(suite.runner, "Cobertura");
|
||||
assert!(suite.has_branches);
|
||||
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("src/calc/__init__.py")).unwrap();
|
||||
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (8, 5, 4, 2));
|
||||
assert_eq!(calc.lines.iter().filter(|l| l.partial()).map(|l| l.line).collect::<Vec<_>>(), [1, 3]);
|
||||
// The test file is not in this checkout: it keeps the runner's path.
|
||||
assert!(
|
||||
suite.files.iter().any(|f| f.path.as_ref() as &Path == Path::new("/home/runner/work/app/app/test_calc.py"))
|
||||
);
|
||||
}
|
||||
|
||||
const COVERAGE_PY_XML: &str = r#"<?xml version="1.0" ?>
|
||||
<coverage version="7.17.5" timestamp="1795754882920" lines-valid="13" lines-covered="10" line-rate="0.7692" branches-valid="4" branches-covered="2" branch-rate="0.5" complexity="0">
|
||||
<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.17.5 -->
|
||||
<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
|
||||
<sources>
|
||||
<source>/home/runner/work/app/app</source>
|
||||
</sources>
|
||||
<packages>
|
||||
<package name="." line-rate="1" branch-rate="1" complexity="0">
|
||||
<classes>
|
||||
<class name="test_calc.py" filename="test_calc.py" complexity="0" line-rate="1" branch-rate="1">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1"/>
|
||||
<line number="3" hits="1"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="7" hits="1"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
<package name="src.calc" line-rate="0.625" branch-rate="0.5" complexity="0">
|
||||
<classes>
|
||||
<class name="__init__.py" filename="src/calc/__init__.py" complexity="0" line-rate="0.625" branch-rate="0.5">
|
||||
<methods/>
|
||||
<lines>
|
||||
<line number="1" hits="1"/>
|
||||
<line number="2" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
|
||||
<line number="3" hits="0"/>
|
||||
<line number="4" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="5"/>
|
||||
<line number="5" hits="0"/>
|
||||
<line number="6" hits="1"/>
|
||||
<line number="13" hits="1"/>
|
||||
<line number="14" hits="0"/>
|
||||
</lines>
|
||||
</class>
|
||||
</classes>
|
||||
</package>
|
||||
</packages>
|
||||
</coverage>
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn imports_go_profiles_of_nested_modules() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
//!
|
||||
//! Lines in the model are 0-based, like every IPC coordinate.
|
||||
|
||||
mod cobertura;
|
||||
mod coveragepy;
|
||||
mod goprofile;
|
||||
mod import;
|
||||
mod jacoco;
|
||||
@@ -23,7 +25,8 @@ mod lcov;
|
||||
mod plan;
|
||||
mod simplecov;
|
||||
|
||||
pub use import::import;
|
||||
pub use coveragepy::is_data_file;
|
||||
pub use import::{import, import_data};
|
||||
pub use plan::prepare;
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
|
||||
@@ -326,7 +326,8 @@ fn python(config: &RunConfig, dir: &Path, out: &Path, py: wrap::PythonCommand) -
|
||||
argv.extend(py.target.iter().cloned());
|
||||
let report = CoverageReportSpec::Exported {
|
||||
runner: s("coverage.py"),
|
||||
argv: with(&["-m", "coverage", "lcov", "-o", &path(&lcov)]),
|
||||
// `--fail-under=0`: a `[report] fail_under` the run misses must not lose its report.
|
||||
argv: with(&["-m", "coverage", "lcov", "--fail-under=0", "-o", &path(&lcov)]),
|
||||
cwd: dir.to_path_buf().into(),
|
||||
env: config.env.clone(),
|
||||
lcov: lcov.into(),
|
||||
|
||||
@@ -17,6 +17,7 @@ ide-jvm-attach.workspace = true
|
||||
ide-jvm-inspect.workspace = true
|
||||
ide-jdwp.workspace = true
|
||||
ide-heap.workspace = true
|
||||
ide-run.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
|
||||
@@ -391,9 +391,10 @@ pub const DEBUGPY_MISSING: &str = "debugpy is not installed";
|
||||
/// `PYTHONPATH`. Neither: an `unavailable` error naming the interpreter.
|
||||
pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
|
||||
let (command, cwd) = (spec.command.clone(), spec.cwd.clone());
|
||||
let Some(python) = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)).await.ok().flatten() else {
|
||||
let Some(python) = tokio::task::spawn_blocking(move || debugpy_python(&command, &cwd)).await.ok().flatten() else {
|
||||
return Ok(()); // Reported as a missing adapter when it is started.
|
||||
};
|
||||
spec.command = python.to_string_lossy().into_owned();
|
||||
let mut probe = Command::new(&python);
|
||||
probe.current_dir(&spec.cwd);
|
||||
ide_core::process::prepare(probe.as_std_mut());
|
||||
@@ -426,6 +427,46 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
|
||||
)))
|
||||
}
|
||||
|
||||
/// The interpreter `<python> -m debugpy.adapter` runs with. On Windows a bare `python3` (the
|
||||
/// built-in `python.toml`'s) or `python` may name an App Execution Alias in `WindowsApps`,
|
||||
/// which only opens the Store unless the Store's Python is installed: every match on `PATH`
|
||||
/// of the command, then `python`, then the `py` launcher, the first that is no alias or runs.
|
||||
fn debugpy_python(command: &str, cwd: &Path) -> Option<PathBuf> {
|
||||
let found = resolve_binary(command, cwd);
|
||||
if !cfg!(windows) || !matches!(command, "python3" | "python") {
|
||||
return found;
|
||||
}
|
||||
let pathext = std::env::var("PATHEXT").ok();
|
||||
let dirs = search_dirs(cwd);
|
||||
let mut candidates: Vec<PathBuf> = Vec::new();
|
||||
for name in [command, "python", "py"] {
|
||||
for dir in &dirs {
|
||||
if let Some(p) = find_binary_in(name, cwd, std::slice::from_ref(dir), true, pathext.as_deref())
|
||||
&& !candidates.contains(&p)
|
||||
{
|
||||
candidates.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
let runs = |p: &Path| {
|
||||
let mut c = std::process::Command::new(p);
|
||||
ide_core::process::prepare(&mut c);
|
||||
c.arg("--version").stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
|
||||
c.status().is_ok_and(|s| s.success())
|
||||
};
|
||||
pick_python(candidates, runs).or(found)
|
||||
}
|
||||
|
||||
/// The first candidate that is no App Execution Alias, or is one that `runs`.
|
||||
fn pick_python(candidates: Vec<PathBuf>, runs: impl Fn(&Path) -> bool) -> Option<PathBuf> {
|
||||
candidates.into_iter().find(|p| !is_app_execution_alias(p) || runs(p))
|
||||
}
|
||||
|
||||
/// A Windows App Execution Alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\python3.exe`).
|
||||
fn is_app_execution_alias(path: &Path) -> bool {
|
||||
path.parent().and_then(Path::file_name).is_some_and(|d| d.eq_ignore_ascii_case("WindowsApps"))
|
||||
}
|
||||
|
||||
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
|
||||
/// "Interpreter `dap' unrecognized".
|
||||
const GDB_MIN_MAJOR: u32 = 14;
|
||||
@@ -859,6 +900,34 @@ async fn connect_with_retries(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Windows: a Store alias on `PATH` before the real interpreter is skipped unless it runs
|
||||
/// (the Store's Python is installed), so the Python Debug Server starts the real one.
|
||||
#[test]
|
||||
fn debugpy_skips_store_aliases_that_do_not_run() {
|
||||
let alias = PathBuf::from("C:/Users/me/AppData/Local/Microsoft/WindowsApps/python3.exe");
|
||||
let real = PathBuf::from("C:/Program Files/Python313/python.exe");
|
||||
assert!(is_app_execution_alias(&alias) && !is_app_execution_alias(&real));
|
||||
let both = vec![alias.clone(), real.clone()];
|
||||
assert_eq!(pick_python(both.clone(), |_| false), Some(real.clone()));
|
||||
assert_eq!(pick_python(both, |_| true), Some(alias.clone()));
|
||||
assert_eq!(pick_python(vec![alias], |_| false), None);
|
||||
}
|
||||
|
||||
/// A user's `languages/python.toml` `[debugger]` is the one debugpy runs with: no other
|
||||
/// language (a template one) declares debugpy before Python.
|
||||
#[test]
|
||||
fn debugpy_comes_from_the_python_language() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let python = include_str!("../../../languages/python.toml").replace(
|
||||
"args = [\"-m\", \"debugpy.adapter\"]",
|
||||
"args = [\"-X\", \"frozen_modules=off\", \"-m\", \"debugpy.adapter\"]",
|
||||
);
|
||||
assert!(python.contains("frozen_modules"));
|
||||
std::fs::write(dir.path().join("python.toml"), python).unwrap();
|
||||
let languages = LanguageRegistry::load(Some(dir.path())).unwrap();
|
||||
assert_eq!(find_config(&languages, "debugpy").unwrap().args[0], "-X");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapters_run_on_the_tool_search_path() {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
|
||||
@@ -51,12 +51,17 @@ pub async fn build(
|
||||
cwd: &Path,
|
||||
args: &[String],
|
||||
filter: &CargoFilter,
|
||||
cancel: &ide_core::CancellationToken,
|
||||
on_output: impl Fn(String) + Send + Sync + 'static,
|
||||
) -> IdeResult<PathBuf> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let cargo = find_binary("cargo", cwd).ok_or_else(|| IdeError::unavailable("`cargo` not found on PATH"))?;
|
||||
let mut cmd = tokio::process::Command::new(cargo);
|
||||
cmd.current_dir(cwd);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
ide_core::process::own_group(cmd.as_std_mut());
|
||||
cmd.args(args)
|
||||
.arg("--message-format=json-render-diagnostics")
|
||||
.stdin(Stdio::null())
|
||||
@@ -65,11 +70,13 @@ pub async fn build(
|
||||
.kill_on_drop(true);
|
||||
on_output(format!("> cargo {}\n", args.join(" ")));
|
||||
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("failed to run cargo: {e}")))?;
|
||||
#[cfg(windows)]
|
||||
let job = child.id().and_then(ide_core::process::Job::for_pid);
|
||||
let stderr = child.stderr.take().ok_or_else(|| IdeError::internal("cargo stderr unavailable"))?;
|
||||
let stdout = child.stdout.take().ok_or_else(|| IdeError::internal("cargo stdout unavailable"))?;
|
||||
let on_output = std::sync::Arc::new(on_output);
|
||||
let err_out = on_output.clone();
|
||||
let err_task = tokio::spawn(async move {
|
||||
let mut err_task = tokio::spawn(async move {
|
||||
let mut lines = BufReader::new(stderr).split(b'\n');
|
||||
while let Ok(Some(line)) = lines.next_segment().await {
|
||||
let line = ide_core::output_encoding::decode_tool_output(&line);
|
||||
@@ -77,19 +84,44 @@ pub async fn build(
|
||||
err_out(format!("{line}\n"));
|
||||
}
|
||||
});
|
||||
let mut found = None;
|
||||
let mut lines = BufReader::new(stdout).lines();
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
if let Some(exe) = artifact_executable(&line, filter) {
|
||||
found = Some(exe);
|
||||
let outcome = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => None,
|
||||
result = async {
|
||||
let mut found = None;
|
||||
let mut lines = BufReader::new(stdout).lines();
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
if let Some(exe) = artifact_executable(&line, filter) {
|
||||
found = Some(exe);
|
||||
}
|
||||
}
|
||||
let _ = (&mut err_task).await;
|
||||
let status = child.wait().await?;
|
||||
if !status.success() {
|
||||
return Err(IdeError::invalid(format!("cargo {} failed ({status})", args.first().map_or("", |s| s))));
|
||||
}
|
||||
found.ok_or_else(|| IdeError::invalid("cargo produced no executable to debug"))
|
||||
} => Some(result),
|
||||
};
|
||||
match outcome {
|
||||
Some(result) => result,
|
||||
None => {
|
||||
err_task.abort();
|
||||
if let Some(pid) = child.id() {
|
||||
let _ = tokio::task::spawn_blocking(move || {
|
||||
#[cfg(windows)]
|
||||
if let Some(job) = job {
|
||||
job.terminate();
|
||||
return;
|
||||
}
|
||||
ide_core::process::kill_tree_of(pid);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
let _ = child.kill().await;
|
||||
Err(IdeError::cancelled())
|
||||
}
|
||||
}
|
||||
let _ = err_task.await;
|
||||
let status = child.wait().await?;
|
||||
if !status.success() {
|
||||
return Err(IdeError::invalid(format!("cargo {} failed ({status})", args.first().map_or("", |s| s))));
|
||||
}
|
||||
found.ok_or_else(|| IdeError::invalid("cargo produced no executable to debug"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Python Debug Server (`attach` with `listen`): the program connects with its own debugpy,
|
||||
//! which may differ from the IDE's adapter. Nothing in the protocol compares them.
|
||||
|
||||
use crate::session::Session;
|
||||
use ide_core::IdeError;
|
||||
use ide_core::event::DebugEvent;
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
pub(crate) fn listens(adapter: &str, request: &str, arguments: &Value) -> bool {
|
||||
adapter == "debugpy" && request == "attach" && arguments.get("listen").is_some()
|
||||
}
|
||||
|
||||
/// debugpy's adapter leaves an `attach` whose port is taken unanswered (it only logs the error),
|
||||
/// which would wait for the program forever: find out before starting it. Listening again right
|
||||
/// after a program ended races the previous adapter, which still listens until its shutdown ends.
|
||||
pub(crate) async fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
|
||||
// ponytail: polls; waiting on the previous session's shutdown would report a taken port sooner.
|
||||
const RELEASE: Duration = Duration::from_secs(5);
|
||||
let listen = &arguments["listen"];
|
||||
let host = listen["host"].as_str().unwrap_or("127.0.0.1");
|
||||
let Some(port) = listen["port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { return Ok(()) };
|
||||
let deadline = tokio::time::Instant::now() + RELEASE;
|
||||
loop {
|
||||
match std::net::TcpListener::bind((host, port)) {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && tokio::time::Instant::now() < deadline => {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Err(e) => return Err(IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On the program's first stop: warns in the Debug console when its debugpy is not the adapter's.
|
||||
/// Evaluated in the stopped frame as a hover: without a frame, debugpy before 1.8 runs the
|
||||
/// expression as a statement and prints its value into the program's output.
|
||||
pub(crate) async fn check_version(s: Arc<Session>, thread: i64) {
|
||||
const WAIT: Duration = Duration::from_secs(5);
|
||||
let request = |command: &'static str, arguments: Value| s.conn.request_timeout(command, arguments, WAIT);
|
||||
let Ok(info) = request("debugpySystemInfo", json!({})).await else { return };
|
||||
let Some(ide) = info.pointer("/debugpy/version").and_then(Value::as_str) else { return };
|
||||
let Ok(trace) = request("stackTrace", json!({ "threadId": thread, "levels": 1 })).await else { return };
|
||||
let Some(frame) = trace.pointer("/stackFrames/0/id").and_then(Value::as_i64) else { return };
|
||||
let expression = json!({ "expression": "__import__('debugpy').__version__", "frameId": frame, "context": "hover" });
|
||||
let Ok(reply) = request("evaluate", expression).await else { return };
|
||||
let Some(program) = reply.get("result").and_then(Value::as_str) else { return };
|
||||
if let Some(warning) = version_warning(ide, program) {
|
||||
s.emit(DebugEvent::Output { category: "console".into(), output: warning });
|
||||
}
|
||||
}
|
||||
|
||||
fn version_warning(ide: &str, program: &str) -> Option<String> {
|
||||
let program = program.trim_matches(|c| c == '\'' || c == '"');
|
||||
(program != ide).then(|| {
|
||||
format!(
|
||||
"The program uses debugpy {program}, the IDE's debugger debugpy {ide}. If breakpoints or stepping \
|
||||
misbehave, install the same version where the program runs: pip install debugpy=={ide}\n"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn warns_only_when_versions_differ() {
|
||||
assert_eq!(version_warning("1.8.22", "'1.8.22'"), None);
|
||||
assert_eq!(version_warning("1.8.22", "1.8.22"), None);
|
||||
let w = version_warning("1.8.22", "'1.8.0'").unwrap();
|
||||
assert!(w.contains("debugpy 1.8.0") && w.ends_with("pip install debugpy==1.8.22\n"), "{w}");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_taken_port_is_reported_before_the_adapter_starts() {
|
||||
let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = taken.local_addr().unwrap().port();
|
||||
let listen = json!({"listen": {"host": "127.0.0.1", "port": port}});
|
||||
let e = require_free_port(&listen).await.unwrap_err();
|
||||
assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}");
|
||||
drop(taken);
|
||||
assert!(require_free_port(&listen).await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_address_the_machine_lacks_is_reported_at_once() {
|
||||
// 192.0.2.0/24 is reserved for documentation, never a local address.
|
||||
let started = std::time::Instant::now();
|
||||
let e = require_free_port(&json!({"listen": {"host": "192.0.2.1", "port": 5678}})).await.unwrap_err();
|
||||
assert!(e.to_string().contains("Cannot listen on 192.0.2.1:5678"), "{e}");
|
||||
assert!(started.elapsed() < Duration::from_secs(1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn waits_for_the_previous_adapter_to_release_the_port() {
|
||||
let previous = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = previous.local_addr().unwrap().port();
|
||||
let released = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
drop(previous);
|
||||
});
|
||||
require_free_port(&json!({"listen": {"host": "127.0.0.1", "port": port}})).await.unwrap();
|
||||
released.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_debugpy_listen_attaches_check() {
|
||||
assert!(listens("debugpy", "attach", &json!({"listen": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "attach", &json!({"connect": {"port": 5678}})));
|
||||
assert!(!listens("debugpy", "launch", &json!({"listen": {}})));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! Machine code of a native program (DAP `disassemble`), for the Disassembly view.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use specta::Type;
|
||||
|
||||
/// The most instructions one request asks for.
|
||||
pub const MAX_INSTRUCTIONS: u32 = 1000;
|
||||
|
||||
/// One disassembled instruction.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Instruction {
|
||||
/// Address as the adapter writes it (`0x5555…`); also a memory reference for the next request.
|
||||
pub address: String,
|
||||
/// The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`).
|
||||
pub instruction: String,
|
||||
/// Its machine code as hex (`488b45d8`), when the adapter sends it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub bytes: Option<String>,
|
||||
/// The function it belongs to, when the adapter names it (often on the first instruction only).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub symbol: Option<String>,
|
||||
}
|
||||
|
||||
/// `disassemble`'s instructions in order; `None` for the padding adapters put where there is no
|
||||
/// code (`presentationHint: "invalid"`, or no address).
|
||||
pub(crate) fn instructions(body: &Value) -> Vec<Option<Instruction>> {
|
||||
let text = |i: &Value, k: &str| i.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
let Some(list) = body.get("instructions").and_then(Value::as_array) else { return Vec::new() };
|
||||
list.iter()
|
||||
.map(|i| {
|
||||
if i.get("presentationHint").and_then(Value::as_str) == Some("invalid") {
|
||||
return None;
|
||||
}
|
||||
Some(Instruction {
|
||||
address: text(i, "address")?,
|
||||
instruction: text(i, "instruction").unwrap_or_default(),
|
||||
bytes: text(i, "instructionBytes"),
|
||||
symbol: text(i, "symbol"),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A memory reference or address as a number (`0x7ffd…` or decimal).
|
||||
pub(crate) fn address(reference: &str) -> Option<u128> {
|
||||
let r = reference.trim();
|
||||
match r.strip_prefix("0x").or_else(|| r.strip_prefix("0X")) {
|
||||
Some(hex) => u128::from_str_radix(hex, 16).ok(),
|
||||
None => r.parse().ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the instruction at `index` is the one at `reference`. References that are not
|
||||
/// addresses cannot be checked and pass.
|
||||
pub(crate) fn at_index(instructions: &[Option<Instruction>], reference: &str, index: usize) -> bool {
|
||||
let Some(want) = address(reference) else { return instructions.len() > index };
|
||||
instructions.get(index).and_then(Option::as_ref).and_then(|i| address(&i.address)) == Some(want)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn reads_gdbs_instructions() {
|
||||
// GDB 17.1 at the reporter-style C fixture's loop line.
|
||||
let body = json!({"instructions": [
|
||||
{"address": "0x5555555551f5", "instruction": "mov -0x2c(%rbp),%eax", "instructionBytes": "8b45d4", "line": 14},
|
||||
{"address": "0x5555555551f8", "instruction": "cltq", "instructionBytes": "4898", "symbol": "sum"},
|
||||
]});
|
||||
let got = instructions(&body);
|
||||
assert_eq!(
|
||||
got[0],
|
||||
Some(Instruction {
|
||||
address: "0x5555555551f5".into(),
|
||||
instruction: "mov -0x2c(%rbp),%eax".into(),
|
||||
bytes: Some("8b45d4".into()),
|
||||
symbol: None,
|
||||
})
|
||||
);
|
||||
assert_eq!(got[1].as_ref().unwrap().symbol.as_deref(), Some("sum"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_is_not_an_instruction() {
|
||||
let body = json!({"instructions": [
|
||||
{"address": "0xfff0", "instruction": "", "presentationHint": "invalid"},
|
||||
{"instruction": "??"},
|
||||
{"address": "0x10000", "instruction": "nop"},
|
||||
]});
|
||||
let got = instructions(&body);
|
||||
assert_eq!((got[0].is_none(), got[1].is_none(), got[2].is_some()), (true, true, true));
|
||||
assert!(instructions(&json!({})).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_reference_by_its_address() {
|
||||
let list = instructions(&json!({"instructions": [
|
||||
{"address": "0x00001000", "instruction": "push %rbp"},
|
||||
{"address": "0x1001", "instruction": "mov %rsp,%rbp"},
|
||||
]}));
|
||||
assert!(at_index(&list, "0x1001", 1));
|
||||
assert!(at_index(&list, "4097", 1));
|
||||
assert!(at_index(&list, "0X1000", 0));
|
||||
assert!(!at_index(&list, "0x1001", 0));
|
||||
assert!(!at_index(&list, "0x1001", 2));
|
||||
assert!(at_index(&list, "frame-3", 1), "opaque references cannot be checked");
|
||||
assert_eq!(address("0xffffffffffffffff1"), Some(0xffffffffffffffff1));
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ pub mod adapter;
|
||||
pub mod attach;
|
||||
mod cargo;
|
||||
pub mod connection;
|
||||
mod debugpy;
|
||||
mod disassembly;
|
||||
mod exception_classes;
|
||||
pub mod jdwp;
|
||||
mod js_cdp;
|
||||
@@ -19,12 +21,15 @@ mod js_debug;
|
||||
mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
mod memory;
|
||||
mod session;
|
||||
mod stream_trace;
|
||||
mod swiftpm;
|
||||
pub mod unity;
|
||||
|
||||
use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher};
|
||||
use connection::{Connection, DapError};
|
||||
pub use disassembly::{Instruction, MAX_INSTRUCTIONS};
|
||||
pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport};
|
||||
use futures::future::join_all;
|
||||
use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink};
|
||||
@@ -32,6 +37,7 @@ use ide_language::LanguageRegistry;
|
||||
pub use js_cdp::JsResponseRule;
|
||||
pub use js_debug::JsResponseBody;
|
||||
pub use jvm_memory::*;
|
||||
pub use memory::{MAX_READ, MemoryBlock};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
@@ -44,6 +50,11 @@ use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
pub use stream_trace::{TracePhase, TraceProgress, TraceRun, TraceUnavailable};
|
||||
|
||||
/// The adapter name of a notebook kernel's own debugger (see [`DebugManager::start_over`]).
|
||||
pub const NOTEBOOK_ADAPTER: &str = "jupyter-kernel";
|
||||
/// How a notebook cell's breakpoints are keyed: `vscode-notebook-cell:<notebook>#<cell>`.
|
||||
pub const NOTEBOOK_CELL_SCHEME: &str = "vscode-notebook-cell:";
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LaunchConfig {
|
||||
@@ -153,6 +164,12 @@ pub struct DebugCapabilities {
|
||||
/// A stream chain can be traced while the program runs it ([`DebugManager::stream_trace`]).
|
||||
/// Can change during the session, like `jvm_instances`.
|
||||
pub stream_trace: bool,
|
||||
/// The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View.
|
||||
pub read_memory: bool,
|
||||
/// The program's machine code can be disassembled ([`DebugManager::disassemble`]): the Disassembly view.
|
||||
pub disassemble: bool,
|
||||
/// Steps can move by one instruction ([`DebugManager::step_instruction`]).
|
||||
pub instruction_stepping: bool,
|
||||
}
|
||||
|
||||
/// Result of [`DebugManager::redefine_classes`].
|
||||
@@ -219,6 +236,10 @@ pub struct StackFrame {
|
||||
pub column: u32,
|
||||
/// `subtle` frames (library/generated) are collapsed in the UI.
|
||||
pub presentation_hint: Option<String>,
|
||||
/// The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub instruction_pointer_reference: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
@@ -243,6 +264,10 @@ pub struct Variable {
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
#[specta(optional)]
|
||||
pub lazy: bool,
|
||||
/// Where the value points to or is stored, for [`DebugManager::read_memory`] (DAP `memoryReference`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub memory_reference: Option<String>,
|
||||
}
|
||||
|
||||
/// A completion the adapter offers for an expression (DAP `completions`).
|
||||
@@ -308,6 +333,14 @@ pub struct SessionInfo {
|
||||
pub parent: Option<DebugSessionId>,
|
||||
}
|
||||
|
||||
/// One owner's breakpoints, kept without a session and sent when one of its sessions starts.
|
||||
#[derive(Default)]
|
||||
struct OwnerBreakpoints {
|
||||
lines: BTreeMap<PathBuf, Vec<Breakpoint>>,
|
||||
functions: Vec<FunctionBreakpoint>,
|
||||
data: Vec<DataBreakpoint>,
|
||||
}
|
||||
|
||||
/// Who started a session. Every event of the session, and of the child sessions
|
||||
/// its adapter starts, goes to `sink` only; `key` (e.g. a window label) scopes
|
||||
/// listings such as [`DebugManager::sessions`].
|
||||
@@ -336,13 +369,12 @@ pub struct DebugManager {
|
||||
sessions: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
/// Session start order, for "the first session" semantics.
|
||||
order: Mutex<Vec<DebugSessionId>>,
|
||||
breakpoints: Mutex<BTreeMap<PathBuf, Vec<Breakpoint>>>,
|
||||
/// Breakpoints by owner (window): each window's sessions get only its own.
|
||||
breakpoints: Mutex<HashMap<String, OwnerBreakpoints>>,
|
||||
states: Mutex<HashMap<PathBuf, Vec<BreakpointState>>>,
|
||||
/// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default.
|
||||
exception_choices: Mutex<BTreeMap<String, bool>>,
|
||||
exception_classes: Mutex<Vec<ExceptionClassBreakpoint>>,
|
||||
function_breakpoints: Mutex<Vec<FunctionBreakpoint>>,
|
||||
data_breakpoints: Mutex<Vec<DataBreakpoint>>,
|
||||
/// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills.
|
||||
stopping: Mutex<HashMap<DebugSessionId, Arc<Session>>>,
|
||||
jvm_finder: Mutex<jvm_memory::JvmFinder>,
|
||||
@@ -582,6 +614,15 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<Debug
|
||||
Ok(Some(DebugServer { host, port }))
|
||||
}
|
||||
|
||||
/// A source served only through the `source` request whose `path` is no file, such as
|
||||
/// lldb-dap's ``/usr/lib/swift/libswiftCore.dylib`swift_willThrow`` for a frame without
|
||||
/// debug info. Opening it would show an error tab; without a path the stop selects the
|
||||
/// first frame with source instead. Non-file paths (`jdt://`, `<node_internals>`) stay.
|
||||
fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool {
|
||||
let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0);
|
||||
reference > 0 && Path::new(path).is_absolute() && !Path::new(path).exists()
|
||||
}
|
||||
|
||||
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
|
||||
pub(crate) fn frame_from(f: &Value) -> StackFrame {
|
||||
let source = f.get("source");
|
||||
@@ -594,10 +635,19 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame {
|
||||
StackFrame {
|
||||
id: f.get("id").and_then(Value::as_i64).unwrap_or_default(),
|
||||
name: f.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(),
|
||||
path: source.and_then(|s| s.get("path")).and_then(Value::as_str).map(Into::into),
|
||||
path: source
|
||||
.and_then(|s| s.get("path"))
|
||||
.and_then(Value::as_str)
|
||||
.filter(|p| !is_pseudo_path(source, p))
|
||||
.map(Into::into),
|
||||
line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
|
||||
column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1),
|
||||
presentation_hint: hint,
|
||||
instruction_pointer_reference: f
|
||||
.get("instructionPointerReference")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|r| !r.is_empty())
|
||||
.map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -674,6 +724,9 @@ pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities {
|
||||
js_page: false,
|
||||
live_evaluate: false,
|
||||
stream_trace: false,
|
||||
read_memory: has("supportsReadMemoryRequest"),
|
||||
disassemble: has("supportsDisassembleRequest"),
|
||||
instruction_stepping: has("supportsSteppingGranularity"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -762,9 +815,15 @@ pub(crate) fn variable_from(v: &Value) -> Variable {
|
||||
variables_reference: v.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
|
||||
evaluate_name: s("evaluateName"),
|
||||
lazy: v.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
|
||||
memory_reference: memory_reference(v),
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable's or evaluation result's `memoryReference`.
|
||||
fn memory_reference(v: &Value) -> Option<String> {
|
||||
v.get("memoryReference").and_then(Value::as_str).filter(|r| !r.is_empty()).map(str::to_owned)
|
||||
}
|
||||
|
||||
async fn session_variables(session: &Session, reference: i64) -> IdeResult<Vec<Variable>> {
|
||||
let body =
|
||||
session.conn.request_timeout("variables", json!({ "variablesReference": reference }), REQUEST_TIMEOUT).await?;
|
||||
@@ -788,6 +847,7 @@ async fn resolve_in(session: &Session, variable: Variable) -> IdeResult<Variable
|
||||
value: value.value,
|
||||
variables_reference: value.variables_reference,
|
||||
lazy: value.lazy,
|
||||
memory_reference: value.memory_reference.or(variable.memory_reference),
|
||||
},
|
||||
_ => variable,
|
||||
})
|
||||
@@ -818,8 +878,6 @@ impl DebugManager {
|
||||
states: Mutex::default(),
|
||||
exception_choices: Mutex::default(),
|
||||
exception_classes: Mutex::default(),
|
||||
function_breakpoints: Mutex::default(),
|
||||
data_breakpoints: Mutex::default(),
|
||||
stopping: Mutex::default(),
|
||||
jvm_finder: Mutex::new(Arc::new(jvm_memory::find_local_jvm)),
|
||||
})
|
||||
@@ -839,8 +897,24 @@ impl DebugManager {
|
||||
self.order.lock().iter().filter_map(|id| sessions.get(id).cloned()).collect()
|
||||
}
|
||||
|
||||
pub(crate) fn stored_breakpoints(&self, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(path).cloned().unwrap_or_default()
|
||||
pub(crate) fn stored_breakpoints(&self, owner: &str, path: &Path) -> Vec<Breakpoint> {
|
||||
self.breakpoints.lock().get(owner).and_then(|b| b.lines.get(path).cloned()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn function_breakpoints(&self, owner: &str) -> Vec<FunctionBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.functions.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn data_breakpoints(&self, owner: &str) -> Vec<DataBreakpoint> {
|
||||
self.breakpoints.lock().get(owner).map(|b| b.data.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// `owner`'s sessions that take breakpoint requests.
|
||||
fn configured_sessions(&self, owner: &str) -> Vec<Arc<Session>> {
|
||||
self.live_sessions()
|
||||
.into_iter()
|
||||
.filter(|s| s.owner.key == owner && s.configured.load(Ordering::Acquire) && !s.conn.is_closed())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Live sessions of `owner` (all owners when `None`).
|
||||
@@ -852,6 +926,30 @@ impl DebugManager {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `s` is live and currently suspended (a breakpoint, step or manual pause).
|
||||
/// `None` when the session has ended.
|
||||
pub fn session_suspended(&self, s: DebugSessionId) -> Option<bool> {
|
||||
self.sessions.lock().get(&s).map(|session| session.suspended.get())
|
||||
}
|
||||
|
||||
/// The thread of `s`'s most recent stop, when the adapter named one.
|
||||
pub fn stopped_thread(&self, s: DebugSessionId) -> Option<i64> {
|
||||
self.sessions.lock().get(&s).and_then(|session| session.suspended.stopped_thread())
|
||||
}
|
||||
|
||||
/// All stored breakpoints of `owner`, for tools that list or edit them. Line breakpoints
|
||||
/// are keyed by file; function and data breakpoints have no file.
|
||||
pub fn breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
) -> (BTreeMap<PathBuf, Vec<Breakpoint>>, Vec<FunctionBreakpoint>, Vec<DataBreakpoint>) {
|
||||
let store = self.breakpoints.lock();
|
||||
match store.get(owner) {
|
||||
Some(owner) => (owner.lines.clone(), owner.functions.clone(), owner.data.clone()),
|
||||
None => Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a session: spawns the adapter, `initialize`, `launch`/`attach`,
|
||||
/// waits for `initialized`, sends breakpoints, then `configurationDone`.
|
||||
/// Events of the session (including cargo build output) go to `owner` only.
|
||||
@@ -879,7 +977,27 @@ impl DebugManager {
|
||||
custom_command: impl FnOnce(&str) -> Option<String>,
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
self.start_with_cancel(config, owner, custom_command, exception_classes, ide_core::CancellationToken::new())
|
||||
.await
|
||||
}
|
||||
|
||||
/// [`start_with_exception_classes`](Self::start_with_exception_classes), cancelling a pending
|
||||
/// pre-launch build, adapter launch or configuration when `cancel` is triggered.
|
||||
pub async fn start_with_cancel(
|
||||
&self,
|
||||
config: LaunchConfig,
|
||||
owner: SessionOwner,
|
||||
custom_command: impl FnOnce(&str) -> Option<String>,
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
cancel: ide_core::CancellationToken,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut arguments = launch_arguments(&config)?;
|
||||
if debugpy::listens(&config.adapter, &config.request, &arguments) {
|
||||
debugpy::require_free_port(&arguments).await?;
|
||||
}
|
||||
// An IDE-side marker (never sent to the adapter): the session is a Flutter
|
||||
// one regardless of what the working directory holds.
|
||||
let force_flutter =
|
||||
@@ -967,7 +1085,7 @@ impl DebugManager {
|
||||
.unwrap_or_else(|| vec!["build".into()]);
|
||||
let filter = cargo::CargoFilter::from_json(cargo.get("filter"));
|
||||
let sink = owner.sink.clone();
|
||||
let program = cargo::build(&cwd, &cargo_args, &filter, move |line| {
|
||||
let program = cargo::build(&cwd, &cargo_args, &filter, &cancel, move |line| {
|
||||
sink.emit(ide_core::IdeEvent::Debug {
|
||||
session: id,
|
||||
event: ide_core::event::DebugEvent::Output { category: "console".into(), output: line },
|
||||
@@ -976,6 +1094,9 @@ impl DebugManager {
|
||||
.await?;
|
||||
arguments["program"] = json!(program);
|
||||
}
|
||||
if let Some(spm) = arguments.as_object_mut().and_then(|o| o.remove("swiftpm")) {
|
||||
arguments["program"] = json!(swiftpm::program(&cwd, &spm, &cancel).await?);
|
||||
}
|
||||
// Attach to a Node process started without `--inspect`: open its inspector first.
|
||||
if config.adapter == "js-debug" && config.request == "attach" && arguments.get("port").is_none() {
|
||||
let pid = arguments.get("processId").and_then(|p| match p {
|
||||
@@ -983,7 +1104,11 @@ impl DebugManager {
|
||||
other => other.as_u64().and_then(|p| u32::try_from(p).ok()),
|
||||
});
|
||||
if let Some(pid) = pid {
|
||||
let port = attach::enable_node_inspector(pid).await?;
|
||||
let port = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
port = attach::enable_node_inspector(pid) => port?,
|
||||
};
|
||||
if let Some(obj) = arguments.as_object_mut() {
|
||||
obj.remove("processId");
|
||||
obj.insert("port".into(), port.into());
|
||||
@@ -1031,6 +1156,52 @@ impl DebugManager {
|
||||
spec,
|
||||
port,
|
||||
exception_classes,
|
||||
cancel,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Starts an `attach` session named `name` over `io`: a debugger reached without an
|
||||
/// adapter process, such as a notebook kernel's over its control channel
|
||||
/// ([`NOTEBOOK_ADAPTER`]). `arguments` is the `attach` request's. `notebook_cells`, the
|
||||
/// prefix of a notebook's cell URIs, gives the session that notebook's cell breakpoints.
|
||||
pub async fn start_over(
|
||||
&self,
|
||||
io: AdapterIo,
|
||||
name: String,
|
||||
adapter: String,
|
||||
arguments: Value,
|
||||
owner: SessionOwner,
|
||||
notebook_cells: Option<String>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
let spec = AdapterSpec {
|
||||
adapter: adapter.clone(),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
transport: adapter::Transport::Stdio,
|
||||
install_hint: None,
|
||||
cwd: PathBuf::new(),
|
||||
env: Vec::new(),
|
||||
server_host: None,
|
||||
connect: None,
|
||||
pinned: None,
|
||||
resolve_lazy_variables: false,
|
||||
};
|
||||
let cancel = ide_core::CancellationToken::new();
|
||||
self.start_session(
|
||||
DebugSessionId::next(),
|
||||
owner,
|
||||
name,
|
||||
adapter,
|
||||
None,
|
||||
"attach".into(),
|
||||
arguments,
|
||||
spec,
|
||||
None,
|
||||
None,
|
||||
cancel,
|
||||
Some((io, notebook_cells)),
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -1065,6 +1236,8 @@ impl DebugManager {
|
||||
spec,
|
||||
port,
|
||||
None,
|
||||
ide_core::CancellationToken::new(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
@@ -1083,11 +1256,26 @@ impl DebugManager {
|
||||
spec: AdapterSpec,
|
||||
reuse_port: Option<u16>,
|
||||
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
|
||||
cancel: ide_core::CancellationToken,
|
||||
connected: Option<(AdapterIo, Option<String>)>,
|
||||
) -> IdeResult<DebugSessionId> {
|
||||
if request != "launch" && request != "attach" {
|
||||
return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`")));
|
||||
}
|
||||
let io = self.launcher.launch(spec.clone(), reuse_port).await?;
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let (io, notebook_cells) = match connected {
|
||||
Some((io, cells)) => (io, cells),
|
||||
None => (
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
io = self.launcher.launch(spec.clone(), reuse_port) => io?,
|
||||
},
|
||||
None,
|
||||
),
|
||||
};
|
||||
let launch_after_configuration = io.launch_after_configuration && request == "launch";
|
||||
let stderr = io.stderr.clone();
|
||||
let (conn, incoming) = {
|
||||
@@ -1099,6 +1287,7 @@ impl DebugManager {
|
||||
.flatten();
|
||||
let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child);
|
||||
session.exception_classes = exception_classes;
|
||||
session.notebook_cells = notebook_cells;
|
||||
session.run = take_run_link(&mut arguments);
|
||||
let session = Arc::new(session);
|
||||
if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) {
|
||||
@@ -1108,6 +1297,21 @@ impl DebugManager {
|
||||
if let Some(pid) = rdbg_pid {
|
||||
session.debuggee_pid.store(i64::from(pid), Ordering::Release);
|
||||
}
|
||||
let cancelled = {
|
||||
let mut sessions = self.sessions.lock();
|
||||
if cancel.is_cancelled() {
|
||||
true
|
||||
} else {
|
||||
sessions.insert(id, session.clone());
|
||||
self.order.lock().push(id);
|
||||
false
|
||||
}
|
||||
};
|
||||
if cancelled {
|
||||
session.conn.close();
|
||||
session.kill_processes();
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if let Some(mut output) = io.program_output {
|
||||
session.output_drained.send_replace(false);
|
||||
let session = session.clone();
|
||||
@@ -1118,8 +1322,6 @@ impl DebugManager {
|
||||
session.output_drained.send_replace(true);
|
||||
});
|
||||
}
|
||||
self.sessions.lock().insert(id, session.clone());
|
||||
self.order.lock().push(id);
|
||||
// Announced before the event loop runs, so it precedes every adapter event.
|
||||
session.emit(ide_core::event::DebugEvent::Started {
|
||||
name: session.name.clone(),
|
||||
@@ -1128,14 +1330,28 @@ impl DebugManager {
|
||||
});
|
||||
tokio::spawn(session::event_loop(self.me.clone(), session.clone(), incoming));
|
||||
|
||||
if debugpy::listens(&session.adapter, &session.request, &arguments) {
|
||||
session.debugpy_version_unchecked.store(true, Ordering::Release);
|
||||
}
|
||||
enum ConfigOutcome {
|
||||
Done(IdeResult<()>),
|
||||
Stopped,
|
||||
Cancelled,
|
||||
}
|
||||
let configured = tokio::select! {
|
||||
biased;
|
||||
_ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
result = self.configure(&session, arguments, launch_after_configuration) => result,
|
||||
_ = session.startup_cancel.cancelled() => ConfigOutcome::Stopped,
|
||||
_ = cancel.cancelled() => ConfigOutcome::Cancelled,
|
||||
result = self.configure(&session, arguments, launch_after_configuration) => ConfigOutcome::Done(result),
|
||||
};
|
||||
match configured {
|
||||
Ok(()) => Ok(id),
|
||||
Err(e) => {
|
||||
ConfigOutcome::Done(Ok(())) => Ok(id),
|
||||
ConfigOutcome::Stopped => Err(IdeError::cancelled()),
|
||||
ConfigOutcome::Cancelled => {
|
||||
let _ = self.stop(id).await;
|
||||
Err(IdeError::cancelled())
|
||||
}
|
||||
ConfigOutcome::Done(Err(e)) => {
|
||||
let e = if session.conn.is_closed() {
|
||||
let mut msg = format!("debug adapter `{}` exited during startup", session.adapter);
|
||||
let tail = stderr.lock().join("\n");
|
||||
@@ -1191,7 +1407,7 @@ impl DebugManager {
|
||||
"supportsProgressReporting": true,
|
||||
// kotlin-lsp sends `invalidated` either way.
|
||||
"supportsInvalidatedEvent": is_kotlin_lsp,
|
||||
"supportsMemoryReferences": false,
|
||||
"supportsMemoryReferences": true,
|
||||
"supportsArgsCanBeInterpretedByShell": false,
|
||||
}),
|
||||
INIT_TIMEOUT,
|
||||
@@ -1199,6 +1415,9 @@ impl DebugManager {
|
||||
.await?;
|
||||
*s.caps.lock() = if caps.is_object() { caps } else { json!({}) };
|
||||
|
||||
if s.adapter == adapter::JAVA_ANALYZER && s.request == "launch" {
|
||||
session::shorten_java_analyzer_classpath(s, &mut arguments)?;
|
||||
}
|
||||
// The Kotlin adapters ignore the resolved classpath and project runtime on launch.
|
||||
let request = if kotlin::is_kotlin(&s.adapter) && s.request == "launch" {
|
||||
session::start_kotlin_debuggee(s, &mut arguments).await?;
|
||||
@@ -1291,8 +1510,11 @@ impl DebugManager {
|
||||
let (files, idle): (Vec<_>, Vec<_>) = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.map(|(p, b)| (p.clone(), b.clone()))
|
||||
.get(&s.owner.key)
|
||||
.map(|b| b.lines.iter().map(|(p, b)| (p.clone(), b.clone())).collect::<Vec<_>>())
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|(path, _)| s.takes(path))
|
||||
.partition(|(_, b)| b.iter().any(|b| b.enabled));
|
||||
let sent = join_all(files.iter().map(|(path, bps)| s.send_breakpoints(path, bps, None))).await;
|
||||
// Breakpoint states follow the owner's first session.
|
||||
@@ -1310,14 +1532,14 @@ impl DebugManager {
|
||||
Err(e) => tracing::debug!("setBreakpoints for {} failed: {e}", path.display()),
|
||||
}
|
||||
}
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&s.owner.key);
|
||||
if !functions.is_empty()
|
||||
&& s.supports("supportsFunctionBreakpoints")
|
||||
&& let Err(e) = s.send_function_breakpoints(&functions).await
|
||||
{
|
||||
tracing::debug!("setFunctionBreakpoints failed: {e}");
|
||||
}
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&s.owner.key);
|
||||
if !data.is_empty()
|
||||
&& s.supports("supportsDataBreakpoints")
|
||||
&& let Err(e) = s.send_data_breakpoints(&data).await
|
||||
@@ -1470,26 +1692,59 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Breakpoints are kept per file even without a session and sent on start.
|
||||
/// Returns states from the first live session, or unverified states when none.
|
||||
/// `owner`'s breakpoints are kept per file even without a session and sent when one of
|
||||
/// its sessions starts. Returns states from its first live session, or unverified states.
|
||||
pub async fn set_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
{
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
if breakpoints.is_empty() {
|
||||
store.remove(&path);
|
||||
lines.remove(&path);
|
||||
} else {
|
||||
store.insert(path.clone(), breakpoints.clone());
|
||||
lines.insert(path.clone(), breakpoints.clone());
|
||||
}
|
||||
}
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await
|
||||
}
|
||||
|
||||
/// Replaces all of `owner`'s line breakpoints with `files` (the window's whole list), sending
|
||||
/// the files that changed to its sessions. A file the window no longer lists can't stay
|
||||
/// behind and be sent to every later session, whatever made the two lists diverge (#6116).
|
||||
pub async fn replace_breakpoints(&self, owner: &str, files: BTreeMap<PathBuf, Vec<Breakpoint>>) -> IdeResult<()> {
|
||||
let changed: Vec<(PathBuf, Vec<Breakpoint>)> = {
|
||||
let mut store = self.breakpoints.lock();
|
||||
let lines = &mut store.entry(owner.to_owned()).or_default().lines;
|
||||
let files: BTreeMap<_, _> = files.into_iter().filter(|(_, b)| !b.is_empty()).collect();
|
||||
let removed = lines.keys().filter(|p| !files.contains_key(*p)).map(|p| (p.clone(), Vec::new()));
|
||||
let changed = files.iter().filter(|(p, b)| lines.get(*p) != Some(b)).map(|(p, b)| (p.clone(), b.clone()));
|
||||
let changed = removed.chain(changed).collect();
|
||||
*lines = files;
|
||||
changed
|
||||
};
|
||||
for (path, breakpoints) in changed {
|
||||
self.send_file_breakpoints(owner, path, breakpoints).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops `owner`'s breakpoints (its window closed).
|
||||
pub fn forget_breakpoints(&self, owner: &str) {
|
||||
self.breakpoints.lock().remove(owner);
|
||||
}
|
||||
|
||||
async fn send_file_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
path: PathBuf,
|
||||
breakpoints: Vec<Breakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
let mut result: Option<Vec<BreakpointState>> = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() {
|
||||
continue;
|
||||
}
|
||||
for s in self.configured_sessions(owner).into_iter().filter(|s| s.takes(&path)) {
|
||||
match s.send_breakpoints(&path, &breakpoints, None).await {
|
||||
Ok(states) => {
|
||||
result.get_or_insert(states);
|
||||
@@ -1613,6 +1868,7 @@ impl DebugManager {
|
||||
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
|
||||
evaluate_name: evaluate_name.or(Some(name)),
|
||||
lazy: false,
|
||||
memory_reference: memory_reference(&body),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1640,16 +1896,39 @@ impl DebugManager {
|
||||
}
|
||||
|
||||
pub async fn stack_trace(&self, s: DebugSessionId, thread_id: i64) -> IdeResult<Vec<StackFrame>> {
|
||||
const MAX_FRAMES: u64 = 400;
|
||||
let session = self.session(s)?;
|
||||
session.check_thread(thread_id)?;
|
||||
let body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
let request = |start: u64, levels: u64| {
|
||||
session.conn.request_timeout(
|
||||
"stackTrace",
|
||||
json!({ "threadId": thread_id, "startFrame": 0, "levels": 400 }),
|
||||
json!({ "threadId": thread_id, "startFrame": start, "levels": levels }),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
};
|
||||
let frames_of = |mut body: Value| match body.get_mut("stackFrames").map(Value::take) {
|
||||
Some(Value::Array(frames)) => frames,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let raw = match request(0, MAX_FRAMES).await {
|
||||
Ok(body) => frames_of(body),
|
||||
// java-debug fails the whole request when one frame's source lookup throws (on Windows,
|
||||
// a CGLIB proxy's `<generated>` source against `sourcePaths`): the frames come one at a
|
||||
// time instead, without the ones it cannot describe.
|
||||
// ponytail: one request per frame; page around the failing ones if deep stacks get slow.
|
||||
Err(first @ DapError::Failed { .. }) => {
|
||||
let Ok(top) = request(0, 1).await else { return Err(first.into()) };
|
||||
let total = top.get("totalFrames").and_then(Value::as_u64).unwrap_or(MAX_FRAMES).min(MAX_FRAMES);
|
||||
let mut raw = frames_of(top);
|
||||
for start in 1..total {
|
||||
if let Ok(body) = request(start, 1).await {
|
||||
raw.extend(frames_of(body));
|
||||
}
|
||||
}
|
||||
raw
|
||||
}
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let kotlin_lsp = session.kotlin_lsp_quirks().is_some();
|
||||
let frame = |f: &Value| {
|
||||
let mut frame = frame_from(f);
|
||||
@@ -1661,7 +1940,7 @@ impl DebugManager {
|
||||
}
|
||||
frame
|
||||
};
|
||||
Ok(body.get("stackFrames").and_then(Value::as_array).map(|f| f.iter().map(frame).collect()).unwrap_or_default())
|
||||
Ok(raw.iter().map(frame).collect())
|
||||
}
|
||||
|
||||
pub async fn scopes(&self, s: DebugSessionId, frame_id: i64) -> IdeResult<Vec<Scope>> {
|
||||
@@ -1727,6 +2006,7 @@ impl DebugManager {
|
||||
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
|
||||
evaluate_name: Some(expression),
|
||||
lazy: body.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
|
||||
memory_reference: memory_reference(&body),
|
||||
};
|
||||
if !session.spec.resolve_lazy_variables {
|
||||
return Ok(result);
|
||||
@@ -1818,6 +2098,22 @@ impl DebugManager {
|
||||
}
|
||||
|
||||
pub async fn step(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> {
|
||||
self.step_with(s, thread_id, kind, json!({ "threadId": thread_id })).await
|
||||
}
|
||||
|
||||
/// Step Over / Into Instruction: a step by one machine instruction (DAP `granularity`).
|
||||
pub async fn step_instruction(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> {
|
||||
let session = self.session(s)?;
|
||||
if !session.supports("supportsSteppingGranularity") {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"debug adapter `{}` cannot step by instruction",
|
||||
session.adapter
|
||||
)));
|
||||
}
|
||||
self.step_with(s, thread_id, kind, json!({ "threadId": thread_id, "granularity": "instruction" })).await
|
||||
}
|
||||
|
||||
async fn step_with(&self, s: DebugSessionId, thread_id: i64, kind: StepKind, args: Value) -> IdeResult<()> {
|
||||
let command = match kind {
|
||||
StepKind::Over => "next",
|
||||
StepKind::Into => "stepIn",
|
||||
@@ -1829,7 +2125,7 @@ impl DebugManager {
|
||||
quirks.step_sent();
|
||||
}
|
||||
let ticket = session.suspended.ticket();
|
||||
let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await;
|
||||
let sent = session.conn.request_timeout(command, args, REQUEST_TIMEOUT).await;
|
||||
step_settled(&session, sent)?;
|
||||
// A step runs its thread; other threads stopped by their own events stay stopped.
|
||||
session.finish_resume(ticket, thread_id, false);
|
||||
@@ -1853,7 +2149,7 @@ impl DebugManager {
|
||||
if force {
|
||||
self.suspend_breakpoints(&session, Some(&path)).await?;
|
||||
}
|
||||
let stored = self.stored_breakpoints(&path);
|
||||
let stored = self.stored_breakpoints(&session.owner.key, &path);
|
||||
let sent: Vec<Breakpoint> =
|
||||
if force { stored.iter().map(|b| Breakpoint { enabled: false, ..b.clone() }).collect() } else { stored };
|
||||
session.send_breakpoints(&path, &sent, Some(line)).await?;
|
||||
@@ -1868,10 +2164,15 @@ impl DebugManager {
|
||||
let files: Vec<PathBuf> = self
|
||||
.breakpoints
|
||||
.lock()
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
.get(&session.owner.key)
|
||||
.map(|b| {
|
||||
b.lines
|
||||
.iter()
|
||||
.filter(|(path, bps)| Some(path.as_path()) != except && bps.iter().any(|b| b.enabled))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let sent = join_all(files.iter().map(|path| session.send_breakpoints(path, &[], None))).await;
|
||||
let mut failed = None;
|
||||
for (path, result) in files.into_iter().zip(sent) {
|
||||
@@ -1885,11 +2186,12 @@ impl DebugManager {
|
||||
if let Some(e) = failed {
|
||||
return Err(e.into());
|
||||
}
|
||||
if !self.function_breakpoints.lock().is_empty() && session.supports("supportsFunctionBreakpoints") {
|
||||
if !self.function_breakpoints(&session.owner.key).is_empty() && session.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
session.send_function_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().functions = true;
|
||||
}
|
||||
if !self.data_breakpoints.lock().is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
if !self.data_breakpoints(&session.owner.key).is_empty() && session.supports("supportsDataBreakpoints") {
|
||||
session.send_data_breakpoints(&[]).await?;
|
||||
session.pending_restore.lock().data = true;
|
||||
}
|
||||
@@ -1899,8 +2201,11 @@ impl DebugManager {
|
||||
/// Re-sends what [`suspend_breakpoints`](Self::suspend_breakpoints) / run to cursor replaced.
|
||||
pub(crate) async fn restore_breakpoints(&self, session: &Arc<Session>) {
|
||||
let pending = std::mem::take(&mut *session.pending_restore.lock());
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> =
|
||||
pending.files.into_iter().map(|path| (path.clone(), self.stored_breakpoints(&path))).collect();
|
||||
let files: Vec<(PathBuf, Vec<Breakpoint>)> = pending
|
||||
.files
|
||||
.into_iter()
|
||||
.map(|path| (path.clone(), self.stored_breakpoints(&session.owner.key, &path)))
|
||||
.collect();
|
||||
let sent = join_all(files.iter().map(|(path, bps)| session.send_breakpoints(path, bps, None))).await;
|
||||
for ((path, _), result) in files.iter().zip(sent) {
|
||||
if let Err(e) = result {
|
||||
@@ -1908,13 +2213,13 @@ impl DebugManager {
|
||||
}
|
||||
}
|
||||
if pending.functions {
|
||||
let functions = self.function_breakpoints.lock().clone();
|
||||
let functions = self.function_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_function_breakpoints(&functions).await {
|
||||
tracing::debug!("restoring function breakpoints failed: {e}");
|
||||
}
|
||||
}
|
||||
if pending.data {
|
||||
let data = self.data_breakpoints.lock().clone();
|
||||
let data = self.data_breakpoints(&session.owner.key);
|
||||
if let Err(e) = session.send_data_breakpoints(&data).await {
|
||||
tracing::debug!("restoring data breakpoints failed: {e}");
|
||||
}
|
||||
@@ -1974,6 +2279,74 @@ impl DebugManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `count` bytes (at most [`MAX_READ`]) from `offset` bytes after `memory_reference`, which
|
||||
/// comes from a variable, an evaluation result or an earlier read's address.
|
||||
pub async fn read_memory(
|
||||
&self,
|
||||
s: DebugSessionId,
|
||||
memory_reference: String,
|
||||
offset: i64,
|
||||
count: u32,
|
||||
) -> IdeResult<MemoryBlock> {
|
||||
let session = self.session(s)?;
|
||||
if !session.supports("supportsReadMemoryRequest") {
|
||||
return Err(IdeError::unavailable(format!("debug adapter `{}` cannot read memory", session.adapter)));
|
||||
}
|
||||
let count = count.min(MAX_READ);
|
||||
let body = session
|
||||
.conn
|
||||
.request_timeout(
|
||||
"readMemory",
|
||||
json!({ "memoryReference": memory_reference, "offset": offset, "count": count }),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
memory::memory_block(&body, count)
|
||||
}
|
||||
|
||||
/// `count` instructions (at most [`MAX_INSTRUCTIONS`]) from `before` instructions ahead of
|
||||
/// `memory_reference` (a frame's instruction pointer or an instruction's address). Adapters that
|
||||
/// cannot disassemble backwards start at the reference instead.
|
||||
pub async fn disassemble(
|
||||
&self,
|
||||
s: DebugSessionId,
|
||||
memory_reference: String,
|
||||
before: u32,
|
||||
count: u32,
|
||||
) -> IdeResult<Vec<Instruction>> {
|
||||
let session = self.session(s)?;
|
||||
if !session.supports("supportsDisassembleRequest") {
|
||||
return Err(IdeError::unavailable(format!("debug adapter `{}` cannot disassemble", session.adapter)));
|
||||
}
|
||||
let count = count.clamp(1, MAX_INSTRUCTIONS);
|
||||
let before = before.min(count - 1);
|
||||
let request = |offset: i64, count: u32| {
|
||||
session.conn.request_timeout(
|
||||
"disassemble",
|
||||
json!({
|
||||
"memoryReference": memory_reference,
|
||||
"offset": 0,
|
||||
"instructionOffset": offset,
|
||||
"instructionCount": count,
|
||||
"resolveSymbols": true,
|
||||
}),
|
||||
REQUEST_TIMEOUT,
|
||||
)
|
||||
};
|
||||
if before > 0 {
|
||||
// GDB (up to 17 at least) answers a negative instruction offset with the instructions after
|
||||
// the reference, or fails: only an answer with the reference in its place is used.
|
||||
if let Ok(body) = request(-i64::from(before), count).await {
|
||||
let instructions = disassembly::instructions(&body);
|
||||
if disassembly::at_index(&instructions, &memory_reference, before as usize) {
|
||||
return Ok(instructions.into_iter().flatten().collect());
|
||||
}
|
||||
}
|
||||
}
|
||||
let body = request(0, count - before).await?;
|
||||
Ok(disassembly::instructions(&body).into_iter().flatten().collect())
|
||||
}
|
||||
|
||||
pub fn capabilities(&self, s: DebugSessionId) -> IdeResult<DebugCapabilities> {
|
||||
Ok(session_capabilities(&*self.session(s)?))
|
||||
}
|
||||
@@ -2124,14 +2497,17 @@ impl DebugManager {
|
||||
Ok(hot_swap_result(&body))
|
||||
}
|
||||
|
||||
/// Stores method breakpoints (kept without a session, sent on start) and sends them to
|
||||
/// every configured session whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(&self, list: Vec<FunctionBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.function_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s method breakpoints (kept without a session, sent on start) and sends them
|
||||
/// to each of its configured sessions whose adapter supports them. States from the first one.
|
||||
pub async fn set_function_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<FunctionBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().functions = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsFunctionBreakpoints")
|
||||
{
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsFunctionBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_function_breakpoints(&list).await {
|
||||
@@ -2144,12 +2520,17 @@ impl DebugManager {
|
||||
Ok(result.unwrap_or_else(|| unverified(list.iter().map(|b| b.enabled))))
|
||||
}
|
||||
|
||||
/// Stores field watchpoints and sends them to every configured session that supports them.
|
||||
pub async fn set_data_breakpoints(&self, list: Vec<DataBreakpoint>) -> IdeResult<Vec<BreakpointState>> {
|
||||
*self.data_breakpoints.lock() = list.clone();
|
||||
/// Stores `owner`'s field watchpoints and sends them to each of its configured sessions that
|
||||
/// supports them.
|
||||
pub async fn set_data_breakpoints(
|
||||
&self,
|
||||
owner: &str,
|
||||
list: Vec<DataBreakpoint>,
|
||||
) -> IdeResult<Vec<BreakpointState>> {
|
||||
self.breakpoints.lock().entry(owner.to_owned()).or_default().data = list.clone();
|
||||
let mut result = None;
|
||||
for s in self.live_sessions() {
|
||||
if !s.configured.load(Ordering::Acquire) || s.conn.is_closed() || !s.supports("supportsDataBreakpoints") {
|
||||
for s in self.configured_sessions(owner) {
|
||||
if !s.supports("supportsDataBreakpoints") {
|
||||
continue;
|
||||
}
|
||||
match s.send_data_breakpoints(&list).await {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Raw memory of a native program (DAP `readMemory`), for the Memory View.
|
||||
|
||||
use base64::Engine;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use specta::Type;
|
||||
|
||||
/// The most bytes one read asks for: a few pages of the view, never a whole mapping.
|
||||
pub const MAX_READ: u32 = 64 * 1024;
|
||||
|
||||
/// Answer of `readMemory`: `data` starts at `address`; the `unreadable_bytes` after it could not be read.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MemoryBlock {
|
||||
/// Address of the first byte, as the adapter writes it (`0x7ffd…`; may be wider than 53 bits).
|
||||
pub address: String,
|
||||
pub data: Vec<u8>,
|
||||
pub unreadable_bytes: u32,
|
||||
}
|
||||
|
||||
/// `readMemory`'s body for a read of `count` bytes. Adapters leave `data` out (or empty) when
|
||||
/// nothing could be read; the bytes asked for then count as unreadable.
|
||||
pub(crate) fn memory_block(body: &Value, count: u32) -> IdeResult<MemoryBlock> {
|
||||
let address = match body.get("address") {
|
||||
Some(Value::String(a)) if !a.is_empty() => a.clone(),
|
||||
Some(Value::Number(n)) => n.to_string(),
|
||||
_ => return Err(IdeError::internal("the debug adapter answered readMemory without an address")),
|
||||
};
|
||||
let mut data = match body.get("data").and_then(Value::as_str) {
|
||||
Some(b64) if !b64.is_empty() => base64::engine::general_purpose::STANDARD
|
||||
.decode(b64)
|
||||
.map_err(|e| IdeError::internal(format!("the debug adapter sent memory that is not base64: {e}")))?,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
data.truncate(count as usize);
|
||||
// At most the rest of what was asked for (the data is never more than that).
|
||||
let rest = count - data.len() as u32;
|
||||
let unreadable_bytes = match body.get("unreadableBytes").and_then(Value::as_u64) {
|
||||
Some(n) => n.min(u64::from(rest)) as u32,
|
||||
None if data.is_empty() => count,
|
||||
None => 0,
|
||||
};
|
||||
Ok(MemoryBlock { address, data, unreadable_bytes })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn decodes_the_bytes_and_keeps_the_address_as_written() {
|
||||
// The reporter's `&msg[0]` (#5921): "Hello, World!\n" and its terminator.
|
||||
let body = json!({"address": "0x000000016FDFE9A0", "data": "SGVsbG8sIFdvcmxkIQoA"});
|
||||
let block = memory_block(&body, 15).unwrap();
|
||||
assert_eq!(block.address, "0x000000016FDFE9A0");
|
||||
assert_eq!(block.data, b"Hello, World!\n\0");
|
||||
assert_eq!(block.unreadable_bytes, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_data_is_unreadable_not_empty() {
|
||||
let block = memory_block(&json!({"address": "0x0"}), 256).unwrap();
|
||||
assert!(block.data.is_empty());
|
||||
assert_eq!(block.unreadable_bytes, 256);
|
||||
let block = memory_block(&json!({"address": "0x0", "data": "", "unreadableBytes": 16}), 256).unwrap();
|
||||
assert_eq!(block.unreadable_bytes, 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_read_reports_the_rest_as_unreadable() {
|
||||
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 13}), 16).unwrap();
|
||||
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1, 2][..], 13));
|
||||
// Counts that disagree with the request are clamped to it.
|
||||
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 99}), 16).unwrap();
|
||||
assert_eq!(block.unreadable_bytes, 13);
|
||||
let block = memory_block(&json!({"address": "0x1000", "data": "AAECAw=="}), 2).unwrap();
|
||||
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1][..], 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_answers_without_an_address_or_with_bad_data() {
|
||||
assert!(memory_block(&json!({"data": "AA=="}), 1).is_err());
|
||||
assert!(memory_block(&json!({"address": "0x10", "data": "not base64!"}), 1).is_err());
|
||||
assert_eq!(memory_block(&json!({"address": 4096, "data": "AA=="}), 1).unwrap().address, "4096");
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,8 @@ pub(crate) struct Session {
|
||||
pub jdwp_port: std::sync::OnceLock<u16>,
|
||||
/// The attach goes through the listen-mode relay of [`crate::jdwp::listen_for_jvm`].
|
||||
pub listen_relay: AtomicBool,
|
||||
/// A Python Debug Server session whose program's debugpy version is checked on its first stop.
|
||||
pub(crate) debugpy_version_unchecked: AtomicBool,
|
||||
pub suspended: Suspension,
|
||||
/// Pids signalled for the current stop: the reported pid and everything it started (an
|
||||
/// adapter may report the launcher shell, whose child is the program).
|
||||
@@ -123,6 +125,8 @@ pub(crate) struct Session {
|
||||
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>>,
|
||||
/// A notebook kernel's session: the prefix of its notebook's cell URIs (`…/a.ipynb#`).
|
||||
pub(crate) notebook_cells: Option<String>,
|
||||
/// 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<()>,
|
||||
@@ -132,6 +136,16 @@ pub(crate) struct Session {
|
||||
/// Used only by a kotlin-lsp session: see [`Session::kotlin_lsp_quirks`].
|
||||
pub(crate) quirks: kotlin_lsp::Quirks,
|
||||
pub(crate) unity_startup_activity: Mutex<Instant>,
|
||||
/// Temporary pathing jars / argfiles created for this session; removed on stop/drop.
|
||||
temp_files: Mutex<Vec<TempFile>>,
|
||||
}
|
||||
|
||||
struct TempFile(PathBuf);
|
||||
|
||||
impl Drop for TempFile {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Which threads of the program are suspended: each from its `stopped` event until a
|
||||
@@ -203,6 +217,14 @@ impl Suspension {
|
||||
stops.all.is_some() || !stops.threads.is_empty()
|
||||
}
|
||||
|
||||
/// The most recently stopped individual thread, when the stop named one. A stop of every
|
||||
/// thread (`allThreadsStopped`) names none, so callers fall back to the adapter's first thread.
|
||||
pub fn stopped_thread(&self) -> Option<i64> {
|
||||
let stops = self.0.lock();
|
||||
let latest = stops.latest()?;
|
||||
stops.threads.iter().find(|&&(_, ticket)| ticket == latest).map(|&(id, _)| id)
|
||||
}
|
||||
|
||||
/// A `stopped` event; `all`: its `allThreadsStopped`.
|
||||
pub fn stopped(&self, thread: Option<i64>, all: bool) {
|
||||
let mut stops = self.0.lock();
|
||||
@@ -316,6 +338,7 @@ impl Session {
|
||||
jvm_pid: AtomicI64::new(0),
|
||||
jdwp_port: std::sync::OnceLock::new(),
|
||||
listen_relay: AtomicBool::new(false),
|
||||
debugpy_version_unchecked: AtomicBool::new(false),
|
||||
suspended: Suspension::default(),
|
||||
stop_pids: parking_lot::Mutex::new(Vec::new()),
|
||||
#[cfg(windows)]
|
||||
@@ -339,11 +362,13 @@ impl Session {
|
||||
run: None,
|
||||
stream_tracer: parking_lot::Mutex::new(None),
|
||||
exception_classes: None,
|
||||
notebook_cells: 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(),
|
||||
unity_startup_activity: Mutex::new(Instant::now()),
|
||||
temp_files: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -422,6 +447,14 @@ impl Session {
|
||||
|
||||
/// Sends the breakpoints of one file (disabled ones omitted, plus an optional
|
||||
/// temporary line) and returns verification states aligned with `breakpoints`.
|
||||
/// Whether this session gets the breakpoints of `path`: a notebook cell's go only to the
|
||||
/// session of that notebook's kernel, which knows the cell's code.
|
||||
pub(crate) fn takes(&self, path: &Path) -> bool {
|
||||
let path = path.to_string_lossy();
|
||||
!path.starts_with(crate::NOTEBOOK_CELL_SCHEME)
|
||||
|| self.notebook_cells.as_deref().is_some_and(|cells| path.starts_with(cells))
|
||||
}
|
||||
|
||||
pub async fn send_breakpoints(
|
||||
&self,
|
||||
path: &Path,
|
||||
@@ -567,6 +600,7 @@ impl Session {
|
||||
if let Some(mut program) = self.program.lock().take() {
|
||||
program.kill();
|
||||
}
|
||||
self.temp_files.lock().clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -854,6 +888,11 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
|
||||
all_threads_stopped: all,
|
||||
});
|
||||
});
|
||||
if let Some(thread) = int("threadId")
|
||||
&& s.debugpy_version_unchecked.swap(false, Ordering::AcqRel)
|
||||
{
|
||||
tokio::spawn(crate::debugpy::check_version(s.clone(), thread));
|
||||
}
|
||||
}
|
||||
"continued" => {
|
||||
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
|
||||
@@ -1299,43 +1338,112 @@ fn kotlin_jvm_args(user: Vec<String>, windows: bool) -> Vec<String> {
|
||||
args
|
||||
}
|
||||
|
||||
fn json_string_list(args: &Value, key: &str) -> Vec<String> {
|
||||
args.get(key)
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn json_args_len(args: &Value, key: &str) -> usize {
|
||||
match args.get(key) {
|
||||
Some(Value::String(s)) => s.len() + 3,
|
||||
Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(|s| s.len() + 3).sum(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shortens `classPaths` for `java-analyzer dap` into a temporary manifest-only pathing jar when
|
||||
/// the command line would exceed the OS limit (e.g. Windows `CreateProcessW` `os error 206` on
|
||||
/// JDK 8 Spring Boot projects).
|
||||
pub(crate) fn shorten_java_analyzer_classpath(s: &Arc<Session>, args: &mut Value) -> ide_core::IdeResult<()> {
|
||||
let cwd = args.get("cwd").and_then(Value::as_str).map(PathBuf::from).unwrap_or_else(|| s.spec.cwd.clone());
|
||||
if let Some(jar) =
|
||||
shorten_java_analyzer_classpath_with(args, &cwd, cfg!(windows), &ide_run::java_cmdline::default_temp_dir())?
|
||||
{
|
||||
s.temp_files.lock().push(TempFile(jar));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn shorten_java_analyzer_classpath_with(
|
||||
args: &mut Value,
|
||||
cwd: &Path,
|
||||
windows: bool,
|
||||
temp_dir: &Path,
|
||||
) -> ide_core::IdeResult<Option<PathBuf>> {
|
||||
let java = args.get("javaExec").and_then(Value::as_str).unwrap_or("java");
|
||||
let class_paths = json_string_list(args, "classPaths");
|
||||
let module_paths = json_string_list(args, "modulePaths");
|
||||
let extra_len = json_args_len(args, "vmArgs")
|
||||
+ json_args_len(args, "args")
|
||||
+ args.get("mainClass").and_then(Value::as_str).map_or(0, |s| s.len() + 3);
|
||||
let Some(jar) = ide_run::java_cmdline::shorten_classpath_to_jar(
|
||||
Path::new(java),
|
||||
&class_paths,
|
||||
&module_paths,
|
||||
extra_len,
|
||||
cwd,
|
||||
windows,
|
||||
temp_dir,
|
||||
)?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
args["classPaths"] = json!([jar.to_string_lossy()]);
|
||||
Ok(Some(jar))
|
||||
}
|
||||
|
||||
/// Launch with the IDE's resolved runtime and classpath; the adapter only attaches.
|
||||
pub(crate) async fn start_kotlin_debuggee(s: &Arc<Session>, args: &mut Value) -> ide_core::IdeResult<()> {
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
let java = args.get("javaExec").and_then(Value::as_str).unwrap_or("java");
|
||||
let strings = |key: &str| -> Vec<String> {
|
||||
args.get(key)
|
||||
.and_then(Value::as_array)
|
||||
.map(|a| a.iter().filter_map(Value::as_str).map(str::to_owned).collect())
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let classpath =
|
||||
std::env::join_paths(strings("classPaths")).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?;
|
||||
let classpath = std::env::join_paths(json_string_list(args, "classPaths"))
|
||||
.map_err(|e| ide_core::IdeError::invalid(e.to_string()))?
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let mut java_args = kotlin_jvm_args(json_string_list(args, "vmArguments"), cfg!(windows));
|
||||
// Let the JVM pick its own port (`:0`) and report it below: pre-picking a free
|
||||
// port here races with other processes that may take it before the JVM binds.
|
||||
java_args.push("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0".to_owned());
|
||||
java_args.push("-cp".to_owned());
|
||||
java_args.push(classpath);
|
||||
let modules = json_string_list(args, "modulePaths");
|
||||
if !modules.is_empty() {
|
||||
java_args.push("--module-path".to_owned());
|
||||
java_args.push(
|
||||
std::env::join_paths(modules)
|
||||
.map_err(|e| ide_core::IdeError::invalid(e.to_string()))?
|
||||
.to_string_lossy()
|
||||
.into_owned(),
|
||||
);
|
||||
}
|
||||
java_args.push(
|
||||
args.get("mainClass")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| ide_core::IdeError::invalid("Missing Kotlin main class"))?
|
||||
.to_owned(),
|
||||
);
|
||||
java_args.extend(json_string_list(args, "programArgs"));
|
||||
if let Some(shortened) = ide_run::java_cmdline::shorten(
|
||||
Path::new(java),
|
||||
&java_args,
|
||||
&s.spec.cwd,
|
||||
cfg!(windows),
|
||||
&ide_run::java_cmdline::default_temp_dir(),
|
||||
)? {
|
||||
java_args = shortened.args;
|
||||
s.temp_files.lock().push(TempFile(shortened.file));
|
||||
}
|
||||
let mut cmd = tokio::process::Command::new(java);
|
||||
cmd.current_dir(&s.spec.cwd);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.args(kotlin_jvm_args(strings("vmArguments"), cfg!(windows)))
|
||||
// Let the JVM pick its own port (`:0`) and report it below: pre-picking a free
|
||||
// port here races with other processes that may take it before the JVM binds.
|
||||
.arg("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0")
|
||||
.arg("-cp")
|
||||
.arg(classpath);
|
||||
let modules = strings("modulePaths");
|
||||
if !modules.is_empty() {
|
||||
cmd.arg("--module-path")
|
||||
.arg(std::env::join_paths(modules).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?);
|
||||
}
|
||||
cmd.arg(
|
||||
args.get("mainClass")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| ide_core::IdeError::invalid("Missing Kotlin main class"))?,
|
||||
)
|
||||
.args(strings("programArgs"))
|
||||
.envs(ide_core::process::shell_env_in(&s.spec.cwd))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
cmd.args(&java_args)
|
||||
.envs(ide_core::process::shell_env_in(&s.spec.cwd))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
if let Some(env) = args.get("env").and_then(Value::as_object) {
|
||||
for (k, v) in env {
|
||||
if let Some(v) = v.as_str() {
|
||||
@@ -1654,4 +1762,41 @@ mod tests {
|
||||
// SAFETY: signal 0 only checks whether the process exists.
|
||||
assert_eq!(unsafe { libc::kill(pid, 0) }, -1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_analyzer_long_windows_classpath_is_shortened_to_pathing_jar() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let short_cp = vec![r"C:\app\target\classes".to_owned()];
|
||||
let mut short_args = serde_json::json!({
|
||||
"javaExec": r"E:\software\Java\jdk1.8.0_431\bin\java.exe",
|
||||
"mainClass": "com.example.App",
|
||||
"classPaths": short_cp,
|
||||
"vmArgs": ["-Dspring.output.ansi.enabled=always"],
|
||||
"args": [],
|
||||
});
|
||||
assert!(
|
||||
super::shorten_java_analyzer_classpath_with(&mut short_args, dir.path(), true, dir.path())
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(short_args["classPaths"].as_array().unwrap().len(), 1);
|
||||
|
||||
let many: Vec<String> = (0..500)
|
||||
.map(|i| format!(r"C:\Users\dev\.m2\repository\org\springframework\boot\dep-{i:04}\dep-{i:04}.jar"))
|
||||
.collect();
|
||||
let mut long_args = serde_json::json!({
|
||||
"javaExec": r"E:\software\Java\jdk1.8.0_431\bin\java.exe",
|
||||
"mainClass": "com.example.App",
|
||||
"classPaths": many,
|
||||
"vmArgs": ["-Dspring.output.ansi.enabled=always"],
|
||||
"args": [],
|
||||
});
|
||||
let jar = super::shorten_java_analyzer_classpath_with(&mut long_args, dir.path(), true, dir.path())
|
||||
.unwrap()
|
||||
.expect("long Windows classpath must be shortened into a pathing jar");
|
||||
assert!(jar.is_file());
|
||||
let replaced = long_args["classPaths"].as_array().unwrap();
|
||||
assert_eq!(replaced.len(), 1);
|
||||
assert_eq!(replaced[0].as_str().unwrap(), jar.to_string_lossy());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
//! SwiftPM launch integration: a launch request may carry
|
||||
//! `"swiftpm": {"product": "greet", "buildArgs": ["-c", "release"]}` instead of `program`.
|
||||
//! The run configuration's before launch task has built the product; this asks
|
||||
//! `swift build <buildArgs> --show-bin-path` where it went (`.build/<triple>/<configuration>`,
|
||||
//! or wherever `--scratch-path` / `--build-path` put it) and launches it from there.
|
||||
|
||||
use crate::adapter::find_binary;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::Value;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
|
||||
/// `swift build` arguments that print the bin path for `buildArgs` without building.
|
||||
pub fn bin_path_args(swiftpm: &Value) -> Vec<String> {
|
||||
let mut args = vec!["build".to_owned()];
|
||||
if let Some(a) = swiftpm.get("buildArgs").and_then(Value::as_array) {
|
||||
args.extend(a.iter().filter_map(|v| v.as_str().map(str::to_owned)));
|
||||
}
|
||||
args.push("--show-bin-path".into());
|
||||
args
|
||||
}
|
||||
|
||||
/// The built product of `swiftpm` (see the module docs).
|
||||
pub async fn program(cwd: &Path, swiftpm: &Value, cancel: &ide_core::CancellationToken) -> IdeResult<PathBuf> {
|
||||
let product = swiftpm
|
||||
.get("product")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|p| !p.is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("the SwiftPM launch names no product"))?;
|
||||
let swift = find_binary("swift", cwd).ok_or_else(|| IdeError::unavailable("`swift` not found on PATH"))?;
|
||||
let args = bin_path_args(swiftpm);
|
||||
let mut cmd = tokio::process::Command::new(swift);
|
||||
cmd.current_dir(cwd);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
cmd.args(&args).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
|
||||
let out = tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
out = cmd.output() => out.map_err(|e| IdeError::unavailable(format!("failed to run swift: {e}")))?,
|
||||
};
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
return Err(IdeError::invalid(format!("swift {} failed: {}", args.join(" "), err.trim())));
|
||||
}
|
||||
// The bin path is the last line: SwiftPM may print warnings about the manifest first.
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
let dir = stdout.lines().map(str::trim).rfind(|l| !l.is_empty()).unwrap_or_default();
|
||||
if dir.is_empty() {
|
||||
return Err(IdeError::invalid("swift build --show-bin-path printed no path"));
|
||||
}
|
||||
let exe = if cfg!(windows) { format!("{product}.exe") } else { product.to_owned() };
|
||||
Ok(cwd.join(dir).join(exe))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn asks_swift_build_for_the_bin_path_of_the_run_configurations_build() {
|
||||
assert_eq!(bin_path_args(&json!({"product": "greet"})), ["build", "--show-bin-path"]);
|
||||
assert_eq!(
|
||||
bin_path_args(&json!({"product": "greet", "buildArgs": ["-c", "release"]})),
|
||||
["build", "-c", "release", "--show-bin-path"]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ mod stream_trace;
|
||||
|
||||
use super::*;
|
||||
use crate::adapter::{AdapterIo, LaunchFuture};
|
||||
use base64::Engine;
|
||||
use ide_core::IdeEvent;
|
||||
use ide_core::event::DebugEvent;
|
||||
use ide_jsonrpc::framing;
|
||||
@@ -126,6 +127,8 @@ struct Script {
|
||||
child_request: Option<Value>,
|
||||
ignore_configuration_done: bool,
|
||||
source_path: Option<String>,
|
||||
/// Fail each `stackTrace` request whose frames include this one (java-debug, one frame's source lookup throwing).
|
||||
failing_frame: Option<u64>,
|
||||
/// Report this process id in the adapter's `process` event (the program being debugged).
|
||||
debuggee_pid: Option<u32>,
|
||||
/// java-debug's spelling of the same event.
|
||||
@@ -193,6 +196,21 @@ struct Script {
|
||||
accept: &'static [&'static str],
|
||||
/// Requests of the adapter's own answered with a body and followed by events.
|
||||
custom: Option<fn(&Value) -> Option<CustomReply>>,
|
||||
/// Advertise `supportsReadMemoryRequest`: memory below 0x1010 reads as its low address byte,
|
||||
/// memory from there on is unmapped.
|
||||
read_memory: bool,
|
||||
/// Advertise `supportsDisassembleRequest` and `supportsSteppingGranularity`, disassembling like
|
||||
/// this adapter: 4-byte instructions from 0x1000 to 0x1100, nothing mapped around them.
|
||||
disassemble: Option<FakeDisassembler>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum FakeDisassembler {
|
||||
/// Negative instruction offsets work; unmapped places are `invalid` padding.
|
||||
Lldb,
|
||||
/// GDB 17: disassembles `instructionOffset + instructionCount` instructions from the reference and
|
||||
/// drops the first `instructionOffset` of them, the way a Python slice does.
|
||||
Gdb,
|
||||
}
|
||||
|
||||
/// The answer to a request of the adapter's own: the response body, then events (name, body).
|
||||
@@ -206,6 +224,7 @@ impl Default for Script {
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
source_path: None,
|
||||
failing_frame: None,
|
||||
debuggee_pid: None,
|
||||
java_process_id: false,
|
||||
output_after_terminate: false,
|
||||
@@ -239,6 +258,8 @@ impl Default for Script {
|
||||
empty_thread_responses: 0,
|
||||
accept: &[],
|
||||
custom: None,
|
||||
read_memory: false,
|
||||
disassemble: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -325,6 +346,9 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
"supportsDataBreakpoints": true,
|
||||
"supportsStepInTargetsRequest": true,
|
||||
"supportsRestartFrame": true,
|
||||
"supportsReadMemoryRequest": script.read_memory,
|
||||
"supportsDisassembleRequest": script.disassemble.is_some(),
|
||||
"supportsSteppingGranularity": script.disassemble.is_some(),
|
||||
"exceptionBreakpointFilters": [
|
||||
{"filter": "raised", "label": "Raised"},
|
||||
{"filter": "uncaught", "label": "Uncaught", "default": true, "description": "Uncaught exceptions"},
|
||||
@@ -520,6 +544,20 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
ok!(msg, json!({"threads": [{"id": 1, "name": "MainThread"}]}));
|
||||
}
|
||||
}
|
||||
"stackTrace" if let Some(bad) = script.failing_frame => {
|
||||
let start = msg["arguments"]["startFrame"].as_u64().unwrap();
|
||||
let end = (start + msg["arguments"]["levels"].as_u64().unwrap()).min(3);
|
||||
if (start..end).contains(&bad) {
|
||||
send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "stackTrace", "success": false, "message": "Illegal char <<> at index 21: C:\\p\\com\\x\\<generated>"})
|
||||
);
|
||||
} else {
|
||||
let frames: Vec<Value> = (start..end)
|
||||
.map(|i| json!({"id": 10 + i, "name": format!("f{i}"), "line": 1, "column": 1}))
|
||||
.collect();
|
||||
ok!(msg, json!({"stackFrames": frames, "totalFrames": 3}));
|
||||
}
|
||||
}
|
||||
"stackTrace" => ok!(
|
||||
msg,
|
||||
json!({"stackFrames": [
|
||||
@@ -553,7 +591,58 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
]})
|
||||
),
|
||||
},
|
||||
"evaluate" if msg["arguments"]["expression"] == "&msg[0]" => ok!(
|
||||
msg,
|
||||
json!({"result": "0x1000 \"Hello\"", "type": "char *", "variablesReference": 1, "memoryReference": "0x1000"})
|
||||
),
|
||||
"evaluate" => ok!(msg, json!({"result": "42", "type": "int", "variablesReference": 0})),
|
||||
"readMemory" => {
|
||||
let args = &msg["arguments"];
|
||||
let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x");
|
||||
let start = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0);
|
||||
let count = args["count"].as_i64().unwrap();
|
||||
const END: i64 = 0x1010;
|
||||
if start >= END {
|
||||
send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "readMemory", "success": false, "message": format!("Cannot access memory at address {start:#x}")})
|
||||
);
|
||||
} else {
|
||||
let bytes: Vec<u8> = (start..(start + count).min(END)).map(|a| a as u8).collect();
|
||||
ok!(
|
||||
msg,
|
||||
json!({"address": format!("{start:#x}"), "data": base64::engine::general_purpose::STANDARD.encode(&bytes), "unreadableBytes": count - bytes.len() as i64})
|
||||
);
|
||||
}
|
||||
}
|
||||
"disassemble" => {
|
||||
let args = &msg["arguments"];
|
||||
let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x");
|
||||
let pc = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0);
|
||||
let (offset, count) =
|
||||
(args["instructionOffset"].as_i64().unwrap(), args["instructionCount"].as_i64().unwrap());
|
||||
let insn = |a: i64| {
|
||||
if (0x1000..0x1100).contains(&a) {
|
||||
json!({"address": format!("{a:#x}"), "instruction": format!("insn {}", (a - 0x1000) / 4), "instructionBytes": "90909090"})
|
||||
} else {
|
||||
json!({"address": format!("{a:#x}"), "instruction": "", "presentationHint": "invalid"})
|
||||
}
|
||||
};
|
||||
let addresses: Option<Vec<i64>> = match script.disassemble.unwrap() {
|
||||
FakeDisassembler::Lldb => Some((0..count).map(|i| pc + 4 * (offset + i)).collect()),
|
||||
FakeDisassembler::Gdb if offset + count < 0 => None,
|
||||
FakeDisassembler::Gdb => {
|
||||
let all: Vec<i64> = (0..offset + count).map(|i| pc + 4 * i).collect();
|
||||
let from = if offset >= 0 { offset } else { (all.len() as i64 + offset).max(0) };
|
||||
Some(all[from as usize..].to_vec())
|
||||
}
|
||||
};
|
||||
match addresses {
|
||||
Some(a) => ok!(msg, json!({"instructions": a.into_iter().map(insn).collect::<Vec<_>>()})),
|
||||
None => send!(
|
||||
json!({"type": "response", "request_seq": msg["seq"], "command": "disassemble", "success": false, "message": "Argument 'count' should be an non-negative integer."})
|
||||
),
|
||||
}
|
||||
}
|
||||
"completions" => ok!(
|
||||
msg,
|
||||
json!({"targets": [
|
||||
@@ -899,7 +988,7 @@ async fn full_protocol_flow() {
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
let disabled = Breakpoint { enabled: false, ..bp(2) };
|
||||
let cond = Breakpoint { condition: Some("x > 1".into()), ..bp(7) };
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4), disabled, cond]).await.unwrap();
|
||||
assert!(states.iter().all(|s| !s.verified), "no session yet");
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
@@ -981,7 +1070,7 @@ async fn full_protocol_flow() {
|
||||
assert_eq!(asked["arguments"]["frameId"], 10);
|
||||
|
||||
// Live breakpoint updates reach the session.
|
||||
let states = h.manager.set_breakpoints(path.clone(), vec![bp(0)]).await.unwrap();
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(0)]).await.unwrap();
|
||||
assert!(states[0].verified);
|
||||
|
||||
h.manager.resume(id, 1).await.unwrap();
|
||||
@@ -1005,7 +1094,7 @@ async fn full_protocol_flow() {
|
||||
async fn run_to_cursor_uses_temporary_breakpoint() {
|
||||
let h = harness(Script::default());
|
||||
let path = PathBuf::from("/p/a.py");
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
h.manager.run_to(id, 1, path.clone(), 9, false).await.unwrap();
|
||||
@@ -1037,7 +1126,7 @@ async fn stop_terminates_and_disconnects() {
|
||||
#[tokio::test]
|
||||
async fn unity_attach_waits_for_mono_and_disconnects_without_terminating_editor() {
|
||||
let h = harness(Script { empty_thread_responses: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.cs"), vec![bp(4)]).await.unwrap();
|
||||
let start = h.start(LaunchConfig {
|
||||
adapter: "unity".into(),
|
||||
request: "attach".into(),
|
||||
@@ -1889,7 +1978,7 @@ fn function_bp(name: &str, enabled: bool) -> FunctionBreakpoint {
|
||||
async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let h = harness(Script::default());
|
||||
let cond = FunctionBreakpoint { condition: Some("n > 1".into()), ..function_bp("com.a.B#run", true) };
|
||||
let states = h.manager.set_function_breakpoints(vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
let states = h.manager.set_function_breakpoints(&h.owner.key, vec![cond, function_bp("off", false)]).await.unwrap();
|
||||
assert!(!states[0].verified && states[1].message.as_deref() == Some("Disabled"), "no session yet");
|
||||
let watch = DataBreakpoint {
|
||||
data_id: "Req#count".into(),
|
||||
@@ -1898,7 +1987,7 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
hit_condition: Some("2".into()),
|
||||
enabled: true,
|
||||
};
|
||||
h.manager.set_data_breakpoints(vec![watch]).await.unwrap();
|
||||
h.manager.set_data_breakpoints(&h.owner.key, vec![watch]).await.unwrap();
|
||||
|
||||
let id = h.start(config()).await.unwrap();
|
||||
assert_eq!(
|
||||
@@ -1914,8 +2003,11 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
let pos = |c: &str| order.iter().position(|x| x == c).unwrap();
|
||||
assert!(pos("setFunctionBreakpoints") < pos("configurationDone"));
|
||||
|
||||
let states =
|
||||
h.manager.set_function_breakpoints(vec![function_bp("missing", true), function_bp("ok", true)]).await.unwrap();
|
||||
let states = h
|
||||
.manager
|
||||
.set_function_breakpoints(&h.owner.key, vec![function_bp("missing", true), function_bp("ok", true)])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!((states[0].verified, states[1].verified), (false, true), "live states from the session");
|
||||
|
||||
let info = h.manager.data_breakpoint_info(id, 101, "count".into(), Some(10)).await.unwrap();
|
||||
@@ -1932,6 +2024,161 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn memory_view_reads_memory_from_a_reference() {
|
||||
let h = harness(Script { read_memory: true, ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
assert_eq!(
|
||||
h.request("initialize")["arguments"]["supportsMemoryReferences"],
|
||||
true,
|
||||
"adapters only send references when asked"
|
||||
);
|
||||
assert!(h.manager.capabilities(id).unwrap().read_memory);
|
||||
|
||||
let pointer = h.manager.evaluate_in(id, Some(10), "&msg[0]".into(), Some("watch".into())).await.unwrap();
|
||||
assert_eq!(pointer.memory_reference.as_deref(), Some("0x1000"));
|
||||
let plain = h.manager.evaluate(id, Some(10), "n".into()).await.unwrap();
|
||||
assert_eq!(plain.memory_reference, None);
|
||||
|
||||
let block = h.manager.read_memory(id, "0x1000".into(), 0, 8).await.unwrap();
|
||||
assert_eq!(block, MemoryBlock { address: "0x1000".into(), data: (0..8).collect(), unreadable_bytes: 0 });
|
||||
assert_eq!(h.request("readMemory")["arguments"], json!({"memoryReference": "0x1000", "offset": 0, "count": 8}));
|
||||
|
||||
// Paging back and forth goes through `offset` on the same reference; the end of the mapping
|
||||
// comes back as unreadable bytes.
|
||||
let block = h.manager.read_memory(id, "0x1000".into(), 8, 16).await.unwrap();
|
||||
assert_eq!((block.address.as_str(), block.data.len(), block.unreadable_bytes), ("0x1008", 8, 8));
|
||||
assert_eq!(block.data[0], 0x08);
|
||||
|
||||
// Unmapped memory is the adapter's error, and the session goes on.
|
||||
let err = h.manager.read_memory(id, "0x1000".into(), 0x20, 16).await.unwrap_err();
|
||||
assert!(err.to_string().contains("Cannot access memory at address 0x1020"), "{err}");
|
||||
assert!(!h.manager.threads(id).await.unwrap().is_empty());
|
||||
|
||||
let _ = h.manager.read_memory(id, "0x1000".into(), 0, u32::MAX).await;
|
||||
let last = h.log.lock().iter().rev().find(|m| m["command"] == "readMemory").cloned().unwrap();
|
||||
assert_eq!(last["arguments"]["count"], MAX_READ, "one read never asks for more than a few pages");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn memory_view_says_when_the_adapter_cannot_read_memory() {
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
assert!(!h.manager.capabilities(id).unwrap().read_memory);
|
||||
let err = h.manager.read_memory(id, "0x1000".into(), 0, 16).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(err.to_string().contains("debug adapter `debugpy` cannot read memory"), "{err}");
|
||||
assert!(!h.commands().iter().any(|c| c == "readMemory"), "nothing is sent to an adapter without support");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variables_keep_their_memory_reference() {
|
||||
let v = variable_from(
|
||||
&json!({"name": "words", "value": "0x4010", "variablesReference": 3, "memoryReference": "0x4010"}),
|
||||
);
|
||||
assert_eq!(v.memory_reference.as_deref(), Some("0x4010"));
|
||||
assert_eq!(variable_from(&json!({"name": "n", "value": "1", "memoryReference": ""})).memory_reference, None);
|
||||
let json = serde_json::to_value(variable_from(&json!({"name": "n", "value": "1"}))).unwrap();
|
||||
assert!(json.get("memoryReference").is_none(), "absent, not null, for the UI's optional field");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disassembly_reads_instructions_around_the_instruction_pointer() {
|
||||
let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let caps = h.manager.capabilities(id).unwrap();
|
||||
assert!(caps.disassemble && caps.instruction_stepping);
|
||||
|
||||
let list = h.manager.disassemble(id, "0x1010".into(), 2, 5).await.unwrap();
|
||||
let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect();
|
||||
assert_eq!(addresses, ["0x1008", "0x100c", "0x1010", "0x1014", "0x1018"]);
|
||||
assert_eq!((list[2].instruction.as_str(), list[2].bytes.as_deref()), ("insn 4", Some("90909090")));
|
||||
assert_eq!(
|
||||
requests(&h, "disassemble")[0],
|
||||
json!({"memoryReference": "0x1010", "offset": 0, "instructionOffset": -2, "instructionCount": 5, "resolveSymbols": true})
|
||||
);
|
||||
|
||||
// Before the first mapped instruction the adapter pads; the padding is not shown.
|
||||
let list = h.manager.disassemble(id, "0x1004".into(), 4, 6).await.unwrap();
|
||||
let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect();
|
||||
assert_eq!(addresses, ["0x1000", "0x1004", "0x1008"]);
|
||||
|
||||
let _ = h.manager.disassemble(id, "0x1000".into(), 0, u32::MAX).await;
|
||||
assert_eq!(requests(&h, "disassemble").last().unwrap()["instructionCount"], MAX_INSTRUCTIONS);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disassembly_starts_at_the_instruction_pointer_when_the_adapter_cannot_go_back() {
|
||||
let h = harness(Script { disassemble: Some(FakeDisassembler::Gdb), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
// GDB's answer to "4 before" leaves out the instruction pointer; the view asks again from it.
|
||||
let list = h.manager.disassemble(id, "0x1010".into(), 4, 10).await.unwrap();
|
||||
assert_eq!(list.first().map(|i| i.address.as_str()), Some("0x1010"));
|
||||
assert_eq!(list.len(), 6);
|
||||
let offsets: Vec<Value> = requests(&h, "disassemble").iter().map(|r| r["instructionOffset"].clone()).collect();
|
||||
assert_eq!(offsets, [json!(-4), json!(0)]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn instruction_steps_send_the_granularity_and_line_steps_do_not() {
|
||||
let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
h.manager.step_instruction(id, 1, StepKind::Into).await.unwrap();
|
||||
assert_eq!(requests(&h, "stepIn").last().unwrap(), &json!({"threadId": 1, "granularity": "instruction"}));
|
||||
h.manager.step(id, 1, StepKind::Over).await.unwrap();
|
||||
assert_eq!(requests(&h, "next").last().unwrap(), &json!({"threadId": 1}));
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disassembly_and_instruction_steps_say_when_the_adapter_cannot() {
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let caps = h.manager.capabilities(id).unwrap();
|
||||
assert!(!caps.disassemble && !caps.instruction_stepping);
|
||||
let err = h.manager.disassemble(id, "0x1000".into(), 0, 16).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(err.to_string().contains("debug adapter `debugpy` cannot disassemble"), "{err}");
|
||||
let err = h.manager.step_instruction(id, 1, StepKind::Over).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
let sent = h.commands();
|
||||
assert!(!sent.iter().any(|c| c == "disassemble" || c == "next"), "nothing is sent to an adapter without support");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_keep_their_instruction_pointer() {
|
||||
let f = frame_from(&json!({"id": 1, "name": "atoi", "line": 0, "instructionPointerReference": "0x7ffff7c4a2e0"}));
|
||||
assert_eq!(f.instruction_pointer_reference.as_deref(), Some("0x7ffff7c4a2e0"));
|
||||
let json = serde_json::to_value(frame_from(&json!({"id": 1, "name": "main"}))).unwrap();
|
||||
assert!(json.get("instructionPointerReference").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_drop_pseudo_paths_of_referenced_sources() {
|
||||
let frame = |path: &str, reference: i64| {
|
||||
frame_from(&json!({"id": 1, "name": "f", "line": 1,
|
||||
"source": {"path": path, "sourceReference": reference}}))
|
||||
.path
|
||||
};
|
||||
let lldb = "/usr/lib/swift/libswiftCore.dylib`swift_willThrow";
|
||||
assert_eq!(frame(lldb, 1), None, "lldb-dap disassembly");
|
||||
assert_eq!(frame(lldb, 0).as_deref(), Some(Path::new(lldb)), "no reference: kept as sent");
|
||||
let here = env!("CARGO_MANIFEST_DIR");
|
||||
assert_eq!(frame(here, 3).as_deref(), Some(Path::new(here)), "an existing file");
|
||||
assert!(frame("jdt://contents/rt.jar/java.lang/String.class", 2).is_some(), "not a file path");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn smart_step_into_and_reset_frame() {
|
||||
let h = harness(Script::default());
|
||||
@@ -1958,10 +2205,13 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
let h = harness(Script::default());
|
||||
let a = PathBuf::from("/p/a.py");
|
||||
let b = PathBuf::from("/p/b.py");
|
||||
h.manager.set_breakpoints(a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(vec![function_bp("run", true)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, a.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, b.clone(), vec![bp(3)]).await.unwrap();
|
||||
h.manager
|
||||
.set_breakpoints(&h.owner.key, PathBuf::from("/p/off.py"), vec![Breakpoint { enabled: false, ..bp(5) }])
|
||||
.await
|
||||
.unwrap();
|
||||
h.manager.set_function_breakpoints(&h.owner.key, vec![function_bp("run", true)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
|
||||
let sent_for = |path: &str| -> Vec<Value> {
|
||||
@@ -1995,10 +2245,10 @@ async fn force_stepping_suspends_breakpoints_until_the_next_stop() {
|
||||
#[tokio::test]
|
||||
async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled() {
|
||||
let h = harness(Script { hold_set_breakpoints: 2, ..Script::default() });
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/a.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, PathBuf::from("/p/b.py"), vec![bp(3)]).await.unwrap();
|
||||
let off = PathBuf::from("/p/off.py");
|
||||
h.manager.set_breakpoints(off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, off.clone(), vec![Breakpoint { enabled: false, ..bp(5) }]).await.unwrap();
|
||||
// Waiting for each answer before the next request would stall until the request timeout.
|
||||
tokio::time::timeout(Duration::from_secs(5), h.start(config())).await.expect("requests pipelined").unwrap();
|
||||
let paths: Vec<Value> = requests(&h, "setBreakpoints").into_iter().map(|r| r["source"]["path"].clone()).collect();
|
||||
@@ -2009,6 +2259,40 @@ async fn startup_sends_every_file_at_once_and_skips_files_with_nothing_enabled()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_get_only_their_windows_breakpoints_and_a_replaced_list_drops_stale_files() {
|
||||
let h = harness(Script::default());
|
||||
let other = "project-2";
|
||||
h.manager.set_breakpoints(other, PathBuf::from("/p/other.py"), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_function_breakpoints(other, vec![function_bp("elsewhere", true)]).await.unwrap();
|
||||
let stale = PathBuf::from("/p/stale.py");
|
||||
h.manager.set_breakpoints(&h.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let paths = || -> Vec<(Value, Value)> {
|
||||
requests(&h, "setBreakpoints")
|
||||
.into_iter()
|
||||
.map(|r| (r["source"]["path"].clone(), r["breakpoints"].clone()))
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(paths(), [(json!("/p/stale.py"), json!([{"line": 3}]))], "another window's file is not sent");
|
||||
assert!(requests(&h, "setFunctionBreakpoints").is_empty(), "nor its method breakpoints");
|
||||
|
||||
// The window's list no longer has the stale file (#6116): replacing clears it in the session...
|
||||
let kept = PathBuf::from("/p/kept.py");
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths()[1..], [(json!("/p/stale.py"), json!([])), (json!("/p/kept.py"), json!([{"line": 5}]))]);
|
||||
// ...unchanged files are not sent again...
|
||||
h.manager.replace_breakpoints(&h.owner.key, BTreeMap::from([(kept.clone(), vec![bp(4)])])).await.unwrap();
|
||||
assert_eq!(paths().len(), 3);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
// ...and the next session gets only what the window lists.
|
||||
let h2 = harness(Script::default());
|
||||
h2.manager.set_breakpoints(&h2.owner.key, stale.clone(), vec![bp(2)]).await.unwrap();
|
||||
h2.manager.replace_breakpoints(&h2.owner.key, BTreeMap::new()).await.unwrap();
|
||||
h2.start(config()).await.unwrap();
|
||||
assert!(requests(&h2, "setBreakpoints").is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hot_reload_sends_its_reason_and_reports_the_flutter_app() {
|
||||
let h = harness(Script::default());
|
||||
@@ -2209,7 +2493,7 @@ async fn godot_gets_resolved_paths() {
|
||||
Arc::new(FakeLauncher { log: log.clone(), script: Script::default() }),
|
||||
);
|
||||
let bp = Breakpoint { line: 0, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints(link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints("main", link.join("player.gd"), vec![bp]).await.unwrap();
|
||||
let id = manager.start(godot_launch(&link), owner).await.unwrap();
|
||||
let sent = log.lock().iter().find(|m| m["command"] == "setBreakpoints").cloned().unwrap();
|
||||
assert_eq!(sent["arguments"]["source"]["path"], json!(real.join("player.gd")));
|
||||
@@ -2236,7 +2520,7 @@ async fn kotlin_configures_without_configuration_done_response() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let mut config = config();
|
||||
config.adapter = kotlin::ADAPTER.into();
|
||||
config.request = "attach".into();
|
||||
@@ -2270,7 +2554,7 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
let (owner, events) = recording_owner("kotlin-probe");
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let h = Harness { manager, owner, events, log: Arc::default() };
|
||||
h.manager.set_breakpoints(source.clone(), vec![bp(5)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, source.clone(), vec![bp(5)]).await.unwrap();
|
||||
let id = h.manager.start_with(config.clone(), h.owner.clone(), |_| Some(adapter.clone())).await.unwrap();
|
||||
let stopped = h.wait_event(|e| matches!(e, DebugEvent::Stopped { reason, .. } if reason == "breakpoint")).await;
|
||||
let DebugEvent::Stopped { thread_id, .. } = stopped else { unreachable!() };
|
||||
@@ -2292,6 +2576,21 @@ async fn kotlin_official_release_ten_no_delay_runs() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stack_trace_leaves_out_a_frame_the_adapter_cannot_describe() {
|
||||
let h = harness(Script { failing_frame: Some(1), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let frames = h.manager.stack_trace(id, 1).await.unwrap();
|
||||
assert_eq!(frames.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["f0", "f2"]);
|
||||
h.manager.stop(id).await.unwrap();
|
||||
|
||||
let h = harness(Script { failing_frame: Some(0), ..Script::default() });
|
||||
let id = h.start(config()).await.unwrap();
|
||||
let error = h.manager.stack_trace(id, 1).await.unwrap_err();
|
||||
assert!(error.message.contains("<generated>"), "{error:?}");
|
||||
h.manager.stop(id).await.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[tokio::test]
|
||||
async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
@@ -2299,7 +2598,7 @@ async fn netcoredbg_windows_source_paths_round_trip() {
|
||||
let native = r"D:\work\LoginController.cs";
|
||||
let h = harness(Script { source_path: Some(native.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(25)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(25)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "netcoredbg".into();
|
||||
let id = h.start(cfg).await.unwrap();
|
||||
@@ -2323,7 +2622,7 @@ async fn java_windows_source_paths_for_launch_and_attach() {
|
||||
] {
|
||||
let h = harness(Script { source_path: Some(returned.into()), ..Script::default() });
|
||||
let path = PathBuf::from(client);
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(4)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(4)]).await.unwrap();
|
||||
let mut cfg = config();
|
||||
cfg.adapter = "java-debug".into();
|
||||
cfg.request = request.into();
|
||||
@@ -3418,7 +3717,7 @@ async fn kotlin_lsp_gets_real_paths_and_its_link_holds_nothing() {
|
||||
let project = tempfile::tempdir().unwrap();
|
||||
let path = project.path().join("Main.kt");
|
||||
std::fs::write(&path, "package org.example\nfun main() {}\n").unwrap();
|
||||
h.manager.set_breakpoints(path.clone(), vec![bp(1)]).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(1)]).await.unwrap();
|
||||
let id = h.start(kotlin_lsp_attach(project.path())).await.unwrap();
|
||||
assert_eq!(h.request("setBreakpoints")["arguments"]["source"]["path"], json!(path));
|
||||
let sent = &h.request("attach")["arguments"];
|
||||
@@ -3719,3 +4018,19 @@ async fn stop_detaches_from_an_attached_program() {
|
||||
assert!(!h.commands().contains(&"terminate".to_owned()));
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
|
||||
use crate::jvm_memory::test_support::bare_session_of;
|
||||
use std::path::Path;
|
||||
let (a, b) = ("vscode-notebook-cell:/p/a.ipynb#c1", "vscode-notebook-cell:/p/b.ipynb#c1");
|
||||
let mut kernel = bare_session_of(crate::NOTEBOOK_ADAPTER, "attach");
|
||||
std::sync::Arc::get_mut(&mut kernel.session).unwrap().notebook_cells =
|
||||
Some("vscode-notebook-cell:/p/a.ipynb#".into());
|
||||
let python = bare_session_of("debugpy", "launch");
|
||||
assert!(kernel.session.takes(Path::new(a)));
|
||||
assert!(!kernel.session.takes(Path::new(b)), "another notebook's cells");
|
||||
assert!(kernel.session.takes(Path::new("/p/lib.py")), "files the cells may call");
|
||||
assert!(!python.session.takes(Path::new(a)));
|
||||
assert!(python.session.takes(Path::new("/p/lib.py")));
|
||||
}
|
||||
@@ -47,7 +47,7 @@ async fn debugpy_end_to_end() {
|
||||
let sink: SharedSink = Arc::new(move |e: IdeEvent| sink_events.lock().push(e));
|
||||
let manager = DebugManager::new(Arc::new(LanguageRegistry::from_configs(Vec::new())));
|
||||
let bp = Breakpoint { line: 3, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
manager.set_breakpoints(script.clone(), vec![bp]).await.unwrap();
|
||||
manager.set_breakpoints("main", script.clone(), vec![bp]).await.unwrap();
|
||||
let id = manager
|
||||
.start(
|
||||
LaunchConfig {
|
||||
@@ -74,7 +74,7 @@ async fn debugpy_end_to_end() {
|
||||
assert!(vars.iter().any(|v| v.name == "total"), "{vars:?}");
|
||||
let v = manager.evaluate(id, Some(frames[0].id), "total + 100".into()).await.unwrap();
|
||||
assert_eq!(v.value, "100");
|
||||
manager.set_breakpoints(script.clone(), vec![]).await.unwrap();
|
||||
manager.set_breakpoints("main", script.clone(), vec![]).await.unwrap();
|
||||
manager.resume(id, thread_id).await.unwrap();
|
||||
wait(&events, |e| matches!(e, DebugEvent::Output { output, .. } if output.contains("total 3"))).await;
|
||||
wait(&events, |e| matches!(e, DebugEvent::Terminated)).await;
|
||||
|
||||
@@ -96,6 +96,7 @@ async fn breakpoints_stepping_and_variables_in_a_real_godot() {
|
||||
let script_as_opened = dir.join("player.gd");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
script_as_opened.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -81,6 +81,7 @@ async fn listens_for_xdebug_until_stopped_with_path_mappings() {
|
||||
let local_script = local.join("index.php");
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"main",
|
||||
local_script.clone(),
|
||||
vec![Breakpoint {
|
||||
line: BREAK_LINE,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
//! Drives real debug adapters against tiny programs (one per language), checking the
|
||||
//! launch templates and the IDEA-parity features: line / method breakpoints, Smart Step
|
||||
//! Into, Reset Frame, Force Step Over, Force Run to Cursor and Set Value.
|
||||
//! Into, Reset Frame, Force Step Over, Force Run to Cursor, Set Value, the Memory View and the Disassembly view.
|
||||
//!
|
||||
//! Ignored by default (needs the adapters installed). Run with
|
||||
//! `OPENIDEA_DAP_FIXTURES=<dir> cargo test -p ide-dap --test real_adapters -- --ignored --nocapture`
|
||||
//! where `<dir>` holds `py/app.py`, `node/app.js`, `go/demo` (built with `-N -l`),
|
||||
//! `rust/target/debug/demo` and `c/main`. Adapters not found on `PATH` are skipped.
|
||||
//! `rust/target/debug/demo` and `c/main` (whose loop function also has a `char msg[]` local, for
|
||||
//! the Memory View). Adapters not found on `PATH` are skipped.
|
||||
|
||||
use ide_core::event::DebugEvent;
|
||||
use ide_core::{DebugSessionId, IdeEvent, SharedSink};
|
||||
@@ -261,7 +262,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let m = &run.manager;
|
||||
let line_bp =
|
||||
Breakpoint { line: case.loop_line, condition: None, hit_condition: None, log_message: None, enabled: true };
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp]).await.map_err(|e| e.message)?;
|
||||
|
||||
let seen = run.seen();
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
@@ -280,6 +281,78 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let caps = m.capabilities(s).map_err(|e| e.message)?;
|
||||
report.push(format!("capabilities: {caps:?}"));
|
||||
|
||||
// Memory View: the bytes at an address expression (the C fixture's `msg`), and an unmapped address.
|
||||
if caps.read_memory {
|
||||
match m.evaluate_in(s, Some(top.id), "&msg[0]".into(), Some("watch".into())).await {
|
||||
Ok(v) => match v.memory_reference {
|
||||
Some(r) => match m.read_memory(s, r.clone(), 0, 16).await {
|
||||
Ok(b) => report.push(format!(
|
||||
"memory view `&msg[0]` ({r}): {} = {:02x?} {:?}, {} unreadable",
|
||||
b.address,
|
||||
b.data,
|
||||
String::from_utf8_lossy(&b.data),
|
||||
b.unreadable_bytes
|
||||
)),
|
||||
Err(e) => report.push(format!("memory view `&msg[0]`: FAILED {}", e.message)),
|
||||
},
|
||||
None => report.push(format!("memory view `&msg[0]` = {}: no memory reference", v.value)),
|
||||
},
|
||||
Err(e) => report.push(format!("memory view `&msg[0]`: not evaluated ({})", e.message)),
|
||||
}
|
||||
match m.read_memory(s, "0x0".into(), 0, 16).await {
|
||||
Ok(b) => report.push(format!("memory view 0x0: {} bytes, {} unreadable", b.data.len(), b.unreadable_bytes)),
|
||||
Err(e) => report.push(format!("memory view 0x0: error `{}`", e.message)),
|
||||
}
|
||||
} else {
|
||||
report.push("memory view: readMemory not supported".into());
|
||||
}
|
||||
|
||||
// Disassembly: the instructions around the stop's instruction pointer, then two instruction steps,
|
||||
// which stay on the loop line and inside the instructions shown.
|
||||
let address = |a: &str| u128::from_str_radix(a.trim_start_matches("0x"), 16).ok();
|
||||
match (caps.disassemble, top.instruction_pointer_reference.clone()) {
|
||||
(true, Some(pc)) => match m.disassemble(s, pc.clone(), 8, 24).await {
|
||||
Ok(list) => {
|
||||
let shown = |a: &str| list.iter().position(|i| address(&i.address) == address(a));
|
||||
match shown(&pc) {
|
||||
Some(at) => report.push(format!(
|
||||
"disassembly at {pc}: {} instructions, the instruction pointer is #{at}: `{}` ({:?})",
|
||||
list.len(),
|
||||
list[at].instruction,
|
||||
list[at].bytes
|
||||
)),
|
||||
None => report.push(format!("disassembly at {pc}: FAILED, not among {list:?}")),
|
||||
}
|
||||
if caps.instruction_stepping {
|
||||
let mut steps = vec![pc];
|
||||
for _ in 0..2 {
|
||||
let seen = run.seen();
|
||||
m.step_instruction(s, thread, StepKind::Over).await.map_err(|e| e.message)?;
|
||||
run.stopped_after(seen).await.ok_or("no stop after step over instruction")?;
|
||||
let f = run.top(s, thread).await;
|
||||
if f.line != case.loop_line {
|
||||
report.push(format!(
|
||||
"step over instruction: left the loop line for {}:{}",
|
||||
f.name,
|
||||
f.line + 1
|
||||
));
|
||||
}
|
||||
steps.push(f.instruction_pointer_reference.unwrap_or_default());
|
||||
}
|
||||
let all = steps.iter().all(|a| shown(a).is_some());
|
||||
report.push(format!("step over instruction: {} (all shown: {all})", steps.join(" -> ")));
|
||||
} else {
|
||||
report.push("instruction stepping: not supported".into());
|
||||
}
|
||||
}
|
||||
Err(e) => report.push(format!("disassembly at {pc}: FAILED {}", e.message)),
|
||||
},
|
||||
(true, None) => report.push("disassembly: the top frame has no instruction pointer".into()),
|
||||
(false, _) => report.push("disassembly: not supported".into()),
|
||||
}
|
||||
// Instruction steps resumed the thread: frame ids from before them may be gone.
|
||||
let top = run.top(s, thread).await;
|
||||
|
||||
// Set Value on the first local that is an integer.
|
||||
let scopes = m.scopes(s, top.id).await.map_err(|e| e.message)?;
|
||||
for scope in scopes.iter().filter(|sc| !sc.expensive) {
|
||||
@@ -356,9 +429,9 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
// Method breakpoint: continue → stops in `parse`.
|
||||
if caps.function_breakpoints {
|
||||
let fb = FunctionBreakpoint { name: case.function.into(), condition: None, hit_condition: None, enabled: true };
|
||||
let states = m.set_function_breakpoints(vec![fb]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_function_breakpoints("test", vec![fb]).await.map_err(|e| e.message)?;
|
||||
report.push(format!("method breakpoint `{}`: verified={}", case.function, states[0].verified));
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -368,8 +441,10 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push("method breakpoint: NOT HIT".into()),
|
||||
}
|
||||
m.set_function_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
m.set_function_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.step(s, thread, StepKind::Out).await.map_err(|e| e.message)?;
|
||||
run.stopped_after(seen).await.ok_or("no stop after step out of parse")?;
|
||||
@@ -378,7 +453,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
|
||||
// Force Step Over ignores the breakpoint inside parse.
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.force_step_over(s, thread).await.map_err(|e| e.message)?;
|
||||
let (_, t, reason) = run.stopped_after(seen).await.ok_or("no stop after force step over")?;
|
||||
@@ -409,8 +484,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
hit_condition: None,
|
||||
enabled: true,
|
||||
};
|
||||
let states = m.set_data_breakpoints(vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let states = m.set_data_breakpoints("test", vec![wp]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s, thread).await.map_err(|e| e.message)?;
|
||||
match run.stopped_after(seen).await {
|
||||
@@ -425,8 +500,8 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
}
|
||||
None => report.push(format!("watchpoint `{data_id}`: NOT HIT")),
|
||||
}
|
||||
m.set_data_breakpoints(vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints(case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
m.set_data_breakpoints("test", vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.loop_line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
}
|
||||
@@ -623,7 +698,7 @@ async fn attach_to_processes() {
|
||||
};
|
||||
let run = Run::new();
|
||||
run.manager
|
||||
.set_breakpoints(case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.set_breakpoints("test", case.source.clone(), vec![line_bp_at(case.line)])
|
||||
.await
|
||||
.map_err(|e| e.message)?;
|
||||
let id =
|
||||
|
||||
@@ -253,7 +253,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
let mut report = Vec::new();
|
||||
let run = Run::new();
|
||||
let m = &run.manager;
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let id = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("start: {}", e.message))?;
|
||||
|
||||
let (s, thread) = run.stopped(0, "the loop breakpoint").await?;
|
||||
@@ -312,7 +312,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
expect_line(&run.top(s2, t2).await?, LOOP_LINE, "continue")?;
|
||||
|
||||
// Without breakpoints, the program runs to its end.
|
||||
m.set_breakpoints(case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
m.resume(s2, t2).await.map_err(|e| e.message)?;
|
||||
run.wait(seen, "terminated", |s, e| (s == id && matches!(e, DebugEvent::Terminated)).then_some(())).await?;
|
||||
@@ -333,7 +333,7 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
|
||||
report.push("continue to exit: output and terminated".into());
|
||||
|
||||
// Restart (the UI starts the same configuration again), then Stop while paused.
|
||||
m.set_breakpoints(case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
m.set_breakpoints("test", case.source.clone(), vec![bp(LOOP_LINE)]).await.map_err(|e| e.message)?;
|
||||
let seen = run.seen();
|
||||
let again = m.start(case.config.clone(), run.owner.clone()).await.map_err(|e| format!("restart: {}", e.message))?;
|
||||
let (s, thread) = run.stopped(seen, "the breakpoint after restart").await?;
|
||||
|
||||
@@ -110,6 +110,7 @@ async fn real_editor_attach_breakpoint_step_variables_and_detach() {
|
||||
let line = SCRIPT.lines().position(|l| l.contains("int answer =")).unwrap() as u32;
|
||||
manager
|
||||
.set_breakpoints(
|
||||
"smoke",
|
||||
source.clone(),
|
||||
vec![Breakpoint { line, condition: None, hit_condition: None, log_message: None, enabled: true }],
|
||||
)
|
||||
|
||||
@@ -127,7 +127,10 @@ mod tests {
|
||||
fn schema(name: &str, tables: &[&str]) -> CatalogSchema {
|
||||
CatalogSchema {
|
||||
name: name.into(),
|
||||
tables: tables.iter().map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table }).collect(),
|
||||
tables: tables
|
||||
.iter()
|
||||
.map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table, comment: None })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use crate::ConsoleId;
|
||||
use crate::conn::{QueryResult, ResultColumn, Setup};
|
||||
use crate::source::{DataSource, DbSslMode, DbTxMode};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use parking_lot::RwLock;
|
||||
use reqwest::{Client, RequestBuilder, StatusCode, Url};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::sync::{Mutex, MutexGuard};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ClickhousePool(Arc<State>);
|
||||
@@ -18,11 +20,17 @@ struct State {
|
||||
database: String,
|
||||
settings: Vec<(String, String)>,
|
||||
read_only: bool,
|
||||
session: Mutex<Session>,
|
||||
connect_timeout: Duration,
|
||||
startup_statements: Vec<String>,
|
||||
use_http_session: bool,
|
||||
session: SessionSlot,
|
||||
console_sessions: parking_lot::Mutex<HashMap<(String, String), Arc<SessionSlot>>>,
|
||||
closed: CancellationToken,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
type SessionSlot = Mutex<Option<Session>>;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Session {
|
||||
id: Option<String>,
|
||||
initialized: bool,
|
||||
@@ -32,6 +40,7 @@ struct Session {
|
||||
/// The response format: a names line, a types line, then one JSON array per row, so rows past
|
||||
/// the grid's limit are skipped without being parsed.
|
||||
const FORMAT: &str = "JSONCompactEachRowWithNamesAndTypes";
|
||||
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(600);
|
||||
const SESSION_LOST: &str = "ClickHouse HTTP session expired or is missing on this node (code 372). Reconnect to start a new session. Behind a load balancer, use one node or session affinity, or set use_http_session=false in Advanced for independent queries.";
|
||||
|
||||
pub(crate) fn transaction_error() -> IdeError {
|
||||
@@ -44,6 +53,7 @@ impl ClickhousePool {
|
||||
return Err(transaction_error());
|
||||
}
|
||||
let mut use_http_session = None;
|
||||
let mut read_timeout = None;
|
||||
let mut settings = Vec::with_capacity(setup.params.len());
|
||||
for (name, value) in setup.params {
|
||||
if name.eq_ignore_ascii_case("use_http_session") {
|
||||
@@ -57,6 +67,14 @@ impl ClickhousePool {
|
||||
} else {
|
||||
return Err(IdeError::invalid("ClickHouse use_http_session must be true or false"));
|
||||
});
|
||||
} else if name.eq_ignore_ascii_case("http_read_timeout") {
|
||||
if read_timeout.is_some() {
|
||||
return Err(IdeError::invalid("ClickHouse http_read_timeout must be specified only once"));
|
||||
}
|
||||
let seconds = value.parse::<std::num::NonZeroU32>().map_err(|_| {
|
||||
IdeError::invalid("ClickHouse http_read_timeout must be a positive whole number of seconds")
|
||||
})?;
|
||||
read_timeout = Some(Duration::from_secs(u64::from(seconds.get())));
|
||||
} else if reserved_setting(&name) {
|
||||
return Err(IdeError::invalid(format!("ClickHouse HTTP manages the {name} setting")));
|
||||
} else {
|
||||
@@ -89,6 +107,7 @@ impl ClickhousePool {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let mut builder = Client::builder()
|
||||
.connect_timeout(timeout)
|
||||
.read_timeout(read_timeout.unwrap_or(DEFAULT_READ_TIMEOUT))
|
||||
.pool_max_idle_per_host(4)
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.user_agent(concat!("OpenIDEA/", env!("CARGO_PKG_VERSION")));
|
||||
@@ -136,79 +155,126 @@ impl ClickhousePool {
|
||||
database: database.into(),
|
||||
settings,
|
||||
read_only: source.read_only,
|
||||
session: Mutex::new(Session {
|
||||
id: use_http_session.then(|| uuid::Uuid::new_v4().to_string()),
|
||||
..Session::default()
|
||||
}),
|
||||
connect_timeout: timeout,
|
||||
startup_statements: setup.statements,
|
||||
use_http_session,
|
||||
session: Mutex::new(None),
|
||||
console_sessions: parking_lot::Mutex::new(HashMap::new()),
|
||||
closed: CancellationToken::new(),
|
||||
}));
|
||||
let cancel = CancellationToken::new();
|
||||
let initialize = async {
|
||||
if let Err(error) = pool.execute("SELECT 1", 1, &cancel).await {
|
||||
let Some(setting) = rejected_driver_setting(&error) else {
|
||||
return Err(error);
|
||||
};
|
||||
if !use_http_session {
|
||||
if setting == "readonly" {
|
||||
return Err(error);
|
||||
}
|
||||
if !source.read_only {
|
||||
return Err(IdeError::new(
|
||||
error.kind,
|
||||
format!(
|
||||
"{}; enable Read-only for independent queries on a strict read-only server",
|
||||
error.message
|
||||
),
|
||||
));
|
||||
}
|
||||
// Every request still sends readonly=1, regardless of which node answers.
|
||||
pool.0.session.lock().await.strict_read_only = true;
|
||||
pool.execute("SELECT 1", 1, &cancel).await?;
|
||||
} else {
|
||||
// Only rely on the server's write protection after proving strict read-only
|
||||
// in this same named session.
|
||||
{
|
||||
let mut session = pool.0.session.lock().await;
|
||||
// The rejected probe may have opened a session on a different node.
|
||||
session.id = Some(uuid::Uuid::new_v4().to_string());
|
||||
session.strict_read_only = true;
|
||||
}
|
||||
let result = pool.execute("SELECT getSetting('readonly')", 1, &cancel).await?;
|
||||
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The HTTP database parameter applies to one request. A named session needs
|
||||
// USE once so later queries inherit the selection (and may change it).
|
||||
if use_http_session && !database.is_empty() {
|
||||
let name = crate::sql::quote_ident(crate::DbDriver::Clickhouse, database);
|
||||
pool.execute(&format!("USE {name}"), 0, &cancel).await?;
|
||||
}
|
||||
for sql in setup.statements {
|
||||
pool.execute(&sql, 0, &cancel).await?;
|
||||
}
|
||||
Ok(pool.clone())
|
||||
if let Err(error) = pool.session(&pool.0.session, &cancel).await {
|
||||
pool.close();
|
||||
return Err(error);
|
||||
}
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
async fn session<'a>(
|
||||
&self,
|
||||
slot: &'a SessionSlot,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<MutexGuard<'a, Option<Session>>> {
|
||||
let mut slot = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
() = self.0.closed.cancelled() => return Err(IdeError::new(ErrorKind::Io, "ClickHouse connection is closed")),
|
||||
session = slot.lock() => session,
|
||||
};
|
||||
tokio::pin!(initialize);
|
||||
tokio::select! {
|
||||
result = &mut initialize => {
|
||||
if result.is_err() {
|
||||
pool.close();
|
||||
if slot.is_none() {
|
||||
let mut session =
|
||||
Session { id: self.0.use_http_session.then(|| uuid::Uuid::new_v4().to_string()), ..Session::default() };
|
||||
{
|
||||
let cancel = cancel.child_token();
|
||||
let initialize = self.initialize(&mut session, &cancel);
|
||||
tokio::pin!(initialize);
|
||||
tokio::select! {
|
||||
result = &mut initialize => result?,
|
||||
() = tokio::time::sleep(self.0.connect_timeout) => {
|
||||
cancel.cancel();
|
||||
let _ = initialize.await;
|
||||
return Err(IdeError::new(ErrorKind::TimedOut, "timed out connecting to ClickHouse HTTP"));
|
||||
}
|
||||
}
|
||||
}
|
||||
*slot = Some(session);
|
||||
}
|
||||
Ok(slot)
|
||||
}
|
||||
|
||||
async fn initialize(&self, session: &mut Session, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
if let Err(error) = self.execute_request("SELECT 1", 0, 1, cancel, session).await {
|
||||
let Some(setting) = rejected_driver_setting(&error) else {
|
||||
return Err(error);
|
||||
};
|
||||
if session.id.is_none() {
|
||||
if setting == "readonly" {
|
||||
return Err(error);
|
||||
}
|
||||
if !self.0.read_only {
|
||||
return Err(IdeError::new(
|
||||
error.kind,
|
||||
format!(
|
||||
"{}; enable Read-only for independent queries on a strict read-only server",
|
||||
error.message
|
||||
),
|
||||
));
|
||||
}
|
||||
// Every request still sends readonly=1, regardless of which node answers.
|
||||
session.strict_read_only = true;
|
||||
self.execute_request("SELECT 1", 0, 1, cancel, session).await?;
|
||||
} else {
|
||||
// Only rely on the server's write protection after proving strict read-only
|
||||
// in this same named session. The rejected probe may have used a different node.
|
||||
session.id = Some(uuid::Uuid::new_v4().to_string());
|
||||
session.strict_read_only = true;
|
||||
let result = self.execute_request("SELECT getSetting('readonly')", 0, 1, cancel, session).await?;
|
||||
if result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) != Some("1") {
|
||||
return Err(error);
|
||||
}
|
||||
result
|
||||
},
|
||||
() = tokio::time::sleep(timeout) => {
|
||||
cancel.cancel();
|
||||
let _ = initialize.await;
|
||||
pool.close();
|
||||
Err(IdeError::new(ErrorKind::TimedOut, "timed out connecting to ClickHouse HTTP"))
|
||||
}
|
||||
}
|
||||
// A named session needs USE once so later queries inherit the database and may change it.
|
||||
if session.id.is_some() && !self.0.database.is_empty() {
|
||||
let name = crate::sql::quote_ident(crate::DbDriver::Clickhouse, &self.0.database);
|
||||
self.execute_request(&format!("USE {name}"), 0, 0, cancel, session).await?;
|
||||
}
|
||||
for sql in &self.0.startup_statements {
|
||||
if transaction_statement(sql) {
|
||||
return Err(transaction_error());
|
||||
}
|
||||
self.execute_request(sql, 0, 0, cancel, session).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn ping(&self) -> IdeResult<()> {
|
||||
let cancel = CancellationToken::new();
|
||||
if !self.0.use_http_session {
|
||||
return self.execute("SELECT 1", 1, &cancel).await.map(|_| ());
|
||||
}
|
||||
let mut result = Ok(());
|
||||
let consoles = self.0.console_sessions.lock().values().cloned().collect::<Vec<_>>();
|
||||
let sessions = std::iter::once(&self.0.session).chain(consoles.iter().map(Arc::as_ref));
|
||||
for slot in sessions {
|
||||
// A running query already keeps its session active.
|
||||
if let Ok(mut slot) = slot.try_lock()
|
||||
&& let Some(session) = slot.as_mut()
|
||||
&& let Err(error) = self.execute_request("SELECT 1", 0, 1, &cancel, session).await
|
||||
{
|
||||
result = result.and(Err(error));
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub fn release_console(&self, console: ConsoleId<'_>) {
|
||||
self.0.console_sessions.lock().remove(&(console.window.into(), console.path.into()));
|
||||
}
|
||||
|
||||
pub fn close(&self) {
|
||||
self.0.closed.cancel();
|
||||
self.0.console_sessions.lock().clear();
|
||||
self.0.client.write().take();
|
||||
}
|
||||
|
||||
@@ -221,19 +287,56 @@ impl ClickhousePool {
|
||||
}
|
||||
|
||||
/// `max_rows`: the rows the server may send (the skipped ones included).
|
||||
fn request(&self, client: &Client, query_id: &str, max_rows: usize, session: &Session) -> RequestBuilder {
|
||||
fn request(
|
||||
&self,
|
||||
client: &Client,
|
||||
query_id: &str,
|
||||
max_rows: usize,
|
||||
session: &Session,
|
||||
workspace_bytes: Option<usize>,
|
||||
) -> RequestBuilder {
|
||||
let mut request = client
|
||||
.post(self.0.endpoint.clone())
|
||||
.basic_auth(&self.0.user, Some(&self.0.password))
|
||||
.header(reqwest::header::CONTENT_TYPE, "text/plain; charset=utf-8")
|
||||
.query(&self.0.settings)
|
||||
.query(&[("query_id", query_id), ("default_format", FORMAT)]);
|
||||
if workspace_bytes.is_some() && !session.strict_read_only {
|
||||
let settings: Vec<_> = self
|
||||
.0
|
||||
.settings
|
||||
.iter()
|
||||
.filter(|(name, _)| !matches!(name.as_str(), "read_overflow_mode" | "timeout_overflow_mode"))
|
||||
.collect();
|
||||
request = request.query(&settings);
|
||||
} else {
|
||||
request = request.query(&self.0.settings);
|
||||
}
|
||||
if !session.strict_read_only {
|
||||
request = request.query(&[
|
||||
("output_format_json_quote_denormals", "1".into()),
|
||||
("max_result_rows", max_rows.saturating_add(1).to_string()),
|
||||
("result_overflow_mode", "break".into()),
|
||||
]);
|
||||
if let Some(bytes) = workspace_bytes {
|
||||
request = request.query(&[
|
||||
("max_result_rows", max_rows.to_string()),
|
||||
("result_overflow_mode", "throw".into()),
|
||||
("read_overflow_mode", "throw".into()),
|
||||
("timeout_overflow_mode", "throw".into()),
|
||||
]);
|
||||
for (name, value) in [
|
||||
("max_result_bytes", bytes),
|
||||
("max_execution_time", 20),
|
||||
("cancel_http_readonly_queries_on_client_close", 1),
|
||||
("max_rows_to_read", 1_000_000),
|
||||
("max_bytes_to_read", 268_435_456),
|
||||
] {
|
||||
if !self.0.settings.iter().any(|(setting, _)| setting == name) {
|
||||
request = request.query(&[(name, value)]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
request = request.query(&[
|
||||
("output_format_json_quote_denormals", "1".into()),
|
||||
("max_result_rows", max_rows.saturating_add(1).to_string()),
|
||||
("result_overflow_mode", "break".into()),
|
||||
]);
|
||||
}
|
||||
}
|
||||
if let Some(session_id) = &session.id {
|
||||
request = request.query(&[("session_id", session_id.as_str()), ("session_timeout", "3600")]);
|
||||
@@ -261,22 +364,70 @@ impl ClickhousePool {
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
self.execute_in_console(sql, skip, max_rows, cancel, None).await
|
||||
}
|
||||
|
||||
pub async fn execute_in_console(
|
||||
&self,
|
||||
sql: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
console: Option<ConsoleId<'_>>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
if transaction_statement(sql) {
|
||||
return Err(transaction_error());
|
||||
}
|
||||
let mut session = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
() = self.0.closed.cancelled() => return Err(IdeError::new(ErrorKind::Io, "ClickHouse connection is closed")),
|
||||
session = self.0.session.lock() => session,
|
||||
};
|
||||
let console_slot = console.filter(|_| self.0.use_http_session).map(|console| {
|
||||
self.0.console_sessions.lock().entry((console.window.into(), console.path.into())).or_default().clone()
|
||||
});
|
||||
let slot = console_slot.as_deref().unwrap_or(&self.0.session);
|
||||
let mut session = self.session(slot, cancel).await?;
|
||||
let state = session.as_mut().expect("session was initialized");
|
||||
if self.0.use_http_session {
|
||||
self.execute_request(sql, skip, max_rows, cancel, state).await
|
||||
} else {
|
||||
// Stateless requests use the setup's read-only flags, and have no server session to lock.
|
||||
let mut request = state.clone();
|
||||
drop(session);
|
||||
self.execute_request(sql, skip, max_rows, cancel, &mut request).await
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_request(
|
||||
&self,
|
||||
sql: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
session: &mut Session,
|
||||
) -> IdeResult<QueryResult> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let client = self.client()?;
|
||||
if session.id.is_none() && session_set_statement(sql) {
|
||||
return Err(IdeError::invalid(
|
||||
"Standalone SET needs a ClickHouse HTTP session. Set use_http_session=true in Advanced or use query-level SETTINGS where applicable.",
|
||||
));
|
||||
}
|
||||
let query_id = uuid::Uuid::new_v4().to_string();
|
||||
let request = self.request(&client, &query_id, skip.saturating_add(max_rows), &session).body(sql.to_owned());
|
||||
let request =
|
||||
self.request(&client, &query_id, skip.saturating_add(max_rows), session, None).body(sql.to_owned());
|
||||
let started = Instant::now();
|
||||
let request_error = |error: reqwest::Error| {
|
||||
if error.is_timeout() && !error.is_connect() {
|
||||
IdeError::new(
|
||||
ErrorKind::TimedOut,
|
||||
format!("ClickHouse HTTP response timed out. The query outcome is unknown (query_id={query_id})."),
|
||||
)
|
||||
} else {
|
||||
http_error(error)
|
||||
}
|
||||
};
|
||||
let fetch = async {
|
||||
let mut response = request.send().await.map_err(http_error)?;
|
||||
let mut response = request.send().await.map_err(request_error)?;
|
||||
let execution_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
let status = response.status();
|
||||
let header = |name: &str| response.headers().get(name).and_then(|v| v.to_str().ok()).map(str::to_owned);
|
||||
@@ -289,11 +440,11 @@ impl ClickhousePool {
|
||||
.and_then(|n| n.as_str().and_then(|n| n.parse::<u64>().ok()).or_else(|| n.as_u64()))
|
||||
});
|
||||
if !status.is_success() || exception_code.as_deref().is_some_and(|code| code != "0") {
|
||||
let body = response.bytes().await.map_err(http_error)?;
|
||||
let body = response_prefix(response).await.map_err(request_error)?;
|
||||
return Err(self.server_error(status, exception_code.as_deref(), &body));
|
||||
}
|
||||
let (columns, rows, has_more) = if format.as_deref().is_some_and(|f| f != FORMAT) {
|
||||
let body = response.bytes().await.map_err(http_error)?;
|
||||
let body = response.bytes().await.map_err(request_error)?;
|
||||
if !body.iter().all(u8::is_ascii_whitespace) {
|
||||
return Err(IdeError::invalid(
|
||||
"ClickHouse result grids need the default output format; remove the query's FORMAT clause",
|
||||
@@ -302,7 +453,7 @@ impl ClickhousePool {
|
||||
(Vec::new(), Vec::new(), false)
|
||||
} else {
|
||||
let mut reader = RowReader::new(skip, max_rows);
|
||||
while let Some(chunk) = response.chunk().await.map_err(http_error)? {
|
||||
while let Some(chunk) = response.chunk().await.map_err(request_error)? {
|
||||
reader.push(&chunk)?;
|
||||
}
|
||||
reader.finish().map_err(|error| self.redact_error(error))?
|
||||
@@ -333,7 +484,7 @@ impl ClickhousePool {
|
||||
result
|
||||
}
|
||||
None => {
|
||||
let killed = self.kill(&client, &query_id, &session).await;
|
||||
let killed = self.kill(&client, &query_id, session).await;
|
||||
match killed {
|
||||
Ok(()) => Err(IdeError::cancelled()),
|
||||
Err(error) => Err(IdeError::new(
|
||||
@@ -345,6 +496,66 @@ impl ClickhousePool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Dedicated workspace sessions consume the response before any grid truncation or formatting.
|
||||
pub(crate) async fn workspace_rows(
|
||||
&self,
|
||||
sql: &str,
|
||||
max_rows: usize,
|
||||
max_bytes: usize,
|
||||
cancel: &CancellationToken,
|
||||
mut consume: impl FnMut(&[u8]) -> IdeResult<()>,
|
||||
) -> IdeResult<()> {
|
||||
let mut slot = self.session(&self.0.session, cancel).await?;
|
||||
let state = slot.as_mut().expect("session was initialized");
|
||||
let mut stateless;
|
||||
let session = if self.0.use_http_session {
|
||||
state
|
||||
} else {
|
||||
stateless = state.clone();
|
||||
drop(slot);
|
||||
&mut stateless
|
||||
};
|
||||
let client = self.client()?;
|
||||
let query_id = uuid::Uuid::new_v4().to_string();
|
||||
let request = self.request(&client, &query_id, max_rows, session, Some(max_bytes)).body(sql.to_owned());
|
||||
let fetch = async {
|
||||
let mut response = request.send().await.map_err(http_error)?;
|
||||
let status = response.status();
|
||||
let metadata = |name: &str| response.headers().get(name).and_then(|v| v.to_str().ok());
|
||||
let code = metadata("X-ClickHouse-Exception-Code").map(str::to_owned);
|
||||
if !status.is_success() || code.as_deref().is_some_and(|code| code != "0") {
|
||||
let body = response_prefix(response).await.map_err(http_error)?;
|
||||
return Err(self.server_error(status, code.as_deref(), &body));
|
||||
}
|
||||
if metadata("X-ClickHouse-Format").is_some_and(|format| format != FORMAT) {
|
||||
return Err(IdeError::invalid("ClickHouse did not return the workspace response format"));
|
||||
}
|
||||
let mut received = 0;
|
||||
while let Some(chunk) = response.chunk().await.map_err(http_error)? {
|
||||
received += chunk.len();
|
||||
if received > max_bytes {
|
||||
return Err(IdeError::invalid("Workspace input exceeds the source byte limit"));
|
||||
}
|
||||
consume(&chunk)?;
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
() = self.0.closed.cancelled() => Err(IdeError::cancelled()),
|
||||
() = tokio::time::sleep(Duration::from_secs(25)) =>
|
||||
Err(IdeError::new(ErrorKind::TimedOut, "Workspace ClickHouse source read timed out")),
|
||||
result = fetch => result,
|
||||
};
|
||||
if result.is_ok() {
|
||||
session.initialized = true;
|
||||
} else {
|
||||
let _ = self.kill(&client, &query_id, session).await;
|
||||
}
|
||||
result.map_err(|e| self.redact_error(e))
|
||||
}
|
||||
|
||||
async fn kill(&self, client: &Client, query_id: &str, session: &Session) -> IdeResult<()> {
|
||||
let mut request = client
|
||||
.post(self.0.endpoint.clone())
|
||||
@@ -361,7 +572,7 @@ impl ClickhousePool {
|
||||
.get("X-ClickHouse-Exception-Code")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_owned);
|
||||
let body = response.bytes().await.map_err(http_error)?;
|
||||
let body = response_prefix(response).await.map_err(http_error)?;
|
||||
if status.is_success() && !code.as_deref().is_some_and(|code| code != "0") && !body.starts_with(b"Code:") {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -390,6 +601,17 @@ impl ClickhousePool {
|
||||
}
|
||||
}
|
||||
|
||||
async fn response_prefix(mut response: reqwest::Response) -> Result<Vec<u8>, reqwest::Error> {
|
||||
const LIMIT: usize = 16_384;
|
||||
let mut body = Vec::new();
|
||||
while body.len() < LIMIT {
|
||||
let Some(chunk) = response.chunk().await? else { break };
|
||||
let remaining = LIMIT - body.len();
|
||||
body.extend_from_slice(&chunk[..chunk.len().min(remaining)]);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
type DecodedResult = (Vec<ResultColumn>, Vec<Vec<Option<String>>>, bool);
|
||||
|
||||
/// Decodes a streamed [`FORMAT`] body. Reads past the first `skip` rows unparsed (a later
|
||||
@@ -596,6 +818,13 @@ fn reserved_setting(name: &str) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
fn session_set_statement(mut sql: &str) -> bool {
|
||||
let mut next_is =
|
||||
|word: &str| crate::split::clickhouse_keyword(&mut sql).is_some_and(|part| part.eq_ignore_ascii_case(word));
|
||||
// SET DEFAULT ROLE persists a user's default roles outside the current session.
|
||||
next_is("SET") && !(next_is("DEFAULT") && next_is("ROLE"))
|
||||
}
|
||||
|
||||
fn transaction_statement(sql: &str) -> bool {
|
||||
let mut sql = sql.trim_start();
|
||||
loop {
|
||||
@@ -832,6 +1061,71 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stateless_session_settings_are_refused_before_sending() {
|
||||
let (port, requests) = server(vec![("200 OK", "", ONE), ("200 OK", "", ONE), ("200 OK", "", "")]).await;
|
||||
let source = DataSource { properties: vec![property("use_http_session", "false")], ..source(port) };
|
||||
let pool = Pool::connect(&source, None, None).await.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
for statement in [
|
||||
"SET log_comment='openidea-test'",
|
||||
"-- leading\n/* outer /* nested */ tail */ SeT `log_comment`='a;b', max_threads=1",
|
||||
"# leading\nSET ROLE NONE",
|
||||
"SET profile='test'",
|
||||
"SET TIME ZONE 'UTC'",
|
||||
] {
|
||||
let error = pool.execute(statement, 1, &cancel).await.expect_err("stateless SET must fail locally");
|
||||
assert_eq!(error.kind, ErrorKind::InvalidInput);
|
||||
assert!(error.message.contains("use_http_session=true"), "{error}");
|
||||
assert!(error.message.contains("query-level SETTINGS"), "{error}");
|
||||
}
|
||||
let stopped = CancellationToken::new();
|
||||
stopped.cancel();
|
||||
assert_eq!(
|
||||
pool.execute("SET log_comment='not sent'", 1, &stopped).await.unwrap_err().kind,
|
||||
ErrorKind::Cancelled
|
||||
);
|
||||
|
||||
// A query-level setting and a persistent role change both still reach the server.
|
||||
let select = "SELECT 'SET;' LIMIT 1 SETTINGS log_comment='local' FORMAT JSONCompactEachRowWithNamesAndTypes";
|
||||
pool.execute(select, 1, &cancel).await.unwrap();
|
||||
let default_role = "SET /* persistent */ DEFAULT # on login\n ROLE NONE TO fixture_user";
|
||||
pool.execute(default_role, 0, &cancel).await.unwrap();
|
||||
let requests = requests.await.unwrap();
|
||||
assert!(requests[0].ends_with("SELECT 1"));
|
||||
assert!(requests[1].ends_with(select));
|
||||
assert!(requests[2].ends_with(default_role));
|
||||
assert!(requests.iter().all(|request| query_value(&request_url(request), "session_id").is_none()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires the disposable ClickHouse fixture on loopback"]
|
||||
async fn clickhouse_live_http_session_settings() -> IdeResult<()> {
|
||||
let port = std::env::var("OPENIDEA_CLICKHOUSE_SET_PORT").unwrap().parse().unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let read = "SELECT concat('[', getSetting('log_comment'), ']') LIMIT 1";
|
||||
for (session, expected) in [("false", "[]"), ("true", "[openidea-test]")] {
|
||||
let source = DataSource {
|
||||
user: "set_fixture".into(),
|
||||
properties: vec![property("use_http_session", session)],
|
||||
..source(port)
|
||||
};
|
||||
let pool = Pool::connect(&source, None, None).await?;
|
||||
let result = pool.execute("SET log_comment='openidea-test'", 1, &cancel).await;
|
||||
if session == "true" {
|
||||
result?;
|
||||
} else {
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::InvalidInput);
|
||||
assert!(error.message.contains("use_http_session=true"), "{error}");
|
||||
let local = format!("{read} SETTINGS log_comment='one-query'");
|
||||
assert_eq!(pool.execute(&local, 1, &cancel).await?.rows, [vec![Some("[one-query]".into())]]);
|
||||
}
|
||||
assert_eq!(pool.execute(read, 1, &cancel).await?.rows, [vec![Some(expected.into())]]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stateless_requests_keep_database_settings_readonly_and_limits() {
|
||||
let (port, requests) = server(vec![("200 OK", "", ONE); 3]).await;
|
||||
@@ -898,6 +1192,90 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stalled_http_response_reports_unknown_outcome_with_query_id() {
|
||||
for prefix in [
|
||||
"",
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n",
|
||||
"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 128\r\nConnection: close\r\n\r\nCode:",
|
||||
] {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let fixture = tokio::spawn(async move {
|
||||
let (mut probe, _) = listener.accept().await.unwrap();
|
||||
read_request(&mut probe).await;
|
||||
reply(&mut probe, "200 OK", "", ONE).await;
|
||||
drop(probe);
|
||||
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let request = read_request(&mut stream).await;
|
||||
let id = query_value(&request_url(&request), "query_id").unwrap();
|
||||
stream.write_all(prefix.as_bytes()).await.unwrap();
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(4), stream.read(&mut [0])).await.unwrap().unwrap(),
|
||||
0
|
||||
);
|
||||
assert_eq!(query_value(&request_url(&request), "http_read_timeout"), None);
|
||||
id
|
||||
});
|
||||
let source = DataSource { properties: vec![property("http_read_timeout", "1")], ..source(port) };
|
||||
let pool = Pool::connect(&source, None, None).await.unwrap();
|
||||
let error = tokio::time::timeout(
|
||||
Duration::from_secs(3),
|
||||
pool.execute("DELETE FROM fixture WHERE id = 1", 0, &CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
.expect("ClickHouse must stop waiting for a stalled response")
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind, ErrorKind::TimedOut);
|
||||
assert!(error.message.contains("outcome is unknown"), "{error}");
|
||||
let id = fixture.await.unwrap();
|
||||
assert!(error.message.contains(&format!("query_id={id}")), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_timeout_resets_while_response_keeps_arriving() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let fixture = tokio::spawn(async move {
|
||||
let (mut probe, _) = listener.accept().await.unwrap();
|
||||
read_request(&mut probe).await;
|
||||
reply(&mut probe, "200 OK", "", ONE).await;
|
||||
drop(probe);
|
||||
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
read_request(&mut stream).await;
|
||||
let (first, rest) = ONE.split_at(6);
|
||||
let headers = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", ONE.len());
|
||||
stream.write_all(headers.as_bytes()).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(1100)).await;
|
||||
stream.write_all(first.as_bytes()).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(1100)).await;
|
||||
stream.write_all(rest.as_bytes()).await.unwrap();
|
||||
});
|
||||
let source = DataSource { properties: vec![property("http_read_timeout", "2")], ..source(port) };
|
||||
let pool = Pool::connect(&source, None, None).await.unwrap();
|
||||
let result = pool.execute("SELECT 1", 1, &CancellationToken::new()).await.unwrap();
|
||||
assert_eq!(result.rows, vec![vec![Some("1".into())]]);
|
||||
fixture.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_read_timeout_rejects_invalid_or_duplicate_values() {
|
||||
for properties in [
|
||||
vec![property("http_read_timeout", "0")],
|
||||
vec![property("http_read_timeout", "1.5")],
|
||||
vec![property("http_read_timeout", "4294967296")],
|
||||
vec![property("http_read_timeout", "1"), property("HTTP-READ-TIMEOUT", "2")],
|
||||
] {
|
||||
let source = DataSource { properties, ..source(0) };
|
||||
let error = Pool::connect(&source, None, None).await.err().unwrap();
|
||||
assert_eq!(error.kind, ErrorKind::InvalidInput);
|
||||
assert!(error.message.contains("http_read_timeout"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sequential_queries_reuse_the_http_connection() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
@@ -1151,6 +1529,84 @@ mod tests {
|
||||
requests.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn console_sessions_have_distinct_http_ids() {
|
||||
let (port, requests) = server(vec![("200 OK", "", ONE); 8]).await;
|
||||
let Pool::Clickhouse(pool) = Pool::connect(&source(port), None, None).await.unwrap() else { unreachable!() };
|
||||
let first = ConsoleId::new("main", "console.sql");
|
||||
let second = ConsoleId::new("main", "console_1.sql");
|
||||
let cancel = CancellationToken::new();
|
||||
for console in [first, second, first] {
|
||||
pool.execute_in_console("SELECT 2", 0, 1, &cancel, Some(console)).await.unwrap();
|
||||
}
|
||||
pool.release_console(second);
|
||||
pool.ping().await.unwrap();
|
||||
let requests = requests.await.unwrap();
|
||||
let ids = requests
|
||||
.iter()
|
||||
.map(|request| query_value(&request_url(request), "session_id").unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert_ne!(ids[0], ids[1]);
|
||||
assert_ne!(ids[1], ids[3]);
|
||||
assert_eq!(ids[1], ids[2]);
|
||||
assert_eq!(ids[3], ids[4]);
|
||||
assert_eq!(ids[1], ids[5]);
|
||||
assert_eq!(ids[0], ids[6]);
|
||||
assert_eq!(ids[1], ids[7]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stateless_queries_do_not_wait_for_a_shared_session() {
|
||||
assert_stateless_requests_overlap(false).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stateless_workspace_reads_do_not_block_queries() {
|
||||
assert_stateless_requests_overlap(true).await;
|
||||
}
|
||||
|
||||
async fn assert_stateless_requests_overlap(workspace: bool) {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let (started, received) = tokio::sync::oneshot::channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut probe, _) = listener.accept().await.unwrap();
|
||||
read_request(&mut probe).await;
|
||||
reply(&mut probe, "200 OK", "", ONE).await;
|
||||
let (mut first, _) = listener.accept().await.unwrap();
|
||||
let first_request = read_request(&mut first).await;
|
||||
started.send(()).unwrap();
|
||||
let (mut second, _) = listener.accept().await.unwrap();
|
||||
let second_request = read_request(&mut second).await;
|
||||
reply(&mut second, "200 OK", "", ONE).await;
|
||||
reply(&mut first, "200 OK", "", ONE).await;
|
||||
(first_request, second_request)
|
||||
});
|
||||
let source = DataSource { properties: vec![property("use_http_session", "false")], ..source(port) };
|
||||
let Pool::Clickhouse(pool) = Pool::connect(&source, None, None).await.unwrap() else { unreachable!() };
|
||||
let cancel = CancellationToken::new();
|
||||
let first = async {
|
||||
if workspace {
|
||||
pool.workspace_rows("SELECT 1", 1, 1024, &cancel, |_| Ok(())).await
|
||||
} else {
|
||||
pool.execute("SELECT 1", 1, &cancel).await.map(drop)
|
||||
}
|
||||
};
|
||||
let second = async {
|
||||
received.await.unwrap();
|
||||
pool.execute("SELECT 2", 1, &cancel).await
|
||||
};
|
||||
let (first, second) = tokio::time::timeout(Duration::from_secs(5), async { tokio::join!(first, second) })
|
||||
.await
|
||||
.expect("both requests should reach the server");
|
||||
first.unwrap();
|
||||
second.unwrap();
|
||||
let (first, second) = server.await.unwrap();
|
||||
for request in [first, second] {
|
||||
assert_eq!(query_value(&request_url(&request), "session_id"), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_sends_kill_outside_the_busy_session() {
|
||||
for stateless in [false, true] {
|
||||
|
||||
@@ -1000,6 +1000,7 @@ impl Pool {
|
||||
pub async fn ping(&self) -> IdeResult<()> {
|
||||
match self {
|
||||
Pool::Jdbc(p) => p.ping().await,
|
||||
Pool::Clickhouse(p) => p.ping().await,
|
||||
_ => self.rows(self.ping_sql(), 1).await.map(|_| ()),
|
||||
}
|
||||
}
|
||||
@@ -1329,6 +1330,71 @@ impl Pool {
|
||||
Ok(conn.finish_read_only(owned, result).await?.1)
|
||||
}
|
||||
|
||||
pub(crate) async fn read_workspace_postgres(
|
||||
&self,
|
||||
request: &crate::workspace_input::WorkspaceInputRequest,
|
||||
selection: Option<&[&str]>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<crate::workspace_input::WorkspaceInput> {
|
||||
let Pool::Postgres(pool) = self else {
|
||||
return Err(IdeError::internal("Expected a PostgreSQL workspace connection"));
|
||||
};
|
||||
let mut conn = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
result = pool.get() => result?,
|
||||
};
|
||||
let mut backend = None;
|
||||
let read = async {
|
||||
if conn.options.read_only == PgReadOnly::Transaction {
|
||||
conn.start_read_only().await?;
|
||||
} else {
|
||||
sqlx::raw_sql("BEGIN READ ONLY").execute(&mut **conn).await.map_err(db_err)?;
|
||||
}
|
||||
let row = sqlx::raw_sql(
|
||||
"SELECT pg_catalog.pg_backend_pid(), pg_catalog.current_setting('transaction_read_only') = 'on'",
|
||||
)
|
||||
.fetch_one(&mut **conn)
|
||||
.await
|
||||
.map_err(db_err)?;
|
||||
backend = Some(row.try_get::<i32, _>(0).map_err(db_err)?);
|
||||
if !row.try_get::<bool, _>(1).map_err(db_err)? {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::PermissionDenied,
|
||||
"Workspace PostgreSQL transaction is not read-only",
|
||||
));
|
||||
}
|
||||
crate::workspace_input::read_postgres(&mut conn, request, selection).await
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => Err(IdeError::cancelled()),
|
||||
() = tokio::time::sleep(Duration::from_secs(30)) =>
|
||||
Err(IdeError::new(ErrorKind::TimedOut, "Workspace PostgreSQL source read timed out")),
|
||||
result = read => result,
|
||||
};
|
||||
if result.is_ok() {
|
||||
// Do not send a PID-based cancel once a pooler may have released this backend.
|
||||
let rollback =
|
||||
tokio::time::timeout(Duration::from_secs(3), sqlx::raw_sql("ROLLBACK").execute(&mut **conn)).await;
|
||||
if matches!(rollback, Ok(Ok(_))) {
|
||||
conn.in_transaction = false;
|
||||
} else {
|
||||
conn.conn.take();
|
||||
}
|
||||
} else {
|
||||
if let Some(pid) = backend {
|
||||
let _ = tokio::time::timeout(
|
||||
Duration::from_secs(3),
|
||||
self.cancel_query(format!("SELECT pg_catalog.pg_cancel_backend({pid})")),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
conn.conn.take();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Runs one statement and keeps at most `max_rows` rows. Cancelling stops
|
||||
/// the statement on the server (PostgreSQL, MySQL) and drops the connection.
|
||||
pub async fn execute(&self, sql: &str, max_rows: usize, cancel: &CancellationToken) -> IdeResult<QueryResult> {
|
||||
|
||||
@@ -30,6 +30,7 @@ pub(crate) struct Key {
|
||||
target: String,
|
||||
statement: String,
|
||||
schema: Option<String>,
|
||||
console: Option<(String, String)>,
|
||||
}
|
||||
|
||||
impl Key {
|
||||
@@ -38,8 +39,14 @@ impl Key {
|
||||
target: target.to_owned(),
|
||||
statement: statement.to_owned(),
|
||||
schema: schema.filter(|s| !s.is_empty()).map(str::to_owned),
|
||||
console: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_console(mut self, console: Option<crate::ConsoleId<'_>>) -> Self {
|
||||
self.console = console.map(|console| (console.window.to_owned(), console.path.to_owned()));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A request for the next rows of a cursor's statement.
|
||||
@@ -186,6 +193,14 @@ impl Cursors {
|
||||
self.registry.lock().slots.retain(|s| s.key != *key);
|
||||
}
|
||||
|
||||
pub(crate) fn release_console(&self, console: crate::ConsoleId<'_>, target: Option<&str>) {
|
||||
self.registry.lock().slots.retain(|slot| {
|
||||
let key = &slot.key;
|
||||
!target.is_none_or(|target| key.target == target)
|
||||
|| !key.console.as_ref().is_some_and(|(window, path)| window == console.window && path == console.path)
|
||||
});
|
||||
}
|
||||
|
||||
/// Closes the cursors of `target`: it disconnects, or a statement that changes
|
||||
/// data or schema is about to run there.
|
||||
pub(crate) fn release_target(&self, target: &str) {
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use parking_lot::Mutex;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
path::Path,
|
||||
process::Stdio,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
|
||||
process::Command,
|
||||
sync::{mpsc, oneshot},
|
||||
time::{Instant, timeout, timeout_at},
|
||||
};
|
||||
|
||||
const LIMIT: usize = 16 * 1024 * 1024;
|
||||
const HEADER: usize = 16;
|
||||
const CANCEL_GRACE: Duration = Duration::from_secs(3);
|
||||
type Replies = Arc<Mutex<HashMap<u64, mpsc::Sender<Vec<u8>>>>>;
|
||||
|
||||
pub(super) struct Bridge {
|
||||
closed: CancellationToken,
|
||||
exited: CancellationToken,
|
||||
sequence: AtomicU64,
|
||||
outgoing: mpsc::Sender<Outgoing>,
|
||||
replies: Replies,
|
||||
}
|
||||
|
||||
struct Outgoing {
|
||||
frame: Vec<u8>,
|
||||
session: CancellationToken,
|
||||
sent: oneshot::Sender<IdeResult<()>>,
|
||||
}
|
||||
|
||||
struct Pending<'a> {
|
||||
bridge: &'a Bridge,
|
||||
id: u64,
|
||||
incoming: mpsc::Receiver<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Drop for Pending<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.bridge.replies.lock().remove(&self.id);
|
||||
}
|
||||
}
|
||||
|
||||
impl Pending<'_> {
|
||||
async fn recv(&mut self) -> IdeResult<Vec<u8>> {
|
||||
tokio::select! {
|
||||
biased;
|
||||
frame = self.incoming.recv() => frame.ok_or_else(disconnected),
|
||||
() = self.bridge.closed.cancelled() => Err(disconnected()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Bridge {
|
||||
pub(super) fn start(cache: &Path, jars: &[String]) -> IdeResult<Self> {
|
||||
let jdks = ide_sdk::java::installed_jdks();
|
||||
let java = ide_sdk::java::java_runtime(&jdks, 17)
|
||||
.ok_or_else(|| IdeError::invalid("Install a Java 17 or newer runtime to use custom JDBC drivers"))?;
|
||||
let jar = ide_sdk::java::jdbc_bridge_jar(cache)
|
||||
.ok_or_else(|| IdeError::invalid("Cannot install the JDBC bridge in the application data directory"))?;
|
||||
let classpath = std::env::join_paths(std::iter::once(jar.as_path()).chain(jars.iter().map(Path::new)))
|
||||
.map_err(|_| IdeError::invalid("A JDBC JAR path contains the system classpath separator"))?;
|
||||
// Embedded databases can resolve file URLs against the JVM's working directory.
|
||||
let files = cache.join("files");
|
||||
std::fs::create_dir_all(&files)?;
|
||||
let mut command = Command::new(ide_sdk::java::java_executable(&java.home));
|
||||
command.current_dir(files);
|
||||
ide_core::process::prepare(command.as_std_mut());
|
||||
let mut child = command
|
||||
.args(["-Xms8m", "-Xmx192m", "--enable-native-access=ALL-UNNAMED", "-cp"])
|
||||
.arg(classpath)
|
||||
.args(["ai.openidea.jdbc.OpenIdeaJdbc", "--multiplex"])
|
||||
.env_remove("CLASSPATH")
|
||||
.env_remove("JDK_JAVA_OPTIONS")
|
||||
.env_remove("JAVA_TOOL_OPTIONS")
|
||||
.env_remove("_JAVA_OPTIONS")
|
||||
.kill_on_drop(true)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()?;
|
||||
let input = child.stdin.take().expect("piped");
|
||||
let output = child.stdout.take().expect("piped");
|
||||
let closed = CancellationToken::new();
|
||||
let exited = CancellationToken::new();
|
||||
tokio::spawn({
|
||||
let closed = closed.clone();
|
||||
let exited = exited.clone();
|
||||
async move {
|
||||
tokio::select! {
|
||||
_ = child.wait() => {}
|
||||
() = closed.cancelled() => {
|
||||
// The writer drops stdin. Give file-based drivers time to flush.
|
||||
if timeout(Duration::from_secs(2), child.wait()).await.is_err() {
|
||||
let _ = child.kill().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
closed.cancel();
|
||||
exited.cancel();
|
||||
}
|
||||
});
|
||||
Ok(Self::with_io(input, output, closed, exited))
|
||||
}
|
||||
|
||||
fn with_io(
|
||||
input: impl AsyncWrite + Unpin + Send + 'static,
|
||||
output: impl AsyncRead + Unpin + Send + 'static,
|
||||
closed: CancellationToken,
|
||||
exited: CancellationToken,
|
||||
) -> Self {
|
||||
let (outgoing, writes) = mpsc::channel(4);
|
||||
let replies = Replies::default();
|
||||
tokio::spawn(write_frames(input, writes, closed.clone()));
|
||||
tokio::spawn(read_frames(output, replies.clone(), closed.clone()));
|
||||
Self { closed, exited, sequence: AtomicU64::new(1), outgoing, replies }
|
||||
}
|
||||
|
||||
pub(super) fn shutdown(&self) {
|
||||
self.closed.cancel();
|
||||
}
|
||||
|
||||
pub(super) fn is_closed(&self) -> bool {
|
||||
self.closed.is_cancelled()
|
||||
}
|
||||
|
||||
pub(super) async fn close(&self) {
|
||||
self.shutdown();
|
||||
self.exited.cancelled().await;
|
||||
}
|
||||
|
||||
async fn send(&self, frame: Vec<u8>, session: &CancellationToken) -> IdeResult<()> {
|
||||
let (sent, receipt) = oneshot::channel();
|
||||
tokio::select! {
|
||||
() = self.closed.cancelled() => return Err(disconnected()),
|
||||
result = self.outgoing.send(Outgoing { frame, session: session.clone(), sent }) => {
|
||||
result.map_err(|_| disconnected())?;
|
||||
}
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = receipt => result.map_err(|_| disconnected())?,
|
||||
() = self.closed.cancelled() => Err(disconnected()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn exchange(
|
||||
&self,
|
||||
session: u32,
|
||||
fields: &[&str],
|
||||
cancel: &CancellationToken,
|
||||
active: &CancellationToken,
|
||||
) -> IdeResult<Option<Vec<u8>>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Ok(None);
|
||||
}
|
||||
if active.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let id = self
|
||||
.sequence
|
||||
.try_update(Ordering::Relaxed, Ordering::Relaxed, |next| next.checked_add(1))
|
||||
.map_err(|_| IdeError::internal("JDBC request IDs exhausted"))?;
|
||||
let frame = encode(id, session, fields)?;
|
||||
let (sender, incoming) = mpsc::channel(2);
|
||||
self.replies.lock().insert(id, sender);
|
||||
let mut pending = Pending { bridge: self, id, incoming };
|
||||
let send = self.send(frame, active);
|
||||
tokio::pin!(send);
|
||||
let early_deadline = tokio::select! {
|
||||
result = &mut send => { result?; None },
|
||||
() = cancel.cancelled() => {
|
||||
let end = Instant::now() + CANCEL_GRACE;
|
||||
timeout_at(end, send).await.map_err(|_| cancel_timeout())??;
|
||||
Some(end)
|
||||
}
|
||||
};
|
||||
let deadline = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => early_deadline.unwrap_or_else(|| Instant::now() + CANCEL_GRACE),
|
||||
data = pending.recv() => {
|
||||
let data = data?;
|
||||
if data.is_empty() { return Err(IdeError::invalid("Unexpected JDBC cancellation acknowledgement")); }
|
||||
return Ok(Some(data));
|
||||
}
|
||||
};
|
||||
let data = timeout_at(deadline, async {
|
||||
self.send(header(id, session, 0).to_vec(), active).await?;
|
||||
let first = pending.recv().await?;
|
||||
let second = pending.recv().await?;
|
||||
match (first.is_empty(), second.is_empty()) {
|
||||
(true, false) => Ok(second),
|
||||
(false, true) => Ok(first),
|
||||
_ => Err(IdeError::invalid("Invalid JDBC cancellation acknowledgement")),
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| cancel_timeout())??;
|
||||
match data.first() {
|
||||
// A committed statement may finish before the bridge receives Cancel.
|
||||
Some(1) => Ok(Some(data)),
|
||||
Some(0) => Ok(None),
|
||||
_ => Err(IdeError::invalid("Invalid JDBC cancellation response")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn close_session(&self, session: u32) -> IdeResult<()> {
|
||||
if self.is_closed() {
|
||||
return Ok(());
|
||||
}
|
||||
let control = CancellationToken::new();
|
||||
let data = timeout(CANCEL_GRACE, self.exchange(session, &["close"], &control, &control))
|
||||
.await
|
||||
.map_err(|_| IdeError::new(ErrorKind::TimedOut, "Closing the JDBC console timed out"))??;
|
||||
super::decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.).map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Bridge {
|
||||
fn drop(&mut self) {
|
||||
self.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
async fn write_frames(
|
||||
mut input: impl AsyncWrite + Unpin,
|
||||
mut writes: mpsc::Receiver<Outgoing>,
|
||||
closed: CancellationToken,
|
||||
) {
|
||||
while let Some(outgoing) = tokio::select! {
|
||||
biased;
|
||||
() = closed.cancelled() => None,
|
||||
outgoing = writes.recv() => outgoing,
|
||||
} {
|
||||
// If Close raced with an enqueued Open or query, discard it before writing.
|
||||
if outgoing.session.is_cancelled() {
|
||||
let _ = outgoing.sent.send(Err(IdeError::cancelled()));
|
||||
continue;
|
||||
}
|
||||
let result = tokio::select! {
|
||||
() = closed.cancelled() => break,
|
||||
result = input.write_all(&outgoing.frame) => result.map_err(IdeError::from),
|
||||
};
|
||||
let failed = result.is_err();
|
||||
let _ = outgoing.sent.send(result);
|
||||
if failed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
closed.cancel();
|
||||
}
|
||||
|
||||
async fn read_frames(mut output: impl AsyncRead + Unpin, replies: Replies, closed: CancellationToken) {
|
||||
loop {
|
||||
let frame = async {
|
||||
let id = output.read_u64().await?;
|
||||
Ok::<_, IdeError>((id, read_frame(&mut output).await?))
|
||||
};
|
||||
let (id, data) = match tokio::select! {
|
||||
() = closed.cancelled() => break,
|
||||
result = frame => result,
|
||||
} {
|
||||
Ok(frame) => frame,
|
||||
Err(_) => break,
|
||||
};
|
||||
let sender = replies.lock().get(&id).cloned();
|
||||
// A response may arrive after its caller was cancelled and retired.
|
||||
if let Some(sender) = sender
|
||||
&& matches!(sender.try_send(data), Err(mpsc::error::TrySendError::Full(_)))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
closed.cancel();
|
||||
}
|
||||
|
||||
fn disconnected() -> IdeError {
|
||||
IdeError::new(ErrorKind::Io, "JDBC connection was lost")
|
||||
}
|
||||
|
||||
fn cancel_timeout() -> IdeError {
|
||||
IdeError::invalid(
|
||||
"Cancellation timed out and the JDBC session was closed. Check the statement's status on the server before running it again. The next query will try to reconnect.",
|
||||
)
|
||||
}
|
||||
|
||||
fn header(id: u64, session: u32, fields: u32) -> [u8; HEADER] {
|
||||
let mut bytes = [0; HEADER];
|
||||
bytes[..8].copy_from_slice(&id.to_be_bytes());
|
||||
bytes[8..12].copy_from_slice(&session.to_be_bytes());
|
||||
bytes[12..].copy_from_slice(&fields.to_be_bytes());
|
||||
bytes
|
||||
}
|
||||
|
||||
pub(super) fn frame_size(fields: &[&str]) -> IdeResult<usize> {
|
||||
if fields.is_empty() || fields.len() > 8192 {
|
||||
return Err(IdeError::invalid("Invalid JDBC field count"));
|
||||
}
|
||||
fields
|
||||
.iter()
|
||||
.try_fold(HEADER, |n, s| n.checked_add(4)?.checked_add(s.len()).filter(|n| *n <= LIMIT))
|
||||
.ok_or_else(|| IdeError::invalid("JDBC request exceeds 16 MiB"))
|
||||
}
|
||||
|
||||
fn encode(id: u64, session: u32, fields: &[&str]) -> IdeResult<Vec<u8>> {
|
||||
let size = frame_size(fields)?;
|
||||
let mut data = Vec::with_capacity(size);
|
||||
data.extend_from_slice(&header(id, session, fields.len() as u32));
|
||||
for field in fields {
|
||||
data.extend_from_slice(&(field.len() as u32).to_be_bytes());
|
||||
data.extend_from_slice(field.as_bytes());
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
async fn read_frame(output: &mut (impl AsyncRead + Unpin)) -> IdeResult<Vec<u8>> {
|
||||
let n = output.read_u32().await? as usize;
|
||||
if n > LIMIT {
|
||||
return Err(IdeError::invalid("JDBC response exceeds 16 MiB"));
|
||||
}
|
||||
let mut data = vec![0; n];
|
||||
output.read_exact(&mut data).await?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn frame_codec_checks_both_16_mib_boundaries() {
|
||||
assert_eq!(encode(7, 3, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 1, b'a']);
|
||||
let mut field = "x".repeat(LIMIT - HEADER - 4);
|
||||
assert_eq!(encode(1, 0, &[&field]).unwrap().len(), LIMIT);
|
||||
field.push('x');
|
||||
assert!(encode(1, 0, &[&field]).is_err());
|
||||
let mut framed = vec![0u8; LIMIT + 4];
|
||||
framed[..4].copy_from_slice(&(LIMIT as u32).to_be_bytes());
|
||||
assert_eq!(read_frame(&mut framed.as_slice()).await.unwrap().len(), LIMIT);
|
||||
assert!(read_frame(&mut &((LIMIT + 1) as u32).to_be_bytes()[..]).await.is_err());
|
||||
assert!(read_frame(&mut &[0, 0, 0, 2, 1u8][..]).await.is_err());
|
||||
}
|
||||
|
||||
async fn reply(output: &mut (impl AsyncWrite + Unpin), id: u64, body: &[u8]) {
|
||||
output.write_u64(id).await.unwrap();
|
||||
output.write_u32(body.len() as u32).await.unwrap();
|
||||
output.write_all(body).await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn exchange_rejects_an_acknowledgement_for_an_uncancelled_request() {
|
||||
let (input, mut peer_input) = tokio::io::duplex(32);
|
||||
let (output, mut peer_output) = tokio::io::duplex(32);
|
||||
let active = CancellationToken::new();
|
||||
let bridge = Bridge::with_io(input, output, CancellationToken::new(), CancellationToken::new());
|
||||
let peer = async {
|
||||
let frame = encode(1, 0, &["query"]).unwrap();
|
||||
let mut actual = vec![0; frame.len()];
|
||||
peer_input.read_exact(&mut actual).await.unwrap();
|
||||
assert_eq!(actual, frame);
|
||||
reply(&mut peer_output, 1, &[]).await;
|
||||
};
|
||||
let (result, ()) = tokio::join!(bridge.exchange(0, &["query"], &active, &active), peer);
|
||||
assert!(result.unwrap_err().message.contains("Unexpected JDBC cancellation acknowledgement"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancellation_drains_tagged_replies_without_stealing_a_siblings_response() {
|
||||
for ack_first in [true, false] {
|
||||
let (input, mut peer_input) = tokio::io::duplex(1);
|
||||
let (output, mut peer_output) = tokio::io::duplex(1);
|
||||
let active = CancellationToken::new();
|
||||
let cancel = CancellationToken::new();
|
||||
let bridge = Bridge::with_io(input, output, CancellationToken::new(), CancellationToken::new());
|
||||
let peer = async {
|
||||
let frame = encode(1, 11, &["query"]).unwrap();
|
||||
let mut request = vec![0; frame.len()];
|
||||
peer_input.read_exact(&mut request).await.unwrap();
|
||||
assert_eq!(request, frame);
|
||||
peer_input.read_exact(&mut request).await.unwrap();
|
||||
assert_eq!(request, encode(2, 22, &["query"]).unwrap());
|
||||
|
||||
// Cancel during a partial reply header; the reader must stay on that frame.
|
||||
peer_output.write_all(&1u64.to_be_bytes()[..2]).await.unwrap();
|
||||
cancel.cancel();
|
||||
let mut stop = [0; HEADER];
|
||||
peer_input.read_exact(&mut stop).await.unwrap();
|
||||
assert_eq!(stop, header(1, 11, 0));
|
||||
|
||||
peer_output.write_all(&1u64.to_be_bytes()[2..]).await.unwrap();
|
||||
let terminal = !ack_first;
|
||||
peer_output.write_u32(u32::from(terminal)).await.unwrap();
|
||||
if terminal {
|
||||
peer_output.write_u8(1).await.unwrap();
|
||||
}
|
||||
reply(&mut peer_output, 2, &[1, b'b']).await;
|
||||
reply(&mut peer_output, 1, if ack_first { &[0] } else { &[] }).await;
|
||||
};
|
||||
let (a, b, ()) = tokio::join!(
|
||||
biased;
|
||||
bridge.exchange(11, &["query"], &cancel, &active),
|
||||
bridge.exchange(22, &["query"], &active, &active),
|
||||
peer,
|
||||
);
|
||||
assert_eq!(a.unwrap(), (!ack_first).then(|| vec![1]));
|
||||
assert_eq!(b.unwrap(), Some(vec![1, b'b']));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
use super::{DbJdbcDriver, JdbcPool};
|
||||
use crate::source::{DUCKDB_URL, duck_lake_path};
|
||||
use crate::{DataSource, DbDuckLake, DbDuckLakeKind, DbManager, Pool};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
|
||||
const DUCKDB_CLASS: &str = "org.duckdb.DuckDBDriver";
|
||||
|
||||
impl DbManager {
|
||||
pub fn approve_ducklake_source(&self, source: &DataSource) -> IdeResult<()> {
|
||||
if source.duck_lake.is_none() {
|
||||
return Err(IdeError::invalid("Expected a DuckLake data source"));
|
||||
}
|
||||
source.validate_duck_lake()?;
|
||||
self.duck_lake_driver(&source.jdbc_driver)?.validate()?;
|
||||
if source.global {
|
||||
return Ok(());
|
||||
}
|
||||
self.record_jdbc_approval(source)
|
||||
}
|
||||
|
||||
fn duck_lake_driver(&self, id: &str) -> IdeResult<DbJdbcDriver> {
|
||||
let driver = self.jdbc_driver_by_id(id)?;
|
||||
driver.require_vendor("duckdb")?;
|
||||
if driver.class_name != DUCKDB_CLASS {
|
||||
return Err(IdeError::invalid("Select a DuckDB driver profile with the official DuckDB JDBC driver class"));
|
||||
}
|
||||
Ok(driver)
|
||||
}
|
||||
|
||||
/// Creates a lake in a new directory through a separate, disposable JDBC session.
|
||||
pub async fn create_ducklake(&self, jdbc_driver: &str, directory: &str) -> IdeResult<()> {
|
||||
duck_lake_path(directory, false)?;
|
||||
let driver = self.duck_lake_driver(jdbc_driver)?;
|
||||
let fields = duck_lake_fields("create", directory.to_owned(), "");
|
||||
let pool = JdbcPool::open(driver, self.jdbc_registry()?.with_file_name("jdbc"), fields).await?;
|
||||
pool.close().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn open_ducklake(&self, source: &DataSource, lake: &DbDuckLake, testing: bool) -> IdeResult<Pool> {
|
||||
source.validate_duck_lake()?;
|
||||
self.check_jdbc_project_approval(source, testing)?;
|
||||
let driver = self.duck_lake_driver(&source.jdbc_driver)?;
|
||||
let cache = self.jdbc_registry()?.with_file_name("jdbc");
|
||||
let (mode, value) = match lake.kind {
|
||||
DbDuckLakeKind::Secret => ("secret", lake.value.clone()),
|
||||
DbDuckLakeKind::File => {
|
||||
let path = self.root.join(&lake.value);
|
||||
let value = path.to_str().ok_or_else(|| IdeError::invalid("Invalid DuckLake catalog file path"))?;
|
||||
duck_lake_path(value, false)?;
|
||||
("file", value.to_owned())
|
||||
}
|
||||
};
|
||||
let fields = duck_lake_fields(mode, value, lake.data_path.as_deref().unwrap_or_default());
|
||||
JdbcPool::open(driver, cache, fields).await.map(Box::new).map(Pool::Jdbc)
|
||||
}
|
||||
}
|
||||
|
||||
fn duck_lake_fields(mode: &str, value: String, data_path: &str) -> Vec<String> {
|
||||
vec![
|
||||
"openDuckLake".into(),
|
||||
DUCKDB_CLASS.into(),
|
||||
DUCKDB_URL.into(),
|
||||
String::new(),
|
||||
String::new(),
|
||||
(mode != "create").to_string(),
|
||||
mode.into(),
|
||||
value,
|
||||
data_path.to_owned(),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn ordinary_jdbc_rejects_a_ducklake_even_with_a_file_url() {
|
||||
let source = DataSource {
|
||||
driver: crate::DbDriver::Jdbc,
|
||||
url: "jdbc:duckdb:existing.duckdb".into(),
|
||||
duck_lake: Some(DbDuckLake {
|
||||
kind: DbDuckLakeKind::File,
|
||||
value: "catalog.ducklake".into(),
|
||||
data_path: None,
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let driver = DbJdbcDriver {
|
||||
id: "duckdb".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: Some("duckdb".into()),
|
||||
jars: vec![],
|
||||
class_name: DUCKDB_CLASS.into(),
|
||||
url_template: DUCKDB_URL.into(),
|
||||
};
|
||||
let error = JdbcPool::connect(&source, None, driver, Default::default())
|
||||
.await
|
||||
.err()
|
||||
.expect("ordinary JDBC must reject DuckLake fields before opening a connection");
|
||||
assert_eq!(error.message, "DuckLake catalogs require a DuckLake connection");
|
||||
}
|
||||
}
|
||||
@@ -2,21 +2,22 @@
|
||||
//! can run driver-specific initialization. A project source may connect only with the
|
||||
//! settings its user last accepted in the dialog; the approval lives outside the project.
|
||||
use crate::local_settings::persist_local;
|
||||
use crate::{DataSource, DbManager, QueryResult, ResultColumn};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use crate::{ConsoleId, DataSource, DbManager, QueryResult, ResultColumn};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Cursor, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
use tokio::process::{ChildStdin, ChildStdout, Command};
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::time::{Instant as Deadline, timeout_at};
|
||||
use tokio::time::timeout;
|
||||
|
||||
const LIMIT: usize = 16 * 1024 * 1024;
|
||||
mod bridge;
|
||||
mod ducklake;
|
||||
|
||||
use bridge::Bridge;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -79,6 +80,13 @@ pub fn jdbc_driver_classes(jars: &[String]) -> IdeResult<Vec<String>> {
|
||||
}
|
||||
|
||||
impl DbJdbcDriver {
|
||||
fn require_vendor(&self, vendor: &str) -> IdeResult<()> {
|
||||
if self.vendor.as_deref() != Some(vendor) {
|
||||
return Err(IdeError::invalid("The JDBC driver profile is not associated with this data source type"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate(&self) -> IdeResult<()> {
|
||||
if self.id.is_empty()
|
||||
|| self.name.trim().is_empty()
|
||||
@@ -138,6 +146,30 @@ impl DbManager {
|
||||
self.update_jdbc_driver(id, None)
|
||||
}
|
||||
|
||||
fn record_jdbc_approval(&self, source: &DataSource) -> IdeResult<()> {
|
||||
let (path, fingerprint) = self.jdbc_approval(source)?;
|
||||
persist_local(&path, fingerprint.as_bytes())
|
||||
}
|
||||
|
||||
fn jdbc_driver_by_id(&self, id: &str) -> IdeResult<DbJdbcDriver> {
|
||||
self.jdbc_drivers()?
|
||||
.into_iter()
|
||||
.find(|d| d.id == id)
|
||||
.ok_or_else(|| IdeError::invalid("Select an installed JDBC driver profile"))
|
||||
}
|
||||
|
||||
fn check_jdbc_project_approval(&self, source: &DataSource, testing: bool) -> IdeResult<()> {
|
||||
if !testing && !source.global {
|
||||
let (path, expected) = self.jdbc_approval(source)?;
|
||||
if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) {
|
||||
return Err(IdeError::invalid(
|
||||
"Review this project's JDBC URL and properties, then save the data source before connecting",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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()))?;
|
||||
@@ -150,7 +182,10 @@ impl DbManager {
|
||||
&source.options,
|
||||
))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
if self.jdbc_password_isolated(source) {
|
||||
if let Some(lake) = &source.duck_lake {
|
||||
settings.extend_from_slice(b"\0ducklake\0");
|
||||
serde_json::to_writer(&mut settings, lake).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
} else if self.jdbc_password_isolated(source) {
|
||||
settings.extend_from_slice(b"\0jdbc-password");
|
||||
}
|
||||
Ok((
|
||||
@@ -164,8 +199,70 @@ impl DbManager {
|
||||
if source.driver != crate::DbDriver::Jdbc || source.plugin_owner.is_some() {
|
||||
return Err(IdeError::invalid("Expected a user-managed JDBC data source"));
|
||||
}
|
||||
let (path, fingerprint) = self.jdbc_approval(source)?;
|
||||
persist_local(&path, fingerprint.as_bytes())
|
||||
if source.duck_lake.is_some() {
|
||||
return self.approve_ducklake_source(source);
|
||||
}
|
||||
self.record_jdbc_approval(source)
|
||||
}
|
||||
|
||||
/// A workspace uses only the selected host driver and a fresh in-memory database.
|
||||
pub(crate) async fn workspace_engine(&self, profile: &str) -> IdeResult<JdbcPool> {
|
||||
let driver = self
|
||||
.jdbc_drivers()?
|
||||
.into_iter()
|
||||
.find(|driver| {
|
||||
driver.id == profile
|
||||
&& driver.vendor.as_deref() == Some("duckdb")
|
||||
&& driver.class_name == "org.duckdb.DuckDBDriver"
|
||||
})
|
||||
.ok_or_else(|| IdeError::invalid("Choose an installed DuckDB JDBC driver for the workspace"))?;
|
||||
let source = DataSource { url: "jdbc:duckdb:".into(), ..Default::default() };
|
||||
JdbcPool::connect(&source, None, driver, self.jdbc_registry()?.with_file_name("jdbc")).await
|
||||
}
|
||||
|
||||
pub(crate) async fn prepare_workspace_duckdb_source(
|
||||
&self,
|
||||
source: &DataSource,
|
||||
) -> IdeResult<WorkspaceDuckDbSource> {
|
||||
let driver = self.approved_jdbc_driver(source, false)?;
|
||||
if driver.vendor.as_deref() != Some("duckdb") || driver.class_name != "org.duckdb.DuckDBDriver" {
|
||||
return Err(IdeError::invalid("Choose a saved DuckDB source with an installed DuckDB driver"));
|
||||
}
|
||||
let target = source.url.strip_prefix("jdbc:duckdb:").unwrap_or_default();
|
||||
let mut parts = target.split(';');
|
||||
let filename = parts.next().unwrap_or_default();
|
||||
let cache = self.jdbc_registry()?.with_file_name("jdbc");
|
||||
let path = cache.join("files").join(filename);
|
||||
if filename.is_empty()
|
||||
|| filename.starts_with([':', ' '])
|
||||
|| filename.starts_with("memory:")
|
||||
|| filename.starts_with("md:")
|
||||
|| filename.contains("://")
|
||||
|| !tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file())
|
||||
{
|
||||
return Err(IdeError::invalid("Choose an existing local DuckDB database file as the workspace source"));
|
||||
}
|
||||
let limits = [
|
||||
("enable_external_access", "false"),
|
||||
("allow_unsigned_extensions", "false"),
|
||||
("autoinstall_known_extensions", "false"),
|
||||
("autoload_known_extensions", "false"),
|
||||
("memory_limit", "96MiB"),
|
||||
("threads", "1"),
|
||||
("temp_directory", ""),
|
||||
("max_temp_directory_size", "0B"),
|
||||
];
|
||||
let protected = |name: &str| limits.iter().any(|(key, _)| name.trim().eq_ignore_ascii_case(key));
|
||||
if parts.any(|option| protected(option.split('=').next().unwrap_or_default())) {
|
||||
return Err(IdeError::invalid("DuckDB Workspace source URL changes a workspace read limit"));
|
||||
}
|
||||
let mut target = source.clone();
|
||||
target.read_only = true;
|
||||
target.properties.retain(|property| !protected(&property.name));
|
||||
target
|
||||
.properties
|
||||
.extend(limits.map(|(name, value)| crate::DbProperty { name: name.into(), value: value.into() }));
|
||||
Ok(WorkspaceDuckDbSource { target, driver, cache })
|
||||
}
|
||||
|
||||
pub(crate) async fn open_pool(
|
||||
@@ -174,200 +271,111 @@ impl DbManager {
|
||||
password: Option<&str>,
|
||||
testing: bool,
|
||||
) -> IdeResult<crate::Pool> {
|
||||
if let Some(lake) = &source.duck_lake {
|
||||
return self.open_ducklake(source, lake, testing).await;
|
||||
}
|
||||
if source.driver != crate::DbDriver::Jdbc {
|
||||
return crate::Pool::connect(source, password, Some(&self.root)).await;
|
||||
}
|
||||
if source.plugin_owner.is_some() {
|
||||
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
|
||||
}
|
||||
if !testing && !source.global {
|
||||
let (path, expected) = self.jdbc_approval(source)?;
|
||||
if std::fs::read_to_string(path).ok().as_deref() != Some(&expected) {
|
||||
return Err(IdeError::invalid(
|
||||
"Review this project's JDBC URL and properties, then save the data source before connecting",
|
||||
));
|
||||
}
|
||||
}
|
||||
let driver = self
|
||||
.jdbc_drivers()?
|
||||
.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"));
|
||||
}
|
||||
let driver = self.approved_jdbc_driver(source, testing)?;
|
||||
JdbcPool::connect(source, password, driver, self.jdbc_registry()?.with_file_name("jdbc"))
|
||||
.await
|
||||
.map(Box::new)
|
||||
.map(crate::Pool::Jdbc)
|
||||
}
|
||||
|
||||
fn approved_jdbc_driver(&self, source: &DataSource, testing: bool) -> IdeResult<DbJdbcDriver> {
|
||||
if source.plugin_owner.is_some() {
|
||||
return Err(IdeError::invalid("Plugins cannot start custom JDBC drivers"));
|
||||
}
|
||||
self.check_jdbc_project_approval(source, testing)?;
|
||||
let driver = self.jdbc_driver_by_id(&source.jdbc_driver)?;
|
||||
if !source.vendor.is_empty() {
|
||||
driver.require_vendor(&source.vendor)?;
|
||||
}
|
||||
Ok(driver)
|
||||
}
|
||||
}
|
||||
|
||||
struct Bridge {
|
||||
stop: tokio::sync::oneshot::Sender<()>,
|
||||
exited: tokio::task::JoinHandle<()>,
|
||||
sequence: u64,
|
||||
input: ChildStdin,
|
||||
output: ChildStdout,
|
||||
pub(crate) struct WorkspaceDuckDbSource {
|
||||
target: DataSource,
|
||||
driver: DbJdbcDriver,
|
||||
cache: PathBuf,
|
||||
}
|
||||
|
||||
impl WorkspaceDuckDbSource {
|
||||
pub(crate) async fn connect(self, password: Option<&str>) -> IdeResult<JdbcPool> {
|
||||
JdbcPool::connect(&self.target, password, self.driver, self.cache).await
|
||||
}
|
||||
}
|
||||
|
||||
struct Session {
|
||||
id: u32,
|
||||
// A physical JDBC Connection executes one request at a time.
|
||||
opened: Mutex<bool>,
|
||||
retired: CancellationToken,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn new(id: u32) -> Self {
|
||||
Self { id, opened: Mutex::new(id == 0), retired: CancellationToken::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ConsoleSessions {
|
||||
latest: u32,
|
||||
opened: HashMap<(String, String), Arc<Session>>,
|
||||
}
|
||||
|
||||
pub struct JdbcPool {
|
||||
bridge: Mutex<Option<Bridge>>,
|
||||
closed: CancellationToken,
|
||||
bridge: Arc<Bridge>,
|
||||
service: Session,
|
||||
consoles: parking_lot::Mutex<ConsoleSessions>,
|
||||
shared_connection: bool,
|
||||
pub(crate) version: String,
|
||||
pub(crate) identifier_quote: String,
|
||||
}
|
||||
|
||||
impl Bridge {
|
||||
fn start(cache: &Path, jars: &[String]) -> IdeResult<Self> {
|
||||
let jdks = ide_sdk::java::installed_jdks();
|
||||
let java = ide_sdk::java::java_runtime(&jdks, 17)
|
||||
.ok_or_else(|| IdeError::invalid("Install a Java 17 or newer runtime to use custom JDBC drivers"))?;
|
||||
let jar = ide_sdk::java::jdbc_bridge_jar(cache)
|
||||
.ok_or_else(|| IdeError::invalid("Cannot install the JDBC bridge in the application data directory"))?;
|
||||
let classpath = std::env::join_paths(std::iter::once(jar.as_path()).chain(jars.iter().map(Path::new)))
|
||||
.map_err(|_| IdeError::invalid("A JDBC JAR path contains the system classpath separator"))?;
|
||||
// Embedded databases can resolve file URLs against the JVM's working directory.
|
||||
let files = cache.join("files");
|
||||
std::fs::create_dir_all(&files)?;
|
||||
let mut command = Command::new(ide_sdk::java::java_executable(&java.home));
|
||||
command.current_dir(files);
|
||||
ide_core::process::prepare(command.as_std_mut());
|
||||
let mut child = command
|
||||
.args(["-Xms8m", "-Xmx192m", "--enable-native-access=ALL-UNNAMED", "-cp"])
|
||||
.arg(classpath)
|
||||
.arg("ai.openidea.jdbc.OpenIdeaJdbc")
|
||||
.env_remove("CLASSPATH")
|
||||
.env_remove("JDK_JAVA_OPTIONS")
|
||||
.env_remove("JAVA_TOOL_OPTIONS")
|
||||
.env_remove("_JAVA_OPTIONS")
|
||||
.kill_on_drop(true)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()?;
|
||||
let input = child.stdin.take().expect("piped");
|
||||
let output = child.stdout.take().expect("piped");
|
||||
let (stop, stopped) = tokio::sync::oneshot::channel();
|
||||
let exited = tokio::spawn(async move {
|
||||
tokio::select! {
|
||||
stop = stopped => {
|
||||
// Disconnect closes stdin so a file-backed driver can flush. A dropped
|
||||
// request or an unresponsive driver must be reaped without waiting.
|
||||
if stop.is_err() || tokio::time::timeout(Duration::from_secs(2), child.wait()).await.is_err() {
|
||||
let _ = child.kill().await;
|
||||
}
|
||||
}
|
||||
_ = child.wait() => {}
|
||||
}
|
||||
});
|
||||
Ok(Self { input, output, stop, exited, sequence: 0 })
|
||||
}
|
||||
|
||||
async fn close(self) {
|
||||
drop(self.input);
|
||||
let _ = self.stop.send(());
|
||||
let _ = self.exited.await;
|
||||
}
|
||||
/// Dropped futures and uncertain transport errors retire the connection they were using.
|
||||
struct ActiveRequest<'a> {
|
||||
pool: &'a JdbcPool,
|
||||
session: &'a Session,
|
||||
completed: bool,
|
||||
}
|
||||
|
||||
// Request: u64 request id, u32 field count, then length-prefixed UTF-8 fields.
|
||||
// Zero fields cancels that id. Replies have a u32 length; zero acknowledges Cancel.
|
||||
fn encode(id: u64, fields: &[&str]) -> IdeResult<Vec<u8>> {
|
||||
if fields.is_empty() || fields.len() > 8192 {
|
||||
return Err(IdeError::invalid("Invalid JDBC field count"));
|
||||
}
|
||||
let size = fields
|
||||
.iter()
|
||||
.try_fold(12usize, |n, s| n.checked_add(4)?.checked_add(s.len()).filter(|n| *n <= LIMIT))
|
||||
.ok_or_else(|| IdeError::invalid("JDBC request exceeds 16 MiB"))?;
|
||||
let mut data = Vec::with_capacity(size);
|
||||
data.extend_from_slice(&id.to_be_bytes());
|
||||
data.extend_from_slice(&(fields.len() as u32).to_be_bytes());
|
||||
for field in fields {
|
||||
data.extend_from_slice(&(field.len() as u32).to_be_bytes());
|
||||
data.extend_from_slice(field.as_bytes());
|
||||
}
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
async fn read_frame(output: &mut (impl AsyncRead + Unpin)) -> IdeResult<Vec<u8>> {
|
||||
let n = output.read_u32().await? as usize;
|
||||
if n > LIMIT {
|
||||
return Err(IdeError::invalid("JDBC response exceeds 16 MiB"));
|
||||
}
|
||||
let mut data = vec![0; n];
|
||||
output.read_exact(&mut data).await?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
const CANCEL_GRACE: Duration = Duration::from_secs(3);
|
||||
|
||||
fn cancel_timeout() -> IdeError {
|
||||
IdeError::invalid(
|
||||
"Cancellation timed out and the JDBC session was closed. Check the statement's status on the server before running it again. The next query will try to reconnect.",
|
||||
)
|
||||
}
|
||||
|
||||
async fn exchange(
|
||||
input: &mut (impl AsyncWrite + Unpin),
|
||||
output: &mut (impl AsyncRead + Unpin),
|
||||
frame: Vec<u8>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<Vec<u8>>> {
|
||||
let mut stop = [0; 12];
|
||||
stop[..8].copy_from_slice(&frame[..8]);
|
||||
let early_deadline = {
|
||||
let send = input.write_all(&frame);
|
||||
tokio::pin!(send);
|
||||
tokio::select! {
|
||||
result = &mut send => { result?; None },
|
||||
() = cancel.cancelled() => {
|
||||
let end = Deadline::now() + CANCEL_GRACE;
|
||||
timeout_at(end, send).await.map_err(|_| cancel_timeout())??;
|
||||
Some(end)
|
||||
}
|
||||
impl Drop for ActiveRequest<'_> {
|
||||
fn drop(&mut self) {
|
||||
if !self.completed {
|
||||
self.pool.retire(self.session);
|
||||
}
|
||||
};
|
||||
drop(frame);
|
||||
let (first, deadline) = {
|
||||
let reply = read_frame(output);
|
||||
tokio::pin!(reply);
|
||||
let end = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => early_deadline.unwrap_or_else(|| Deadline::now() + CANCEL_GRACE),
|
||||
data = &mut reply => {
|
||||
let data = data?;
|
||||
if data.is_empty() { return Err(IdeError::invalid("Unexpected JDBC cancellation acknowledgement")); }
|
||||
return Ok(Some(data));
|
||||
}
|
||||
};
|
||||
let first = timeout_at(end, async {
|
||||
input.write_all(&stop).await?;
|
||||
reply.await
|
||||
})
|
||||
.await
|
||||
.map_err(|_| cancel_timeout())??;
|
||||
(first, end)
|
||||
};
|
||||
// Drain both frames before the next statement can use this session. The driver
|
||||
// may complete the statement before or after the control thread acknowledges it.
|
||||
let data = if first.is_empty() {
|
||||
timeout_at(deadline, read_frame(output)).await.map_err(|_| cancel_timeout())??
|
||||
} else {
|
||||
if timeout_at(deadline, output.read_u32()).await.map_err(|_| cancel_timeout())?? != 0 {
|
||||
return Err(IdeError::invalid("Invalid JDBC cancellation acknowledgement"));
|
||||
}
|
||||
first
|
||||
};
|
||||
match data.first() {
|
||||
// A committed statement may have finished before the control thread received Cancel.
|
||||
Some(1) => Ok(Some(data)),
|
||||
Some(0) => Ok(None),
|
||||
_ => Err(IdeError::invalid("Invalid JDBC cancellation response")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A second connection to an anonymous database would see a different database.
|
||||
fn private_database_url(url: &str) -> bool {
|
||||
if let Some(h2) = url.strip_prefix("jdbc:h2:mem:") {
|
||||
return h2.is_empty() || h2.starts_with(';');
|
||||
}
|
||||
let Some(sqlite) = url.strip_prefix("jdbc:sqlite:") else {
|
||||
return false;
|
||||
};
|
||||
let (path, query) = sqlite.split_once('?').unwrap_or((sqlite, ""));
|
||||
if matches!(path, "" | ":memory:" | "file:") {
|
||||
return true;
|
||||
}
|
||||
let option = |name| {
|
||||
query
|
||||
.split('&')
|
||||
.rev()
|
||||
.filter_map(|part| part.split_once('='))
|
||||
.find_map(|(key, value)| (key == name).then_some(value))
|
||||
};
|
||||
path.starts_with("file:")
|
||||
&& (path == "file::memory:" || option("mode") == Some("memory"))
|
||||
&& option("cache") != Some("shared")
|
||||
}
|
||||
|
||||
impl JdbcPool {
|
||||
async fn connect(
|
||||
source: &DataSource,
|
||||
@@ -375,10 +383,12 @@ impl JdbcPool {
|
||||
driver: DbJdbcDriver,
|
||||
cache: PathBuf,
|
||||
) -> IdeResult<Self> {
|
||||
driver.validate()?;
|
||||
if source.duck_lake.is_some() {
|
||||
return Err(IdeError::invalid("DuckLake catalogs require a DuckLake connection"));
|
||||
}
|
||||
let mut fields = vec![
|
||||
"open".to_string(),
|
||||
driver.class_name,
|
||||
driver.class_name.clone(),
|
||||
source.url.clone(),
|
||||
source.user.clone(),
|
||||
password.unwrap_or_default().to_owned(),
|
||||
@@ -390,35 +400,93 @@ impl JdbcPool {
|
||||
}
|
||||
fields.extend([p.name.clone(), p.value.clone()]);
|
||||
}
|
||||
Self::open(driver, cache, fields).await
|
||||
}
|
||||
|
||||
async fn open(driver: DbJdbcDriver, cache: PathBuf, fields: Vec<String>) -> IdeResult<Self> {
|
||||
driver.validate()?;
|
||||
let bridge = tokio::task::spawn_blocking(move || Bridge::start(&cache, &driver.jars))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
let mut pool = Self {
|
||||
bridge: Mutex::new(Some(bridge)),
|
||||
closed: CancellationToken::new(),
|
||||
version: String::new(),
|
||||
identifier_quote: String::new(),
|
||||
};
|
||||
let args: Vec<_> = fields.iter().map(String::as_str).collect();
|
||||
let cancel = CancellationToken::new();
|
||||
let result = tokio::time::timeout(Duration::from_secs(30), pool.request(&args, "", &cancel))
|
||||
let data = timeout(Duration::from_secs(30), bridge.exchange(0, &args, &cancel, &cancel))
|
||||
.await
|
||||
.map_err(|_| IdeError::new(ide_core::error::ErrorKind::TimedOut, "JDBC connection timed out"))??;
|
||||
.map_err(|_| IdeError::new(ErrorKind::TimedOut, "JDBC connection timed out"))??;
|
||||
let result = decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.)?;
|
||||
let mut metadata = result.rows.into_iter().next().unwrap_or_default().into_iter();
|
||||
pool.version = metadata.next().flatten().unwrap_or_else(|| "Connected".into());
|
||||
pool.identifier_quote = metadata.next().flatten().unwrap_or_default().trim().into();
|
||||
Ok(pool)
|
||||
Ok(Self {
|
||||
bridge: Arc::new(bridge),
|
||||
service: Session::new(0),
|
||||
consoles: Default::default(),
|
||||
shared_connection: private_database_url(&fields[2]),
|
||||
version: metadata.next().flatten().unwrap_or_else(|| "Connected".into()),
|
||||
identifier_quote: metadata.next().flatten().unwrap_or_default().trim().into(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn close(&self) {
|
||||
self.closed.cancel();
|
||||
if let Some(bridge) = self.bridge.lock().await.take() {
|
||||
bridge.close().await;
|
||||
}
|
||||
self.bridge.close().await;
|
||||
}
|
||||
|
||||
pub(crate) fn is_closed(&self) -> bool {
|
||||
self.closed.is_cancelled()
|
||||
self.bridge.is_closed()
|
||||
}
|
||||
|
||||
fn console(&self, console: ConsoleId<'_>) -> IdeResult<Arc<Session>> {
|
||||
let key = (console.window.to_owned(), console.path.to_owned());
|
||||
let mut sessions = self.consoles.lock();
|
||||
if let Some(existing) = sessions.opened.get(&key)
|
||||
&& !existing.retired.is_cancelled()
|
||||
{
|
||||
return Ok(existing.clone());
|
||||
}
|
||||
let id = sessions.latest.checked_add(1).ok_or_else(|| IdeError::internal("JDBC session IDs exhausted"))?;
|
||||
sessions.latest = id;
|
||||
let session = Arc::new(Session::new(id));
|
||||
sessions.opened.insert(key, session.clone());
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
pub(crate) async fn release_console(&self, console: ConsoleId<'_>) -> IdeResult<()> {
|
||||
let key = (console.window.to_owned(), console.path.to_owned());
|
||||
// Retire the ID before allowing a reopened editor to allocate a replacement.
|
||||
let session = self.consoles.lock().opened.remove(&key).inspect(|session| session.retired.cancel());
|
||||
if let Some(session) = session {
|
||||
let closed = self.bridge.close_session(session.id).await;
|
||||
self.shutdown_service_if_idle();
|
||||
closed?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn retire(&self, session: &Session) {
|
||||
if session.retired.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
session.retired.cancel();
|
||||
if session.id != 0 {
|
||||
let bridge = self.bridge.clone();
|
||||
let id = session.id;
|
||||
tokio::spawn(async move {
|
||||
let _ = bridge.close_session(id).await;
|
||||
});
|
||||
}
|
||||
self.shutdown_service_if_idle();
|
||||
}
|
||||
|
||||
fn shutdown_service_if_idle(&self) {
|
||||
if !self.service.retired.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
let has_consoles =
|
||||
self.consoles.lock().opened.values().any(|session| {
|
||||
!session.retired.is_cancelled() && session.opened.try_lock().map_or(true, |opened| *opened)
|
||||
});
|
||||
// Service failure cannot discard a healthy editor's transaction or temporary tables.
|
||||
if !has_consoles {
|
||||
self.bridge.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn query(
|
||||
@@ -439,7 +507,21 @@ impl JdbcPool {
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
self.request(
|
||||
self.query_in_console(sql, skip, max, cancel, schema, None).await
|
||||
}
|
||||
|
||||
pub(crate) async fn query_in_console(
|
||||
&self,
|
||||
sql: &str,
|
||||
skip: usize,
|
||||
max: usize,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
console: Option<ConsoleId<'_>>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let session = console.filter(|_| !self.shared_connection).map(|console| self.console(console)).transpose()?;
|
||||
self.request_on(
|
||||
session.as_deref().unwrap_or(&self.service),
|
||||
&["query", sql, &skip.to_string(), &max.min(i32::MAX as usize).to_string(), schema.unwrap_or_default()],
|
||||
sql,
|
||||
cancel,
|
||||
@@ -457,82 +539,91 @@ impl JdbcPool {
|
||||
self.request(&["page", sql, &offset.to_string(), &limit.min(i32::MAX as u64).to_string()], sql, cancel).await
|
||||
}
|
||||
|
||||
/// Introspection on this connection. `catalogs` lists live catalogs with the current one marked.
|
||||
/// `schemas`, `tables`, `schemaColumns`, and `columns` accept a final catalog argument.
|
||||
pub(crate) async fn metadata(&self, fields: &[&str]) -> IdeResult<Vec<Vec<Option<String>>>> {
|
||||
Ok(self.request(fields, "", &CancellationToken::new()).await?.rows)
|
||||
}
|
||||
|
||||
async fn request(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
|
||||
let result = self.exchange_once(fields, sql, cancel).await;
|
||||
if let Err(e) = &result
|
||||
&& fields.first() != Some(&"open")
|
||||
&& e.kind != ide_core::error::ErrorKind::Cancelled
|
||||
&& !self.is_closed()
|
||||
&& !self.session_valid().await
|
||||
{
|
||||
// The session is gone (a proxy or tunnel dropped the idle TCP connection): close the
|
||||
// pool so the next statement or Connect starts a new one instead of failing forever.
|
||||
self.close().await;
|
||||
self.request_on(&self.service, fields, sql, cancel).await
|
||||
}
|
||||
|
||||
async fn request_on(
|
||||
&self,
|
||||
session: &Session,
|
||||
fields: &[&str],
|
||||
sql: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
// A rejected local request has not used the connection and cannot invalidate it.
|
||||
bridge::frame_size(fields)?;
|
||||
let mut opened = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
() = session.retired.cancelled() => {
|
||||
return Err(if session.id == 0 {
|
||||
IdeError::new(ErrorKind::Io, "The JDBC service connection was lost. Reconnect to restore catalog access.")
|
||||
} else {
|
||||
IdeError::cancelled()
|
||||
});
|
||||
}
|
||||
slot = session.opened.lock() => slot,
|
||||
};
|
||||
let mut active = ActiveRequest { pool: self, session, completed: false };
|
||||
if !*opened {
|
||||
let data = timeout(Duration::from_secs(30), self.exchange(session, &["open"], cancel))
|
||||
.await
|
||||
.map_err(|_| IdeError::new(ErrorKind::TimedOut, "JDBC connection timed out"))??;
|
||||
decode(&data.ok_or_else(IdeError::cancelled)?, "", 0.)?;
|
||||
*opened = true;
|
||||
}
|
||||
let start = Instant::now();
|
||||
let data = self.exchange(session, fields, cancel).await?;
|
||||
let result = data
|
||||
.ok_or_else(IdeError::cancelled)
|
||||
.and_then(|data| decode(&data, sql, start.elapsed().as_secs_f64() * 1000.0));
|
||||
if result.as_ref().is_err_and(|error| error.kind != ErrorKind::Cancelled) && !self.session_valid(session).await
|
||||
{
|
||||
return result;
|
||||
}
|
||||
active.completed = true;
|
||||
result
|
||||
}
|
||||
|
||||
/// Keep-alive: checks the session (any SQL would be dialect-specific) and closes a dead one.
|
||||
async fn exchange(
|
||||
&self,
|
||||
session: &Session,
|
||||
fields: &[&str],
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<Vec<u8>>> {
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = session.retired.cancelled() => Err(IdeError::cancelled()),
|
||||
data = self.bridge.exchange(session.id, fields, cancel, &session.retired) => data,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep-alive operates on the service connection without waiting on an editor's query.
|
||||
pub(crate) async fn ping(&self) -> IdeResult<()> {
|
||||
if self.session_valid().await {
|
||||
let _service = self.service.opened.lock().await;
|
||||
if self.service.retired.is_cancelled() || self.session_valid(&self.service).await {
|
||||
return Ok(());
|
||||
}
|
||||
self.close().await;
|
||||
Err(IdeError::new(ide_core::error::ErrorKind::Io, "JDBC connection was lost"))
|
||||
self.retire(&self.service);
|
||||
Err(IdeError::new(ErrorKind::Io, "JDBC connection was lost"))
|
||||
}
|
||||
|
||||
/// Whether the JDBC session still works, asked after a failed statement.
|
||||
async fn session_valid(&self) -> bool {
|
||||
if self.bridge.lock().await.is_none() {
|
||||
return false;
|
||||
}
|
||||
/// Checks that an error was local to this statement before reusing its connection.
|
||||
async fn session_valid(&self, session: &Session) -> bool {
|
||||
let cancel = CancellationToken::new();
|
||||
match tokio::time::timeout(Duration::from_secs(10), self.exchange_once(&["valid"], "", &cancel)).await {
|
||||
Ok(Ok(result)) => {
|
||||
result.rows.first().and_then(|row| row.first()).cloned().flatten().as_deref() != Some("false")
|
||||
}
|
||||
Ok(Err(_)) | Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn exchange_once(&self, fields: &[&str], sql: &str, cancel: &CancellationToken) -> IdeResult<QueryResult> {
|
||||
let mut slot = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
() = self.closed.cancelled() => return Err(IdeError::invalid("JDBC connection is closed")),
|
||||
slot = self.bridge.lock() => slot,
|
||||
let Ok(Ok(Some(data))) = timeout(Duration::from_secs(10), self.exchange(session, &["valid"], &cancel)).await
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let bridge = slot
|
||||
.as_mut()
|
||||
.ok_or_else(|| IdeError::invalid("JDBC connection is closed; reconnect to start a new session"))?;
|
||||
bridge.sequence = bridge.sequence.wrapping_add(1);
|
||||
let frame = encode(bridge.sequence, fields)?;
|
||||
let mut bridge = slot.take().expect("checked above");
|
||||
// Dropping an in-flight request must discard its process and partially consumed frame.
|
||||
let interrupted = self.closed.clone().drop_guard();
|
||||
let start = Instant::now();
|
||||
let response = tokio::select! {
|
||||
biased;
|
||||
() = self.closed.cancelled() => Err(IdeError::cancelled()),
|
||||
response = exchange(&mut bridge.input, &mut bridge.output, frame, cancel) => response,
|
||||
};
|
||||
let data = match response {
|
||||
Ok(data) => {
|
||||
*slot = Some(bridge);
|
||||
interrupted.disarm();
|
||||
data
|
||||
}
|
||||
Err(e) => {
|
||||
drop(bridge.stop);
|
||||
let _ = bridge.exited.await;
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
decode(&data.ok_or_else(IdeError::cancelled)?, sql, start.elapsed().as_secs_f64() * 1000.0)
|
||||
decode(&data, "", 0.).is_ok_and(|result| {
|
||||
result.rows.first().and_then(|row| row.first()).and_then(Option::as_deref) == Some("true")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -655,7 +746,7 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
|
||||
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default, comment) by table.
|
||||
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
|
||||
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
|
||||
for row in rows {
|
||||
@@ -664,12 +755,15 @@ fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::
|
||||
let data_type = it.next().flatten().unwrap_or_default();
|
||||
let nullable = it.next().flatten().as_deref() != Some("0");
|
||||
let has_default = it.next().flatten().is_some();
|
||||
// Bridges built before the comment column send five fields.
|
||||
let comment = it.next().flatten().filter(|c| !c.trim().is_empty());
|
||||
by_table.entry(table).or_default().push(crate::CompletionColumn {
|
||||
name,
|
||||
data_type,
|
||||
nullable,
|
||||
primary_key: false,
|
||||
has_default,
|
||||
comment,
|
||||
});
|
||||
}
|
||||
by_table
|
||||
@@ -679,85 +773,134 @@ fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_private_jdbc_databases_keep_one_connection() {
|
||||
for url in [
|
||||
"jdbc:sqlite:",
|
||||
"jdbc:sqlite::memory:",
|
||||
"jdbc:sqlite:file:",
|
||||
"jdbc:sqlite:file:private?mode=memory&cache=private",
|
||||
"jdbc:h2:mem:",
|
||||
"jdbc:h2:mem:;DB_CLOSE_DELAY=-1",
|
||||
] {
|
||||
assert!(private_database_url(url), "{url}");
|
||||
}
|
||||
for url in [
|
||||
"jdbc:sqlite:/tmp/data.db",
|
||||
"jdbc:sqlite:file:data.db?cache=shared",
|
||||
"jdbc:sqlite:file:shared?mode=memory&cache=shared",
|
||||
"jdbc:sqlite:file::memory:?cache=shared",
|
||||
"jdbc:h2:mem:shared;DB_CLOSE_DELAY=-1",
|
||||
"jdbc:h2:file:/tmp/data",
|
||||
"jdbc:h2:tcp://server/data",
|
||||
"jdbc:duckdb:",
|
||||
"jdbc:clickhouse://localhost/default",
|
||||
] {
|
||||
assert!(!private_database_url(url), "{url}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_columns_group_by_table() {
|
||||
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
|
||||
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
|
||||
};
|
||||
let by_table = schema_columns(vec![
|
||||
row("orders", "id", "0", None),
|
||||
row("orders", "note", "1", Some("'none'")),
|
||||
row("items", "sku", "1", None),
|
||||
vec![None, Some("orphan".into())],
|
||||
]);
|
||||
let mut commented = row("orders", "note", "1", Some("'none'"));
|
||||
commented.push(Some("free text".into()));
|
||||
let mut blank = row("items", "sku", "1", None);
|
||||
blank.push(Some(" ".into()));
|
||||
let by_table =
|
||||
schema_columns(vec![row("orders", "id", "0", None), commented, blank, vec![None, Some("orphan".into())]]);
|
||||
let orders = &by_table["orders"];
|
||||
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
|
||||
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
|
||||
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
|
||||
assert_eq!((orders[0].comment.as_deref(), orders[1].comment.as_deref()), (None, Some("free text")));
|
||||
assert_eq!(by_table["items"][0].comment, None);
|
||||
assert_eq!(by_table["items"].len(), 1);
|
||||
assert_eq!(by_table.len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn frame_codec_checks_both_16_mib_boundaries() {
|
||||
assert_eq!(encode(7, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 1, b'a']);
|
||||
let mut field = "x".repeat(LIMIT - 16);
|
||||
assert_eq!(encode(1, &[&field]).unwrap().len(), LIMIT);
|
||||
field.push('x');
|
||||
assert!(encode(1, &[&field]).is_err());
|
||||
let mut framed = vec![0u8; LIMIT + 4];
|
||||
framed[..4].copy_from_slice(&(LIMIT as u32).to_be_bytes());
|
||||
assert_eq!(read_frame(&mut framed.as_slice()).await.unwrap().len(), LIMIT);
|
||||
assert!(read_frame(&mut &((LIMIT + 1) as u32).to_be_bytes()[..]).await.is_err());
|
||||
assert!(read_frame(&mut &[0, 0, 0, 2, 1u8][..]).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancel_drains_partial_replies_in_either_order() {
|
||||
for ack_first in [true, false] {
|
||||
let (mut input, mut peer_input) = tokio::io::duplex(1);
|
||||
let (mut output, mut peer_output) = tokio::io::duplex(1);
|
||||
let cancel = CancellationToken::new();
|
||||
let frame = encode(42, &["query"]).unwrap();
|
||||
let peer = async {
|
||||
let mut request = vec![0; frame.len()];
|
||||
peer_input.read_exact(&mut request).await.unwrap();
|
||||
assert_eq!(request, frame);
|
||||
// The one-byte pipe forces the reader to consume part of the header before Cancel.
|
||||
peer_output.write_all(&[0, 0]).await.unwrap();
|
||||
cancel.cancel();
|
||||
let mut stop = [0; 12];
|
||||
peer_input.read_exact(&mut stop).await.unwrap();
|
||||
assert_eq!(&stop[..8], &42u64.to_be_bytes());
|
||||
assert_eq!(&stop[8..], &[0; 4]);
|
||||
let frames = if ack_first { [0, 0, 0, 0, 0, 1, 0] } else { [0, 1, 1, 0, 0, 0, 0] };
|
||||
peer_output.write_all(&frames).await.unwrap();
|
||||
};
|
||||
let (result, ()) = tokio::join!(exchange(&mut input, &mut output, frame.clone(), &cancel), peer);
|
||||
assert_eq!(result.unwrap(), (!ack_first).then(|| vec![1]));
|
||||
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
|
||||
async fn duckdb_live_catalog_metadata_is_scoped_to_the_requested_namespace() -> IdeResult<()> {
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let source = DataSource { url: "jdbc:duckdb:".into(), ..Default::default() };
|
||||
let driver = DbJdbcDriver {
|
||||
id: "duckdb".into(),
|
||||
name: "DuckDB".into(),
|
||||
vendor: None,
|
||||
jars: vec![std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR")],
|
||||
class_name: "org.duckdb.DuckDBDriver".into(),
|
||||
url_template: String::new(),
|
||||
};
|
||||
let pool = JdbcPool::connect(&source, None, driver, tmp.path().join("jdbc")).await?;
|
||||
let stop = CancellationToken::new();
|
||||
let path = |file| tmp.path().join(file).to_string_lossy().replace('\'', "''");
|
||||
let archive = "archive.db:1";
|
||||
for sql in [
|
||||
"SET threads = 1".into(),
|
||||
"CREATE TABLE memory.main.dupe (root_only INT)".into(),
|
||||
format!("ATTACH '{}' AS first", path("first.duckdb")),
|
||||
format!(r#"ATTACH '{}' AS "archive.db:1""#, path("archive.duckdb")),
|
||||
"CREATE TABLE first.main.dupe (first_only INT PRIMARY KEY)".into(),
|
||||
r#"CREATE TABLE "archive.db:1".main.dupe (archive_only INT)"#.into(),
|
||||
r#"CREATE SCHEMA "archive.db:1"."qa_%""#.into(),
|
||||
r#"CREATE SCHEMA "archive.db:1".qaSimilar"#.into(),
|
||||
r#"CREATE TABLE "archive.db:1"."qa_%"."t_%""q" (quoted_only INT PRIMARY KEY)"#.into(),
|
||||
r#"COMMENT ON TABLE "archive.db:1"."qa_%"."t_%""q" IS 'Archive table'"#.into(),
|
||||
r#"COMMENT ON COLUMN "archive.db:1"."qa_%"."t_%""q".quoted_only IS 'In the archive'"#.into(),
|
||||
r#"CREATE TABLE "archive.db:1".qaSimilar."t_%""q" (wrong_schema INT)"#.into(),
|
||||
r#"COMMENT ON TABLE "archive.db:1".qaSimilar."t_%""q" IS 'Wrong schema table'"#.into(),
|
||||
r#"COMMENT ON COLUMN "archive.db:1".qaSimilar."t_%""q".wrong_schema IS 'Outside the schema'"#.into(),
|
||||
] {
|
||||
pool.query(&sql, 0, 1, &stop).await?;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn exchange_rejects_unexpected_acknowledgements() {
|
||||
let cancel = CancellationToken::new();
|
||||
let mut sink = tokio::io::sink();
|
||||
let mut reply = &[0, 0, 0, 1, 1u8][..];
|
||||
assert_eq!(
|
||||
exchange(&mut sink, &mut reply, encode(1, &["query"]).unwrap(), &cancel).await.unwrap(),
|
||||
Some(vec![1])
|
||||
);
|
||||
for cancelled in [false, true] {
|
||||
if cancelled {
|
||||
cancel.cancel();
|
||||
}
|
||||
let mut duplicate_ack = &[0u8; 8][..];
|
||||
assert!(exchange(&mut sink, &mut duplicate_ack, encode(1, &["query"]).unwrap(), &cancel).await.is_err());
|
||||
let catalogs = pool.metadata(&["catalogs"]).await?;
|
||||
assert!(catalogs.contains(&vec![Some("memory".into()), Some("1".into())]));
|
||||
assert!(catalogs.contains(&vec![Some("first".into()), Some("0".into())]));
|
||||
assert!(catalogs.contains(&vec![Some(archive.into()), Some("0".into())]));
|
||||
let mut schemas = pool.metadata(&["schemas", archive]).await?;
|
||||
// DuckDB JDBC 1.1.3 also lists these system schemas for attached catalogs.
|
||||
schemas.retain(|row| !matches!(row[0].as_deref(), Some("information_schema" | "pg_catalog")));
|
||||
assert_eq!(schemas, ["main", "qaSimilar", "qa_%"].map(|schema| vec![Some(schema.into())]));
|
||||
let tables = pool.metadata(&["tables", "qa_%", archive]).await?;
|
||||
assert_eq!(tables.len(), 1);
|
||||
assert_eq!(tables[0][0].as_deref(), Some(r#"t_%"q"#));
|
||||
assert_eq!(tables[0][2].as_deref(), Some("Archive table"));
|
||||
|
||||
for (catalog, column, primary) in
|
||||
[("memory", "root_only", "0"), ("first", "first_only", "1"), (archive, "archive_only", "0")]
|
||||
{
|
||||
let columns = pool.metadata(&["columns", "main", "dupe", catalog]).await?;
|
||||
assert_eq!(columns.len(), 1);
|
||||
assert_eq!(columns[0][0].as_deref(), Some(column));
|
||||
assert_eq!(columns[0][4].as_deref(), Some(primary));
|
||||
}
|
||||
let (mut peer, mut output) = tokio::io::duplex(4);
|
||||
peer.write_u32(0).await.unwrap();
|
||||
let error = exchange(&mut sink, &mut output, encode(1, &["query"]).unwrap(), &cancel).await.unwrap_err();
|
||||
assert_eq!(error.message, cancel_timeout().message);
|
||||
let quoted = pool.metadata(&["columns", "qa_%", r#"t_%"q"#, archive]).await?;
|
||||
assert_eq!(quoted.len(), 1);
|
||||
assert_eq!(quoted[0][0].as_deref(), Some("quoted_only"));
|
||||
assert_eq!(quoted[0][4].as_deref(), Some("1"));
|
||||
let all = schema_columns(pool.metadata(&["schemaColumns", "qa_%", archive]).await?);
|
||||
assert_eq!(all.len(), 1);
|
||||
assert_eq!(all[r#"t_%"q"#][0].name, "quoted_only");
|
||||
assert_eq!(all[r#"t_%"q"#][0].comment.as_deref(), Some("In the archive"));
|
||||
|
||||
pool.query("USE first", 0, 1, &stop).await?;
|
||||
let catalogs = pool.metadata(&["catalogs"]).await?;
|
||||
assert!(catalogs.contains(&vec![Some("first".into()), Some("1".into())]));
|
||||
let legacy = pool.metadata(&["columns", "main", "dupe"]).await?;
|
||||
assert_eq!(legacy[0][0].as_deref(), Some("first_only"));
|
||||
pool.query("USE memory", 0, 1, &stop).await?;
|
||||
pool.query("DETACH first", 0, 1, &stop).await?;
|
||||
let catalogs = pool.metadata(&["catalogs"]).await?;
|
||||
assert!(!catalogs.iter().any(|r| r[0].as_deref() == Some("first")));
|
||||
assert!(pool.metadata(&["schemas", "first"]).await?.is_empty());
|
||||
assert!(pool.metadata(&["tables", "main", "first"]).await?.is_empty());
|
||||
assert!(pool.metadata(&["columns", "main", "dupe", "first"]).await?.is_empty());
|
||||
pool.close().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+545
-118
File diff suppressed because it is too large.
Load diff
Loaded 100 of 2268 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача