дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 10:07:11 +02:00
Порівняти коміти
606
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
53937b9d66 | ||
|
|
69fca0aaa3 | ||
|
|
f8e1705dff | ||
|
|
a4394d3ece | ||
|
|
4021bdd0d1 | ||
|
|
8e8a3f397b | ||
|
|
cfbc0e3ed3 | ||
|
|
775a5e04d0 | ||
|
|
90f1ad67d4 | ||
|
|
67c48409c8 | ||
|
|
85e03f72ee | ||
|
|
98ffcf5919 | ||
|
|
4650d88b73 | ||
|
|
305b8c7eec | ||
|
|
03ce267445 | ||
|
|
2aa242252f | ||
|
|
4ff4b2d016 | ||
|
|
d85939395b | ||
|
|
95ac0a0c1a | ||
|
|
396a490adf | ||
|
|
cc877ed9f7 | ||
|
|
0c495e2eed | ||
|
|
1cbb572631 | ||
|
|
251f3953fa | ||
|
|
aa124276b2 | ||
|
|
fb91ace8aa | ||
|
|
c931cbecc0 | ||
|
|
cfaf05c84b | ||
|
|
59f3994b6c | ||
|
|
908b753daf | ||
|
|
3790f578be | ||
|
|
68ffce6340 | ||
|
|
3f74972f11 | ||
|
|
eefe6cc9c8 | ||
|
|
e9480d690c | ||
|
|
13b8024588 | ||
|
|
452d897032 | ||
|
|
a69ff2499d | ||
|
|
0df4bc2289 | ||
|
|
83a3b1208a | ||
|
|
94cfde8025 | ||
|
|
b228d31ff9 | ||
|
|
f160d60a7a | ||
|
|
46031d162b | ||
|
|
4c44beba35 | ||
|
|
65545d3563 | ||
|
|
b4148e2f39 | ||
|
|
6e642b4d4b | ||
|
|
4bd6f8e720 | ||
|
|
7145b81ac1 | ||
|
|
8f080ee99e | ||
|
|
feb5262a16 | ||
|
|
7911a74c05 | ||
|
|
bb7cacb357 | ||
|
|
b5f7f0f472 | ||
|
|
8a26dff72b | ||
|
|
529cd33ddc | ||
|
|
838cf14845 | ||
|
|
4baa407e25 | ||
|
|
b01ba2da03 | ||
|
|
e4f7709f53 | ||
|
|
bcee799269 | ||
|
|
ec4da5efa5 | ||
|
|
94a28cbd1d | ||
|
|
63830dcbaf | ||
|
|
4ab9f02dc2 | ||
|
|
1102822981 | ||
|
|
006777dae1 | ||
|
|
df77c18117 | ||
|
|
360c6f1ae1 | ||
|
|
258639c372 | ||
|
|
9a10fde46f | ||
|
|
eecd78aee5 | ||
|
|
32fa8b60f8 | ||
|
|
7f81ec7f63 | ||
|
|
1f4ac3afbb | ||
|
|
7a20b20b2d | ||
|
|
cd0fe6c8f5 | ||
|
|
b8d0d12142 | ||
|
|
7ba1acc0cf | ||
|
|
9aab39de87 | ||
|
|
c77545460d | ||
|
|
6d22097e9a | ||
|
|
cd92df2007 | ||
|
|
8a301dad86 | ||
|
|
66b90e3ee8 | ||
|
|
ee6f9f81a5 | ||
|
|
c13cb2bf27 | ||
|
|
7d30d23a56 | ||
|
|
749c34df7a | ||
|
|
acf5e53953 | ||
|
|
9d5c294218 | ||
|
|
588d1d17aa | ||
|
|
6b94744df3 | ||
|
|
30c80107e3 | ||
|
|
05a88394fb | ||
|
|
455e32ab76 | ||
|
|
c55ee61b71 | ||
|
|
0b7485f69f | ||
|
|
5a44ccb615 | ||
|
|
587d964e42 | ||
|
|
63f20ce5cc | ||
|
|
2389f55bae | ||
|
|
af416b0572 | ||
|
|
a19864d5b1 | ||
|
|
1548f5cfe5 | ||
|
|
bca532e4e3 | ||
|
|
c04fe9a72b | ||
|
|
04d5eae0d1 | ||
|
|
32242eaf53 | ||
|
|
ef986fbeca | ||
|
|
7f40257632 | ||
|
|
630e56a263 | ||
|
|
6d576e8ff5 | ||
|
|
6600a06ee8 | ||
|
|
ca4644cbde | ||
|
|
d1c07306e9 | ||
|
|
9f63ea75fe | ||
|
|
cff33ee70d | ||
|
|
ccb73f4efd | ||
|
|
d69ebb9f1e | ||
|
|
579ce3f731 | ||
|
|
71ded3e4c0 | ||
|
|
59397c4842 | ||
|
|
76cb012b92 | ||
|
|
853a0304e1 | ||
|
|
5c2b52075d | ||
|
|
2389c0e07e | ||
|
|
df5df76c92 | ||
|
|
4fe11aacbd | ||
|
|
11db5c34d9 | ||
|
|
7d4d0cb921 | ||
|
|
d84cae9525 | ||
|
|
61a4118921 | ||
|
|
63ce54dc1e | ||
|
|
2d3f81cf54 | ||
|
|
cd989aace8 | ||
|
|
bb628998cc | ||
|
|
72aa411d2b | ||
|
|
d1925ada22 | ||
|
|
1eb91d4cef | ||
|
|
3b00295036 | ||
|
|
86a39c6573 | ||
|
|
979d19d066 | ||
|
|
ea32779559 | ||
|
|
42ba15665b | ||
|
|
65e243f5fc | ||
|
|
3a956c72b8 | ||
|
|
84ae5bb179 | ||
|
|
f49302d365 | ||
|
|
35f525dbde | ||
|
|
24b00c3db1 | ||
|
|
6a1cd830f5 | ||
|
|
9e605ee761 | ||
|
|
cf5493959b | ||
|
|
8f1d2afb0c | ||
|
|
d48146f52d | ||
|
|
5cfd5157d0 | ||
|
|
0ba39f732e | ||
|
|
194b01d74f | ||
|
|
6ea187f0d0 | ||
|
|
0fe7fa9b48 | ||
|
|
f75b1c0a04 | ||
|
|
e5642b0631 | ||
|
|
632ee77580 | ||
|
|
51227d5898 | ||
|
|
f5180392f2 | ||
|
|
3278eab0c8 | ||
|
|
71bfc70996 | ||
|
|
1e6ab2ecff | ||
|
|
0f0e3e73e7 | ||
|
|
a2498f096a | ||
|
|
494d1a9bf5 | ||
|
|
417ecfed50 | ||
|
|
94653b487d | ||
|
|
a5473e896a | ||
|
|
8483c355c8 | ||
|
|
8d2d2d27e6 | ||
|
|
72db7ecb97 | ||
|
|
406cf4e474 | ||
|
|
bc019ace9d | ||
|
|
55c9787996 | ||
|
|
5b1e4a31f2 | ||
|
|
f3582403f3 | ||
|
|
a5f958d544 | ||
|
|
4aeeb4d883 | ||
|
|
15f3eadcf1 | ||
|
|
ae9804bc8b | ||
|
|
644a380616 | ||
|
|
4a41b14992 | ||
|
|
551328c901 | ||
|
|
54ce7ac6f8 | ||
|
|
a33c46465b | ||
|
|
b747e81cb6 | ||
|
|
24fdbb54db | ||
|
|
535f7584ee | ||
|
|
49e26d1de1 | ||
|
|
40fb4923e6 | ||
|
|
8fefbc1c82 | ||
|
|
059dca5b34 | ||
|
|
277464e93b | ||
|
|
a6e9c79c96 | ||
|
|
1a6c0dff36 | ||
|
|
73708c8e7d | ||
|
|
d2cc2093b1 | ||
|
|
ff9a48eb0e | ||
|
|
24e42bb302 | ||
|
|
67c00a986a | ||
|
|
896ec3b924 | ||
|
|
2f18cacbaf | ||
|
|
2cad48b401 | ||
|
|
1f8cf7e3a8 | ||
|
|
978bcd6dd4 | ||
|
|
a1d406beb3 | ||
|
|
b46c467fc3 | ||
|
|
091dd85ef0 | ||
|
|
4eab243ef2 | ||
|
|
56c6e8090a | ||
|
|
bd3f0cb651 | ||
|
|
fe1838aca6 | ||
|
|
9737adb66c | ||
|
|
1c4aa9f1b2 | ||
|
|
4335cf46af | ||
|
|
f2b602a48e | ||
|
|
b4c8a6708c | ||
|
|
8e36365bc4 | ||
|
|
b5a8a77cfa | ||
|
|
70a4fbec3a | ||
|
|
b640078b11 | ||
|
|
e186f74782 | ||
|
|
25d0294947 | ||
|
|
5d26e44c0e | ||
|
|
6e327e6ffc | ||
|
|
81d1285e38 | ||
|
|
8a92a7b10c | ||
|
|
3eb4b54525 | ||
|
|
5dd0565456 | ||
|
|
b16d485f35 | ||
|
|
34739e181d | ||
|
|
2cf5f5369f | ||
|
|
b27ef431a6 | ||
|
|
166ef2dffa | ||
|
|
ed57059cad | ||
|
|
31e7b420ae | ||
|
|
70a7932939 | ||
|
|
8b1ca86526 | ||
|
|
16e160f5b9 | ||
|
|
0d3e9a27cc | ||
|
|
3a31ec25aa | ||
|
|
693b24bf65 | ||
|
|
6304811ac9 | ||
|
|
d55f116add | ||
|
|
d62c978032 | ||
|
|
5f452a8e36 | ||
|
|
7992063ef2 | ||
|
|
34cb6a45cd | ||
|
|
e670463b8e | ||
|
|
2b0cc6b733 | ||
|
|
152f7123a0 | ||
|
|
a223f3e6b2 | ||
|
|
9c73f7d784 | ||
|
|
9ad7f91c04 | ||
|
|
5ec05b3aca | ||
|
|
26688a79f7 | ||
|
|
c6428a8e4c | ||
|
|
9e3077753d | ||
|
|
7d33b470f2 | ||
|
|
5bfdaf679d | ||
|
|
ab08c3d245 | ||
|
|
1ee5f0d71d | ||
|
|
d2686f922d | ||
|
|
35682aadc2 | ||
|
|
35529ddd64 | ||
|
|
f5abe8b509 | ||
|
|
c1cde544fb | ||
|
|
40ea4267bd | ||
|
|
377e900e84 | ||
|
|
74b2b5113b | ||
|
|
68a322edad | ||
|
|
ba04c34710 | ||
|
|
cddf57d4c7 | ||
|
|
8c82d9924c | ||
|
|
a050a8054f | ||
|
|
a12999c3d5 | ||
|
|
309a805794 | ||
|
|
ac9198dd52 | ||
|
|
7eed207163 | ||
|
|
952c67f752 | ||
|
|
e4d0a36b5a | ||
|
|
d1f311d2a3 | ||
|
|
52e81f8158 | ||
|
|
7cca129a8e | ||
|
|
006ab617e8 | ||
|
|
fbc4c51c8f | ||
|
|
6f68b8659d | ||
|
|
f49782daaf | ||
|
|
69374c8868 | ||
|
|
7c9fa1dc3b | ||
|
|
c412491972 | ||
|
|
6fbbab6c6f | ||
|
|
eb2be13a1e | ||
|
|
7fd5ad50b8 | ||
|
|
b21be36bf8 | ||
|
|
35e4b4cc92 | ||
|
|
f1876f1260 | ||
|
|
703c33a089 | ||
|
|
16def0187c | ||
|
|
d61ffa5430 | ||
|
|
9fcd7c1468 | ||
|
|
a6aa26ea2a | ||
|
|
ea4ac8cc6e | ||
|
|
f62b89fccc | ||
|
|
3edc7ee1a0 | ||
|
|
42b6363646 | ||
|
|
7ff13704ff | ||
|
|
a53e25f398 | ||
|
|
ade8bdd36a | ||
|
|
0e221ba78a | ||
|
|
5f31f1292a | ||
|
|
5de7b0964e | ||
|
|
61418e9cb5 | ||
|
|
fd22254194 | ||
|
|
e666bb2e33 | ||
|
|
4f2d85007b | ||
|
|
6e5f91f7fd | ||
|
|
e38599b82b | ||
|
|
437008c517 | ||
|
|
5947204022 | ||
|
|
d4a2a84c36 | ||
|
|
1c94aeb476 | ||
|
|
b9014f34cf | ||
|
|
0920f189d6 | ||
|
|
a3c7591624 | ||
|
|
1ba9ace7e2 | ||
|
|
d8e58296be | ||
|
|
196057019f | ||
|
|
272a183442 | ||
|
|
cd57b7f053 | ||
|
|
45dd96cdeb | ||
|
|
22db3ab9c3 | ||
|
|
343dd51082 | ||
|
|
75c57e2691 | ||
|
|
856fc3009e | ||
|
|
3f7a072fa1 | ||
|
|
c9a2b6200e | ||
|
|
c1d552e578 | ||
|
|
02d22fe658 | ||
|
|
7f9a618cac | ||
|
|
1877d8c1a1 | ||
|
|
839da450f7 | ||
|
|
ba42061885 | ||
|
|
2b359f9a98 | ||
|
|
b83c1a60c2 | ||
|
|
f213999338 | ||
|
|
920e321109 | ||
|
|
ede0705bd5 | ||
|
|
a75c332905 | ||
|
|
954180beb0 | ||
|
|
eb6483030c | ||
|
|
6c9c02417e | ||
|
|
9e7f842caf | ||
|
|
0bda7b194b | ||
|
|
9ab90941ef | ||
|
|
1dc1c67095 | ||
|
|
6f7c8e246f | ||
|
|
5638f8d04e | ||
|
|
f156baa976 | ||
|
|
d41bccc50c | ||
|
|
9087fa61d9 | ||
|
|
6404c30718 | ||
|
|
66a765664c | ||
|
|
fe1b5eacf8 | ||
|
|
21c4b08a5d | ||
|
|
f8e0ad57ff | ||
|
|
72e1d6afc1 | ||
|
|
8ffd6c9e2c | ||
|
|
dbfec0c433 | ||
|
|
1bdd5b4094 | ||
|
|
88eba9f3bd | ||
|
|
8044948178 | ||
|
|
0425004ecd | ||
|
|
c1b45b037d | ||
|
|
f5732dd706 | ||
|
|
e86e28ae63 | ||
|
|
82fdd97588 | ||
|
|
1757d26e78 | ||
|
|
766e1edc0c | ||
|
|
fc52975be0 | ||
|
|
c3726daed6 | ||
|
|
69c9521e85 | ||
|
|
fc60719d4b | ||
|
|
e35ba7d805 | ||
|
|
fa0783ab03 | ||
|
|
5338a34008 | ||
|
|
1d3547a953 | ||
|
|
14ed7aa647 | ||
|
|
27164e8919 | ||
|
|
62bac6ec8c | ||
|
|
17a32e0c1f | ||
|
|
e0ed6a0a3b | ||
|
|
db0cdccd66 | ||
|
|
4237117f2c | ||
|
|
26edc6d826 | ||
|
|
92c71837cb | ||
|
|
0791e73974 | ||
|
|
a8773a196c | ||
|
|
5f50469d7e | ||
|
|
9e4fbe863d | ||
|
|
7fdd39a628 | ||
|
|
9d8fdab75e | ||
|
|
f09d51bd49 | ||
|
|
00aef16862 | ||
|
|
87b659b3ac | ||
|
|
709cde907e | ||
|
|
6a69707220 | ||
|
|
e30651473d | ||
|
|
8397e5e2a3 | ||
|
|
890fade636 | ||
|
|
dfe4784874 | ||
|
|
43c9053624 | ||
|
|
05c64c2475 | ||
|
|
3334d1016b | ||
|
|
637e227efa | ||
|
|
5432d7f288 | ||
|
|
2fdc024358 | ||
|
|
84267f44ed | ||
|
|
e08e455fe5 | ||
|
|
ceb020857a | ||
|
|
e8f5f6d6ba | ||
|
|
b0f5c9aed0 | ||
|
|
f40550e0cf | ||
|
|
43d668dc75 | ||
|
|
81a746b8e2 | ||
|
|
0aaa586cec | ||
|
|
159f10ba82 | ||
|
|
355d6005aa | ||
|
|
98a6de6ff0 | ||
|
|
2f3f08efde | ||
|
|
797904c308 | ||
|
|
c8f9f9cc37 | ||
|
|
db57c0961e | ||
|
|
70f6316a69 | ||
|
|
ac68fbe39e | ||
|
|
41f4e22b29 | ||
|
|
af2e515d0f | ||
|
|
a1ed7af5cf | ||
|
|
43dac21ac3 | ||
|
|
0d3b001191 | ||
|
|
0f328854a2 | ||
|
|
5ae211ecd6 | ||
|
|
55274d2dd1 | ||
|
|
72f7b59e3b | ||
|
|
581672eebc | ||
|
|
eace2fc741 | ||
|
|
f39b728947 | ||
|
|
f307355369 | ||
|
|
611f40c6ce | ||
|
|
391b91539f | ||
|
|
5633d76da1 | ||
|
|
310cbaad66 | ||
|
|
bc63e8e029 | ||
|
|
a579d81694 | ||
|
|
6eb1f0713d | ||
|
|
95d4a41b62 | ||
|
|
18ac414b52 | ||
|
|
10e399cbec | ||
|
|
ce4b2f9655 | ||
|
|
65686e246e | ||
|
|
3078674a86 | ||
|
|
82d8a6ea19 | ||
|
|
3785b75582 | ||
|
|
15b55c66ca | ||
|
|
d6d6fd0909 | ||
|
|
7bfad25bb5 | ||
|
|
5c31ccfe70 | ||
|
|
304674d0fe | ||
|
|
aa003541a3 | ||
|
|
d2699c430e | ||
|
|
f404a33e7a | ||
|
|
05e7db4be6 | ||
|
|
8ad3fc4faf | ||
|
|
3f7b83e8fd | ||
|
|
7fa280e9e0 | ||
|
|
3c8acf8ee3 | ||
|
|
0d94a8973e | ||
|
|
18f28cd804 | ||
|
|
37f2dd3ced | ||
|
|
ba5eb92c70 | ||
|
|
bbbcf23c77 | ||
|
|
ac9f745dcf | ||
|
|
86cfabfbe4 | ||
|
|
6b038245fd | ||
|
|
e985322f3a | ||
|
|
1f329cbc87 | ||
|
|
0f0cdd4672 | ||
|
|
875b17938e | ||
|
|
6820d27af5 | ||
|
|
02aa916a26 | ||
|
|
a7b9529109 | ||
|
|
0303a513cd | ||
|
|
a2bf7fb0c4 | ||
|
|
17dd723a3d | ||
|
|
f1097831d7 | ||
|
|
ad0a755f07 | ||
|
|
099bb57abd | ||
|
|
1ba2ce55bb | ||
|
|
24588b0975 | ||
|
|
8dc1fecc0e | ||
|
|
cb7668d4f0 | ||
|
|
90377204aa | ||
|
|
1d3de3c366 | ||
|
|
4466a059b3 | ||
|
|
b7bacc8ff5 | ||
|
|
50508b0af0 | ||
|
|
ef4458c04c | ||
|
|
0666f9ea5a | ||
|
|
3fe4e12252 | ||
|
|
9ecb664036 | ||
|
|
e6c8d6d9ac | ||
|
|
a68ebc1293 | ||
|
|
8b267c6307 | ||
|
|
67460f1275 | ||
|
|
4a620287c8 | ||
|
|
607812d8fa | ||
|
|
90f9d4ffd0 | ||
|
|
0f359ddf3b | ||
|
|
51a6b40314 | ||
|
|
bd5af356f4 | ||
|
|
d3cb8513be | ||
|
|
29d1a52d91 | ||
|
|
5b24b61b49 | ||
|
|
1dd8ea9b3b | ||
|
|
2221afad01 | ||
|
|
471bce2bb1 | ||
|
|
b630dfad55 | ||
|
|
74b50f7592 | ||
|
|
95bc3622ab | ||
|
|
b911366115 | ||
|
|
b2a9d105e2 | ||
|
|
b83c2cf11a | ||
|
|
6648f502f1 | ||
|
|
115003f0b6 | ||
|
|
02d912d72a | ||
|
|
70fe0e6653 | ||
|
|
950bf986d6 | ||
|
|
310d923480 | ||
|
|
0c506fa479 | ||
|
|
bc86836492 | ||
|
|
dead55af21 | ||
|
|
c7a4201ce9 | ||
|
|
91cf66e72e | ||
|
|
4a87022e58 | ||
|
|
c92bd0999b | ||
|
|
880835f0ac | ||
|
|
ce938df81b | ||
|
|
9abe3d7e3c | ||
|
|
4e5ae49aa9 | ||
|
|
9443517d1c | ||
|
|
29f6131f9d | ||
|
|
4027b8341f | ||
|
|
ddc483fd2a | ||
|
|
23d81a2b3d | ||
|
|
74f61a3540 | ||
|
|
c287ce0ee3 | ||
|
|
607e4e095d | ||
|
|
e7da5e0937 | ||
|
|
ae4a90b23a | ||
|
|
04006f2ea7 | ||
|
|
7f20fc0c54 | ||
|
|
a8db175c25 | ||
|
|
8aacedf5ad | ||
|
|
1425bfe8ae | ||
|
|
75ec6c51a3 | ||
|
|
b20e7c0817 | ||
|
|
adf5701e16 | ||
|
|
5debc5297b | ||
|
|
5db70297cb | ||
|
|
0f78b845e6 | ||
|
|
c319656529 | ||
|
|
4ebc769042 | ||
|
|
300424658a | ||
|
|
44ccaaef26 | ||
|
|
befb4792ce | ||
|
|
34741f56c4 | ||
|
|
2907832e37 | ||
|
|
ff4e916561 | ||
|
|
2f799aede9 | ||
|
|
f853ccf544 | ||
|
|
8b4de98664 | ||
|
|
a36516d463 | ||
|
|
b7c2d4eacb | ||
|
|
abc5b2b2c6 | ||
|
|
cb10ba7207 | ||
|
|
0fe39535d6 | ||
|
|
0c9ffe1e41 | ||
|
|
cda99d5495 | ||
|
|
d979e102f9 | ||
|
|
67d68f7f4e | ||
|
|
2b73ef73f1 | ||
|
|
de41651a5e | ||
|
|
6bd2d5f843 | ||
|
|
93c15547ef | ||
|
|
90d98f3edd | ||
|
|
b7ef68df71 | ||
|
|
fdc4df4752 | ||
|
|
54ce048ec9 |
No files matched your search
@@ -0,0 +1,129 @@
|
||||
---
|
||||
name: pr
|
||||
description: Prepare and open an OpenIDEA pull request that a maintainer can accept from its description — scope check, the checks CI runs, evidence chosen by the kind of change, UX consistency review, and a filled-in template. Use before opening or updating a PR ("提 pr", "open a PR", "写 PR 描述", "准备验收证据").
|
||||
---
|
||||
|
||||
# Open a pull request with evidence
|
||||
|
||||
A reviewer should be able to accept the PR from its description: what changed, why, and proof
|
||||
that it works and didn't break its neighbours. Evidence is the part people skip; it is required.
|
||||
|
||||
## 1. Scope
|
||||
|
||||
- One problem per PR. If the description needs more than 2–4 sentences, split it.
|
||||
- `Closes #<n>` when it resolves an issue. Read the issue's comments first: a maintainer may
|
||||
already have decided how it should behave.
|
||||
- The diff contains only what the problem needs: no drive-by refactors, formatting of untouched
|
||||
files, generated files you didn't need to regenerate, or local IDE state (`.openidea/`).
|
||||
- A product decision you can't make (layout or navigation restructure, a changed default, an
|
||||
unclear expected behaviour) → ask in the issue, label `needs-decision`, stop.
|
||||
- Title in Conventional Commits, written as the commit you want on `main`:
|
||||
`fix(editor): keep the caret visible after folding`. It describes the change, not the
|
||||
process; no references to screenshots, other products or "parity".
|
||||
|
||||
## 2. Checks
|
||||
|
||||
Run what CI runs for the parts you touched (`AGENTS.md` § Before opening a PR). Run long checks
|
||||
one at a time. Paste the command and its result line (`test result: ok. 412 passed`,
|
||||
`Tests 87 passed`), not "tests pass".
|
||||
|
||||
Easy to miss:
|
||||
|
||||
| You touched | Also run |
|
||||
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
||||
| Any `.ts`/`.tsx`, including tests | `pnpm typecheck` |
|
||||
| A feature's UI | every spec under `e2e/` whose name contains the feature |
|
||||
| New regex in frontend code | `pnpm vitest run src/platform/webkitCompatibility.test.ts` |
|
||||
| Text catalog keys | `pnpm vitest run src/platform/locales/textCatalog.test.ts src/platform/i18n.test.ts` |
|
||||
| `tokens.css` | `pnpm gen:theme-docs`, then the full `pnpm test` |
|
||||
| Moved or removed exports | `pnpm knip` |
|
||||
| A `pub fn` signature | `cargo test -p <crate>` (all targets), or workspace clippy |
|
||||
| A new crate dependency, or imports in files the smoke runs load | `pnpm vitest run scripts/smoke-paths.test.ts` |
|
||||
| IPC types | `pnpm gen:bindings`, commit `src/bindings.ts` |
|
||||
| `wit/` or the plugin SDK | `plugins/build.sh`, commit the rebuilt `dist/` |
|
||||
|
||||
## 3. Evidence
|
||||
|
||||
Pick every row that applies. Evidence must come from the final commit of the branch; re-take it
|
||||
after review changes that affect it.
|
||||
|
||||
| Change | Evidence |
|
||||
| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Bug fix | A test that fails on `main` and passes on the branch (name it), or exact steps from a fresh start with the before/after result |
|
||||
| Visible UI | `before.png` / `after.png` at the same state and window size. Every theme the change touches (at least Islands Light and Islands Dark when colours, borders or icons change). The narrow case when width matters |
|
||||
| Interaction: multi-step, drag and drop, keyboard, focus, animation | A short recording (GIF/MP4), or numbered screenshots of each step |
|
||||
| Keyboard shortcut or action | Where it appears (Find Action, menu, keymap settings) and that it doesn't clash in the default keymaps |
|
||||
| Code intelligence / language support | Which `fixtures/` project, `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` output; for Java, `pnpm eval --only <id>` numbers before/after |
|
||||
| Run / debug | `pnpm smoke smoke/run.test.ts -t <language>` or `smoke/debug.test.ts`, plus a screenshot of the Run/Debug tool window |
|
||||
| Performance | Before/after numbers on the same machine and build type (`pnpm perf`, `pnpm perf:rust`, or the exact measurement), and evidence the results are identical: a fast path must return the same results or fall back |
|
||||
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine. Say plainly if you couldn't run it on that platform |
|
||||
| Backend / IPC | Test output; logs for behaviour tests can't reach |
|
||||
| Remote development / containers / WSL | The flow against a real `openidea-server` host or container, with a screenshot or log |
|
||||
| Plugin API / `wit/` | A sample plugin exercising the change, and the rebuilt `dist/` |
|
||||
| Settings / persisted data / migrations | Start from data written by the previous release and show it still loads and behaves the same |
|
||||
| Security fix | A test for the attack case. Describe the class of problem only; follow `SECURITY.md` for anything not yet public |
|
||||
| Copy, docs, pure refactor | The commands run, and "No visible change" / "no behaviour change" stated |
|
||||
|
||||
Also state what else the change could affect (other languages, platforms, entry points such as
|
||||
menu / context menu / shortcut, other themes) and how you checked each.
|
||||
|
||||
How to capture:
|
||||
|
||||
- Use the `verify` skill to drive the app and take screenshots. Before: on `main` (or with the
|
||||
fix reverted). After: on the branch, same state and window size.
|
||||
- Crop to the relevant area when the window is large, but keep enough context to locate it.
|
||||
- Drag screenshots and recordings into the PR description on GitHub. Never commit them.
|
||||
- No real credentials, tokens, private repository names or personal paths in screenshots or logs.
|
||||
|
||||
## 4. UX consistency
|
||||
|
||||
For any change users can see, review it against `DESIGN.md`, `PRODUCT.md` and
|
||||
`docs/en/contribute/guidelines/ui.mdx` before taking the "after" screenshots:
|
||||
|
||||
- Tokens only; spacing on the `--space-*` scale; icons from `src/ui/icons.tsx`; no emoji.
|
||||
- Built from `src/ui/` primitives and workbench contributions; it looks like its neighbours
|
||||
(same row height, font size, padding, hover/selection, empty state) rather than new.
|
||||
- Same action, same name, place and shortcut as elsewhere in the IDE.
|
||||
- Keyboard reachable, visible focus, focus returns sensibly; `aria-label` on icon buttons.
|
||||
- Every new string in `en.json` and `zh.json`; long translations don't break the layout.
|
||||
- Light and dark, default and narrow widths all look right.
|
||||
- The Impeccable design skills can help critique and polish; they read `DESIGN.md`,
|
||||
`PRODUCT.md` and `.impeccable/`.
|
||||
|
||||
A layout or navigation restructure needs a maintainer decision first (§ 1).
|
||||
|
||||
## 5. Description
|
||||
|
||||
Fill in `.github/pull_request_template.md`; keep it short and plain:
|
||||
|
||||
```markdown
|
||||
Closes #123
|
||||
|
||||
## What and why
|
||||
|
||||
<The change a user notices, and the root cause. 2–4 sentences.>
|
||||
|
||||
## How it was verified
|
||||
|
||||
- [x] Bug fix: `pnpm vitest run src/features/editor/folding.test.ts` — the new
|
||||
`keeps caret visible after fold` fails on main, passes here (12 passed)
|
||||
- [x] Visible UI: before / after (Islands Light, Islands Dark)
|
||||
<screenshots>
|
||||
- `pnpm typecheck`, `pnpm lint`, `pnpm e2e e2e/editor-folding.spec.ts` — all pass
|
||||
- Also affected: folding from the gutter and from ⌘- — both checked in the app
|
||||
|
||||
## Review focus
|
||||
|
||||
<Optional.>
|
||||
```
|
||||
|
||||
The `PR check` workflow labels the PR `needs-info` when **How it was verified** is empty, or when
|
||||
the PR changes UI files and the section has no screenshot or recording and doesn't say
|
||||
"No visible change".
|
||||
|
||||
## 6. Before you push
|
||||
|
||||
- Re-read the diff as the reviewer: anything unrelated, debug output, commented-out code,
|
||||
leftover TODOs?
|
||||
- Rebased on current `main`; checks re-run if the rebase changed anything they cover.
|
||||
- Open as draft while evidence is missing; mark ready once it's in.
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
name: verify
|
||||
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
|
||||
---
|
||||
|
||||
# Verify OpenIDEA in the running app
|
||||
|
||||
## Launch
|
||||
|
||||
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
|
||||
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
|
||||
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
|
||||
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
|
||||
session already running for this worktree, reuse that one.
|
||||
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
|
||||
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
|
||||
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
|
||||
`location.href` before acting if anything looks off.
|
||||
- Make sure the binary contains the change: a session already running for this worktree may be an
|
||||
older build. Restart it after Rust changes; frontend changes reload through Vite.
|
||||
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
|
||||
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
|
||||
reload shows an empty `#root`. Stop that app and start the session again.
|
||||
- Stop everything you started when done and nothing else; never use process-name kills.
|
||||
|
||||
## Driving
|
||||
|
||||
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
|
||||
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
|
||||
screenshots come back black.
|
||||
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
|
||||
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
|
||||
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
|
||||
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
|
||||
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
|
||||
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
|
||||
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
|
||||
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
|
||||
|
||||
## Evidence
|
||||
|
||||
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
|
||||
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
|
||||
flows: a numbered series (`after-1.png`, `after-2.png`, ...). When colours, borders or icons
|
||||
change, take each in Islands Light and Islands Dark. The `pr` skill lists what evidence each
|
||||
kind of change needs.
|
||||
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
|
||||
acceptance entry. Never commit screenshots to the feature branch.
|
||||
|
||||
## Fixture
|
||||
|
||||
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
|
||||
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
|
||||
|
||||
## Flows worth driving
|
||||
|
||||
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
|
||||
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
|
||||
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
|
||||
Symlink
@@ -0,0 +1 @@
|
||||
../../.agents/skills/pr
|
||||
Symlink
@@ -0,0 +1 @@
|
||||
../../.agents/skills/verify
|
||||
@@ -16,5 +16,5 @@ test-group = "windows-clipboard"
|
||||
# that hangs (a server left stopped) is ended after 5 minutes instead of waiting for svn's own
|
||||
# timeout.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(=ide-svn) | (package(=ide-host) & (binary(=svn) | binary(=ij_svn_roots)))'
|
||||
filter = 'package(=ide-svn) | (package(=ide-host) & binary(=integration) & (test(/^svn::/) | test(/^ij_svn_roots::/)))'
|
||||
slow-timeout = { period = "60s", terminate-after = 5 }
|
||||
Бінарний файл не відображається.
|
До Ширина: | Висота: | Розмір: 169 KiB |
Бінарний файл не відображається.
|
Після Ширина: | Висота: | Розмір: 179 KiB |
@@ -6,4 +6,6 @@ updates:
|
||||
directory: /
|
||||
schedule: { interval: weekly }
|
||||
groups:
|
||||
actions: { patterns: ["*"] }
|
||||
# tauri-action builds and uploads the release, so its updates come as their own PR and are
|
||||
# merged after a draft release has gone through with them.
|
||||
actions: { patterns: ["*"], exclude-patterns: ["tauri-apps/tauri-action"] }
|
||||
@@ -7,11 +7,20 @@
|
||||
|
||||
## How it was verified
|
||||
|
||||
<!-- Required. Commands you actually ran and their results; what else this could
|
||||
affect and how you checked it still works.
|
||||
Visible UI changes: before/after screenshots (not for removed UI or copy-only
|
||||
changes). Multi-step interactions: a recording.
|
||||
Backend changes: logs or command output. -->
|
||||
<!-- Required, from the final version of this branch. Commands you actually ran and
|
||||
their results; what else this could affect and how you checked it still works.
|
||||
Then the evidence for each kind of change this PR makes (AGENTS.md § Issues & PRs):
|
||||
|
||||
- Bug fix: a test that fails on main and passes here, or exact repro steps
|
||||
- Visible UI: before/after screenshots, same state and size; each theme touched
|
||||
- Interaction (multi-step, drag, keyboard, focus): a recording
|
||||
- Code intelligence / run / debug: language_smoke or smoke output on a fixture
|
||||
- Performance: before/after numbers on the same machine, and the results unchanged
|
||||
- Windows/Linux only: CI job plus a screenshot or log from a real machine
|
||||
- Settings / persisted data: starting from the previous version's data
|
||||
- Copy, docs, refactor, no UI change: write "No visible change"
|
||||
|
||||
Drag screenshots and recordings in here; don't commit them. -->
|
||||
|
||||
## Review focus
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ BASEDPYRIGHT=1.40.2
|
||||
RUFF=0.17.3
|
||||
GOPLS=v0.24.0
|
||||
JDTLS=1.63.0-202610191322
|
||||
KOTLIN_LSP=271.2085.0
|
||||
KOTLIN_LSP=271.3588.0
|
||||
GRADLE=8.14.3
|
||||
INTELEPHENSE=1.18.5
|
||||
# The JDK projects compile against (JAVA_HOME): library navigation opens its sources.
|
||||
|
||||
@@ -106,8 +106,9 @@ jobs:
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
permissions:
|
||||
contents: read
|
||||
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run.
|
||||
timeout-minutes: ${{ matrix.os == 'windows-latest' && 75 || 60 }}
|
||||
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run;
|
||||
# on macOS clippy plus the test build alone take ~45 minutes.
|
||||
timeout-minutes: ${{ matrix.os == 'ubuntu-latest' && 60 || 75 }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -117,13 +118,6 @@ jobs:
|
||||
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
|
||||
with: { version: 11 }
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
with:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
with: { components: "clippy, rustfmt" }
|
||||
# Self-hosted runners keep persistent local Cargo caches; GitHub-hosted runners use Actions cache
|
||||
@@ -147,6 +141,11 @@ jobs:
|
||||
fi
|
||||
- uses: taiki-e/install-action@073e1fd0bc889c9aee68dbaaa927cde1b5653a83 # v2.90.11
|
||||
with: { tool: nextest }
|
||||
# ide-sdk's .NET status test and crates/ide-coverage/tests/dotnet_cli.rs run the real `dotnet`
|
||||
# CLI; with CI set they fail, not skip, when it is missing.
|
||||
- uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5.4.0
|
||||
with:
|
||||
dotnet-version: 10.0.x
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
@@ -163,11 +162,14 @@ jobs:
|
||||
shell: bash
|
||||
run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version
|
||||
# tauri-build checks that frontendDist exists.
|
||||
- run: pnpm install --frozen-lockfile && mkdir -p dist
|
||||
- run: mkdir -p dist
|
||||
shell: bash
|
||||
- if: runner.os == 'Linux'
|
||||
run: cargo fmt --all --check
|
||||
- run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
# On PRs, run clippy on Linux only; macOS/Windows still compile and test all targets
|
||||
# via nextest, and run clippy on main/merge_group so platform-only lints are still caught.
|
||||
- if: runner.os == 'Linux' || github.event_name != 'pull_request'
|
||||
run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
# Test fixtures write LF files; keep Git from converting them on checkout.
|
||||
- run: git config --global core.autocrlf false
|
||||
- name: Restore Maven artifacts for Java build tests
|
||||
@@ -211,14 +213,47 @@ jobs:
|
||||
with:
|
||||
path: ${{ runner.temp }}/jbuild-maven-repository
|
||||
key: ${{ steps.jbuild-maven-cache.outputs.cache-primary-key }}
|
||||
# python_yappi.rs profiles real runs. Self-hosted runners have no setup-python; without
|
||||
# YAPPI_PYTHON those tests return early.
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
if: runner.environment == 'github-hosted'
|
||||
id: yappi-python
|
||||
with: { python-version: "3.12", update-environment: false }
|
||||
- name: Install yappi for the Python profiler tests
|
||||
if: steps.yappi-python.outputs.python-path != ''
|
||||
shell: bash
|
||||
env:
|
||||
PYTHON: ${{ steps.yappi-python.outputs.python-path }}
|
||||
run: |
|
||||
"$PYTHON" -m venv "$RUNNER_TEMP/yappi-venv"
|
||||
venv_py="$RUNNER_TEMP/yappi-venv/bin/python"
|
||||
[ -x "$venv_py" ] || venv_py="$RUNNER_TEMP/yappi-venv/Scripts/python.exe"
|
||||
"$venv_py" -m pip install yappi==1.7.6
|
||||
echo "YAPPI_PYTHON=$venv_py" >> "$GITHUB_ENV"
|
||||
# python_memray.rs profiles real runs. memray has no Windows build.
|
||||
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
if: runner.os != 'Windows' && runner.environment == 'github-hosted'
|
||||
id: memray-python
|
||||
with: { python-version: "3.12", update-environment: false }
|
||||
- name: Install memray for the Python profiler tests
|
||||
# Self-hosted runners have no setup-python; without MEMRAY_PYTHON those tests return early.
|
||||
if: steps.memray-python.outputs.python-path != ''
|
||||
shell: bash
|
||||
env:
|
||||
PYTHON: ${{ steps.memray-python.outputs.python-path }}
|
||||
run: |
|
||||
"$PYTHON" -m venv "$RUNNER_TEMP/memray-venv"
|
||||
"$RUNNER_TEMP/memray-venv/bin/python" -m pip install memray==1.21.0
|
||||
echo "MEMRAY_PYTHON=$RUNNER_TEMP/memray-venv/bin/python" >> "$GITHUB_ENV"
|
||||
- run: cargo nextest run --workspace --no-fail-fast
|
||||
- name: Remote backend with Docker Compose
|
||||
# Self-hosted runner containers do not mount /var/run/docker.sock (scripts/selfhost-runner/README.md).
|
||||
if: runner.os == 'Linux' && runner.environment != 'self-hosted'
|
||||
run: |
|
||||
docker pull busybox:latest
|
||||
cargo nextest run -p ide-host --test remote_daemon --run-ignored only \
|
||||
-E 'test(=compose_service_survives_disconnect_and_is_removed_on_stop)'
|
||||
# --workspace, not -p ide-host: -p would rebuild instead of reusing the test build above.
|
||||
cargo nextest run --workspace --run-ignored only \
|
||||
-E 'package(=ide-host) & binary(=integration) & test(=remote_daemon::compose_service_survives_disconnect_and_is_removed_on_stop)'
|
||||
# nextest skips doctests; ide-command's are its compile-fail tests.
|
||||
- if: runner.os == 'Linux'
|
||||
run: cargo test --doc -p ide-command
|
||||
@@ -257,7 +292,9 @@ jobs:
|
||||
with: { targets: x86_64-unknown-linux-musl }
|
||||
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
if: runner.environment != 'self-hosted'
|
||||
with: { key: server-musl }
|
||||
with:
|
||||
key: server-musl
|
||||
save-if: ${{ github.ref == 'refs/heads/main' }}
|
||||
- name: Persistent Cargo target dir
|
||||
if: runner.environment == 'self-hosted'
|
||||
shell: bash
|
||||
@@ -370,6 +407,12 @@ jobs:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
# src/features/dotnet/edit.test.ts and *.cli.test.ts run the real `dotnet` CLI; with CI set they fail, not skip, when it is missing.
|
||||
- uses: actions/setup-dotnet@v5
|
||||
with:
|
||||
dotnet-version: |
|
||||
10.0.x
|
||||
11.0.x
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
|
||||
@@ -26,6 +26,9 @@ on:
|
||||
- "src/features/build/**"
|
||||
- "src/features/build-tools/**"
|
||||
- "src/platform/**"
|
||||
- "!src/platform/locales/text/**"
|
||||
- "!src/platform/locales/*.json"
|
||||
- "src/platform/locales/en.json"
|
||||
- "src/workbench/**"
|
||||
- "src/ui/**"
|
||||
- "src/editor/api.ts"
|
||||
@@ -36,6 +39,7 @@ on:
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/core/cm/inlineBg.ts"
|
||||
- "src/editor/core/cm/localAppearance.ts"
|
||||
- "src/editor/core/cm/lineNumberOptions.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
- "src/editor/lsp/files.ts"
|
||||
@@ -46,7 +50,7 @@ on:
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
- "src-tauri/icons/128x128.png"
|
||||
- "src/assets/openidea-logo.png"
|
||||
- "smoke/**"
|
||||
- "vite.config.ts"
|
||||
- "tsconfig.json"
|
||||
@@ -88,6 +92,7 @@ jobs:
|
||||
pull-requests: read
|
||||
outputs:
|
||||
languages: ${{ steps.classify.outputs.languages }}
|
||||
groups: ${{ steps.classify.outputs.groups }}
|
||||
steps:
|
||||
- id: classify
|
||||
env:
|
||||
@@ -97,8 +102,18 @@ jobs:
|
||||
set -euo pipefail
|
||||
all="typescript python rust go java kotlin php c cpp"
|
||||
emit() { tr ' ' '\n' <<< "$1" | { grep . || true; } | sort -u | jq -Rsc 'split("\n") | map(select(. != ""))'; }
|
||||
emit_groups() {
|
||||
jq -nc --argjson langs "$1" '
|
||||
[
|
||||
{ name: "jvm", languages: ($langs | map(select(. == "java" or . == "kotlin"))) },
|
||||
{ name: "systems", languages: ($langs | map(select(. == "rust" or . == "go" or . == "c" or . == "cpp"))) },
|
||||
{ name: "scripting", languages: ($langs | map(select(. == "typescript" or . == "python" or . == "php"))) }
|
||||
] | map(select(.languages | length > 0))'
|
||||
}
|
||||
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
|
||||
echo "languages=$(emit "$all")" | tee -a "$GITHUB_OUTPUT"
|
||||
langs_json=$(emit "$all")
|
||||
echo "languages=$langs_json" | tee -a "$GITHUB_OUTPUT"
|
||||
echo "groups=$(emit_groups "$langs_json")" | tee -a "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
|
||||
@@ -107,15 +122,18 @@ jobs:
|
||||
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
|
||||
# SDKs, build tools, the project model, Find Usages candidates, debug stream traces):
|
||||
# cargo metadata, ide-host's direct deps ide-search/ide-streams and the deps of
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# ide-lsp/dap/run/sdk/tools. Also skip non-English lazy locale catalogs (smoke always
|
||||
# runs in the default English locale).
|
||||
unused='^(crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/|src/platform/locales/text/)'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src/assets/openidea-logo\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
crates/ide-host/tests/language_smoke.rs | crates/ide-host/tests/project_smoke.rs) langs="$all"; break ;;
|
||||
crates/*/tests/* | crates/*/benches/*) ;;
|
||||
src/platform/locales/en.json) langs="$all"; break ;;
|
||||
src/platform/locales/*.json) ;;
|
||||
fixtures/ts-app/*) langs+=" typescript" ;;
|
||||
fixtures/python-app/*) langs+=" python" ;;
|
||||
fixtures/rust-app/*) langs+=" rust" ;;
|
||||
@@ -140,7 +158,9 @@ jobs:
|
||||
*) if grep -Eq "$smoke" <<< "$f" && ! grep -Eq "$unused" <<< "$f"; then langs="$all"; break; fi ;;
|
||||
esac
|
||||
done < files.txt
|
||||
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
|
||||
langs_json=$(emit "$langs")
|
||||
echo "languages=$langs_json" | tee -a "$GITHUB_OUTPUT"
|
||||
echo "groups=$(emit_groups "$langs_json")" | tee -a "$GITHUB_OUTPUT"
|
||||
|
||||
# Builds the smoke test binaries and openidea-server once for every language below.
|
||||
build:
|
||||
@@ -189,12 +209,12 @@ jobs:
|
||||
with: { name: smoke-bin, path: smoke-bin.tar, retention-days: 1 }
|
||||
|
||||
smoke:
|
||||
name: Language smoke (${{ matrix.language }})
|
||||
name: Language smoke (${{ matrix.group.name }})
|
||||
needs: [changes, build]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ${{ fromJSON(needs.changes.outputs.languages) }}
|
||||
group: ${{ fromJSON(needs.changes.outputs.groups) }}
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
@@ -207,7 +227,8 @@ jobs:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
# Tool versions, shared with the evals (pnpm eval).
|
||||
- run: grep -E '^[A-Z0-9_]+=' .github/tool-versions.env >> "$GITHUB_ENV"
|
||||
- uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
- if: contains(matrix.group.languages, 'rust')
|
||||
uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable
|
||||
with: { components: "rust-analyzer, rustfmt" }
|
||||
- uses: actions/download-artifact@018cc2cf5baa6db3ef3c5f8a56943fffe632ef53 # v6.0.0
|
||||
with: { name: smoke-bin }
|
||||
@@ -222,11 +243,11 @@ jobs:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
- if: matrix.language == 'typescript'
|
||||
- if: contains(matrix.group.languages, 'typescript')
|
||||
run: npm install --global "@vtsls/language-server@$VTSLS" "typescript@$TYPESCRIPT"
|
||||
|
||||
# The smoke checks C/C++ with clangd and debugs c-app with GDB's own DAP interpreter (GDB 14+).
|
||||
- if: matrix.language == 'c' || matrix.language == 'cpp'
|
||||
- if: contains(matrix.group.languages, 'c') || contains(matrix.group.languages, 'cpp')
|
||||
shell: bash
|
||||
run: |
|
||||
pkgs=()
|
||||
@@ -242,22 +263,22 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- if: matrix.language == 'python'
|
||||
- if: contains(matrix.group.languages, 'python')
|
||||
uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
|
||||
with: { python-version: "3.12" }
|
||||
- if: matrix.language == 'python'
|
||||
- if: contains(matrix.group.languages, 'python')
|
||||
run: pip install "basedpyright==$BASEDPYRIGHT" "ruff==$RUFF"
|
||||
|
||||
- if: matrix.language == 'go'
|
||||
- if: contains(matrix.group.languages, 'go')
|
||||
uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0
|
||||
with: { go-version: "1.27", cache: false }
|
||||
- if: matrix.language == 'go'
|
||||
- if: contains(matrix.group.languages, 'go')
|
||||
run: go install "golang.org/x/tools/gopls@$GOPLS"
|
||||
|
||||
- if: matrix.language == 'java' || matrix.language == 'kotlin'
|
||||
- if: contains(matrix.group.languages, 'java') || contains(matrix.group.languages, 'kotlin')
|
||||
uses: actions/setup-java@cf277c60eb25467037889841efdb72551f06f6c3 # v4.9.1
|
||||
with: { distribution: temurin, java-version: "${{ env.JAVA }}" }
|
||||
- if: matrix.language == 'java'
|
||||
- if: contains(matrix.group.languages, 'java')
|
||||
run: |
|
||||
command -v mvn >/dev/null || { sudo apt-get update && sudo apt-get install -y maven; }
|
||||
mkdir -p "$RUNNER_TEMP/jdtls"
|
||||
@@ -266,10 +287,12 @@ jobs:
|
||||
echo "$RUNNER_TEMP/jdtls/bin" >> "$GITHUB_PATH"
|
||||
|
||||
# The Kotlin fixture has no Gradle wrapper: the server imports it with the Gradle on PATH.
|
||||
- if: matrix.language == 'kotlin'
|
||||
- if: contains(matrix.group.languages, 'kotlin')
|
||||
uses: gradle/actions/setup-gradle@ed408507eac070d1f99cc633dbcf757c94c7933a # v4.4.3
|
||||
with: { gradle-version: "${{ env.GRADLE }}" }
|
||||
- if: matrix.language == 'kotlin'
|
||||
with:
|
||||
gradle-version: "${{ env.GRADLE }}"
|
||||
cache-read-only: ${{ github.ref != 'refs/heads/main' }}
|
||||
- if: contains(matrix.group.languages, 'kotlin')
|
||||
run: |
|
||||
mkdir -p "$RUNNER_TEMP/kotlin-lsp" "$RUNNER_TEMP/bin"
|
||||
curl -fsSL "https://download.jetbrains.com/language-server/kotlin-server/$KOTLIN_LSP/kotlin-server-$KOTLIN_LSP.tar.gz" \
|
||||
@@ -278,31 +301,48 @@ jobs:
|
||||
echo "$RUNNER_TEMP/bin" >> "$GITHUB_PATH"
|
||||
|
||||
# Xdebug for the debug smoke; Composer installs the fixture's Pest for the run smoke.
|
||||
- if: matrix.language == 'php'
|
||||
- if: contains(matrix.group.languages, 'php')
|
||||
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
|
||||
with: { php-version: "8.5", coverage: xdebug, tools: composer }
|
||||
- if: matrix.language == 'php'
|
||||
- if: contains(matrix.group.languages, 'php')
|
||||
run: npm install --global "intelephense@$INTELEPHENSE"
|
||||
|
||||
# The binaries from the build job, run from the crate directory as `cargo test` does.
|
||||
- working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact ${{ matrix.language }}
|
||||
# Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in.
|
||||
- if: matrix.language == 'typescript'
|
||||
- name: Code intelligence and project smoke
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style
|
||||
- if: matrix.language == 'java'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier
|
||||
- if: matrix.language == 'kotlin'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact gradle_sync
|
||||
- if: matrix.language == 'python'
|
||||
working-directory: crates/ide-host
|
||||
run: ../../smoke-bin/project_smoke --ignored --exact python_venv
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
status=0
|
||||
for lang in ${{ join(matrix.group.languages, ' ') }}; do
|
||||
echo "::group::language_smoke ($lang)"
|
||||
../../smoke-bin/language_smoke --ignored --exact "$lang" || status=1
|
||||
# Problems › TypeScript Project Errors runs the project's own tsc: the global install stands in.
|
||||
if [ "$lang" = typescript ]; then
|
||||
../../smoke-bin/language_smoke --ignored --exact typescript_project_errors typescript_import_style || status=1
|
||||
fi
|
||||
if [ "$lang" = java ]; then
|
||||
../../smoke-bin/project_smoke --ignored --exact maven_sync jdk maven_launch_classpath_uses_the_runner_jdk_classifier || status=1
|
||||
fi
|
||||
if [ "$lang" = kotlin ]; then
|
||||
../../smoke-bin/project_smoke --ignored --exact gradle_sync || status=1
|
||||
fi
|
||||
if [ "$lang" = python ]; then
|
||||
../../smoke-bin/project_smoke --ignored --exact python_venv || status=1
|
||||
fi
|
||||
echo "::endgroup::"
|
||||
done
|
||||
exit "$status"
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm smoke smoke/run.test.ts -t "^${{ matrix.language }}$"
|
||||
- run: pnpm smoke smoke/debug.test.ts -t "^${{ matrix.language }}$"
|
||||
- name: Run and debug smoke
|
||||
shell: bash
|
||||
# The IDE installs the debugger from GitHub releases: authenticated, against rate limits.
|
||||
env: { GITHUB_TOKEN: "${{ github.token }}" }
|
||||
run: |
|
||||
set -euo pipefail
|
||||
pattern="^($(echo "${{ join(matrix.group.languages, '|') }}"))$"
|
||||
status=0
|
||||
pnpm smoke smoke/run.test.ts -t "$pattern" || status=1
|
||||
pnpm smoke smoke/debug.test.ts -t "$pattern" || status=1
|
||||
exit "$status"
|
||||
@@ -1,9 +1,9 @@
|
||||
name: PR check
|
||||
on:
|
||||
# pull_request_target so the check can label PRs from forks. It never checks out
|
||||
# or runs PR code: it only reads the PR title and description.
|
||||
# or runs PR code: it only reads the PR title, description and changed file names.
|
||||
pull_request_target:
|
||||
types: [opened, edited, reopened, ready_for_review]
|
||||
types: [opened, edited, reopened, ready_for_review, synchronize]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
@@ -34,6 +34,24 @@ jobs:
|
||||
|
||||
const { owner, repo } = context.repo;
|
||||
const issue_number = pr.number;
|
||||
|
||||
if (verified && verified[1].trim()) {
|
||||
const section = verified[1];
|
||||
const hasMedia =
|
||||
/!\[[^\]]*\]\(|<img\b|<video\b|github\.com\/user-attachments\/|https?:\/\/\S+\.(png|jpe?g|gif|webp|mp4|mov|webm)\b/i.test(section);
|
||||
const optedOut = /no visible change/i.test(section);
|
||||
if (!hasMedia && !optedOut) {
|
||||
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: issue_number, per_page: 100 });
|
||||
const ui = files
|
||||
.filter(f => f.status !== 'removed')
|
||||
.map(f => f.filename)
|
||||
.filter(name => /^src\/.*\.(tsx|css)$/.test(name) && !/\.(test|spec)\.tsx$/.test(name));
|
||||
if (ui.length) {
|
||||
const shown = ui.slice(0, 3).map(n => `\`${n}\``).join(', ') + (ui.length > 3 ? ', …' : '');
|
||||
problems.push(`This PR changes UI files (${shown}). Add before/after screenshots, or a recording for interactions, to **How it was verified**; if nothing users see changed, write "No visible change" and say what you checked.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
|
||||
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes(MARKER));
|
||||
const labeled = pr.labels.some(l => l.name === LABEL);
|
||||
|
||||
@@ -47,6 +47,7 @@ jobs:
|
||||
environment: release
|
||||
env:
|
||||
OPENIDEA_OFFICIAL_PLUGIN_KEYS: ${{ needs.plugin-keys.outputs.keys }}
|
||||
OPENIDEA_BUILD: ${{ github.sha }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
|
||||
+7
-5
@@ -27,18 +27,20 @@ dist-ssr
|
||||
|
||||
# Rust
|
||||
target/
|
||||
!/crates/ide-ssh/src/target/
|
||||
# Tauri generated schemas
|
||||
/src-tauri/gen/schemas
|
||||
*.tsbuildinfo
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
# Local AI agent files
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
|
||||
CLAUDE.local.md
|
||||
.agents/
|
||||
.claude/
|
||||
.claude/*
|
||||
!.claude/skills/
|
||||
.claude/skills/*
|
||||
!.claude/skills/pr
|
||||
!.claude/skills/verify
|
||||
|
||||
# Local reference screenshots
|
||||
pycharm-screenshots/
|
||||
@@ -20,6 +20,7 @@
|
||||
"pnpm-lock.yaml",
|
||||
"**/*.toml",
|
||||
"fixtures",
|
||||
"vendor",
|
||||
"plugins/*/web",
|
||||
"plugins/official/*/web",
|
||||
"crates/**/tests/fixtures"
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"src/editor/core/cm/angular/parser*.ts",
|
||||
"src/editor/core/cm/astro/parser*.ts",
|
||||
"fixtures",
|
||||
"vendor",
|
||||
"plugins",
|
||||
"test-results",
|
||||
"playwright-report",
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
# OpenIDEA — contributor guide
|
||||
|
||||
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
|
||||
Visual style: rounded content islands on a grey frame, low-contrast greys, one cool accent;
|
||||
Islands Light is the default theme. `src/styles/tokens.css` is the source of truth for colours
|
||||
and metrics; `DESIGN.md` and `PRODUCT.md` describe the design system and who the product is for.
|
||||
|
||||
## Layout
|
||||
|
||||
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
|
||||
types; never reach into another crate's internals.
|
||||
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
|
||||
(desktop-only commands; the adapters of `ide-host` commands are derived), `events.rs`.
|
||||
No domain logic here.
|
||||
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
|
||||
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
|
||||
keymap + dispatcher, context keys / `when` clauses, project store.
|
||||
- `src/workbench/contributions.ts` — extension points (tool windows, status items,
|
||||
overlays, editor kinds) and cross-feature services (editor, tool windows, notifications).
|
||||
- `src/ui/` — design-system primitives. `src/features/<name>/` — one feature each,
|
||||
exporting `activate()` registered in `src/features/index.ts`.
|
||||
- `languages/<id>.toml` — language definitions (detection, comments, LSP, DAP).
|
||||
- `crates/ide-host` — the `openidea-server` binary for remote development and the
|
||||
`openidea-plugin` CLI (plugin starter templates live in its `templates.rs`).
|
||||
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins.
|
||||
Plugin docs: `plugins/README.md`, `plugins/themes.md`.
|
||||
- `java/` — JDT LS extension bundles (`java-usages`, `kotlin-bridge`) and the patched
|
||||
Lombok agent, embedded into the app by `ide-sdk` / `ide-tools`.
|
||||
- `e2e/` — Playwright UI tests (`pnpm e2e`). `evals/` — code-intelligence evals (`pnpm eval`).
|
||||
`fixtures/` — sample projects per language for manual and automated testing.
|
||||
- `docs/` — the Mintlify documentation site (`docs.json` navigation, `en/` and `zh/` pages);
|
||||
preview with `npx mint dev` in `docs/`.
|
||||
|
||||
## Rules
|
||||
|
||||
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`).
|
||||
- Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
|
||||
- Declare a command once, on its implementation: `#[command(trust = …)]` in `ide-host::ops`
|
||||
plus its module's `domain!` list (Tauri adapter, server handler and bindings are derived);
|
||||
desktop-only commands use `#[desktop_command(trust = …)]` and `desktop_domain!`.
|
||||
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
|
||||
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
|
||||
- Long work never blocks the UI thread or a Tauri command thread: use
|
||||
`spawn_blocking`/rayon, honour `CancellationToken`.
|
||||
- Frontend features never import each other; communicate via actions, contributions
|
||||
and services. All user-invocable behaviour is an action with a stable id; default
|
||||
shortcuts live in `src/platform/keymaps/`.
|
||||
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
|
||||
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
|
||||
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
|
||||
- User-visible text goes through the text catalog: add every new string to both
|
||||
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
|
||||
Other locales may lack entries; their UI shows the English text until a translator adds it.
|
||||
- Keep comments sparse and purposeful; match surrounding style.
|
||||
- New regular expressions in frontend code must run on WebKit (no lookbehind):
|
||||
`src/platform/webkitCompatibility.test.ts` checks them.
|
||||
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
|
||||
unavailable or cannot cover the required checks.
|
||||
|
||||
## UX changes
|
||||
|
||||
A change to what users see or how they interact must look and behave like the rest of the IDE.
|
||||
|
||||
- `DESIGN.md` (colours, type, layout, components, Do's and Don'ts) and `PRODUCT.md`
|
||||
(users, principles, accessibility) are the reference; `docs/en/contribute/guidelines/ui.mdx`
|
||||
has the code-level rules. Build from `src/ui/` primitives and workbench contributions;
|
||||
don't create a one-off control, colour or spacing when an existing one fits.
|
||||
- Check every theme the change touches (at least Islands Light and Islands Dark) and narrow
|
||||
sizes (e.g. the Commit tool window at its default width, a small window). Long translated
|
||||
strings must not break the layout.
|
||||
- Everything works from the keyboard; focus is visible and lands somewhere sensible when a
|
||||
popup or dialog closes. Icon-only buttons have an `aria-label` and a tooltip.
|
||||
- Follow the conventions users of this kind of IDE already know: the same action keeps the
|
||||
same name, place and shortcut across views. Don't invent a new pattern for an existing one.
|
||||
- Agent and MCP features follow good agent-tool practice: restrained, predictable, reversible.
|
||||
- Restructuring a page layout or navigation, or changing a default behaviour, needs a
|
||||
maintainer's decision first: ask in the issue and label it `needs-decision`.
|
||||
- The Impeccable design skills may be used for design critique and polish; they read
|
||||
`DESIGN.md`, `PRODUCT.md` and `.impeccable/`. A detector exception goes in
|
||||
`.impeccable/config.json` with a reason.
|
||||
|
||||
## Issues & PRs
|
||||
|
||||
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
|
||||
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain
|
||||
description. Unclear product decisions → `needs-decision` and stop.
|
||||
|
||||
Every PR carries evidence a reviewer can accept without re-running everything, in
|
||||
**How it was verified**. It must come from the final version of the branch:
|
||||
|
||||
| Change | Evidence |
|
||||
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Bug fix | A test that fails before the fix and passes after, or exact reproduction steps with before/after result |
|
||||
| Visible UI | Before/after screenshots at the same state and window size; each theme the change touches |
|
||||
| Interaction (multi-step, drag, keyboard, focus) | A short recording or numbered screenshots |
|
||||
| Code intelligence / language support | The fixture used and `language_smoke` output; `pnpm eval` numbers for Java |
|
||||
| Run / debug | `pnpm smoke smoke/run.test.ts` / `smoke/debug.test.ts -t <language>` output |
|
||||
| Performance | Before/after numbers on the same machine (`pnpm perf`, `pnpm perf:rust` or a stated measurement), plus proof the results are unchanged |
|
||||
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine |
|
||||
| Backend / IPC | Test output; regenerated `src/bindings.ts` when types changed |
|
||||
| Remote development | The flow against a real `openidea-server` host |
|
||||
| Plugin API / `wit/` | `plugins/build.sh` run and `dist/` committed; a sample plugin using the change |
|
||||
| Settings / persisted data | Behaviour when starting from data written by the previous version |
|
||||
| Copy, docs, refactor | The commands run; "No visible change" when nothing users see changed |
|
||||
|
||||
Attach screenshots and recordings to the PR description; never commit them. The `pr` skill
|
||||
has the full checklist.
|
||||
|
||||
## Skills
|
||||
|
||||
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
|
||||
`pr` prepares a pull request — checks to run, evidence for the kind of change, description;
|
||||
`verify` drives the running app through Tauri MCP and captures screenshot evidence.
|
||||
|
||||
## Commands
|
||||
|
||||
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
|
||||
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
|
||||
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
|
||||
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
|
||||
this worktree's running MCP bridges and actual ports.
|
||||
- `pnpm build` — typecheck + bundle frontend.
|
||||
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
|
||||
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
|
||||
- `pnpm dogfood:servers [all | x86_64 | aarch64]` (or `mise run dogfood:servers ...`) — cross-build and locally stage Linux `openidea-server` binaries with Zig.
|
||||
- `pnpm dogfood:all [all | x86_64 | aarch64] [--build-only]` (or `mise run dogfood:all ...`) — run `dogfood:local` and `dogfood:servers` in parallel, without requiring an SSH host;
|
||||
`dogfood:all <remote_name> [--restart | --no-restart]` runs `dogfood:local` and `dogfood:remote <remote_name>` in parallel instead.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
|
||||
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
|
||||
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
|
||||
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
|
||||
`sudo DevToolsSecurity -enable`).
|
||||
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
|
||||
`pnpm gen:bindings`.
|
||||
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
|
||||
benches vs budgets). Budgets: `perf/budgets.json`.
|
||||
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
|
||||
usages, gutter markers) in the production workbench against a release `openidea-server` and
|
||||
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
|
||||
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
|
||||
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
|
||||
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
|
||||
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
|
||||
|
||||
## Before opening a PR
|
||||
|
||||
Run what CI runs for the parts you touched:
|
||||
|
||||
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
|
||||
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
|
||||
commit `src/bindings.ts`; CI fails if it differs.
|
||||
- Frontend: `pnpm typecheck` (vitest does not type-check), `pnpm lint`, `pnpm format:check`,
|
||||
`pnpm knip`, `pnpm test`, `pnpm build`, and every `e2e/` spec of the feature you touched.
|
||||
- New text keys: `src/platform/locales/textCatalog.test.ts` and `src/platform/i18n.test.ts`.
|
||||
New or renamed tokens: `pnpm gen:theme-docs`.
|
||||
- Changed a `pub fn` signature in a crate: run that crate's whole `cargo test`, not one test.
|
||||
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`) and collect
|
||||
the evidence above (`.agents/skills/pr`).
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
|
||||
the filter and runs the whole suite, which takes several minutes.
|
||||
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
|
||||
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
|
||||
before committing. A cold build cache can take around 5 minutes. Run long checks one at
|
||||
a time, not chained in one shell call that may hit the 10-minute tool timeout.
|
||||
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
|
||||
doesn't make the first launch fast.
|
||||
|
||||
## Parallel worktrees
|
||||
|
||||
Several worktrees can be developed and run side by side.
|
||||
|
||||
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
|
||||
`pnpm install` in it.
|
||||
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
|
||||
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
|
||||
URL to Tauri, and reports an existing launcher instead of starting another for the same
|
||||
worktree. HMR uses the Vite port.
|
||||
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
|
||||
worktree path captured at build time, independent of launch cwd. Launching the same debug
|
||||
binary again focuses its existing instance and forwards its path argument. Different
|
||||
worktrees and the installed release can coexist. `--release` uses normal release identity
|
||||
and bypasses the development wrapper.
|
||||
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
|
||||
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
|
||||
default MCP session belongs to this worktree.
|
||||
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
|
||||
`target` symlinks at a shared directory.
|
||||
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
|
||||
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
|
||||
- Stop only processes started for the current worktree/session. Never use broad
|
||||
process-name kills such as `pkill openidea`.
|
||||
- When done: stop that worktree's app and dev session, delete its build output, then
|
||||
`git worktree remove ../<name>`.
|
||||
Symlink
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
@@ -1,6 +1,7 @@
|
||||
# Contributing to OpenIDEA
|
||||
|
||||
These rules apply to everyone, and to any coding agent working on their behalf.
|
||||
Project layout, coding rules, commands, checks and the evidence a PR needs are in [AGENTS.md](AGENTS.md).
|
||||
|
||||
## Issues
|
||||
|
||||
@@ -26,7 +27,12 @@ These rules apply to everyone, and to any coding agent working on their behalf.
|
||||
- **How it was verified** is required: the commands you ran and their results,
|
||||
and what else the change could affect. Changes to what users see need before/after
|
||||
screenshots; multi-step interactions need a recording. UI that goes away with a removed
|
||||
feature, copy-only and non-visual changes don't; say what you checked instead.
|
||||
feature, copy-only and non-visual changes don't; write "No visible change" and say what
|
||||
you checked instead. [AGENTS.md](AGENTS.md#issues--prs) lists the evidence for each kind of
|
||||
change (tests, smoke output, perf numbers, real-machine logs…).
|
||||
- Changes to what users see follow [DESIGN.md](DESIGN.md) and the existing UI: tokens,
|
||||
`src/ui/` primitives, both themes, keyboard access. Restructuring a layout or navigation
|
||||
needs a maintainer's decision first.
|
||||
- If a change needs a product decision you can't make, ask in the issue and stop
|
||||
rather than guessing.
|
||||
|
||||
@@ -35,4 +41,4 @@ and the plugin API. Community plugins live in their authors' repositories and
|
||||
are listed through [l0ng-ai/openidea-plugins](https://github.com/l0ng-ai/openidea-plugins);
|
||||
see [`plugins/README.md`](plugins/README.md) § 8.1.
|
||||
|
||||
A check on each PR adds `needs-info` when the verification section is missing, and removes it once it's filled in.
|
||||
A check on each PR adds `needs-info` when the verification section is missing, or when the PR changes UI files and the section has neither a screenshot nor a recording nor "No visible change". It removes the label once that's fixed.
|
||||
Створено
+401
-570
File diff suppressed because it is too large.
Load diff
+8
-2
@@ -2,10 +2,10 @@
|
||||
resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
# Plugins and the guest SDK build for wasm32-wasip2 in their own workspaces.
|
||||
exclude = ["sdk", "plugins"]
|
||||
exclude = ["sdk", "plugins", "vendor"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.56"
|
||||
version = "0.1.57"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -101,6 +101,7 @@ tar = "0.4"
|
||||
grep-searcher = "0.1"
|
||||
grep-regex = "0.1"
|
||||
regex-syntax = "0.8"
|
||||
regex = "1"
|
||||
grep-matcher = "0.1"
|
||||
nucleo-matcher = "0.3"
|
||||
redb = "4"
|
||||
@@ -160,3 +161,8 @@ opt-level = 3
|
||||
panic = "unwind"
|
||||
# Keep the symbol table: crash reports and logged backtraces name functions.
|
||||
strip = "debuginfo"
|
||||
|
||||
# tauri-plugin-mcp-bridge 0.13.2 (debug-only E2E bridge) pins `tauri ~2.12`; this copy only widens
|
||||
# that requirement to 2.13. Drop it once a release supporting tauri 2.13 is published.
|
||||
[patch.crates-io]
|
||||
tauri-plugin-mcp-bridge = { path = "vendor/tauri-plugin-mcp-bridge" }
|
||||
+2
-2
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a>
|
||||
English · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -74,7 +74,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
|
||||
<img src=".github/assets/wechat-group-5.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
<p align="center">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="src-tauri/icons/source/openidea-wordmark-dark.svg">
|
||||
<img src="src-tauri/icons/source/openidea-wordmark.svg" alt="OpenIDEA" height="56">
|
||||
</picture>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
Знакомая вам IDE, переписанная на Rust.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · <a href="README.tr.md">Türkçe</a> · Русский
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Скачать</b></a>
|
||||
·
|
||||
<a href="https://openidea.sh">Документация</a>
|
||||
·
|
||||
<a href="#сравнение-производительности">Производительность</a>
|
||||
·
|
||||
<a href="#плагины">Плагины</a>
|
||||
·
|
||||
<a href="#сообщество">Сообщество</a>
|
||||
</p>
|
||||
|
||||
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
|
||||
|
||||
OpenIDEA переносит привычные для пользователей IntelliJ IDEA сочетания клавиш, окна инструментов
|
||||
и глобальный поиск в нативное приложение с ядром на Rust.
|
||||
|
||||
Редактор, средства анализа кода, отладчик, Git, терминал, клиенты для работы с базами данных и HTTP.
|
||||
Поддержка более 60 языков. Сборки для macOS, Windows и Linux.
|
||||
|
||||
На macOS IDE также можно установить через Homebrew:
|
||||
|
||||
```bash
|
||||
brew install --cask l0ng-ai/tap/openidea
|
||||
```
|
||||
|
||||
## Сравнение производительности
|
||||
|
||||
Открытие проекта [freqtrade](https://github.com/freqtrade/freqtrade) (Python, около 770 файлов)
|
||||
с прогретыми кешами, медиана пяти запусков:
|
||||
|
||||
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|
||||
| ---------------------------------------------- | ------------------- | ---------------------- |
|
||||
| Появление окна с проектом | **0,9 с** | 3,1 с |
|
||||
| Готовность (нагрузка на CPU стабилизировалась) | **1,1 с** | 13,2 с |
|
||||
| Память (USS, все процессы) | **169 МБ** | 2011 МБ |
|
||||
| Процессорное время до готовности | **2,4 с** | 47,9 с |
|
||||
| Загрузка CPU в простое | **4 %** одного ядра | 7 % одного ядра |
|
||||
| Завершение работы | **0,3 с** | 5,9 с |
|
||||
|
||||
В тесте использовались релизная сборка OpenIDEA из ветки `main` и IDEA с настройками и плагинами по умолчанию.
|
||||
Окружение: Windows 11, 32-ядерный процессор AMD, 62 ГБ оперативной памяти.
|
||||
IDEA глубже анализирует Python-код, поэтому к моменту готовности обе IDE выполняют разный объём работы.
|
||||
Измерения обеих IDE проводились извне по одной методике: с помощью
|
||||
[`perf/compare`](perf/compare) можно повторить тест на своём компьютере со своими проектами.
|
||||
|
||||
## Плагины
|
||||
|
||||
Плагины добавляют действия, автодополнение кода, быстрые исправления, окна инструментов, пользовательские редакторы,
|
||||
темы оформления, значки файлов и поддержку языков. Они работают как компоненты WebAssembly в изолированной среде;
|
||||
для тем оформления, тем значков и языков писать код не нужно.
|
||||
|
||||
Плагины можно установить в разделе «Настройки › Плагины» (Settings › Plugins) или создать собственный командой
|
||||
`openidea-plugin new`. См. [руководство по созданию плагинов OpenIDEA](https://openidea.sh/en/plugins)
|
||||
и [официальные плагины](plugins/official). API плагинов пока доступен в предварительной версии.
|
||||
|
||||
## Сообщество
|
||||
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): вопросы, обратная связь и новости о релизах.
|
||||
- Группа WeChat: отсканируйте QR-код, чтобы присоединиться.
|
||||
|
||||
<img src=".github/assets/wechat-group-5.png" alt="QR-код группы WeChat" width="200">
|
||||
|
||||
- Как внести вклад: см. [CONTRIBUTING.md](CONTRIBUTING.md) и [документацию для участников проекта](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
## Лицензия
|
||||
|
||||
[Apache 2.0](LICENSE). Включённые в поставку сторонние ресурсы перечислены в [`THIRD_PARTY_LICENSES.md`](THIRD_PARTY_LICENSES.md).
|
||||
|
||||
<sub>OpenIDEA не связан с JetBrains. IntelliJ IDEA — товарный знак JetBrains s.r.o.</sub>
|
||||
+2
-2
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe
|
||||
<a href="README.md">English</a> · <a href="README.zh-CN.md">简体中文</a> · Türkçe · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -74,7 +74,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
|
||||
- WeChat grubu, katılmak için kodu okut:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
|
||||
<img src=".github/assets/wechat-group-5.png" alt="WeChat grubu QR kodu" width="200">
|
||||
|
||||
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="README.md">English</a> · 简体中文
|
||||
<a href="README.md">English</a> · 简体中文 · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
@@ -72,7 +72,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
<img src=".github/assets/wechat-group-5.png" alt="微信群二维码" width="200">
|
||||
|
||||
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
`src/ui/brands/*.svg` use the unmodified logo paths from
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:odin`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos; `dotnet_dark.svg` lightens .NET's purple for dark themes). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## DuckDB symbol
|
||||
|
||||
@@ -288,6 +288,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## tree-sitter-fsharp queries
|
||||
|
||||
`crates/ide-language/queries/fsharp_signature/highlights.scm` is the signature grammar's
|
||||
`highlights.scm` from [tree-sitter-fsharp](https://github.com/ionide/tree-sitter-fsharp)
|
||||
0.3.13 (the grammar itself is a Cargo dependency).
|
||||
|
||||
### MIT License (tree-sitter-fsharp)
|
||||
|
||||
Copyright (c) 2023 Nikolaj Sidorenco
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## nvim-treesitter queries
|
||||
|
||||
`crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm`
|
||||
|
||||
@@ -24,7 +24,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
match run_once(shared, spec, prefer_stored, model).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::is_copilot_provider(spec.base_id())
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
@@ -53,7 +53,7 @@ async fn run_once(
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
let cwd = dunce::canonicalize(&root).unwrap_or(root);
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() });
|
||||
let updates = Arc::new(DiscoveryUpdates { provider: spec.base_id().to_owned(), ..Default::default() });
|
||||
let client = Dialect::wrap(updates.clone());
|
||||
let on_stderr: Box<dyn Fn(String) + Send + Sync> = Box::new(|_| {});
|
||||
let peer = (shared.connector)(&launch, &cwd, client.clone(), on_stderr)
|
||||
@@ -69,7 +69,7 @@ async fn run_once(
|
||||
.await
|
||||
.map_err(discovery_error)?;
|
||||
let mut options = config::options_of(&new);
|
||||
config::add_client_options(&launch.id, &mut options);
|
||||
config::add_client_options(launch.base_id(), &mut options);
|
||||
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
|
||||
let mut levels = BTreeMap::new();
|
||||
let has_config = new.get("configOptions").is_some_and(Value::is_array);
|
||||
@@ -119,7 +119,7 @@ async fn run_once(
|
||||
.commands
|
||||
.lock()
|
||||
.clone()
|
||||
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, &launch.id)));
|
||||
.or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, launch.base_id())));
|
||||
Ok::<_, String>(Discovered { config: options, commands, levels })
|
||||
};
|
||||
let result = tokio::time::timeout(DISCOVER_TIMEOUT, work).await;
|
||||
|
||||
@@ -105,6 +105,7 @@ fn manager(dir: &Path, agent: Arc<FakeV2Agent>) -> AgentManager {
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
|
||||
@@ -53,6 +53,24 @@ pub(crate) fn auth_required(code: i64, message: &str) -> bool {
|
||||
.any(|w| w == ["logged", "out"] || w == ["sign", "in"] || w == ["log", "in"] || w == ["login", "required"])
|
||||
}
|
||||
|
||||
/// Whether a failed request only means the agent hasn't finished starting up: OpenCode
|
||||
/// rejects session opens until the location's plugins and MCP servers finish activating
|
||||
/// (`ServiceUnavailableError`, "Location plugins did not finish activating") and reports
|
||||
/// an unavailable server as `ServerUnavailable`. Both arrive as internal errors naming
|
||||
/// the cause in `data.errorName`; retrying them once activation completes succeeds.
|
||||
pub(crate) fn service_warming_up(error: &RpcError) -> bool {
|
||||
let RpcError::Server { code: codes::INTERNAL_ERROR, message, data } = error else {
|
||||
return false;
|
||||
};
|
||||
if let Some(name) = data.as_ref().and_then(|d| d.get("errorName")).and_then(Value::as_str)
|
||||
&& matches!(name, "ServiceUnavailableError" | "ServerUnavailable")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let lower = message.to_lowercase();
|
||||
lower.contains("did not finish activating") || lower.contains("opencode server is unavailable")
|
||||
}
|
||||
|
||||
/// The capabilities this client offers, in v1 form.
|
||||
fn client_capabilities() -> Value {
|
||||
json!({
|
||||
@@ -62,6 +80,8 @@ fn client_capabilities() -> Value {
|
||||
"subagents": {},
|
||||
// Forms the agent asks the user to fill in (`elicitation/create`); not URL mode.
|
||||
"elicitation": { "form": {} },
|
||||
// Ghost-text next-prompt suggestions (`prompt_suggestions_update`).
|
||||
"session": { "promptSuggestions": {} },
|
||||
// Cursor exposes model parameters (e.g. Composer `fast`) as separate config options
|
||||
// only when the client advertises this flag (undocumented Cursor ACP extension).
|
||||
"_meta": { "parameterizedModelPicker": true },
|
||||
@@ -76,7 +96,7 @@ pub(crate) fn initialize_params(client_info: &Value) -> Value {
|
||||
json!({
|
||||
"protocolVersion": 2,
|
||||
"info": client_info,
|
||||
"capabilities": {},
|
||||
"capabilities": { "session": { "promptSuggestions": {} } },
|
||||
"clientCapabilities": client_capabilities(),
|
||||
"clientInfo": client_info,
|
||||
})
|
||||
@@ -341,7 +361,7 @@ impl Handler for Dialect {
|
||||
|
||||
fn on_request_raw(&self, method: &str, params: Value, raw: &[u8]) -> Result<Value, (i64, String, Option<Value>)> {
|
||||
if self.v2() && method == "session/request_permission" {
|
||||
return self.on_request_with_data(method, params);
|
||||
return self.inner.on_request_raw(method, v1_permission_request(params), raw);
|
||||
}
|
||||
self.inner.on_request_raw(method, params, raw)
|
||||
}
|
||||
|
||||
@@ -52,6 +52,40 @@ fn auth_required_matches_authentication_words_and_sign_in_phrases() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_warming_up_matches_opencode_startup_races_only() {
|
||||
for (code, message, data, expected) in [
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure",
|
||||
Some(json!({"errorName": "ServiceUnavailableError"})),
|
||||
true,
|
||||
),
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: OpenCode server is unavailable",
|
||||
Some(json!({"errorName": "ServerUnavailable"})),
|
||||
true,
|
||||
),
|
||||
(codes::INTERNAL_ERROR, "Location plugins did not finish activating", None, true),
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure",
|
||||
Some(json!({"errorName": "SQLiteError"})),
|
||||
false,
|
||||
),
|
||||
(codes::INTERNAL_ERROR, "Internal error: Internal service failure", None, false),
|
||||
(codes::INTERNAL_ERROR, "boom", None, false),
|
||||
(AUTH_REQUIRED, "Authentication required", None, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
service_warming_up(&RpcError::Server { code, message: message.into(), data: data.clone() }),
|
||||
expected,
|
||||
"code={code}, message={message:?}, data={data:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The messages of a fixture going `dir` (`in` or `out`).
|
||||
pub(crate) fn frames(fixture: &str, dir: &str) -> Vec<Value> {
|
||||
fixture
|
||||
@@ -99,11 +133,14 @@ fn the_negotiating_request_carries_both_versions() {
|
||||
);
|
||||
// Forms only: URL mode would open pages the agent names.
|
||||
assert_eq!(p["clientCapabilities"]["elicitation"], json!({ "form": {} }));
|
||||
assert_eq!(p["clientCapabilities"]["session"], json!({ "promptSuggestions": {} }));
|
||||
assert_eq!(p["capabilities"]["session"], json!({ "promptSuggestions": {} }));
|
||||
// What we sent in the capture is what claude-agent-acp negotiated v2 and v1 from.
|
||||
let sent = frames(TURN, "out")[0]["params"]["clientCapabilities"].clone();
|
||||
let mut expected = sent;
|
||||
expected["_meta"] = p["clientCapabilities"]["_meta"].clone();
|
||||
expected["elicitation"] = p["clientCapabilities"]["elicitation"].clone();
|
||||
expected["session"] = p["clientCapabilities"]["session"].clone();
|
||||
assert_eq!(expected, p["clientCapabilities"]);
|
||||
}
|
||||
|
||||
@@ -155,6 +192,7 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
|
||||
store_dir: tmp.path().join("store"),
|
||||
worktrees_dir: tmp.path().join("worktrees"),
|
||||
models_file: tmp.path().join("models.json"),
|
||||
cli_dir: tmp.path().join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
|
||||
@@ -50,6 +50,10 @@ fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
/// Whether each scheduled firing starts a fresh task or continues the previous task's conversation.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -242,6 +246,10 @@ pub struct AgentAutomation {
|
||||
#[specta(optional)]
|
||||
pub memory_overrides: Option<AgentMemoryOverrides>,
|
||||
pub trigger: AutomationTrigger,
|
||||
/// When `true`, runs of this automation may call the `schedule_next_run` MCP tool to set
|
||||
/// their own next firing time and prompt without interactive human confirmation.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub allow_agent_schedule: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub misfire_policy: Option<AutomationMisfirePolicy>,
|
||||
@@ -254,6 +262,16 @@ pub struct AgentAutomation {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub next_run_ms: Option<f64>,
|
||||
/// Pending one-time firing timestamp scheduled by the agent via `schedule_next_run`.
|
||||
/// Consumed on the next firing without altering [`Self::trigger`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub next_run_override_ms: Option<f64>,
|
||||
/// Pending one-time prompt instructions scheduled by the agent via `schedule_next_run`.
|
||||
/// Consumed on the next firing without altering [`Self::prompt`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub next_prompt_override: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub paused_reason: Option<String>,
|
||||
@@ -292,6 +310,13 @@ pub struct SaveAutomationInput {
|
||||
pub memory_overrides: Option<AgentMemoryOverrides>,
|
||||
pub trigger: AutomationTrigger,
|
||||
#[serde(default)]
|
||||
pub allow_agent_schedule: bool,
|
||||
/// When `true` on an update, explicitly discards any pending agent-scheduled
|
||||
/// `next_run_override_ms` / `next_prompt_override` and reverts to the regular `trigger`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub clear_override: bool,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub misfire_policy: Option<AutomationMisfirePolicy>,
|
||||
#[serde(default)]
|
||||
@@ -739,6 +764,34 @@ pub fn preview_trigger_runs(trigger: &AutomationTrigger, from_ms: f64, count: us
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats an epoch-millisecond timestamp in `trigger`'s timezone (or system local timezone for
|
||||
/// `OneShot` / `Manual`) as an ISO-8601 zoned string.
|
||||
pub fn format_trigger_timestamp(trigger: &AutomationTrigger, ms: f64) -> Option<String> {
|
||||
if !ms.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let ts = jiff::Timestamp::from_millisecond(ms.round() as i64).ok()?;
|
||||
let tz_name = match trigger {
|
||||
AutomationTrigger::Hourly { time_zone, .. }
|
||||
| AutomationTrigger::Daily { time_zone, .. }
|
||||
| AutomationTrigger::Weekdays { time_zone, .. }
|
||||
| AutomationTrigger::Weekly { time_zone, .. }
|
||||
| AutomationTrigger::Cron { time_zone, .. } => time_zone.as_str(),
|
||||
AutomationTrigger::Manual | AutomationTrigger::OneShot { .. } => "local",
|
||||
};
|
||||
let tz = resolve_time_zone(tz_name).ok()?;
|
||||
Some(ts.to_zoned(tz).to_string())
|
||||
}
|
||||
|
||||
/// Parses an ISO-8601 / RFC-3339 timestamp string into epoch milliseconds.
|
||||
pub fn parse_iso_timestamp_ms(raw: &str) -> IdeResult<f64> {
|
||||
let ts = raw
|
||||
.trim()
|
||||
.parse::<jiff::Timestamp>()
|
||||
.map_err(|e| IdeError::invalid(format!("invalid ISO-8601 timestamp '{}': {e}", raw.trim())))?;
|
||||
Ok(ts.as_millisecond() as f64)
|
||||
}
|
||||
|
||||
/// Parses an interval string such as `"10m"`, `"90s"`, `"2h"`, `"1d"`, `"15 minutes"` into seconds.
|
||||
pub fn parse_interval_secs(raw: &str, min_secs: u64, max_secs: u64) -> IdeResult<u64> {
|
||||
let trimmed = raw.trim().to_ascii_lowercase();
|
||||
@@ -783,6 +836,8 @@ pub struct PortableAutomation {
|
||||
#[specta(optional)]
|
||||
pub description: Option<String>,
|
||||
pub trigger: AutomationTrigger,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub allow_agent_schedule: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub disable_after_ms: Option<f64>,
|
||||
@@ -813,7 +868,7 @@ pub fn slugify_id(name: &str) -> String {
|
||||
/// Exports an [`AgentAutomation`] into the portable `.automation.md` format (YAML frontmatter + prompt body).
|
||||
pub fn export_markdown(automation: &AgentAutomation) -> IdeResult<String> {
|
||||
let has_disable = automation.disable_after_ms.is_some() || automation.max_runs.is_some();
|
||||
let version = if has_disable { 2 } else { 1 };
|
||||
let version = if has_disable || automation.allow_agent_schedule { 2 } else { 1 };
|
||||
let slug = slugify_id(&automation.name);
|
||||
let id = if slug.is_empty() { automation.id.clone() } else { slug };
|
||||
let mut out = String::new();
|
||||
@@ -821,6 +876,9 @@ pub fn export_markdown(automation: &AgentAutomation) -> IdeResult<String> {
|
||||
out.push_str(&format!("version: {version}\n"));
|
||||
out.push_str(&format!("id: {}\n", yaml_scalar(&id)));
|
||||
out.push_str(&format!("name: {}\n", yaml_scalar(&automation.name)));
|
||||
if automation.allow_agent_schedule {
|
||||
out.push_str("allowAgentSchedule: true\n");
|
||||
}
|
||||
out.push_str("schedule:\n");
|
||||
match &automation.trigger {
|
||||
AutomationTrigger::Manual => {
|
||||
@@ -883,6 +941,7 @@ pub fn parse_markdown(markdown: &str) -> IdeResult<PortableAutomation> {
|
||||
let mut id: Option<String> = None;
|
||||
let mut name: Option<String> = None;
|
||||
let mut description: Option<String> = None;
|
||||
let mut allow_agent_schedule = false;
|
||||
let mut sched_kind = String::from("manual");
|
||||
let mut sched_expr: Option<String> = None;
|
||||
let mut sched_run_at: Option<String> = None;
|
||||
@@ -921,6 +980,7 @@ pub fn parse_markdown(markdown: &str) -> IdeResult<PortableAutomation> {
|
||||
"id" => id = Some(val),
|
||||
"name" => name = Some(val),
|
||||
"description" => description = Some(val),
|
||||
"allowAgentSchedule" => allow_agent_schedule = val.eq_ignore_ascii_case("true"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -989,7 +1049,7 @@ pub fn parse_markdown(markdown: &str) -> IdeResult<PortableAutomation> {
|
||||
other => return Err(IdeError::invalid(format!("unsupported schedule kind '{other}'"))),
|
||||
};
|
||||
|
||||
Ok(PortableAutomation { id, name, description, trigger, disable_after_ms, max_runs, prompt })
|
||||
Ok(PortableAutomation { id, name, description, trigger, allow_agent_schedule, disable_after_ms, max_runs, prompt })
|
||||
}
|
||||
|
||||
fn yaml_scalar(s: &str) -> String {
|
||||
@@ -1182,10 +1242,13 @@ mod tests {
|
||||
expression: "30 10 * * FRI".into(),
|
||||
time_zone: "America/Los_Angeles".into(),
|
||||
},
|
||||
allow_agent_schedule: true,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: Some(ts_ms("2027-03-01T00:00:00Z")),
|
||||
max_runs: Some(25),
|
||||
next_run_ms: None,
|
||||
next_run_override_ms: None,
|
||||
next_prompt_override: None,
|
||||
paused_reason: None,
|
||||
run_count: 0,
|
||||
unread_runs: 0,
|
||||
@@ -1194,9 +1257,11 @@ mod tests {
|
||||
};
|
||||
let md = export_markdown(&auto).unwrap();
|
||||
assert!(md.contains("version: 2\n"));
|
||||
assert!(md.contains("allowAgentSchedule: true\n"));
|
||||
let parsed = parse_markdown(&md).unwrap();
|
||||
assert_eq!(parsed.id, "weekly-review-core-rpc");
|
||||
assert_eq!(parsed.name, "Weekly Review: Core & RPC");
|
||||
assert!(parsed.allow_agent_schedule);
|
||||
assert_eq!(parsed.disable_after_ms, Some(ts_ms("2027-03-01T00:00:00Z")));
|
||||
assert_eq!(parsed.max_runs, Some(25));
|
||||
assert_eq!(parsed.prompt, "Inspect open PRs and run /code-review.");
|
||||
|
||||
@@ -25,6 +25,8 @@ type Key = (PathBuf, PathBuf, String);
|
||||
#[derive(Default)]
|
||||
pub struct AgentCatalogs {
|
||||
state: Mutex<State>,
|
||||
/// Orders model requests by when they were made, not when they reach `state`.
|
||||
tickets: std::sync::atomic::AtomicU64,
|
||||
#[cfg(test)]
|
||||
clock_ms: std::sync::atomic::AtomicU64,
|
||||
}
|
||||
@@ -49,6 +51,8 @@ struct Entry {
|
||||
abort: Option<tokio::task::AbortHandle>,
|
||||
flight_model: Option<String>,
|
||||
requested_model: Option<String>,
|
||||
/// Ticket of the newest model request applied: an older one arriving late can't supersede it.
|
||||
model_ticket: u64,
|
||||
model_failures: HashMap<String, ModelFailure>,
|
||||
catalog: Option<CatalogData>,
|
||||
}
|
||||
@@ -254,7 +258,16 @@ impl AgentCatalogs {
|
||||
}
|
||||
let unavailable = || "The agent did not report settings for the selected model".to_owned();
|
||||
let spec = shared.spec(provider).ok_or_else(unavailable)?;
|
||||
let (_, flight) = self.request(shared, spec, false, Some(model));
|
||||
// Taken now: the blocking task may run after a newer selection's request.
|
||||
let ticket = self.ticket();
|
||||
let flight = {
|
||||
let catalogs = self.clone();
|
||||
let shared = shared.clone();
|
||||
let model = model.to_owned();
|
||||
tokio::task::spawn_blocking(move || catalogs.request_with(&shared, spec, false, Some(&model), ticket).1)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
};
|
||||
if let Some(mut ready) = flight {
|
||||
while !*ready.borrow_and_update() {
|
||||
if ready.changed().await.is_err() {
|
||||
@@ -324,12 +337,49 @@ impl AgentCatalogs {
|
||||
}
|
||||
|
||||
/// Start or join a lookup. No queued refresh can outlive the request that asked for it.
|
||||
/// The model the running discovery of `provider` looks up, if one is running.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn flight_model(&self, shared: &Shared, provider: &str) -> Option<Option<String>> {
|
||||
let state = self.state.lock();
|
||||
let entry = state.entries.get(&Self::key(shared, provider))?;
|
||||
entry.flight.as_ref().map(|_| entry.flight_model.clone())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn request_as_of(
|
||||
self: &Arc<Self>,
|
||||
shared: &Arc<Shared>,
|
||||
spec: provider::ProviderSpec,
|
||||
model: &str,
|
||||
ticket: u64,
|
||||
) -> Option<watch::Receiver<bool>> {
|
||||
self.request_with(shared, spec, false, Some(model), ticket).1
|
||||
}
|
||||
|
||||
pub(crate) fn ticket(&self) -> u64 {
|
||||
self.tickets.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
|
||||
}
|
||||
|
||||
pub(crate) fn request(
|
||||
self: &Arc<Self>,
|
||||
shared: &Arc<Shared>,
|
||||
spec: provider::ProviderSpec,
|
||||
force: bool,
|
||||
model: Option<&str>,
|
||||
) -> (AgentModelCatalog, Option<watch::Receiver<bool>>) {
|
||||
let ticket = self.ticket();
|
||||
self.request_with(shared, spec, force, model, ticket)
|
||||
}
|
||||
|
||||
/// [`Self::request`] for a request made when `ticket` was taken. A model request older than
|
||||
/// the newest one applied neither changes the requested model nor supersedes its flight.
|
||||
fn request_with(
|
||||
self: &Arc<Self>,
|
||||
shared: &Arc<Shared>,
|
||||
spec: provider::ProviderSpec,
|
||||
force: bool,
|
||||
model: Option<&str>,
|
||||
ticket: u64,
|
||||
) -> (AgentModelCatalog, Option<watch::Receiver<bool>>) {
|
||||
let key = Self::key(shared, &spec.id);
|
||||
let context = LaunchContext::new(spec.clone(), &shared.paths.project_root);
|
||||
@@ -381,6 +431,7 @@ impl AgentCatalogs {
|
||||
abort: None,
|
||||
flight_model: None,
|
||||
requested_model: None,
|
||||
model_ticket: 0,
|
||||
model_failures: HashMap::new(),
|
||||
},
|
||||
);
|
||||
@@ -397,10 +448,15 @@ impl AgentCatalogs {
|
||||
|| (!fresh && catalog.model_option().is_none())
|
||||
})
|
||||
.map(str::to_owned);
|
||||
if model.is_some() && entry.requested_model.as_deref() != model {
|
||||
entry.requested_model = model.map(str::to_owned);
|
||||
let stale = model.is_some() && ticket < entry.model_ticket;
|
||||
if model.is_some() && !stale {
|
||||
entry.model_ticket = ticket;
|
||||
if entry.requested_model.as_deref() != model {
|
||||
entry.requested_model = model.map(str::to_owned);
|
||||
}
|
||||
}
|
||||
let superseded = model.is_some()
|
||||
let superseded = !stale
|
||||
&& model.is_some()
|
||||
&& entry.flight.is_some()
|
||||
&& (entry.flight_model.is_some() || target.is_some())
|
||||
&& entry.flight_model.as_deref() != target.as_deref();
|
||||
@@ -444,7 +500,22 @@ impl AgentCatalogs {
|
||||
let flight_key = key.clone();
|
||||
let task = shared.runtime.clone().spawn(async move {
|
||||
let result = discover(&shared, spec, model.as_deref()).await;
|
||||
coordinator.complete(&shared, flight_key, generation, model, result);
|
||||
let current = {
|
||||
let shared = shared.clone();
|
||||
let provider_id = flight_key.2.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
shared
|
||||
.paths
|
||||
.provider_specs()
|
||||
.into_iter()
|
||||
.find(|spec| spec.id == provider_id)
|
||||
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root))
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
};
|
||||
coordinator.complete(&shared, flight_key, generation, model, current, result);
|
||||
let _ = done.send(true);
|
||||
});
|
||||
// A subscriber can re-enter and change configuration during the start event.
|
||||
@@ -466,12 +537,9 @@ impl AgentCatalogs {
|
||||
key: Key,
|
||||
generation: u64,
|
||||
model: Option<String>,
|
||||
current: Option<LaunchContext>,
|
||||
result: Result<Discovered, String>,
|
||||
) {
|
||||
let current = provider::load(shared.paths.custom_agents_dir.as_deref(), shared.env_secrets())
|
||||
.into_iter()
|
||||
.find(|spec| spec.id == key.2)
|
||||
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root));
|
||||
let mut state = self.state.lock();
|
||||
let Some(entry) = state.entries.get_mut(&key).filter(|e| e.generation == generation) else { return };
|
||||
// Configuration may have changed without another refresh request arriving.
|
||||
@@ -622,8 +690,7 @@ impl crate::AgentManager {
|
||||
/// Return cached choices immediately and schedule discovery when eligible.
|
||||
pub fn refresh_models(&self, provider: &str, force: bool, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
// Settings and environment secrets can change while this window is open.
|
||||
*self.shared.providers.write() =
|
||||
provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
*self.shared.providers.write() = self.shared.paths.provider_specs();
|
||||
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)
|
||||
}
|
||||
@@ -631,7 +698,10 @@ impl crate::AgentManager {
|
||||
/// 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())
|
||||
let mut spec = self
|
||||
.shared
|
||||
.paths
|
||||
.provider_specs()
|
||||
.into_iter()
|
||||
.find(|p| p.id == "copilot")
|
||||
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
|
||||
@@ -676,7 +746,7 @@ async fn discover(
|
||||
Ok(Discovered {
|
||||
commands: Some(config::commands_of(
|
||||
&serde_json::json!({ "availableCommands": found.commands }),
|
||||
&spec.id,
|
||||
spec.base_id(),
|
||||
)),
|
||||
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
|
||||
levels: found
|
||||
@@ -700,7 +770,7 @@ async fn discover(
|
||||
Ok(found) => Ok(Discovered {
|
||||
commands: Some(config::commands_of(
|
||||
&serde_json::json!({ "availableCommands": found.commands }),
|
||||
&spec.id,
|
||||
spec.base_id(),
|
||||
)),
|
||||
config: config::options_of(&serde_json::json!({ "configOptions": found.options })),
|
||||
levels: found
|
||||
|
||||
@@ -157,6 +157,7 @@ fn make_manager_at(root: &Path, models_file: &Path, catalogs: Arc<AgentCatalogs>
|
||||
store_dir: root.join("store"),
|
||||
worktrees_dir: root.join("worktrees"),
|
||||
models_file: models_file.to_path_buf(),
|
||||
cli_dir: root.join("agent-cli"),
|
||||
catalogs,
|
||||
custom_agents_dir: Some(root.join("agents")),
|
||||
home_dir: Some(root.to_path_buf()),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Checks and updates only the global npm installation selected by the agent launcher.
|
||||
//! Installs built-in CLIs into IDE-owned npm prefixes and updates the npm installation selected by the launcher.
|
||||
use crate::{AgentManager, AgentSource, provider};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -29,6 +29,14 @@ pub enum AgentCliUpdateResult {
|
||||
Error { code: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "status", rename_all = "camelCase")]
|
||||
pub enum AgentCliInstallResult {
|
||||
Installed,
|
||||
NodeRequired,
|
||||
Error { code: String },
|
||||
}
|
||||
|
||||
pub(crate) fn package(id: &str) -> Option<&'static str> {
|
||||
Some(match id {
|
||||
"claude" => "@anthropic-ai/claude-code",
|
||||
@@ -45,6 +53,64 @@ pub(crate) fn package(id: &str) -> Option<&'static str> {
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
/// Installs the built-in CLI into an npm prefix owned by the IDE on this host.
|
||||
pub fn cli_install(
|
||||
&self,
|
||||
id: &str,
|
||||
approved_command: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliInstallResult> {
|
||||
use AgentCliInstallResult::*;
|
||||
let spec = self.shared.paths.provider_specs().into_iter().find(|spec| spec.id == id);
|
||||
let (Some(spec), Some(pkg), Some(builtin)) = (spec, package(id), provider::builtin_spec(id)) else {
|
||||
return Err(IdeError::invalid("This agent has no built-in CLI installer"));
|
||||
};
|
||||
if spec.source != AgentSource::Builtin || spec.command != builtin.command {
|
||||
return Err(IdeError::invalid("This agent has no built-in CLI installer"));
|
||||
}
|
||||
let prefix = self.shared.paths.cli_dir.join(id);
|
||||
if install_command(&prefix, pkg).as_deref() != Some(approved_command) {
|
||||
return Err(IdeError::invalid("The CLI install command changed. Reopen Agent Setup and try again."));
|
||||
}
|
||||
if provider::installed_with_env(spec.executable(), &spec.env) {
|
||||
return Ok(Installed);
|
||||
}
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let Some(npm) = ide_core::process::find_executable("npm", &search)
|
||||
.filter(|_| ide_core::process::find_executable("node", &search).is_some())
|
||||
else {
|
||||
return Ok(NodeRequired);
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let _lock = lock_prefix(&prefix)?;
|
||||
if managed_cli(&prefix, pkg, &builtin.command).is_some() {
|
||||
return Ok(Installed);
|
||||
}
|
||||
let installation = Installation::at(&prefix, pkg, &builtin.command);
|
||||
// Only publish a CLI after npm has finished and its launcher has been verified.
|
||||
let marker = prefix.join(INSTALLED_MARKER);
|
||||
if marker.exists() {
|
||||
fs::remove_file(&marker)?;
|
||||
}
|
||||
let spec = format!("{pkg}@latest");
|
||||
match run_npm(&npm, &install_args(prefix.to_str().unwrap(), &spec), cancel) {
|
||||
Err(error) if error.kind == ErrorKind::Unavailable => return Ok(Error { code: error.message }),
|
||||
result => result?,
|
||||
};
|
||||
if installation.version(&installation.link, pkg, &builtin.command)?.is_none()
|
||||
|| !provider::installed_with_env(&installation.link.to_string_lossy(), &[])
|
||||
{
|
||||
return Err(IdeError::invalid("npm installation verification failed"));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
fs::write(marker, [])?;
|
||||
Ok(Installed)
|
||||
}
|
||||
|
||||
pub fn cli_update(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -61,14 +127,50 @@ impl AgentManager {
|
||||
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
};
|
||||
let prefix = self.shared.paths.cli_dir.join(id);
|
||||
let managed = spec.managed_cli.is_some().then_some(prefix.as_path());
|
||||
let _lock = if offer.is_some() { managed.map(lock_prefix).transpose()? } else { None };
|
||||
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, managed, offer, cancel) {
|
||||
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const INSTALLED_MARKER: &str = ".openidea-installed";
|
||||
|
||||
fn lock_prefix(prefix: &Path) -> IdeResult<fs::File> {
|
||||
fs::create_dir_all(prefix)?;
|
||||
let lock = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(prefix.join(".openidea-install.lock"))?;
|
||||
lock.try_lock().map_err(|error| match error {
|
||||
fs::TryLockError::WouldBlock => IdeError::new(ErrorKind::AlreadyExists, "CLI installation is in progress"),
|
||||
fs::TryLockError::Error(error) => error.into(),
|
||||
})?;
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
pub(crate) fn managed_cli(prefix: &Path, pkg: &str, bin: &str) -> Option<PathBuf> {
|
||||
let link = Installation::at(prefix, pkg, bin).link;
|
||||
(prefix.join(INSTALLED_MARKER).is_file() && provider::installed_with_env(&link.to_string_lossy(), &[]))
|
||||
.then_some(link)
|
||||
}
|
||||
|
||||
pub(crate) fn install_command(prefix: &Path, pkg: &str) -> Option<String> {
|
||||
let spec = format!("{pkg}@latest");
|
||||
let args = install_args(prefix.to_str()?, &spec);
|
||||
Some(provider::render_shell_command(Path::new("npm"), args, cfg!(windows)))
|
||||
}
|
||||
|
||||
fn install_args<'a>(prefix: &'a str, spec: &'a str) -> [&'a str; 7] {
|
||||
["install", "-g", "--prefix", prefix, "--no-audit", "--no-fund", spec]
|
||||
}
|
||||
|
||||
struct Installation {
|
||||
modules: PathBuf,
|
||||
folder: PathBuf,
|
||||
@@ -151,47 +253,19 @@ fn maintain(
|
||||
program: &Path,
|
||||
bin: &str,
|
||||
pkg: &str,
|
||||
managed: Option<&Path>,
|
||||
approved: Option<&AgentCliOffer>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
use AgentCliUpdateResult::*;
|
||||
let run = |args: &[&str]| {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.args(args)
|
||||
.current_dir(npm.parent().unwrap())
|
||||
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
|
||||
.env("NPM_CONFIG_LOGLEVEL", "error");
|
||||
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
|
||||
if e.kind == ErrorKind::Cancelled {
|
||||
return e;
|
||||
}
|
||||
// npm diagnostics can contain private registry URLs; expose only known codes.
|
||||
let code = e
|
||||
.message
|
||||
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
|
||||
.find(|w| {
|
||||
matches!(
|
||||
*w,
|
||||
"EACCES"
|
||||
| "EPERM"
|
||||
| "EROFS"
|
||||
| "ENOTFOUND"
|
||||
| "EAI_AGAIN"
|
||||
| "ETIMEDOUT"
|
||||
| "E404"
|
||||
| "E401"
|
||||
| "E403"
|
||||
)
|
||||
})
|
||||
.unwrap_or("npm");
|
||||
IdeError::unavailable(code)
|
||||
})
|
||||
let run = |args: &[&str]| run_npm(npm, args, cancel);
|
||||
let output;
|
||||
let prefix = if let Some(prefix) = managed {
|
||||
prefix
|
||||
} else {
|
||||
output = run(&["prefix", "-g"])?;
|
||||
Path::new(output.trim_end())
|
||||
};
|
||||
let output = run(&["prefix", "-g"])?;
|
||||
let prefix = Path::new(output.trim_end());
|
||||
if !prefix.is_absolute() {
|
||||
return Err(IdeError::invalid("Invalid npm global prefix"));
|
||||
}
|
||||
@@ -212,21 +286,42 @@ fn maintain(
|
||||
if approved != Some(&offer) {
|
||||
return Ok(Available(offer));
|
||||
}
|
||||
run(&[
|
||||
"install",
|
||||
"-g",
|
||||
"--prefix",
|
||||
prefix.to_str().unwrap(),
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
&format!("{pkg}@{}", offer.latest),
|
||||
])?;
|
||||
run(&install_args(prefix.to_str().unwrap(), &format!("{pkg}@{}", offer.latest)))?;
|
||||
if installation.version(program, pkg, bin)?.as_ref() != Some(&offer.latest) {
|
||||
return Err(IdeError::invalid("npm installation verification failed"));
|
||||
}
|
||||
Ok(Updated { current: offer.latest })
|
||||
}
|
||||
|
||||
fn run_npm(npm: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<String> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.args(args)
|
||||
.current_dir(npm.parent().unwrap())
|
||||
.env("PATH", ide_core::tool_path::search_path())
|
||||
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
|
||||
.env("NPM_CONFIG_LOGLEVEL", "error");
|
||||
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
|
||||
if e.kind == ErrorKind::Cancelled {
|
||||
return e;
|
||||
}
|
||||
// npm diagnostics can contain private registry URLs; expose only known codes.
|
||||
let code = e
|
||||
.message
|
||||
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
|
||||
.find(|w| {
|
||||
matches!(
|
||||
*w,
|
||||
"EACCES" | "EPERM" | "EROFS" | "ENOTFOUND" | "EAI_AGAIN" | "ETIMEDOUT" | "E404" | "E401" | "E403"
|
||||
)
|
||||
})
|
||||
.unwrap_or("npm");
|
||||
IdeError::unavailable(code)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -314,8 +409,9 @@ esac"#;
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(NPM);
|
||||
let cancel = CancellationToken::new();
|
||||
let run =
|
||||
|offer: Option<&AgentCliOffer>| maintain(&npm, &f.install.link, "claude", PKG, offer, &cancel).unwrap();
|
||||
let run = |offer: Option<&AgentCliOffer>| {
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, offer, &cancel).unwrap()
|
||||
};
|
||||
let latest = f.root.path().join("latest");
|
||||
fs::write(&latest, r#""2.1.12""#).unwrap();
|
||||
let Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
@@ -351,7 +447,7 @@ esac"#;
|
||||
let npm = f.npm(NPM);
|
||||
fs::write(f.root.path().join("latest"), r#""2.1.12""#).unwrap();
|
||||
let run = |offer: Option<&AgentCliOffer>| {
|
||||
maintain(&npm, &f.install.link, "claude", PKG, offer, &CancellationToken::new()).unwrap()
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, offer, &CancellationToken::new()).unwrap()
|
||||
};
|
||||
let AgentCliUpdateResult::Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
@@ -377,13 +473,13 @@ esac"#,
|
||||
);
|
||||
let cancel = CancellationToken::new();
|
||||
let AgentCliUpdateResult::Available(offer) =
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, &cancel).unwrap()
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, None, &cancel).unwrap()
|
||||
else {
|
||||
panic!("expected an offer")
|
||||
};
|
||||
let started = f.root.path().join("started");
|
||||
std::thread::scope(|s| {
|
||||
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, Some(&offer), &cancel));
|
||||
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, None, Some(&offer), &cancel));
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !started.exists() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
|
||||
@@ -146,6 +146,10 @@ pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
|
||||
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
|
||||
}
|
||||
|
||||
pub(crate) fn is_approval_option_id(id: &str) -> bool {
|
||||
id == CURSOR_APPROVAL || matches!(id, "mode" | "allow_all" | "permissions" | "approval" | "approval_policy")
|
||||
}
|
||||
|
||||
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
|
||||
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
|
||||
}
|
||||
@@ -425,15 +429,19 @@ pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
id == "fast"
|
||||
}
|
||||
|
||||
/// Whether a raw config option id belongs to the selected model rather than the provider.
|
||||
pub(crate) fn is_per_model_option_id(id: &str) -> bool {
|
||||
matches!(id, "effort" | "reasoning_effort" | "thinking" | "reasoning" | "service_tier")
|
||||
|| is_fast_option(id)
|
||||
|| is_context_option(id)
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`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"
|
||||
|| is_per_model_option_id(&o.id)
|
||||
}
|
||||
|
||||
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::model::AgentEntry;
|
||||
use crate::timeline::{Timeline, blocks_text, content_text};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Where an entry lives: the task's own conversation (`None`) or a subagent's session.
|
||||
pub(crate) type Session = Option<String>;
|
||||
@@ -107,7 +108,7 @@ impl Conversation {
|
||||
out.push((parent, index));
|
||||
if stopped && let Some(child) = self.timeline_mut(&Some(id.to_owned())) {
|
||||
let id = Some(id.to_owned());
|
||||
out.extend(child.end_turn(None).into_iter().map(|i| (id.clone(), i)));
|
||||
out.extend(child.end_turn(None, &HashSet::new()).into_iter().map(|i| (id.clone(), i)));
|
||||
}
|
||||
}
|
||||
"session_message" | "session_message_chunk" => {
|
||||
@@ -169,18 +170,20 @@ impl Conversation {
|
||||
self.subagents.retain(|_| keep.next().unwrap_or(true));
|
||||
}
|
||||
|
||||
/// Settles what an ended turn of the task left open. Subagents work on (in the background).
|
||||
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<(Session, usize)> {
|
||||
self.main.end_turn(done).into_iter().map(|i| (None, i)).collect()
|
||||
/// Settles what an ended turn of the task left open. Subagents work on (in the background),
|
||||
/// and the requests in `open`, which they asked, stay open.
|
||||
pub fn end_turn(&mut self, done: Option<f64>, open: &HashSet<u32>) -> Vec<(Session, usize)> {
|
||||
self.main.end_turn(done, open).into_iter().map(|i| (None, i)).collect()
|
||||
}
|
||||
|
||||
/// Settles everything left open once the agent is gone, subagents included.
|
||||
pub fn settle(&mut self, now: f64) -> Vec<(Session, usize)> {
|
||||
let mut out: Vec<(Session, usize)> = self.main.end_turn(None).into_iter().map(|i| (None, i)).collect();
|
||||
let none = HashSet::new();
|
||||
let mut out: Vec<(Session, usize)> = self.main.end_turn(None, &none).into_iter().map(|i| (None, i)).collect();
|
||||
out.extend(self.main.stop_subagents(now).into_iter().map(|i| (None, i)));
|
||||
for s in &mut self.subagents {
|
||||
let id = Some(s.id.clone());
|
||||
let mut changed = s.timeline.end_turn(None);
|
||||
let mut changed = s.timeline.end_turn(None, &none);
|
||||
changed.extend(s.timeline.stop_subagents(now));
|
||||
out.extend(changed.into_iter().map(|i| (id.clone(), i)));
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! ACP elicitation in form mode: the agent's restricted JSON Schema as form fields, and the
|
||||
//! user's answer as the `elicitation/create` response.
|
||||
|
||||
use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption};
|
||||
use crate::model::{
|
||||
AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption, AgentQuestion,
|
||||
AgentQuestionOption,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -10,6 +13,9 @@ use serde_json::{Map, Value, json};
|
||||
/// anything else cancels it.
|
||||
const DECLINE: &str = "decline";
|
||||
|
||||
/// What the question card sends for Skip.
|
||||
const SKIP: &str = "reject";
|
||||
|
||||
/// The form `elicitation/create` asks for; `Err` when it asks for something else.
|
||||
pub(crate) fn form_of(params: &Value) -> Result<AgentForm, String> {
|
||||
if params.get("mode").and_then(Value::as_str) != Some("form") {
|
||||
@@ -148,6 +154,97 @@ fn scalar(value: &Value) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The questions a form asks when it is an agent's question tool in form shape: every field
|
||||
/// a choice, each followed by its own text field for a typed answer, named after it
|
||||
/// (`question_0` + `question_0_custom` from claude-agent-acp's `AskUserQuestion`, `q0` +
|
||||
/// `q0__other` from OMP's `ask`). They are shown and answered as the agent's questions, one
|
||||
/// at a time like a native `AskUserQuestion` (#7359); [`answer_questions`] turns the answers
|
||||
/// back into the form's values. `None` for any other form.
|
||||
pub(crate) fn questions_of(form: &AgentForm, params: &Value, message: &str) -> Option<Vec<AgentQuestion>> {
|
||||
let choices = form.fields.len() / 2;
|
||||
if choices == 0 || form.fields.len() % 2 == 1 {
|
||||
return None;
|
||||
}
|
||||
let properties = params.pointer("/requestedSchema/properties");
|
||||
form.fields
|
||||
.chunks(2)
|
||||
.map(|pair| {
|
||||
let [choice, text] = pair else { return None };
|
||||
let asks = matches!(choice.kind, AgentFormFieldKind::Choice | AgentFormFieldKind::Choices)
|
||||
&& !choice.options.is_empty()
|
||||
&& text.kind == AgentFormFieldKind::Text
|
||||
&& text.name.len() > choice.name.len()
|
||||
&& text.name.starts_with(&choice.name);
|
||||
if !asks {
|
||||
return None;
|
||||
}
|
||||
let (title, description) = (choice.title.trim(), choice.description.trim());
|
||||
let (header, question) = if choices == 1 && !message.is_empty() {
|
||||
(if title == message || title == choice.name { "" } else { title }, message)
|
||||
} else if description.is_empty() {
|
||||
("", title)
|
||||
} else {
|
||||
(if title == choice.name { "" } else { title }, description)
|
||||
};
|
||||
let schema = properties.and_then(|p| p.get(&choice.name));
|
||||
let options = choice
|
||||
.options
|
||||
.iter()
|
||||
.map(|option| AgentQuestionOption {
|
||||
label: option.label.clone(),
|
||||
description: option.description.clone(),
|
||||
preview: schema.and_then(|s| option_preview(s, &option.value)),
|
||||
})
|
||||
.collect();
|
||||
Some(AgentQuestion {
|
||||
answer_key: Some(choice.name.clone()),
|
||||
header: header.to_owned(),
|
||||
question: question.to_owned(),
|
||||
multi_select: choice.kind == AgentFormFieldKind::Choices,
|
||||
options,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The preview claude-agent-acp forwards beside an option (`_meta["_claude/askUserQuestionOption"]`).
|
||||
fn option_preview(schema: &Value, value: &str) -> Option<String> {
|
||||
let listed = schema.get("oneOf").or_else(|| schema.get("anyOf")).or_else(|| schema.pointer("/items/anyOf"));
|
||||
listed?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.find(|o| o.get("const").and_then(Value::as_str) == Some(value))?
|
||||
.pointer("/_meta/_claude~1askUserQuestionOption/preview")?
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// The form reply to the answers of [`questions_of`]'s questions (question key to the picked
|
||||
/// labels and the typed text): picked options as the choice's values, the text in the field
|
||||
/// beside it. The question card's Skip declines the form; nothing passes through.
|
||||
pub(crate) fn answer_questions(form: &AgentForm, reply: Option<&str>) -> Option<String> {
|
||||
let reply = reply?;
|
||||
if reply == SKIP {
|
||||
return Some(DECLINE.to_owned());
|
||||
}
|
||||
let Ok(answers) = serde_json::from_str::<Map<String, Value>>(reply) else { return Some(reply.to_owned()) };
|
||||
let mut values = Map::new();
|
||||
for pair in form.fields.chunks(2) {
|
||||
let [choice, text] = pair else { continue };
|
||||
let items = answers.get(&choice.name).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
|
||||
let (mut picked, mut typed) = (Vec::new(), Vec::new());
|
||||
for item in items {
|
||||
match choice.options.iter().find(|o| o.label == item) {
|
||||
Some(option) => picked.push(json!(option.value)),
|
||||
None => typed.push(item),
|
||||
}
|
||||
}
|
||||
values.insert(choice.name.clone(), Value::Array(picked));
|
||||
values.insert(text.name.clone(), json!([typed.join("\n")]));
|
||||
}
|
||||
Some(Value::Object(values).to_string())
|
||||
}
|
||||
|
||||
/// A form is submitted from its own card; this option only names a declined form.
|
||||
pub(crate) fn options() -> Vec<AgentPermissionOption> {
|
||||
vec![AgentPermissionOption { id: DECLINE.to_owned(), name: "Decline".to_owned(), kind: "reject_once".to_owned() }]
|
||||
@@ -295,6 +392,90 @@ mod tests {
|
||||
assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b");
|
||||
}
|
||||
|
||||
/// What claude-agent-acp sends for `AskUserQuestion` with two questions.
|
||||
fn claude_questions() -> Value {
|
||||
json!({
|
||||
"sessionId": "s", "mode": "form", "message": "Please answer the following questions.",
|
||||
"requestedSchema": { "type": "object", "properties": {
|
||||
"question_0": { "type": "string", "title": "Delivery", "description": "How should it ship?",
|
||||
"oneOf": [{ "const": "Util + table (Recommended)", "title": "Util + table (Recommended)",
|
||||
"description": "Tracks tasks",
|
||||
"_meta": { "_claude/askUserQuestionOption": { "preview": "```\nUtil\n```" } } },
|
||||
{ "const": "Util only", "title": "Util only" }] },
|
||||
"question_0_custom": { "type": "string", "title": "Other" },
|
||||
"question_1": { "type": "array", "title": "Targets", "description": "Who receives it?",
|
||||
"items": { "anyOf": [{ "const": "Members", "title": "Members" },
|
||||
{ "const": "Tags", "title": "Tags" }] } },
|
||||
"question_1_custom": { "type": "string", "title": "Other" }
|
||||
} }
|
||||
})
|
||||
}
|
||||
|
||||
fn in_order(params: &Value, names: &[&str]) -> AgentForm {
|
||||
let mut form = form_of(params).unwrap();
|
||||
form.fields.sort_by_key(|f| names.iter().position(|n| *n == f.name));
|
||||
form
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_question_tool_form_is_asked_as_questions() {
|
||||
let params = claude_questions();
|
||||
let form = in_order(¶ms, &["question_0", "question_0_custom", "question_1", "question_1_custom"]);
|
||||
let questions = questions_of(&form, ¶ms, "Please answer the following questions.").unwrap();
|
||||
let [delivery, targets] = questions.as_slice() else { panic!("{questions:?}") };
|
||||
assert_eq!(
|
||||
(
|
||||
delivery.answer_key.as_deref(),
|
||||
delivery.header.as_str(),
|
||||
delivery.question.as_str(),
|
||||
delivery.multi_select
|
||||
),
|
||||
(Some("question_0"), "Delivery", "How should it ship?", false)
|
||||
);
|
||||
assert_eq!(delivery.options[0].description, "Tracks tasks");
|
||||
assert_eq!(delivery.options[0].preview.as_deref(), Some("```\nUtil\n```"));
|
||||
assert_eq!(delivery.options[1].preview, None);
|
||||
assert_eq!((targets.question.as_str(), targets.multi_select), ("Who receives it?", true));
|
||||
|
||||
let reply = json!({ "question_0": ["Util only", "keep it small"], "question_1": ["Members", "Tags"] });
|
||||
let reply = answer_questions(&form, Some(&reply.to_string()));
|
||||
let (response, chosen) = answer(&form, reply.as_deref());
|
||||
assert_eq!(
|
||||
response,
|
||||
json!({ "action": "accept", "content": {
|
||||
"question_0": "Util only", "question_0_custom": "keep it small", "question_1": ["Members", "Tags"]
|
||||
} })
|
||||
);
|
||||
assert_eq!(chosen, "Delivery: Util only; Other: keep it small; Targets: Members, Tags");
|
||||
assert_eq!(answer_questions(&form, Some(SKIP)).as_deref(), Some(DECLINE));
|
||||
assert_eq!(answer_questions(&form, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_question_reads_from_the_message() {
|
||||
let params = ask();
|
||||
let form = in_order(¶ms, &["q0", "q0__other"]);
|
||||
let questions = questions_of(&form, ¶ms, "Which database?").unwrap();
|
||||
assert_eq!((questions[0].header.as_str(), questions[0].question.as_str()), ("", "Which database?"));
|
||||
assert_eq!(questions[0].options[0].label, "Postgres");
|
||||
let reply = answer_questions(&form, Some(&json!({ "q0": ["SQLite"] }).to_string()));
|
||||
assert_eq!(answer(&form, reply.as_deref()).0, json!({ "action": "accept", "content": { "q0": "sqlite" } }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_forms_stay_forms() {
|
||||
let only_choices = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
|
||||
"size": { "type": "string", "enum": ["s", "l"] }, "env": { "type": "string", "enum": ["dev"] }
|
||||
} } }))
|
||||
.unwrap();
|
||||
assert_eq!(questions_of(&only_choices, &json!({}), "Pick"), None);
|
||||
let unrelated_text = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
|
||||
"size": { "type": "string", "enum": ["s", "l"] }, "note": { "type": "string" }
|
||||
} } }))
|
||||
.unwrap();
|
||||
assert_eq!(questions_of(&unrelated_text, &json!({}), "Pick"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declining_and_dismissing_send_no_content() {
|
||||
let form = form_of(&ask()).unwrap();
|
||||
|
||||
@@ -16,14 +16,19 @@ pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
|
||||
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None, inline_number: None });
|
||||
}
|
||||
from_uri(str_of(content, "uri")?)
|
||||
}
|
||||
"resource" => {
|
||||
let resource = content.get("resource")?;
|
||||
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
|
||||
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
|
||||
mime.starts_with("image/").then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
})
|
||||
}
|
||||
"resource_link" => {
|
||||
let uri = str_of(content, "uri")?;
|
||||
@@ -51,6 +56,7 @@ pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
});
|
||||
}
|
||||
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
|
||||
@@ -67,6 +73,7 @@ pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
|
||||
mime_type: mime.into(),
|
||||
data: base64::engine::general_purpose::STANDARD.encode(bytes),
|
||||
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
|
||||
inline_number: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+1123
-275
File diff suppressed because it is too large.
Load diff
@@ -70,6 +70,8 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: cfg.registry_name.clone(),
|
||||
registry_url: cfg.registry_url.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,6 +256,28 @@ pub fn apply_save(
|
||||
if input.scope == McpScope::Workspace && !has_workspace {
|
||||
return Err("Open a project to configure workspace MCP servers".into());
|
||||
}
|
||||
let existing_meta = input.id.as_deref().and_then(parse_server_id).and_then(|(prev_scope, prev_name)| {
|
||||
let map = match prev_scope {
|
||||
McpScope::User => &*user,
|
||||
McpScope::Workspace => &*workspace,
|
||||
};
|
||||
map.get(prev_name).map(|prev| (prev.registry_name.clone(), prev.registry_url.clone()))
|
||||
});
|
||||
let registry_name = input
|
||||
.registry_name
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| existing_meta.as_ref().and_then(|(rn, _)| rn.clone()));
|
||||
let registry_url = input
|
||||
.registry_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| existing_meta.and_then(|(_, ru)| ru));
|
||||
|
||||
let cfg = match input.transport {
|
||||
McpTransport::Stdio => {
|
||||
let cmd = input.command.as_deref().map(str::trim).unwrap_or_default();
|
||||
@@ -277,6 +301,8 @@ pub fn apply_save(
|
||||
url: None,
|
||||
headers: BTreeMap::new(),
|
||||
agents: normalize_agents_list(input.agents),
|
||||
registry_name,
|
||||
registry_url,
|
||||
}
|
||||
}
|
||||
McpTransport::Http | McpTransport::Sse => {
|
||||
@@ -301,6 +327,8 @@ pub fn apply_save(
|
||||
url: Some(url.to_owned()),
|
||||
headers,
|
||||
agents: normalize_agents_list(input.agents),
|
||||
registry_name,
|
||||
registry_url,
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1018,6 +1046,8 @@ fn parse_one_server_def(obj: &serde_json::Map<String, Value>) -> Option<AgentMcp
|
||||
url,
|
||||
headers: parse_key_values_map(obj.get("headers")),
|
||||
agents,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1272,6 +1302,8 @@ mod tests {
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1327,6 +1359,8 @@ mod tests {
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1347,6 +1381,8 @@ mod tests {
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1367,6 +1403,8 @@ mod tests {
|
||||
url: Some("https://example.com/mcp".into()),
|
||||
headers: vec![McpKeyValue { name: "Authorization".into(), value: "Bearer secret".into() }],
|
||||
agents: vec!["claude".into()],
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,14 +1,14 @@
|
||||
//! Unified Agent Memory hub (#6810): discovers curated instruction files, path-scoped
|
||||
//! rules, and cross-session learned auto-memories across every coding agent (`claude`,
|
||||
//! `codex`, `copilot`, `cursor`, `gemini`, `hermes`, `opencode`, and custom ACP agents),
|
||||
//! deduplicates symlinks and `@AGENTS.md` imports, resolves `[agents.memory]` policies
|
||||
//! under Workspace Trust without mutating tracked repository files, stages per-session
|
||||
//! `_meta.openidea.memory` delivery for each driver.
|
||||
//! Unified Agent Rules & Memory hub: discovers curated instruction files, path-scoped
|
||||
//! rules, and cross-session learned auto-memories across coding agents (`claude`, `codex`,
|
||||
//! `copilot`, `cursor`, `gemini`, `hermes`, and custom ACP agents), deduplicates symlinks
|
||||
//! and `@AGENTS.md` wrapper imports, resolves per-provider auto-memory policies under
|
||||
//! Workspace Trust, and builds native per-session `_meta.openidea.memory` payloads only
|
||||
//! for drivers that enforce them (`claude`, `codex`).
|
||||
|
||||
use crate::{
|
||||
AgentAutoMemoryStatus, AgentMemoryCatalog, AgentMemoryCreateTarget, AgentMemoryEntry, AgentMemoryEntryPolicy,
|
||||
AgentMemoryKind, AgentMemoryMode, AgentMemoryOrigin, AgentMemoryOverrides, AgentMemorySettings, AgentMemorySource,
|
||||
AgentMemoryState, AutoMemoryMode, CreateAgentMemoryInput, McpScope, PromoteAgentMemoryInput, hermes,
|
||||
AgentAutoMemoryStatus, AgentMemoryCatalog, AgentMemoryCreateTarget, AgentMemoryEntry, AgentMemoryKind,
|
||||
AgentMemoryOrigin, AgentMemoryOverrides, AgentMemorySettings, AgentMemorySource, AutoMemoryMode,
|
||||
CreateAgentMemoryInput, McpScope, PromoteAgentMemoryInput, hermes,
|
||||
};
|
||||
use ide_core::output_encoding::strip_ansi;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -21,7 +21,11 @@ const CLAUDE_MEMORY_INDEX_WARN_LINES: u32 = 180;
|
||||
const CLAUDE_MEMORY_INDEX_BYTE_CAP: u64 = 25 * 1024;
|
||||
const CLAUDE_MEMORY_INDEX_WARN_BYTES: u64 = 22 * 1024;
|
||||
const INSTRUCTION_WARN_LINES: u32 = 200;
|
||||
const MAX_STAGED_SYSTEM_BYTES: usize = 32 * 1024;
|
||||
|
||||
const CLAUDE_AUTO_MODES: &[AutoMemoryMode] = &[AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::Off];
|
||||
const CODEX_AUTO_MODES: &[AutoMemoryMode] =
|
||||
&[AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::ReadOnly, AutoMemoryMode::Off];
|
||||
const HERMES_AUTO_MODES: &[AutoMemoryMode] = &[AutoMemoryMode::ReadWrite, AutoMemoryMode::Off];
|
||||
|
||||
const SKIP_MONOREPO_DIRS: &[&str] =
|
||||
&["node_modules", "target", "dist", "build", "out", "vendor", "coverage", ".git", ".openidea", ".idea"];
|
||||
@@ -46,56 +50,43 @@ impl Default for MemoryPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-session memory payload attached to `session/new`, `session/load`, and `session/fork`
|
||||
/// at `_meta.openidea.memory`.
|
||||
/// Per-session auto-memory payload attached to `session/new`, `session/load`, and `session/fork`
|
||||
/// at `_meta.openidea.memory` for native drivers that enforce it (`claude`, `codex`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct Delivery {
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_auto_memory: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub claude_md_excludes: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_instruction_files: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub claude_add_dir: Option<PathBuf>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub claude_additional_dirs_claude_md: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_use_memories: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_generate_memories: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub codex_developer_instructions: Option<String>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub copilot_exclude_store_memory: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub copilot_enable_memory: Option<bool>,
|
||||
#[serde(skip_serializing_if = "is_false")]
|
||||
pub copilot_disable_custom_instructions: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub copilot_system_message: Option<String>,
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
/// Normalizes a provider id to its auto-memory policy key.
|
||||
/// Native `claude` and `codex` keep their exact ids (distinct from `claude-acp` / `codex-acp`,
|
||||
/// whose external ACP adapters do not consume `_meta.openidea.memory`); Hermes profiles collapse
|
||||
/// onto `"hermes"`.
|
||||
pub fn provider_key(provider: &str) -> &str {
|
||||
let trimmed = provider.trim();
|
||||
if trimmed == "hermes" || trimmed.starts_with("hermes-") { "hermes" } else { trimmed }
|
||||
}
|
||||
|
||||
pub fn normalize_provider_id(provider: &str) -> &str {
|
||||
let base = provider.strip_suffix("-acp").unwrap_or(provider);
|
||||
if base == "hermes" || base.starts_with("hermes-") { "hermes" } else { base }
|
||||
}
|
||||
|
||||
pub fn matches_agent_filter(agents: &[String], provider: &str) -> bool {
|
||||
if agents.is_empty() {
|
||||
return true;
|
||||
/// Auto-memory modes enforced by `provider`. Empty means the agent manages auto-memory itself.
|
||||
pub fn supported_auto_memory_modes(provider: &str) -> &'static [AutoMemoryMode] {
|
||||
match provider_key(provider) {
|
||||
"claude" => CLAUDE_AUTO_MODES,
|
||||
"codex" => CODEX_AUTO_MODES,
|
||||
"hermes" => HERMES_AUTO_MODES,
|
||||
_ => &[],
|
||||
}
|
||||
let target = normalize_provider_id(provider);
|
||||
agents.iter().any(|raw| {
|
||||
let trimmed = raw.trim();
|
||||
trimmed.eq_ignore_ascii_case(provider) || normalize_provider_id(trimmed).eq_ignore_ascii_case(target)
|
||||
})
|
||||
}
|
||||
|
||||
/// True when `provider`'s auto-memory mode is persisted directly in its own native config file
|
||||
/// (e.g. `~/.hermes/config.yaml`) rather than per-project settings or per-session overrides.
|
||||
pub fn is_native_config_auto_memory(provider: &str) -> bool {
|
||||
provider_key(provider) == "hermes"
|
||||
}
|
||||
|
||||
fn source_key(source: AgentMemorySource) -> &'static str {
|
||||
@@ -473,7 +464,7 @@ pub fn discover_memories_with_plugins(
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (discovered entries + per-provider auto-memory statuses)
|
||||
/// against `policy` and optional per-session `session_overrides`.
|
||||
pub fn resolve_catalog(
|
||||
entries: Vec<AgentMemoryEntry>,
|
||||
@@ -481,105 +472,45 @@ pub fn resolve_catalog(
|
||||
policy: &MemoryPolicy,
|
||||
home: Option<&Path>,
|
||||
) -> AgentMemoryCatalog {
|
||||
let resolved_entries = resolve_entries(entries, session_overrides, policy);
|
||||
let (auto_memory, auto_memory_origin) = resolve_global_auto_memory(session_overrides, policy);
|
||||
let providers = build_provider_statuses(&resolved_entries, session_overrides, policy, home);
|
||||
AgentMemoryCatalog { entries: resolved_entries, providers, auto_memory, auto_memory_origin }
|
||||
let providers = build_provider_statuses(&entries, session_overrides, policy, home);
|
||||
AgentMemoryCatalog { entries, providers, workspace_trusted: policy.workspace_trusted }
|
||||
}
|
||||
|
||||
/// Resolves every discovered memory entry's effective [`AgentMemoryMode`] with precedence:
|
||||
/// `Workspace Trust > Session Override > Workspace Settings > User Settings > Default (Auto)`.
|
||||
pub fn resolve_entries(
|
||||
entries: Vec<AgentMemoryEntry>,
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> Vec<AgentMemoryState> {
|
||||
let mut out = Vec::with_capacity(entries.len());
|
||||
for entry in entries {
|
||||
if entry.source.is_workspace() && !policy.workspace_trusted {
|
||||
out.push(AgentMemoryState {
|
||||
entry,
|
||||
mode: AgentMemoryMode::Off,
|
||||
agents: Vec::new(),
|
||||
origin: AgentMemoryOrigin::Trust,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let ws_pol = lookup_entry_policy(&policy.workspace.entries, &entry.id)
|
||||
.filter(|p| policy.workspace_trusted || p.mode == AgentMemoryMode::Off);
|
||||
let user_pol = lookup_entry_policy(&policy.user.entries, &entry.id);
|
||||
let agents = ws_pol
|
||||
.filter(|p| !p.agents.is_empty())
|
||||
.or_else(|| user_pol.filter(|p| !p.agents.is_empty()))
|
||||
.map(|p| p.agents.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
let (mode, origin) =
|
||||
if let Some(chosen) = session_overrides.and_then(|s| lookup_session_entry(&s.entries, &entry.id)) {
|
||||
(chosen, AgentMemoryOrigin::Session)
|
||||
} else if let Some(ws) = ws_pol {
|
||||
(ws.mode, AgentMemoryOrigin::Workspace)
|
||||
} else if let Some(us) = user_pol {
|
||||
(us.mode, AgentMemoryOrigin::User)
|
||||
} else {
|
||||
(AgentMemoryMode::Auto, AgentMemoryOrigin::None)
|
||||
};
|
||||
out.push(AgentMemoryState { entry, mode, agents, origin });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn resolve_global_auto_memory(
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> (AutoMemoryMode, AgentMemoryOrigin) {
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory) {
|
||||
return (mode, AgentMemoryOrigin::Session);
|
||||
}
|
||||
let ws_mode = policy.workspace.auto_memory;
|
||||
if ws_mode != AutoMemoryMode::Inherit && (policy.workspace_trusted || ws_mode == AutoMemoryMode::Off) {
|
||||
return (ws_mode, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if policy.user.auto_memory != AutoMemoryMode::Inherit {
|
||||
return (policy.user.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
(AutoMemoryMode::Inherit, AgentMemoryOrigin::None)
|
||||
}
|
||||
|
||||
/// Resolves the effective [`AutoMemoryMode`] for one `provider` (`claude`, `codex`, `copilot`, `hermes`, etc.).
|
||||
/// Resolves the effective [`AutoMemoryMode`] for one `provider` that supports OpenIDEA-managed
|
||||
/// settings/session overrides (`claude`, `codex`).
|
||||
/// Precedence: `Session Override > Workspace Settings (when trusted or Off) > User Settings > Inherit`.
|
||||
pub fn resolve_provider_auto_memory(
|
||||
provider: &str,
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
) -> (AutoMemoryMode, AgentMemoryOrigin) {
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory) {
|
||||
let supported = supported_auto_memory_modes(provider);
|
||||
if supported.is_empty() || is_native_config_auto_memory(provider) {
|
||||
return (AutoMemoryMode::Inherit, AgentMemoryOrigin::None);
|
||||
}
|
||||
let accepts = |mode: AutoMemoryMode| mode != AutoMemoryMode::Inherit && supported.contains(&mode);
|
||||
if let Some(mode) = session_overrides.and_then(|s| s.auto_memory)
|
||||
&& accepts(mode)
|
||||
{
|
||||
return (mode, AgentMemoryOrigin::Session);
|
||||
}
|
||||
let key = normalize_provider_id(provider);
|
||||
let key = provider_key(provider);
|
||||
if let Some(ws_prov) = policy.workspace.providers.get(key)
|
||||
&& ws_prov.auto_memory != AutoMemoryMode::Inherit
|
||||
&& accepts(ws_prov.auto_memory)
|
||||
&& (policy.workspace_trusted || ws_prov.auto_memory == AutoMemoryMode::Off)
|
||||
{
|
||||
return (ws_prov.auto_memory, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if policy.workspace.auto_memory != AutoMemoryMode::Inherit
|
||||
&& (policy.workspace_trusted || policy.workspace.auto_memory == AutoMemoryMode::Off)
|
||||
{
|
||||
return (policy.workspace.auto_memory, AgentMemoryOrigin::Workspace);
|
||||
}
|
||||
if let Some(user_prov) = policy.user.providers.get(key)
|
||||
&& user_prov.auto_memory != AutoMemoryMode::Inherit
|
||||
&& accepts(user_prov.auto_memory)
|
||||
{
|
||||
return (user_prov.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
if policy.user.auto_memory != AutoMemoryMode::Inherit {
|
||||
return (policy.user.auto_memory, AgentMemoryOrigin::User);
|
||||
}
|
||||
(AutoMemoryMode::Inherit, AgentMemoryOrigin::None)
|
||||
}
|
||||
|
||||
fn build_provider_statuses(
|
||||
states: &[AgentMemoryState],
|
||||
entries: &[AgentMemoryEntry],
|
||||
session_overrides: Option<&AgentMemoryOverrides>,
|
||||
policy: &MemoryPolicy,
|
||||
home: Option<&Path>,
|
||||
@@ -587,11 +518,9 @@ fn build_provider_statuses(
|
||||
let stats_for = |src: AgentMemorySource| -> (u32, u32) {
|
||||
let mut count = 0u32;
|
||||
let mut tokens = 0u32;
|
||||
for s in states.iter().filter(|s| s.entry.source == src) {
|
||||
for e in entries.iter().filter(|e| e.source == src) {
|
||||
count += 1;
|
||||
if s.mode != AgentMemoryMode::Off {
|
||||
tokens = tokens.saturating_add(s.entry.approx_tokens);
|
||||
}
|
||||
tokens = tokens.saturating_add(e.approx_tokens);
|
||||
}
|
||||
(count, tokens)
|
||||
};
|
||||
@@ -614,19 +543,12 @@ fn build_provider_statuses(
|
||||
codex_dir.as_ref().map(|d| markdown_files(&d.join("rollout_summaries"), 1).len() as u32).unwrap_or(0);
|
||||
let (codex_mode, codex_origin) = resolve_provider_auto_memory("codex", session_overrides, policy);
|
||||
|
||||
let (copilot_mode, copilot_origin) = resolve_provider_auto_memory("copilot", session_overrides, policy);
|
||||
|
||||
let (hermes_notes, hermes_tokens) = stats_for(AgentMemorySource::HermesAuto);
|
||||
let hermes_dir = hermes_root(home).map(|r| r.join("memories"));
|
||||
let (mut hermes_mode, hermes_origin) = resolve_provider_auto_memory("hermes", session_overrides, policy);
|
||||
if hermes_mode == AutoMemoryMode::Inherit
|
||||
&& let Some(root) = hermes_root(home)
|
||||
&& let Some(cfg_mode) = read_hermes_config_memory_mode(&root)
|
||||
{
|
||||
hermes_mode = cfg_mode;
|
||||
}
|
||||
|
||||
let (acp_mode, acp_origin) = resolve_provider_auto_memory("acp", session_overrides, policy);
|
||||
let (hermes_mode, hermes_origin) = match hermes_root(home).and_then(|root| read_hermes_config_memory_mode(&root)) {
|
||||
Some(cfg_mode) => (cfg_mode, AgentMemoryOrigin::Native),
|
||||
None => (AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Native),
|
||||
};
|
||||
|
||||
vec![
|
||||
AgentAutoMemoryStatus {
|
||||
@@ -634,12 +556,12 @@ fn build_provider_statuses(
|
||||
label: "Claude Code".into(),
|
||||
mode: claude_mode,
|
||||
origin: claude_origin,
|
||||
supported_modes: CLAUDE_AUTO_MODES.to_vec(),
|
||||
native_config_only: false,
|
||||
note_count: claude_notes,
|
||||
rollout_count: 0,
|
||||
approx_tokens: claude_tokens,
|
||||
storage_path: claude_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: true,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
@@ -647,295 +569,81 @@ fn build_provider_statuses(
|
||||
label: "Codex".into(),
|
||||
mode: codex_mode,
|
||||
origin: codex_origin,
|
||||
supported_modes: CODEX_AUTO_MODES.to_vec(),
|
||||
native_config_only: false,
|
||||
note_count: codex_notes,
|
||||
rollout_count: codex_rollouts,
|
||||
approx_tokens: codex_tokens,
|
||||
storage_path: codex_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "copilot".into(),
|
||||
label: "GitHub Copilot".into(),
|
||||
mode: copilot_mode,
|
||||
origin: copilot_origin,
|
||||
note_count: 0,
|
||||
rollout_count: 0,
|
||||
approx_tokens: 0,
|
||||
storage_path: home.map(|h| h.join(".copilot").into()),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: false,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "hermes".into(),
|
||||
label: "Hermes Agent".into(),
|
||||
mode: hermes_mode,
|
||||
origin: hermes_origin,
|
||||
supported_modes: HERMES_AUTO_MODES.to_vec(),
|
||||
native_config_only: true,
|
||||
note_count: hermes_notes,
|
||||
rollout_count: 0,
|
||||
approx_tokens: hermes_tokens,
|
||||
storage_path: hermes_dir.map(Into::into),
|
||||
supports_auto_control: true,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: true,
|
||||
},
|
||||
AgentAutoMemoryStatus {
|
||||
provider: "acp".into(),
|
||||
label: "Cursor / Gemini / ACP".into(),
|
||||
mode: acp_mode,
|
||||
origin: acp_origin,
|
||||
note_count: 0,
|
||||
rollout_count: 0,
|
||||
approx_tokens: 0,
|
||||
storage_path: None,
|
||||
supports_auto_control: false,
|
||||
supports_file_exclusion: false,
|
||||
supports_reset: false,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Directory under `<store_dir>/session-memory/<task_id>` holding per-session staged rules.
|
||||
pub fn farm_dir(store_dir: &Path, task_id: &str) -> PathBuf {
|
||||
store_dir.join("session-memory").join(task_id)
|
||||
/// Builds the per-session [`Delivery`] payload (`_meta.openidea.memory`) for a native driver
|
||||
/// (`"claude"` or `"codex"`). Returns `None` when `auto_memory` is `Inherit` or the driver
|
||||
/// does not consume `_meta.openidea.memory`.
|
||||
pub fn build_delivery(driver_key: &str, auto_memory: AutoMemoryMode) -> Option<Delivery> {
|
||||
if auto_memory == AutoMemoryMode::Inherit {
|
||||
return None;
|
||||
}
|
||||
match driver_key {
|
||||
"claude" => match auto_memory {
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
Some(Delivery { auto_memory, claude_auto_memory: Some(true), ..Delivery::default() })
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
Some(Delivery { auto_memory, claude_auto_memory: Some(false), ..Delivery::default() })
|
||||
}
|
||||
AutoMemoryMode::Inherit | AutoMemoryMode::ReadOnly => None,
|
||||
},
|
||||
"codex" => match auto_memory {
|
||||
AutoMemoryMode::ReadWrite => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(true),
|
||||
codex_generate_memories: Some(true),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::ReadOnly => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(true),
|
||||
codex_generate_memories: Some(false),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::Off => Some(Delivery {
|
||||
auto_memory,
|
||||
codex_use_memories: Some(false),
|
||||
codex_generate_memories: Some(false),
|
||||
..Delivery::default()
|
||||
}),
|
||||
AutoMemoryMode::Inherit => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes a deleted task's staged memory folder, if any.
|
||||
pub fn remove_farm(store_dir: &Path, task_id: &str) {
|
||||
let _ = std::fs::remove_dir_all(farm_dir(store_dir, task_id));
|
||||
}
|
||||
|
||||
/// Computes the per-session [`Delivery`] payload (`_meta.openidea.memory`) for `provider`,
|
||||
/// staging non-native rules into `farm` where needed (e.g. Claude `.claude/rules/`).
|
||||
pub fn stage(
|
||||
farm: &Path,
|
||||
provider: &str,
|
||||
states: &[AgentMemoryState],
|
||||
auto_memory: AutoMemoryMode,
|
||||
cwd: &Path,
|
||||
home: Option<&Path>,
|
||||
) -> std::io::Result<Delivery> {
|
||||
let norm = normalize_provider_id(provider);
|
||||
let mut out = Delivery { auto_memory, ..Delivery::default() };
|
||||
|
||||
let claude_rules_dir = farm.join(".claude/rules");
|
||||
match std::fs::remove_dir_all(&claude_rules_dir) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
|
||||
_ => {}
|
||||
/// Explicitly updates Hermes's native `config.yaml` (`memory_enabled` and `user_profile_enabled`).
|
||||
/// Never called during session startup — only when the user changes Hermes's setting directly.
|
||||
pub fn set_hermes_auto_memory(provider: &str, mode: AutoMemoryMode, home: Option<&Path>) -> Result<(), String> {
|
||||
if !matches!(mode, AutoMemoryMode::ReadWrite | AutoMemoryMode::Off) {
|
||||
return Err("Hermes auto-memory supports only On (readWrite) or Off".into());
|
||||
}
|
||||
|
||||
match norm {
|
||||
"claude" => {
|
||||
out.claude_auto_memory = match auto_memory {
|
||||
AutoMemoryMode::Inherit => None,
|
||||
AutoMemoryMode::ReadWrite => Some(true),
|
||||
// Claude Code has one boolean (`autoMemoryEnabled`): ReadOnly and Off both stop background writes;
|
||||
// existing `MEMORY.md` entries that remain `Auto`/`Always` can still be staged as read-only rules.
|
||||
AutoMemoryMode::ReadOnly | AutoMemoryMode::Off => Some(false),
|
||||
};
|
||||
|
||||
let mut agents_md_active = false;
|
||||
let mut agents_md_off = false;
|
||||
let mut claude_md_active = false;
|
||||
|
||||
for state in states {
|
||||
let effective_on = state.mode != AgentMemoryMode::Off && matches_agent_filter(&state.agents, provider);
|
||||
let p = state.entry.path.0.as_path();
|
||||
let fname = file_name(p).unwrap_or_default();
|
||||
|
||||
if matches!(state.entry.source, AgentMemorySource::Workspace) && fname == "AGENTS.md" {
|
||||
if effective_on {
|
||||
agents_md_active = true;
|
||||
} else {
|
||||
agents_md_off = true;
|
||||
}
|
||||
}
|
||||
if matches!(state.entry.source, AgentMemorySource::ClaudeWorkspace)
|
||||
&& matches!(fname.as_str(), "CLAUDE.md" | "CLAUDE.local.md")
|
||||
&& effective_on
|
||||
{
|
||||
claude_md_active = true;
|
||||
}
|
||||
|
||||
if !effective_on {
|
||||
if !state.entry.source.is_auto() {
|
||||
out.claude_md_excludes.push(p.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Stage `Always` rules from other agents, or a `ReadOnly` `ClaudeAuto` `MEMORY.md`,
|
||||
// into `<farm>/.claude/rules/`.
|
||||
let stage_into_claude = (auto_memory == AutoMemoryMode::ReadOnly
|
||||
&& state.entry.source == AgentMemorySource::ClaudeAuto
|
||||
&& fname == "MEMORY.md")
|
||||
|| (state.mode == AgentMemoryMode::Always
|
||||
&& !matches!(
|
||||
state.entry.source,
|
||||
AgentMemorySource::ClaudeWorkspace | AgentMemorySource::ClaudeUser
|
||||
));
|
||||
|
||||
if stage_into_claude {
|
||||
stage_claude_rule(&claude_rules_dir, state)?;
|
||||
}
|
||||
}
|
||||
|
||||
if agents_md_active && claude_md_active {
|
||||
out.claude_instruction_files = Some("claude-md-and-agents-md".into());
|
||||
} else if agents_md_off {
|
||||
out.claude_instruction_files = Some("claude-md".into());
|
||||
}
|
||||
|
||||
if claude_rules_dir.exists() {
|
||||
out.claude_add_dir = Some(farm.to_path_buf());
|
||||
out.claude_additional_dirs_claude_md = true;
|
||||
}
|
||||
}
|
||||
"codex" => {
|
||||
match auto_memory {
|
||||
AutoMemoryMode::Inherit => {}
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
out.codex_use_memories = Some(true);
|
||||
out.codex_generate_memories = Some(true);
|
||||
}
|
||||
AutoMemoryMode::ReadOnly => {
|
||||
out.codex_use_memories = Some(true);
|
||||
out.codex_generate_memories = Some(false);
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
out.codex_use_memories = Some(false);
|
||||
out.codex_generate_memories = Some(false);
|
||||
}
|
||||
}
|
||||
let extra = collect_staged_text(states, provider, cwd, home, |s| {
|
||||
s.mode == AgentMemoryMode::Always
|
||||
&& !matches!(s.entry.source, AgentMemorySource::CodexUser | AgentMemorySource::CodexAuto)
|
||||
});
|
||||
if !extra.is_empty() {
|
||||
out.codex_developer_instructions = Some(extra);
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
match auto_memory {
|
||||
AutoMemoryMode::Inherit => {}
|
||||
AutoMemoryMode::ReadWrite => {
|
||||
out.copilot_enable_memory = Some(true);
|
||||
}
|
||||
AutoMemoryMode::ReadOnly => {
|
||||
out.copilot_enable_memory = Some(true);
|
||||
out.copilot_exclude_store_memory = true;
|
||||
}
|
||||
AutoMemoryMode::Off => {
|
||||
out.copilot_enable_memory = Some(false);
|
||||
out.copilot_exclude_store_memory = true;
|
||||
}
|
||||
}
|
||||
let native_instructions: Vec<&AgentMemoryState> = states
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
matches!(
|
||||
s.entry.source,
|
||||
AgentMemorySource::Workspace
|
||||
| AgentMemorySource::ClaudeWorkspace
|
||||
| AgentMemorySource::GithubWorkspace
|
||||
| AgentMemorySource::CopilotUser
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
if !native_instructions.is_empty()
|
||||
&& native_instructions
|
||||
.iter()
|
||||
.all(|s| s.mode == AgentMemoryMode::Off || !matches_agent_filter(&s.agents, provider))
|
||||
{
|
||||
out.copilot_disable_custom_instructions = true;
|
||||
}
|
||||
let extra = collect_staged_text(states, provider, cwd, home, |s| {
|
||||
s.mode == AgentMemoryMode::Always
|
||||
&& !matches!(s.entry.source, AgentMemorySource::GithubWorkspace | AgentMemorySource::CopilotUser)
|
||||
});
|
||||
if !extra.is_empty() {
|
||||
out.copilot_system_message = Some(extra);
|
||||
}
|
||||
}
|
||||
"hermes" => {
|
||||
if auto_memory != AutoMemoryMode::Inherit
|
||||
&& let Some(root) = hermes_root(home)
|
||||
&& let Some(prof_home) = hermes::profile_home(&root, provider)
|
||||
{
|
||||
let _ = write_hermes_config_memory_mode(&prof_home, auto_memory);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn stage_claude_rule(rules_dir: &Path, state: &AgentMemoryState) -> std::io::Result<()> {
|
||||
let Ok(raw) = std::fs::read_to_string(&state.entry.path.0) else {
|
||||
return Ok(());
|
||||
};
|
||||
std::fs::create_dir_all(rules_dir)?;
|
||||
let fm = Frontmatter::parse(&raw);
|
||||
let body = raw.get(fm.body..).unwrap_or(raw.as_str()).trim();
|
||||
if body.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let slug = sanitize_slug(&state.entry.id);
|
||||
let out_text = if state.mode != AgentMemoryMode::Always && !state.entry.paths.is_empty() {
|
||||
let mut header = String::from("---\npaths:\n");
|
||||
for p in &state.entry.paths {
|
||||
header.push_str(&format!(" - \"{}\"\n", p.replace('"', "\\\"")));
|
||||
}
|
||||
header.push_str("---\n\n");
|
||||
header.push_str(body);
|
||||
header.push('\n');
|
||||
header
|
||||
} else {
|
||||
format!("{body}\n")
|
||||
};
|
||||
std::fs::write(rules_dir.join(format!("{slug}.md")), out_text)
|
||||
}
|
||||
|
||||
fn collect_staged_text<F>(
|
||||
states: &[AgentMemoryState],
|
||||
provider: &str,
|
||||
_cwd: &Path,
|
||||
_home: Option<&Path>,
|
||||
include: F,
|
||||
) -> String
|
||||
where
|
||||
F: Fn(&AgentMemoryState) -> bool,
|
||||
{
|
||||
let mut buf = String::new();
|
||||
for state in states {
|
||||
if state.mode == AgentMemoryMode::Off || !matches_agent_filter(&state.agents, provider) {
|
||||
continue;
|
||||
}
|
||||
if !include(state) {
|
||||
continue;
|
||||
}
|
||||
// Path-scoped rules only enter un-scoped system prompts when explicitly set to `Always`.
|
||||
if state.mode != AgentMemoryMode::Always && !state.entry.paths.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Ok(raw) = std::fs::read_to_string(&state.entry.path.0) else {
|
||||
continue;
|
||||
};
|
||||
let fm = Frontmatter::parse(&raw);
|
||||
let body = raw.get(fm.body..).unwrap_or(raw.as_str()).trim();
|
||||
if body.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let chunk = format!("## Memory ({})\n{}\n\n", state.entry.title, body);
|
||||
if buf.len() + chunk.len() > MAX_STAGED_SYSTEM_BYTES {
|
||||
break;
|
||||
}
|
||||
buf.push_str(&chunk);
|
||||
}
|
||||
buf.trim().to_owned()
|
||||
let root = hermes_root(home).ok_or("Home directory is unavailable")?;
|
||||
let prof_home = hermes::profile_home(&root, provider).unwrap_or(root);
|
||||
write_hermes_config_memory_mode(&prof_home, mode).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
// ─── File Operations: Create, Promote, Delete & Reset ───────────────────────────────
|
||||
@@ -1064,9 +772,7 @@ pub fn promote_memory(
|
||||
pub fn delete_memory(id: &str, entries: &[AgentMemoryEntry]) -> Result<(), String> {
|
||||
let entry = entries.iter().find(|e| e.id == id).ok_or_else(|| format!("Memory entry `{id}` was not found"))?;
|
||||
if !entry.writable {
|
||||
return Err(
|
||||
"Curated instruction and rule files cannot be deleted here; open the file or set its mode to Off.".into()
|
||||
);
|
||||
return Err("Curated instruction and rule files cannot be deleted here; open the file in the editor.".into());
|
||||
}
|
||||
match std::fs::remove_file(&entry.path.0) {
|
||||
Ok(()) => Ok(()),
|
||||
@@ -1079,7 +785,7 @@ pub fn delete_memory(id: &str, entries: &[AgentMemoryEntry]) -> Result<(), Strin
|
||||
pub fn reset_provider_memory(provider: &str, workspaces: &[PathBuf], home: Option<&Path>) -> Result<u32, String> {
|
||||
let home = home.ok_or("Home directory is unavailable")?;
|
||||
let mut removed = 0u32;
|
||||
match normalize_provider_id(provider) {
|
||||
match provider_key(provider) {
|
||||
"claude" => {
|
||||
for dir in claude_auto_memory_dirs(&home.join(".claude"), home, workspaces) {
|
||||
for f in markdown_files(&dir, 2) {
|
||||
@@ -1134,19 +840,6 @@ fn validate_slug(raw: &str) -> Result<String, String> {
|
||||
Ok(trimmed.to_owned())
|
||||
}
|
||||
|
||||
fn sanitize_slug(raw: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for ch in raw.chars() {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
|
||||
out.push(ch.to_ascii_lowercase());
|
||||
} else if !out.ends_with('-') {
|
||||
out.push('-');
|
||||
}
|
||||
}
|
||||
let trimmed = out.trim_matches('-');
|
||||
if trimmed.is_empty() { "memory".into() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
fn format_markdown_with_frontmatter(
|
||||
description: Option<&str>,
|
||||
paths_key: &str,
|
||||
@@ -1201,17 +894,6 @@ fn format_cursor_mdc(description: Option<&str>, globs: &[String], always_apply:
|
||||
out
|
||||
}
|
||||
|
||||
fn lookup_entry_policy<'a>(
|
||||
map: &'a BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
id: &str,
|
||||
) -> Option<&'a AgentMemoryEntryPolicy> {
|
||||
map.get(id).or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(id)).map(|(_, v)| v))
|
||||
}
|
||||
|
||||
fn lookup_session_entry(map: &BTreeMap<String, AgentMemoryMode>, id: &str) -> Option<AgentMemoryMode> {
|
||||
map.get(id).copied().or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(id)).map(|(_, v)| *v))
|
||||
}
|
||||
|
||||
fn claude_auto_memory_dirs(claude_home: &Path, home: &Path, workspaces: &[PathBuf]) -> Vec<PathBuf> {
|
||||
let mut dirs = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
@@ -1899,111 +1581,112 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_resolution_enforces_workspace_trust_and_precedence() {
|
||||
fn policy_resolution_enforces_workspace_trust_and_provider_capabilities() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
let home = tmp.path().join("home");
|
||||
write(&ws.join("AGENTS.md"), "Workspace instructions\n");
|
||||
write(&home.join(".claude/CLAUDE.md"), "User memory\n");
|
||||
write(&home.join(".hermes/profile.yaml"), "display_name: default\n");
|
||||
|
||||
let entries = discover_memories(std::slice::from_ref(&ws), Some(&home));
|
||||
|
||||
let mut ws_settings = AgentMemorySettings { auto_memory: AutoMemoryMode::ReadWrite, ..Default::default() };
|
||||
// Untrusted workspace tries to turn user memory `Always` on (ignored!) and another `Off` (honored).
|
||||
ws_settings.entries.insert(
|
||||
"claudeUser::CLAUDE.md".into(),
|
||||
AgentMemoryEntryPolicy { mode: AgentMemoryMode::Always, agents: Vec::new() },
|
||||
);
|
||||
let mut ws_settings = AgentMemorySettings::default();
|
||||
ws_settings
|
||||
.providers
|
||||
.insert("claude".into(), crate::AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::ReadWrite });
|
||||
ws_settings
|
||||
.providers
|
||||
.insert("codex".into(), crate::AgentProviderMemoryPolicy { auto_memory: AutoMemoryMode::Off });
|
||||
|
||||
let untrusted = MemoryPolicy {
|
||||
user: AgentMemorySettings::default(),
|
||||
workspace: ws_settings.clone(),
|
||||
workspace: ws_settings,
|
||||
workspace_trusted: false,
|
||||
workspace_roots: vec![ws.clone()],
|
||||
};
|
||||
let cat = resolve_catalog(entries.clone(), None, &untrusted, Some(&home));
|
||||
// Workspace entry locked `Off` by Trust
|
||||
let ws_state = cat.entries.iter().find(|s| s.entry.id == "workspace::AGENTS.md").unwrap();
|
||||
assert_eq!((ws_state.mode, ws_state.origin), (AgentMemoryMode::Off, AgentMemoryOrigin::Trust));
|
||||
// Untrusted workspace could NOT escalate `claudeUser::CLAUDE.md` or `autoMemory`
|
||||
let user_state = cat.entries.iter().find(|s| s.entry.id == "claudeUser::CLAUDE.md").unwrap();
|
||||
assert_eq!((user_state.mode, user_state.origin), (AgentMemoryMode::Auto, AgentMemoryOrigin::None));
|
||||
assert_eq!(cat.auto_memory, AutoMemoryMode::Inherit);
|
||||
assert!(!cat.workspace_trusted);
|
||||
// Untrusted workspace cannot enable Claude auto-memory, but can turn Codex auto-memory off.
|
||||
let claude = cat.providers.iter().find(|p| p.provider == "claude").unwrap();
|
||||
assert_eq!((claude.mode, claude.origin), (AutoMemoryMode::Inherit, AgentMemoryOrigin::None));
|
||||
assert_eq!(claude.supported_modes, [AutoMemoryMode::Inherit, AutoMemoryMode::ReadWrite, AutoMemoryMode::Off]);
|
||||
let codex = cat.providers.iter().find(|p| p.provider == "codex").unwrap();
|
||||
assert_eq!((codex.mode, codex.origin), (AutoMemoryMode::Off, AgentMemoryOrigin::Workspace));
|
||||
let hermes = cat.providers.iter().find(|p| p.provider == "hermes").unwrap();
|
||||
assert!(hermes.native_config_only);
|
||||
assert_eq!((hermes.mode, hermes.origin), (AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Native));
|
||||
|
||||
// Session override wins in a trusted workspace
|
||||
// Session override wins in a trusted workspace, and unsupported modes are ignored.
|
||||
let trusted = MemoryPolicy { workspace_trusted: true, ..untrusted };
|
||||
let session = AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::from([("workspace::AGENTS.md".into(), AgentMemoryMode::Off)]),
|
||||
};
|
||||
let cat2 = resolve_catalog(entries, Some(&session), &trusted, Some(&home));
|
||||
assert_eq!((cat2.auto_memory, cat2.auto_memory_origin), (AutoMemoryMode::ReadOnly, AgentMemoryOrigin::Session));
|
||||
let ws_state2 = cat2.entries.iter().find(|s| s.entry.id == "workspace::AGENTS.md").unwrap();
|
||||
assert_eq!((ws_state2.mode, ws_state2.origin), (AgentMemoryMode::Off, AgentMemoryOrigin::Session));
|
||||
let session_ro = AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::ReadOnly) };
|
||||
assert_eq!(
|
||||
resolve_provider_auto_memory("claude", Some(&session_ro), &trusted),
|
||||
(AutoMemoryMode::ReadWrite, AgentMemoryOrigin::Workspace)
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_provider_auto_memory("codex", Some(&session_ro), &trusted),
|
||||
(AutoMemoryMode::ReadOnly, AgentMemoryOrigin::Session)
|
||||
);
|
||||
// External ACP adapters and unsupported providers never report OpenIDEA auto-memory control.
|
||||
assert!(supported_auto_memory_modes("claude-acp").is_empty());
|
||||
assert!(supported_auto_memory_modes("codex-acp").is_empty());
|
||||
assert!(supported_auto_memory_modes("copilot").is_empty());
|
||||
assert!(supported_auto_memory_modes("cursor").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stages_per_driver_delivery_for_claude_codex_copilot_and_hermes() {
|
||||
fn builds_delivery_only_for_native_claude_and_codex_and_keeps_hermes_explicit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
let home = tmp.path().join("home");
|
||||
let farm = tmp.path().join("farm");
|
||||
|
||||
write(&ws.join("AGENTS.md"), "Shared workspace rule\n");
|
||||
write(&ws.join("CLAUDE.md"), "Claude-specific rule\n");
|
||||
write(&ws.join("CLAUDE.local.md"), "Noisy local note\n");
|
||||
write(
|
||||
&ws.join(".github/instructions/ipc.instructions.md"),
|
||||
"---\napplyTo: \"crates/**/*.rs\"\n---\nUse async IPC for disk ops.\n",
|
||||
);
|
||||
write(&home.join(".gemini/GEMINI.md"), "Keep PRs focused.\n");
|
||||
write(&home.join(".hermes/profile.yaml"), "display_name: default\n");
|
||||
|
||||
let entries = discover_memories(std::slice::from_ref(&ws), Some(&home));
|
||||
let session = AgentMemoryOverrides {
|
||||
auto_memory: Some(AutoMemoryMode::ReadOnly),
|
||||
entries: BTreeMap::from([
|
||||
("claudeWorkspace::CLAUDE.local.md".into(), AgentMemoryMode::Off),
|
||||
// `Always` delivers another agent's files to every agent, path scope dropped.
|
||||
("githubWorkspace::.github/instructions/ipc.instructions.md".into(), AgentMemoryMode::Always),
|
||||
("geminiUser::GEMINI.md".into(), AgentMemoryMode::Always),
|
||||
]),
|
||||
};
|
||||
let policy = MemoryPolicy { workspace_roots: vec![ws.clone()], workspace_trusted: true, ..Default::default() };
|
||||
let cat = resolve_catalog(entries, Some(&session), &policy, Some(&home));
|
||||
// Claude: Inherit -> None, ReadWrite -> true, Off -> false, ReadOnly -> None
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::Inherit), None);
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::ReadOnly), None);
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::ReadWrite).unwrap().claude_auto_memory, Some(true));
|
||||
assert_eq!(build_delivery("claude", AutoMemoryMode::Off).unwrap().claude_auto_memory, Some(false));
|
||||
|
||||
// 1. Claude delivery
|
||||
let claude = stage(&farm, "claude", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(claude.claude_auto_memory, Some(false));
|
||||
assert_eq!(claude.claude_instruction_files.as_deref(), Some("claude-md-and-agents-md"));
|
||||
assert!(claude.claude_md_excludes.iter().any(|p| p.ends_with("CLAUDE.local.md")));
|
||||
assert!(claude.claude_add_dir.is_some());
|
||||
assert!(claude.claude_additional_dirs_claude_md);
|
||||
let staged_rule = std::fs::read_to_string(
|
||||
farm.join(".claude/rules/githubworkspace-github-instructions-ipc-instructions-md.md"),
|
||||
// Codex: ReadWrite / ReadOnly / Off
|
||||
assert_eq!(build_delivery("codex", AutoMemoryMode::Inherit), None);
|
||||
let codex_ro = build_delivery("codex", AutoMemoryMode::ReadOnly).unwrap();
|
||||
assert_eq!(codex_ro.codex_use_memories, Some(true));
|
||||
assert_eq!(codex_ro.codex_generate_memories, Some(false));
|
||||
let codex_off = build_delivery("codex", AutoMemoryMode::Off).unwrap();
|
||||
assert_eq!(codex_off.codex_use_memories, Some(false));
|
||||
assert_eq!(codex_off.codex_generate_memories, Some(false));
|
||||
|
||||
// Copilot, ACP, Hermes produce no session delivery and never touch Hermes config.yaml
|
||||
assert_eq!(build_delivery("copilot", AutoMemoryMode::Off), None);
|
||||
assert_eq!(build_delivery("acp", AutoMemoryMode::Off), None);
|
||||
assert_eq!(build_delivery("hermes", AutoMemoryMode::Off), None);
|
||||
assert!(!home.join(".hermes/config.yaml").exists());
|
||||
|
||||
// Explicit Hermes toggle updates config.yaml directly and rejects unsupported modes
|
||||
assert!(set_hermes_auto_memory("hermes", AutoMemoryMode::ReadOnly, Some(&home)).is_err());
|
||||
set_hermes_auto_memory("hermes", AutoMemoryMode::Off, Some(&home)).unwrap();
|
||||
assert_eq!(read_hermes_config_memory_mode(&home.join(".hermes")), Some(AutoMemoryMode::Off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_settings_and_overrides_deserialize_cleanly() {
|
||||
let legacy_settings: AgentMemorySettings = serde_json::from_str(
|
||||
r#"{
|
||||
"autoMemory": "readOnly",
|
||||
"providers": { "codex": { "autoMemory": "off" } },
|
||||
"entries": { "workspace::AGENTS.md": { "mode": "off" } }
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(staged_rule, "Use async IPC for disk ops.\n");
|
||||
assert!(farm.join(".claude/rules/geminiuser-gemini-md.md").is_file());
|
||||
assert_eq!(legacy_settings.providers["codex"].auto_memory, AutoMemoryMode::Off);
|
||||
|
||||
// 2. Codex delivery
|
||||
let codex = stage(&farm, "codex", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(codex.codex_use_memories, Some(true));
|
||||
assert_eq!(codex.codex_generate_memories, Some(false));
|
||||
assert!(codex.codex_developer_instructions.as_deref().unwrap().contains("Keep PRs focused."));
|
||||
|
||||
// 3. Copilot delivery
|
||||
let copilot = stage(&farm, "copilot", &cat.entries, AutoMemoryMode::ReadOnly, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(copilot.copilot_enable_memory, Some(true));
|
||||
assert!(copilot.copilot_exclude_store_memory);
|
||||
let copilot_message = copilot.copilot_system_message.as_deref().unwrap();
|
||||
assert!(copilot_message.contains("Keep PRs focused."));
|
||||
// Copilot reads `.github/instructions` natively: not repeated in the system message.
|
||||
assert!(!copilot_message.contains("Use async IPC"));
|
||||
|
||||
// 4. Hermes delivery updates config.yaml
|
||||
let _ = stage(&farm, "hermes", &cat.entries, AutoMemoryMode::Off, &ws, Some(&home)).unwrap();
|
||||
assert_eq!(read_hermes_config_memory_mode(&home.join(".hermes")), Some(AutoMemoryMode::Off));
|
||||
let legacy_overrides: AgentMemoryOverrides = serde_json::from_str(
|
||||
r#"{
|
||||
"autoMemory": "off",
|
||||
"entries": { "workspace::AGENTS.md": "off" }
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(legacy_overrides.auto_memory, Some(AutoMemoryMode::Off));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -71,6 +71,7 @@ pub enum InterruptionReason {
|
||||
BackendStop,
|
||||
UnexpectedExit,
|
||||
NetworkTimeout,
|
||||
CursorCapacity,
|
||||
}
|
||||
|
||||
impl From<AgentShutdownReason> for InterruptionReason {
|
||||
@@ -203,6 +204,10 @@ pub struct AgentTask {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
|
||||
/// Ephemeral next-prompt suggestions from ACP `prompt_suggestions_update`.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
#[specta(optional)]
|
||||
pub prompt_suggestions: Box<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -431,6 +436,9 @@ pub struct AgentImage {
|
||||
/// Base64, without a `data:` prefix.
|
||||
pub data: String,
|
||||
pub name: Option<String>,
|
||||
/// The `[Image #n]` label in the prompt text for an inline attachment.
|
||||
#[specta(optional)]
|
||||
pub inline_number: Option<u32>,
|
||||
}
|
||||
|
||||
impl AgentImage {
|
||||
@@ -638,6 +646,9 @@ pub enum AgentEntry {
|
||||
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
|
||||
#[serde(default)]
|
||||
recovery: Option<InterruptionReason>,
|
||||
/// One-based automatic retry number for this continuation.
|
||||
#[serde(default)]
|
||||
retry_attempt: Option<u32>,
|
||||
},
|
||||
Agent {
|
||||
text: String,
|
||||
@@ -753,12 +764,21 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// Command the project host can run to install this missing built-in CLI.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cli_install_command: Option<String>,
|
||||
/// 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,
|
||||
/// The built-in agent this one is an instance of.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base: Option<String>,
|
||||
/// A built-in agent, of which another instance can be added.
|
||||
#[serde(default)]
|
||||
pub can_duplicate: bool,
|
||||
/// Environment variables it starts with (from its agent file).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
|
||||
@@ -854,6 +874,10 @@ pub struct NewAgentTask {
|
||||
pub isolation: Isolation,
|
||||
/// Branch to start the worktree from; the current branch when `None`.
|
||||
pub base: Option<String>,
|
||||
/// Reuse an existing managed worktree directory instead of creating a new one (`Isolation::Worktree` only).
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub worktree_path: Option<IpcPath>,
|
||||
/// Per-session MCP server enable/disable overrides (`server_name` -> `enabled`).
|
||||
#[serde(default)]
|
||||
pub mcp_overrides: BTreeMap<String, bool>,
|
||||
@@ -1048,6 +1072,14 @@ pub struct McpServer {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
/// Canonical MCP registry server identifier when installed from an MCP registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL when installed from an MCP registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating or updating a user or workspace MCP server.
|
||||
@@ -1074,6 +1106,14 @@ pub struct McpServerInput {
|
||||
/// Agent provider ids this server is enabled for; empty means enabled for all agents.
|
||||
#[serde(default)]
|
||||
pub agents: Vec<String>,
|
||||
/// Canonical MCP registry server identifier when installed from an MCP registry.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL when installed from an MCP registry.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
@@ -1081,8 +1121,8 @@ fn default_true() -> bool {
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
|
||||
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
|
||||
AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings, AgentProviderMemoryPolicy, AgentSkillMode,
|
||||
AgentSkillPolicy, AutoMemoryMode,
|
||||
};
|
||||
|
||||
/// Kind of discovered agent memory entry.
|
||||
@@ -1148,7 +1188,7 @@ impl AgentMemorySource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which layer decided an [`AgentMemoryState::mode`] or [`AutoMemoryMode`].
|
||||
/// Which layer decided a provider's effective [`AutoMemoryMode`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryOrigin {
|
||||
@@ -1157,8 +1197,8 @@ pub enum AgentMemoryOrigin {
|
||||
Session,
|
||||
Workspace,
|
||||
User,
|
||||
/// Locked `Off` because the workspace is untrusted.
|
||||
Trust,
|
||||
/// Configured directly in the agent's own native config file (e.g. `~/.hermes/config.yaml`).
|
||||
Native,
|
||||
}
|
||||
|
||||
/// One discovered instruction file, rule file, or learned auto-memory note.
|
||||
@@ -1205,18 +1245,6 @@ pub struct AgentMemoryEntry {
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryState {
|
||||
pub entry: AgentMemoryEntry,
|
||||
pub mode: AgentMemoryMode,
|
||||
/// Optional provider filter from `[agents.memory.entries.<id>]`; empty means all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
}
|
||||
|
||||
/// Live auto-memory status and capability summary for one agent family.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -1225,41 +1253,43 @@ pub struct AgentAutoMemoryStatus {
|
||||
pub label: String,
|
||||
pub mode: AutoMemoryMode,
|
||||
pub origin: AgentMemoryOrigin,
|
||||
/// Auto-memory modes this provider enforces (empty when the agent manages auto-memory itself).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub supported_modes: Vec<AutoMemoryMode>,
|
||||
/// True when changing the mode edits the agent's own global config (e.g. `~/.hermes/config.yaml`)
|
||||
/// rather than a project or per-session override.
|
||||
#[serde(default)]
|
||||
pub native_config_only: bool,
|
||||
pub note_count: u32,
|
||||
pub rollout_count: u32,
|
||||
pub approx_tokens: u32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub storage_path: Option<IpcPath>,
|
||||
pub supports_auto_control: bool,
|
||||
pub supports_file_exclusion: bool,
|
||||
pub supports_reset: bool,
|
||||
}
|
||||
|
||||
/// Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`.
|
||||
/// Full catalog returned to Settings › Agents › Rules & Memory and the Composer `MemoryPicker`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMemoryCatalog {
|
||||
pub entries: Vec<AgentMemoryState>,
|
||||
pub entries: Vec<AgentMemoryEntry>,
|
||||
pub providers: Vec<AgentAutoMemoryStatus>,
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
pub auto_memory_origin: AgentMemoryOrigin,
|
||||
pub workspace_trusted: bool,
|
||||
}
|
||||
|
||||
/// Per-session memory overrides stored on an [`AgentTask`].
|
||||
/// Per-session auto-memory override stored on an [`AgentTask`] or automation.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemoryOverrides {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub auto_memory: Option<AutoMemoryMode>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub entries: BTreeMap<String, AgentMemoryMode>,
|
||||
}
|
||||
|
||||
impl AgentMemoryOverrides {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.auto_memory.is_none() && self.entries.is_empty()
|
||||
self.auto_memory.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1663,6 +1693,12 @@ pub struct AgentMarketplaceCandidate {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_dark_url: Option<String>,
|
||||
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
|
||||
pub source_spec: String,
|
||||
pub subpath: String,
|
||||
@@ -1751,6 +1787,12 @@ pub struct AgentPluginPreview {
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_dark_url: Option<String>,
|
||||
pub formats: Vec<AgentPluginFormat>,
|
||||
pub capabilities: AgentPluginCapabilities,
|
||||
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
|
||||
@@ -1838,13 +1880,16 @@ pub struct McpProbeResult {
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating a custom ACP agent (always the ACP driver); the id
|
||||
/// becomes the `<config>/agents/<id>.toml` file name.
|
||||
/// Payload for creating a custom ACP agent, or an instance of built-in `base` (which
|
||||
/// launches as its base does when `command` is empty); the id becomes the
|
||||
/// `<config>/agents/<id>.toml` file name.
|
||||
#[derive(Clone, Debug, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct CustomAgentInput {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub base: Option<String>,
|
||||
pub command: String,
|
||||
#[serde(default)]
|
||||
pub args: Vec<String>,
|
||||
|
||||
@@ -209,6 +209,17 @@ pub(super) fn cut(chain: &[&Value], turns: usize) -> Result<Option<String>, Stri
|
||||
Ok(parent(first_dropped).map(str::to_owned))
|
||||
}
|
||||
|
||||
/// Where to fork `chain` to keep only its first `turns` turns: the entry the last kept
|
||||
/// turn ends with, as [`cut`] reports it. `None` when the chain has fewer turns.
|
||||
pub(super) fn keep(chain: &[&Value], turns: usize) -> Option<Option<String>> {
|
||||
let total = chain.iter().filter(|e| is_turn_start(e)).count();
|
||||
if turns > total {
|
||||
return None;
|
||||
}
|
||||
// A turn that runs now is in the chain up to where it got: it is dropped like any other.
|
||||
cut(chain, total - turns).ok()
|
||||
}
|
||||
|
||||
/// The newest title Claude Code gave the session.
|
||||
pub(crate) fn title(entries: &[Value]) -> Option<String> {
|
||||
entries
|
||||
|
||||
@@ -58,7 +58,7 @@ pub(crate) fn connect(
|
||||
on_stderr: Box<dyn Fn(String) + Send + Sync>,
|
||||
) -> std::io::Result<Peer> {
|
||||
let config = Config {
|
||||
program: super::newest_install(&spec.command),
|
||||
program: super::newest_install(spec.executable()),
|
||||
args: spec.args.clone(),
|
||||
env: spec.env.clone(),
|
||||
config_dir: cli::config_dir(&spec.env),
|
||||
@@ -174,13 +174,9 @@ struct Session {
|
||||
mcp_off: Vec<String>,
|
||||
/// The staged skills folder passed as `--add-dir` (its `.claude/skills` holds the copies).
|
||||
skills_add_dir: Option<PathBuf>,
|
||||
/// The staged memory rules folder passed as `--add-dir` (its `.claude/rules` holds shared rules).
|
||||
memory_add_dir: Option<PathBuf>,
|
||||
/// Load `.claude/rules` from `--add-dir` folders (`CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`).
|
||||
additional_dirs_claude_md: bool,
|
||||
/// The workspace's other roots, each passed as `--add-dir`.
|
||||
additional_dirs: Vec<String>,
|
||||
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`).
|
||||
/// Combined `--settings` JSON (`skillOverrides`, `autoMemoryEnabled`).
|
||||
cli_settings: Option<String>,
|
||||
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
|
||||
ephemeral: bool,
|
||||
@@ -347,6 +343,24 @@ impl Shim {
|
||||
}
|
||||
|
||||
/// The conversation a session started with `start` begins with.
|
||||
/// `start` (a fork's) cut after the source's first `turns` turns; `None` when the
|
||||
/// transcript can't be read or has fewer turns.
|
||||
fn pin_fork(&self, cwd: &Path, start: &Start, id: &str, turns: usize) -> Option<Start> {
|
||||
let chain = match self.base_chain(cwd, start) {
|
||||
Ok(chain) => chain,
|
||||
Err(e) => {
|
||||
tracing::debug!("Claude Code fork {id}: can't read the source transcript: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let refs: Vec<&Value> = chain.iter().collect();
|
||||
Some(match (start, history::keep(&refs, turns)?) {
|
||||
(_, None) => Start::New { id: id.to_owned() },
|
||||
(Start::Fork { from, .. }, Some(at)) => Start::Fork { from: from.clone(), id: id.to_owned(), at: Some(at) },
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn base_chain(&self, cwd: &Path, start: &Start) -> Result<Vec<Value>, String> {
|
||||
let (id, at) = match start {
|
||||
Start::New { .. } => return Ok(Vec::new()),
|
||||
@@ -382,11 +396,6 @@ impl Shim {
|
||||
mcp_config,
|
||||
mcp_off,
|
||||
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
memory_add_dir: memory.and_then(|m| m.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
|
||||
additional_dirs_claude_md: memory
|
||||
.and_then(|m| m.get("claudeAdditionalDirsClaudeMd"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
additional_dirs: additional_dirs(params),
|
||||
cli_settings,
|
||||
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
|
||||
@@ -509,11 +518,28 @@ impl Shim {
|
||||
// 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()),
|
||||
};
|
||||
// Pinned now: the source may go on (or be running a turn) before the fork starts.
|
||||
let wanted = params.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64);
|
||||
let mut kept = None;
|
||||
let start = match wanted {
|
||||
Some(turns) => match self.pin_fork(&cwd, &start, &id, turns as usize) {
|
||||
Some(pinned) => {
|
||||
kept = Some(turns);
|
||||
pinned
|
||||
}
|
||||
None => start,
|
||||
},
|
||||
None => start,
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
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 }))
|
||||
let mut reply = json!({ "sessionId": id, "configOptions": options });
|
||||
if let Some(turns) = kept {
|
||||
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
"session/set_config_option" | "session/set_mode" => {
|
||||
let session = self.session(¶ms)?;
|
||||
@@ -739,11 +765,6 @@ impl Session {
|
||||
if let Some(dir) = &self.skills_add_dir {
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
if let Some(dir) = &self.memory_add_dir
|
||||
&& self.skills_add_dir.as_ref() != Some(dir)
|
||||
{
|
||||
args.extend(["--add-dir".to_owned(), dir.to_string_lossy().into_owned()]);
|
||||
}
|
||||
for dir in &self.additional_dirs {
|
||||
args.extend(["--add-dir".to_owned(), dir.clone()]);
|
||||
}
|
||||
@@ -754,12 +775,7 @@ impl Session {
|
||||
args.push("--no-session-persistence".to_owned());
|
||||
}
|
||||
args.extend(start.args());
|
||||
let mut env = shim.config.env.clone();
|
||||
if self.additional_dirs_claude_md
|
||||
&& !env.iter().any(|(k, _)| k == "CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD")
|
||||
{
|
||||
env.push(("CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD".to_owned(), "1".to_owned()));
|
||||
}
|
||||
let env = shim.config.env.clone();
|
||||
let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env };
|
||||
let io = shim
|
||||
.cli
|
||||
@@ -947,7 +963,7 @@ impl Session {
|
||||
fn steer(&self, prompt: Value) -> Result<(), String> {
|
||||
let uuid = new_uuid(true);
|
||||
let mut message = user_message(&prompt, &uuid, true);
|
||||
message["priority"] = json!("now");
|
||||
message["priority"] = json!("next");
|
||||
let mut st = self.st.lock();
|
||||
let proc = st.proc.clone().ok_or("Claude Code is not running")?;
|
||||
let turn = st.turn.as_mut().filter(|t| !t.cancelled).ok_or("no turn is running")?;
|
||||
@@ -1622,8 +1638,8 @@ fn write_mcp_config(json: &str) -> std::io::Result<tempfile::TempPath> {
|
||||
/// The servers switched off for the session (`_meta.openidea.mcpServersOff`) as Claude Code
|
||||
/// permission rules that deny all of a server's tools (`mcp__<server>`), so a server of
|
||||
/// Claude Code's own configuration stays off too.
|
||||
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with memory
|
||||
/// settings (`autoMemoryEnabled`, `claudeMdExcludes`, `instructionFiles`) into one `--settings` JSON.
|
||||
/// Combines `skillOverrides` from `_meta.openidea.skills.claudeSettings` with
|
||||
/// `autoMemoryEnabled` from `_meta.openidea.memory` into one `--settings` JSON.
|
||||
fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<String> {
|
||||
let mut root = skills
|
||||
.and_then(|s| s.get("claudeSettings"))
|
||||
@@ -1631,27 +1647,8 @@ fn build_cli_settings(skills: Option<&Value>, memory: Option<&Value>) -> Option<
|
||||
.and_then(|raw| serde_json::from_str::<serde_json::Map<String, Value>>(raw).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
if let Some(mem) = memory {
|
||||
if let Some(auto) = mem.get("claudeAutoMemory").and_then(Value::as_bool) {
|
||||
root.insert("autoMemoryEnabled".into(), json!(auto));
|
||||
}
|
||||
if let Some(excludes) = mem.get("claudeMdExcludes").and_then(Value::as_array) {
|
||||
let clean: Vec<Value> =
|
||||
excludes.iter().filter_map(Value::as_str).filter(|s| !s.is_empty()).map(|s| json!(s)).collect();
|
||||
if !clean.is_empty() {
|
||||
root.insert("claudeMdExcludes".into(), Value::Array(clean));
|
||||
}
|
||||
}
|
||||
if let Some(inst) = mem.get("claudeInstructionFiles").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
root.insert(
|
||||
"pluginConfigs".into(),
|
||||
json!({
|
||||
"cc-plugin-agents-md@builtin": {
|
||||
"options": { "instructionFiles": inst }
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
if let Some(auto) = memory.and_then(|m| m.get("claudeAutoMemory")).and_then(Value::as_bool) {
|
||||
root.insert("autoMemoryEnabled".into(), json!(auto));
|
||||
}
|
||||
|
||||
(!root.is_empty()).then(|| serde_json::to_string(&Value::Object(root)).expect("settings serialize"))
|
||||
|
||||
@@ -212,6 +212,30 @@ async fn steer(h: &Harness) -> (Outcome, String) {
|
||||
(vec![outcome("prompt", r), outcome("steer", steered)], s)
|
||||
}
|
||||
|
||||
/// Stops the turn while a steered message waits for the running tool.
|
||||
async fn steer_stop(h: &Harness) -> (Outcome, String) {
|
||||
let s = h.new_session().await;
|
||||
let prompt = h.prompt(&s, "Run the Bash command `sleep 5 && echo done`, then tell me its output in one line.");
|
||||
let steer_and_stop = async {
|
||||
tokio::time::sleep(Duration::from_millis(3000)).await;
|
||||
let steered = h
|
||||
.request(
|
||||
"_openidea/steer",
|
||||
json!({ "sessionId": s, "prompt": [{ "type": "text", "text": "Also end your answer with the word BANANA." }] }),
|
||||
)
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
h.client.notify("session/cancel", json!({ "sessionId": s })).unwrap();
|
||||
steered
|
||||
};
|
||||
let (r, steered) = tokio::join!(prompt, steer_and_stop);
|
||||
if h.recording {
|
||||
// Long enough for the CLI to run the steered message, had it kept it.
|
||||
tokio::time::sleep(Duration::from_secs(8)).await;
|
||||
}
|
||||
(vec![outcome("prompt", r), outcome("steer", steered)], s)
|
||||
}
|
||||
|
||||
async fn subagent(h: &Harness) -> (Outcome, String) {
|
||||
let s = h.new_session().await;
|
||||
h.answer(&[Some("allow"), Some("allow")]);
|
||||
@@ -253,6 +277,7 @@ const SCENARIOS: &[(&str, ScenarioFn)] = &[
|
||||
("tool_approval", |h| Box::pin(tool_approval(h))),
|
||||
("interrupt", |h| Box::pin(interrupt(h))),
|
||||
("steer", |h| Box::pin(steer(h))),
|
||||
("steer_stop", |h| Box::pin(steer_stop(h))),
|
||||
("subagent", |h| Box::pin(subagent(h))),
|
||||
("resume", |h| Box::pin(resume(h))),
|
||||
];
|
||||
@@ -620,10 +645,20 @@ async fn replay_steer() {
|
||||
assert_eq!(r.stop("prompt"), "end_turn");
|
||||
assert!(r.h.text(&r.session, "agent_message_chunk").contains("BANANA"));
|
||||
let steer = r.sent(0).into_iter().filter(|m| m["type"] == "user").nth(1).unwrap();
|
||||
assert_eq!(steer["priority"], "now");
|
||||
assert_eq!(steer["priority"], "next");
|
||||
assert!(steer["uuid"].as_str().unwrap().ends_with(history::STEER_MARK));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_steer_stop() {
|
||||
let r = replay("steer_stop").await;
|
||||
assert!(r.result("steer").is_ok(), "{:?}", r.result("steer"));
|
||||
assert_eq!(r.stop("prompt"), "cancelled");
|
||||
assert!(!r.h.text(&r.session, "agent_message_chunk").contains("BANANA"));
|
||||
let interrupt = r.sent(0).into_iter().find(|m| m["request"]["subtype"] == "interrupt").unwrap();
|
||||
assert_eq!(interrupt["request"]["cancel_queued"], true);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_subagent() {
|
||||
let r = replay("subagent").await;
|
||||
@@ -695,6 +730,73 @@ async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() {
|
||||
assert_eq!(saved, json!({ "fork": source, "id": target, "at": null }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_pins_the_cut_to_the_kept_turns() {
|
||||
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";
|
||||
// Two finished turns and a third still running.
|
||||
let dir = config.path().join("projects").join(history::escape(&h.cwd));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut parent = Value::Null;
|
||||
let mut lines = String::new();
|
||||
for (uuid, kind, text) in [
|
||||
("u1", "user", "one"),
|
||||
("a1", "assistant", "1"),
|
||||
("u2", "user", "two"),
|
||||
("a2", "assistant", "2"),
|
||||
("u3", "user", "three"),
|
||||
("a3", "assistant", "partial"),
|
||||
] {
|
||||
let entry = json!({"type": kind, "uuid": uuid, "parentUuid": parent,
|
||||
"message": {"role": kind, "content": [{"type": "text", "text": text}]}});
|
||||
lines += &format!("{entry}\n");
|
||||
parent = json!(uuid);
|
||||
}
|
||||
std::fs::write(dir.join(format!("{source}.jsonl")), lines).unwrap();
|
||||
|
||||
let fork = |target: &'static str, turns: u64| {
|
||||
h.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": source,
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": target, "forkTurns": turns } }
|
||||
}),
|
||||
)
|
||||
};
|
||||
let saved = |target: &str| -> Value {
|
||||
serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap()
|
||||
};
|
||||
|
||||
let target = "22222222-2222-4222-8222-222222222222";
|
||||
let reply = fork(target, 2).await.unwrap();
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns"), Some(&json!(2)));
|
||||
assert_eq!(saved(target), json!({ "fork": source, "id": target, "at": "a2" }));
|
||||
|
||||
// More turns than the transcript holds: left to the host to settle.
|
||||
let target = "33333333-3333-4333-8333-333333333333";
|
||||
let reply = fork(target, 4).await.unwrap();
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns"), None);
|
||||
assert_eq!(saved(target), 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;
|
||||
@@ -799,7 +901,14 @@ fn scrub(frame: &mut Value) -> bool {
|
||||
json!([{ "name": "review", "description": "Review a pull request", "argumentHint": "" },
|
||||
{ "name": "init", "description": "Write a CLAUDE.md", "argumentHint": "" }]),
|
||||
);
|
||||
for k in ["agents", "account", "available_output_styles", "user_output_styles_dir", "output_style"] {
|
||||
for k in [
|
||||
"agents",
|
||||
"account",
|
||||
"stored_login_organization_uuid",
|
||||
"available_output_styles",
|
||||
"user_output_styles_dir",
|
||||
"output_style",
|
||||
] {
|
||||
o.remove(k);
|
||||
}
|
||||
}
|
||||
@@ -1444,7 +1553,7 @@ async fn an_ephemeral_session_is_not_saved() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env() {
|
||||
async fn session_merges_skills_and_auto_memory_into_claude_settings() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
@@ -1460,45 +1569,8 @@ async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env()
|
||||
"claudeSettings": "{\"skillOverrides\":{\"tdd\":\"user-invocable-only\"}}"
|
||||
},
|
||||
"memory": {
|
||||
"autoMemory": "readOnly",
|
||||
"claudeAutoMemory": false,
|
||||
"claudeMdExcludes": ["/repo/CLAUDE.local.md"],
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md",
|
||||
"claudeAddDir": "/tmp/farm-memory",
|
||||
"claudeAdditionalDirsClaudeMd": true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-memory"]), "{args:?}");
|
||||
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
|
||||
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
|
||||
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
|
||||
assert_eq!(parsed["autoMemoryEnabled"], false);
|
||||
assert_eq!(parsed["claudeMdExcludes"], json!(["/repo/CLAUDE.local.md"]));
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md"
|
||||
"autoMemory": "off",
|
||||
"claudeAutoMemory": false
|
||||
},
|
||||
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
|
||||
}
|
||||
@@ -1506,12 +1578,12 @@ async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_inje
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(args.windows(2).any(|w| w == ["--add-dir", "/tmp/farm-skills"]), "{args:?}");
|
||||
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
|
||||
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
|
||||
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
assert!(parsed["pluginConfigs"]["azure"].is_null());
|
||||
assert_eq!(parsed["skillOverrides"]["tdd"], "user-invocable-only");
|
||||
assert_eq!(parsed["autoMemoryEnabled"], false);
|
||||
assert!(parsed.get("claudeMdExcludes").is_none());
|
||||
assert!(parsed.get("pluginConfigs").is_none());
|
||||
}
|
||||
@@ -34,6 +34,14 @@ const OUTPUT_EVERY: Duration = Duration::from_millis(200);
|
||||
const EARLY_CANCEL: Duration = Duration::from_secs(1);
|
||||
/// How long the client's connection outlives codex.
|
||||
const EXIT_GRACE: Duration = Duration::from_millis(100);
|
||||
/// How often running background terminals are listed again: codex announces neither a
|
||||
/// terminal that outlives its turn nor its end.
|
||||
#[cfg(not(test))]
|
||||
const TERMINAL_POLL: Duration = Duration::from_secs(3);
|
||||
#[cfg(test)]
|
||||
const TERMINAL_POLL: Duration = Duration::from_millis(20);
|
||||
/// How long closing the connection waits for codex to stop the background terminals.
|
||||
const TERMINAL_CLEAN: Duration = Duration::from_secs(3);
|
||||
/// What a thread's name is asked for with, after its first turn.
|
||||
const NAME_PROMPT: &str = "Name this conversation for a list of tasks: a short title of at most six words, in the \
|
||||
language the user writes in. Reply with the title only, without quotes or a closing period.";
|
||||
@@ -66,7 +74,7 @@ pub(crate) fn connect(
|
||||
on_stderr: Box<dyn Fn(String) + Send + Sync>,
|
||||
) -> std::io::Result<Peer> {
|
||||
attach(client, |events| {
|
||||
let command = super::newest_install(&spec.command);
|
||||
let command = super::newest_install(spec.executable());
|
||||
Peer::spawn_framed(&command, &spec.args, cwd, &spec.env, events, on_stderr, Framing::Lines)
|
||||
})
|
||||
}
|
||||
@@ -187,6 +195,10 @@ fn attach(
|
||||
}
|
||||
tokio::spawn(async move {
|
||||
to_client.closed().await;
|
||||
// Background terminals run in process groups of their own: stopping codex alone
|
||||
// would leave them running with nothing left to report or stop them.
|
||||
let threads: Vec<String> = shim.state.lock().threads.keys().cloned().collect();
|
||||
shim.clean_terminals(&threads).await;
|
||||
codex.kill();
|
||||
});
|
||||
Ok(ours)
|
||||
@@ -248,6 +260,14 @@ struct Thread {
|
||||
token_usage: Option<Value>,
|
||||
/// The thread has a name.
|
||||
named: bool,
|
||||
/// Running background terminals of this session and its subagents, by task id:
|
||||
/// `(thread, processId)`.
|
||||
terminals: HashMap<String, (String, String)>,
|
||||
/// The background tasks reported last.
|
||||
shown_tasks: Vec<Value>,
|
||||
/// The background terminals are being followed; `relist` asks for another listing.
|
||||
watching: bool,
|
||||
relist: bool,
|
||||
/// A name is being asked for.
|
||||
naming: bool,
|
||||
}
|
||||
@@ -365,18 +385,25 @@ fn apply_thread_config(params: &Value, request: &mut Value) {
|
||||
if let Some(mem) = params.pointer("/_meta/openidea/memory")
|
||||
&& let Some(map) = config.as_object_mut()
|
||||
{
|
||||
let use_m = mem.get("codexUseMemories").and_then(Value::as_bool);
|
||||
let gen_m = mem.get("codexGenerateMemories").and_then(Value::as_bool);
|
||||
let mut mem_cfg = serde_json::Map::new();
|
||||
if let Some(use_m) = mem.get("codexUseMemories").and_then(Value::as_bool) {
|
||||
mem_cfg.insert("use_memories".into(), json!(use_m));
|
||||
if let Some(v) = use_m {
|
||||
mem_cfg.insert("use_memories".into(), json!(v));
|
||||
}
|
||||
if let Some(gen_m) = mem.get("codexGenerateMemories").and_then(Value::as_bool) {
|
||||
mem_cfg.insert("generate_memories".into(), json!(gen_m));
|
||||
if let Some(v) = gen_m {
|
||||
mem_cfg.insert("generate_memories".into(), json!(v));
|
||||
}
|
||||
if !mem_cfg.is_empty() {
|
||||
map.insert("memories".into(), Value::Object(mem_cfg));
|
||||
}
|
||||
if let Some(dev) = mem.get("codexDeveloperInstructions").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
map.insert("developer_instructions".into(), json!(dev));
|
||||
// Codex's `memories` feature flag defaults to `false`; turn it on whenever the user
|
||||
// explicitly asks to read or generate memories.
|
||||
if use_m == Some(true) || gen_m == Some(true) {
|
||||
let features = map.entry("features".to_owned()).or_insert_with(|| Value::Object(serde_json::Map::new()));
|
||||
if let Some(f) = features.as_object_mut() {
|
||||
f.insert("memories".into(), json!(true));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !config.as_object().is_some_and(|m| m.is_empty()) {
|
||||
@@ -416,6 +443,7 @@ impl CodexShim {
|
||||
"session/prompt" => self.prompt(¶ms).await,
|
||||
"_openidea/steer" => self.steer(¶ms).await,
|
||||
"_openidea/rollback" => self.rollback(¶ms).await,
|
||||
"_openidea/stop_task" => self.stop_task(¶ms).await,
|
||||
"session/close" => self.close(¶ms).await,
|
||||
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
|
||||
}
|
||||
@@ -439,7 +467,7 @@ impl CodexShim {
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": false, "sse": false, "stdio": true },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true } },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
|
||||
},
|
||||
"agentInfo": { "name": "codex", "title": "Codex", "version": version },
|
||||
"authMethods": [],
|
||||
@@ -568,9 +596,26 @@ impl CodexShim {
|
||||
}
|
||||
let result = self.call("thread/fork", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, settings);
|
||||
// Cut by what the fork holds: a turn the source runs now may or may not be in it.
|
||||
let wanted = params.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64);
|
||||
let held = result.pointer("/thread/turns").and_then(Value::as_array).map(|t| t.len() as u64);
|
||||
let mut kept = None;
|
||||
if let (Some(turns), Some(held)) = (wanted, held)
|
||||
&& turns <= held
|
||||
{
|
||||
let dropped = held - turns;
|
||||
if dropped > 0 {
|
||||
self.rollback(&json!({ "sessionId": id, "turns": dropped })).await?;
|
||||
}
|
||||
kept = Some(turns);
|
||||
}
|
||||
self.apply_skill_roots(&id, params).await;
|
||||
self.publish_skills(&id).await;
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
let mut reply = json!({ "sessionId": id, "configOptions": options });
|
||||
if let Some(turns) = kept {
|
||||
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
async fn set_config(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
@@ -915,6 +960,16 @@ impl CodexShim {
|
||||
/// Stops following the session's thread (codex unloads it once nothing follows it).
|
||||
async fn close(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let threads: Vec<String> = {
|
||||
let state = self.state.lock();
|
||||
state
|
||||
.threads
|
||||
.iter()
|
||||
.filter(|(id, t)| *id == session || t.parent.as_deref() == Some(session))
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect()
|
||||
};
|
||||
self.clean_terminals(&threads).await;
|
||||
let known = self.state.lock().threads.remove(session).is_some();
|
||||
if known && let Err(e) = self.call("thread/unsubscribe", json!({ "threadId": session })).await {
|
||||
tracing::debug!("codex: unsubscribing from {session}: {}", e.message);
|
||||
@@ -922,6 +977,129 @@ impl CodexShim {
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
/// Follows the background terminals of `session` and its subagents until none runs:
|
||||
/// codex keeps them running after the turn that started them.
|
||||
fn watch_terminals(self: &Arc<Self>, session: &str) {
|
||||
{
|
||||
let mut state = self.state.lock();
|
||||
if state.gone {
|
||||
return;
|
||||
}
|
||||
let Some(t) = state.threads.get_mut(session) else { return };
|
||||
if t.watching {
|
||||
t.relist = true;
|
||||
return;
|
||||
}
|
||||
t.watching = true;
|
||||
}
|
||||
let (shim, session) = (self.clone(), session.to_owned());
|
||||
self.runtime.spawn(async move {
|
||||
loop {
|
||||
let running = shim.list_terminals(&session).await;
|
||||
let relist = {
|
||||
let mut state = shim.state.lock();
|
||||
let Some(t) = state.threads.get_mut(&session) else { return };
|
||||
let relist = std::mem::take(&mut t.relist);
|
||||
if !relist && !running {
|
||||
t.watching = false;
|
||||
return;
|
||||
}
|
||||
relist
|
||||
};
|
||||
if !relist {
|
||||
tokio::time::sleep(TERMINAL_POLL).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Reports the running background terminals of `session` and its subagents as the
|
||||
/// session's background tasks; whether any runs. A codex without the (experimental)
|
||||
/// listing has none to report.
|
||||
async fn list_terminals(&self, session: &str) -> bool {
|
||||
let threads: Vec<String> = {
|
||||
let state = self.state.lock();
|
||||
let children = state.threads.iter().filter(|(_, t)| t.parent.as_deref() == Some(session));
|
||||
std::iter::once(session.to_owned()).chain(children.map(|(id, _)| id.clone())).collect()
|
||||
};
|
||||
let mut terminals = HashMap::new();
|
||||
let mut tasks = Vec::new();
|
||||
for thread in &threads {
|
||||
let listed = match self.terminals_of(thread).await {
|
||||
Ok(listed) => listed,
|
||||
Err(e) => {
|
||||
tracing::debug!("codex: listing the background terminals of {thread}: {}", e.message);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for (process, description) in listed {
|
||||
let id = if thread == session { process.clone() } else { format!("{thread}:{process}") };
|
||||
tasks.push(json!({ "task_id": id, "task_type": "local_bash", "description": description }));
|
||||
terminals.insert(id, (thread.clone(), process));
|
||||
}
|
||||
}
|
||||
let running = !tasks.is_empty();
|
||||
let changed = {
|
||||
let mut state = self.state.lock();
|
||||
let Some(t) = state.threads.get_mut(session) else { return false };
|
||||
t.terminals = terminals;
|
||||
let changed = t.shown_tasks != tasks;
|
||||
if changed {
|
||||
t.shown_tasks = tasks.clone();
|
||||
}
|
||||
changed
|
||||
};
|
||||
if changed {
|
||||
self.emit(session, json!({ "sessionUpdate": crate::BACKGROUND_TASKS_UPDATE, "tasks": tasks }));
|
||||
}
|
||||
running
|
||||
}
|
||||
|
||||
/// The running background terminals of `thread`, as `(processId, description)`.
|
||||
async fn terminals_of(&self, thread: &str) -> Result<Vec<(String, String)>, ResponseError> {
|
||||
let mut all = Vec::new();
|
||||
let mut cursor = Value::Null;
|
||||
let mut seen = HashSet::new();
|
||||
loop {
|
||||
let page =
|
||||
self.call("thread/backgroundTerminals/list", json!({ "threadId": thread, "cursor": cursor })).await?;
|
||||
all.extend(translate::background_terminals(&page));
|
||||
match page.get("nextCursor").and_then(Value::as_str) {
|
||||
Some(next) if !next.is_empty() && seen.insert(next.to_owned()) => cursor = json!(next),
|
||||
_ => return Ok(all),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `_openidea/stop_task`: stops one background terminal.
|
||||
async fn stop_task(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let task = str_param(params, "taskId")?;
|
||||
let known = self.state.lock().threads.get(session).and_then(|t| t.terminals.get(task).cloned());
|
||||
let (thread, process) = known.unwrap_or_else(|| (session.to_owned(), task.to_owned()));
|
||||
self.call("thread/backgroundTerminals/terminate", json!({ "threadId": thread, "processId": process })).await?;
|
||||
self.list_terminals(session).await;
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
/// Stops the background terminals of `threads`; a codex without the (experimental)
|
||||
/// method has none.
|
||||
async fn clean_terminals(&self, threads: &[String]) {
|
||||
if threads.is_empty() || self.state.lock().gone {
|
||||
return;
|
||||
}
|
||||
let clean = async {
|
||||
for thread in threads {
|
||||
if let Err(e) = self.call("thread/backgroundTerminals/clean", json!({ "threadId": thread })).await {
|
||||
tracing::debug!("codex: stopping the background terminals of {thread}: {}", e.message);
|
||||
}
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(TERMINAL_CLEAN, clean).await.is_err() {
|
||||
tracing::warn!("codex: stopping the background terminals timed out");
|
||||
}
|
||||
}
|
||||
|
||||
/// `session/cancel`: interrupts the session's turn, or the one about to start.
|
||||
fn cancel(&self, session: &str) {
|
||||
let mut state = self.state.lock();
|
||||
@@ -1261,6 +1439,19 @@ impl CodexShim {
|
||||
t.turn = None;
|
||||
}
|
||||
t.completed = Some(id.to_owned());
|
||||
// A command still open when its turn completed goes on in the background (a
|
||||
// background terminal): its call returned, so it didn't fail with the turn. Its
|
||||
// own completion reports how it ended. Sent before the prompt's answer settles the
|
||||
// turn.
|
||||
if completed {
|
||||
let commands = t.items.values().filter(|i| i["type"] == "commandExecution");
|
||||
for id in commands.filter_map(|i| i["id"].as_str()) {
|
||||
self.emit(
|
||||
thread,
|
||||
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed" }),
|
||||
);
|
||||
}
|
||||
}
|
||||
t.items.clear();
|
||||
t.last_chunk = None;
|
||||
let error = t.error.take();
|
||||
@@ -1275,6 +1466,7 @@ impl CodexShim {
|
||||
t.naming |= name;
|
||||
(t.parent.clone(), (answer, error), name)
|
||||
};
|
||||
self.watch_terminals(parent.as_deref().unwrap_or(thread));
|
||||
if name {
|
||||
let (shim, thread, turn) = (self.clone(), thread.to_owned(), id.to_owned());
|
||||
self.runtime.spawn(async move { shim.name_thread(&thread, &turn).await });
|
||||
|
||||
@@ -66,6 +66,7 @@ fn manager(dir: &Path, runtime: Arc<Runtime>) -> AgentManager {
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: Some(agents),
|
||||
home_dir: Some(dir.into()),
|
||||
env_secrets: None,
|
||||
|
||||
@@ -125,11 +125,13 @@ for line in sys.stdin:
|
||||
name: "Codex".into(),
|
||||
driver: crate::provider::Driver::Codex,
|
||||
command: script.to_string_lossy().into_owned(),
|
||||
managed_cli: None,
|
||||
args: Vec::new(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: String::new(),
|
||||
source: crate::AgentSource::Builtin,
|
||||
base: None,
|
||||
};
|
||||
let found = discover(spec, tmp.path().to_path_buf()).await.unwrap();
|
||||
let models: Vec<_> = found
|
||||
@@ -1019,10 +1021,12 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
.unwrap()
|
||||
.unwrap_or_else(|| panic!("the shim closed before {frame}"));
|
||||
let actual: Value = serde_json::from_str(&line).unwrap();
|
||||
// Older recordings predate config inspection, skill discovery and thread naming; play an
|
||||
// unsupported server.
|
||||
// Older recordings predate config inspection, skill discovery, thread naming and
|
||||
// background terminals; play an unsupported server.
|
||||
let method = actual["method"].as_str().unwrap_or_default();
|
||||
if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method {
|
||||
let unrecorded = matches!(method, "config/read" | "skills/list" | "thread/sample")
|
||||
|| method.starts_with("thread/backgroundTerminals/");
|
||||
if unrecorded && frame["method"] != method {
|
||||
let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } });
|
||||
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
|
||||
continue;
|
||||
@@ -1162,6 +1166,60 @@ impl Handler for TrustServer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Forks a thread holding two finished turns and one cut off by the fork.
|
||||
#[derive(Default)]
|
||||
struct ForkServer {
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl Handler for ForkServer {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.calls.lock().push((method.to_owned(), params));
|
||||
match method {
|
||||
"initialize" | "thread/rollback" => Ok(json!({})),
|
||||
"model/list" | "skills/list" => Ok(json!({"data": []})),
|
||||
"config/read" => Ok(json!({"layers": []})),
|
||||
"thread/fork" => Ok(json!({"thread": {"id": "copy", "turns": [
|
||||
{"id": "t1", "status": "completed"},
|
||||
{"id": "t2", "status": "completed"},
|
||||
{"id": "t3", "status": "interrupted"},
|
||||
]}})),
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_keeps_the_asked_turns_of_what_the_fork_holds() {
|
||||
for (turns, rolled_back, kept) in [(Some(2), Some(1), Some(2)), (Some(3), None, Some(3)), (Some(4), None, None)] {
|
||||
let server = Arc::new(ForkServer::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(Arc::new(Client::default()), |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 params = json!({"cwd": "/tmp", "sessionId": "source", "mcpServers": [],
|
||||
"_meta": {"openidea": {"forkTurns": turns}}});
|
||||
let reply = request(&acp, "session/fork", params).await.unwrap();
|
||||
assert_eq!(reply["sessionId"], "copy");
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64), kept);
|
||||
let rollbacks: Vec<Value> =
|
||||
server.calls.lock().iter().filter(|(m, _)| m == "thread/rollback").map(|(_, p)| p.clone()).collect();
|
||||
assert_eq!(
|
||||
rollbacks,
|
||||
rolled_back.map(|n| json!({"threadId": "copy", "numTurns": n})).into_iter().collect::<Vec<_>>()
|
||||
);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn project_trust_is_confirmed_before_new_resumed_and_forked_sessions() {
|
||||
for method in ["session/new", "session/load", "session/fork"] {
|
||||
@@ -1243,7 +1301,10 @@ async fn auth_failure_names_auth() {
|
||||
let (results, _client, frames, _) = replay(Scenario::AuthFailure).await;
|
||||
let init = result(&results, "initialize").as_ref().unwrap();
|
||||
assert_eq!(init["agentCapabilities"]["loadSession"], true);
|
||||
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"], json!({"rollback": true, "steer": true}));
|
||||
assert_eq!(
|
||||
init["agentCapabilities"]["_meta"]["openidea"],
|
||||
json!({"rollback": true, "steer": true, "backgroundTasks": true})
|
||||
);
|
||||
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
|
||||
let new = result(&results, "new").as_ref().unwrap();
|
||||
let categories: Vec<&str> =
|
||||
@@ -2166,8 +2227,7 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
"skills": { "codexOff": [["noisy", "/repo/.agents/skills/noisy/SKILL.md"]] },
|
||||
"memory": {
|
||||
"codexUseMemories": true,
|
||||
"codexGenerateMemories": false,
|
||||
"codexDeveloperInstructions": "## Memory (style)\nUse targeted selectors."
|
||||
"codexGenerateMemories": false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2175,8 +2235,27 @@ fn workspace_roots_join_the_thread_roots() {
|
||||
&mut mem_req,
|
||||
);
|
||||
assert_eq!(mem_req["config"]["memories"], json!({ "use_memories": true, "generate_memories": false }));
|
||||
assert_eq!(mem_req["config"]["developer_instructions"], "## Memory (style)\nUse targeted selectors.");
|
||||
assert_eq!(mem_req["config"]["features"]["memories"], true);
|
||||
assert_eq!(mem_req["config"]["skills"]["config"][0]["enabled"], false);
|
||||
|
||||
let mut off_req = json!({});
|
||||
apply_thread_config(
|
||||
&json!({
|
||||
"cwd": "/w/api",
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"codexUseMemories": false,
|
||||
"codexGenerateMemories": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
&mut off_req,
|
||||
);
|
||||
assert_eq!(off_req["config"]["memories"], json!({ "use_memories": false, "generate_memories": false }));
|
||||
assert!(off_req["config"].get("features").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -2215,3 +2294,179 @@ async fn an_ephemeral_session_starts_an_ephemeral_thread() {
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
|
||||
/// A codex whose background terminals listings come from `pages` (an empty list after
|
||||
/// them); `None` answers like a codex without the method.
|
||||
struct TerminalServer {
|
||||
pages: Mutex<VecDeque<Value>>,
|
||||
supported: bool,
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl TerminalServer {
|
||||
fn new(pages: Vec<Value>, supported: bool) -> Arc<Self> {
|
||||
Arc::new(Self { pages: Mutex::new(pages.into()), supported, calls: Mutex::default() })
|
||||
}
|
||||
|
||||
fn calls_of(&self, method: &str) -> Vec<Value> {
|
||||
self.calls.lock().iter().filter(|(m, _)| m == method).map(|(_, p)| p.clone()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler for TerminalServer {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.calls.lock().push((method.to_owned(), params));
|
||||
match method {
|
||||
"initialize" => Ok(json!({})),
|
||||
"model/list" => Ok(json!({"data": []})),
|
||||
"config/read" => Ok(json!({"layers": []})),
|
||||
"thread/start" => Ok(json!({"thread": {"id": "s", "turns": []}, "cwd": "/w"})),
|
||||
"skills/list" => Ok(json!({"data": []})),
|
||||
"thread/unsubscribe" => Ok(json!({})),
|
||||
m if m.starts_with("thread/backgroundTerminals/") && !self.supported => {
|
||||
Err((codes::INVALID_REQUEST, format!("Invalid request: unknown variant `{m}`")))
|
||||
}
|
||||
"thread/backgroundTerminals/list" => {
|
||||
Ok(self.pages.lock().pop_front().unwrap_or_else(|| json!({"data": [], "nextCursor": null})))
|
||||
}
|
||||
"thread/backgroundTerminals/terminate" => Ok(json!({"terminated": true})),
|
||||
"thread/backgroundTerminals/clean" => Ok(json!({})),
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn terminal(process: &str, command: &str) -> Value {
|
||||
json!({"itemId": format!("item-{process}"), "processId": process, "command": command, "cwd": "/w", "osPid": 4242})
|
||||
}
|
||||
|
||||
/// A session over a codex playing `server`; the codex peer and the ACP peer.
|
||||
async fn terminal_session(server: Arc<TerminalServer>, client: Arc<Client>) -> (Peer, Peer) {
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server, Framing::Lines);
|
||||
let acp = attach(client, |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
let init = request(&acp, "initialize", json!({})).await.unwrap();
|
||||
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["backgroundTasks"], true);
|
||||
request(&acp, "session/new", json!({"cwd": "/w", "mcpServers": []})).await.unwrap();
|
||||
(native, acp)
|
||||
}
|
||||
|
||||
fn shown_tasks(client: &Client) -> Vec<Value> {
|
||||
client
|
||||
.of("s")
|
||||
.into_iter()
|
||||
.filter(|u| u["sessionUpdate"] == crate::BACKGROUND_TASKS_UPDATE)
|
||||
.map(|u| u["tasks"].clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn until(what: &str, mut done: impl FnMut() -> bool) {
|
||||
for _ in 0..200 {
|
||||
if done() {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("timed out waiting for {what}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn background_terminals_outlive_their_turn_as_background_tasks_until_they_end() {
|
||||
let running = json!({"data": [terminal("p1", "/bin/zsh -lc 'sleep 600; echo done'")], "nextCursor": null});
|
||||
let server = TerminalServer::new(vec![running.clone(), running.clone(), running], true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the terminal to end", || shown_tasks(&client).len() == 2).await;
|
||||
assert_eq!(
|
||||
shown_tasks(&client),
|
||||
[json!([{"task_id": "p1", "task_type": "local_bash", "description": "sleep 600; echo done"}]), json!([])]
|
||||
);
|
||||
let listed = server.calls_of("thread/backgroundTerminals/list").len();
|
||||
assert!(listed >= 4, "listed until none ran, got {listed}");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), listed, "stops listing once none runs");
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_background_terminal_stops_on_request_and_all_stop_with_the_connection() {
|
||||
let running = json!({"data": [terminal("p1", "cargo nextest run")], "nextCursor": null});
|
||||
let server = TerminalServer::new(vec![running; 1000], true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the terminal to show", || !shown_tasks(&client).is_empty()).await;
|
||||
request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.unwrap();
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/terminate"), [json!({"threadId": "s", "processId": "p1"})]);
|
||||
assert!(server.calls_of("thread/backgroundTerminals/clean").is_empty());
|
||||
acp.kill();
|
||||
until("the terminals to be cleaned", || !server.calls_of("thread/backgroundTerminals/clean").is_empty()).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/clean"), [json!({"threadId": "s"})]);
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn closing_a_session_stops_its_background_terminals() {
|
||||
let server = TerminalServer::new(Vec::new(), true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client).await;
|
||||
request(&acp, "session/close", json!({"sessionId": "s"})).await.unwrap();
|
||||
let calls: Vec<String> = server.calls.lock().iter().map(|(m, _)| m.clone()).collect();
|
||||
let clean = calls.iter().position(|m| m == "thread/backgroundTerminals/clean").expect("cleaned");
|
||||
let unsubscribe = calls.iter().position(|m| m == "thread/unsubscribe").expect("unsubscribed");
|
||||
assert!(clean < unsubscribe);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_codex_without_background_terminals_reports_none() {
|
||||
let server = TerminalServer::new(Vec::new(), false);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the listing", || !server.calls_of("thread/backgroundTerminals/list").is_empty()).await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), 1);
|
||||
assert!(shown_tasks(&client).is_empty());
|
||||
assert!(request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.is_err());
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_command_left_running_by_a_completed_turn_is_not_a_failure() {
|
||||
for (status, settled) in [("completed", true), ("interrupted", false)] {
|
||||
let server = TerminalServer::new(Vec::new(), true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server, client.clone()).await;
|
||||
let item = json!({"type": "commandExecution", "id": "call_1", "command": "/bin/zsh -lc 'sleep 240'",
|
||||
"cwd": "/w", "status": "inProgress", "commandActions": []});
|
||||
native.notify("item/started", json!({"threadId": "s", "turnId": "t1", "item": item})).unwrap();
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": status}})).unwrap();
|
||||
until("the command card", || client.of("s").iter().any(|u| u["sessionUpdate"] == "tool_call")).await;
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
let updates: Vec<Value> = client
|
||||
.of("s")
|
||||
.into_iter()
|
||||
.filter(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "call_1")
|
||||
.collect();
|
||||
let expected = if settled {
|
||||
vec![json!({"sessionUpdate": "tool_call_update", "toolCallId": "call_1", "status": "completed"})]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
assert_eq!(updates, expected, "turn {status}");
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
@@ -553,7 +553,12 @@ fn image_content(image: &crate::model::AgentImage) -> Value {
|
||||
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
|
||||
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
|
||||
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
|
||||
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
|
||||
let image = crate::model::AgentImage {
|
||||
mime_type: "image/png".into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
};
|
||||
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
|
||||
}
|
||||
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
|
||||
@@ -876,6 +881,20 @@ pub(super) fn decisions(params: &Value, command: bool) -> Vec<Choice> {
|
||||
out
|
||||
}
|
||||
|
||||
/// One page of `thread/backgroundTerminals/list`: the running terminals as
|
||||
/// `(processId, description)`.
|
||||
pub(super) fn background_terminals(page: &Value) -> Vec<(String, String)> {
|
||||
let data = page.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
data.iter()
|
||||
.filter_map(|t| {
|
||||
let process = t.get("processId").and_then(Value::as_str).filter(|p| !p.is_empty())?;
|
||||
let command = t.get("command").and_then(Value::as_str).unwrap_or_default();
|
||||
let description = crate::shell_script(command).unwrap_or_else(|| command.to_owned());
|
||||
Some((process.to_owned(), description))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A command prefix as typed: the script of a `<shell> -lc <script>` wrapper, else the words.
|
||||
fn shell_unwrapped(argv: &[&str]) -> String {
|
||||
match argv {
|
||||
|
||||
@@ -68,7 +68,7 @@ pub(crate) fn connect(
|
||||
) -> std::io::Result<Peer> {
|
||||
let launch_args = spec.args.clone();
|
||||
attach_with_args(client, launch_args, |events| {
|
||||
let command = super::newest_install(&spec.command);
|
||||
let command = super::newest_install(spec.executable());
|
||||
let args = headless_args(&spec.args);
|
||||
Peer::spawn_framed(&command, &args, cwd, &spec.env, events, on_stderr, Framing::ContentLength)
|
||||
})
|
||||
@@ -471,38 +471,6 @@ fn apply_skills(params: &Value, req: &mut Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies `_meta.openidea.memory` to Copilot's `session.create` / `session.resume` payload:
|
||||
/// gates `store_memory` when auto-memory is `ReadOnly` or `Off`, disables custom instructions
|
||||
/// when all workspace/user instructions are muted, and appends shared OpenIDEA memories.
|
||||
fn apply_memory(params: &Value, req: &mut Value) {
|
||||
let Some(mem) = params.pointer("/_meta/openidea/memory") else {
|
||||
return;
|
||||
};
|
||||
if mem.get("copilotExcludeStoreMemory").and_then(Value::as_bool) == Some(true) {
|
||||
let mut excluded: Vec<String> = req
|
||||
.get("excludedTools")
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
if !excluded.iter().any(|t| t == "store_memory") {
|
||||
excluded.push("store_memory".into());
|
||||
}
|
||||
req["excludedTools"] = json!(excluded);
|
||||
}
|
||||
if mem.get("copilotDisableCustomInstructions").and_then(Value::as_bool) == Some(true) {
|
||||
req["customInstructions"] = json!(false);
|
||||
}
|
||||
if let Some(sys) = mem.get("copilotSystemMessage").and_then(Value::as_str).filter(|s| !s.is_empty()) {
|
||||
req["systemMessage"] = json!({
|
||||
"mode": "append",
|
||||
"content": sys,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> ResponseError {
|
||||
error(codes::INVALID_PARAMS, message)
|
||||
}
|
||||
@@ -630,7 +598,6 @@ impl CopilotShim {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let created = self.call("session.create", req).await?;
|
||||
let session_id = created
|
||||
@@ -701,7 +668,6 @@ impl CopilotShim {
|
||||
req["disabledMcpServers"] = disabled;
|
||||
}
|
||||
apply_skills(params, &mut req);
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
|
||||
@@ -1372,6 +1338,10 @@ fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Valu
|
||||
{
|
||||
let path_str = saved.to_string_lossy().into_owned();
|
||||
let name = saved.file_name().and_then(|n| n.to_str()).unwrap_or("image").to_owned();
|
||||
// Copilot takes one text prompt and a separate attachments array.
|
||||
if let Some(number) = block.pointer("/_meta/openideaImageNumber").and_then(Value::as_u64) {
|
||||
text_parts.push(format!("[Image #{number}: {name}]"));
|
||||
}
|
||||
attachments.push(json!({ "type": "file", "path": path_str, "displayName": name }));
|
||||
temp_files.push(saved);
|
||||
}
|
||||
|
||||
@@ -953,56 +953,6 @@ async fn session_new_and_load_forward_staged_skill_directories_and_disabled_skil
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn session_new_and_load_apply_copilot_memory_gating_and_system_message() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates, move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
let meta = json!({
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"autoMemory": "readOnly",
|
||||
"copilotExcludeStoreMemory": true,
|
||||
"copilotDisableCustomInstructions": true,
|
||||
"copilotSystemMessage": "## Memory (shared)\nRun targeted tests."
|
||||
}
|
||||
}
|
||||
});
|
||||
let _: Value =
|
||||
client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [], "_meta": meta }), None).await.unwrap();
|
||||
let _: Value = client
|
||||
.request(
|
||||
"session/load",
|
||||
json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [], "_meta": meta }),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calls = server.calls.lock();
|
||||
for method in ["session.create", "session.resume"] {
|
||||
let params = calls.iter().find_map(|(m, p)| (m == method).then_some(p)).expect(method);
|
||||
assert_eq!(params["excludedTools"], json!(["store_memory"]), "{method}: {params}");
|
||||
assert_eq!(params["customInstructions"], json!(false), "{method}: {params}");
|
||||
assert_eq!(
|
||||
params["systemMessage"],
|
||||
json!({ "mode": "append", "content": "## Memory (shared)\nRun targeted tests." }),
|
||||
"{method}: {params}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translates_context_attribution_without_double_counting_parent_rollups() {
|
||||
let payload = json!({
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
//!
|
||||
//! A shim speaks ACP v1 as the agent side, plus:
|
||||
//! - `agentCapabilities.sessionCapabilities.fork` and `session/fork`
|
||||
//! (`{ sessionId, cwd, mcpServers }` → a `session/new` result for the copy);
|
||||
//! (`{ sessionId, cwd, mcpServers }` → a `session/new` result for the copy). With
|
||||
//! `_meta.openidea.forkTurns`, the copy keeps only the source's first that many turns;
|
||||
//! the result repeats it in its `_meta.openidea.forkTurns` when the shim cut the copy;
|
||||
//! - `agentCapabilities._meta.openidea.rollback` and `_openidea/rollback`
|
||||
//! (`{ sessionId, turns }`: drops the last `turns` user turns from the session);
|
||||
//! - `agentCapabilities._meta.openidea.steer` and `_openidea/steer`
|
||||
@@ -16,8 +18,49 @@ pub(crate) mod codex;
|
||||
pub(crate) mod copilot;
|
||||
|
||||
use ide_jsonrpc::{Framing, Handler, Peer};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::{Duration, Instant, SystemTime};
|
||||
|
||||
const VERSION_CACHE_TTL: Duration = Duration::from_secs(60);
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
struct VersionCacheKey {
|
||||
path: PathBuf,
|
||||
modified: Option<SystemTime>,
|
||||
len: Option<u64>,
|
||||
#[cfg(unix)]
|
||||
ino: Option<u64>,
|
||||
}
|
||||
|
||||
impl VersionCacheKey {
|
||||
fn of(real: &Path) -> Self {
|
||||
let meta = std::fs::metadata(real).ok();
|
||||
#[cfg(unix)]
|
||||
let ino = meta.as_ref().map(std::os::unix::fs::MetadataExt::ino);
|
||||
Self {
|
||||
path: real.to_path_buf(),
|
||||
modified: meta.as_ref().and_then(|m| m.modified().ok()),
|
||||
len: meta.as_ref().map(std::fs::Metadata::len),
|
||||
#[cfg(unix)]
|
||||
ino,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct CachedVersion {
|
||||
version: Vec<u64>,
|
||||
checked_at: Instant,
|
||||
}
|
||||
|
||||
type VersionSlot = Arc<Mutex<Option<CachedVersion>>>;
|
||||
|
||||
fn version_cache() -> &'static Mutex<HashMap<VersionCacheKey, VersionSlot>> {
|
||||
static CACHE: OnceLock<Mutex<HashMap<VersionCacheKey, VersionSlot>>> = OnceLock::new();
|
||||
CACHE.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
/// The newest install of `command` on the `PATH` a child sees, by its `--version`.
|
||||
/// Several installs are common (npm, Homebrew, the vendor's own installer), and the first
|
||||
@@ -36,27 +79,69 @@ fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
|
||||
let names =
|
||||
ide_core::process::executable_names(command, cfg!(windows), pathext.as_deref().and_then(|p| p.to_str()));
|
||||
let mut seen = Vec::new();
|
||||
let candidates: Vec<PathBuf> = std::env::split_paths(search)
|
||||
let candidates: Vec<(PathBuf, PathBuf)> = std::env::split_paths(search)
|
||||
.filter(|d| !d.as_os_str().is_empty())
|
||||
.flat_map(|dir| names.iter().map(move |n| dir.join(n)))
|
||||
.filter(|p| p.is_file())
|
||||
.filter(|p| {
|
||||
let real = dunce::canonicalize(p).unwrap_or_else(|_| p.clone());
|
||||
let new = !seen.contains(&real);
|
||||
seen.push(real);
|
||||
new
|
||||
.filter_map(|p| {
|
||||
let real = dunce::canonicalize(&p).unwrap_or_else(|_| p.clone());
|
||||
if seen.contains(&real) {
|
||||
return None;
|
||||
}
|
||||
seen.push(real.clone());
|
||||
Some((p, real))
|
||||
})
|
||||
.collect();
|
||||
if candidates.len() < 2 {
|
||||
return candidates.into_iter().next().map_or_else(|| command.to_owned(), |p| p.to_string_lossy().into_owned());
|
||||
return candidates
|
||||
.into_iter()
|
||||
.next()
|
||||
.map_or_else(|| command.to_owned(), |(p, _)| p.to_string_lossy().into_owned());
|
||||
}
|
||||
// Probe distinct installs in parallel; per-binary cache + single-flight avoids re-spawning
|
||||
// `--version` on concurrent or repeated lookups while still noticing upgraded binaries.
|
||||
let versions: Vec<Option<Vec<u64>>> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = candidates.iter().map(|(p, real)| s.spawn(|| cached_version_of(p, real))).collect();
|
||||
handles.into_iter().map(|h| h.join().ok().flatten()).collect()
|
||||
});
|
||||
candidates
|
||||
.into_iter()
|
||||
.filter_map(|p| version_of(&p).map(|v| (v, p)))
|
||||
.zip(versions)
|
||||
.filter_map(|((p, _), v)| v.map(|v| (v, p)))
|
||||
.max_by(|a, b| a.0.cmp(&b.0))
|
||||
.map_or_else(|| command.to_owned(), |(_, p)| p.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
fn cached_version_of(program: &Path, real: &Path) -> Option<Vec<u64>> {
|
||||
let key = VersionCacheKey::of(real);
|
||||
let slot = {
|
||||
let mut cache = version_cache().lock();
|
||||
if cache.len() > 64 {
|
||||
cache.retain(|_, slot| {
|
||||
slot.try_lock()
|
||||
.is_none_or(|guard| guard.as_ref().is_some_and(|c| c.checked_at.elapsed() < VERSION_CACHE_TTL))
|
||||
});
|
||||
}
|
||||
cache.entry(key).or_default().clone()
|
||||
};
|
||||
let mut guard = slot.lock();
|
||||
if let Some(cached) = guard.as_ref()
|
||||
&& cached.checked_at.elapsed() < VERSION_CACHE_TTL
|
||||
{
|
||||
return Some(cached.version.clone());
|
||||
}
|
||||
match version_of(program) {
|
||||
Some(version) => {
|
||||
*guard = Some(CachedVersion { version: version.clone(), checked_at: Instant::now() });
|
||||
Some(version)
|
||||
}
|
||||
None => {
|
||||
*guard = None;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `x.y.z` from `<program> --version` ("codex-cli 0.164.0", "2.1.312 (Claude Code)").
|
||||
fn version_of(program: &Path) -> Option<Vec<u64>> {
|
||||
let mut cmd = std::process::Command::new(program);
|
||||
@@ -142,4 +227,77 @@ mod tests {
|
||||
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn newest_install_caches_versions_and_invalidates_on_change() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = dir.path().join("old");
|
||||
let new = dir.path().join("new");
|
||||
let old_log = dir.path().join("old.log");
|
||||
let new_log = dir.path().join("new.log");
|
||||
for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
let executable = path.join("agent");
|
||||
std::fs::write(&executable, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display()))
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let search = std::env::join_paths([&old, &new]).unwrap();
|
||||
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
|
||||
assert_eq!(newest_install_in("agent", &search), new.join("agent").to_string_lossy());
|
||||
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1);
|
||||
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
|
||||
|
||||
// Replacing the older binary with a newer version invalidates only its cache entry.
|
||||
let upgraded = old.join("agent");
|
||||
std::fs::write(&upgraded, format!("#!/bin/sh\nprintf 'x\\n' >> '{}'\necho 2.11.0\n", old_log.display()))
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&upgraded, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
assert_eq!(newest_install_in("agent", &search), upgraded.to_string_lossy());
|
||||
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 2);
|
||||
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn newest_install_deduplicates_concurrent_probes() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let old = dir.path().join("old");
|
||||
let new = dir.path().join("new");
|
||||
let old_log = dir.path().join("old.log");
|
||||
let new_log = dir.path().join("new.log");
|
||||
for (path, log, version) in [(&old, &old_log, "2.9.0"), (&new, &new_log, "2.10.0")] {
|
||||
std::fs::create_dir_all(path).unwrap();
|
||||
let executable = path.join("agent");
|
||||
std::fs::write(
|
||||
&executable,
|
||||
format!("#!/bin/sh\nsleep 0.05\nprintf 'x\\n' >> '{}'\necho {version}\n", log.display()),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let search = std::env::join_paths([&old, &new]).unwrap();
|
||||
let expected = new.join("agent").to_string_lossy().into_owned();
|
||||
let barrier = std::sync::Barrier::new(4);
|
||||
std::thread::scope(|s| {
|
||||
let handles: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
s.spawn(|| {
|
||||
barrier.wait();
|
||||
newest_install_in("agent", &search)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for handle in handles {
|
||||
assert_eq!(handle.join().unwrap(), expected);
|
||||
}
|
||||
});
|
||||
assert_eq!(std::fs::read_to_string(&old_log).unwrap().lines().count(), 1);
|
||||
assert_eq!(std::fs::read_to_string(&new_log).unwrap().lines().count(), 1);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use base64::Engine as _;
|
||||
use ide_core::settings::{AgentMcpServer, AgentPluginEntryPolicy, AgentPluginSettings};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -46,6 +47,37 @@ const MARKETPLACE_MANIFEST_PATHS: &[&str] = &[
|
||||
".github/plugin/marketplace.json",
|
||||
];
|
||||
|
||||
/// Maximum local icon file size inlined as a base64 `data:` URI (64 KiB).
|
||||
const MAX_INLINE_ICON_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// Conventional icon file locations checked inside a plugin directory when no explicit icon is declared.
|
||||
const CONVENTIONAL_ICON_PATHS: &[&str] = &[
|
||||
".claude-plugin/icon.png",
|
||||
".claude-plugin/icon.svg",
|
||||
".claude-plugin/icon.webp",
|
||||
".plugin/icon.png",
|
||||
".plugin/icon.svg",
|
||||
".plugin/icon.webp",
|
||||
".github/plugin/icon.png",
|
||||
".github/plugin/icon.svg",
|
||||
".github/plugin/icon.webp",
|
||||
".codex-plugin/icon.png",
|
||||
".codex-plugin/icon.svg",
|
||||
".codex-plugin/icon.webp",
|
||||
"assets/logo.png",
|
||||
"assets/logo.svg",
|
||||
"assets/logo.webp",
|
||||
"assets/icon.png",
|
||||
"assets/icon.svg",
|
||||
"assets/icon.webp",
|
||||
"icon.png",
|
||||
"icon.svg",
|
||||
"icon.webp",
|
||||
"logo.png",
|
||||
"logo.svg",
|
||||
"logo.webp",
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InstalledPluginProvenance {
|
||||
@@ -1461,6 +1493,8 @@ pub fn projected_mcp_servers(
|
||||
unapproved: false,
|
||||
plugin_id: Some(state.plugin.id.clone()),
|
||||
plugin_name: Some(state.plugin.display_name.clone()),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1551,6 +1585,7 @@ pub fn browse_marketplace(
|
||||
let tree = fetcher.git_tree(RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &git_ref }, cancel)?;
|
||||
|
||||
let target = RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &git_ref };
|
||||
let tree_paths: HashSet<&str> = tree.tree.iter().filter(|e| e.kind == "blob").map(|e| e.path.as_str()).collect();
|
||||
|
||||
// 1. Check for a `marketplace.json` manifest in the repository (under `parsed.subpath` if given, or root).
|
||||
let sub_prefix = parsed.subpath.as_deref().map(|s| format!("{s}/")).unwrap_or_default();
|
||||
@@ -1561,10 +1596,9 @@ pub fn browse_marketplace(
|
||||
let text = String::from_utf8(bytes).map_err(|_| IdeError::invalid("marketplace.json is not UTF-8"))?;
|
||||
let (mkt_name, candidates) = parse_marketplace_json_remote(
|
||||
&text,
|
||||
&parsed.owner,
|
||||
&parsed.repo,
|
||||
&git_ref,
|
||||
target,
|
||||
parsed.subpath.as_deref(),
|
||||
&tree_paths,
|
||||
user_home,
|
||||
workspace_root,
|
||||
)?;
|
||||
@@ -1614,6 +1648,7 @@ pub fn browse_marketplace(
|
||||
let mut description = String::new();
|
||||
let mut author = None;
|
||||
let mut keywords = Vec::new();
|
||||
let mut manifest_val: Option<Value> = None;
|
||||
|
||||
for (manifest_rel, _) in MANIFEST_CANDIDATES {
|
||||
let p = format!("{prefix}{manifest_rel}");
|
||||
@@ -1644,10 +1679,18 @@ pub fn browse_marketplace(
|
||||
if keywords.is_empty() {
|
||||
keywords = extract_string_array(val.get("keywords"));
|
||||
}
|
||||
manifest_val = Some(val);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let (icon_url, icon_dark_url) = resolve_remote_plugin_icons(
|
||||
manifest_val.as_ref(),
|
||||
Some((&parsed.owner, &parsed.repo, &git_ref, root_dir.as_str(), Some(&tree_paths))),
|
||||
None,
|
||||
Some(&parsed.owner),
|
||||
);
|
||||
|
||||
let source_spec = if root_dir.is_empty() {
|
||||
format!("{}/{}#{git_ref}", parsed.owner, parsed.repo)
|
||||
} else {
|
||||
@@ -1661,6 +1704,8 @@ pub fn browse_marketplace(
|
||||
description,
|
||||
author,
|
||||
marketplace: None,
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec,
|
||||
subpath: root_dir,
|
||||
keywords,
|
||||
@@ -1717,7 +1762,7 @@ pub fn preview_plugin(
|
||||
}
|
||||
let scanned = scan_local_subtree(&canon, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin")?;
|
||||
let inspected =
|
||||
inspect_fetched_subtree(&scanned, canon.file_name().and_then(|s| s.to_str()).unwrap_or("plugin"))?;
|
||||
inspect_fetched_subtree(&scanned, canon.file_name().and_then(|s| s.to_str()).unwrap_or("plugin"), None)?;
|
||||
let marketplace_source = marketplace
|
||||
.and_then(|name| local_marketplace_source(&local_dir, name))
|
||||
.map(|path| path.to_string_lossy().into_owned());
|
||||
@@ -1746,6 +1791,8 @@ pub fn preview_plugin(
|
||||
display_name: inspected.display_name,
|
||||
version: inspected.version,
|
||||
description: inspected.description,
|
||||
icon_url: inspected.icon_url,
|
||||
icon_dark_url: inspected.icon_dark_url,
|
||||
formats: inspected.formats,
|
||||
capabilities: inspected.capabilities,
|
||||
files: scanned.files,
|
||||
@@ -1764,7 +1811,11 @@ pub fn preview_plugin(
|
||||
let scanned =
|
||||
fetch_and_scan_subtree(fetcher, target, &subpath, None, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin", cancel)?;
|
||||
let fallback_name = subpath.rsplit('/').next().filter(|s| !s.is_empty()).unwrap_or(&parsed.repo);
|
||||
let inspected = inspect_fetched_subtree(&scanned, fallback_name)?;
|
||||
let inspected = inspect_fetched_subtree(
|
||||
&scanned,
|
||||
fallback_name,
|
||||
Some((&parsed.owner, &parsed.repo, &commit_sha, scanned.normalized_subpath.as_str())),
|
||||
)?;
|
||||
let targets = plugin_install_targets(
|
||||
&inspected.name,
|
||||
inspected.version.as_deref(),
|
||||
@@ -1791,6 +1842,8 @@ pub fn preview_plugin(
|
||||
display_name: inspected.display_name,
|
||||
version: inspected.version,
|
||||
description: inspected.description,
|
||||
icon_url: inspected.icon_url,
|
||||
icon_dark_url: inspected.icon_dark_url,
|
||||
formats: inspected.formats,
|
||||
capabilities: inspected.capabilities,
|
||||
files: scanned.files,
|
||||
@@ -1919,7 +1972,7 @@ pub fn install_plugin(
|
||||
));
|
||||
}
|
||||
|
||||
let inspected = inspect_fetched_subtree(&scanned, &fallback_name)?;
|
||||
let inspected = inspect_fetched_subtree(&scanned, &fallback_name, None)?;
|
||||
if let Some(reason) = plugin_install_blocker(
|
||||
source,
|
||||
&inspected.formats,
|
||||
@@ -2057,16 +2110,23 @@ struct InspectedSubtreeMeta {
|
||||
display_name: String,
|
||||
version: Option<String>,
|
||||
description: String,
|
||||
icon_url: Option<String>,
|
||||
icon_dark_url: Option<String>,
|
||||
formats: Vec<AgentPluginFormat>,
|
||||
capabilities: AgentPluginCapabilities,
|
||||
}
|
||||
|
||||
fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> IdeResult<InspectedSubtreeMeta> {
|
||||
fn inspect_fetched_subtree(
|
||||
scanned: &FetchedSubtree,
|
||||
fallback_name: &str,
|
||||
remote_repo: Option<(&str, &str, &str, &str)>,
|
||||
) -> IdeResult<InspectedSubtreeMeta> {
|
||||
let mut formats = Vec::new();
|
||||
let mut name: Option<String> = None;
|
||||
let mut display_name: Option<String> = None;
|
||||
let mut version: Option<String> = None;
|
||||
let mut description = String::new();
|
||||
let mut primary_manifest: Option<Value> = None;
|
||||
let mut native_harnesses = BTreeSet::new();
|
||||
|
||||
let file_map: BTreeMap<String, &[u8]> =
|
||||
@@ -2108,6 +2168,9 @@ fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> Ide
|
||||
{
|
||||
description = d.trim().to_owned();
|
||||
}
|
||||
if primary_manifest.is_none() {
|
||||
primary_manifest = Some(val);
|
||||
}
|
||||
}
|
||||
|
||||
let mut skill_names = Vec::new();
|
||||
@@ -2158,12 +2221,15 @@ fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> Ide
|
||||
|
||||
let final_name = name.unwrap_or_else(|| sanitize_plugin_slug(fallback_name));
|
||||
let final_display = display_name.unwrap_or_else(|| final_name.clone());
|
||||
let (icon_url, icon_dark_url) = resolve_subtree_icons(primary_manifest.as_ref(), &file_map, remote_repo);
|
||||
|
||||
Ok(InspectedSubtreeMeta {
|
||||
name: final_name,
|
||||
display_name: final_display,
|
||||
version,
|
||||
description,
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
formats,
|
||||
capabilities: AgentPluginCapabilities {
|
||||
skill_count: skill_names.len() as u32,
|
||||
@@ -3654,6 +3720,13 @@ fn browse_local_marketplace(
|
||||
if source_spec.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let local_plugin_dir = Path::new(&source_spec);
|
||||
let (icon_url, icon_dark_url) = if local_plugin_dir.is_dir() {
|
||||
resolve_local_plugin_icons(Some(item), local_plugin_dir)
|
||||
} else {
|
||||
let ext_repo = source_spec.split('#').next();
|
||||
resolve_remote_plugin_icons(Some(item), None, ext_repo, None)
|
||||
};
|
||||
let (already_user, already_ws) =
|
||||
plugin_installed_anywhere(&name, Some(&mkt_name), user_home, workspace_root);
|
||||
candidates.push(AgentMarketplaceCandidate {
|
||||
@@ -3663,6 +3736,8 @@ fn browse_local_marketplace(
|
||||
description,
|
||||
author,
|
||||
marketplace: Some(mkt_name.clone()),
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec,
|
||||
subpath,
|
||||
keywords,
|
||||
@@ -3685,6 +3760,11 @@ fn browse_local_marketplace(
|
||||
// Direct local plugin folder. The source only selects how metadata is read; the target
|
||||
// harness is chosen at install time.
|
||||
if let Some(plug) = inspect_plugin_dir(local_path, AgentPluginSource::CopilotUser, McpScope::User, None, true) {
|
||||
let manifest_val = MANIFEST_CANDIDATES.iter().find_map(|(rel, _)| {
|
||||
let text = std::fs::read_to_string(local_path.join(rel)).ok()?;
|
||||
parse_jsonc(&text).ok()
|
||||
});
|
||||
let (icon_url, icon_dark_url) = resolve_local_plugin_icons(manifest_val.as_ref(), local_path);
|
||||
let (already_user, already_ws) = plugin_installed_anywhere(&plug.name, None, user_home, workspace_root);
|
||||
return Ok(AgentMarketplaceBrowseResult {
|
||||
source: raw_source.to_owned(),
|
||||
@@ -3700,6 +3780,8 @@ fn browse_local_marketplace(
|
||||
description: plug.description,
|
||||
author: plug.author,
|
||||
marketplace: None,
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec: local_path.to_string_lossy().into_owned(),
|
||||
subpath: String::new(),
|
||||
keywords: Vec::new(),
|
||||
@@ -3836,13 +3918,13 @@ fn safe_marketplace_repo(raw: &str) -> Option<String> {
|
||||
|
||||
fn parse_marketplace_json_remote(
|
||||
text: &str,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
git_ref: &str,
|
||||
target: RepoRef<'_>,
|
||||
base_subpath: Option<&str>,
|
||||
tree_paths: &HashSet<&str>,
|
||||
user_home: Option<&Path>,
|
||||
workspace_root: Option<&Path>,
|
||||
) -> IdeResult<(String, Vec<AgentMarketplaceCandidate>)> {
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
let val = parse_jsonc(text).map_err(|e| IdeError::invalid(format!("Invalid marketplace.json: {e}")))?;
|
||||
let mkt_name =
|
||||
val.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).unwrap_or(repo).to_owned();
|
||||
@@ -3872,7 +3954,7 @@ fn parse_marketplace_json_remote(
|
||||
let author = extract_author(item);
|
||||
let keywords = extract_string_array(item.get("keywords"));
|
||||
|
||||
let (source_spec, subpath) = match item.get("source") {
|
||||
let (source_spec, subpath, ext_repo_owner, in_marketplace_repo) = match item.get("source") {
|
||||
Some(Value::String(rel)) => {
|
||||
let Some(clean) = safe_marketplace_subpath(rel) else { continue };
|
||||
let mut parts: Vec<&str> = Vec::new();
|
||||
@@ -3891,7 +3973,7 @@ fn parse_marketplace_json_remote(
|
||||
} else {
|
||||
format!("{owner}/{repo}/{joined}#{git_ref}")
|
||||
};
|
||||
(spec, joined)
|
||||
(spec, joined, None, true)
|
||||
}
|
||||
Some(Value::Object(obj)) => match obj.get("source").and_then(Value::as_str).unwrap_or_default() {
|
||||
"local" => {
|
||||
@@ -3916,7 +3998,7 @@ fn parse_marketplace_json_remote(
|
||||
} else {
|
||||
format!("{owner}/{repo}/{joined}#{git_ref}")
|
||||
};
|
||||
(spec, joined)
|
||||
(spec, joined, None, true)
|
||||
}
|
||||
"github" => {
|
||||
let Some(ext_repo) = obj.get("repo").and_then(Value::as_str).and_then(safe_marketplace_repo) else {
|
||||
@@ -3926,9 +4008,9 @@ fn parse_marketplace_json_remote(
|
||||
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else { continue };
|
||||
let spec = match r {
|
||||
Some(gr) => format!("{ext_repo}#{gr}"),
|
||||
None => ext_repo.to_owned(),
|
||||
None => ext_repo.clone(),
|
||||
};
|
||||
(spec, String::new())
|
||||
(spec, String::new(), Some(ext_repo), false)
|
||||
}
|
||||
"git-subdir" => {
|
||||
let Some(ext_repo) = obj
|
||||
@@ -3949,15 +4031,19 @@ fn parse_marketplace_json_remote(
|
||||
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else { continue };
|
||||
let spec = match r {
|
||||
Some(gr) => format!("{ext_repo}#{gr}"),
|
||||
None => ext_repo.to_owned(),
|
||||
None => ext_repo.clone(),
|
||||
};
|
||||
(spec, sub)
|
||||
(spec, sub, Some(ext_repo), false)
|
||||
}
|
||||
_ => continue,
|
||||
},
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
let in_repo_ctx = in_marketplace_repo.then_some((owner, repo, git_ref, subpath.as_str(), Some(tree_paths)));
|
||||
let (icon_url, icon_dark_url) =
|
||||
resolve_remote_plugin_icons(Some(item), in_repo_ctx, ext_repo_owner.as_deref(), Some(owner));
|
||||
|
||||
let (already_user, already_ws) = plugin_installed_anywhere(&name, Some(&mkt_name), user_home, workspace_root);
|
||||
out.push(AgentMarketplaceCandidate {
|
||||
name,
|
||||
@@ -3966,6 +4052,8 @@ fn parse_marketplace_json_remote(
|
||||
description,
|
||||
author,
|
||||
marketplace: Some(mkt_name.clone()),
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec,
|
||||
subpath,
|
||||
keywords,
|
||||
@@ -3977,6 +4065,302 @@ fn parse_marketplace_json_remote(
|
||||
Ok((mkt_name, out))
|
||||
}
|
||||
|
||||
fn safe_https_icon_url(raw: &str) -> Option<String> {
|
||||
let trimmed = raw.trim();
|
||||
let rest = trimmed.strip_prefix("https://")?;
|
||||
if trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) {
|
||||
return None;
|
||||
}
|
||||
let authority = rest.split('/').next().unwrap_or_default();
|
||||
if authority.is_empty() || authority.contains('@') {
|
||||
return None;
|
||||
}
|
||||
Some(trimmed.to_owned())
|
||||
}
|
||||
|
||||
fn icon_mime_for_path(path: &str) -> Option<&'static str> {
|
||||
let lower = path.to_ascii_lowercase();
|
||||
if lower.ends_with(".png") {
|
||||
Some("image/png")
|
||||
} else if lower.ends_with(".svg") {
|
||||
Some("image/svg+xml")
|
||||
} else if lower.ends_with(".webp") {
|
||||
Some("image/webp")
|
||||
} else if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
|
||||
Some("image/jpeg")
|
||||
} else if lower.ends_with(".ico") {
|
||||
Some("image/x-icon")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_data_uri(mime: &str, bytes: &[u8]) -> Option<String> {
|
||||
if bytes.is_empty() || bytes.len() > MAX_INLINE_ICON_BYTES {
|
||||
return None;
|
||||
}
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(bytes);
|
||||
Some(format!("data:{mime};base64,{b64}"))
|
||||
}
|
||||
|
||||
fn percent_encode_path_segment(segment: &str) -> String {
|
||||
let mut out = String::with_capacity(segment.len());
|
||||
for byte in segment.bytes() {
|
||||
let unreserved = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~');
|
||||
if unreserved {
|
||||
out.push(byte as char);
|
||||
} else {
|
||||
out.push('%');
|
||||
let hi = byte >> 4;
|
||||
let lo = byte & 0x0f;
|
||||
out.push(if hi < 10 { (b'0' + hi) as char } else { (b'A' + hi - 10) as char });
|
||||
out.push(if lo < 10 { (b'0' + lo) as char } else { (b'A' + lo - 10) as char });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn github_raw_file_url(owner: &str, repo: &str, git_ref: &str, repo_path: &str) -> String {
|
||||
let enc_ref = git_ref.split('/').map(percent_encode_path_segment).collect::<Vec<_>>().join("/");
|
||||
let enc_path = repo_path.split('/').map(percent_encode_path_segment).collect::<Vec<_>>().join("/");
|
||||
format!("https://raw.githubusercontent.com/{owner}/{repo}/{enc_ref}/{enc_path}")
|
||||
}
|
||||
|
||||
fn is_valid_github_owner(owner: &str) -> bool {
|
||||
!owner.is_empty()
|
||||
&& owner.len() <= 39
|
||||
&& owner.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
&& !owner.starts_with('-')
|
||||
&& !owner.ends_with('-')
|
||||
}
|
||||
|
||||
fn github_owner_from_url(raw: &str) -> Option<&str> {
|
||||
let trimmed = raw.trim();
|
||||
let rest = trimmed
|
||||
.strip_prefix("https://github.com/")
|
||||
.or_else(|| trimmed.strip_prefix("http://github.com/"))
|
||||
.or_else(|| trimmed.strip_prefix("https://www.github.com/"))?;
|
||||
let owner = rest.split('/').next()?;
|
||||
is_valid_github_owner(owner).then_some(owner)
|
||||
}
|
||||
|
||||
fn github_owner_from_repo_slug(slug: &str) -> Option<&str> {
|
||||
let owner = slug.trim().split('/').next()?;
|
||||
is_valid_github_owner(owner).then_some(owner)
|
||||
}
|
||||
|
||||
fn github_owner_avatar(val: Option<&Value>, ext_repo: Option<&str>, fallback_owner: Option<&str>) -> Option<String> {
|
||||
if let Some(owner) = ext_repo.and_then(github_owner_from_repo_slug) {
|
||||
return Some(format!("https://github.com/{owner}.png?size=64"));
|
||||
}
|
||||
if let Some(v) = val {
|
||||
let candidate_urls = [
|
||||
v.get("repository").and_then(|r| r.get("url").or(Some(r))).and_then(Value::as_str),
|
||||
v.get("homepage").and_then(Value::as_str),
|
||||
v.pointer("/author/url").and_then(Value::as_str),
|
||||
];
|
||||
for raw_url in candidate_urls.into_iter().flatten() {
|
||||
if let Some(owner) = github_owner_from_url(raw_url) {
|
||||
return Some(format!("https://github.com/{owner}.png?size=64"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(owner) = fallback_owner.filter(|o| is_valid_github_owner(o)) {
|
||||
return Some(format!("https://github.com/{owner}.png?size=64"));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Resolves explicit icon references `(light, dark)` from a marketplace entry or plugin manifest,
|
||||
/// skipping any invalid/unresolvable entries before picking light/dark variants.
|
||||
fn resolve_manifest_icon_refs(
|
||||
val: &Value,
|
||||
resolve: impl Fn(&str) -> Option<String>,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
if let Some(icons) = val.get("icons").and_then(Value::as_array) {
|
||||
let mut light: Option<String> = None;
|
||||
let mut dark: Option<String> = None;
|
||||
let mut unthemed: Option<String> = None;
|
||||
let mut first: Option<String> = None;
|
||||
for item in icons {
|
||||
let Some(obj) = item.as_object() else { continue };
|
||||
let Some(src) = obj.get("src").and_then(Value::as_str).and_then(&resolve) else {
|
||||
continue;
|
||||
};
|
||||
if first.is_none() {
|
||||
first = Some(src.clone());
|
||||
}
|
||||
match obj.get("theme").and_then(Value::as_str).map(|s| s.trim().to_ascii_lowercase()).as_deref() {
|
||||
Some("light") if light.is_none() => light = Some(src),
|
||||
Some("dark") if dark.is_none() => dark = Some(src),
|
||||
None | Some("") if unthemed.is_none() => unthemed = Some(src),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let resolved_light = light.or_else(|| unthemed.clone()).or(first);
|
||||
if resolved_light.is_some() {
|
||||
let resolved_dark = dark.or(unthemed).filter(|d| Some(d.as_str()) != resolved_light.as_deref());
|
||||
return (resolved_light, resolved_dark);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(icon) = val.get("icon") {
|
||||
if let Some(resolved) = icon.as_str().and_then(&resolve) {
|
||||
return (Some(resolved), None);
|
||||
}
|
||||
if let Some(obj) = icon.as_object() {
|
||||
let light = obj.get("light").and_then(Value::as_str).and_then(&resolve);
|
||||
let dark = obj.get("dark").and_then(Value::as_str).and_then(&resolve);
|
||||
if light.is_some() || dark.is_some() {
|
||||
let eff_light = light.or_else(|| dark.clone());
|
||||
let eff_dark = dark.filter(|d| Some(d.as_str()) != eff_light.as_deref());
|
||||
return (eff_light, eff_dark);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for candidate in [
|
||||
val.get("logo"),
|
||||
val.pointer("/interface/logo"),
|
||||
val.pointer("/interface/composerIcon"),
|
||||
val.get("iconUrl"),
|
||||
val.get("icon_url"),
|
||||
] {
|
||||
if let Some(resolved) = candidate.and_then(Value::as_str).and_then(&resolve) {
|
||||
return (Some(resolved), None);
|
||||
}
|
||||
}
|
||||
|
||||
(None, None)
|
||||
}
|
||||
|
||||
fn join_repo_subpath(subpath: &str, rel: &str) -> String {
|
||||
if subpath.is_empty() { rel.to_owned() } else { format!("{subpath}/{rel}") }
|
||||
}
|
||||
|
||||
type RemoteRepoIconContext<'a> = (&'a str, &'a str, &'a str, &'a str, Option<&'a HashSet<&'a str>>);
|
||||
|
||||
fn resolve_remote_icon_ref(raw: &str, in_repo: Option<RemoteRepoIconContext<'_>>) -> Option<String> {
|
||||
if let Some(https) = safe_https_icon_url(raw) {
|
||||
return Some(https);
|
||||
}
|
||||
let (owner, repo, git_ref, subpath, tree_paths) = in_repo?;
|
||||
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
|
||||
icon_mime_for_path(clean)?;
|
||||
let full = join_repo_subpath(subpath, clean);
|
||||
if let Some(paths) = tree_paths
|
||||
&& !paths.contains(full.as_str())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(github_raw_file_url(owner, repo, git_ref, &full))
|
||||
}
|
||||
|
||||
fn resolve_remote_plugin_icons(
|
||||
val: Option<&Value>,
|
||||
in_repo: Option<RemoteRepoIconContext<'_>>,
|
||||
ext_repo: Option<&str>,
|
||||
fallback_owner: Option<&str>,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
if let Some(v) = val {
|
||||
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_remote_icon_ref(r, in_repo));
|
||||
if light.is_some() || dark.is_some() {
|
||||
return (light, dark);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((owner, repo, git_ref, subpath, Some(tree_paths))) = in_repo {
|
||||
for rel in CONVENTIONAL_ICON_PATHS {
|
||||
let full = join_repo_subpath(subpath, rel);
|
||||
if tree_paths.contains(full.as_str()) {
|
||||
return (Some(github_raw_file_url(owner, repo, git_ref, &full)), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(github_owner_avatar(val, ext_repo, fallback_owner), None)
|
||||
}
|
||||
|
||||
fn resolve_local_icon_ref(raw: &str, plugin_dir: &Path) -> Option<String> {
|
||||
if let Some(https) = safe_https_icon_url(raw) {
|
||||
return Some(https);
|
||||
}
|
||||
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
|
||||
let mime = icon_mime_for_path(clean)?;
|
||||
let path = contained_join(plugin_dir, clean).ok()?;
|
||||
let meta = std::fs::metadata(&path).ok()?;
|
||||
if !meta.is_file() || meta.len() > MAX_INLINE_ICON_BYTES as u64 {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::fs::read(&path).ok()?;
|
||||
encode_data_uri(mime, &bytes)
|
||||
}
|
||||
|
||||
fn resolve_local_plugin_icons(val: Option<&Value>, plugin_dir: &Path) -> (Option<String>, Option<String>) {
|
||||
if let Some(v) = val {
|
||||
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_local_icon_ref(r, plugin_dir));
|
||||
if light.is_some() || dark.is_some() {
|
||||
return (light, dark);
|
||||
}
|
||||
}
|
||||
|
||||
for rel in CONVENTIONAL_ICON_PATHS {
|
||||
if let Some(data_uri) = resolve_local_icon_ref(rel, plugin_dir) {
|
||||
return (Some(data_uri), None);
|
||||
}
|
||||
}
|
||||
|
||||
(github_owner_avatar(val, None, None), None)
|
||||
}
|
||||
|
||||
fn resolve_subtree_icon_ref(
|
||||
raw: &str,
|
||||
file_map: &BTreeMap<String, &[u8]>,
|
||||
remote_repo: Option<(&str, &str, &str, &str)>,
|
||||
) -> Option<String> {
|
||||
if let Some(https) = safe_https_icon_url(raw) {
|
||||
return Some(https);
|
||||
}
|
||||
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
|
||||
let mime = icon_mime_for_path(clean)?;
|
||||
let bytes = file_map.get(clean)?;
|
||||
if let Some((owner, repo, git_ref, subpath)) = remote_repo {
|
||||
let full = join_repo_subpath(subpath, clean);
|
||||
return Some(github_raw_file_url(owner, repo, git_ref, &full));
|
||||
}
|
||||
encode_data_uri(mime, bytes)
|
||||
}
|
||||
|
||||
fn resolve_subtree_icons(
|
||||
val: Option<&Value>,
|
||||
file_map: &BTreeMap<String, &[u8]>,
|
||||
remote_repo: Option<(&str, &str, &str, &str)>,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
if let Some(v) = val {
|
||||
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_subtree_icon_ref(r, file_map, remote_repo));
|
||||
if light.is_some() || dark.is_some() {
|
||||
return (light, dark);
|
||||
}
|
||||
}
|
||||
|
||||
for rel in CONVENTIONAL_ICON_PATHS {
|
||||
if let Some(bytes) = file_map.get(*rel)
|
||||
&& let Some(mime) = icon_mime_for_path(rel)
|
||||
{
|
||||
if let Some((owner, repo, git_ref, subpath)) = remote_repo {
|
||||
let full = join_repo_subpath(subpath, rel);
|
||||
return (Some(github_raw_file_url(owner, repo, git_ref, &full)), None);
|
||||
}
|
||||
if let Some(data_uri) = encode_data_uri(mime, bytes) {
|
||||
return (Some(data_uri), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fallback_owner = remote_repo.map(|(owner, _, _, _)| owner);
|
||||
(github_owner_avatar(val, None, fallback_owner), None)
|
||||
}
|
||||
|
||||
const INSTALL_SOURCES: [AgentPluginSource; 4] = [
|
||||
AgentPluginSource::ClaudeUser,
|
||||
AgentPluginSource::CopilotUser,
|
||||
@@ -5553,7 +5937,7 @@ mod tests {
|
||||
|
||||
let on_disk = inspect_plugin_dir(&dir, AgentPluginSource::ClaudeUser, McpScope::User, Some("m"), true).unwrap();
|
||||
let scanned = scan_local_subtree(&dir, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin").unwrap();
|
||||
let preview = inspect_fetched_subtree(&scanned, "hooked").unwrap();
|
||||
let preview = inspect_fetched_subtree(&scanned, "hooked", None).unwrap();
|
||||
for hooks in [&on_disk.capabilities.hook_files, &preview.capabilities.hook_files] {
|
||||
assert!(hooks.contains(&".claude-plugin/plugin.json#hooks".to_owned()), "{hooks:?}");
|
||||
assert!(hooks.contains(&"config/copilot-hooks.json".to_owned()), "{hooks:?}");
|
||||
@@ -5698,19 +6082,19 @@ mod tests {
|
||||
{"name":"gh-bad-ref","source":{"source":"github","repo":"acme/tools","ref":"main#x"}},
|
||||
{"name":"sub-bad","source":{"source":"git-subdir","url":"https://github.com/acme/tools.git","path":"../x"}}
|
||||
]}"##;
|
||||
let (_, candidates) =
|
||||
parse_marketplace_json_remote(manifest, "acme", "repo", "main", None, None, None).unwrap();
|
||||
let empty_tree = HashSet::new();
|
||||
let target = RepoRef { owner: "acme", repo: "repo", git_ref: "main" };
|
||||
let (_, candidates) = parse_marketplace_json_remote(manifest, target, None, &empty_tree, None, None).unwrap();
|
||||
let specs: Vec<_> = candidates.iter().map(|c| (c.name.as_str(), c.source_spec.as_str())).collect();
|
||||
assert_eq!(specs, [("ok", "acme/repo/plugins/ok#main"), ("gh-ok", "acme/tools#v1.2")]);
|
||||
assert!(
|
||||
parse_marketplace_json_remote(
|
||||
r#"{"metadata":{"pluginRoot":"../up"},"plugins":[]}"#,
|
||||
"acme",
|
||||
"repo",
|
||||
"main",
|
||||
target,
|
||||
None,
|
||||
&empty_tree,
|
||||
None,
|
||||
None,
|
||||
None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
@@ -5828,4 +6212,112 @@ mod tests {
|
||||
&& plugin.scope == McpScope::Workspace
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marketplace_browse_and_preview_resolve_explicit_bundled_local_and_avatar_icons() {
|
||||
let cancel = CancellationToken::new();
|
||||
let marketplace_json = br#"{
|
||||
"name": "claude-plugins-official",
|
||||
"plugins": [
|
||||
{
|
||||
"name": "themed-ext",
|
||||
"description": "Explicit light/dark icons",
|
||||
"source": "./plugins/themed-ext",
|
||||
"icons": [
|
||||
{ "src": "javascript:alert(1)", "theme": "light" },
|
||||
{ "src": "https://cdn.example.com/light.png", "theme": "light" },
|
||||
{ "src": "https://cdn.example.com/dark.png", "theme": "dark" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "champion-kit",
|
||||
"description": "Bundled .claude-plugin/icon.png",
|
||||
"source": "./plugins/champion-kit"
|
||||
},
|
||||
{
|
||||
"name": "adobe-for-creativity",
|
||||
"description": "External git-subdir plugin",
|
||||
"source": {
|
||||
"source": "git-subdir",
|
||||
"url": "https://github.com/adobe/skills.git",
|
||||
"path": "plugins/creative-cloud/adobe-for-creativity"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "first-party",
|
||||
"description": "Falls back to marketplace repo owner avatar",
|
||||
"source": "./plugins/first-party"
|
||||
},
|
||||
{
|
||||
"name": "unsafe-icon",
|
||||
"description": "Rejects http:// and escaping relative paths",
|
||||
"source": "./plugins/unsafe-icon",
|
||||
"icon": "../escape.png"
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
|
||||
let gh = FakeGitHub::new(
|
||||
&[
|
||||
(".claude-plugin/marketplace.json", marketplace_json.as_slice(), "100644"),
|
||||
("plugins/champion-kit/.claude-plugin/plugin.json", br#"{"name":"champion-kit"}"#, "100644"),
|
||||
("plugins/champion-kit/.claude-plugin/icon.png", b"\x89PNG\r\n\x1a\n", "100644"),
|
||||
("plugins/first-party/.claude-plugin/plugin.json", br#"{"name":"first-party"}"#, "100644"),
|
||||
],
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
);
|
||||
|
||||
let browse = browse_marketplace(&gh, "anthropics/claude-plugins-official", None, None, &cancel).unwrap();
|
||||
let by = |name: &str| browse.candidates.iter().find(|c| c.name == name).unwrap();
|
||||
|
||||
assert_eq!(by("themed-ext").icon_url.as_deref(), Some("https://cdn.example.com/light.png"));
|
||||
assert_eq!(by("themed-ext").icon_dark_url.as_deref(), Some("https://cdn.example.com/dark.png"));
|
||||
assert_eq!(
|
||||
by("champion-kit").icon_url.as_deref(),
|
||||
Some(
|
||||
"https://raw.githubusercontent.com/anthropics/claude-plugins-official/main/plugins/champion-kit/.claude-plugin/icon.png"
|
||||
)
|
||||
);
|
||||
assert_eq!(by("adobe-for-creativity").icon_url.as_deref(), Some("https://github.com/adobe.png?size=64"));
|
||||
assert_eq!(by("first-party").icon_url.as_deref(), Some("https://github.com/anthropics.png?size=64"));
|
||||
assert_eq!(by("unsafe-icon").icon_url.as_deref(), Some("https://github.com/anthropics.png?size=64"));
|
||||
|
||||
// Remote preview also resolves bundled icons to raw.githubusercontent.com at commit_sha.
|
||||
let remote_preview = preview_plugin(
|
||||
&gh,
|
||||
"anthropics/claude-plugins-official/plugins/champion-kit#main",
|
||||
None,
|
||||
Some("claude-plugins-official"),
|
||||
None,
|
||||
None,
|
||||
&cancel,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
remote_preview.icon_url.as_deref(),
|
||||
Some(
|
||||
"https://raw.githubusercontent.com/anthropics/claude-plugins-official/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/plugins/champion-kit/.claude-plugin/icon.png"
|
||||
)
|
||||
);
|
||||
|
||||
// Local marketplace & preview inline small local PNG icons as data URIs.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let local_plugin = tmp.path().join("my-local-plugin");
|
||||
write(
|
||||
&local_plugin.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"my-local-plugin","interface":{"logo":"./assets/logo.png"}}"#,
|
||||
);
|
||||
std::fs::create_dir_all(local_plugin.join("assets")).unwrap();
|
||||
std::fs::write(local_plugin.join("assets/logo.png"), b"\x89PNG\r\n\x1a\n").unwrap();
|
||||
|
||||
let local_browse = browse_marketplace(&gh, local_plugin.to_str().unwrap(), None, None, &cancel).unwrap();
|
||||
assert_eq!(local_browse.candidates.len(), 1);
|
||||
assert!(
|
||||
local_browse.candidates[0].icon_url.as_deref().is_some_and(|u| u.starts_with("data:image/png;base64,"))
|
||||
);
|
||||
|
||||
let local_preview =
|
||||
preview_plugin(&gh, local_plugin.to_str().unwrap(), None, None, None, None, &cancel).unwrap();
|
||||
assert!(local_preview.icon_url.as_deref().is_some_and(|u| u.starts_with("data:image/png;base64,")));
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ pub(crate) struct ProviderSpec {
|
||||
pub name: String,
|
||||
pub driver: Driver,
|
||||
pub command: String,
|
||||
pub managed_cli: Option<String>,
|
||||
pub args: Vec<String>,
|
||||
/// Number of trailing arguments added by the built-in agent's settings.
|
||||
pub additional_args_len: usize,
|
||||
@@ -42,6 +43,8 @@ pub(crate) struct ProviderSpec {
|
||||
/// How to sign in when the agent reports it needs authentication.
|
||||
pub login_hint: String,
|
||||
pub source: AgentSource,
|
||||
/// The built-in agent an instance copies (its identity); `None` for every other agent.
|
||||
pub base: Option<String>,
|
||||
}
|
||||
|
||||
/// `(id, name, driver, command line, sign-in hint)`. npm adapters are pinned so a
|
||||
@@ -90,6 +93,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
("vibe", "Mistral Vibe", Driver::Acp, &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
|
||||
("omp", "OMP", Driver::Acp, &["omp", "acp"], "Run `omp` in a terminal and sign in."),
|
||||
("hermes", "Hermes Agent", Driver::Acp, &["hermes", "acp"], "Run `hermes model` in a terminal."),
|
||||
("antigravity-acp", "Google Antigravity", Driver::Acp, &["agy", "acp"], "Run `agy acp --login` in a terminal."),
|
||||
];
|
||||
|
||||
fn builtins() -> Vec<ProviderSpec> {
|
||||
@@ -100,22 +104,33 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
name: (*name).into(),
|
||||
driver: *driver,
|
||||
command: cmd[0].into(),
|
||||
managed_cli: None,
|
||||
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
login_hint: (*hint).into(),
|
||||
source: AgentSource::Builtin,
|
||||
base: None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl ProviderSpec {
|
||||
/// The built-in id this agent is an instance of, or else its own id.
|
||||
pub(crate) fn base_id(&self) -> &str {
|
||||
self.base.as_deref().unwrap_or(&self.id)
|
||||
}
|
||||
|
||||
pub(crate) fn executable(&self) -> &str {
|
||||
self.managed_cli.as_deref().unwrap_or(&self.command)
|
||||
}
|
||||
|
||||
pub(crate) fn login_hint(&self, program: &Path) -> String {
|
||||
if !program.is_absolute() {
|
||||
return self.login_hint.clone();
|
||||
}
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let builtin = builtin_spec(&self.id);
|
||||
let builtin = builtin_spec(self.base_id());
|
||||
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
|
||||
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
|
||||
}
|
||||
@@ -135,7 +150,7 @@ impl ProviderSpec {
|
||||
.flatten();
|
||||
let hint = match terminal_args {
|
||||
Some(args) => {
|
||||
let command = render_login_command(program, args, cfg!(windows));
|
||||
let command = render_shell_command(program, args, cfg!(windows));
|
||||
format!("Run `{command}` in a terminal.")
|
||||
}
|
||||
None => self.login_hint(program),
|
||||
@@ -154,7 +169,7 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let is_copilot = is_copilot_provider(self.base_id());
|
||||
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
|
||||
let explicit_copilot_token =
|
||||
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
|
||||
@@ -179,10 +194,12 @@ impl ProviderSpec {
|
||||
}
|
||||
|
||||
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
|
||||
if self.driver != Driver::Acp {
|
||||
if let Some(program) = self.managed_cli.take() {
|
||||
self.command = program;
|
||||
} else if self.driver != Driver::Acp {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
if is_copilot_provider(self.base_id()) {
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
@@ -208,7 +225,7 @@ impl ProviderSpec {
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
if let Some((separate_cmd, separate_args)) = match self.base_id() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
@@ -222,7 +239,9 @@ impl ProviderSpec {
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
if let Some(builtin) = builtin_spec(self.base_id())
|
||||
&& !(matches!(self.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&self.id))
|
||||
{
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
@@ -230,7 +249,7 @@ impl ProviderSpec {
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
|
||||
if is_copilot_provider(&self.id) {
|
||||
if is_copilot_provider(self.base_id()) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
@@ -521,7 +540,7 @@ pub(crate) fn sanitize_copilot_env_with(
|
||||
}
|
||||
|
||||
fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>, windows: bool) -> String {
|
||||
let Some(builtin) = builtin_spec(&spec.id) else { return spec.login_hint.clone() };
|
||||
let Some(builtin) = builtin_spec(spec.base_id()) else { return spec.login_hint.clone() };
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let Some(rest) = spec.login_hint.strip_prefix(&prefix).filter(|rest| rest.starts_with([' ', '`'])) else {
|
||||
return spec.login_hint.clone();
|
||||
@@ -533,7 +552,7 @@ fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>
|
||||
return spec.login_hint.clone();
|
||||
}
|
||||
let (args, suffix) = rest.split_once('`').expect("built-in login hints delimit their command");
|
||||
let command = render_login_command(program, args.split_whitespace(), windows);
|
||||
let command = render_shell_command(program, args.split_whitespace(), windows);
|
||||
match suffix {
|
||||
" in a terminal." => format!("Run `{command}` in a terminal."),
|
||||
" in a terminal and sign in." => format!("Run `{command}` in a terminal and sign in."),
|
||||
@@ -541,7 +560,11 @@ fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>
|
||||
}
|
||||
}
|
||||
|
||||
fn render_login_command<'a>(program: &Path, args: impl IntoIterator<Item = &'a str>, windows: bool) -> String {
|
||||
pub(crate) fn render_shell_command<'a>(
|
||||
program: &Path,
|
||||
args: impl IntoIterator<Item = &'a str>,
|
||||
windows: bool,
|
||||
) -> String {
|
||||
let quote = |word: &str| {
|
||||
if windows { format!("'{}'", word.replace('\'', "''")) } else { format!("'{}'", word.replace('\'', "'\\''")) }
|
||||
};
|
||||
@@ -585,6 +608,13 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
|
||||
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
|
||||
}
|
||||
|
||||
/// Built-in CLI agents whose ACP Registry archive ships a separate ACP server binary
|
||||
/// rather than the CLI itself, so the built-in CLI's login subcommand does not apply
|
||||
/// to a registry install.
|
||||
fn registry_uses_separate_binary(id: &str) -> bool {
|
||||
id == "antigravity-acp"
|
||||
}
|
||||
|
||||
fn uses_package_runner(command: &str) -> bool {
|
||||
matches!(command, "npx" | "bunx" | "uvx")
|
||||
}
|
||||
@@ -598,6 +628,8 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
let builtin = builtin_spec(&spec.id);
|
||||
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
|
||||
Some(AgentCommandReadOnlyReason::Registry)
|
||||
} else if spec.base.is_some() {
|
||||
Some(AgentCommandReadOnlyReason::CustomAgent)
|
||||
} else if let Some(default) = &builtin {
|
||||
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
} else {
|
||||
@@ -610,22 +642,25 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
AgentProvider {
|
||||
id: spec.id.clone(),
|
||||
name: spec.name.clone(),
|
||||
command: std::iter::once(spec.command.as_str())
|
||||
command: std::iter::once(spec.executable())
|
||||
.chain(spec.args.iter().map(String::as_str))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" "),
|
||||
program: spec.command.clone(),
|
||||
program: spec.executable().to_owned(),
|
||||
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))),
|
||||
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(spec.executable(), &spec.env))),
|
||||
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed_with_env(&spec.command, &spec.env),
|
||||
installed: installed_with_env(spec.executable(), &spec.env),
|
||||
cli_install_command: None,
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
base: spec.base.clone(),
|
||||
can_duplicate: builtin.is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
thought_levels: BTreeMap::new(),
|
||||
@@ -664,13 +699,17 @@ pub(crate) fn set_builtin_additional_args(
|
||||
})
|
||||
}
|
||||
|
||||
/// The environment built-in `id` starts with, through its agent file (empty clears it).
|
||||
/// The environment built-in `id` (or an instance of one) starts with, through its agent file
|
||||
/// (empty clears it).
|
||||
pub(crate) fn set_builtin_env(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
if builtin_spec(id).is_none() {
|
||||
return set_instance_env(custom_dir, secrets, id, env);
|
||||
}
|
||||
if id == "copilot" {
|
||||
let file = custom_dir.join("copilot.toml");
|
||||
if file.try_exists()?
|
||||
@@ -702,6 +741,26 @@ pub(crate) fn set_builtin_env(
|
||||
})
|
||||
}
|
||||
|
||||
/// An instance's environment is all its own: never merged with its base's.
|
||||
fn set_instance_env(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
id: &str,
|
||||
env: BTreeMap<String, String>,
|
||||
) -> IdeResult<()> {
|
||||
let id = validated_custom_id(id)?;
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
let mut agent = match CustomAgent::read_with(&file, &id, secrets) {
|
||||
Ok(agent) if agent.registry.is_none() && agent.base.as_deref().is_some_and(|b| builtin_spec(b).is_some()) => {
|
||||
agent
|
||||
}
|
||||
_ => return Err(IdeError::invalid(format!("{id} is not a built-in agent or an instance of one"))),
|
||||
};
|
||||
agent.env = env;
|
||||
agent.write_with(&file, &id, secrets)
|
||||
}
|
||||
|
||||
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
|
||||
fn update_builtin(
|
||||
custom_dir: &Path,
|
||||
@@ -718,6 +777,7 @@ fn update_builtin(
|
||||
} else {
|
||||
CustomAgent {
|
||||
name: Some(builtin.name.clone()),
|
||||
base: None,
|
||||
driver: builtin.driver,
|
||||
command: builtin.command.clone(),
|
||||
args: builtin.args.clone(),
|
||||
@@ -747,9 +807,24 @@ fn update_builtin(
|
||||
agent.write_with(&file, id, secrets)
|
||||
}
|
||||
|
||||
/// Project backends can share a config directory. Keep the ID check, credential
|
||||
/// changes and file write in the same critical section.
|
||||
fn lock_custom_agents(custom_dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::create_dir_all(custom_dir)?;
|
||||
let lock = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(custom_dir.join(".custom-agents.lock"))?;
|
||||
lock.lock()?;
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
/// Saves a new custom agent; refuses built-in and ACP Registry ids, taken ids
|
||||
/// and an empty command. The id is also the agent file's name, so it must be
|
||||
/// a safe file stem.
|
||||
/// a safe file stem. An instance of a built-in (`base`) may leave the command
|
||||
/// empty to launch as its base does.
|
||||
pub(crate) fn save_custom(
|
||||
custom_dir: &Path,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
@@ -759,9 +834,20 @@ pub(crate) fn save_custom(
|
||||
if builtin_spec(&id).is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is a built-in agent; change its command instead")));
|
||||
}
|
||||
if input.command.trim().is_empty() {
|
||||
let base = match input.base.as_deref() {
|
||||
Some(base) => {
|
||||
Some(builtin_spec(base).ok_or_else(|| IdeError::invalid(format!("{base} is not a built-in agent")))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let inherits = input.command.trim().is_empty();
|
||||
if inherits && base.is_none() {
|
||||
return Err(IdeError::invalid("the agent command must not be empty"));
|
||||
}
|
||||
if inherits && !input.args.is_empty() {
|
||||
return Err(IdeError::invalid("an agent without its own command takes no arguments"));
|
||||
}
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
if file.try_exists()? {
|
||||
if CustomAgent::read(&file).is_ok_and(|a| a.registry.is_some()) {
|
||||
@@ -773,8 +859,9 @@ pub(crate) fn save_custom(
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some(input.name.clone()),
|
||||
driver: Driver::Acp,
|
||||
command: input.command.clone(),
|
||||
driver: base.as_ref().filter(|_| !inherits).map_or(Driver::Acp, |b| b.driver),
|
||||
command: if inherits { String::new() } else { input.command.clone() },
|
||||
base: base.map(|b| b.id),
|
||||
args: input.args.clone(),
|
||||
additional_args: Vec::new(),
|
||||
env: input.env.clone(),
|
||||
@@ -790,6 +877,7 @@ pub(crate) fn remove_custom(custom_dir: &Path, secrets: Option<&dyn EnvSecrets>,
|
||||
if builtin_spec(id).is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is a built-in agent and cannot be removed")));
|
||||
}
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
let agent =
|
||||
CustomAgent::read(&file).map_err(|_| IdeError::not_found(format!("there is no custom agent '{id}'")))?;
|
||||
@@ -829,6 +917,7 @@ pub(crate) fn import_acp(
|
||||
}
|
||||
let parsed: AcpJson =
|
||||
serde_json::from_str(text).map_err(|e| IdeError::invalid(format!("not an acp.json file: {e}")))?;
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let mut outcomes = Vec::with_capacity(parsed.agent_servers.len());
|
||||
for (name, server) in parsed.agent_servers {
|
||||
let id = slugify_id(&name);
|
||||
@@ -844,6 +933,7 @@ pub(crate) fn import_acp(
|
||||
} else {
|
||||
CustomAgent {
|
||||
name: Some(outcome.name.clone()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: server.command,
|
||||
args: server.args,
|
||||
@@ -886,8 +976,12 @@ pub(crate) fn slugify_id(name: &str) -> String {
|
||||
pub(crate) struct CustomAgent {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// The built-in agent this one is an instance of; without a `command` it launches as the base does.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub base: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Driver::is_acp")]
|
||||
pub driver: Driver,
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub command: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub args: Vec<String>,
|
||||
@@ -916,9 +1010,13 @@ impl Driver {
|
||||
|
||||
impl CustomAgent {
|
||||
pub(crate) fn read(path: &Path) -> Result<Self, String> {
|
||||
std::fs::read_to_string(path)
|
||||
let agent = std::fs::read_to_string(path)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))
|
||||
.and_then(|t| toml::from_str::<CustomAgent>(&t).map_err(|e| e.to_string()))?;
|
||||
if agent.command.is_empty() && agent.base.is_none() {
|
||||
return Err("missing field `command`".into());
|
||||
}
|
||||
Ok(agent)
|
||||
}
|
||||
|
||||
/// Writes the file atomically (a reader never sees half of it).
|
||||
@@ -990,7 +1088,8 @@ fn forget_env(secrets: Option<&dyn EnvSecrets>, id: &str, keep: &[String]) {
|
||||
}
|
||||
|
||||
/// Built-in agents, then the `*.toml` agents of `custom_dir`; a custom agent with a
|
||||
/// built-in id replaces it.
|
||||
/// built-in id replaces it. Instances of a built-in (`base`) are resolved last, against
|
||||
/// the built-in as its own file left it, so file order does not matter.
|
||||
pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) -> Vec<ProviderSpec> {
|
||||
let mut specs = builtins();
|
||||
let mut files: Vec<PathBuf> = custom_dir
|
||||
@@ -1002,6 +1101,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
.filter(|p| p.extension().is_some_and(|e| e == "toml"))
|
||||
.collect();
|
||||
files.sort();
|
||||
let mut instances = Vec::new();
|
||||
for path in files {
|
||||
let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else { continue };
|
||||
let explicit_driver = std::fs::read_to_string(&path)
|
||||
@@ -1015,6 +1115,18 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if let Some(base) = agent.base.clone() {
|
||||
if builtin_spec(&id).is_some() {
|
||||
tracing::warn!("skipping agent {}: a built-in agent cannot have a base", path.display());
|
||||
} else if agent.registry.is_some() {
|
||||
tracing::warn!("skipping agent {}: an ACP Registry install cannot have a base", path.display());
|
||||
} else if builtin_spec(&base).is_none() {
|
||||
tracing::warn!("skipping agent {}: {base} is not a built-in agent", path.display());
|
||||
} else {
|
||||
instances.push((id, agent));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let env: Vec<(String, String)> = agent.env.into_iter().collect();
|
||||
let source = match agent.registry {
|
||||
Some(r) => AgentSource::Registry { version: r.version, update: None },
|
||||
@@ -1024,16 +1136,20 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
name: agent.name.unwrap_or_else(|| id.clone()),
|
||||
driver: agent.driver,
|
||||
command: agent.command,
|
||||
managed_cli: None,
|
||||
args: agent.args,
|
||||
additional_args_len: 0,
|
||||
env,
|
||||
login_hint: "Sign in with the agent's own command line first.".into(),
|
||||
source,
|
||||
base: None,
|
||||
id,
|
||||
};
|
||||
match specs.iter_mut().find(|s| s.id == spec.id) {
|
||||
Some(existing) => {
|
||||
spec.login_hint = existing.login_hint.clone();
|
||||
if !(matches!(spec.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&spec.id)) {
|
||||
spec.login_hint = existing.login_hint.clone();
|
||||
}
|
||||
if !explicit_driver && existing.driver == Driver::Copilot && spec.driver == Driver::Acp {
|
||||
// Registry installs (`github-copilot-cli`) record `args = ["--acp"]` with no
|
||||
// `driver`; upgrade them in place to the native headless driver (which
|
||||
@@ -1054,6 +1170,34 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
None => specs.push(spec),
|
||||
}
|
||||
}
|
||||
for (id, agent) in instances {
|
||||
let base = agent.base.expect("instances have a base");
|
||||
let Some(base_spec) = specs.iter().find(|s| s.id == base && s.base.is_none()) else { continue };
|
||||
let (driver, command, args) = if agent.command.is_empty() {
|
||||
(base_spec.driver, base_spec.command.clone(), base_spec.args.clone())
|
||||
} else {
|
||||
(agent.driver, agent.command, agent.args)
|
||||
};
|
||||
let login_hint = base_spec.login_hint.clone();
|
||||
// Copies of one agent follow it, in the order of their file names.
|
||||
let at = specs.iter().rposition(|s| s.base_id() == base).map_or(specs.len(), |i| i + 1);
|
||||
specs.insert(
|
||||
at,
|
||||
ProviderSpec {
|
||||
name: agent.name.unwrap_or_else(|| id.clone()),
|
||||
driver,
|
||||
command,
|
||||
managed_cli: None,
|
||||
args,
|
||||
additional_args_len: 0,
|
||||
env: agent.env.into_iter().collect(),
|
||||
login_hint,
|
||||
source: AgentSource::Custom,
|
||||
base: Some(base),
|
||||
id,
|
||||
},
|
||||
);
|
||||
}
|
||||
specs
|
||||
}
|
||||
|
||||
@@ -1102,6 +1246,56 @@ mod tests {
|
||||
assert_eq!(info.login_hint.as_deref(), Some("Run `hermes model` in a terminal."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn antigravity_is_built_in_over_acp() {
|
||||
let spec = builtin_spec("antigravity-acp").unwrap();
|
||||
assert_eq!(spec.driver, Driver::Acp);
|
||||
assert!(!is_builtin("antigravity-acp"));
|
||||
let info = describe(&spec);
|
||||
assert_eq!((info.name.as_str(), info.command.as_str()), ("Google Antigravity", "agy acp"));
|
||||
assert_eq!(info.login_hint.as_deref(), Some("Run `agy acp --login` in a terminal."));
|
||||
assert!(info.command_editable);
|
||||
assert_eq!(info.additional_args, Some(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_antigravity_does_not_inherit_cli_login_subcommand() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join(if cfg!(windows) { "agy_acp_server.exe" } else { "agy_acp_server.par" });
|
||||
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();
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some("Google Antigravity".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: bin.to_string_lossy().into_owned(),
|
||||
args: Vec::new(),
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "antigravity-acp".into(), version: "1.5.2".into() }),
|
||||
}
|
||||
.write(&dir.path().join("antigravity-acp.toml"))
|
||||
.unwrap();
|
||||
|
||||
let reg = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
|
||||
assert_eq!(reg.source, AgentSource::Registry { version: "1.5.2".into(), update: None });
|
||||
assert_eq!(reg.login_hint, "Sign in with the agent's own command line first.");
|
||||
assert_eq!(describe(®).login_hint.as_deref(), Some("Sign in with the agent's own command line first."));
|
||||
assert!(reg.login_launch(dir.path(), None).is_none());
|
||||
let terminal_launch = reg.login_launch(dir.path(), Some(&["--login".into()])).unwrap();
|
||||
assert_eq!(terminal_launch.program, bin);
|
||||
assert_eq!(terminal_launch.args, ["--login"]);
|
||||
|
||||
std::fs::remove_file(dir.path().join("antigravity-acp.toml")).unwrap();
|
||||
let builtin = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
|
||||
assert_eq!(builtin.source, AgentSource::Builtin);
|
||||
assert_eq!((builtin.command.as_str(), builtin.args.as_slice()), ("agy", &["acp".to_owned()][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qoder_global_and_cn_editions_are_both_built_in() {
|
||||
let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap());
|
||||
@@ -1154,6 +1348,7 @@ mod tests {
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert_eq!(args("antigravity-acp"), ["acp", "--login"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
@@ -1228,7 +1423,7 @@ mod tests {
|
||||
(true, "& '/agent''s tools/$cli' auth login --account 'user name' 'a''b' '$token' ''"),
|
||||
] {
|
||||
assert_eq!(
|
||||
render_login_command(
|
||||
render_shell_command(
|
||||
Path::new("/agent's tools/$cli"),
|
||||
["auth", "login", "--account", "user name", "a'b", "$token", ""],
|
||||
windows
|
||||
@@ -1280,10 +1475,10 @@ mod tests {
|
||||
for p in &defaults {
|
||||
assert_eq!(p.source, AgentSource::Builtin);
|
||||
assert!(p.default_program.is_some());
|
||||
assert_eq!(p.command_editable, !p.id.ends_with("-acp"));
|
||||
assert_eq!(p.command_editable, !uses_package_runner(&p.program));
|
||||
assert_eq!(
|
||||
p.command_read_only_reason,
|
||||
p.id.ends_with("-acp").then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
uses_package_runner(&p.program).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
);
|
||||
}
|
||||
set_builtin_command(dir.path(), None, "codex", Some("/path with spaces/codex")).unwrap();
|
||||
@@ -1416,6 +1611,7 @@ mod tests {
|
||||
let file = dir.path().join("copilot.toml");
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/tools/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
@@ -1473,6 +1669,7 @@ mod tests {
|
||||
let path = dir.path().join("codex.toml");
|
||||
CustomAgent {
|
||||
name: None,
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "amp".into(),
|
||||
args: vec![],
|
||||
@@ -1499,6 +1696,7 @@ mod tests {
|
||||
for field in ["name", "driver", "args", "env", "unnamed"] {
|
||||
let mut agent = CustomAgent {
|
||||
name: Some("Claude Code".into()),
|
||||
base: None,
|
||||
driver: Driver::Claude,
|
||||
command: "/old/claude".into(),
|
||||
args: vec![],
|
||||
@@ -1553,6 +1751,7 @@ mod tests {
|
||||
let path = dir.path().join("agents").join("amp-acp.toml");
|
||||
let agent = CustomAgent {
|
||||
name: Some("Amp".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
|
||||
args: vec!["acp".into()],
|
||||
@@ -1573,6 +1772,7 @@ mod tests {
|
||||
CustomAgentInput {
|
||||
id: id.into(),
|
||||
name: "Mine".into(),
|
||||
base: None,
|
||||
command: "/opt/mine".into(),
|
||||
args: vec!["acp".into()],
|
||||
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
|
||||
@@ -1794,4 +1994,188 @@ github.com
|
||||
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
}
|
||||
|
||||
fn write_agent(dir: &Path, id: &str, text: &str) {
|
||||
std::fs::write(dir.join(format!("{id}.toml")), text).unwrap();
|
||||
}
|
||||
|
||||
fn spec_of(dir: &Path, id: &str) -> Option<ProviderSpec> {
|
||||
load(Some(dir), None).into_iter().find(|s| s.id == id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_inherit_the_base_launch_whatever_the_file_order() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let instance =
|
||||
"base = \"claude\"\nname = \"Claude Work\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n";
|
||||
// `a-claude` sorts before the base's own file, `z-claude` after it.
|
||||
write_agent(dir.path(), "a-claude", instance);
|
||||
write_agent(dir.path(), "z-claude", instance);
|
||||
write_agent(
|
||||
dir.path(),
|
||||
"claude",
|
||||
"name = \"Claude Code\"\ndriver = \"claude\"\ncommand = \"/opt/claude\"\n[env]\nB = \"1\"\n",
|
||||
);
|
||||
let builtin = builtin_spec("claude").unwrap();
|
||||
for id in ["a-claude", "z-claude"] {
|
||||
let spec = spec_of(dir.path(), id).unwrap();
|
||||
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Claude, "/opt/claude"), "{id}");
|
||||
assert_eq!(spec.args, builtin.args);
|
||||
assert_eq!(spec.env, [("CLAUDE_CONFIG_DIR".to_owned(), "/home/me/.claude-work".to_owned())]);
|
||||
assert_eq!(spec.login_hint, builtin.login_hint);
|
||||
assert_eq!(
|
||||
(&spec.source, spec.base.as_deref(), spec.base_id()),
|
||||
(&AgentSource::Custom, Some("claude"), "claude")
|
||||
);
|
||||
assert_eq!(spec.name, "Claude Work");
|
||||
}
|
||||
std::fs::remove_file(dir.path().join("claude.toml")).unwrap();
|
||||
assert_eq!(spec_of(dir.path(), "a-claude").unwrap().command, "claude");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_follow_their_base_in_the_list() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "z-claude", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "a-claude", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "codex-2", "base = \"codex\"\n");
|
||||
write_agent(dir.path(), "mine", "command = \"/opt/mine\"\n");
|
||||
let ids: Vec<String> = load(Some(dir.path()), None).into_iter().map(|s| s.id).collect();
|
||||
let at = |id: &str| ids.iter().position(|i| i == id).unwrap();
|
||||
assert_eq!((at("a-claude"), at("z-claude")), (at("claude") + 1, at("claude") + 2));
|
||||
assert_eq!(at("codex-2"), at("codex") + 1);
|
||||
assert_eq!(at("mine"), ids.len() - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_with_its_own_command_keeps_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(
|
||||
dir.path(),
|
||||
"codex-2",
|
||||
"base = \"codex\"\ndriver = \"codex\"\ncommand = \"/opt/codex2\"\nargs = [\"app-server\", \"-v\"]\n",
|
||||
);
|
||||
write_agent(dir.path(), "codex", "driver = \"codex\"\ncommand = \"/opt/codex\"\nargs = [\"app-server\"]\n");
|
||||
let spec = spec_of(dir.path(), "codex-2").unwrap();
|
||||
assert_eq!((spec.driver, spec.command.as_str()), (Driver::Codex, "/opt/codex2"));
|
||||
assert_eq!(spec.args, ["app-server", "-v"]);
|
||||
assert_eq!(spec.base.as_deref(), Some("codex"));
|
||||
assert_eq!(spec.login_hint, builtin_spec("codex").unwrap().login_hint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_instances_are_skipped() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "unknown-base", "base = \"nope\"\n");
|
||||
write_agent(dir.path(), "first", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "chained", "base = \"first\"\n");
|
||||
write_agent(dir.path(), "codex", "base = \"claude\"\n");
|
||||
write_agent(dir.path(), "no-command", "name = \"Nothing\"\n");
|
||||
let specs = load(Some(dir.path()), None);
|
||||
let ids: Vec<&str> = specs.iter().filter(|s| s.source != AgentSource::Builtin).map(|s| s.id.as_str()).collect();
|
||||
assert_eq!(ids, ["first"]);
|
||||
assert_eq!(specs.iter().find(|s| s.id == "codex").unwrap(), &builtin_spec("codex").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_custom_writes_instances() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let instance = |id: &str, base: &str| CustomAgentInput {
|
||||
base: Some(base.into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
..custom_input(id)
|
||||
};
|
||||
save_custom(dir.path(), None, &instance("work", "claude")).unwrap();
|
||||
let text = std::fs::read_to_string(dir.path().join("work.toml")).unwrap();
|
||||
assert!(text.contains("base = \"claude\"") && !text.contains("command") && !text.contains("driver"), "{text}");
|
||||
let spec = spec_of(dir.path(), "work").unwrap();
|
||||
assert_eq!(
|
||||
(spec.driver, spec.command.as_str(), spec.base.as_deref()),
|
||||
(Driver::Claude, "claude", Some("claude"))
|
||||
);
|
||||
|
||||
save_custom(dir.path(), None, &CustomAgentInput { command: "/opt/codex".into(), ..instance("own", "codex") })
|
||||
.unwrap();
|
||||
let own = spec_of(dir.path(), "own").unwrap();
|
||||
assert_eq!((own.driver, own.command.as_str()), (Driver::Codex, "/opt/codex"));
|
||||
|
||||
save_custom(dir.path(), None, &instance("work", "claude")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("other", "nope")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("other", "work")).unwrap_err();
|
||||
save_custom(dir.path(), None, &instance("codex", "claude")).unwrap_err();
|
||||
save_custom(dir.path(), None, &CustomAgentInput { args: vec!["x".into()], ..instance("other", "claude") })
|
||||
.unwrap_err();
|
||||
assert!(!dir.path().join("other.toml").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instances_describe_their_base() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
write_agent(dir.path(), "work", "base = \"claude\"\n");
|
||||
save_custom(dir.path(), None, &custom_input("mine")).unwrap();
|
||||
let info = |id: &str| describe(&spec_of(dir.path(), id).unwrap());
|
||||
let work = info("work");
|
||||
assert_eq!(work.base.as_deref(), Some("claude"));
|
||||
assert!(!work.can_duplicate && !work.can_check_cli_update && !work.command_editable);
|
||||
assert_eq!(work.command_read_only_reason, Some(AgentCommandReadOnlyReason::CustomAgent));
|
||||
assert_eq!(work.login_hint.as_deref(), Some("Run `claude` in a terminal and sign in."));
|
||||
let claude = info("claude");
|
||||
assert!(claude.can_duplicate && claude.base.is_none());
|
||||
let mine = info("mine");
|
||||
assert!(!mine.can_duplicate && mine.base.is_none());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn instances_sign_in_with_their_own_environment() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join("claude");
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
write_agent(dir.path(), "claude", &format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy()));
|
||||
write_agent(dir.path(), "work", "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n");
|
||||
let spec = spec_of(dir.path(), "work").unwrap();
|
||||
assert!(spec.can_sign_in(dir.path(), None));
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert!(launch.args.is_empty());
|
||||
assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_environment_is_set_and_forgotten_through_the_secrets() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let secrets = MemorySecrets::default();
|
||||
let s = Some(&secrets as &dyn EnvSecrets);
|
||||
let instance = CustomAgentInput {
|
||||
base: Some("copilot".into()),
|
||||
command: String::new(),
|
||||
args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
..custom_input("copilot-work")
|
||||
};
|
||||
save_custom(dir.path(), s, &instance).unwrap();
|
||||
let env = BTreeMap::from([
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.to_owned(), "octo-work".to_owned()),
|
||||
("COPILOT_HOME".to_owned(), "/home/me/.copilot-work".to_owned()),
|
||||
]);
|
||||
set_builtin_env(dir.path(), s, "copilot-work", env.clone()).unwrap();
|
||||
let text = std::fs::read_to_string(dir.path().join("copilot-work.toml")).unwrap();
|
||||
assert!(text.contains("base = \"copilot\"") && !text.contains("octo-work"), "{text}");
|
||||
let spec = load(Some(dir.path()), s).into_iter().find(|p| p.id == "copilot-work").unwrap();
|
||||
assert_eq!(describe(&spec).env, env);
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("octo-work"));
|
||||
assert!(load(Some(dir.path()), s).iter().find(|p| p.id == "copilot").unwrap().env.is_empty());
|
||||
|
||||
save_custom(dir.path(), s, &custom_input("mine")).unwrap();
|
||||
set_builtin_env(dir.path(), s, "mine", env.clone()).unwrap_err();
|
||||
write_agent(dir.path(), "bad-base", "base = \"nope\"\n");
|
||||
set_builtin_env(dir.path(), s, "bad-base", env).unwrap_err();
|
||||
assert!(secrets.keys("agent/bad-base/").is_empty());
|
||||
remove_custom(dir.path(), s, "copilot-work").unwrap();
|
||||
assert!(!dir.path().join("copilot-work.toml").exists());
|
||||
assert!(secrets.keys("agent/copilot-work/").is_empty());
|
||||
}
|
||||
}
|
||||
@@ -587,6 +587,7 @@ fn install_entry_with(
|
||||
}
|
||||
let agent = CustomAgent {
|
||||
name: Some(entry.name.clone()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: exe.to_string_lossy().into_owned(),
|
||||
args,
|
||||
@@ -985,6 +986,7 @@ mod tests {
|
||||
let entries = parse(INDEX).unwrap();
|
||||
let installed = |id: &str, version: &str| CustomAgent {
|
||||
name: None,
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/x".into(),
|
||||
args: vec![],
|
||||
@@ -1222,6 +1224,7 @@ esac
|
||||
|
||||
CustomAgent {
|
||||
name: Some("GitHub Copilot".into()),
|
||||
base: None,
|
||||
driver: Driver::Acp,
|
||||
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
|
||||
args: vec!["--acp".into()],
|
||||
|
||||
@@ -22,6 +22,7 @@ fn paths(dir: &Path) -> AgentPaths {
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
|
||||
@@ -296,6 +296,24 @@ pub fn discover_skills_with_agent_plugins(
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
) -> Vec<AgentSkill> {
|
||||
discover_skills_with_indexed_files(workspaces, home, plugin_skill_dirs, agent_plugin_roots, &[])
|
||||
}
|
||||
|
||||
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
|
||||
/// resolved agent plugin bundle roots (`agent_plugin_roots`), and deeply nested workspace packages
|
||||
/// inferred from `indexed_skill_files` (typically `ProjectIndex::files_with_names(&["SKILL.md"])`).
|
||||
///
|
||||
/// Direct workspace roots and shallow monorepo packages (depth 1–2) are scanned directly on disk
|
||||
/// first so discovery works before indexing finishes and preserves shallow-over-deep precedence.
|
||||
/// Any deeper package roots discovered via `indexed_skill_files` are scanned next, sorted from
|
||||
/// shallowest to deepest and deduplicated by canonical path.
|
||||
pub fn discover_skills_with_indexed_files(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
indexed_skill_files: &[PathBuf],
|
||||
) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
|
||||
@@ -321,6 +339,13 @@ pub fn discover_skills_with_agent_plugins(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Deeply nested packages (arbitrary depth) surfaced by the project file index.
|
||||
for sub in indexed_package_roots(&all_workspaces, indexed_skill_files) {
|
||||
let sub_canon = dunce::canonicalize(&sub).unwrap_or_else(|_| sub.clone());
|
||||
if seen_workspaces.insert(sub_canon) {
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (sub.join(rel), *source)));
|
||||
}
|
||||
}
|
||||
if let Some(home) = home {
|
||||
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
|
||||
}
|
||||
@@ -413,6 +438,74 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Extracts workspace package roots from indexed `SKILL.md` file paths.
|
||||
///
|
||||
/// Only accepts `SKILL.md` files located inside one of [`WORKSPACE_ROOTS`] at depth 0, 1, or 2
|
||||
/// below `<dot_dir>/skills` (`skills/SKILL.md`, `skills/<name>/SKILL.md`, or
|
||||
/// `skills/<category>/<name>/SKILL.md`), rejecting unrelated fixture/doc `SKILL.md` files as well
|
||||
/// as packages under hidden directories or [`SKIP_MONOREPO_DIRS`]. Returns roots sorted from
|
||||
/// shallowest to deepest (then lexicographically) so shallower packages always win on name clashes.
|
||||
fn indexed_package_roots(workspaces: &[PathBuf], indexed_skill_files: &[PathBuf]) -> Vec<PathBuf> {
|
||||
if workspaces.is_empty() || indexed_skill_files.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let workspace_pairs: Vec<(&Path, Option<PathBuf>)> =
|
||||
workspaces.iter().map(|ws| (ws.as_path(), dunce::canonicalize(ws).ok())).collect();
|
||||
let mut candidates: Vec<(usize, PathBuf)> = Vec::new();
|
||||
for file in indexed_skill_files {
|
||||
let Some(pkg_root) = package_root_of_skill_file(file) else { continue };
|
||||
let Some(rel) = relative_within_workspaces(&pkg_root, &workspace_pairs) else { continue };
|
||||
if rel.components().any(|c| match c {
|
||||
std::path::Component::Normal(seg) => {
|
||||
seg.to_str().is_none_or(|s| s.starts_with('.') || SKIP_MONOREPO_DIRS.contains(&s))
|
||||
}
|
||||
_ => true,
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
if !pkg_root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
candidates.push((rel.components().count(), pkg_root));
|
||||
}
|
||||
candidates.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
|
||||
candidates.dedup_by(|a, b| a.1 == b.1);
|
||||
candidates.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
||||
/// If `skill_md` sits inside `<pkg>/<dot_dir>/skills[/<category>][/<name>]/SKILL.md` for one of
|
||||
/// [`WORKSPACE_ROOTS`], returns `<pkg>`.
|
||||
fn package_root_of_skill_file(skill_md: &Path) -> Option<PathBuf> {
|
||||
if skill_md.file_name().and_then(|n| n.to_str()) != Some("SKILL.md") {
|
||||
return None;
|
||||
}
|
||||
let mut cur = skill_md.parent()?;
|
||||
for _ in 0..=2 {
|
||||
if cur.file_name().and_then(|n| n.to_str()) == Some("skills")
|
||||
&& let Some(dot_dir) = cur.parent()
|
||||
&& let Some(dot_name) = dot_dir.file_name().and_then(|n| n.to_str())
|
||||
&& WORKSPACE_ROOTS.iter().any(|(rel, _)| rel.split('/').next() == Some(dot_name))
|
||||
&& let Some(pkg_root) = dot_dir.parent()
|
||||
{
|
||||
return Some(pkg_root.to_path_buf());
|
||||
}
|
||||
cur = cur.parent()?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn relative_within_workspaces(pkg_root: &Path, workspaces: &[(&Path, Option<PathBuf>)]) -> Option<PathBuf> {
|
||||
let pick_shortest =
|
||||
|iter: &mut dyn Iterator<Item = &Path>| iter.min_by_key(|rel| rel.components().count()).map(Path::to_path_buf);
|
||||
let mut direct = workspaces.iter().filter_map(|(ws, _)| pkg_root.strip_prefix(ws).ok());
|
||||
if let Some(rel) = pick_shortest(&mut direct) {
|
||||
return Some(rel);
|
||||
}
|
||||
let canon_pkg = dunce::canonicalize(pkg_root).ok()?;
|
||||
let mut canonical = workspaces.iter().filter_map(|(_, canon_ws)| canon_pkg.strip_prefix(canon_ws.as_ref()?).ok());
|
||||
pick_shortest(&mut canonical)
|
||||
}
|
||||
|
||||
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
|
||||
/// category folders, validated.
|
||||
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
|
||||
@@ -1469,4 +1562,65 @@ mod tests {
|
||||
let staged_md = std::fs::read_to_string(farm.join("copilot/verify-ux/SKILL.md")).unwrap();
|
||||
assert_eq!(staged_md, raw_md);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_skill_files_discover_deep_monorepo_skills_and_respect_filters_and_precedence() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let ws = root.join("ws");
|
||||
|
||||
let deep_grafana =
|
||||
ws.join("mango/tools/mai-grafana-dashboards/.github/skills/edit-grafana-dashboards/SKILL.md");
|
||||
let deep_category = ws.join("a/b/c/.agents/skills/ops/deploy/SKILL.md");
|
||||
let deep_named_skills = ws.join("a/b/c/.claude/skills/skills/SKILL.md");
|
||||
let shallow_clash = ws.join("pkg/.agents/skills/shared/SKILL.md");
|
||||
let deep_clash = ws.join("a/b/c/.github/skills/shared/SKILL.md");
|
||||
let depth3_clash = ws.join("x/y/z/.github/skills/depth-race/SKILL.md");
|
||||
let depth4_clash = ws.join("x/y/z/w/.agents/skills/depth-race/SKILL.md");
|
||||
let fixture_skill = ws.join("crates/ide-plugin/tests/fixtures/agent-skills/skills/fixture-only/SKILL.md");
|
||||
let hidden_dir_skill = ws.join(".worktrees/branch/.github/skills/wt-only/SKILL.md");
|
||||
let target_dir_skill = ws.join("crates/app/target/gen/.github/skills/build-only/SKILL.md");
|
||||
|
||||
write(&deep_grafana, "---\nname: edit-grafana-dashboards\ndescription: Edit Grafana dashboards\n---\n");
|
||||
write(&deep_category, "---\nname: deploy\ndescription: Deploy service\n---\n");
|
||||
write(&deep_named_skills, "---\nname: skills\ndescription: Skill named skills\n---\n");
|
||||
write(&shallow_clash, "---\nname: shared\ndescription: Shallow copy\n---\n");
|
||||
write(&deep_clash, "---\nname: shared\ndescription: Deep copy\n---\n");
|
||||
write(&depth3_clash, "---\nname: depth-race\ndescription: Depth 3 wins\n---\n");
|
||||
write(&depth4_clash, "---\nname: depth-race\ndescription: Depth 4 loses\n---\n");
|
||||
write(&fixture_skill, "---\nname: fixture-only\ndescription: Fixture not under a skill root\n---\n");
|
||||
write(&hidden_dir_skill, "---\nname: wt-only\ndescription: Inside hidden dir\n---\n");
|
||||
write(&target_dir_skill, "---\nname: build-only\ndescription: Inside target dir\n---\n");
|
||||
|
||||
// Without indexed files, depth-3+ packages are beyond the 2-level direct walk.
|
||||
let shallow_only = discover_skills(&ws, None);
|
||||
assert!(shallow_only.iter().all(|s| s.name != "edit-grafana-dashboards"));
|
||||
assert!(shallow_only.iter().any(|s| s.name == "shared" && s.description == "Shallow copy"));
|
||||
|
||||
// Passing indexed `SKILL.md` paths (even in reversed depth order) surfaces deep skills
|
||||
// while keeping shallow-over-deep precedence and ignoring fixtures/hidden/build dirs.
|
||||
let indexed = vec![
|
||||
depth4_clash,
|
||||
depth3_clash,
|
||||
deep_clash,
|
||||
deep_grafana,
|
||||
deep_category,
|
||||
deep_named_skills,
|
||||
fixture_skill,
|
||||
hidden_dir_skill,
|
||||
target_dir_skill,
|
||||
];
|
||||
let found = discover_skills_with_indexed_files(std::slice::from_ref(&ws), None, &[], &[], &indexed);
|
||||
let by = |n: &str| found.iter().find(|s| s.name == n);
|
||||
|
||||
let grafana = by("edit-grafana-dashboards").expect("depth-3 .github/skills discovered");
|
||||
assert_eq!(grafana.source, AgentSkillSource::GithubWorkspace);
|
||||
assert!(by("deploy").is_some(), "category skill under depth-3 package discovered");
|
||||
assert!(by("skills").is_some(), "skill named `skills` under depth-3 package discovered");
|
||||
assert_eq!(by("shared").unwrap().description, "Shallow copy", "shallow package beats deep package");
|
||||
assert_eq!(by("depth-race").unwrap().description, "Depth 3 wins", "depth 3 beats depth 4");
|
||||
assert!(by("fixture-only").is_none(), "unrelated fixture SKILL.md ignored");
|
||||
assert!(by("wt-only").is_none(), "hidden directory tree ignored");
|
||||
assert!(by("build-only").is_none(), "SKIP_MONOREPO_DIRS tree ignored");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,7 +3,7 @@
|
||||
use crate::model::{AgentEntry, AgentImage, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
|
||||
use ide_core::IpcPath;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// Tool output kept per call; longer output keeps its tail.
|
||||
const MAX_OUTPUT: usize = 64 * 1024;
|
||||
@@ -20,6 +20,8 @@ pub(crate) struct Timeline {
|
||||
cards: HashMap<String, usize>,
|
||||
/// Session messages, by message id.
|
||||
messages: HashMap<String, usize>,
|
||||
/// The next agent text starts an entry of its own (see [`Timeline::seal`]).
|
||||
sealed: bool,
|
||||
}
|
||||
|
||||
/// What a `session/update` changed in the timeline.
|
||||
@@ -138,10 +140,17 @@ impl Timeline {
|
||||
out
|
||||
}
|
||||
|
||||
/// A prompt is being sent: text the agent sent before it (a startup notice) is not the
|
||||
/// start of the reply, so the reply's text gets an entry of its own.
|
||||
pub fn seal(&mut self) {
|
||||
self.sealed = true;
|
||||
}
|
||||
|
||||
fn append_text(&mut self, thought: bool, text: &str) -> usize {
|
||||
let sealed = std::mem::take(&mut self.sealed);
|
||||
match self.entries.last_mut() {
|
||||
Some(AgentEntry::Agent { text: t }) if !thought => t.push_str(text),
|
||||
Some(AgentEntry::Thought { text: t, .. }) if thought => t.push_str(text),
|
||||
Some(AgentEntry::Agent { text: t }) if !thought && !sealed => t.push_str(text),
|
||||
Some(AgentEntry::Thought { text: t, .. }) if thought && !sealed => t.push_str(text),
|
||||
_ => {
|
||||
let text = text.to_owned();
|
||||
return self.push(if thought {
|
||||
@@ -307,9 +316,9 @@ impl Timeline {
|
||||
changed
|
||||
}
|
||||
|
||||
/// Settles what an ended turn left open: running tools and pending permissions,
|
||||
/// and records when the turn ended (`done`) on the message that started it.
|
||||
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<usize> {
|
||||
/// Settles what an ended turn left open: running tools and pending permissions (but the
|
||||
/// requests in `open`), and records when the turn ended (`done`) on the message that started it.
|
||||
pub fn end_turn(&mut self, done: Option<f64>, open: &HashSet<u32>) -> Vec<usize> {
|
||||
let mut changed = Vec::new();
|
||||
// A steered message rides along in a running turn; the one that started it owns its end.
|
||||
let started = self.entries.iter().rposition(|e| matches!(e, AgentEntry::User { steered: false, .. }));
|
||||
@@ -325,7 +334,7 @@ impl Timeline {
|
||||
*status = AgentToolStatus::Failed;
|
||||
changed.push(i);
|
||||
}
|
||||
AgentEntry::Permission { chosen, .. } if chosen.is_none() => {
|
||||
AgentEntry::Permission { id, chosen, .. } if chosen.is_none() && !open.contains(id) => {
|
||||
*chosen = Some("Cancelled".into());
|
||||
changed.push(i);
|
||||
}
|
||||
@@ -357,7 +366,8 @@ fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>
|
||||
})
|
||||
}
|
||||
|
||||
/// Folds a tool update's content into its output, diffs and images.
|
||||
/// Replaces a tool's output, diffs and images with `content`: an update's `content` replaces the
|
||||
/// whole array, so what it leaves out is gone.
|
||||
fn merge_content(
|
||||
content: &[Value],
|
||||
output: &mut Option<String>,
|
||||
@@ -389,20 +399,14 @@ fn merge_content(
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !text.is_empty() {
|
||||
// The command a call announced (`$ cmd`) stays above the result that replaces it.
|
||||
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
|
||||
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
|
||||
text = format!("{command}\n{text}");
|
||||
}
|
||||
*output = Some(tail(text));
|
||||
}
|
||||
if !new_diffs.is_empty() {
|
||||
*diffs = new_diffs;
|
||||
}
|
||||
if !new_images.is_empty() {
|
||||
*images = new_images;
|
||||
// The command a call announced (`$ cmd`) stays above the result that replaces it.
|
||||
let command = output.as_deref().and_then(|o| o.lines().next()).filter(|l| l.starts_with("$ "));
|
||||
if let Some(command) = command.filter(|c| !text.starts_with(c)) {
|
||||
text = if text.is_empty() { command.to_owned() } else { format!("{command}\n{text}") };
|
||||
}
|
||||
*output = (!text.is_empty()).then(|| tail(text));
|
||||
*diffs = new_diffs;
|
||||
*images = new_images;
|
||||
}
|
||||
|
||||
/// The text of a list of content blocks, one per line.
|
||||
@@ -464,7 +468,7 @@ mod tests {
|
||||
let update = json!({"sessionUpdate":"user_question","id":"call-1","title":"Which?",
|
||||
"questions":[{"answerKey":"q1","question":"Which?","options":[]}]});
|
||||
assert_eq!(t.apply(&update).changed, vec![0]);
|
||||
assert!(t.end_turn(None).is_empty());
|
||||
assert!(t.end_turn(None, &HashSet::new()).is_empty());
|
||||
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: None, .. }));
|
||||
let saved = serde_json::to_string(&t.entries).unwrap();
|
||||
let mut t = Timeline::from_entries(serde_json::from_str(&saved).unwrap());
|
||||
@@ -523,7 +527,7 @@ mod tests {
|
||||
t.apply(&update);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
|
||||
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
|
||||
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None, inline_number: None }]);
|
||||
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
|
||||
assert_eq!(*status, AgentToolStatus::Completed);
|
||||
let saved = serde_json::to_string(&t.entries[0]).unwrap();
|
||||
@@ -612,6 +616,42 @@ mod tests {
|
||||
assert!(t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "zz"})).changed.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_update_with_content_replaces_all_of_the_calls_content() {
|
||||
let text = |t: &str| json!({"type": "content", "content": {"type": "text", "text": t}});
|
||||
let update = |id: &str, content: Value| json!({"sessionUpdate": "tool_call_update", "toolCallId": id, "content": content});
|
||||
let mut t = Timeline::default();
|
||||
// An edit announced with its diff that fails: the error replaces the diff.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "e1", "title": "Edit a.txt", "kind": "edit",
|
||||
"status": "pending",
|
||||
"content": [{"type": "diff", "path": "/p/a.txt", "oldText": "one\n", "newText": "two\nthree\n"}]}));
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "e1", "status": "failed",
|
||||
"content": [text("old_string not found in a.txt")]}));
|
||||
let AgentEntry::Tool { diffs, output, .. } = &t.entries[0] else { panic!() };
|
||||
assert!(diffs.is_empty(), "{diffs:?}");
|
||||
assert_eq!(output.as_deref(), Some("old_string not found in a.txt"));
|
||||
// Text replaces images, and no content clears the output.
|
||||
let image =
|
||||
json!({"type": "content", "content": {"type": "image", "mimeType": "image/png", "data": "iVBORw0KGgo="}});
|
||||
t.apply(&update("e1", json!([image])));
|
||||
t.apply(&update("e1", json!([text("done")])));
|
||||
let AgentEntry::Tool { images, output, .. } = &t.entries[0] else { panic!() };
|
||||
assert!(images.is_empty());
|
||||
assert_eq!(output.as_deref(), Some("done"));
|
||||
t.apply(&update("e1", json!([])));
|
||||
let AgentEntry::Tool { output, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(*output, None);
|
||||
// The command a call announced (`$ cmd`) stays above what replaces its output.
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "r1", "title": "Run make", "kind": "execute",
|
||||
"content": [text("$ make")]}));
|
||||
t.apply(&update("r1", json!([text("building")])));
|
||||
let AgentEntry::Tool { output, .. } = &t.entries[1] else { panic!() };
|
||||
assert_eq!(output.as_deref(), Some("$ make\nbuilding"));
|
||||
t.apply(&update("r1", json!([])));
|
||||
let AgentEntry::Tool { output, .. } = &t.entries[1] else { panic!() };
|
||||
assert_eq!(output.as_deref(), Some("$ make"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_is_one_entry_and_end_turn_settles_open_items() {
|
||||
let mut t = Timeline::default();
|
||||
@@ -621,16 +661,20 @@ mod tests {
|
||||
t.push(AgentEntry::Agent { text: "between".into() });
|
||||
assert_eq!(t.apply(&plan("completed")).changed, vec![0]);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "title": "Run", "status": "in_progress"}));
|
||||
t.push(AgentEntry::Permission {
|
||||
id: 1,
|
||||
let permission = |id| AgentEntry::Permission {
|
||||
id,
|
||||
title: "Run?".into(),
|
||||
command: None,
|
||||
options: vec![],
|
||||
questions: vec![],
|
||||
form: None,
|
||||
chosen: None,
|
||||
});
|
||||
assert_eq!(t.end_turn(None), vec![2, 3]);
|
||||
};
|
||||
t.push(permission(1));
|
||||
// A request that stays open (a subagent's that works on) keeps its card.
|
||||
t.push(permission(2));
|
||||
assert_eq!(t.end_turn(None, &HashSet::from([2])), vec![2, 3]);
|
||||
assert!(matches!(t.entries[4], AgentEntry::Permission { chosen: None, .. }));
|
||||
let again = Timeline::from_entries(t.entries.clone());
|
||||
assert_eq!(again.plan, Some(0));
|
||||
assert_eq!(again.tools.get("c"), Some(&2));
|
||||
@@ -646,16 +690,17 @@ mod tests {
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
recovery: None,
|
||||
retry_attempt: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0));
|
||||
t.push(AgentEntry::Agent { text: "a".into() });
|
||||
t.push(user(2.0));
|
||||
assert_eq!(t.end_turn(Some(5.0)), vec![2]);
|
||||
assert_eq!(t.end_turn(Some(5.0), &HashSet::new()), vec![2]);
|
||||
assert!(matches!(t.entries[0], AgentEntry::User { done_ms: None, .. }));
|
||||
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: Some(5.0), .. }));
|
||||
// Settled once: a later end (a restart) doesn't move it.
|
||||
assert_eq!(t.end_turn(Some(9.0)), Vec::<usize>::new());
|
||||
assert_eq!(t.end_turn(Some(9.0), &HashSet::new()), Vec::<usize>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -668,6 +713,7 @@ mod tests {
|
||||
done_ms: None,
|
||||
steered,
|
||||
recovery: None,
|
||||
retry_attempt: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0, false));
|
||||
@@ -675,7 +721,7 @@ mod tests {
|
||||
t.push(user(2.0, true));
|
||||
// The steered message rides along in the turn: the reply's time belongs to the
|
||||
// message that started it.
|
||||
assert_eq!(t.end_turn(Some(5.0)), vec![0]);
|
||||
assert_eq!(t.end_turn(Some(5.0), &HashSet::new()), vec![0]);
|
||||
assert!(matches!(t.entries[0], AgentEntry::User { done_ms: Some(5.0), .. }));
|
||||
assert!(matches!(t.entries[2], AgentEntry::User { done_ms: None, .. }));
|
||||
}
|
||||
|
||||
@@ -287,6 +287,88 @@ pub(crate) fn create_for_task(
|
||||
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
|
||||
}
|
||||
|
||||
/// Validates and opens an existing managed worktree under `worktrees_dir` so a new task can
|
||||
/// reuse it. Rejects paths outside `worktrees_dir`, non-directories, non-linked repositories,
|
||||
/// or worktrees belonging to a different Git repository than `project_root`. Preserves any
|
||||
/// project-relative subdirectory inside `project_root` just like [`create_for_task`].
|
||||
pub(crate) fn reuse_for_task(project_root: &Path, worktrees_dir: &Path, worktree_path: &Path) -> IdeResult<Created> {
|
||||
let canon_input = verify_confined_worktree_cwd(worktrees_dir, worktree_path)?;
|
||||
if !canon_input.is_dir() {
|
||||
return Err(IdeError::not_found(format!("worktree {} does not exist", worktree_path.display())));
|
||||
}
|
||||
let project_repo = repo_at(project_root)?;
|
||||
let wt_repo = repo_at(&canon_input)?;
|
||||
let [_, project_common] = project_repo.metadata_dirs()?;
|
||||
let [wt_git_dir, wt_common] = wt_repo.metadata_dirs()?;
|
||||
let canon_wt_git_dir = dunce::canonicalize(&wt_git_dir)?;
|
||||
let canon_wt_common = dunce::canonicalize(&wt_common)?;
|
||||
let canon_project_common = dunce::canonicalize(&project_common)?;
|
||||
if canon_wt_git_dir == canon_wt_common || canon_wt_common != canon_project_common {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree {} is not a linked worktree of this repository",
|
||||
worktree_path.display()
|
||||
)));
|
||||
}
|
||||
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
|
||||
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
|
||||
if !canon_wt_root.starts_with(&canon_wt_dir)
|
||||
|| canon_wt_root == canon_wt_dir
|
||||
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
|
||||
{
|
||||
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
|
||||
}
|
||||
let canon_repo = dunce::canonicalize(project_repo.root())?;
|
||||
let canon_proj = dunce::canonicalize(project_root)?;
|
||||
let rel_subdir = if canon_proj != canon_repo {
|
||||
canon_proj
|
||||
.strip_prefix(&canon_repo)
|
||||
.map_err(|_| {
|
||||
IdeError::invalid(format!(
|
||||
"{} is outside git repository {}",
|
||||
canon_proj.display(),
|
||||
canon_repo.display()
|
||||
))
|
||||
})?
|
||||
.to_path_buf()
|
||||
} else {
|
||||
PathBuf::new()
|
||||
};
|
||||
let raw_cwd =
|
||||
if rel_subdir.as_os_str().is_empty() { canon_wt_root.clone() } else { canon_wt_root.join(&rel_subdir) };
|
||||
if !raw_cwd.is_dir() {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"project folder {} does not exist in worktree {}",
|
||||
rel_subdir.display(),
|
||||
canon_wt_root.display()
|
||||
)));
|
||||
}
|
||||
let canon_cwd = verify_confined_worktree_subdir(&canon_wt_root, &raw_cwd)?;
|
||||
let (branch, base_commit) = head_of(&canon_cwd)?;
|
||||
Ok(Created { path: canon_wt_root, cwd: canon_cwd, branch: branch.clone(), base: branch, base_commit })
|
||||
}
|
||||
|
||||
/// Checks out (or creates and checks out) `branch` in `cwd` using Smart checkout so uncommitted
|
||||
/// edits are stashed and restored across the switch. Returns the resulting branch name, HEAD
|
||||
/// commit (when available), and checkout outcome.
|
||||
pub(crate) fn checkout_branch(
|
||||
cwd: &Path,
|
||||
branch: &str,
|
||||
create: bool,
|
||||
) -> IdeResult<(String, Option<String>, ide_vcs::CheckoutOutcome)> {
|
||||
let name = branch.trim();
|
||||
if name.is_empty() {
|
||||
return Err(IdeError::invalid("branch name cannot be empty"));
|
||||
}
|
||||
let repo = repo_at(cwd)?;
|
||||
let options = ide_vcs::CheckoutOptions { mode: ide_vcs::CheckoutMode::Smart, ..Default::default() };
|
||||
let outcome = repo.checkout_with(name, create, &options)?;
|
||||
let (current, head_commit) = match head_of(cwd) {
|
||||
Ok((b, commit)) => (b, Some(commit)),
|
||||
Err(_) => (name.to_owned(), None),
|
||||
};
|
||||
Ok((current, head_commit, outcome))
|
||||
}
|
||||
|
||||
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
|
||||
let canon_cwd = dunce::canonicalize(target_cwd)?;
|
||||
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
|
||||
@@ -327,23 +409,60 @@ pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) ->
|
||||
verify_confined_worktree_subdir(&canon_wt_root, cwd)
|
||||
}
|
||||
|
||||
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
|
||||
if let Ok(rel) = path.strip_prefix(worktrees_dir)
|
||||
/// Returns a canonical comparison key for the managed worktree checkout root containing `path`,
|
||||
/// so two tasks pointing to different subdirs or path casings of the same worktree match.
|
||||
pub(crate) fn shared_worktree_root(worktrees_dir: &Path, path: &Path) -> PathBuf {
|
||||
let (root, _) = worktree_checkout_root(worktrees_dir, path);
|
||||
let resolved = dunce::canonicalize(&root).unwrap_or(root);
|
||||
normalize_path_key(resolved)
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_path_key(path: PathBuf) -> PathBuf {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
PathBuf::from(path.to_string_lossy().replace('/', "\\").to_lowercase())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
fn first_child_under(base: &Path, path: &Path) -> Option<PathBuf> {
|
||||
if let Ok(rel) = path.strip_prefix(base)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
|
||||
return Some(base.join(first));
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let base_comps: Vec<String> =
|
||||
base.components().map(|c| c.as_os_str().to_string_lossy().to_lowercase()).collect();
|
||||
let path_comps: Vec<std::path::Component<'_>> = path.components().collect();
|
||||
if path_comps.len() > base_comps.len()
|
||||
&& base_comps
|
||||
.iter()
|
||||
.zip(path_comps.iter())
|
||||
.all(|(a, b)| a == &b.as_os_str().to_string_lossy().to_lowercase())
|
||||
{
|
||||
return Some(base.join(path_comps[base_comps.len()]));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
|
||||
if let Some(child) = first_child_under(worktrees_dir, path) {
|
||||
return (child, worktrees_dir.to_path_buf());
|
||||
}
|
||||
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
|
||||
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
if let Some(child) = first_child_under(&canon_wt_dir, path) {
|
||||
return (child, canon_wt_dir);
|
||||
}
|
||||
if let Ok(canon_path) = dunce::canonicalize(path)
|
||||
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
&& let Some(child) = first_child_under(&canon_wt_dir, &canon_path)
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
return (child, canon_wt_dir);
|
||||
}
|
||||
}
|
||||
(path.to_path_buf(), worktrees_dir.to_path_buf())
|
||||
@@ -2314,4 +2433,109 @@ mod tests {
|
||||
"symlink swap on worktree reuse must be rejected: {reuse_err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuse_for_task_validates_confinement_and_repo_membership() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "hello\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let other = tmp.path().join("other");
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
git(&other, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(other.join("b.txt"), "world\n").unwrap();
|
||||
git(&other, &["add", "."]);
|
||||
git(&other, &["commit", "-q", "-m", "init other"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap();
|
||||
|
||||
// Reusing a managed worktree of the same repository succeeds and reports its live branch.
|
||||
let reused = super::reuse_for_task(&repo, &wt_dir, &created.cwd).unwrap();
|
||||
assert_eq!(reused.cwd, created.cwd);
|
||||
assert_eq!(reused.branch, created.branch);
|
||||
assert_eq!(reused.base_commit, created.base_commit);
|
||||
|
||||
// Paths outside `worktrees_dir` are rejected.
|
||||
assert!(super::reuse_for_task(&repo, &wt_dir, &repo).is_err());
|
||||
|
||||
// Worktrees belonging to a different repository are rejected.
|
||||
let other_wt = create_for_task(&other, &wt_dir, "task-2", "Other work", None).unwrap();
|
||||
assert!(super::reuse_for_task(&repo, &wt_dir, &other_wt.cwd).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkout_branch_creates_and_switches_branches_in_worktree() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
std::fs::create_dir_all(&repo).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(repo.join("a.txt"), "hello\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&repo, &wt_dir, "task-1", "Feature work", None).unwrap();
|
||||
|
||||
let (branch, head_commit, outcome) = super::checkout_branch(&created.cwd, "feat/follow-up", true).unwrap();
|
||||
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
|
||||
assert_eq!(branch, "feat/follow-up");
|
||||
assert_eq!(head_commit.as_deref(), Some(created.base_commit.as_str()));
|
||||
|
||||
let (back, back_commit, outcome) = super::checkout_branch(&created.cwd, &created.branch, false).unwrap();
|
||||
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
|
||||
assert_eq!(back, created.branch);
|
||||
assert_eq!(back_commit.as_deref(), Some(created.base_commit.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuse_for_task_resolves_subdir_consistently_and_rejects_standalone_repo() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
let sub = repo.join("packages").join("app");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(sub.join("a.txt"), "hello\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&sub, &wt_dir, "task-sub", "Subdir work", None).unwrap();
|
||||
assert!(created.cwd.ends_with(Path::new("packages").join("app")));
|
||||
|
||||
// Passing either the worktree root or the subdir cwd resolves to the same subdir cwd.
|
||||
let reused_from_root = super::reuse_for_task(&sub, &wt_dir, &created.path).unwrap();
|
||||
assert_eq!(reused_from_root.cwd, created.cwd);
|
||||
assert_eq!(reused_from_root.path, dunce::canonicalize(&created.path).unwrap());
|
||||
|
||||
let reused_from_sub = super::reuse_for_task(&sub, &wt_dir, &created.cwd).unwrap();
|
||||
assert_eq!(reused_from_sub.cwd, created.cwd);
|
||||
|
||||
// `shared_worktree_root` matches root and subdir (and mixed casing on Windows).
|
||||
assert_eq!(
|
||||
super::shared_worktree_root(&wt_dir, &created.path),
|
||||
super::shared_worktree_root(&wt_dir, &created.cwd)
|
||||
);
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let upper = PathBuf::from(created.cwd.to_string_lossy().to_uppercase());
|
||||
assert_eq!(
|
||||
super::shared_worktree_root(&wt_dir, &created.path),
|
||||
super::shared_worktree_root(&wt_dir, &upper)
|
||||
);
|
||||
}
|
||||
|
||||
// A standalone repo placed directly inside `worktrees_dir` (not a linked worktree) is rejected.
|
||||
let standalone = wt_dir.join("standalone");
|
||||
std::fs::create_dir_all(&standalone).unwrap();
|
||||
git(&standalone, &["init", "-q", "-b", "main"]);
|
||||
std::fs::write(standalone.join("x.txt"), "x\n").unwrap();
|
||||
git(&standalone, &["add", "."]);
|
||||
git(&standalone, &["commit", "-q", "-m", "standalone"]);
|
||||
assert!(super::reuse_for_task(&standalone, &wt_dir, &standalone).is_err());
|
||||
}
|
||||
}
|
||||
+107
-111
@@ -1,112 +1,108 @@
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6"]}
|
||||
{"from":"shim","msg":{"request":{"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","feedback_mode":{"kind":"post"},"ide_rc_auto_enable_gate":true,"models":[{"description":"Sonnet 5.5 · Efficient for routine tasks","displayName":"Default (recommended)","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.1","resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","resolvedModel":"claude-sonnet-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-4-6"}],"pid":23982,"remote_control_auto_connect_default":false,"remote_control_auto_enable":false,"remote_control_auto_on_by_default":false,"remote_control_available":true,"session_state":"idle"},"subtype":"success"},"type":"control_response"}}
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","a89e008b-23b6-41ea-bebb-612440f38e3c"]}
|
||||
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
|
||||
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"effort":"medium","model":"claude-haiku-5-5","ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false},"effective":{"model":"opus"}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"running","subtype":"session_state_changed","type":"system","uuid":"5e39fde0-9f18-47f0-8b7e-21007ec957c0"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"ad1291e3-8d79-4048-a10c-599eafd30c9b"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"0ed63980-6c4a-40b9-b94d-3bc062cddd58"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"17b7ad4c-6ad3-4d9c-aeef-2e027b0d75ae","view_mode":"default"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"7b8f8fcd-669e-4606-ad6f-3368116e7a75"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"org_level_disabled","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1793203800,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1793203800,"status":"allowed","utilization":0.31},"seven_day":{"resetsAt":1793631600,"status":"allowed","utilization":0.32}}},"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"rate_limit_event","uuid":"b3ef3e2a-11ad-46f9-8ea5-fd01f8d0fe39"}}
|
||||
{"from":"cli","msg":{"commands":[{"argumentHint":"","description":"Review a pull request","name":"review"}],"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"commands_changed","type":"system","uuid":"5f60f663-94ff-4885-9167-b12cae835fca"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1661,"type":"stream_event","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"4fb86b8a-bfa9-439b-b46b-6ef6e381d243"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0bc16cbc-fcbb-4d52-bd5b-4d864b307bbd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0510612a-2068-496a-85f4-f61706fb8cd5"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"{\"command\": \"sleep 3","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"281a35ac-8285-4591-8c60-5ddc743b7036"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"44c02159-084d-48d1-a23c-5bd3628e69e7"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"ca641c1e-c60b-4943-a07b-9ea03c9b8845"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"leep 3 se","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"bc5c34f0-653a-4041-a6cf-42c0dcd0fc2c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"conds then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"00cd396e-f45d-4b60-b484-9fb0ddfc3384"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6987c232-0dbf-43be-83fe-2164d6d701ee"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhj5SvXJc5aP46FPBxn","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:00.931Z","type":"assistant","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"b7befa90-ef05-44ff-9822-ec00f61130b2","wire_tool_inputs":{"toolu_01RLgKZhL3rEQrnb6R4yD7LH":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"01897941-b66d-4657-a87b-14dde2420f38"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"daf07992-fd3c-46c2-8fe7-3014bf6e6cf0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6c4b9511-1539-45a7-9184-9efc1ce9384d"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"now","session_id":"","type":"user","uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"6ae9f6be-c8d5-4feb-8c17-71bfc3d4880e"}}
|
||||
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"task_started","task_id":"bk6c5st9v","task_type":"local_bash","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"e45f0b55-eb72-4cc6-8bb7-0ba207583cc7"}}
|
||||
{"from":"cli","msg":{"output_file":"","run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bk6c5st9v","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"0d23dced-54be-49b0-963b-a9e67ae4b75c"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:04.328Z","tool_result_meta":[{"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"998e4d6c-47bf-4e81-b630-1eb86398d192"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":2891,"duration_ms":5544,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1797,"first_request_input_tokens":29936,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":1,"request_sent_wall_ms":1793193598927,"result":"","result_index":0,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"aborted_tools","time_to_request_ms":138,"total_cost_usd":0.0033443400000000003,"ttft_ms":2142,"ttft_stream_ms":1797,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"a4afa59a-be05-41e3-bc85-4cc8e9b28506"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"cancelled","type":"command_lifecycle","uuid":"4911bef5-6b3d-4c0e-803e-5f21202ce766"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"89c8590f-1c08-4183-b430-5e888745fbfc"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"a05d013f-558f-4581-9ac1-49e4329e9d7d","view_mode":"default"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"d00d3b7f-227d-4373-9092-676090723763"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1500,"type":"stream_event","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"c634f9c8-ff1c-44fa-9138-5d357a418f58"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0db4c93b-e0cb-4fcf-857f-c79fed9a2609"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e7d95fb9-826f-45e1-8e7c-4e6abcdef7c9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"27c0c433-3ee8-42fc-830a-90d67cb371d1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"cc8a606b-0251-4927-96c5-160880f430f6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" s","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1c859e8c-52fe-4fb3-8ad1-0122752cdccf"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"202bcadf-3533-4744-a259-97bfc7bef0e3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"leep task","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2a273607-1f22-4a49-860c-30184e6bfe01"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":9,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"63d703f5-6eec-4a89-a6c7-c38245001004"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" completed with","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"dba1141d-78a3-406a-9125-bf02b5b4a2a3"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2618ae50-9e26-4724-89f6-7fda1f105f42"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" output \"done.\"","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ba6f0b4d-aa70-4347-903e-46119eaa15e6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":16,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"beaeb52e-0825-47b9-ba7e-e09d6de4818c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" The user as","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"3408f5ca-fe05-4bbf-8ae0-b1bc4db97033"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"b5f0f099-f629-469e-a51b-bcb1abaf5f66"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ked me","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"32b263d1-ff54-48f3-a61d-96e98eddce23"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":22,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"581160fb-90e0-4831-b087-d702a7a42fa4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" to end my answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"af0f7710-cb0d-4192-85b6-2a458a17a463"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1ea97064-de2c-4b80-9f32-09ce3a9ce60b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"er with the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ad449330-cf10-4919-b4a0-9f510c259d38"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"9c7d8148-ced4-4647-bdb0-fca91d88aab9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" word BAN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2e4fed14-2110-4d2c-81d0-033f66954ed6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":29,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"dea229d8-9c12-4bf9-9cea-bf9813d41840"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"AN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"a4c1bb86-c884-4f6b-b752-3d57bbb36b1c"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":31,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1cbe8e9c-f44c-4dfb-b6e0-8032d35991db"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"A, which","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0a79f76a-a558-4de1-8323-7547d8628d28"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1961a504-ee75-484f-9c2d-8418496ff795"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" is a har","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"5fa188a2-6e70-4af5-8900-13c30c78c7ad"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":7,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a4d053b7-4485-4d18-8fd2-2354b2a22310"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"mless request, and there's a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"d734fe28-ce41-4002-ad2f-ea0dbc0857a0"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"7fa6189b-3633-4814-9755-a93619616466"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" note","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6dfd60d4-172b-456e-bb66-4f2d6c966233"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":45,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"4aa94d3f-16be-48dc-aa05-1a85105921bb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" about","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"9eb2805d-f684-40ee-b368-468facc4890a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"992053c7-e234-4d72-9c11-d00786dd2c52"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" repl","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"10f0c715-33ad-44fc-8818-7d1a4549fef3"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":49,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e1dad1ff-ec95-4ce1-b07b-b3b42c5f0a15"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ying in","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"244ce6fc-4dfd-4f6e-abf5-57f860663fdc"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":54,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"6f4e3a68-8a38-4ef1-a1d8-5d16b0bdb9e0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" Chinese per inst","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6fce552c-bfa4-4705-b50e-1e162b487f9d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":58,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"491e90c9-da11-4f2f-96d1-2e6c501a13b9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ructions, but","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"cee9edc1-dac1-4997-9b0e-a64e6cc17173"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":61,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2ad92491-7893-4f66-9f8c-8e0c49a0dd21"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" the user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0d10f6b1-daf3-4c40-92cc-78a3b7addc0d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":65,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"48d2ff82-0a78-43f7-bd6e-41170fd9be53"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"rote in English—","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"7af06734-f004-4264-aa76-0e5404fb1da7"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":66,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a607027c-4b06-467b-bd39-99a40085c05b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"I","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f651bfee-b7bb-4d2f-8872-bc43aff55c2b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":72,"estimated_tokens_delta":6,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"862b7d4a-8d66-48ce-a954-764541537982"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"'ll decide how to handle","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f9a8266d-7203-49f1-b14e-cdbcd5311bda"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":75,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"c5bc3ec1-229c-4acc-8a9a-b1184be9a1bf"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" that bal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1ea067e9-fbb8-4685-a217-e42170c35740"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":80,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"ce143939-c780-4938-ba2c-f6a54b8f4a6f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ance while including","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"77668dd2-c3ad-4df5-87a3-4b76a2219c65"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":81,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"0475f779-b12b-4ae0-a42a-4ae723a6d468"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"49727b38-d58a-4ad0-9728-aa4bc223b54d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":86,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"02f8ee0c-36d8-4de5-af74-fe7d19969366"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA at the end.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2adc15b2-5b1c-4add-b3ad-1ceaaa665bae"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":87,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"eb0ae205-deb6-4b79-9726-98fd9d1d533c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"40e6df26-1321-45ea-8ca5-9d96ca00087b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":287,"estimated_tokens_delta":200,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"57a445b0-9671-4073-89c6-f72835125be3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"aaf131b8-99e0-4fd9-9169-00be0b4e360a"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The sleep task completed with output \"done.\" The user asked me to end my answer with the word BANANA, which is a harmless request, and there's a note about replying in Chinese per instructions, but the user wrote in English—I'll decide how to handle that balance while including BANANA at the end.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","thinking_duration_ms":3423,"timestamp":"2026-10-28T13:20:09.346Z","type":"assistant","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"ecaa1288-7581-48ad-9c59-89e4bb9f063f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"549a0ef9-e0b3-40af-bb4a-8aba4c08eb8d"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d3049aaf-53af-4878-b273-68835033ff92"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"命","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"4a3271f3-0c7d-427c-9407-c610ad454b15"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"令输出为 `done`","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"3558f94f-6fcb-4c7a-96a5-6f6e415a5f93"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"。\n\nB","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fea97b73-1f25-4f88-94db-0f0fdd401d2b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"ANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"303a047a-fc87-48ea-9524-e102e112b10a"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"命令输出为 `done`。\n\nBANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:09.358Z","type":"assistant","uuid":"73a78906-d0d9-432d-b1d7-a34ac4d05707"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d665c80a-e37f-476e-ac86-e12d44f26fad"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"46798358-6519-4878-af21-22006f465f53"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fe0e0673-335a-41a0-b7c2-7b5d78e99739"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":7859,"duration_ms":5066,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1586,"first_request_input_tokens":33868,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":19042,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":19042,"cacheReadInputTokens":44758,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00453478,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":318,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":3932,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":3932,"cacheReadInputTokens":29934,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00119044,"inputTokens":2,"maxOutputTokens":128000,"outputTokens":209,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"num_turns":1,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"request_sent_wall_ms":1793193604397,"result":"命令输出为 `done`。\n\nBANANA","result_index":1,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_ms":59,"total_cost_usd":0.00453478,"ttft_ms":5008,"ttft_stream_ms":1563,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"8172897e-6304-4855-9480-f4e579da730f"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"completed","type":"command_lifecycle","uuid":"3c5163f4-90c0-4939-a3e5-aba1cf13bca3"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"idle","subtype":"session_state_changed","type":"system","uuid":"57c31a3d-da32-4a0c-9124-372c880779b7"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"e745940b-18ac-4078-b11e-72be2ae6401b","written_at":"2026-12-03T13:51:32.578Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"f85c6752-6469-4ce7-bbb2-0349f3fabfa8","written_at":"2026-12-03T13:51:32.579Z"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/992375695253/scratchpad","served_by_anthropic":true,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":69,"other_plugin":17,"user_settings":37},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":69,"own":69},"phase_start_ms":{"first_message_handle_ms":282,"first_message_read_ms":0,"grove_check_ms":187,"headless_post_load_ms":257,"headless_prologue_ms":186,"hooks_init_ms":178,"init_emit_ms":343,"initial_messages_load_ms":189,"input_ready_ms":0,"mcp_client_module_load_ms":192,"mcp_config_wait_ms":170,"mcp_connect_ms":182,"mcp_prewait_ms":283,"model_catalog_decision_ms":166,"node_boot_ms":0,"permission_context_ms":89,"pre_action_client_data_url_ms":84,"pre_action_init_ms":46,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":45,"pre_action_migrations_ms":84,"pre_action_ms":45,"print_import_ms":183,"prompt_submit_hooks_ms":301,"qe_plugin_skills_load_ms":341,"qe_system_prompt_ms":286,"sdk_mcp_update_ms":282,"settings_load_ms":44,"setup_file_watcher_ms":118,"setup_hooks_snapshot_ms":118,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":119,"setup_uds_dir_ms":96,"setup_uds_listen_ms":114,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":117,"skills_load_ms":95,"tools_commands_load_ms":130},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":282,"grove_check_ms":1,"headless_post_load_ms":1,"headless_prologue_ms":2,"hooks_init_ms":78,"init_emit_ms":1,"initial_messages_load_ms":68,"input_ready_ms":265,"mcp_client_module_load_ms":0,"mcp_config_load_ms":62,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":3,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":37,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":43,"print_import_ms":3,"prompt_submit_hooks_ms":37,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":4,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":31,"setup_release_notes_ms":8,"setup_uds_dir_ms":18,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":23,"setup_uds_publish_ms":0,"skills_load_ms":66,"tools_commands_load_ms":35},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305892295.906,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"488f600b-a63e-4882-99b1-8dcdfe076157","view_mode":"default","written_at":"2026-12-03T13:51:32.639Z"}}
|
||||
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"b6a40890-0e2f-40ab-afc9-8a609749d59e","written_at":"2026-12-03T13:51:32.642Z"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.21},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"rate_limit_event","uuid":"0cafd103-637f-4025-913d-3d23ec776453","written_at":"2026-12-03T13:51:33.412Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":1089,"type":"stream_event","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"1eba9396-f0bb-4de5-8627-5cebfc962d2a"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5abf5f-2492-4471-b355-ffb886685b08"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"3df5ecdd-e701-43ab-8ad3-90428c0a9bf4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a78c66ea-06f0-4c08-93c3-073ac79ce208"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":3,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58e5f0b8-1cae-4e6e-8142-28c83c20d09c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a66bf075-7a36-4bb4-9b94-090567a1047e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c1baabcf-b72e-438b-8b98-42b628a6c14b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ants a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"25f84cb1-9180-49b0-b722-0ae6617e00f5"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":11,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"9d1b3935-0637-45ca-a613-f1d02b08bf36"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" Bash command run. The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"de8666db-803f-4a33-8cb2-9faa68ff3e2a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"e0d0e6f0-dad3-4075-95d3-cf993ac621d9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" session","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"85784fb7-e5a4-4e17-acb8-2018e82e8458"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"962c83d1-069c-4ff4-b27f-1199d1b3d1b9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"-start hook points","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd405da7-abb7-443d-b309-ac6e805014ed"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":19,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c77e142c-8284-48f4-b67f-24f6fd1cc99b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" to","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"4957baf5-5e7a-4e23-bfe6-7bd1be56cee1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":24,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"2f3e6875-f0b9-4da6-806b-6420f8e11801"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ward skills, but n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ec0306de-6581-4dcb-8ef0-8bc9a2dffe5b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"08432ff1-c798-4640-bb4e-9c6bcb1fa879"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"othing here cal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"934bdb11-4eac-4db8-ba78-d751a132767a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":33,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b68b320e-d34a-4dd2-a52f-d4eb23b6e631"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ls for one, so I'll","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"1a0911c3-5d56-4df6-a490-ca853de74fe0"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":40,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"a0659fe6-3f44-4ee7-8f28-86561a981c00"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" just run the command direct","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"d243b5f8-2ad4-4137-abc0-993b12b30faf"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"0ff88c48-df4d-4fb0-9e10-aad67ea6f912"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ly.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"43859418-f19d-4dab-b439-e24db14015f1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":42,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"bcb9947d-4522-4206-bc6c-2fe20b0ee3f0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"480e67e5-6243-4a07-80dc-5e7218eea10d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":198,"estimated_tokens_delta":156,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"72763f2b-38bb-45f8-b9b4-6dce76fe87dd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2c35aff5-f8f1-423d-ab16-a50fe7f92d2c"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The user wants a Bash command run. The session-start hook points toward skills, but nothing here calls for one, so I'll just run the command directly.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1155,"timestamp":"2026-12-03T13:51:35.067Z","type":"assistant","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"f53249a7-87bb-48d3-8a4d-46fb2bc373c3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"50eafebf-1675-454d-b48d-4c33f9c46fd0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{},"name":"Bash","type":"tool_use"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"df423477-fdd3-40b4-bd3f-a6e5e2f4285a"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2840ddf3-7a52-45a6-bcee-28d02c695ce1"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"{\"command\": \"sleep 3 && ech","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"f279d761-fe64-4811-ba7a-d3389c7fa1d6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"o done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2d7cc471-fe87-49cc-975e-5aefe894bd35"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"77a255b8-8924-4cd2-8239-13d56352e157"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"leep 3 seconds","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5ddf158c-a8ed-475e-b425-4d6aa69d9216"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"8c902fdc-adb0-4db8-91fd-a3c9f799193b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"1019a3dc-64e5-4166-981a-f57347563c32"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:35.072Z","type":"assistant","uuid":"717bc1de-feb1-41aa-81d7-3ac47c772112","wire_tool_inputs":{"toolu_012tPQXDR9Kw59zBCFJqSuXP":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"149df489-36d1-4db3-8f19-ae26b6733dc9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"output_tokens":142,"type":"message"}],"output_tokens":142,"output_tokens_details":{"thinking_tokens":51}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"84156816-f10d-4dd6-8dca-f441fea39795"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"93925996-0953-4359-9383-f6db7885eb3f"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"58a87b31-0fab-415d-b450-0ed1f58ec0bc","written_at":"2026-12-03T13:51:35.084Z"}}
|
||||
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP"},"level":"warning","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"1bb27652-e9f7-4277-8138-8840aa03937c","written_at":"2026-12-03T13:51:35.090Z"}}
|
||||
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"task_started","task_id":"bzep4576h","task_type":"local_bash","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"9f3e9fb8-34cd-4f9c-95f9-b4a7af80eb18","written_at":"2026-12-03T13:51:39.785Z"}}
|
||||
{"from":"cli","msg":{"duration_ms":3020,"output_file":"","run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bzep4576h","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"63898564-4e95-4aa3-8e90-7fc67025ddce","written_at":"2026-12-03T13:51:39.802Z"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:39.838Z","tool_result_meta":[{"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"8103e7bc-d615-4e6a-9c31-c7d36db98577"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"93252284-65fe-4529-ba8f-485b97e6734a","written_at":"2026-12-03T13:51:39.892Z"}}
|
||||
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"1f01a672-b108-46e4-9637-57b2abd60258","written_at":"2026-12-03T13:51:39.892Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":931,"type":"stream_event","uuid":"29de849c-06bb-40e5-a9ad-b70c2f061329"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"92b49174-c189-466f-ad5d-5eea3b3afc2e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b8ec03ca-333f-4fac-a597-c43aa181360f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"I need","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ab10276f-535b-4f19-948c-3f31c090a94e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":8,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"44beb4b3-366d-4725-8781-17a8ab0c2743"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" to make sure the answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"fa8db41b-008b-4779-8269-e3df396df9b2"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":10,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58821ddd-b1aa-437b-b6ea-120c4a781f6b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"er fin","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a4b2ec90-2589-4308-b773-1d95de4e39ab"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"11a853c1-af93-4d0d-b600-e7f2e51a3a16"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ishes with B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3a9a743b-6a39-4572-b86e-4b07355aad6c"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":17,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"42ca95a6-a59d-4e50-8633-8689136027ad"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA, and the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e1173332-7e42-470a-bba6-28348e046d10"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":21,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"1c94c3c4-4eba-42e7-a8a4-00c60bb98763"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" Bash result was","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"c9e62676-e267-4934-85f2-79d124d4bae8"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"03d96f9b-adf7-4f6f-b28b-d427db8b8630"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" just \"done.\" So","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bcbdb107-0d53-4872-a6d0-ea0443ab46a6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":26,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"383344f4-e9c7-4fc6-8156-2a455fc315d4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd677e6a-ccc0-460c-b78c-d146e412fdfc"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":27,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"95673280-0801-43f2-a343-0e1e2294440d"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" re","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3ceba820-e7a1-406d-85cc-4e737440db84"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"ec3fefec-de8f-49c3-832f-ee8cdb9098ba"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ply will start with \"Output:","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"479a0469-81c6-44ed-901f-3b5ba5919286"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":38,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f1187702-1431-4c3f-b55b-b5d6b6e1b4cf"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" done\" and close","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"256ff2f5-a3c1-4c39-ba87-85a6f8a66995"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"db91d155-3a27-4751-8f44-9f55e24a2d56"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" with BANANA on the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"96de0914-3708-4b8f-afcd-6b1834e0a46a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":46,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f315f874-841c-471a-aa95-c7b30c4ecca9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" last line.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5125ea-c014-4134-9967-bfc89d40f300"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"7be0f157-678f-462f-b2ed-f69ee1306d62"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e17e4edd-aef5-4819-ae50-94d9b359f5e9"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":199,"estimated_tokens_delta":152,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"344c71df-0721-4f7a-bf9d-a2c9ac2b0431"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5e790c6d-4323-451b-9dbf-9f36e94b59d0"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"I need to make sure the answer finishes with BANANA, and the Bash result was just \"done.\" So the reply will start with \"Output: done\" and close with BANANA on the last line.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1170,"timestamp":"2026-12-03T13:51:42.004Z","type":"assistant","uuid":"19f7c707-0b92-43f4-a1ff-6f6ba28c9158"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"66f6946c-8aa7-4893-8a3f-fc7c023ea3f6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"6bef1d9a-bcfa-42d8-b3fa-865bbe31804e"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"The command print","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5866afb3-f9f8-42ba-9ae6-928e88f63709"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"ed `done`.","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"22c7b7dc-dfa8-49c6-a931-a2a5f179eebe"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":" BANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"265276d2-0f17-4bd8-8719-b6c0464079fc"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"The command printed `done`. BANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:42.006Z","type":"assistant","uuid":"4edeb5e3-ae9c-4e64-ab43-dd864db6636c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"950b3a05-26db-4a0b-bb6e-62d584a38638"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":72,"output_tokens_details":{"thinking_tokens":58}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"3fb8dfd0-35eb-49ff-a0f9-94c6cff59bcd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"eafb6e94-6aeb-4c20-929f-6d5dc4f8df6a"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"e5548a7e-c304-42d1-a536-2e123ebd58d4","written_at":"2026-12-03T13:51:42.067Z"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"begun_message_ids":["msg_011CheuFeb6zou7Nmj7hYFnf","msg_011CheuGALWJsYSxwR2j7F3W"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":4974,"duration_ms":9488,"fast_mode_state":"off","first_content_frame_ms":1332,"first_request_cache_read_input_tokens":26096,"first_request_input_tokens":42859,"input_attachments_detail":{"ambient_start_ms":1,"ambient_wait_ms":5,"cpu_ms":15,"major_faults":0,"producers":44,"prompt_producers_ms":0,"render_ms":0,"setup_ms":0,"slowest_producer":"deferred_tools_delta","slowest_producer_ms":6,"token_counts":0},"is_error":false,"message_normalization_detail":{"after_ms":0,"before_ms":0,"images_ms":0,"messages":19,"normalize_ms":0,"other_ms":1,"post_process_ms":0,"wire_messages":2},"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"process_turn_index":0,"queued_turn_count":0,"request_build_detail":{"cache_break_record_ms":1,"headers_ms":0,"other_ms":0,"plans_ms":0,"record_attempt_ms":0,"records_ms":0,"retry_setup_ms":0,"sent_build_cache_breakpoints_ms":0,"sent_build_ms":1,"sent_build_safety_context_ms":0,"sent_build_surrogate_scan_ms":0,"system_ms":0},"request_sent_wall_ms":1796305892823,"result":"The command printed `done`. BANANA","result_index":0,"safety_stops":0,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_cpu_ms":107,"time_to_request_loop_lag_ms":1,"time_to_request_major_faults":1,"time_to_request_ms":243,"time_to_request_phases_ms":{"autocompact":1,"client_creation":2,"conversation_append":1,"engine_pickup":1,"init_frame_send":1,"init_message":2,"input_attachments":8,"input_hooks":37,"loop_entry":1,"message_normalization":1,"message_prep":1,"model_config_wait":0,"model_gates":163,"other":2,"process_user_input":2,"query_setup":0,"request_announcements":3,"request_build":2,"resume_other":0,"system_prompt":5,"tool_pool_refresh":1,"tool_schema_build":8,"transcript_persist":1},"tool_schema_build_detail":{"after_ms":0,"betas_ms":0,"new_schemas":13,"other_ms":0,"placement_ms":2,"render_ms":3,"tools":13,"waits_ms":3},"total_cost_usd":0.0067110300000000015,"ttft_ms":2487,"ttft_stream_ms":1331,"turn_start_resume_kind":"none","type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":28926,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":28926,"cache_read_input_tokens":68953,"fallback_credit":null,"inference_geo":"global","input_tokens":4,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":214,"output_tokens_details":{"thinking_tokens":109},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"d3f210c9-67ad-4ec5-b122-3d4477ae65b5","written_at":"2026-12-03T13:51:42.069Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"32e0888f-d2b7-4721-bc7c-6c5320d3c99c","written_at":"2026-12-03T13:51:42.070Z"}}
|
||||
@@ -0,0 +1,34 @@
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","f782ff38-9bfe-4bd7-a857-f3cb10b38bcf"]}
|
||||
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
|
||||
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 5 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"750456ba-c54c-493b-bb61-40a9d825a457"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"b57b173d-a184-4e10-8ac6-46bd57c905b2","written_at":"2026-12-03T13:52:52.103Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"started","type":"command_lifecycle","uuid":"cd26e730-c57b-49c0-bfed-0ed2202ba6f5","written_at":"2026-12-03T13:52:52.104Z"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/443805216073/scratchpad","served_by_anthropic":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":79,"other_plugin":23,"user_settings":51},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":79,"own":79},"phase_start_ms":{"first_message_handle_ms":299,"first_message_read_ms":0,"grove_check_ms":193,"headless_post_load_ms":273,"headless_prologue_ms":192,"hooks_init_ms":184,"init_emit_ms":361,"initial_messages_load_ms":196,"input_ready_ms":0,"mcp_client_module_load_ms":200,"mcp_config_wait_ms":175,"mcp_connect_ms":188,"mcp_prewait_ms":300,"model_catalog_decision_ms":170,"node_boot_ms":0,"permission_context_ms":90,"pre_action_client_data_url_ms":84,"pre_action_init_ms":45,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":44,"pre_action_migrations_ms":84,"pre_action_ms":44,"print_import_ms":189,"prompt_submit_hooks_ms":319,"qe_plugin_skills_load_ms":360,"qe_system_prompt_ms":302,"sdk_mcp_update_ms":299,"settings_load_ms":43,"setup_file_watcher_ms":119,"setup_hooks_snapshot_ms":119,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":120,"setup_uds_dir_ms":97,"setup_uds_listen_ms":116,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":119,"skills_load_ms":96,"tools_commands_load_ms":132},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":299,"grove_check_ms":2,"headless_post_load_ms":1,"headless_prologue_ms":3,"hooks_init_ms":89,"init_emit_ms":1,"initial_messages_load_ms":77,"input_ready_ms":280,"mcp_client_module_load_ms":0,"mcp_config_load_ms":67,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":2,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":39,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":45,"print_import_ms":3,"prompt_submit_hooks_ms":38,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":5,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":32,"setup_release_notes_ms":9,"setup_uds_dir_ms":19,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":24,"setup_uds_publish_ms":0,"skills_load_ms":69,"tools_commands_load_ms":38},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305971804.1318,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"4614d51b-c114-4e3a-87c1-474dd3221ccb","view_mode":"default","written_at":"2026-12-03T13:52:52.166Z"}}
|
||||
{"from":"cli","msg":{"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","status":"requesting","subtype":"status","type":"system","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"1334ad42-52e2-4940-a881-df02701bbce2","written_at":"2026-12-03T13:52:52.168Z"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.22},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"rate_limit_event","uuid":"2d31cd09-90af-4542-9ab8-d6d35208343a","written_at":"2026-12-03T13:52:52.848Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","thinking_display":"summarized","ttft_ms":870,"type":"stream_event","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"a07fd809-d225-4ae9-8a9a-1cfcd3ba452b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"d87d4b0c-0817-44f3-ba3d-506b145416eb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"7ebaa4fa-4334-42cd-87b9-86efb45b06fd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"{\"command\": \"sleep 5","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"92f03d38-e933-444a-af9e-5d97a3bc17e1"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"156dfb71-8647-402b-81f1-d28209de7f6b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f2218947-8767-4812-b6e9-5081d444668e"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"leep 5 seconds","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"645079d4-6f4f-403c-aef0-add49e320bdb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"fc1582cb-4fe7-4747-b65a-5d57351c1749"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"8de2ab6a-1c5f-43be-99c5-accf562bded5"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuMVa2bRTBYmxzHrdZU","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:53.341Z","type":"assistant","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"543df181-f94c-4c59-8a54-6790d7c146fe","wire_tool_inputs":{"toolu_013cYTr5SPmttma9grssUDvs":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"}}}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"c95ced13-7ba7-4081-96dc-72e2e1ee9c67"}}
|
||||
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs"},"level":"warning","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"c5ce69e8-b5c8-4e04-b6af-b1a4d9760a3d","written_at":"2026-12-03T13:52:53.356Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f1c31fc2-e095-4a52-a92c-752feb90d83c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"5fd7d71c-5822-414a-b3e1-d11395fd7022"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee"}}
|
||||
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"d4038320-e65f-4937-b14c-8948234e08c4","written_at":"2026-12-03T13:52:55.103Z"}}
|
||||
{"from":"shim","msg":{"request":{"cancel_queued":true,"subtype":"interrupt"},"request_id":"req_3","type":"control_request"}}
|
||||
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"24e8c7aa-31e8-455f-a456-12ee15e0e8f9","written_at":"2026-12-03T13:52:55.604Z"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_3","response":{"cancelled":["6e50c1f5-335e-4d89-a2ef-725e845b57ee"],"still_queued":[]},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed. Correction to the text above: this call was stopped while running, not refused before it ran. It may have run in part or in full, and its changes may have been written. No permission prompt was involved. Work it started elsewhere (a remote command, a background process) may still be running, so check before starting the same work again. The instruction to stop and wait still stands.","is_error":true,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.608Z","tool_result_meta":[{"id":"toolu_013cYTr5SPmttma9grssUDvs","non_execution_kind":"user-rejected"}],"tool_use_result":"User rejected tool use","type":"user","uuid":"087df73f-b2fe-42d9-9de4-f3fab77aefe0"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"text":"[Request interrupted by user for tool use]","type":"text"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.610Z","type":"user","uuid":"900c03e1-b662-4e5f-aaf6-384263031910"}}
|
||||
{"from":"cli","msg":{"begun_message_ids":["msg_011CheuMVnw6EQjt4etKk278"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":1721,"duration_ms":3506,"errors":["[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"],"fast_mode_state":"off","is_error":true,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":3,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"result_index":0,"safety_stops":0,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"error_during_execution","terminal_reason":"aborted_tools","total_cost_usd":0.00340499,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"5c62e1de-fdfc-44f7-ae20-cd70b87590e5","written_at":"2026-12-03T13:52:55.613Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","idle":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"53cf7918-cf6e-4c94-984c-8401081fa93e","written_at":"2026-12-03T13:52:55.615Z"}}
|
||||
@@ -63,7 +63,7 @@ pub(crate) fn stream_batched<T>(
|
||||
}
|
||||
}
|
||||
flush(&mut batch, on_batch);
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
Ok((lines.finish(cancel)?.success(), stderr_tail))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
|
||||
@@ -29,7 +29,7 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
|
||||
let repo = crate::maven::local_repository_for(&p.options);
|
||||
args.extend([
|
||||
"process-resources".into(),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref()),
|
||||
crate::maven::plugin_goal("help:evaluate", repo.as_deref(), crate::maven::maven_version(&p.command)),
|
||||
"-Dexpression=project.build.outputDirectory".into(),
|
||||
format!("-Doutput={}", manifest.display()),
|
||||
]);
|
||||
|
||||
@@ -21,8 +21,9 @@ pub use single::{
|
||||
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,
|
||||
StructureBuildContext, StructureJdk, StructureRoots, artifact_file, artifact_output, language_release,
|
||||
structure_build, structure_build_war, 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};
|
||||
@@ -293,7 +294,7 @@ pub fn plan(
|
||||
}
|
||||
BuildSystem::TypeScript => ts_steps(&dir, kind),
|
||||
BuildSystem::CMake => cmake_steps(&dir, kind, cmake.and_then(<[_]>::first)),
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind)?,
|
||||
BuildSystem::Dotnet => dotnet_steps(&dir, kind, file)?,
|
||||
// Never detected from a folder: it comes from the Project Structure (`structure_plan`).
|
||||
BuildSystem::Javac => return Err(IdeError::invalid("no build tool to run")),
|
||||
}
|
||||
@@ -358,16 +359,14 @@ pub(super) fn maven_steps(
|
||||
};
|
||||
// The reactor root containing the module builds it with what it depends on (`-pl … -am`).
|
||||
let rel = rel_str(root, module);
|
||||
if !m.projects.iter().any(|p| p.dir == rel) {
|
||||
let Some(target) = m.projects.iter().find(|p| p.dir == rel) else {
|
||||
return Err(IdeError::not_found("no linked Maven project found for module"));
|
||||
}
|
||||
};
|
||||
let top = maven_reactor(m, &rel).ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
if module == top_dir {
|
||||
return Ok(vec![step(top, &[])]);
|
||||
if let Some(pl) = maven::module_selector(root, top, target) {
|
||||
return Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])]);
|
||||
}
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or(rel);
|
||||
Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])])
|
||||
Ok(vec![step(top, &[])])
|
||||
}
|
||||
|
||||
fn gradle_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
|
||||
@@ -421,13 +420,14 @@ 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), one job per
|
||||
/// `CMakeCache.txt` or no File API reply 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> {
|
||||
let build_dir = match profile {
|
||||
Some(p) if !p.build_dir.trim().is_empty() => p.build_dir.trim().to_owned(),
|
||||
Some(p) if p.build_type.is_empty() => "cmake-build-default".into(),
|
||||
Some(p) => format!("cmake-build-{}", p.build_type.to_lowercase()),
|
||||
None => {
|
||||
let mut configured: Vec<String> = std::fs::read_dir(dir)
|
||||
@@ -444,18 +444,49 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
|
||||
let build_type = profile.map_or("Debug", |p| p.build_type.as_str());
|
||||
let env = profile.map(|p| p.env.clone()).unwrap_or_default();
|
||||
let mut steps = Vec::new();
|
||||
if !dir.join(&build_dir).join("CMakeCache.txt").is_file() {
|
||||
let mut configure = BuildStep::new("cmake", &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
|
||||
if let Some(p) = profile.filter(|p| !p.generator.trim().is_empty()) {
|
||||
configure.args.extend(["-G".into(), p.generator.clone()]);
|
||||
}
|
||||
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
|
||||
let preset = profile.and_then(|p| p.preset.as_ref());
|
||||
// The profile's toolchain may bring its own cmake.
|
||||
let cmake = profile.and_then(|p| p.cmake_program.as_ref()).map_or("cmake".into(), |c| c.to_string_lossy());
|
||||
let cmake = cmake.as_ref();
|
||||
let build_path = dir.join(&build_dir);
|
||||
// Configured without the File API queries (by another tool, or before they were written):
|
||||
// configure again so the targets, and their run configurations, become known.
|
||||
let fresh = !build_path.join("CMakeCache.txt").is_file();
|
||||
if fresh || !build_path.join(ide_core::cmake_file_api::REPLY).is_dir() {
|
||||
// Best effort: without the queries the build still runs, only the targets stay unknown.
|
||||
let _ = ide_core::cmake_file_api::write_queries(&build_path);
|
||||
let mut configure = match preset {
|
||||
// The preset sets the generator and cache variables.
|
||||
Some(preset) => BuildStep::new(cmake, &["--preset", &preset.configure], dir, Format::Gcc),
|
||||
None => {
|
||||
let mut configure = BuildStep::new(cmake, &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
|
||||
// A configured directory keeps its generator (CMake refuses another one) and,
|
||||
// without a profile, its build type.
|
||||
if let Some(p) = profile.filter(|p| fresh && !p.generator.trim().is_empty()) {
|
||||
configure.args.extend(["-G".into(), p.generator.clone()]);
|
||||
}
|
||||
if fresh || profile.is_some() {
|
||||
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
|
||||
}
|
||||
configure
|
||||
}
|
||||
};
|
||||
configure.args.push("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".into());
|
||||
configure.args.extend(profile.map(|p| p.cmake_args.clone()).unwrap_or_default());
|
||||
configure.env = env.clone();
|
||||
steps.push(configure);
|
||||
}
|
||||
let mut build = BuildStep::new("cmake", &["--build", &build_dir, "--config", build_type], dir, Format::Gcc);
|
||||
let mut build = match preset.and_then(|p| p.build.as_deref()) {
|
||||
Some(build) => BuildStep::new(cmake, &["--build", "--preset", build], dir, Format::Gcc),
|
||||
None => {
|
||||
let mut build = BuildStep::new(cmake, &["--build", &build_dir], dir, Format::Gcc);
|
||||
// CLion's "Default" build type: no configuration at all.
|
||||
if !build_type.is_empty() {
|
||||
build.args.extend(["--config".into(), build_type.into()]);
|
||||
}
|
||||
build
|
||||
}
|
||||
};
|
||||
if kind == BuildKind::Rebuild {
|
||||
build.args.push("--clean-first".into());
|
||||
}
|
||||
@@ -522,10 +553,24 @@ fn dotnet_target(dir: &Path) -> Option<PathBuf> {
|
||||
solution.or_else(|| files.iter().find(|p| matches!(ext(p).as_str(), "csproj" | "fsproj" | "vbproj"))).cloned()
|
||||
}
|
||||
|
||||
/// `dotnet build` of the directory's solution or project; Rebuild skips incremental builds,
|
||||
/// `dotnet build` of `file` when it is a solution or project in `dir` (a run configuration's
|
||||
/// project), else of the directory's solution or project; Rebuild skips incremental builds,
|
||||
/// Build Artifacts publishes. The summary that repeats every message is left out.
|
||||
fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
let target = dotnet_target(dir).ok_or_else(|| IdeError::not_found("no .NET solution or project found"))?;
|
||||
fn dotnet_steps(dir: &Path, kind: BuildKind, file: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
|
||||
let given = file.filter(|f| {
|
||||
f.parent() == Some(dir)
|
||||
&& f.is_file()
|
||||
&& f.extension().is_some_and(|e| {
|
||||
matches!(
|
||||
e.to_string_lossy().to_ascii_lowercase().as_str(),
|
||||
"sln" | "slnx" | "csproj" | "fsproj" | "vbproj"
|
||||
)
|
||||
})
|
||||
});
|
||||
let target = given
|
||||
.map(Path::to_path_buf)
|
||||
.or_else(|| dotnet_target(dir))
|
||||
.ok_or_else(|| IdeError::not_found("no .NET solution or project found"))?;
|
||||
let target = target.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned());
|
||||
let verb = if kind == BuildKind::Artifacts { "publish" } else { "build" };
|
||||
let mut step = BuildStep::new("dotnet", &[verb, &target, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild);
|
||||
@@ -538,6 +583,77 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
Ok(vec![step])
|
||||
}
|
||||
|
||||
/// A `dotnet` command the .NET tool window runs on a solution or project file.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DotnetCommand {
|
||||
Build,
|
||||
Clean,
|
||||
Restore,
|
||||
}
|
||||
|
||||
/// `dotnet build` / `clean` / `restore` of one solution or project file, followed by `options`
|
||||
/// (`--configuration`, `--framework`, `-p:…`).
|
||||
pub fn dotnet_command_plan(file: &Path, command: DotnetCommand, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
let verb = match command {
|
||||
DotnetCommand::Build => "build",
|
||||
DotnetCommand::Clean => "clean",
|
||||
DotnetCommand::Restore => "restore",
|
||||
};
|
||||
dotnet_file_plan(file, verb, true, options)
|
||||
}
|
||||
|
||||
/// `dotnet publish` of one project file with the publish dialog's `options` (`-p:PublishProfile=…`,
|
||||
/// or `--configuration` / `--runtime` / `--output`).
|
||||
pub fn dotnet_publish_plan(file: &Path, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
dotnet_file_plan(file, "publish", false, options)
|
||||
}
|
||||
|
||||
fn dotnet_file_plan(file: &Path, verb: &str, solutions: bool, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
let accepted = match ext.as_str() {
|
||||
"csproj" | "fsproj" | "vbproj" => true,
|
||||
"sln" | "slnx" => solutions,
|
||||
_ => false,
|
||||
};
|
||||
let (Some(dir), Some(name), true) = (file.parent(), file.file_name(), accepted) else {
|
||||
return Err(IdeError::invalid(if solutions {
|
||||
format!("dotnet {verb} needs a solution or a C#, F# or VB project")
|
||||
} else {
|
||||
format!("dotnet {verb} needs a C#, F# or VB project")
|
||||
}));
|
||||
};
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
|
||||
}
|
||||
let name = name.to_string_lossy();
|
||||
let mut step = BuildStep::new("dotnet", &[verb, &name, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild);
|
||||
step.args.extend_from_slice(options);
|
||||
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
|
||||
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet {verb} {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
/// `dotnet format` of a solution or C# / VB project file; `verify` only reports what it would
|
||||
/// change and fails when there is anything.
|
||||
pub fn dotnet_format_plan(file: &Path, verify: bool) -> IdeResult<BuildPlan> {
|
||||
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
let (Some(dir), Some(name), true) =
|
||||
(file.parent(), file.file_name(), matches!(ext.as_str(), "sln" | "slnx" | "csproj" | "vbproj"))
|
||||
else {
|
||||
return Err(IdeError::invalid("dotnet format needs a solution or a C# / VB project"));
|
||||
};
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
|
||||
}
|
||||
let name = name.to_string_lossy();
|
||||
// Verbose output names the files it changed; verifying changes none.
|
||||
let options: &[&str] = if verify { &["--verify-no-changes"] } else { &["--verbosity", "normal"] };
|
||||
let mut step = BuildStep::new("dotnet", &["format", &name], dir, Format::Msbuild);
|
||||
step.args.extend(options.iter().map(|o| (*o).to_owned()));
|
||||
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
|
||||
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet format {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
let script = has_build_script(dir);
|
||||
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
|
||||
@@ -926,17 +1042,7 @@ pub fn has_non_java_sources(module: &Path) -> bool {
|
||||
}
|
||||
|
||||
fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject) -> Vec<&'a maven::MavenProject> {
|
||||
let mut projects = Vec::new();
|
||||
let mut pending = vec![top];
|
||||
let mut seen = HashSet::new();
|
||||
while let Some(p) = pending.pop() {
|
||||
if !seen.insert(&p.pom) {
|
||||
continue;
|
||||
}
|
||||
projects.push(p);
|
||||
pending.extend(m.projects.iter().filter(|child| p.modules.contains(&child.pom)));
|
||||
}
|
||||
projects
|
||||
maven::reactor_projects(m, top)
|
||||
}
|
||||
|
||||
/// A step running Maven, its output parsed as Maven's.
|
||||
@@ -962,7 +1068,7 @@ pub(crate) fn reactor_projects_of<'a>(
|
||||
}
|
||||
|
||||
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
|
||||
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
|
||||
maven::reactor_for_dir(m, module)
|
||||
}
|
||||
|
||||
/// Launch module first, followed by its upstream modules in the same Maven reactor.
|
||||
@@ -1642,6 +1748,36 @@ mod tests {
|
||||
let p = plan(&net, &BuildModel::default(), BuildKind::Artifacts, None, None, None, &CancellationToken::new())
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[0], "publish");
|
||||
// A run configuration's project is built even when its folder holds other projects or a
|
||||
// solution that sort first (#8179).
|
||||
write(&net, "src/Host/Legacy.csproj", "<Project/>");
|
||||
write(&net, "src/Host/Main.csproj", "<Project/>");
|
||||
write(&net, "src/Host/All.sln", "");
|
||||
for name in ["Main.csproj", "All.sln", "Legacy.csproj"] {
|
||||
let file = net.join("src/Host").join(name);
|
||||
let p = plan(
|
||||
&net,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&file),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[1], name);
|
||||
}
|
||||
let p = plan(
|
||||
&net,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
Some(&net.join("src/Host/Program.cs")),
|
||||
None,
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[1], "All.sln");
|
||||
|
||||
let cm = tmp.path().join("cm");
|
||||
write(&cm, "CMakeLists.txt", "project(app)");
|
||||
@@ -1659,6 +1795,15 @@ mod tests {
|
||||
"an unconfigured project is configured first"
|
||||
);
|
||||
write(&cm, "cmake-build-release/CMakeCache.txt", "");
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
p.steps[0].args,
|
||||
["-S", ".", "-B", "cmake-build-release", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"],
|
||||
"configured again, as it was, when it has no File API reply"
|
||||
);
|
||||
assert!(cm.join("cmake-build-release/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file());
|
||||
std::fs::create_dir_all(cm.join("cmake-build-release").join(ide_core::cmake_file_api::REPLY)).unwrap();
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
@@ -1694,6 +1839,33 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]);
|
||||
let preset = CMakeProfile {
|
||||
build_dir: "out/dev".into(),
|
||||
preset: Some(ide_core::settings::CMakePresetRef {
|
||||
configure: "dev".into(),
|
||||
build: Some("dev-build".into()),
|
||||
..Default::default()
|
||||
}),
|
||||
..CMakeProfile::default()
|
||||
};
|
||||
let p = plan(
|
||||
&cm,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
None,
|
||||
Some(std::slice::from_ref(&preset)),
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
[
|
||||
"--preset dev -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
|
||||
format!("--build --preset dev-build {jobs}")
|
||||
],
|
||||
"a preset profile configures and builds with its presets"
|
||||
);
|
||||
|
||||
let siblings = tmp.path().join("siblings");
|
||||
write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
|
||||
@@ -1993,6 +2165,34 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sibling_reactor_launch_uses_relative_module_selector() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(
|
||||
root,
|
||||
"parent/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"common/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId></project>",
|
||||
);
|
||||
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
|
||||
let plan =
|
||||
launch_plan(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(plan.steps.len(), 1);
|
||||
assert_eq!(plan.steps[0].cwd, root.join("parent"));
|
||||
let pl = plan.steps[0].args.iter().position(|a| a == "-pl").unwrap();
|
||||
assert_eq!(&plan.steps[0].args[pl..pl + 3], &["-pl", "../app", "-am"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
|
||||
@@ -2162,4 +2362,142 @@ mod tests {
|
||||
assert_eq!(whole.steps[0].cwd, root);
|
||||
assert_eq!(whole.steps[0].args, ["build", "./..."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_format_runs_on_the_given_solution_or_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj", "App.fsproj", "A.cs"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj"] {
|
||||
let plan = super::dotnet_format_plan(&dir.path().join(name), false).unwrap();
|
||||
assert_eq!(plan.steps[0].args, ["format", name, "--verbosity", "normal"]);
|
||||
assert_eq!(plan.steps[0].cwd, dir.path());
|
||||
let verify = super::dotnet_format_plan(&dir.path().join(name), true).unwrap();
|
||||
assert_eq!(verify.steps[0].args, ["format", name, "--verify-no-changes"]);
|
||||
}
|
||||
for name in ["App.fsproj", "A.cs", "Missing.sln"] {
|
||||
assert!(super::dotnet_format_plan(&dir.path().join(name), false).is_err(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The real `dotnet format` (`-- --ignored`): verifying reports and changes nothing, formatting rewrites.
|
||||
#[test]
|
||||
#[ignore = "needs the .NET SDK"]
|
||||
fn dotnet_format_reports_and_rewrites_with_the_real_sdk() {
|
||||
let found = std::process::Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success());
|
||||
if !found {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for args in [
|
||||
&["new", "console", "-n", "App", "-o", "App"][..],
|
||||
&["new", "sln", "-n", "Sln", "--format", "slnx"],
|
||||
&["new", "sln", "-n", "Classic", "--format", "sln"],
|
||||
&["sln", "Sln.slnx", "add", "App/App.csproj"],
|
||||
&["sln", "Classic.sln", "add", "App/App.csproj"],
|
||||
] {
|
||||
assert!(std::process::Command::new("dotnet").args(args).current_dir(&root).status().unwrap().success());
|
||||
}
|
||||
let source = root.join("App").join("中 A.cs");
|
||||
let messy = "class A{void M( ){var x=1;}}\n";
|
||||
for target in ["Sln.slnx", "Classic.sln", "App/App.csproj"] {
|
||||
std::fs::write(&source, messy).unwrap();
|
||||
let run = |verify| {
|
||||
let plan = super::dotnet_format_plan(&root.join(target), verify).unwrap();
|
||||
super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap()
|
||||
};
|
||||
let verified = run(true);
|
||||
assert!(!verified.success, "{target}");
|
||||
let message = verified.messages.iter().find(|m| m.code.as_deref() == Some("WHITESPACE")).unwrap();
|
||||
assert!(message.path.as_ref().unwrap().ends_with("中 A.cs"), "{message:?}");
|
||||
assert_eq!(std::fs::read_to_string(&source).unwrap(), messy);
|
||||
assert!(run(false).success, "{target}");
|
||||
assert_ne!(std::fs::read_to_string(&source).unwrap(), messy);
|
||||
assert!(run(true).success, "{target}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_publish_runs_on_one_project_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.csproj", "App.fsproj", "App.vbproj", "Sln.slnx"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
let options = ["-p:PublishProfile=My Folder".to_owned()];
|
||||
for name in ["App.csproj", "App.fsproj", "App.vbproj"] {
|
||||
let plan = super::dotnet_publish_plan(&dir.path().join(name), &options).unwrap();
|
||||
assert_eq!(
|
||||
plan.steps[0].args,
|
||||
["publish", name, "-nologo", "-clp:NoSummary", "-p:PublishProfile=My Folder"]
|
||||
);
|
||||
}
|
||||
for name in ["Sln.slnx", "Missing.csproj"] {
|
||||
assert!(super::dotnet_publish_plan(&dir.path().join(name), &[]).is_err(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_commands_run_on_one_solution_or_project_file() {
|
||||
use super::DotnetCommand;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.csproj", "Sln.sln", "Sln.slnx", "notes.txt"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
let options = ["--configuration".to_owned(), "Release".to_owned()];
|
||||
for (name, command, verb) in [
|
||||
("Sln.sln", DotnetCommand::Build, "build"),
|
||||
("Sln.slnx", DotnetCommand::Clean, "clean"),
|
||||
("App.csproj", DotnetCommand::Restore, "restore"),
|
||||
] {
|
||||
let plan = super::dotnet_command_plan(&dir.path().join(name), command, &options).unwrap();
|
||||
assert_eq!(plan.title, format!("dotnet {verb} {name}"));
|
||||
assert_eq!(plan.steps[0].args, [verb, name, "-nologo", "-clp:NoSummary", "--configuration", "Release"]);
|
||||
assert_eq!(plan.steps[0].cwd, dir.path());
|
||||
}
|
||||
for name in ["notes.txt", "Missing.sln"] {
|
||||
assert!(super::dotnet_command_plan(&dir.path().join(name), DotnetCommand::Build, &[]).is_err(), "{name}");
|
||||
}
|
||||
assert!(super::dotnet_publish_plan(&dir.path().join("Sln.sln"), &[]).is_err(), "publish takes a project");
|
||||
}
|
||||
|
||||
/// The real `dotnet publish` (`-- --ignored`): publishes, reports compile errors, and stops
|
||||
/// when cancelled.
|
||||
#[test]
|
||||
#[ignore = "needs the .NET SDK"]
|
||||
fn dotnet_publish_publishes_fails_and_cancels_with_the_real_sdk() {
|
||||
let found = std::process::Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success());
|
||||
if !found {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let new = ["new", "console", "-n", "App", "-o", "App"];
|
||||
assert!(std::process::Command::new("dotnet").args(new).current_dir(&root).status().unwrap().success());
|
||||
let project = root.join("App").join("App.csproj");
|
||||
let options = ["--output".to_owned(), "out dir".to_owned()];
|
||||
let plan = super::dotnet_publish_plan(&project, &options).unwrap();
|
||||
|
||||
let published = super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert!(published.success);
|
||||
let output = root.join("App").join("out dir").join("App.dll");
|
||||
assert!(output.is_file());
|
||||
|
||||
std::fs::remove_dir_all(root.join("App").join("out dir")).unwrap();
|
||||
let token = CancellationToken::new();
|
||||
let cancel = token.clone();
|
||||
let result = super::run(&root, &plan, &token, &|e| {
|
||||
if matches!(e, BuildEvent::Output { .. }) {
|
||||
cancel.cancel();
|
||||
}
|
||||
});
|
||||
assert!(result.is_err(), "a cancelled publish is not a result");
|
||||
assert!(!output.exists());
|
||||
|
||||
std::fs::write(root.join("App").join("Program.cs"), "nope\n").unwrap();
|
||||
let failed = super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert!(!failed.success);
|
||||
assert!(failed.messages.iter().any(|m| m.path.as_ref().is_some_and(|p| p.ends_with("Program.cs"))));
|
||||
}
|
||||
}
|
||||
@@ -72,15 +72,19 @@ fn affected_projects(reactor: &[&maven::MavenProject], changed: &HashSet<String>
|
||||
/// `-pl` entries of the affected modules, relative to the reactor root the step
|
||||
/// runs in, sorted so the command line does not depend on the model's project
|
||||
/// order (Maven reorders the selection into its own reactor order anyway).
|
||||
fn selection(reactor: &[&maven::MavenProject], top_dir: &str, affected: &HashSet<String>) -> String {
|
||||
fn selection(
|
||||
root: &Path,
|
||||
top: &maven::MavenProject,
|
||||
reactor: &[&maven::MavenProject],
|
||||
affected: &HashSet<String>,
|
||||
) -> String {
|
||||
let mut entries: Vec<String> = reactor
|
||||
.iter()
|
||||
.filter(|p| affected.contains(&p.dir))
|
||||
.map(|p| {
|
||||
Path::new(&p.dir).strip_prefix(top_dir).unwrap_or(Path::new(&p.dir)).to_string_lossy().replace('\\', "/")
|
||||
})
|
||||
.filter_map(|p| maven::module_selector(root, top, p))
|
||||
.collect();
|
||||
entries.sort();
|
||||
entries.dedup();
|
||||
entries.join(",")
|
||||
}
|
||||
|
||||
@@ -130,8 +134,12 @@ pub(super) fn narrowed_maven_steps(
|
||||
if affected.len() >= reactor.len() || affected.contains(&top.dir) {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
let pl = selection(&reactor, &top.dir, &affected);
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
let pl = selection(root, top, &reactor, &affected);
|
||||
if pl.is_empty() {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(steps))
|
||||
@@ -405,4 +413,36 @@ mod tests {
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "solo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sibling_reactor_narrows_with_relative_module_selectors() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
write(
|
||||
root,
|
||||
"parent/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"common/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(root, "common/src/main/java/t/C.java", "package t; public class C {}");
|
||||
write(root, "app/src/main/java/t/A.java", "package t; public class A {}");
|
||||
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, "common/src/main/java/t/C.java", "package t; public class C { int x; }");
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "parent"));
|
||||
assert_eq!(pl_arg(&steps[0]), "../app,../common");
|
||||
assert!(steps[0].args.contains(&"-am".into()));
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,7 @@ pub(super) fn build_javac_step(
|
||||
cwd: &Path,
|
||||
out_dir: &Path,
|
||||
classpath: &str,
|
||||
encoding: &str,
|
||||
sources: &[PathBuf],
|
||||
release: Vec<String>,
|
||||
file: &Path,
|
||||
@@ -73,7 +74,7 @@ pub(super) fn build_javac_step(
|
||||
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", out_dir.display())))?;
|
||||
// Raw `javac` prints `path:line: error: …`, the same form Gradle forwards.
|
||||
let mut step = BuildStep::new(javac, &[], cwd, Format::Gradle);
|
||||
step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
|
||||
step.args.extend(["-encoding".into(), encoding.to_owned(), "-g".into()]);
|
||||
step.args.extend(["-d".into(), out_dir.to_string_lossy().into_owned()]);
|
||||
if !classpath.is_empty() {
|
||||
step.args.extend(["-cp".into(), classpath.to_owned()]);
|
||||
@@ -118,6 +119,8 @@ pub struct SingleFileTarget {
|
||||
pub pl: String,
|
||||
/// `maven.compiler.release` (or equivalent) of the module's project.
|
||||
pub java_version: Option<u32>,
|
||||
/// `project.build.sourceEncoding` of the module's project, as the POM spells it.
|
||||
pub source_encoding: Option<String>,
|
||||
}
|
||||
|
||||
/// Locates the linked Maven module owning a `.java` source file.
|
||||
@@ -143,12 +146,19 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
|
||||
let module = subdir(root, &project.dir);
|
||||
let top = maven_reactor(m, &project.dir)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
|
||||
let pl = maven::module_selector(root, top, project).unwrap_or_default();
|
||||
// Test sources see the test classpath and compile into test classes.
|
||||
let test = is_test_source(&rel);
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
Ok(SingleFileTarget {
|
||||
module,
|
||||
test,
|
||||
out_dir,
|
||||
top: top.clone(),
|
||||
pl,
|
||||
java_version: project.java_version,
|
||||
source_encoding: project.source_encoding.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The Maven reactor target for a launch module whose source file is not known yet.
|
||||
@@ -164,10 +174,17 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
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);
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
|
||||
let pl = maven::module_selector(root, top, project).unwrap_or_default();
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
Ok(SingleFileTarget {
|
||||
module,
|
||||
test,
|
||||
out_dir,
|
||||
top: top.clone(),
|
||||
pl,
|
||||
java_version: project.java_version,
|
||||
source_encoding: project.source_encoding.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// `javac` for the module: its `JAVA_HOME`, else `PATH`.
|
||||
@@ -407,8 +424,11 @@ fn classpaths(
|
||||
if compile_first {
|
||||
args.push("compile");
|
||||
}
|
||||
let build_classpath =
|
||||
maven::plugin_goal("dependency:build-classpath", maven::local_repository_for(&top.options).as_deref());
|
||||
let build_classpath = maven::plugin_goal(
|
||||
"dependency:build-classpath",
|
||||
maven::local_repository_for(&top.options).as_deref(),
|
||||
maven::maven_version(&top.command),
|
||||
);
|
||||
args.extend([build_classpath.as_str(), output_arg.as_str(), scope_arg.as_str(), "-q"]);
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let owned_args: Vec<String> = args.into_iter().map(str::to_owned).collect();
|
||||
@@ -470,7 +490,17 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget)
|
||||
pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult<BuildStep> {
|
||||
let sources = source_roots(target);
|
||||
let release = release_args(target.java_version, java_home_major(&target.top.env));
|
||||
build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone())
|
||||
build_javac_step(
|
||||
javac,
|
||||
&target.module,
|
||||
&target.out_dir,
|
||||
classpath,
|
||||
target.source_encoding.as_deref().unwrap_or("UTF-8"),
|
||||
&sources,
|
||||
release,
|
||||
file,
|
||||
target.top.env.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The module's Java source folders that exist, generated ones included; test sources see
|
||||
@@ -573,17 +603,16 @@ pub fn gradle_compile_file_plan(
|
||||
fs::create_dir_all(cache)?;
|
||||
let init_script = cache.join("gradle-compile-cp.init.gradle");
|
||||
fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?;
|
||||
let args = vec![
|
||||
"--console=plain".into(),
|
||||
"-q".into(),
|
||||
"-Dorg.gradle.configuration-cache=false".into(),
|
||||
let gradle_dir = subdir(root, &gradle.dir);
|
||||
let mut args = vec!["--console=plain".into(), "-q".into(), "-Dorg.gradle.configuration-cache=false".into()];
|
||||
args.extend(crate::gradle::no_isolated_projects(&gradle_dir, &gradle.env));
|
||||
args.extend([
|
||||
"--init-script".into(),
|
||||
init_script.to_string_lossy().into_owned(),
|
||||
format!("-Popenidea.target={}", project.path),
|
||||
format!("-Popenidea.scope={scope}"),
|
||||
"help".into(),
|
||||
];
|
||||
let gradle_dir = subdir(root, &gradle.dir);
|
||||
]);
|
||||
let mut reported: Option<String> = None;
|
||||
let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| {
|
||||
if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") {
|
||||
@@ -646,8 +675,17 @@ pub fn gradle_compile_file_plan(
|
||||
}
|
||||
let javac = find_javac(&gradle.env);
|
||||
let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env));
|
||||
let step =
|
||||
build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?;
|
||||
let step = build_javac_step(
|
||||
&javac,
|
||||
&module_dir,
|
||||
&out_dir,
|
||||
&classpath,
|
||||
"UTF-8",
|
||||
&sources,
|
||||
release,
|
||||
file,
|
||||
gradle.env.clone(),
|
||||
)?;
|
||||
Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
@@ -708,6 +746,28 @@ mod tests {
|
||||
assert_eq!(test.out_dir, root.join("app/target/test-classes"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_reads_sources_in_the_encoding_of_the_module_pom() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root_buf = dunce::canonicalize(dir.path()).unwrap();
|
||||
let root = root_buf.as_path();
|
||||
fixture(root);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>app</artifactId>
|
||||
<properties><project.build.sourceEncoding>ISO-8859-15</project.build.sourceEncoding></properties></project>"#,
|
||||
);
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let file = root.join("app/src/main/java/demo/Main.java");
|
||||
let target = single_file_target(root, &model, &file).unwrap();
|
||||
let step = javac_step(&target, &file, "", "javac").unwrap();
|
||||
let at = step.args.iter().position(|a| a == "-encoding").expect("an -encoding");
|
||||
assert_eq!(step.args[at + 1], "ISO-8859-15");
|
||||
assert_eq!(target.source_encoding.as_deref(), Some("ISO-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_rejects_non_java_missing_and_unlinked_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -40,6 +40,15 @@ def describe = { Project p ->
|
||||
try { p.extensions.findByName('testing')?.suites?.each { suites << it.sources.name } } catch (ignored) {}
|
||||
def ideaTests = [] as Set
|
||||
try { p.extensions.findByName('idea')?.module?.testSources?.files?.each { ideaTests << canon(it) } } catch (ignored) {}
|
||||
// The `Test` tasks running each classes folder, as IDEA maps tests to tasks: a JVM test
|
||||
// suite's tests run with its own task (`integrationTest`), not with `test`.
|
||||
def testTasks = [:]
|
||||
try {
|
||||
p.tasks.withType(Test).each { t ->
|
||||
def dirs = t.hasProperty('testClassesDirs') ? t.testClassesDirs.files : [t.testClassesDir]
|
||||
dirs.findAll { it != null }.each { testTasks.get(canon(it), []) << t.name }
|
||||
}
|
||||
} catch (ignored) {}
|
||||
m.sourceSets = sets.collect { s ->
|
||||
def res = s.resources.srcDirs.collect(canon)
|
||||
def src = s.allSource.srcDirs.collect(canon) - res
|
||||
@@ -49,6 +58,11 @@ def describe = { Project p ->
|
||||
def set = [name: s.name, test: test, src: src, res: res]
|
||||
def processed = processedResources(p, s)
|
||||
if (processed != null) set.processed = processed
|
||||
try {
|
||||
def classes = s.output.hasProperty('classesDirs') ? s.output.classesDirs.files : [s.output.classesDir]
|
||||
def tasks = classes.findAll { it != null }.collectMany { testTasks[canon(it)] ?: [] }.unique()
|
||||
if (!tasks.isEmpty()) set.testTasks = tasks
|
||||
} catch (ignored) {}
|
||||
set
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,47 @@ 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"];
|
||||
const ISOLATED_PROJECTS: [&str; 2] = ["org.gradle.isolated-projects", "org.gradle.unsafe.isolated-projects"];
|
||||
|
||||
/// Arguments turning Isolated Projects off for the IDE's own model reads of the build at `dir`, when
|
||||
/// the build enables it: Gradle refuses them without the configuration cache, and their init scripts
|
||||
/// read projects across the build. Other builds keep their command line. Gradle 9 still reads the
|
||||
/// Gradle 8 name.
|
||||
pub(crate) fn no_isolated_projects(dir: &Path, env: &BTreeMap<String, String>) -> Vec<String> {
|
||||
// The variable as the Gradle process gets it: the project's and the login shell's environment too.
|
||||
let inherited = ide_core::process::host_vars_in(dir)
|
||||
.chain(ide_core::process::shell_env_in(dir))
|
||||
.find(|(key, _)| key == "GRADLE_USER_HOME")
|
||||
.map(|(_, value)| value);
|
||||
let home = user_home(dir, env, inherited, dirs::home_dir());
|
||||
if !isolated_projects(dir, home.as_deref()) {
|
||||
return Vec::new();
|
||||
}
|
||||
ISOLATED_PROJECTS.iter().map(|key| format!("-D{key}=false")).collect()
|
||||
}
|
||||
|
||||
fn user_home(
|
||||
dir: &Path,
|
||||
env: &BTreeMap<String, String>,
|
||||
inherited: Option<std::ffi::OsString>,
|
||||
home: Option<PathBuf>,
|
||||
) -> Option<PathBuf> {
|
||||
let set = env.get("GRADLE_USER_HOME").map(PathBuf::from).or_else(|| inherited.map(PathBuf::from));
|
||||
set.map(|path| dir.join(path)).or_else(|| Some(home?.join(".gradle")))
|
||||
}
|
||||
|
||||
/// The user home's `gradle.properties` overrides the build's; when the two names disagree, Gradle
|
||||
/// keeps Isolated Projects off.
|
||||
fn isolated_projects(dir: &Path, user_home: Option<&Path>) -> bool {
|
||||
let user = user_home.map(file_properties).unwrap_or_default();
|
||||
let build = file_properties(dir);
|
||||
let values: Vec<bool> = ISOLATED_PROJECTS
|
||||
.iter()
|
||||
.filter_map(|key| user.get(*key).or_else(|| build.get(*key)))
|
||||
.map(|value| value.eq_ignore_ascii_case("true"))
|
||||
.collect();
|
||||
values.contains(&true) && !values.contains(&false)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -51,6 +92,20 @@ pub struct GradleProject {
|
||||
/// `:buildSrc`); null for the opened build.
|
||||
#[serde(default)]
|
||||
pub build: Option<String>,
|
||||
/// The project's `Test` tasks, or null before Gradle reports the project.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub test_tasks: Option<Vec<GradleTestTask>>,
|
||||
}
|
||||
|
||||
/// A `Test` task and the source folders of the source sets whose test classes it runs.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GradleTestTask {
|
||||
/// Name in its project (`test`, `integrationTest`).
|
||||
pub name: String,
|
||||
/// Project-relative.
|
||||
pub source_folders: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -341,6 +396,7 @@ fn project_at(root: &Path, path: String, name: String, pdir: &Path) -> GradlePro
|
||||
tasks,
|
||||
resolvable_configurations: None,
|
||||
build: None,
|
||||
test_tasks: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -380,6 +436,9 @@ pub struct ReportedSourceSet {
|
||||
/// includes / excludes, extra sources), which the Java language server's copy does not.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub processed: Option<ProcessedResources>,
|
||||
/// The `Test` tasks whose `testClassesDirs` hold the set's classes.
|
||||
#[serde(default, rename = "testTasks", skip_serializing_if = "Vec::is_empty")]
|
||||
pub test_tasks: Vec<String>,
|
||||
}
|
||||
|
||||
/// The task that copies a source set's resources, and where it writes them.
|
||||
@@ -455,6 +514,7 @@ pub fn merge_reported_projects(root: &Path, model: &mut GradleModel, reported: &
|
||||
}
|
||||
project.resolvable_configurations = p.resolvable_configurations.clone();
|
||||
project.build = p.build.clone();
|
||||
project.test_tasks = Some(test_tasks(root, p));
|
||||
project
|
||||
})
|
||||
.collect();
|
||||
@@ -466,6 +526,20 @@ pub fn merge_reported_projects(root: &Path, model: &mut GradleModel, reported: &
|
||||
}
|
||||
}
|
||||
|
||||
fn test_tasks(root: &Path, p: &ReportedProject) -> Vec<GradleTestTask> {
|
||||
let mut out: Vec<GradleTestTask> = Vec::new();
|
||||
for set in &p.source_sets {
|
||||
for name in &set.test_tasks {
|
||||
let folders = set.src.iter().map(|dir| rel(root, Path::new(dir)));
|
||||
match out.iter_mut().find(|t| t.name == *name) {
|
||||
Some(task) => task.source_folders.extend(folders),
|
||||
None => out.push(GradleTestTask { name: name.clone(), source_folders: folders.collect() }),
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Project directories outside `root`, outermost only (`../svc`, not also `../svc/sources/app`):
|
||||
/// the folders IDEA shows as extra top-level module roots.
|
||||
pub fn external_roots<'a>(root: &Path, dirs: impl IntoIterator<Item = &'a str>) -> Vec<PathBuf> {
|
||||
@@ -1545,6 +1619,53 @@ dependencies {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn isolated_projects_are_read_from_the_build_and_the_user_home() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (build, home) = (temp.path().join("build"), temp.path().join("home"));
|
||||
std::fs::create_dir_all(&build).unwrap();
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let enabled = |user_home: Option<&Path>| isolated_projects(&build, user_home);
|
||||
assert!(!enabled(Some(&home)), "no gradle.properties");
|
||||
std::fs::write(build.join("gradle.properties"), "org.gradle.jvmargs=-Xmx2g\n").unwrap();
|
||||
assert!(!enabled(Some(&home)), "not enabled");
|
||||
std::fs::write(build.join("gradle.properties"), "org.gradle.isolated-projects=true\n").unwrap();
|
||||
assert!(enabled(Some(&home)), "the build's gradle.properties");
|
||||
assert!(enabled(None));
|
||||
std::fs::write(home.join("gradle.properties"), "org.gradle.isolated-projects=false\n").unwrap();
|
||||
assert!(!enabled(Some(&home)), "the user home overrides the build");
|
||||
std::fs::write(build.join("gradle.properties"), "").unwrap();
|
||||
std::fs::write(home.join("gradle.properties"), "org.gradle.unsafe.isolated-projects = true\n").unwrap();
|
||||
assert!(enabled(Some(&home)), "the user home's gradle.properties, Gradle 8 name");
|
||||
std::fs::write(build.join("gradle.properties"), "org.gradle.isolated-projects=false\n").unwrap();
|
||||
assert!(!enabled(Some(&home)), "disabled under either name wins");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gradle_user_home_is_the_builds_setting_then_the_environment_then_dot_gradle() {
|
||||
let dir = Path::new("/build");
|
||||
let env = BTreeMap::from([("GRADLE_USER_HOME".to_owned(), "/setting".to_owned())]);
|
||||
let inherited = || Some(std::ffi::OsString::from("/inherited"));
|
||||
let home = || Some(PathBuf::from("/home/u"));
|
||||
assert_eq!(user_home(dir, &env, inherited(), home()), Some(PathBuf::from("/setting")));
|
||||
assert_eq!(user_home(dir, &BTreeMap::new(), inherited(), home()), Some(PathBuf::from("/inherited")));
|
||||
assert_eq!(user_home(dir, &BTreeMap::new(), None, home()), Some(PathBuf::from("/home/u/.gradle")));
|
||||
let relative = Some(std::ffi::OsString::from("gradle-home"));
|
||||
assert_eq!(user_home(dir, &BTreeMap::new(), relative, home()), Some(PathBuf::from("/build/gradle-home")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_without_isolated_projects_keep_their_command_line() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let env = BTreeMap::from([("GRADLE_USER_HOME".to_owned(), temp.path().join("home").display().to_string())]);
|
||||
assert!(no_isolated_projects(temp.path(), &env).is_empty());
|
||||
std::fs::write(temp.path().join("gradle.properties"), "org.gradle.isolated-projects=true\n").unwrap();
|
||||
assert_eq!(
|
||||
no_isolated_projects(temp.path(), &env),
|
||||
["-Dorg.gradle.isolated-projects=false", "-Dorg.gradle.unsafe.isolated-projects=false"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_scripts() {
|
||||
let kts = r#"
|
||||
@@ -1748,4 +1869,48 @@ Pattern: clean<TaskName>: Cleans the output files of a task.
|
||||
assert!(!model.projects[4].tasks.is_empty());
|
||||
assert!(build_files(&root, &model).contains(&ws.join("lib/settings.gradle")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reported_test_tasks_carry_the_source_folders_they_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let src = |dir: &str| root.join(dir).to_string_lossy().into_owned();
|
||||
let set = |name: &str, dirs: &[&str], tasks: &[&str]| ReportedSourceSet {
|
||||
name: name.into(),
|
||||
test: !tasks.is_empty(),
|
||||
src: dirs.iter().map(|d| src(d)).collect(),
|
||||
test_tasks: tasks.iter().map(|t| (*t).into()).collect(),
|
||||
..ReportedSourceSet::default()
|
||||
};
|
||||
// As `gradle-model.gradle` prints a project with a JVM test suite.
|
||||
let reported = ReportedProject {
|
||||
path: ":app".into(),
|
||||
dir: src("app"),
|
||||
source_sets: vec![
|
||||
set("main", &["app/src/main/java"], &[]),
|
||||
set("test", &["app/src/test/java"], &["test"]),
|
||||
set(
|
||||
"integrationTest",
|
||||
&["app/src/integrationTest/java", "app/src/integrationTest/kotlin"],
|
||||
&["integrationTest"],
|
||||
),
|
||||
],
|
||||
..ReportedProject::default()
|
||||
};
|
||||
let line = format!("{MODEL_LINE}{}\n", serde_json::to_string(&reported).unwrap());
|
||||
assert!(line.contains(r#""testTasks":["integrationTest"]"#), "{line}");
|
||||
let mut model = GradleModel::default();
|
||||
merge_reported_projects(&root, &mut model, &parse_reported_projects(&line));
|
||||
let task = |name: &str, folders: &[&str]| GradleTestTask {
|
||||
name: name.into(),
|
||||
source_folders: folders.iter().map(|f| (*f).into()).collect(),
|
||||
};
|
||||
assert_eq!(
|
||||
model.projects[0].test_tasks,
|
||||
Some(vec![
|
||||
task("test", &["app/src/test/java"]),
|
||||
task("integrationTest", &["app/src/integrationTest/java", "app/src/integrationTest/kotlin"]),
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -64,9 +64,303 @@ pub struct JavaBuildService {
|
||||
}
|
||||
|
||||
impl JavaBuildService {
|
||||
fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
|
||||
pub(crate) fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
|
||||
self.locks.lock().unwrap().entry(dir.to_path_buf()).or_default().clone()
|
||||
}
|
||||
|
||||
/// Compiles what changed in one source set (see [`incremental`]).
|
||||
pub fn compile_incremental(
|
||||
&self,
|
||||
set: &IncrementalSet<'_>,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
messages: &mut Vec<BuildMessage>,
|
||||
) -> IdeResult<IncrementalOutcome> {
|
||||
if set.clean {
|
||||
remove_classes(&set.output);
|
||||
let _ = std::fs::remove_dir_all(&set.generated_dir);
|
||||
let _ = std::fs::remove_file(&set.state_file);
|
||||
}
|
||||
let source_stamps: BTreeMap<PathBuf, FileStamp> =
|
||||
set.sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect();
|
||||
let previous = incremental::load_state(&set.state_file);
|
||||
let reactor: Vec<PathBuf> = set.upstream_states.iter().map(|(o, _)| o.clone()).collect();
|
||||
let stamp = SetStamp {
|
||||
options: set.options.clone(),
|
||||
libraries: set.libraries.iter().map(|e| (e.clone(), file_stamp(e))).collect(),
|
||||
reactor,
|
||||
processor_path: set.processor_path.iter().map(|p| (p.clone(), file_stamp(p))).collect(),
|
||||
java_home: set.java_home.clone(),
|
||||
};
|
||||
|
||||
// What the upstream outputs it compiles against changed since it last compiled.
|
||||
let mut upstream = BTreeMap::new();
|
||||
let mut upstream_changed = BTreeSet::new();
|
||||
let mut upstream_all = false;
|
||||
for (entry, up_state_file) in &set.upstream_states {
|
||||
let state = incremental::load_state(up_state_file);
|
||||
let generation = state.as_ref().map_or(0, |s| s.generation);
|
||||
upstream.insert(entry.clone(), generation);
|
||||
let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied();
|
||||
if recorded == Some(generation) {
|
||||
continue;
|
||||
}
|
||||
match (recorded, state.and_then(|s| s.changes_since(recorded?))) {
|
||||
(Some(_), Some(changed)) => upstream_changed.extend(changed),
|
||||
_ => upstream_all = true,
|
||||
}
|
||||
}
|
||||
|
||||
let had_state = previous.is_some();
|
||||
let previous = previous.unwrap_or_default();
|
||||
let force_canonical: HashSet<PathBuf> = set.force.iter().filter_map(|p| dunce::canonicalize(p).ok()).collect();
|
||||
let mut changed: BTreeSet<PathBuf> = source_stamps
|
||||
.iter()
|
||||
.filter(|(path, stamp)| {
|
||||
previous.sources.get(*path) != Some(*stamp)
|
||||
|| previous.dirty.contains(*path)
|
||||
|| set.force.contains(*path)
|
||||
|| (!force_canonical.is_empty()
|
||||
&& dunce::canonicalize(path).ok().is_some_and(|c| force_canonical.contains(&c)))
|
||||
})
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
let removed: BTreeSet<PathBuf> =
|
||||
previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect();
|
||||
let mut from_scratch = !had_state
|
||||
|| previous.stamp != stamp
|
||||
|| upstream_all
|
||||
|| !set.output.is_dir()
|
||||
|| (!previous.success && previous.dirty.is_empty());
|
||||
if had_state && !from_scratch {
|
||||
for record in previous.classes.values() {
|
||||
if !record.file.is_file() {
|
||||
match &record.source {
|
||||
Some(src) if source_stamps.contains_key(src) => {
|
||||
changed.insert(src.clone());
|
||||
}
|
||||
Some(src) if removed.contains(src) => {}
|
||||
_ => {
|
||||
from_scratch = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
|
||||
return Ok(IncrementalOutcome { failed: false, compiled_files: 0, outputs_changed: false });
|
||||
}
|
||||
// Processors that aggregate (or name no originating source) can't be followed class by class.
|
||||
let has_changes = !changed.is_empty() || !removed.is_empty() || !upstream_changed.is_empty();
|
||||
let from_scratch =
|
||||
from_scratch || ((!previous.generated.is_empty() || !previous.unowned.is_empty()) && has_changes);
|
||||
|
||||
let mut state = SetState {
|
||||
stamp,
|
||||
sources: source_stamps.clone(),
|
||||
generation: previous.generation,
|
||||
upstream,
|
||||
classes: previous.classes,
|
||||
changes: previous.changes,
|
||||
..Default::default()
|
||||
};
|
||||
let mut api_changed = BTreeSet::new();
|
||||
let mut constants_changed = false;
|
||||
// Classes of removed sources go first, and count as changed.
|
||||
let gone: Vec<String> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect();
|
||||
let gone_empty = gone.is_empty();
|
||||
for name in gone {
|
||||
let record = state.classes.remove(&name).expect("listed");
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
constants_changed |= record.constants != incremental::NO_CONSTANTS;
|
||||
api_changed.insert(name);
|
||||
}
|
||||
let mut to_compile: BTreeSet<PathBuf> = if from_scratch || constants_changed {
|
||||
remove_classes(&set.output);
|
||||
for file in previous.generated.iter().chain(&previous.unowned) {
|
||||
let _ = std::fs::remove_file(file);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&set.generated_dir);
|
||||
state.classes.retain(|_, r| r.source.is_some());
|
||||
source_stamps.keys().cloned().collect()
|
||||
} else {
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
|
||||
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
|
||||
};
|
||||
std::fs::create_dir_all(&set.output)?;
|
||||
std::fs::create_dir_all(&set.generated_dir)?;
|
||||
|
||||
let total = source_stamps.len();
|
||||
let mut compiled: BTreeSet<PathBuf> = BTreeSet::new();
|
||||
let mut server = None;
|
||||
loop {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let batch: BTreeSet<PathBuf> = to_compile
|
||||
.iter()
|
||||
.filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s))
|
||||
.cloned()
|
||||
.collect();
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
// The classes the batch replaces: their files go first, so nothing stale is left.
|
||||
let replaced: BTreeMap<String, ClassRecord> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
|
||||
.map(|(n, r)| (n.clone(), r.clone()))
|
||||
.collect();
|
||||
for (name, record) in &replaced {
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
state.classes.remove(name);
|
||||
}
|
||||
let files: Vec<PathBuf> = batch.iter().cloned().collect();
|
||||
let noun = if total == 1 { "file" } else { "files" };
|
||||
let count = if files.len() == total {
|
||||
format!("{total} {noun}")
|
||||
} else {
|
||||
format!("{} of {total} {noun}", files.len())
|
||||
};
|
||||
on_event(BuildEvent::Step {
|
||||
command: format!("javac {} ({}, {count})", set.module_name, set.set_name),
|
||||
cwd: set.cwd.clone().into(),
|
||||
});
|
||||
if server.is_none() {
|
||||
let key = ServerKey { java_home: set.java_home.clone(), jvm_args: set.jvm_args.clone() };
|
||||
server = Some(self.servers.server(set.jar, &key)?);
|
||||
}
|
||||
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
|
||||
let result =
|
||||
server.as_ref().expect("started").compile(&set.options, &files, set.encoding, cancel, |reply| {
|
||||
match reply {
|
||||
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
|
||||
Reply::Generated { path, .. } => state.generated.push(path.clone()),
|
||||
Reply::OutputText { text } => {
|
||||
on_event(BuildEvent::Output { text: text.clone(), stderr: false })
|
||||
}
|
||||
Reply::Diagnostic { .. } => {
|
||||
if let Some(m) = diagnostic(reply) {
|
||||
on_event(BuildEvent::Output {
|
||||
text: message_text(&m),
|
||||
stderr: m.severity == Severity::Error,
|
||||
});
|
||||
on_event(BuildEvent::Message { message: m.clone() });
|
||||
messages.push(m);
|
||||
}
|
||||
}
|
||||
Reply::Done { .. } => {}
|
||||
}
|
||||
});
|
||||
if !matches!(result, Ok(true)) {
|
||||
for (path, _) in &written {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
// The next build starts from the state this one started from, with whatever this
|
||||
// one had to compile still to compile. Its earlier rounds' classes are not the
|
||||
// baseline: compared with them, the API and constant changes those rounds found
|
||||
// would never reach this set's dependents or the sets compiled against it.
|
||||
let mut retry = incremental::load_state(&set.state_file).unwrap_or_default();
|
||||
retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned());
|
||||
retry.success = false;
|
||||
let _ = model::write_json(&set.state_file, &retry);
|
||||
return result.map(|_| IncrementalOutcome {
|
||||
failed: true,
|
||||
compiled_files: compiled.len(),
|
||||
outputs_changed: false,
|
||||
});
|
||||
}
|
||||
// javac names sources as they were passed; other spellings are matched canonically,
|
||||
// and classes of sources outside the set (processors' output) are unowned.
|
||||
let canonical: HashMap<PathBuf, &PathBuf> =
|
||||
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
|
||||
let own = |source: PathBuf| -> Option<PathBuf> {
|
||||
if source_stamps.contains_key(&source) {
|
||||
return Some(source);
|
||||
}
|
||||
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
|
||||
};
|
||||
let mut fresh = BTreeMap::new();
|
||||
for (path, source) in written {
|
||||
let source = source.and_then(own);
|
||||
let class = (path.extension().is_some_and(|e| e == "class"))
|
||||
.then(|| std::fs::read(&path).ok())
|
||||
.flatten()
|
||||
.and_then(|bytes| classfile::parse(&bytes));
|
||||
match (class, source) {
|
||||
(Some(class), Some(source)) => {
|
||||
let (name, record) = ClassRecord::new(class, path, Some(source));
|
||||
fresh.insert(name, record);
|
||||
}
|
||||
_ => state.unowned.push(path),
|
||||
}
|
||||
}
|
||||
let round = incremental::diff(&replaced, &fresh);
|
||||
constants_changed |= round.constants;
|
||||
api_changed.extend(round.api.iter().cloned());
|
||||
state.classes.extend(fresh);
|
||||
compiled.extend(batch);
|
||||
if constants_changed {
|
||||
// Constants are copied into the classes that use them: compile the rest too.
|
||||
to_compile.extend(source_stamps.keys().cloned());
|
||||
continue;
|
||||
}
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
|
||||
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
|
||||
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
|
||||
}
|
||||
state.success = true;
|
||||
if !compiled.is_empty() || !api_changed.is_empty() {
|
||||
let changed =
|
||||
incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect());
|
||||
state.log(now_generation(), changed, !had_state || constants_changed);
|
||||
}
|
||||
model::write_json(&set.state_file, &state)?;
|
||||
Ok(IncrementalOutcome {
|
||||
failed: false,
|
||||
compiled_files: compiled.len(),
|
||||
outputs_changed: !compiled.is_empty() || !gone_empty,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Inputs for compiling one source set incrementally with the resident `javac` server.
|
||||
pub struct IncrementalSet<'a> {
|
||||
pub module_name: String,
|
||||
pub set_name: &'static str,
|
||||
pub cwd: PathBuf,
|
||||
pub sources: Vec<PathBuf>,
|
||||
pub output: PathBuf,
|
||||
pub options: Vec<String>,
|
||||
pub libraries: Vec<PathBuf>,
|
||||
/// Upstream `(output_dir, state_file)` pairs this set compiles against.
|
||||
pub upstream_states: Vec<(PathBuf, PathBuf)>,
|
||||
pub processor_path: Vec<PathBuf>,
|
||||
pub java_home: PathBuf,
|
||||
pub jvm_args: Vec<String>,
|
||||
pub encoding: Option<&'a str>,
|
||||
pub state_file: PathBuf,
|
||||
pub generated_dir: PathBuf,
|
||||
pub force: &'a BTreeSet<PathBuf>,
|
||||
pub jar: &'a Path,
|
||||
pub clean: bool,
|
||||
}
|
||||
|
||||
/// Result of compiling one source set incrementally.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct IncrementalOutcome {
|
||||
pub failed: bool,
|
||||
pub compiled_files: usize,
|
||||
pub outputs_changed: bool,
|
||||
}
|
||||
|
||||
/// One build of the IDE's Java build service.
|
||||
@@ -79,6 +373,8 @@ pub struct JavaBuild<'a> {
|
||||
/// Changes when the jar does, so models recorded by an older extension are prepared again.
|
||||
pub jar_version: &'a str,
|
||||
pub local_repo: Option<PathBuf>,
|
||||
/// Explicit Maven goals the project's settings allow the IDE to skip in compile phases.
|
||||
pub ignored_maven_compile_goals: &'a [String],
|
||||
pub service: &'a JavaBuildService,
|
||||
/// The JDK home that compiles for a release, when Maven's environment names none.
|
||||
pub jdk: &'a (dyn Fn(Option<u32>) -> Option<PathBuf> + Sync),
|
||||
@@ -214,51 +510,116 @@ fn ant_match(pattern: &str, path: &str) -> bool {
|
||||
segments(&p, &s)
|
||||
}
|
||||
|
||||
/// The `.java` files of a source set, filtered by the compiler's includes and excludes.
|
||||
/// The `.java` files of a source set, filtered by the compiler's includes and excludes. A file
|
||||
/// reached through several links is listed once: javac 8 fails on a class named twice, and newer
|
||||
/// ones record a single source for it, whose removal would leave the other spelling uncompiled.
|
||||
/// Deduplication runs after includes/excludes so an excluded alias cannot hide a valid path, and
|
||||
/// prefers a path that passes through no symlink over a linked one.
|
||||
fn java_sources(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<Vec<PathBuf>> {
|
||||
let config = set.compiler.as_ref();
|
||||
let includes = config.map(|c| c.includes.as_slice()).unwrap_or_default();
|
||||
let excludes = config.map(|c| c.excludes.as_slice()).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut kept: HashMap<PathBuf, (PathBuf, bool)> = HashMap::new();
|
||||
for root in &set.source_roots {
|
||||
if model::is_processor_output(set, root) || !root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let mut pending = vec![root.clone()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
walk_files(root, cancel, &mut |path, canonical, via_link| {
|
||||
if path.extension().is_none_or(|e| e != "java") {
|
||||
return;
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let Ok(kind) = entry.file_type() else { continue };
|
||||
if kind.is_dir() {
|
||||
pending.push(path);
|
||||
} else if path.extension().is_some_and(|e| e == "java") {
|
||||
let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = includes.is_empty() || includes.iter().any(|p| ant_match(p, &rel));
|
||||
if included && !excludes.iter().any(|p| ant_match(p, &rel)) && seen.insert(path.clone()) {
|
||||
out.push(path);
|
||||
let rel = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = includes.is_empty() || includes.iter().any(|p| ant_match(p, &rel));
|
||||
if !included || excludes.iter().any(|p| ant_match(p, &rel)) {
|
||||
return;
|
||||
}
|
||||
match kept.entry(canonical) {
|
||||
std::collections::hash_map::Entry::Vacant(slot) => {
|
||||
slot.insert((path, via_link));
|
||||
}
|
||||
std::collections::hash_map::Entry::Occupied(mut slot) => {
|
||||
if slot.get().1 && !via_link {
|
||||
slot.insert((path, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let mut out: Vec<PathBuf> = kept.into_values().map(|(path, _)| path).collect();
|
||||
out.sort();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `-g`, `-g:lines,vars` or `-g:none`, as maven-compiler-plugin passes them.
|
||||
fn debug_args(c: &CompilerConfig) -> Vec<String> {
|
||||
if c.debug == Some(false) {
|
||||
return vec!["-g:none".into()];
|
||||
/// Reports the files under `root` with their canonical paths and whether the path passed through
|
||||
/// any symlink, following links to folders: a module can link a shared source folder into its own,
|
||||
/// and Maven's resources plugin copies through such links too. Files keep the spelling under
|
||||
/// `root`, so javac's messages and the debugger name the path the user opened. Only links back to
|
||||
/// an ancestor on the current descent path (cycles) are skipped. Each folder is read in full
|
||||
/// before its subfolders, so a deep tree holds one open directory at a time; real entries come
|
||||
/// before links, by name, so the walk order does not depend on the file system's order.
|
||||
fn walk_files(root: &Path, cancel: &CancellationToken, found: &mut dyn FnMut(PathBuf, PathBuf, bool)) -> IdeResult<()> {
|
||||
type DirEntry = (bool, std::ffi::OsString, PathBuf, bool);
|
||||
struct Frame {
|
||||
canonical: std::rc::Rc<PathBuf>,
|
||||
via_link: bool,
|
||||
entries: std::vec::IntoIter<DirEntry>,
|
||||
}
|
||||
match c.debuglevel.as_deref().map(str::trim).filter(|l| !l.is_empty()) {
|
||||
Some(level) => vec![format!("-g:{level}")],
|
||||
None => vec!["-g".into()],
|
||||
|
||||
fn read_sorted_entries(dir: &Path, cancel: &CancellationToken) -> IdeResult<Option<std::vec::IntoIter<DirEntry>>> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(read) = std::fs::read_dir(dir) else { return Ok(None) };
|
||||
let mut entries: Vec<DirEntry> = read
|
||||
.flatten()
|
||||
.filter_map(|e| {
|
||||
let kind = e.file_type().ok()?;
|
||||
Some((kind.is_symlink(), e.file_name(), e.path(), kind.is_dir()))
|
||||
})
|
||||
.collect();
|
||||
entries.sort();
|
||||
Ok(Some(entries.into_iter()))
|
||||
}
|
||||
|
||||
let Ok(canonical) = dunce::canonicalize(root) else { return Ok(()) };
|
||||
let via_link = std::fs::symlink_metadata(root).is_ok_and(|m| m.file_type().is_symlink());
|
||||
let Some(entries) = read_sorted_entries(root, cancel)? else { return Ok(()) };
|
||||
|
||||
let root_canonical = std::rc::Rc::new(canonical);
|
||||
let mut ancestors: HashSet<std::rc::Rc<PathBuf>> = HashSet::from([std::rc::Rc::clone(&root_canonical)]);
|
||||
let mut stack = vec![Frame { canonical: root_canonical, via_link, entries }];
|
||||
|
||||
while let Some(frame) = stack.last_mut() {
|
||||
let Some((linked, name, path, is_dir)) = frame.entries.next() else {
|
||||
let done = stack.pop().expect("top frame");
|
||||
ancestors.remove(&done.canonical);
|
||||
continue;
|
||||
};
|
||||
let (is_dir, real) = if linked {
|
||||
let (Ok(meta), Ok(target)) = (std::fs::metadata(&path), dunce::canonicalize(&path)) else { continue };
|
||||
(meta.is_dir(), target)
|
||||
} else {
|
||||
(is_dir, frame.canonical.join(&name))
|
||||
};
|
||||
let entry_via_link = frame.via_link || linked;
|
||||
if !is_dir {
|
||||
found(path, real, entry_via_link);
|
||||
} else if !ancestors.contains(&real)
|
||||
&& let Some(children) = read_sorted_entries(&path, cancel)?
|
||||
{
|
||||
let real = std::rc::Rc::new(real);
|
||||
ancestors.insert(std::rc::Rc::clone(&real));
|
||||
stack.push(Frame { canonical: real, via_link: entry_via_link, entries: children });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A javac debug-info option (`-g`, `-g:none`, `-g:lines,vars`). The IDE's build always
|
||||
/// compiles with `-g`: breakpoints need line numbers and local variables, whatever
|
||||
/// maven-compiler-plugin's `<debug>` / `<debuglevel>` ask of Maven's own build (#7786).
|
||||
fn is_debug_option(arg: &str) -> bool {
|
||||
arg == "-g" || arg.starts_with("-g:")
|
||||
}
|
||||
|
||||
/// The JDK feature version of `release` / `source` (`1.8` → 8).
|
||||
@@ -294,7 +655,7 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
|
||||
if let Some(proc) = c.proc.as_deref().filter(|p| !p.is_empty()) {
|
||||
args.push(format!("-proc:{proc}"));
|
||||
}
|
||||
args.extend(debug_args(&c));
|
||||
args.push("-g".into());
|
||||
if c.parameters == Some(true) {
|
||||
args.push("-parameters".into());
|
||||
}
|
||||
@@ -323,15 +684,19 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
|
||||
}
|
||||
}
|
||||
for (key, value) in &c.compiler_arguments {
|
||||
args.push(if key.starts_with('-') { key.clone() } else { format!("-{key}") });
|
||||
let key = if key.starts_with('-') { key.clone() } else { format!("-{key}") };
|
||||
if is_debug_option(&key) {
|
||||
continue;
|
||||
}
|
||||
args.push(key);
|
||||
if let Some(value) = value.as_ref().filter(|v| !v.is_empty()) {
|
||||
args.push(value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(argument) = &c.compiler_argument {
|
||||
args.extend(argument.split_whitespace().map(str::to_owned));
|
||||
args.extend(argument.split_whitespace().filter(|a| !is_debug_option(a)).map(str::to_owned));
|
||||
}
|
||||
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty()).cloned());
|
||||
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty() && !is_debug_option(a)).cloned());
|
||||
args
|
||||
}
|
||||
|
||||
@@ -558,7 +923,7 @@ impl JavaBuild<'_> {
|
||||
}
|
||||
};
|
||||
for (project, test) in &projects {
|
||||
if let Some(reason) = project.unsupported(*test) {
|
||||
if let Some(reason) = project.unsupported(*test, self.ignored_maven_compile_goals) {
|
||||
return Ok(Built::Unsupported(reason));
|
||||
}
|
||||
// A launch of a Java module runs it from the module path, which the language server reports.
|
||||
@@ -667,6 +1032,7 @@ impl JavaBuild<'_> {
|
||||
for project in &reactor_model.projects {
|
||||
for test in [false, true] {
|
||||
let stamp = resource_stamp(project.set(test), cancel)?;
|
||||
self.prune_resources(dir, project, test, cancel)?;
|
||||
model::write_json(&state_path(dir, project, test, "resources"), &stamp)?;
|
||||
}
|
||||
}
|
||||
@@ -702,7 +1068,11 @@ impl JavaBuild<'_> {
|
||||
let step = match top {
|
||||
Reactor::Maven(top) => {
|
||||
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
|
||||
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection];
|
||||
// The resources plugin copies a file only when it is newer than the copy; content
|
||||
// replaced without moving the mtime (a sync tool, PowerShell `Copy-Item`) would stay
|
||||
// stale while its stamp is recorded as processed.
|
||||
let mut extra =
|
||||
vec!["-q".to_owned(), "-pl".to_owned(), selection, "-Dmaven.resources.overwrite=true".to_owned()];
|
||||
extra.push("resources:resources".into());
|
||||
if changed.iter().any(|(_, test, _)| *test) {
|
||||
extra.push("resources:testResources".into());
|
||||
@@ -730,11 +1100,42 @@ impl JavaBuild<'_> {
|
||||
}));
|
||||
}
|
||||
for (project, test, stamp) in changed {
|
||||
self.prune_resources(dir, project, test, cancel)?;
|
||||
model::write_json(&state_path(dir, project, test, "resources"), &stamp)?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Removes what the sources no longer have from a source set's output: the resources step
|
||||
/// copies and overwrites, it never deletes, so a file deleted from the sources would stay on
|
||||
/// the launch's classpath (a stale `META-INF/spring.factories` then fails the application).
|
||||
fn prune_resources(
|
||||
&self,
|
||||
dir: &Path,
|
||||
project: &ProjectModel,
|
||||
test: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<()> {
|
||||
let set = project.set(test);
|
||||
let expected = resource_outputs(set, cancel)?;
|
||||
let recorded: BTreeSet<PathBuf> = std::fs::read(state_path(dir, project, test, "resource-outputs"))
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
||||
.unwrap_or_default();
|
||||
for stale in recorded.difference(&expected) {
|
||||
let _ = std::fs::remove_file(stale);
|
||||
// The folders a removed resource leaves empty are not part of the output either.
|
||||
let mut parent = stale.parent();
|
||||
while let Some(folder) = parent.filter(|d| d.starts_with(&set.output) && *d != set.output) {
|
||||
if std::fs::remove_dir(folder).is_err() {
|
||||
break;
|
||||
}
|
||||
parent = folder.parent();
|
||||
}
|
||||
}
|
||||
model::write_json(&state_path(dir, project, test, "resource-outputs"), &expected)
|
||||
}
|
||||
|
||||
/// Removes the classes of a source set and its record: the next build compiles it from scratch.
|
||||
fn clean(&self, dir: &Path, project: &ProjectModel, test: bool) -> IdeResult<()> {
|
||||
let set = project.set(test);
|
||||
@@ -758,244 +1159,46 @@ impl JavaBuild<'_> {
|
||||
return Ok(false);
|
||||
}
|
||||
let sources = java_sources(set, cancel)?;
|
||||
let source_stamps: BTreeMap<PathBuf, FileStamp> =
|
||||
sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect();
|
||||
let state_file = state_path(dir, project, test, "compile");
|
||||
let previous = incremental::load_state(&state_file);
|
||||
let config = set.compiler.clone().unwrap_or_default();
|
||||
let release = config.release.as_deref().or(config.source.as_deref()).and_then(feature);
|
||||
let java_home = self.java_home(top, &config, release)?;
|
||||
let generated = generated_dir(dir, project, test);
|
||||
let generated_dir = generated_dir(dir, project, test);
|
||||
let classpath: Vec<PathBuf> = if test {
|
||||
std::iter::once(project.main.output.clone()).chain(set.classpath.iter().cloned()).collect()
|
||||
} else {
|
||||
set.classpath.clone()
|
||||
};
|
||||
let options = javac_options(set, &classpath, &generated, jdk_major(&java_home));
|
||||
let reactor: Vec<PathBuf> =
|
||||
classpath.iter().filter(|e| **e != set.output && outputs.contains_key(*e)).cloned().collect();
|
||||
let stamp = SetStamp {
|
||||
options: options.clone(),
|
||||
libraries: classpath
|
||||
.iter()
|
||||
.filter(|e| **e != set.output && !outputs.contains_key(*e))
|
||||
.map(|e| (e.clone(), file_stamp(e)))
|
||||
.collect(),
|
||||
reactor: reactor.clone(),
|
||||
processor_path: config.processor_path.iter().flatten().map(|p| (p.clone(), file_stamp(p))).collect(),
|
||||
java_home: java_home.clone(),
|
||||
};
|
||||
|
||||
// What the reactor outputs it compiles against changed since it last compiled.
|
||||
let mut upstream = BTreeMap::new();
|
||||
let mut upstream_changed = BTreeSet::new();
|
||||
let mut upstream_all = false;
|
||||
for entry in &reactor {
|
||||
let (key, entry_test) = &outputs[entry];
|
||||
let state = incremental::load_state(&state_path_of(dir, key, *entry_test, "compile"));
|
||||
let generation = state.as_ref().map_or(0, |s| s.generation);
|
||||
upstream.insert(entry.clone(), generation);
|
||||
let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied();
|
||||
if recorded == Some(generation) {
|
||||
continue;
|
||||
}
|
||||
match (recorded, state.and_then(|s| s.changes_since(recorded?))) {
|
||||
(Some(_), Some(changed)) => upstream_changed.extend(changed),
|
||||
_ => upstream_all = true,
|
||||
}
|
||||
}
|
||||
|
||||
let had_state = previous.is_some();
|
||||
let previous = previous.unwrap_or_default();
|
||||
let changed: BTreeSet<PathBuf> = source_stamps
|
||||
let options = javac_options(set, &classpath, &generated_dir, jdk_major(&java_home));
|
||||
let upstream_states: Vec<(PathBuf, PathBuf)> = classpath
|
||||
.iter()
|
||||
.filter(|(path, stamp)| {
|
||||
previous.sources.get(*path) != Some(*stamp) || previous.dirty.contains(*path) || force.contains(*path)
|
||||
.filter(|e| **e != set.output)
|
||||
.filter_map(|e| {
|
||||
outputs.get(e).map(|(key, entry_test)| (e.clone(), state_path_of(dir, key, *entry_test, "compile")))
|
||||
})
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
let removed: BTreeSet<PathBuf> =
|
||||
previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect();
|
||||
let from_scratch = !had_state
|
||||
|| previous.stamp != stamp
|
||||
|| upstream_all
|
||||
|| !set.output.is_dir()
|
||||
|| (!previous.success && previous.dirty.is_empty());
|
||||
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
// Processors that aggregate (or name no originating source) can't be followed class by class.
|
||||
let from_scratch = from_scratch
|
||||
|| (!previous.generated.is_empty() || !previous.unowned.is_empty())
|
||||
&& !(changed.is_empty() && removed.is_empty() && upstream_changed.is_empty());
|
||||
|
||||
let mut state = SetState {
|
||||
stamp,
|
||||
sources: source_stamps.clone(),
|
||||
generation: previous.generation,
|
||||
upstream,
|
||||
classes: previous.classes,
|
||||
changes: previous.changes,
|
||||
..Default::default()
|
||||
let libraries: Vec<PathBuf> =
|
||||
classpath.iter().filter(|e| **e != set.output && !outputs.contains_key(*e)).cloned().collect();
|
||||
let incremental_set = IncrementalSet {
|
||||
module_name: project.artifact_id.clone(),
|
||||
set_name: if test { "tests" } else { "main" },
|
||||
cwd: project.dir.clone(),
|
||||
sources,
|
||||
output: set.output.clone(),
|
||||
options,
|
||||
libraries,
|
||||
upstream_states,
|
||||
processor_path: config.processor_path.unwrap_or_default(),
|
||||
jvm_args: jvm_config(top, &subdir(self.root, top.rel_dir())),
|
||||
java_home,
|
||||
encoding: config.encoding.as_deref(),
|
||||
state_file: state_path(dir, project, test, "compile"),
|
||||
generated_dir,
|
||||
force,
|
||||
jar: self.jar,
|
||||
clean: false,
|
||||
};
|
||||
let mut api_changed = BTreeSet::new();
|
||||
let mut constants_changed = false;
|
||||
// Classes of removed sources go first, and count as changed.
|
||||
let gone: Vec<String> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect();
|
||||
for name in gone {
|
||||
let record = state.classes.remove(&name).expect("listed");
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
constants_changed |= record.constants != incremental::NO_CONSTANTS;
|
||||
api_changed.insert(name);
|
||||
}
|
||||
let mut to_compile: BTreeSet<PathBuf> = if from_scratch || constants_changed {
|
||||
remove_classes(&set.output);
|
||||
for file in previous.generated.iter().chain(&previous.unowned) {
|
||||
let _ = std::fs::remove_file(file);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&generated);
|
||||
state.classes.retain(|_, r| r.source.is_some());
|
||||
source_stamps.keys().cloned().collect()
|
||||
} else {
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
|
||||
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
|
||||
};
|
||||
std::fs::create_dir_all(&set.output)?;
|
||||
std::fs::create_dir_all(&generated)?;
|
||||
|
||||
let set_name = if test { "tests" } else { "main" };
|
||||
let total = source_stamps.len();
|
||||
let mut compiled: BTreeSet<PathBuf> = BTreeSet::new();
|
||||
let mut server = None;
|
||||
loop {
|
||||
let batch: BTreeSet<PathBuf> = to_compile
|
||||
.iter()
|
||||
.filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s))
|
||||
.cloned()
|
||||
.collect();
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
// The classes the batch replaces: their files go first, so nothing stale is left.
|
||||
let replaced: BTreeMap<String, ClassRecord> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
|
||||
.map(|(n, r)| (n.clone(), r.clone()))
|
||||
.collect();
|
||||
for (name, record) in &replaced {
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
state.classes.remove(name);
|
||||
}
|
||||
let files: Vec<PathBuf> = batch.iter().cloned().collect();
|
||||
let noun = if total == 1 { "file" } else { "files" };
|
||||
let count = if files.len() == total {
|
||||
format!("{total} {noun}")
|
||||
} else {
|
||||
format!("{} of {total} {noun}", files.len())
|
||||
};
|
||||
on_event(BuildEvent::Step {
|
||||
command: format!("javac {} ({set_name}, {count})", project.artifact_id),
|
||||
cwd: project.dir.clone().into(),
|
||||
});
|
||||
if server.is_none() {
|
||||
let key = ServerKey {
|
||||
java_home: java_home.clone(),
|
||||
jvm_args: jvm_config(top, &subdir(self.root, top.rel_dir())),
|
||||
};
|
||||
server = Some(self.service.servers.server(self.jar, &key)?);
|
||||
}
|
||||
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
|
||||
let result = server.as_ref().expect("started").compile(
|
||||
&options,
|
||||
&files,
|
||||
config.encoding.as_deref(),
|
||||
cancel,
|
||||
|reply| match reply {
|
||||
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
|
||||
Reply::Generated { path, .. } => state.generated.push(path.clone()),
|
||||
Reply::OutputText { text } => on_event(BuildEvent::Output { text: text.clone(), stderr: false }),
|
||||
Reply::Diagnostic { .. } => {
|
||||
if let Some(m) = diagnostic(reply) {
|
||||
on_event(BuildEvent::Output {
|
||||
text: message_text(&m),
|
||||
stderr: m.severity == Severity::Error,
|
||||
});
|
||||
on_event(BuildEvent::Message { message: m.clone() });
|
||||
messages.push(m);
|
||||
}
|
||||
}
|
||||
Reply::Done { .. } => {}
|
||||
},
|
||||
);
|
||||
if !matches!(result, Ok(true)) {
|
||||
for (path, _) in &written {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
// The next build starts from the state this one started from, with whatever this
|
||||
// one had to compile still to compile. Its earlier rounds' classes are not the
|
||||
// baseline: compared with them, the API and constant changes those rounds found
|
||||
// would never reach this set's dependents or the sets compiled against it.
|
||||
let mut retry = incremental::load_state(&state_file).unwrap_or_default();
|
||||
retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned());
|
||||
retry.success = false;
|
||||
let _ = model::write_json(&state_file, &retry);
|
||||
return result.map(|_| true);
|
||||
}
|
||||
// javac names sources as they were passed; other spellings are matched canonically,
|
||||
// and classes of sources outside the set (processors' output) are unowned.
|
||||
let canonical: HashMap<PathBuf, &PathBuf> =
|
||||
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
|
||||
let own = |source: PathBuf| -> Option<PathBuf> {
|
||||
if source_stamps.contains_key(&source) {
|
||||
return Some(source);
|
||||
}
|
||||
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
|
||||
};
|
||||
let mut fresh = BTreeMap::new();
|
||||
for (path, source) in written {
|
||||
let source = source.and_then(own);
|
||||
let class = (path.extension().is_some_and(|e| e == "class"))
|
||||
.then(|| std::fs::read(&path).ok())
|
||||
.flatten()
|
||||
.and_then(|bytes| classfile::parse(&bytes));
|
||||
match (class, source) {
|
||||
(Some(class), Some(source)) => {
|
||||
let (name, record) = ClassRecord::new(class, path, Some(source));
|
||||
fresh.insert(name, record);
|
||||
}
|
||||
_ => state.unowned.push(path),
|
||||
}
|
||||
}
|
||||
let round = incremental::diff(&replaced, &fresh);
|
||||
constants_changed |= round.constants;
|
||||
api_changed.extend(round.api.iter().cloned());
|
||||
state.classes.extend(fresh);
|
||||
compiled.extend(batch);
|
||||
if constants_changed {
|
||||
// Constants are copied into the classes that use them: compile the rest too.
|
||||
to_compile.extend(source_stamps.keys().cloned());
|
||||
continue;
|
||||
}
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
|
||||
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
|
||||
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
|
||||
}
|
||||
state.success = true;
|
||||
if !compiled.is_empty() || !api_changed.is_empty() {
|
||||
let changed =
|
||||
incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect());
|
||||
state.log(now_generation(), changed, !had_state || constants_changed);
|
||||
}
|
||||
model::write_json(&state_file, &state)?;
|
||||
Ok(false)
|
||||
let outcome = self.service.compile_incremental(&incremental_set, cancel, on_event, messages)?;
|
||||
Ok(outcome.failed)
|
||||
}
|
||||
|
||||
/// The JDK compiling a source set: the compiler plugin's forked `executable`, else Maven's
|
||||
@@ -1110,21 +1313,29 @@ fn remove_classes(dir: &Path) {
|
||||
fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTreeMap<PathBuf, FileStamp>> {
|
||||
let mut out = BTreeMap::new();
|
||||
for root in &set.resources {
|
||||
let mut pending = vec![root.directory.clone()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
walk_files(&root.directory, cancel, &mut |path, _, _| {
|
||||
if let Some(stamp) = file_stamp(&path) {
|
||||
out.insert(path, stamp);
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
pending.push(path);
|
||||
} else if let Some(stamp) = file_stamp(&path) {
|
||||
out.insert(path, stamp);
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Where `process-resources` puts each file of a source set's resource folders: the output folder,
|
||||
/// the root's target path, then the path under the root, filtered by its includes and excludes.
|
||||
fn resource_outputs(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTreeSet<PathBuf>> {
|
||||
let mut out = BTreeSet::new();
|
||||
for root in &set.resources {
|
||||
walk_files(&root.directory, cancel, &mut |path, _, _| {
|
||||
let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel));
|
||||
if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/");
|
||||
out.insert(set.output.join(target.trim_matches('/')).join(&rel));
|
||||
})?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -105,13 +105,26 @@ impl ProjectModel {
|
||||
}
|
||||
|
||||
/// Why the IDE can't compile this project with javac itself, if it can't.
|
||||
pub fn unsupported(&self, test: bool) -> Option<String> {
|
||||
pub fn unsupported(&self, test: bool, ignored_maven_compile_goals: &[String]) -> Option<String> {
|
||||
// What the build tool couldn't resolve or read: the model would be incomplete.
|
||||
if let Some(problem) = self.problems.first() {
|
||||
return Some(format!("{}: {problem}", self.artifact_id));
|
||||
}
|
||||
if !self.other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
|
||||
// Keep the recorded model intact: adding or removing a project override must also
|
||||
// affect an already prepared model. Gradle tasks never use Maven overrides.
|
||||
let other_compilers: Vec<&str> = self
|
||||
.other_compilers
|
||||
.iter()
|
||||
.filter(|execution| {
|
||||
!(self.gradle_path.is_none()
|
||||
&& execution.split_once('@').is_some_and(|(goal, _)| {
|
||||
ignored_maven_compile_goals.iter().any(|ignored| ignored.trim() == goal)
|
||||
}))
|
||||
})
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
if !other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, other_compilers.join(", ")));
|
||||
}
|
||||
if test && !self.test_generators.is_empty() {
|
||||
return Some(format!(
|
||||
@@ -287,6 +300,7 @@ pub(super) fn gradle_step(
|
||||
&["--console=plain", "--no-configuration-cache"],
|
||||
&subdir(root, &g.dir),
|
||||
);
|
||||
step.args.extend(crate::gradle::no_isolated_projects(&step.cwd, &g.env));
|
||||
step.args.extend(["--init-script".to_owned(), init.to_string_lossy().into_owned()]);
|
||||
step.args.push(format!("-Popenidea.build.output={}", output_root.display()));
|
||||
if let Some(file) = model_file {
|
||||
|
||||
@@ -55,6 +55,75 @@ fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
|
||||
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_apply_to_cached_models_and_can_be_removed() {
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{goal}@default-jar"), format!("{goal}@extra-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
let cached: ProjectModel = serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap();
|
||||
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
|
||||
assert_eq!(cached.unsupported(false, &[goal.into()]), None);
|
||||
assert_eq!(cached.unsupported(false, &[format!(" {goal} ")]), None);
|
||||
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
|
||||
assert_eq!(cached.other_compilers, project.other_compilers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_match_exact_goals_and_keep_other_executions() {
|
||||
let jar = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let kotlin = "org.jetbrains.kotlin:kotlin-maven-plugin:compile";
|
||||
let mut project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{jar}@default-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
for unmatched in [
|
||||
"",
|
||||
"*",
|
||||
"org.apache.maven.plugins:maven-jar-plugin",
|
||||
"maven-jar-plugin:jar",
|
||||
"org.apache.maven.plugins:maven-jar-plugin:test-jar",
|
||||
"org.apache.maven.plugins:*:jar",
|
||||
] {
|
||||
assert!(project.unsupported(false, &[unmatched.into()]).is_some(), "{unmatched}");
|
||||
}
|
||||
project.other_compilers.push(format!("{kotlin}@compile"));
|
||||
let reason = project.unsupported(false, &[jar.into()]).unwrap();
|
||||
assert!(reason.contains(kotlin));
|
||||
assert!(!reason.contains(jar));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_do_not_affect_gradle_or_other_safety_checks() {
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let ignored = [goal.into()];
|
||||
let mut project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{goal}@default-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
project.gradle_path = Some(":app".into());
|
||||
assert!(project.unsupported(false, &ignored).is_some());
|
||||
project.gradle_path = None;
|
||||
project.problems.push("unresolved dependency".into());
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("unresolved dependency"));
|
||||
project.problems.clear();
|
||||
project.test_generators.push("org.example:generator:test@tests".into());
|
||||
assert_eq!(project.unsupported(false, &ignored), None);
|
||||
assert!(project.unsupported(true, &ignored).unwrap().contains("generates test sources"));
|
||||
project.test_generators.clear();
|
||||
project.main.compiler = Some(CompilerConfig { compiler_id: Some("eclipse".into()), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("eclipse"));
|
||||
project.main.compiler = Some(CompilerConfig { multi_release_output: Some(true), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("multi-release"));
|
||||
project.main.compiler =
|
||||
Some(CompilerConfig { processor_path_error: Some("missing processor".into()), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("missing processor"));
|
||||
}
|
||||
|
||||
/// 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())?;
|
||||
@@ -169,6 +238,17 @@ impl Fixture {
|
||||
}
|
||||
|
||||
fn build(&self, target: Target) -> LaunchOutputs {
|
||||
match self.try_build(target, &[]) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_build(&self, target: Target, ignored_maven_compile_goals: &[String]) -> IdeResult<Built> {
|
||||
let jdk = |_: Option<u32>| None;
|
||||
let build = JavaBuild {
|
||||
root: &self.root,
|
||||
@@ -177,18 +257,12 @@ impl Fixture {
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
ignored_maven_compile_goals,
|
||||
service: &self.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event)
|
||||
}
|
||||
|
||||
/// The steps of the launch builds since the last call.
|
||||
@@ -213,6 +287,37 @@ impl Fixture {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_maven_compile_goal_can_be_skipped_with_a_cached_reactor() {
|
||||
let pom = APP_POM.replace(
|
||||
"</build>",
|
||||
concat!(
|
||||
"<plugins><plugin><groupId>org.apache.maven.plugins</groupId>",
|
||||
"<artifactId>maven-jar-plugin</artifactId><version>3.4.1</version>",
|
||||
"<executions><execution><id>early-jar</id><phase>compile</phase>",
|
||||
"<goals><goal>jar</goal></goals></execution></executions></plugin></plugins></build>",
|
||||
),
|
||||
);
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/pom.xml", &pom),
|
||||
("lib/src/main/java/l/L.java", "package l; public class L {}"),
|
||||
("app/src/main/java/a/A.java", "package a; public class A { l.L dependency; }"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let module = f.root.join("app");
|
||||
let go = |ignored: &[String]| f.try_build(Target::Launch { module: &module, test: false }, ignored).unwrap();
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
|
||||
f.steps();
|
||||
let Built::Done(output) = go(&[goal.into()]) else { panic!("expected the configured build to use javac") };
|
||||
assert!(output.failure.is_none(), "{:?}", output.messages);
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
assert!(!f.root.join("app/target/app-1.jar").exists());
|
||||
assert!(f.steps().iter().all(|step| step.starts_with("javac")), "the prepared model was reused");
|
||||
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
@@ -258,6 +363,8 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl t:app"), "{steps:?}");
|
||||
// #7340: content replaced without a newer mtime is copied too.
|
||||
assert!(steps[0].contains("-Dmaven.resources.overwrite=true"), "{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.
|
||||
@@ -309,6 +416,104 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
assert!(f.out("t.app/test-classes/a/AggTest.class").is_file());
|
||||
}
|
||||
|
||||
/// #7743: a dependency's own dependencies come before its next sibling on the classpath, as in
|
||||
/// `mvn compile`, so of two artifacts with the same classes (`dom4j:dom4j` 1.x and
|
||||
/// `org.dom4j:dom4j` 2.x) javac sees the one Maven does.
|
||||
#[test]
|
||||
fn maven_classpath_lists_dependencies_in_maven_order() {
|
||||
let module = |name: &str, deps: &[&str]| {
|
||||
let deps: String = deps
|
||||
.iter()
|
||||
.map(|d| {
|
||||
format!("<dependency><groupId>t</groupId><artifactId>{d}</artifactId><version>1</version></dependency>")
|
||||
})
|
||||
.collect();
|
||||
format!(
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId>\
|
||||
<version>1</version></parent><artifactId>{name}</artifactId><dependencies>{deps}</dependencies></project>"
|
||||
)
|
||||
};
|
||||
let root = ROOT_POM.replace(
|
||||
"<module>lib</module>",
|
||||
"<module>newdom</module><module>olddom</module><module>x</module><module>lib</module>",
|
||||
);
|
||||
let (newdom, olddom, x, lib) =
|
||||
(module("newdom", &[]), module("olddom", &[]), module("x", &["newdom"]), module("lib", &["x", "olddom"]));
|
||||
let Some(f) = Fixture::new(&[
|
||||
("pom.xml", &root),
|
||||
("newdom/pom.xml", &newdom),
|
||||
("olddom/pom.xml", &olddom),
|
||||
("x/pom.xml", &x),
|
||||
("lib/pom.xml", &lib),
|
||||
("newdom/src/main/java/d/Element.java", "package d;\npublic class Element { public void fresh() {} }\n"),
|
||||
("olddom/src/main/java/d/Element.java", "package d;\npublic class Element {}\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { void f() { new d.Element().fresh(); } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let built = f.launch(false);
|
||||
assert_eq!(built.failure, None, "{:?}", built.messages);
|
||||
let position = |name: &str| built.class_paths.iter().position(|p| *p == f.out(&format!("t.{name}/classes")));
|
||||
assert!(position("newdom") < position("olddom"), "{:?}", built.class_paths);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_resources_to_the_output_paths_the_build_tool_writes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
write(&root, "src/main/resources/app.properties", "a=1");
|
||||
write(&root, "src/main/resources/notes.txt", "n");
|
||||
write(&root, "src/main/resources/deep/app.properties", "b=2");
|
||||
let resources = root.join("src/main/resources");
|
||||
let output = root.join("out/classes");
|
||||
let set = SourceSet {
|
||||
output: output.clone(),
|
||||
resources: vec![
|
||||
ResourceRoot { directory: resources.clone(), ..Default::default() },
|
||||
// A `<targetPath>` and an `<includes>` pattern, as a POM can configure them.
|
||||
ResourceRoot {
|
||||
directory: resources,
|
||||
target_path: Some("META-INF".into()),
|
||||
includes: vec!["*.properties".into()],
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
resource_outputs(&set, &CancellationToken::new()).unwrap(),
|
||||
BTreeSet::from([
|
||||
output.join("app.properties"),
|
||||
output.join("notes.txt"),
|
||||
output.join("deep/app.properties"),
|
||||
output.join("META-INF/app.properties"),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletes_the_output_of_a_resource_removed_from_the_sources() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
|
||||
("app/src/main/resources/app.properties", "version=${project.version}\n"),
|
||||
("app/src/main/resources/META-INF/spring.factories", "a.A\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/META-INF/spring.factories")).unwrap(), "a.A\n");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
|
||||
// A deleted resource leaves no copy behind: the launch would read a file the sources no longer have.
|
||||
fs::remove_file(f.root.join("app/src/main/resources/META-INF/spring.factories")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps.iter().any(|s| s.contains("resources:resources")), "{steps:?}");
|
||||
assert!(!f.out("t.app/classes/META-INF/spring.factories").exists(), "the removed resource stays on the classpath");
|
||||
// The resource that is still there keeps its copy, and a launch with nothing changed runs nothing.
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recompiles_the_classes_an_api_change_reaches() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
@@ -485,7 +690,7 @@ fn javac_options_follow_the_compiler_configuration() {
|
||||
"-processorpath /p.jar",
|
||||
"-processor a.P",
|
||||
"-proc:none",
|
||||
"-g:lines,vars",
|
||||
"-g",
|
||||
"-parameters",
|
||||
"-nowarn",
|
||||
"-encoding UTF-8",
|
||||
@@ -500,6 +705,28 @@ fn javac_options_follow_the_compiler_configuration() {
|
||||
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_options_always_keep_debug_info() {
|
||||
// `<debug>false</debug>` makes Maven pass `-g:none`; the IDE's build still emits the line
|
||||
// numbers and variables the debugger needs (#7786).
|
||||
let set = SourceSet {
|
||||
output: PathBuf::from("/o"),
|
||||
compiler: Some(CompilerConfig {
|
||||
debug: Some(false),
|
||||
debuglevel: Some("source".into()),
|
||||
compiler_args: vec!["-g:none".into(), "-Xlint:all".into()],
|
||||
compiler_argument: Some("-g:source -Xlint:none".into()),
|
||||
compiler_arguments: [("g:none".to_owned(), None)].into(),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let args = javac_options(&set, &[], Path::new("/gen"), Some(21));
|
||||
let debug: Vec<_> = args.iter().filter(|a| a.starts_with("-g")).collect();
|
||||
assert_eq!(debug, ["-g"], "{args:?}");
|
||||
assert!(args.iter().any(|a| a == "-Xlint:all") && args.iter().any(|a| a == "-Xlint:none"), "{args:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_gradle_projects_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
@@ -565,6 +792,22 @@ fn builds_gradle_projects_with_javac_and_only_what_changed() {
|
||||
assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_gradle_projects_that_enable_isolated_projects() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
(
|
||||
"gradle.properties",
|
||||
"org.gradle.daemon=false\norg.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n",
|
||||
),
|
||||
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let built = f.launch(false);
|
||||
assert_eq!(built.failure, None, "{:?}\n{}", built.messages, build_output_tail(&f.events.lock().unwrap()));
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_gradle_projects_with_other_compilers_to_gradle() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
@@ -581,6 +824,7 @@ fn leaves_gradle_projects_with_other_compilers_to_gradle() {
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
ignored_maven_compile_goals: &[],
|
||||
service: &f.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
@@ -591,3 +835,314 @@ fn leaves_gradle_projects_with_other_compilers_to_gradle() {
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `.java` files `java_sources` lists for one source root.
|
||||
#[cfg(unix)]
|
||||
fn sources_of(root: &Path) -> Vec<PathBuf> {
|
||||
let set = SourceSet { source_roots: vec![root.to_path_buf()], ..Default::default() };
|
||||
java_sources(&set, &CancellationToken::new()).unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_follow_directory_links_and_keep_the_linked_spelling() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("app/src/main/java");
|
||||
write(&root, "a/A.java", "package a;\nclass A {}\n");
|
||||
write(&base, "shared/b/B.java", "package b;\npublic class B {}\n");
|
||||
write(&base, "shared/b/c/C.java", "package b.c;\npublic class C {}\n");
|
||||
symlink(base.join("shared/b"), root.join("b")).unwrap();
|
||||
// A link to a file was already listed; it stays listed.
|
||||
write(&base, "shared/D.java", "package d;\npublic class D {}\n");
|
||||
fs::create_dir_all(root.join("d")).unwrap();
|
||||
symlink(base.join("shared/D.java"), root.join("d/D.java")).unwrap();
|
||||
// A broken link is skipped.
|
||||
symlink(base.join("missing"), root.join("gone")).unwrap();
|
||||
// javac and the debugger get the path the user opened, not the link's target.
|
||||
assert_eq!(
|
||||
sources_of(&root),
|
||||
[root.join("a/A.java"), root.join("b/B.java"), root.join("b/c/C.java"), root.join("d/D.java")]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_stop_at_link_cycles() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("src");
|
||||
write(&root, "a/A.java", "package a;\nclass A {}\n");
|
||||
write(&base, "shared/b/B.java", "package b;\npublic class B {}\n");
|
||||
symlink(&root, root.join("a/up")).unwrap();
|
||||
symlink(".", root.join("a/here")).unwrap();
|
||||
symlink(base.join("shared/b"), root.join("b")).unwrap();
|
||||
symlink(base.join("shared"), base.join("shared/b/back")).unwrap();
|
||||
assert_eq!(sources_of(&root), [root.join("a/A.java"), root.join("b/B.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_follow_links_that_share_a_folder() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
write(&base, "shared/s/S.java", "package s;\npublic class S {}\n");
|
||||
let shared = base.join("shared/s");
|
||||
// Each module links the same folder into its own sources: every one of them compiles it.
|
||||
let (one, two) = (base.join("one/src"), base.join("two/src"));
|
||||
for root in [&one, &two] {
|
||||
fs::create_dir_all(root).unwrap();
|
||||
symlink(&shared, root.join("s")).unwrap();
|
||||
}
|
||||
assert_eq!(sources_of(&one), [one.join("s/S.java")]);
|
||||
assert_eq!(sources_of(&two), [two.join("s/S.java")]);
|
||||
// Within one source set a file reached through two links is listed once, real entries before links, then by name.
|
||||
let three = base.join("three/src");
|
||||
fs::create_dir_all(three.join("x")).unwrap();
|
||||
symlink(&shared, three.join("s")).unwrap();
|
||||
symlink(&shared, three.join("x/s")).unwrap();
|
||||
assert_eq!(sources_of(&three), [three.join("x/s/S.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_list_a_file_reached_through_two_paths_once() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("src");
|
||||
write(&root, "p/C.java", "package p;\npublic class C {}\n");
|
||||
symlink(root.join("p"), root.join("alias")).unwrap();
|
||||
symlink(root.join("p/C.java"), root.join("C.java")).unwrap();
|
||||
// The real folder comes before the links to it.
|
||||
assert_eq!(sources_of(&root), [root.join("p/C.java")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_sources_match_each_nested_root_against_its_own_paths() {
|
||||
// Without links the listing is what it was before links were followed: a file the outer
|
||||
// root's relative path excludes is still listed through the inner root.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let outer = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let inner = outer.join("inner");
|
||||
write(&outer, "inner/X.java", "class X {}\n");
|
||||
write(&outer, "Y.java", "class Y {}\n");
|
||||
let set = SourceSet {
|
||||
source_roots: vec![outer.clone(), inner.clone()],
|
||||
compiler: Some(CompilerConfig { excludes: vec!["inner/**".into()], ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(java_sources(&set, &CancellationToken::new()).unwrap(), [outer.join("Y.java"), inner.join("X.java")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn java_sources_find_a_file_deep_in_plain_folders() {
|
||||
// Iterative walk with one folder open at a time: avoids exhausting file descriptors under
|
||||
// macOS's default limit of 256 and avoids overflowing Windows' 1-2 MB thread stack in deep
|
||||
// trees. Target 3000 levels on Windows (long paths up to 32,767 chars); on Unix, cap to the
|
||||
// deepest path that fits under PATH_MAX (1024 bytes on macOS, 4096 bytes on Linux).
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let max_path_bytes: Option<usize> = if cfg!(target_os = "macos") {
|
||||
Some(1020)
|
||||
} else if cfg!(unix) {
|
||||
Some(4090)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let target_depth = 3000;
|
||||
let depth = match max_path_bytes {
|
||||
Some(limit) => target_depth.min(limit.saturating_sub(root.as_os_str().len() + "/C.java".len()) / 2),
|
||||
None => target_depth,
|
||||
};
|
||||
assert!(depth >= 300, "temp root too long for deep folder test: {}", root.display());
|
||||
|
||||
let mut dir = root.clone();
|
||||
for _ in 0..depth {
|
||||
dir.push("d");
|
||||
fs::create_dir(&dir).unwrap();
|
||||
}
|
||||
let file = dir.join("C.java");
|
||||
fs::write(&file, "class C {}\n").unwrap();
|
||||
|
||||
let set = SourceSet { source_roots: vec![root], ..Default::default() };
|
||||
let found = java_sources(&set, &CancellationToken::new()).unwrap();
|
||||
|
||||
// Remove iteratively so deep trees don't rely on recursive directory removal.
|
||||
fs::remove_file(&file).unwrap();
|
||||
for _ in 0..depth {
|
||||
fs::remove_dir(&dir).unwrap();
|
||||
dir.pop();
|
||||
}
|
||||
assert_eq!(found, [file]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn compiles_the_other_spelling_when_the_kept_link_goes() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { p.C c; }\n"),
|
||||
("shared/p/C.java", "package p;\npublic class C {}\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let java = f.root.join("app/src/main/java");
|
||||
symlink(f.root.join("shared/p"), java.join("p")).unwrap();
|
||||
symlink(f.root.join("shared/p"), java.join("z")).unwrap();
|
||||
f.steps_of_launch();
|
||||
let class = f.out("t.app/classes/p/C.class");
|
||||
assert!(class.is_file());
|
||||
|
||||
// The class keeps its source through the link that is left.
|
||||
fs::remove_file(java.join("p")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(class.is_file(), "C.class is gone after {steps:?}");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn builds_and_recompiles_sources_under_a_linked_folder() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new b.B().b(); } }\n"),
|
||||
("shared/b/B.java", "package b;\npublic class B { public int b() { return 1; } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
std::os::unix::fs::symlink(f.root.join("shared/b"), f.root.join("app/src/main/java/b")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps.contains(&"javac app (main, 2 files)".to_owned()), "{steps:?}");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
|
||||
// An edit behind the link is seen through it.
|
||||
f.write("shared/b/B.java", "package b;\npublic class B { public int b() { return 2; } }\n");
|
||||
assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]);
|
||||
|
||||
// Errors name the file as it sits under the source root.
|
||||
f.write("shared/b/B.java", "package b;\npublic class B { public int b() { return \"\"; } }\n");
|
||||
let failed = f.launch(false);
|
||||
let error = failed.messages.iter().find(|m| m.severity == Severity::Error).expect("an error");
|
||||
assert_eq!(
|
||||
error.path.as_deref(),
|
||||
Some(f.root.join("app/src/main/java/b/B.java").as_path()),
|
||||
"{:?}",
|
||||
failed.messages
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn resources_under_a_linked_folder_are_copied_refreshed_and_pruned() {
|
||||
let Some(f) =
|
||||
Fixture::new(&[("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"), ("shared/r/x.txt", "one\n")])
|
||||
else {
|
||||
return;
|
||||
};
|
||||
fs::create_dir_all(f.root.join("app/src/main/resources")).unwrap();
|
||||
std::os::unix::fs::symlink(f.root.join("shared/r"), f.root.join("app/src/main/resources/r")).unwrap();
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/r/x.txt")).unwrap(), "one\n");
|
||||
|
||||
// An edit behind the link reaches the copy the launch reads.
|
||||
f.write("shared/r/x.txt", "two\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps.iter().any(|s| s.contains("resources:resources")), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/r/x.txt")).unwrap(), "two\n");
|
||||
|
||||
// So does a file deleted behind it.
|
||||
fs::remove_file(f.root.join("shared/r/x.txt")).unwrap();
|
||||
f.steps_of_launch();
|
||||
assert!(!f.out("t.app/classes/r/x.txt").exists(), "the removed resource stays on the classpath");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_keep_a_valid_link_when_an_earlier_alias_is_excluded() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("src/main/java");
|
||||
write(&base, "shared/one/p/C.java", "package p;\npublic class C {}\n");
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
symlink(base.join("shared/one"), root.join("a")).unwrap();
|
||||
symlink(base.join("shared/one"), root.join("z")).unwrap();
|
||||
let set = SourceSet {
|
||||
source_roots: vec![root.clone()],
|
||||
compiler: Some(CompilerConfig { excludes: vec!["a/**".into()], ..Default::default() }),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(java_sources(&set, &CancellationToken::new()).unwrap(), [root.join("z/p/C.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn excluded_link_alias_does_not_drop_compiled_classes() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let pom = APP_POM.replace(
|
||||
"</build>",
|
||||
concat!(
|
||||
"<plugins><plugin><artifactId>maven-compiler-plugin</artifactId>",
|
||||
"<configuration><excludes><exclude>a/**</exclude></excludes></configuration>",
|
||||
"</plugin></plugins></build>",
|
||||
),
|
||||
);
|
||||
let Some(f) = Fixture::new(&[("app/pom.xml", &pom), ("shared/one/p/C.java", "package p;\npublic class C {}\n")])
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let java = f.root.join("app/src/main/java");
|
||||
fs::create_dir_all(&java).unwrap();
|
||||
symlink(f.root.join("shared/one"), java.join("z")).unwrap();
|
||||
f.steps_of_launch();
|
||||
let class = f.out("t.app/classes/p/C.class");
|
||||
assert!(class.is_file());
|
||||
|
||||
// Adding an excluded link to the same folder must not hide the surviving link or delete its class.
|
||||
symlink(f.root.join("shared/one"), java.join("a")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(class.is_file(), "C.class is gone after {steps:?}");
|
||||
assert!(steps.is_empty(), "{steps:?}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn java_sources_prefer_a_plain_path_over_an_earlier_linked_alias() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap().join("src/main/java");
|
||||
write(&root, "p/C.java", "package p;\npublic class C {}\n");
|
||||
fs::create_dir_all(root.join("a")).unwrap();
|
||||
symlink(root.join("p"), root.join("a/link")).unwrap();
|
||||
assert_eq!(sources_of(&root), [root.join("p/C.java")]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn recompiles_a_single_file_through_either_the_plain_or_linked_spelling() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let Some(f) = Fixture::new(&[("app/src/main/java/p/C.java", "package p;\npublic class C {}\n")]) else {
|
||||
return;
|
||||
};
|
||||
f.steps_of_launch();
|
||||
let java = f.root.join("app/src/main/java");
|
||||
assert!(f.out("t.app/classes/p/C.class").is_file());
|
||||
|
||||
// Adding a link under an earlier directory keeps the plain spelling and still lets Recompile
|
||||
// hit through either spelling.
|
||||
fs::create_dir_all(java.join("a")).unwrap();
|
||||
symlink(java.join("p"), java.join("a/link")).unwrap();
|
||||
let second = f.steps_of_launch();
|
||||
|
||||
f.steps();
|
||||
assert_eq!(f.build(Target::File(&java.join("p/C.java"))).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
|
||||
f.steps();
|
||||
assert_eq!(f.build(Target::File(&java.join("a/link/C.java"))).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
|
||||
assert!(second.is_empty(), "{second:?}");
|
||||
}
|
||||
@@ -98,14 +98,19 @@ pub fn load_linked_with_jdk(
|
||||
maven_jdk_version: Option<u32>,
|
||||
) -> BuildModel {
|
||||
let maven = maven::has_projects(root, settings).then(|| {
|
||||
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
|
||||
let activation =
|
||||
maven::ProfileActivation::new(root, settings, &sync::maven_profiles(cache_dir), maven_jdk_version);
|
||||
let repo = maven_repo.or_else(maven::default_local_repo);
|
||||
let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects);
|
||||
let mut m = maven::load_with_activation(root, repo, &activation, &settings.linked_projects);
|
||||
maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m);
|
||||
// The user settings' profiles can be chosen too (`-P` applies to them as well).
|
||||
for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() {
|
||||
if !m.profiles.iter().any(|x| x.id == p.id) {
|
||||
m.profiles.push(p);
|
||||
if let Some(settings_file) = maven::user_settings_file(root, settings) {
|
||||
for p in maven::settings_profiles(&settings_file) {
|
||||
if let Some(existing) = m.profiles.iter_mut().find(|x| x.id == p.id) {
|
||||
existing.active_by_default |= p.active_by_default;
|
||||
} else {
|
||||
m.profiles.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
sync::apply_maven_cache(root, cache_dir, &mut m);
|
||||
@@ -157,8 +162,8 @@ pub fn maven_external_roots(
|
||||
) -> Vec<PathBuf> {
|
||||
let mut dirs = maven::external_pom_dirs(root, &settings.linked_projects);
|
||||
if trusted {
|
||||
let profiles = settings.profiles(&sync::maven_profiles(cache_dir));
|
||||
dirs.extend(maven::reactor_external_dirs(root, &profiles, &settings.unlinked_projects));
|
||||
let activation = maven::ProfileActivation::new(root, settings, &sync::maven_profiles(cache_dir), None);
|
||||
dirs.extend(maven::reactor_external_dirs(root, &activation, &settings.unlinked_projects));
|
||||
}
|
||||
let owned: Vec<String> = dirs.iter().map(|dir| dir.to_string_lossy().into_owned()).collect();
|
||||
gradle::external_roots(root, owned.iter().map(String::as_str))
|
||||
@@ -334,6 +339,47 @@ mod tests {
|
||||
assert_eq!(roots(&settings, true), [a, e]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_maven_turns_on_by_itself_is_shown_on_and_unticking_it_turns_it_off() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for module in ["extras", "it"] {
|
||||
std::fs::create_dir(root.join(module)).unwrap();
|
||||
std::fs::write(root.join(module).join("pom.xml"), "<project><artifactId>m</artifactId></project>").unwrap();
|
||||
}
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><artifactId>root</artifactId><packaging>pom</packaging><profiles>
|
||||
<profile><id>dev</id><activation><activeByDefault>true</activeByDefault></activation></profile>
|
||||
<profile><id>full</id><activation><property><name>!quick</name></property></activation><modules><module>extras</module></modules></profile>
|
||||
<profile><id>ci</id><modules><module>it</module></modules></profile>
|
||||
</profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::create_dir(root.join(".mvn")).unwrap();
|
||||
std::fs::write(root.join(".mvn/maven.config"), "-Pci\n").unwrap();
|
||||
let cache = root.join("cache");
|
||||
let settings = ide_core::settings::MavenSettings {
|
||||
user_settings: root.join("settings.xml").to_string_lossy().into_owned(),
|
||||
..Default::default()
|
||||
};
|
||||
let load = || load_linked(root, &cache, None, &settings, &Default::default()).maven.unwrap();
|
||||
let flags =
|
||||
|m: &maven::MavenModel| m.profiles.iter().map(|p| (p.id.clone(), p.active_by_default)).collect::<Vec<_>>();
|
||||
let pair = |id: &str, on: bool| (id.to_owned(), on);
|
||||
|
||||
// On by default (the tool window's grey check), so `dev` steps aside as it does in Maven.
|
||||
let model = load();
|
||||
assert_eq!(flags(&model), [pair("dev", false), pair("full", true), pair("ci", true)]);
|
||||
assert_eq!(model.projects[0].modules, ["extras/pom.xml", "it/pom.xml"]);
|
||||
|
||||
// Unticked: off in the model, still on by default so the tool window keeps passing `-P !id`.
|
||||
save_maven_profiles(&cache, &["!full".into(), "!ci".into()]).unwrap();
|
||||
let model = load();
|
||||
assert_eq!(flags(&model), [pair("dev", true), pair("full", true), pair("ci", true)]);
|
||||
assert!(model.projects[0].modules.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_profiles_and_checkbox_choices_control_modules_before_sync() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -358,6 +404,50 @@ mod tests {
|
||||
assert!(modules(&settings).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_xml_active_profiles_mark_pom_profiles_active_by_default() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir(root.join("child")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
r#"<project><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version><packaging>pom</packaging>
|
||||
<modules><module>child</module></modules>
|
||||
<profiles>
|
||||
<profile><id>test3</id></profile>
|
||||
<profile><id>dev</id><activation><activeByDefault>TRUE</activeByDefault></activation></profile>
|
||||
</profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
root.join("child/pom.xml"),
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>root</artifactId><version>1.0</version></parent>
|
||||
<artifactId>child</artifactId>
|
||||
<profiles><profile><id>child-default</id><activation><activeByDefault>TRUE</activeByDefault></activation></profile></profiles></project>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let settings_xml = root.join("settings.xml");
|
||||
std::fs::write(
|
||||
&settings_xml,
|
||||
r#"<settings><activeProfiles><activeProfile>test3</activeProfile></activeProfiles></settings>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let cache = root.join("cache");
|
||||
let settings = ide_core::settings::MavenSettings {
|
||||
user_settings: settings_xml.to_string_lossy().into_owned(),
|
||||
..Default::default()
|
||||
};
|
||||
let model = load_linked(root, &cache, None, &settings, &Default::default()).maven.unwrap();
|
||||
let flags: Vec<(&str, bool)> = model.profiles.iter().map(|p| (p.id.as_str(), p.active_by_default)).collect();
|
||||
assert!(
|
||||
flags.contains(&("test3", true)),
|
||||
"activeProfile from settings.xml marks POM profile active: {flags:?}"
|
||||
);
|
||||
// As in Maven, `dev` steps aside: settings.xml turns on test3 of the same POM.
|
||||
assert!(flags.contains(&("dev", false)), "activeByDefault beside an active profile: {flags:?}");
|
||||
assert!(flags.contains(&("child-default", true)), "case-insensitive activeByDefault of a module: {flags:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_build_systems_and_build_files() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,463 @@
|
||||
//! Which profiles of a POM Maven turns on for a project, decided as Maven 3.9 does
|
||||
//! (`DefaultProfileSelector` and its activators): from the `-P` entries, the `-D` properties of
|
||||
//! `.mvn/maven.config`, the JDK Maven runs on, the OS and the files of the project.
|
||||
|
||||
use super::{RawProfile, interpolate, jdk_matches};
|
||||
use crate::xml::Element;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// What decides profile activation besides the POMs and the machine. The `.mvn/maven.config`
|
||||
/// of each build is read with its POMs.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct ProfileActivation {
|
||||
/// `-P` entries of every Maven run (`!id` or `-id` turns a profile off): Settings › Maven's
|
||||
/// active profiles and the `<activeProfiles>` of the user `settings.xml`.
|
||||
pub profiles: Vec<String>,
|
||||
/// `-P` entries chosen in the Maven tool window.
|
||||
pub choices: Vec<String>,
|
||||
/// Feature version of the JDK Maven runs on.
|
||||
pub jdk: Option<u32>,
|
||||
}
|
||||
|
||||
impl ProfileActivation {
|
||||
/// For the builds under `root`, with the Maven tool window's `choices`.
|
||||
pub fn new(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::MavenSettings,
|
||||
choices: &[String],
|
||||
jdk: Option<u32>,
|
||||
) -> Self {
|
||||
let mut profiles = settings.profiles(&[]);
|
||||
if let Some(file) = super::user_settings_file(root, settings) {
|
||||
profiles.extend(super::settings_active_profiles(&file));
|
||||
}
|
||||
Self { profiles, choices: choices.to_vec(), jdk }
|
||||
}
|
||||
|
||||
/// `Some(false)` when a `-P` entry turns profile `id` off (that wins in Maven, whatever the
|
||||
/// order), `Some(true)` when one turns it on. The tool window's entries for `except` are
|
||||
/// left out.
|
||||
fn explicit(&self, config: &MavenConfig, id: &str, except: Option<&str>) -> Option<bool> {
|
||||
let choices = self.choices.iter().filter(|c| except.is_none_or(|except| entry(c).1 != except));
|
||||
let mut on = None;
|
||||
for (turns_on, entry) in self.profiles.iter().chain(&config.profiles).chain(choices).map(|e| entry(e)) {
|
||||
if entry == id {
|
||||
if !turns_on {
|
||||
return Some(false);
|
||||
}
|
||||
on = Some(true);
|
||||
}
|
||||
}
|
||||
on
|
||||
}
|
||||
}
|
||||
|
||||
/// A `-P` entry as (turns the profile on, its id): `!id` and `-id` turn it off, `+id` and
|
||||
/// Maven 3.9's optional `?id` turn it on.
|
||||
fn entry(entry: &str) -> (bool, &str) {
|
||||
let entry = entry.trim();
|
||||
let (on, id) = match entry.strip_prefix(['!', '-']) {
|
||||
Some(id) => (false, id),
|
||||
None => (true, entry.strip_prefix('+').unwrap_or(entry)),
|
||||
};
|
||||
(on, id.strip_prefix('?').unwrap_or(id).trim())
|
||||
}
|
||||
|
||||
/// The `-P` and `-D` options of the `.mvn/maven.config` Maven reads before every run.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct MavenConfig {
|
||||
profiles: Vec<String>,
|
||||
properties: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl MavenConfig {
|
||||
/// The `maven.config` of a Maven run in `dir`: in the `.mvn` folder of the nearest folder
|
||||
/// from `dir` up that has one, as the `mvn` script finds the build's base directory; else
|
||||
/// where it would be created in `dir`.
|
||||
pub(crate) fn file(dir: &Path) -> PathBuf {
|
||||
let base = dir.ancestors().find(|d| !d.as_os_str().is_empty() && d.join(".mvn").is_dir());
|
||||
base.unwrap_or(dir).join(".mvn").join("maven.config")
|
||||
}
|
||||
|
||||
pub(crate) fn read(file: &Path) -> Self {
|
||||
std::fs::read_to_string(file).map(|text| Self::parse(&text)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Since Maven 3.9 each line is one argument (`-P a` and `-P` followed by `a` both work);
|
||||
/// lines starting with `#` are comments.
|
||||
fn parse(text: &str) -> Self {
|
||||
let mut config = Self::default();
|
||||
let mut args = text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#'));
|
||||
while let Some(arg) = args.next() {
|
||||
if let Some(value) = option_value(arg, "-P", "--activate-profiles", &mut args) {
|
||||
config.profiles.extend(value.split(',').map(str::trim).filter(|p| !p.is_empty()).map(str::to_owned));
|
||||
} else if let Some(value) = option_value(arg, "-D", "--define", &mut args) {
|
||||
// `-Dname` alone sets it to `true`, as on the command line.
|
||||
let (name, value) = value.split_once('=').unwrap_or((value, "true"));
|
||||
config.properties.insert(name.trim().to_owned(), value.to_owned());
|
||||
}
|
||||
}
|
||||
config
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the option `short` / `long` given in `arg` (`-Pa`, `-P a`, `--activate-profiles=a`)
|
||||
/// or as the next argument.
|
||||
fn option_value<'a>(
|
||||
arg: &'a str,
|
||||
short: &str,
|
||||
long: &str,
|
||||
args: &mut impl Iterator<Item = &'a str>,
|
||||
) -> Option<&'a str> {
|
||||
let value = match arg.strip_prefix(long) {
|
||||
Some(rest) if rest.is_empty() || rest.starts_with(['=', ' ', '\t']) => rest.trim_start_matches('='),
|
||||
Some(_) => return None,
|
||||
None => arg.strip_prefix(short)?,
|
||||
};
|
||||
match value.trim() {
|
||||
"" => args.next(),
|
||||
value => Some(value),
|
||||
}
|
||||
}
|
||||
|
||||
/// A profile's `<activation>`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct Activation {
|
||||
pub(crate) by_default: bool,
|
||||
/// `<jdk>`: `21`, `1.8`, `[17,)`, `!21`.
|
||||
pub(crate) jdk: Option<String>,
|
||||
os: Option<OsCondition>,
|
||||
property: Option<PropertyCondition>,
|
||||
file: Option<FileCondition>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct OsCondition {
|
||||
family: Option<String>,
|
||||
name: Option<String>,
|
||||
arch: Option<String>,
|
||||
version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct PropertyCondition {
|
||||
name: String,
|
||||
value: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct FileCondition {
|
||||
exists: Option<String>,
|
||||
missing: Option<String>,
|
||||
}
|
||||
|
||||
impl Activation {
|
||||
pub(crate) fn read(profile: &Element) -> Self {
|
||||
let Some(a) = profile.child("activation") else { return Self::default() };
|
||||
Self {
|
||||
by_default: a.text_of("activeByDefault").is_some_and(|v| v.eq_ignore_ascii_case("true")),
|
||||
// Present but empty, Maven's prefix match takes any JDK.
|
||||
jdk: a.child("jdk").map(|jdk| jdk.text.trim().to_owned()),
|
||||
os: a.child("os").map(|os| OsCondition {
|
||||
family: os.text_of("family"),
|
||||
name: os.text_of("name"),
|
||||
arch: os.text_of("arch"),
|
||||
version: os.text_of("version"),
|
||||
}),
|
||||
property: a
|
||||
.child("property")
|
||||
.map(|p| PropertyCondition { name: p.text_of("name").unwrap_or_default(), value: p.text_of("value") }),
|
||||
file: a.child("file").map(|f| FileCondition { exists: f.text_of("exists"), missing: f.text_of("missing") }),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn checks_files(&self) -> bool {
|
||||
self.file.is_some()
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.jdk.is_none() && self.os.is_none() && self.property.is_none() && self.file.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the profiles of one project are activated with.
|
||||
pub(crate) struct Env<'a> {
|
||||
pub(crate) activation: &'a ProfileActivation,
|
||||
pub(crate) config: &'a MavenConfig,
|
||||
/// The folder of the project being built, also for the profiles its parents declare.
|
||||
pub(crate) basedir: &'a Path,
|
||||
}
|
||||
|
||||
impl Env<'_> {
|
||||
/// Whether the `<activation>` conditions of each profile hold; the files they look at are
|
||||
/// added to `files`. `properties` are the own `<properties>` of the POM declaring them.
|
||||
pub(crate) fn conditions(
|
||||
&self,
|
||||
profiles: &[RawProfile],
|
||||
properties: &[(String, String)],
|
||||
files: &mut Vec<PathBuf>,
|
||||
) -> Vec<bool> {
|
||||
if profiles.iter().all(|p| p.activation.is_empty()) {
|
||||
return vec![false; profiles.len()];
|
||||
}
|
||||
let props = self.interpolation(properties);
|
||||
profiles.iter().map(|p| self.holds(&p.activation, &props, files)).collect()
|
||||
}
|
||||
|
||||
/// Which profiles are on: those a `-P` entry turns on or whose `conditions` hold, unless one
|
||||
/// turns them off; the `activeByDefault` ones only when no other profile of the POM is on.
|
||||
/// The tool window's choice for profile `except` is left out.
|
||||
pub(crate) fn select(&self, profiles: &[RawProfile], conditions: &[bool], except: Option<&str>) -> Vec<bool> {
|
||||
let explicit: Vec<Option<bool>> =
|
||||
profiles.iter().map(|p| self.activation.explicit(self.config, &p.id, except)).collect();
|
||||
let mut on: Vec<bool> = explicit.iter().zip(conditions).map(|(e, &holds)| e.unwrap_or(holds)).collect();
|
||||
if !on.contains(&true) {
|
||||
for ((on, p), e) in on.iter_mut().zip(profiles).zip(&explicit) {
|
||||
*on = p.activation.by_default && *e != Some(false);
|
||||
}
|
||||
}
|
||||
on
|
||||
}
|
||||
|
||||
/// Whether each profile is on unless the Maven tool window turns it off: what the tool
|
||||
/// window shows as on by default, so that unticking it passes `-P!id`.
|
||||
pub(crate) fn implicit(&self, profiles: &[RawProfile], conditions: &[bool]) -> Vec<bool> {
|
||||
profiles.iter().enumerate().map(|(i, p)| self.select(profiles, conditions, Some(&p.id))[i]).collect()
|
||||
}
|
||||
|
||||
/// Values for `${…}` in activation conditions: the declaring POM's own properties, then the
|
||||
/// `-D` ones, then the JVM's; `${basedir}` is the project's.
|
||||
fn interpolation(&self, properties: &[(String, String)]) -> HashMap<String, String> {
|
||||
let mut props: HashMap<String, String> = ["os.name", "os.arch", "user.home"]
|
||||
.into_iter()
|
||||
.filter_map(|k| Some((k.to_owned(), system_property(k)?)))
|
||||
.collect();
|
||||
props.extend(self.config.properties.iter().map(|(k, v)| (k.clone(), v.clone())));
|
||||
props.extend(properties.iter().cloned());
|
||||
let basedir = self.basedir.to_string_lossy().into_owned();
|
||||
props.insert("project.basedir".into(), basedir.clone());
|
||||
props.insert("basedir".into(), basedir);
|
||||
props
|
||||
}
|
||||
|
||||
/// Since Maven 3.2.2 every condition present has to hold, and one at least has to be present.
|
||||
fn holds(&self, a: &Activation, props: &HashMap<String, String>, files: &mut Vec<PathBuf>) -> bool {
|
||||
let jdk = self.activation.jdk;
|
||||
let results = [
|
||||
a.jdk.as_ref().map(|spec| jdk.is_some() && (spec.is_empty() || jdk_matches(spec, jdk))),
|
||||
a.os.as_ref().map(|os| os_matches(os, props)),
|
||||
a.property.as_ref().map(|p| self.property_matches(p, props)),
|
||||
a.file.as_ref().map(|f| self.file_matches(f, props, files)),
|
||||
];
|
||||
let mut present = results.into_iter().flatten().peekable();
|
||||
present.peek().is_some() && present.all(|holds| holds)
|
||||
}
|
||||
|
||||
fn property_matches(&self, p: &PropertyCondition, props: &HashMap<String, String>) -> bool {
|
||||
let name = interpolate(&p.name, props);
|
||||
let (negated, name) = negation(&name);
|
||||
if name.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let actual = self.config.properties.get(name).cloned().or_else(|| system_property(name));
|
||||
match p.value.as_deref().map(|v| interpolate(v, props)) {
|
||||
Some(value) => {
|
||||
let (negated, value) = negation(&value);
|
||||
negated != (actual.as_deref() == Some(value))
|
||||
}
|
||||
None => negated != actual.is_some_and(|v| !v.is_empty()),
|
||||
}
|
||||
}
|
||||
|
||||
fn file_matches(&self, f: &FileCondition, props: &HashMap<String, String>, files: &mut Vec<PathBuf>) -> bool {
|
||||
let (path, missing) = match (&f.exists, &f.missing) {
|
||||
(Some(path), _) => (path, false),
|
||||
(None, Some(path)) => (path, true),
|
||||
(None, None) => return false,
|
||||
};
|
||||
let path = crate::gradle::normalize(&self.basedir.join(interpolate(path, props)));
|
||||
let exists = path.exists();
|
||||
files.push(path);
|
||||
exists != missing
|
||||
}
|
||||
}
|
||||
|
||||
fn negation(value: &str) -> (bool, &str) {
|
||||
match value.strip_prefix('!') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, value),
|
||||
}
|
||||
}
|
||||
|
||||
/// `<os>` as Maven 3.9 matches it (`org.apache.maven.utils.Os`) against what Java reports for
|
||||
/// this machine.
|
||||
fn os_matches(os: &OsCondition, props: &HashMap<String, String>) -> bool {
|
||||
let name = os_name().to_lowercase();
|
||||
let test = |value: &Option<String>, matches: &dyn Fn(&str) -> bool| {
|
||||
value.as_deref().is_none_or(|v| {
|
||||
let v = interpolate(v, props).to_lowercase();
|
||||
let (negated, v) = negation(&v);
|
||||
negated != matches(v)
|
||||
})
|
||||
};
|
||||
(os.family.is_some() || os.name.is_some() || os.arch.is_some())
|
||||
// The OS version Java reports is not known here.
|
||||
&& os.version.is_none()
|
||||
&& test(&os.family, &|family| family_matches(family, &name))
|
||||
&& test(&os.name, &|n| n == name)
|
||||
&& test(&os.arch, &|arch| arch == os_arch())
|
||||
}
|
||||
|
||||
fn family_matches(family: &str, os_name: &str) -> bool {
|
||||
let windows = os_name.contains("windows");
|
||||
let win9x = windows && ["95", "98", "me", "ce"].iter().any(|v| os_name.contains(v));
|
||||
let mac = os_name.contains("mac") || os_name.contains("darwin");
|
||||
match family {
|
||||
"windows" => windows,
|
||||
"win9x" => win9x,
|
||||
"winnt" => windows && !win9x,
|
||||
"dos" => cfg!(windows) && !os_name.contains("netware"),
|
||||
"mac" => mac,
|
||||
"unix" => !cfg!(windows) && !os_name.contains("openvms") && (!mac || os_name.ends_with('x')),
|
||||
"tandem" => os_name.contains("nonstop_kernel"),
|
||||
"z/os" => os_name.contains("z/os") || os_name.contains("os/390"),
|
||||
family => os_name.contains(family),
|
||||
}
|
||||
}
|
||||
|
||||
/// `os.name` as Java reports it; on Windows it also names the version, which is not known here.
|
||||
fn os_name() -> &'static str {
|
||||
match std::env::consts::OS {
|
||||
"macos" => "Mac OS X",
|
||||
"windows" => "Windows",
|
||||
"linux" => "Linux",
|
||||
"freebsd" => "FreeBSD",
|
||||
"openbsd" => "OpenBSD",
|
||||
"netbsd" => "NetBSD",
|
||||
"solaris" | "illumos" => "SunOS",
|
||||
"aix" => "AIX",
|
||||
os => os,
|
||||
}
|
||||
}
|
||||
|
||||
/// `os.arch` as Java reports it.
|
||||
fn os_arch() -> &'static str {
|
||||
match std::env::consts::ARCH {
|
||||
"x86_64" if cfg!(target_os = "macos") => "x86_64",
|
||||
"x86_64" => "amd64",
|
||||
"x86" if cfg!(windows) => "x86",
|
||||
"x86" => "i386",
|
||||
"powerpc64" if cfg!(target_endian = "little") => "ppc64le",
|
||||
"powerpc64" => "ppc64",
|
||||
arch => arch,
|
||||
}
|
||||
}
|
||||
|
||||
/// The system properties of Maven's JVM that conditions use: the environment as `env.*`, and
|
||||
/// those of the JVM's own that are known here.
|
||||
fn system_property(name: &str) -> Option<String> {
|
||||
if let Some(var) = name.strip_prefix("env.") {
|
||||
return std::env::var(var).ok();
|
||||
}
|
||||
match name {
|
||||
"os.name" => Some(os_name().to_owned()),
|
||||
"os.arch" => Some(os_arch().to_owned()),
|
||||
"user.home" => dirs::home_dir().map(|home| home.to_string_lossy().into_owned()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn profiles(xml: &str) -> Vec<RawProfile> {
|
||||
super::super::parse_pom(&format!("<project><profiles>{xml}</profiles></project>")).unwrap().profiles
|
||||
}
|
||||
|
||||
fn holds(env: &Env, activation: &str) -> bool {
|
||||
let profiles = profiles(&format!("<profile><id>p</id><activation>{activation}</activation></profile>"));
|
||||
env.conditions(&profiles, &[], &mut Vec::new())[0]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_config_takes_one_option_per_line() {
|
||||
let config = MavenConfig::parse(
|
||||
"# shared options\n-Pci,!slow\n-P\nnative\n--activate-profiles=docs\n-Dflavor=x\n-Dquick\n-D\nmode=a=b\n-T4\n",
|
||||
);
|
||||
assert_eq!(config.profiles, ["ci", "!slow", "native", "docs"]);
|
||||
let properties = HashMap::from(
|
||||
[("flavor", "x"), ("quick", "true"), ("mode", "a=b")].map(|(k, v)| (k.to_owned(), v.to_owned())),
|
||||
);
|
||||
assert_eq!(config.properties, properties);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditions_hold_as_mavens_activators_decide() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(dir.path().join("present")).unwrap();
|
||||
let activation = ProfileActivation { jdk: Some(21), ..Default::default() };
|
||||
let config = MavenConfig::parse("-Dflavor=x\n-Dempty=\n");
|
||||
let env = Env { activation: &activation, config: &config, basedir: dir.path() };
|
||||
let family = if cfg!(windows) {
|
||||
"windows"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"mac"
|
||||
} else {
|
||||
"unix"
|
||||
};
|
||||
let cases = [
|
||||
("<property><name>flavor</name></property>".to_owned(), true),
|
||||
("<property><name>!flavor</name></property>".into(), false),
|
||||
("<property><name>flavor</name><value>x</value></property>".into(), true),
|
||||
("<property><name>flavor</name><value>!x</value></property>".into(), false),
|
||||
("<property><name>empty</name></property>".into(), false),
|
||||
("<property><name>!unset</name></property>".into(), true),
|
||||
(format!("<os><family>{family}</family></os>"), true),
|
||||
(format!("<os><family>!{family}</family></os>"), false),
|
||||
("<os><family>os/400</family></os>".into(), false),
|
||||
(format!("<os><arch>{}</arch></os>", os_arch()), true),
|
||||
// Maven compares what Java reports (`Mac OS X`, `aarch64`), not other spellings.
|
||||
(format!("<os><name>{}</name></os>", os_name()), true),
|
||||
("<os><name>macos</name></os>".into(), false),
|
||||
("<os><arch>arm64</arch></os>".into(), false),
|
||||
("<os/>".into(), false),
|
||||
("<file><exists>present</exists></file>".into(), true),
|
||||
("<file><missing>${basedir}/absent</missing></file>".into(), true),
|
||||
("<file/>".into(), false),
|
||||
("<jdk>[17,)</jdk>".into(), true),
|
||||
("<jdk></jdk>".into(), true),
|
||||
(format!("<os><family>{family}</family></os><jdk>[30,)</jdk>"), false),
|
||||
];
|
||||
for (activation, expected) in cases {
|
||||
assert_eq!(holds(&env, &activation), expected, "{activation}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_profile_turned_off_stays_off_and_active_by_default_ones_step_aside() {
|
||||
let ps = profiles(
|
||||
"<profile><id>dev</id><activation><activeByDefault>true</activeByDefault></activation></profile>\
|
||||
<profile><id>ci</id></profile>",
|
||||
);
|
||||
let config = MavenConfig::default();
|
||||
let none = [false, false];
|
||||
let select = |profiles: &[&str], choices: &[&str], implicit: bool| {
|
||||
let activation = ProfileActivation {
|
||||
profiles: profiles.iter().map(|p| p.to_string()).collect(),
|
||||
choices: choices.iter().map(|p| p.to_string()).collect(),
|
||||
jdk: None,
|
||||
};
|
||||
let env = Env { activation: &activation, config: &config, basedir: Path::new("/") };
|
||||
if implicit { env.implicit(&ps, &none) } else { env.select(&ps, &none, None) }
|
||||
};
|
||||
assert_eq!(select(&[], &[], false), [true, false]);
|
||||
assert_eq!(select(&[], &["ci"], false), [false, true]);
|
||||
assert_eq!(select(&[], &["ci", "dev"], false), [true, true]);
|
||||
// Turned off by the tool window while Settings turn it on: off, whatever the order.
|
||||
assert_eq!(select(&["ci"], &["!ci"], false), [true, false]);
|
||||
// Still on unless the tool window turns it off, so it keeps passing `-P!ci`.
|
||||
assert_eq!(select(&["ci"], &["!ci"], true), [true, true]);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ use std::fs::{self, File};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1";
|
||||
const SOURCE_REFRESH_WORKERS: usize = 4;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
@@ -44,7 +43,15 @@ impl Artifact {
|
||||
|
||||
/// Resolve only jars inside the selected local repository, including custom repositories.
|
||||
pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
let relative = jar.strip_prefix(repository).ok()?;
|
||||
let (jar, relative) = match jar.strip_prefix(repository) {
|
||||
Ok(rel) => (jar.to_path_buf(), rel.to_path_buf()),
|
||||
Err(_) => {
|
||||
let canon_repo = dunce::canonicalize(repository).ok()?;
|
||||
let canon_jar = dunce::canonicalize(jar).unwrap_or_else(|_| jar.to_path_buf());
|
||||
let rel = canon_jar.strip_prefix(&canon_repo).ok()?.to_path_buf();
|
||||
(canon_jar, rel)
|
||||
}
|
||||
};
|
||||
let parts: Vec<&str> = relative
|
||||
.components()
|
||||
.map(|c| match c {
|
||||
@@ -64,8 +71,8 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option<Artifact> {
|
||||
group: parts[..n - 3].join("."),
|
||||
name: name.into(),
|
||||
version: version.into(),
|
||||
binary: jar.to_owned(),
|
||||
sources: jar.with_file_name(format!("{name}-{version}-sources.jar")),
|
||||
binary: jar,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -99,6 +106,11 @@ fn resolve(
|
||||
args.extend(profile_args.iter().cloned());
|
||||
args.push(format!("-Dmaven.repo.local={}", repository.display()));
|
||||
let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version);
|
||||
// The newest `maven-dependency-plugin` the project's Maven can load (#8114).
|
||||
let plugin = format!(
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:{}",
|
||||
super::pinned_plugin("maven-dependency-plugin", super::maven_version(&project.command))
|
||||
);
|
||||
let stage = if let Some(binary) = stale {
|
||||
// Keep the existing attachment readable while Maven resolves the timestamped snapshot.
|
||||
// Disable Resolver's in-place copy to the base -SNAPSHOT filename.
|
||||
@@ -107,14 +119,14 @@ fn resolve(
|
||||
args.extend([
|
||||
"-U".into(),
|
||||
"-Daether.artifactResolver.snapshotNormalization=false".into(),
|
||||
format!("{DEPENDENCY_PLUGIN}:copy"),
|
||||
format!("{plugin}:copy"),
|
||||
coordinate,
|
||||
"-Dmdep.useBaseVersion=true".into(),
|
||||
format!("-DoutputDirectory={}", stage.path().display()),
|
||||
]);
|
||||
Some((stage, binary))
|
||||
} else {
|
||||
args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]);
|
||||
args.extend([format!("{plugin}:get"), coordinate, "-Dtransitive=false".into()]);
|
||||
None
|
||||
};
|
||||
let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?;
|
||||
@@ -290,6 +302,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_canonicalized_jar_against_non_canonical_repository() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let real_repo = dir.path().join("real-repo");
|
||||
let sibling = dir.path().join("other");
|
||||
let jar = real_repo.join("org/example/demo/1.2.3/demo-1.2.3.jar");
|
||||
fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
fs::create_dir_all(&sibling).unwrap();
|
||||
fs::write(&jar, b"").unwrap();
|
||||
let canon_jar = dunce::canonicalize(&jar).unwrap();
|
||||
let non_canon_repo = sibling.join("..").join("real-repo");
|
||||
|
||||
let found = artifact(&canon_jar, &non_canon_repo).expect("should match via canonicalized repo fallback");
|
||||
assert_eq!(found.group, "org.example");
|
||||
assert_eq!(found.name, "demo");
|
||||
assert_eq!(found.version, "1.2.3");
|
||||
assert_eq!(found.sources, canon_jar.with_file_name("demo-1.2.3-sources.jar"));
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let link_repo = dir.path().join("m2-link");
|
||||
std::os::unix::fs::symlink(&real_repo, &link_repo).unwrap();
|
||||
let linked = artifact(&canon_jar, &link_repo).expect("should match through symlinked Maven repo");
|
||||
assert_eq!(linked.group, "org.example");
|
||||
assert_eq!(linked.sources, canon_jar.with_file_name("demo-1.2.3-sources.jar"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_existing_snapshot_attachments_from_the_resolved_tree() {
|
||||
use crate::maven::{MavenDependency, Omission};
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::process::{self, Output};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
@@ -32,6 +32,8 @@ pub struct SyncOptions {
|
||||
pub profiles: Vec<String>,
|
||||
/// Extra environment (`JAVA_HOME`).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Major version of the JDK Maven runs on, the same as the model is loaded with.
|
||||
pub jdk_version: Option<u32>,
|
||||
/// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home).
|
||||
pub maven_command: Option<String>,
|
||||
/// Resolved Gradle launcher from Settings.
|
||||
@@ -62,6 +64,9 @@ struct MavenCache {
|
||||
/// The trees list omitted occurrences (`-Dverbose`); older caches are reloaded.
|
||||
#[serde(default)]
|
||||
verbose: bool,
|
||||
/// [`MavenModel::jdk_activations`] of the sync; `None` in caches from before they were recorded.
|
||||
#[serde(default)]
|
||||
jdk_activations: Option<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
@@ -76,6 +81,9 @@ struct GradleCache {
|
||||
/// The projects report how their resources are processed; older caches are stale.
|
||||
#[serde(default)]
|
||||
resources: bool,
|
||||
/// The source sets report the `Test` tasks running them; older caches are stale.
|
||||
#[serde(default)]
|
||||
test_tasks: bool,
|
||||
}
|
||||
|
||||
/// Init script printing every project, its source sets and Java version once configured.
|
||||
@@ -84,34 +92,39 @@ const MODEL_INIT_SCRIPT: &str = include_str!("gradle-model.gradle");
|
||||
const MAVEN_CACHE: &str = "maven.json";
|
||||
const MAVEN_CACHE_VERSION: u32 = 1;
|
||||
|
||||
/// `dependency:tree` of a plugin version whose `-Dverbose` lists the occurrences Maven
|
||||
/// omitted (conflicts, duplicates): verbose output was dropped in 3.0 and is back since 3.2.
|
||||
/// Offline, it is used only when an earlier sync downloaded it; otherwise the newest version
|
||||
/// in the local repository is.
|
||||
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
|
||||
const DEPENDENCY_TREE_JAR: &str =
|
||||
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
|
||||
|
||||
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
|
||||
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
|
||||
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
|
||||
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
|
||||
/// still resolves the dependency tree instead of failing to download the help plugin.
|
||||
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
|
||||
/// `repo` is the local repository the build resolves from and `maven` the version of the Maven
|
||||
/// that runs them, when known. Both goals name their plugin by coordinates: offline, a prefix
|
||||
/// resolves only from group metadata the repository may lack. The tree uses a pinned
|
||||
/// `maven-dependency-plugin` whose `-Dverbose` lists the occurrences Maven omitted (conflicts,
|
||||
/// duplicates; dropped in 3.0, back since 3.2), the newest that `maven` can load; offline it is
|
||||
/// used only when an earlier sync downloaded it, otherwise the newest compatible version in the
|
||||
/// local repository is. Offline without a cached compatible 3.x `maven-help-plugin`,
|
||||
/// `effective-pom` is skipped so `mvn -o` still resolves the dependency tree instead of failing
|
||||
/// to download the help plugin.
|
||||
fn maven_sync_goals(
|
||||
effective: &Path,
|
||||
offline: bool,
|
||||
repo: Option<&Path>,
|
||||
maven: Option<maven::MavenVersion>,
|
||||
) -> Vec<String> {
|
||||
let version = maven::pinned_plugin("maven-dependency-plugin", maven);
|
||||
let jar =
|
||||
format!("org/apache/maven/plugins/maven-dependency-plugin/{version}/maven-dependency-plugin-{version}.jar");
|
||||
let pinned = !offline || repo.is_some_and(|repo| repo.join(jar).is_file());
|
||||
let tree = if pinned {
|
||||
DEPENDENCY_TREE.to_owned()
|
||||
format!("org.apache.maven.plugins:maven-dependency-plugin:{version}:tree")
|
||||
} else {
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2)).map_or_else(
|
||||
repo.and_then(|repo| maven::newest_local_plugin(repo, "maven-dependency-plugin", 2, maven)).map_or_else(
|
||||
|| "dependency:tree".to_owned(),
|
||||
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
|
||||
)
|
||||
};
|
||||
let has_help =
|
||||
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
|
||||
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3, maven).is_some());
|
||||
let mut goals = Vec::with_capacity(4);
|
||||
if has_help {
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo));
|
||||
goals.push(maven::plugin_goal("help:effective-pom", repo, maven));
|
||||
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
|
||||
}
|
||||
goals.push(tree);
|
||||
@@ -233,7 +246,9 @@ pub fn apply_maven_cache(root: &Path, cache_dir: &Path, model: &mut MavenModel)
|
||||
}
|
||||
model.synced_at = Some(cache.at_ms);
|
||||
model.sync_error = cache.error;
|
||||
let changed = cache.hash != hash_files(&maven::build_files(root, model));
|
||||
// Another JDK can switch profiles of the same build files.
|
||||
let changed = cache.hash != hash_files(&maven::build_files(root, model))
|
||||
|| cache.jdk_activations.is_some_and(|jdks| jdks != model.jdk_activations);
|
||||
model.stale = !cache.verbose || changed;
|
||||
// A cache older than the current build files: its effective-POM plugins and
|
||||
// resolved dependencies would hide what the POMs declare now (a just added
|
||||
@@ -288,8 +303,9 @@ pub fn apply_gradle_cache(root: &Path, cache_dir: &Path, model: &mut GradleModel
|
||||
}
|
||||
}
|
||||
// A successful sync from before projects were cached has not seen computed includes,
|
||||
// nor, before resources were read, which launches need Gradle to process them.
|
||||
let outdated = cache.error.is_none() && (cache.projects.is_empty() || !cache.resources);
|
||||
// nor, before resources were read, which launches need Gradle to process them, nor, before
|
||||
// test tasks were read, which task runs the tests of a test suite.
|
||||
let outdated = cache.error.is_none() && (cache.projects.is_empty() || !cache.resources || !cache.test_tasks);
|
||||
model.synced_at = Some(cache.at_ms);
|
||||
model.sync_error = cache.error;
|
||||
model.stale = outdated || cache.hash != hash_gradle_files(&gradle::build_files(root, model));
|
||||
@@ -368,10 +384,12 @@ pub fn sync_maven(
|
||||
cancel: &CancellationToken,
|
||||
progress: &dyn Fn(SyncProgress),
|
||||
) -> IdeResult<()> {
|
||||
let mut model = maven::load_with_linked(
|
||||
let activation =
|
||||
maven::ProfileActivation::new(root, &options.maven_settings, &options.profiles, options.jdk_version);
|
||||
let mut model = maven::load_with_activation(
|
||||
root,
|
||||
maven::default_local_repo(),
|
||||
&options.maven_settings.profiles(&options.profiles),
|
||||
&activation,
|
||||
&options.maven_settings.linked_projects,
|
||||
);
|
||||
maven::UnlinkedProjects::from_model(&model, &options.maven_settings).filter(&mut model);
|
||||
@@ -380,6 +398,7 @@ pub fn sync_maven(
|
||||
version: MAVEN_CACHE_VERSION,
|
||||
hash: hash_files(&maven::build_files(root, &model)),
|
||||
verbose: true,
|
||||
jdk_activations: Some(model.jdk_activations.clone()),
|
||||
..MavenCache::default()
|
||||
};
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read from.
|
||||
@@ -405,9 +424,9 @@ pub fn sync_maven(
|
||||
if !options.profiles.is_empty() {
|
||||
args.push(format!("-P{}", options.profiles.join(",")));
|
||||
}
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref()));
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let command = options.maven_command.as_deref().unwrap_or(&top.command);
|
||||
args.extend(maven_sync_goals(&effective, options.offline, repo.as_deref(), maven::maven_version(command)));
|
||||
progress(SyncProgress { message: format!("Reading {}", top.display_name), fraction: None });
|
||||
let out = run(command, &args, &root.join(&top.dir), &options.env, cancel, |line| {
|
||||
if let Some((name, i, total)) = maven_building(line) {
|
||||
let fraction = (i.saturating_sub(1) as f32 / total.max(1) as f32).min(1.0);
|
||||
@@ -480,11 +499,9 @@ pub fn sync_gradle_model(
|
||||
"-q".into(),
|
||||
// The init script reports the evaluated projects, even when a build enables the configuration cache.
|
||||
"-Dorg.gradle.configuration-cache=false".into(),
|
||||
"--init-script".into(),
|
||||
init_script.to_string_lossy().into_owned(),
|
||||
"tasks".into(),
|
||||
"--all".into(),
|
||||
];
|
||||
args.extend(gradle::no_isolated_projects(&root.join(&model.dir), &options.env));
|
||||
args.extend(["--init-script".into(), init_script.to_string_lossy().into_owned(), "tasks".into(), "--all".into()]);
|
||||
if options.offline {
|
||||
args.push("--offline".into());
|
||||
}
|
||||
@@ -517,6 +534,7 @@ pub fn sync_gradle_model(
|
||||
tasks: if out.success { gradle::parse_tasks(&out.text) } else { Vec::new() },
|
||||
projects,
|
||||
resources: true,
|
||||
test_tasks: true,
|
||||
};
|
||||
write_cache(&cache_dir, GRADLE_CACHE, &cache)
|
||||
}
|
||||
@@ -683,6 +701,7 @@ mod tests {
|
||||
at_ms: 5.0,
|
||||
error: None,
|
||||
verbose: true,
|
||||
jdk_activations: None,
|
||||
projects: vec![CachedMavenProject {
|
||||
key: "g:a".into(),
|
||||
plugins: vec![maven::plugin(
|
||||
@@ -733,6 +752,7 @@ mod tests {
|
||||
at_ms: 5.0,
|
||||
error: None,
|
||||
verbose: true,
|
||||
jdk_activations: None,
|
||||
projects: vec![CachedMavenProject {
|
||||
key: "g:a".into(),
|
||||
plugins: vec![maven::plugin(
|
||||
@@ -772,7 +792,7 @@ mod tests {
|
||||
test,
|
||||
src: src.iter().map(|p| core_src(p)).collect(),
|
||||
res: res.iter().map(|p| core_src(p)).collect(),
|
||||
processed: None,
|
||||
..Default::default()
|
||||
};
|
||||
// A settings script's own println comes first; task listing lines follow.
|
||||
let out = format!(
|
||||
@@ -873,6 +893,7 @@ mod tests {
|
||||
})
|
||||
.collect(),
|
||||
resources: true,
|
||||
test_tasks: true,
|
||||
};
|
||||
write_cache(&cache_dir, GRADLE_CACHE, &cache).unwrap();
|
||||
apply_gradle_cache(&root, &cache_dir, &mut model);
|
||||
@@ -918,6 +939,7 @@ mod tests {
|
||||
..Default::default()
|
||||
}],
|
||||
resources: true,
|
||||
test_tasks: true,
|
||||
..Default::default()
|
||||
};
|
||||
write_cache(&cache_dir, GRADLE_CACHE, &cache).unwrap();
|
||||
@@ -948,15 +970,19 @@ mod tests {
|
||||
assert!(!save_maven_offline(&tmp.path().join("other"), false).unwrap(), "online is the default");
|
||||
}
|
||||
|
||||
const DEPENDENCY_TREE: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:tree";
|
||||
const DEPENDENCY_TREE_JAR: &str =
|
||||
"org/apache/maven/plugins/maven-dependency-plugin/3.8.1/maven-dependency-plugin-3.8.1.jar";
|
||||
|
||||
#[test]
|
||||
fn sync_reads_verbose_trees_with_a_pinned_plugin_unless_offline_without_it() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
|
||||
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()), None);
|
||||
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
|
||||
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
|
||||
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
|
||||
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
|
||||
// since the prefix needs group metadata a repository filled from a private mirror may lack;
|
||||
@@ -967,21 +993,37 @@ mod tests {
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
}
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
|
||||
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
|
||||
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&help_jar, "").unwrap();
|
||||
// A version folder without its jar (only the POM was fetched) doesn't count.
|
||||
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
|
||||
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None);
|
||||
assert_eq!(offline[0], "org.apache.maven.plugins:maven-help-plugin:3.4.0:effective-pom");
|
||||
assert_eq!(offline[2], "org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree");
|
||||
// Downloaded by an online sync: offline keeps using it, the project's version may be missing.
|
||||
let jar = tmp.path().join(DEPENDENCY_TREE_JAR);
|
||||
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&jar, "").unwrap();
|
||||
assert_eq!(maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()))[2], DEPENDENCY_TREE);
|
||||
assert_eq!(maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()), None)[2], DEPENDENCY_TREE);
|
||||
}
|
||||
|
||||
/// #8114: an old Maven gets plugin versions it can load, also for the verbose tree.
|
||||
#[test]
|
||||
fn sync_goals_follow_the_maven_version() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let goals = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()), Some((3, 3, 9)));
|
||||
assert_eq!(
|
||||
goals,
|
||||
[
|
||||
"org.apache.maven.plugins:maven-help-plugin:3.3.0:effective-pom",
|
||||
"-Doutput=e.xml",
|
||||
"org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree",
|
||||
"-Dverbose",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1055,6 +1097,95 @@ mod tests {
|
||||
assert_eq!(std::fs::metadata(&mvnw).unwrap().permissions().mode() & 0o777, 0o644);
|
||||
}
|
||||
|
||||
/// `root` with module `core`, and what `profile` adds when the JDK activates it: the module
|
||||
/// `modern` or only a property. Synced with `jdk` by a launcher printing `core`'s tree.
|
||||
#[cfg(unix)]
|
||||
fn synced_with_a_jdk_profile(base: &Path, profile: &str, jdk: Option<u32>) -> (PathBuf, PathBuf) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (root, cache) = (base.join("p"), base.join("cache"));
|
||||
let project = "<project><groupId>g</groupId><version>1</version>";
|
||||
for module in ["core", "modern"] {
|
||||
std::fs::create_dir_all(root.join(module)).unwrap();
|
||||
let pom = format!("{project}<artifactId>{module}</artifactId></project>");
|
||||
std::fs::write(root.join(module).join("pom.xml"), pom).unwrap();
|
||||
}
|
||||
let pom = format!(
|
||||
"{project}<artifactId>root</artifactId><packaging>pom</packaging><modules><module>core</module></modules>\
|
||||
<profiles><profile><id>modern</id><activation><jdk>[11,)</jdk></activation>{profile}</profile></profiles>\
|
||||
</project>"
|
||||
);
|
||||
std::fs::write(root.join("pom.xml"), pom).unwrap();
|
||||
let launcher = base.join("mvn");
|
||||
let tree = "[INFO] --- dependency:3.8.1:tree (default-cli) @ core ---\\n[INFO] g:core:jar:1\\n\
|
||||
[INFO] \\\\- g:lib:jar:1:compile\\n[INFO] \\\\- g:transitive:jar:1:compile\\n";
|
||||
std::fs::write(&launcher, format!("#!/bin/sh\nprintf '{tree}'\n")).unwrap();
|
||||
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let options = SyncOptions {
|
||||
maven_command: Some(launcher.to_string_lossy().into_owned()),
|
||||
jdk_version: jdk,
|
||||
..Default::default()
|
||||
};
|
||||
sync_maven(&root, &cache, &options, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
(root, cache)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn loaded_with_jdk((root, cache): &(PathBuf, PathBuf), jdk: Option<u32>) -> MavenModel {
|
||||
crate::load_linked_with_jdk(root, cache, None, &Default::default(), &Default::default(), jdk).maven.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
const MODULE: &str = "<modules><module>modern</module></modules>";
|
||||
#[cfg(unix)]
|
||||
const PROPERTY: &str = "<properties><x>1</x></properties>";
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_synced_model_with_a_jdk_profile_is_current() {
|
||||
for (profile, jdk, modules) in
|
||||
[(MODULE, Some(17), 3), (MODULE, Some(8), 2), (MODULE, None, 2), (PROPERTY, Some(17), 2)]
|
||||
{
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, jdk), jdk);
|
||||
assert_eq!(model.projects.len(), modules, "{profile} {jdk:?}");
|
||||
assert!(!model.stale, "{profile} {jdk:?}");
|
||||
let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap();
|
||||
assert_eq!(core.dependencies[0].children[0].artifact_id, "transitive", "{profile} {jdk:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_jdk_change_is_stale_when_it_switches_a_profile() {
|
||||
for profile in [MODULE, PROPERTY] {
|
||||
for (synced, loaded, stale) in [
|
||||
(Some(17), Some(21), false),
|
||||
(Some(17), Some(8), true),
|
||||
(Some(8), Some(17), true),
|
||||
(Some(17), None, true),
|
||||
(None, Some(17), true),
|
||||
(None, Some(8), false),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, synced), loaded);
|
||||
assert_eq!(model.stale, stale, "{profile} {synced:?} {loaded:?}");
|
||||
let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap();
|
||||
assert_eq!(core.dependencies.is_empty(), stale, "{profile} {synced:?} {loaded:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_sync_from_before_jdk_profiles_were_recorded_stays_current() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = synced_with_a_jdk_profile(tmp.path(), PROPERTY, Some(17));
|
||||
let mut json: serde_json::Value = read_cache(&project.1, MAVEN_CACHE).unwrap();
|
||||
assert!(json.as_object_mut().unwrap().remove("jdk_activations").is_some());
|
||||
write_cache(&project.1, MAVEN_CACHE, &json).unwrap();
|
||||
assert!(!loaded_with_jdk(&project, Some(17)).stale);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn maven_sync_runs_the_daemon_command_serially() {
|
||||
@@ -1075,4 +1206,42 @@ mod tests {
|
||||
assert!(args.contains("-T1"), "args: {args}");
|
||||
assert!(args.contains("maven-help-plugin:"), "args: {args}");
|
||||
}
|
||||
|
||||
/// Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path).
|
||||
#[test]
|
||||
fn gradle_sync_lists_tasks_of_builds_that_enable_isolated_projects() {
|
||||
let has_jdk = std::env::var_os("JAVA_HOME").is_some();
|
||||
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
|
||||
.map(std::path::PathBuf::from)
|
||||
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()));
|
||||
let Some(gradle) = gradle.filter(|_| has_jdk) else {
|
||||
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
|
||||
return;
|
||||
};
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(temp.path()).unwrap();
|
||||
let files = [
|
||||
(
|
||||
"gradle.properties",
|
||||
"org.gradle.daemon=false\norg.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n",
|
||||
),
|
||||
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib'\n"),
|
||||
("build.gradle", ""),
|
||||
("lib/build.gradle", "plugins { id 'java' }\n"),
|
||||
];
|
||||
for (rel, text) in files {
|
||||
let path = root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
let mut model = gradle::load(&root).unwrap();
|
||||
model.command = gradle.to_string_lossy().into_owned();
|
||||
let cache = root.join(".cache");
|
||||
sync_gradle_model(&root, &cache, &model, &SyncOptions::default(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let loaded = crate::load(&root, &cache, None);
|
||||
let build = &loaded.gradle[0];
|
||||
assert_eq!(build.sync_error, None);
|
||||
let lib = build.projects.iter().find(|p| p.path == ":lib").expect("the reported :lib project");
|
||||
assert!(lib.tasks.iter().any(|t| t.name == "compileJava"), "{:?}", lib.tasks);
|
||||
}
|
||||
}
|
||||
@@ -110,35 +110,26 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
}
|
||||
fs::write(cache.join("artifact-id.txt"), id)?;
|
||||
if let Some(pom) = id.strip_prefix("maven:") {
|
||||
let p = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.and_then(|m| m.projects.iter().find(|p| p.pom == pom && p.packaging == "war"))
|
||||
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let projects = &model.maven.as_ref().unwrap().projects;
|
||||
let top = projects
|
||||
let maven = model.maven.as_ref().ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let p = maven
|
||||
.projects
|
||||
.iter()
|
||||
.filter(|t| {
|
||||
!t.aggregated && (t.dir.is_empty() || p.dir == t.dir || p.dir.starts_with(&format!("{}/", t.dir)))
|
||||
})
|
||||
.max_by_key(|t| t.dir.len())
|
||||
.unwrap_or(p);
|
||||
.find(|p| p.pom == pom && p.packaging == "war")
|
||||
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let top = crate::maven::reactor_for_pom(maven, &p.pom).unwrap_or(p);
|
||||
let mut args = top.options.clone();
|
||||
if top.pom != p.pom {
|
||||
let module = root
|
||||
.join(&p.dir)
|
||||
.strip_prefix(root.join(&top.dir))
|
||||
.map_err(|e| IdeError::invalid(e.to_string()))?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
if let Some(module) = crate::maven::module_selector(root, top, p) {
|
||||
args.extend(["-pl".into(), module, "-am".into()]);
|
||||
}
|
||||
// help:evaluate runs once, in the reactor's first project. Query the selected
|
||||
// POM's effective identity first; profiles and -D options can change its GAV.
|
||||
let output = cache.join("artifact-project.txt");
|
||||
let mut probe = top.options.clone();
|
||||
let evaluate =
|
||||
crate::maven::plugin_goal("help:evaluate", crate::maven::local_repository_for(&top.options).as_deref());
|
||||
let evaluate = crate::maven::plugin_goal(
|
||||
"help:evaluate",
|
||||
crate::maven::local_repository_for(&top.options).as_deref(),
|
||||
crate::maven::maven_version(&top.command),
|
||||
);
|
||||
probe.extend([
|
||||
"-f".into(),
|
||||
root.join(&p.pom).to_string_lossy().into_owned(),
|
||||
@@ -316,4 +307,90 @@ mod tests {
|
||||
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_sibling_reactor_builds_war_through_aggregator_with_relative_pl() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["parent", "common", "app"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
fs::write(
|
||||
root.join("parent/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("common/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("app/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging><dependencies><dependency><groupId>test</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let a = artifacts(root, &model);
|
||||
assert_eq!(a.len(), 1);
|
||||
assert_eq!(a[0].id, "maven:app/pom.xml");
|
||||
|
||||
let plan = build(root, &model, &a[0].id, &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, "parent");
|
||||
assert_eq!(&plan.args[..3], &["-pl", "../app", "-am"]);
|
||||
let (probe, _) = plan.maven_project.as_ref().unwrap();
|
||||
assert!(probe.contains(&root.join("app/pom.xml").to_string_lossy().into_owned()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_subfolder_aggregator_builds_root_war_with_parent_pl() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["parent", "common"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
fs::write(
|
||||
root.join("pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("parent/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../</module><module>../common</module></modules></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("common/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let settings =
|
||||
ide_core::settings::MavenSettings { linked_projects: vec!["parent/pom.xml".into()], ..Default::default() };
|
||||
let model = crate::load_linked(root, &root.join("cache"), None, &settings, &Default::default());
|
||||
let plan = build(root, &model, "maven:pom.xml", &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, "parent");
|
||||
assert_eq!(&plan.args[..3], &["-pl", "..", "-am"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_independent_sibling_wars_keep_own_reactor() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["a", "b"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
fs::write(
|
||||
root.join(dir).join("pom.xml"),
|
||||
format!("<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>{dir}</artifactId><version>1</version><packaging>war</packaging></project>"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
for dir in ["a", "b"] {
|
||||
let plan = build(root, &model, &format!("maven:{dir}/pom.xml"), &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, dir);
|
||||
assert!(!plan.args.contains(&"-pl".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
|
||||
png = "0.18"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
gtk = "0.18"
|
||||
gtk = "0.19"
|
||||
|
||||
[dev-dependencies]
|
||||
png = "0.18"
|
||||
@@ -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_Storage_FileSystem", "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_Environment", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -175,7 +175,7 @@ impl CliTool {
|
||||
Poll::Finished => break,
|
||||
}
|
||||
}
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
Ok((lines.finish(cancel)?.success(), stderr_tail))
|
||||
}
|
||||
|
||||
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
|
||||
@@ -301,9 +301,9 @@ impl Lines {
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
|
||||
/// killing it, when `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
|
||||
/// Waits for the child to exit and returns how it exited. Fails, after killing it, when
|
||||
/// `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<std::process::ExitStatus> {
|
||||
let status = loop {
|
||||
if let Some(status) = self.child.try_wait()? {
|
||||
break status;
|
||||
@@ -314,6 +314,6 @@ impl Lines {
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(status.success())
|
||||
Ok(status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! The CMake File API queries the IDE writes into a build directory, shared by the run
|
||||
//! configurations (which read the replies) and Build Project (which configures).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The objects asked for: targets, cache, toolchains and the CMake files.
|
||||
pub const QUERIES: [&str; 4] = ["codemodel-v2", "cache-v2", "toolchains-v1", "cmakeFiles-v1"];
|
||||
const QUERY: &str = ".cmake/api/v1/query/client-openidea";
|
||||
/// Where CMake writes its replies, relative to the build directory.
|
||||
pub const REPLY: &str = ".cmake/api/v1/reply";
|
||||
|
||||
/// Asks CMake to answer [`QUERIES`] on the next configure of `build`.
|
||||
pub fn write_queries(build: &Path) -> std::io::Result<()> {
|
||||
let query = build.join(QUERY);
|
||||
std::fs::create_dir_all(&query)?;
|
||||
for name in QUERIES {
|
||||
std::fs::write(query.join(name), "")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -86,6 +86,8 @@ pub struct EditorAppearanceSettings {
|
||||
pub indent_guides: bool,
|
||||
/// Colour indent guides by depth (`--syn-rainbow-*`), while `indent_guides` is on.
|
||||
pub rainbow_indent_guides: bool,
|
||||
/// Also tint each indent level's whitespace in its rainbow colour, while `rainbow_indent_guides` is on.
|
||||
pub rainbow_indent_guides_fill: bool,
|
||||
/// Right margin and visual guides from Code Style.
|
||||
pub hard_wrap_guides: bool,
|
||||
pub intention_bulb: bool,
|
||||
@@ -114,6 +116,7 @@ impl Default for EditorAppearanceSettings {
|
||||
whitespace_trailing: true,
|
||||
indent_guides: true,
|
||||
rainbow_indent_guides: false,
|
||||
rainbow_indent_guides_fill: false,
|
||||
hard_wrap_guides: true,
|
||||
intention_bulb: true,
|
||||
render_doc_comments: false,
|
||||
@@ -377,6 +380,8 @@ pub struct CodeEditingSettings {
|
||||
pub quick_doc_delay: u32,
|
||||
/// Next / previous error goes to errors only (skips warnings).
|
||||
pub next_error_errors_only: bool,
|
||||
/// Show the diagnostic producer and rule code beneath each message in editor hover tooltips.
|
||||
pub show_diagnostic_source_on_hover: bool,
|
||||
pub sticky_lines_max: u32,
|
||||
pub sticky_lines_disabled_languages: Vec<String>,
|
||||
}
|
||||
@@ -390,6 +395,7 @@ impl Default for CodeEditingSettings {
|
||||
quick_doc_on_hover: true,
|
||||
quick_doc_delay: 500,
|
||||
next_error_errors_only: true,
|
||||
show_diagnostic_source_on_hover: true,
|
||||
sticky_lines_max: 5,
|
||||
sticky_lines_disabled_languages: Vec::new(),
|
||||
}
|
||||
@@ -401,6 +407,8 @@ impl Default for CodeEditingSettings {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct InlayHintsSettings {
|
||||
pub types: bool,
|
||||
/// Inferred variable and field types from the JavaScript and TypeScript servers (on, as in WebStorm).
|
||||
pub js_ts_types: bool,
|
||||
pub parameters: bool,
|
||||
/// Hints of other kinds (chaining, closing labels…).
|
||||
pub other: bool,
|
||||
@@ -436,6 +444,7 @@ impl Default for InlayHintsSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
types: true,
|
||||
js_ts_types: true,
|
||||
parameters: true,
|
||||
other: true,
|
||||
closing_labels: true,
|
||||
@@ -710,6 +719,19 @@ mod folding_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod inlay_hints_tests {
|
||||
use super::InlayHintsSettings;
|
||||
|
||||
#[test]
|
||||
fn existing_settings_enable_js_ts_type_hints_by_default() {
|
||||
let settings: InlayHintsSettings = serde_json::from_str(r#"{"parameters":false}"#).unwrap();
|
||||
assert!(settings.types);
|
||||
assert!(settings.js_ts_types);
|
||||
assert!(!settings.parameters);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sticky_lines_tests {
|
||||
use super::CodeEditingSettings;
|
||||
@@ -725,4 +747,15 @@ mod sticky_lines_tests {
|
||||
assert_eq!(saved.sticky_lines_disabled_languages, ["markdown", "rust"]);
|
||||
assert_eq!(serde_json::to_value(saved).unwrap()["stickyLinesDisabledLanguages"], json);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostic_source_on_hover_defaults_to_true_and_round_trips() {
|
||||
let legacy: CodeEditingSettings = serde_json::from_value(serde_json::json!({"quickDocOnHover": true})).unwrap();
|
||||
assert!(legacy.show_diagnostic_source_on_hover);
|
||||
let hidden: CodeEditingSettings =
|
||||
serde_json::from_value(serde_json::json!({"showDiagnosticSourceOnHover": false})).unwrap();
|
||||
assert!(!hidden.show_diagnostic_source_on_hover);
|
||||
let serialized = serde_json::to_value(&hidden).unwrap();
|
||||
assert_eq!(serialized["showDiagnosticSourceOnHover"], false);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,14 @@ use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The execution target recorded with an MCP agent run.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum McpAgentRunTarget {
|
||||
Host,
|
||||
Container { id: String },
|
||||
}
|
||||
|
||||
/// 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. `RunConfiguration` starts a run configuration (a serialized
|
||||
@@ -42,6 +50,7 @@ pub enum McpUiRequest {
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
target: McpAgentRunTarget,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
@@ -108,6 +117,14 @@ pub enum IdeEvent {
|
||||
host: String,
|
||||
#[serde(default)]
|
||||
taken_over: bool,
|
||||
/// Plain-language explanation when a dev container exited from the OOM killer (`OOMKilled` / exit 137).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
oom_message: Option<String>,
|
||||
/// Local configuration file (`devcontainer.json` or Compose file) that sets the container's limit.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
oom_config_path: Option<String>,
|
||||
},
|
||||
ProjectTrustChanged {
|
||||
root: crate::IpcPath,
|
||||
@@ -191,6 +208,12 @@ pub enum IdeEvent {
|
||||
/// A `LineEnding` in its serialized form: `lf`, `crLf` or `cr`.
|
||||
line_ending: String,
|
||||
},
|
||||
/// An open file was made read-only or writable outside the IDE (`chmod`, a VCS sync), which
|
||||
/// the editor only reads when it opens the file.
|
||||
DocReadOnly {
|
||||
doc: DocId,
|
||||
read_only: bool,
|
||||
},
|
||||
/// Full replacement of diagnostics for one file from one producer.
|
||||
Diagnostics {
|
||||
path: crate::IpcPath,
|
||||
@@ -311,6 +334,18 @@ pub enum IdeEvent {
|
||||
AskpassDone {
|
||||
id: u64,
|
||||
},
|
||||
/// An external `/api/file` request asks the target project window to confirm opening a file;
|
||||
/// answered with `web_file_api_confirm`.
|
||||
FileApiConfirm {
|
||||
id: u64,
|
||||
source: String,
|
||||
path: crate::IpcPath,
|
||||
line: Option<u32>,
|
||||
},
|
||||
/// File-open confirmation prompt `id` was answered or cancelled.
|
||||
FileApiConfirmDone {
|
||||
id: u64,
|
||||
},
|
||||
/// The kernel of an open notebook changed state (`starting`, `idle`, `busy`,
|
||||
/// `dead`); `message` says why it failed to start or died.
|
||||
NotebookKernel {
|
||||
@@ -430,6 +465,8 @@ pub enum LspRefreshKind {
|
||||
Inheritance,
|
||||
/// The Dart server published a document's Flutter outline.
|
||||
FlutterOutline,
|
||||
/// Spring bean markers of open documents may have changed.
|
||||
SpringBeanMarkers,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -81,9 +81,61 @@ pub fn strip(src: &str) -> String {
|
||||
cleaned
|
||||
}
|
||||
|
||||
/// Comments and a leading byte order mark turned into spaces, byte for byte, so that offsets
|
||||
/// into the result are offsets into `src`. Line breaks stay, and so do trailing commas.
|
||||
pub fn blank_comments(src: &str) -> String {
|
||||
let mut out = src.as_bytes().to_vec();
|
||||
let blank = |out: &mut [u8]| out.iter_mut().filter(|b| !matches!(b, b'\n' | b'\r')).for_each(|b| *b = b' ');
|
||||
let mut i = 0;
|
||||
if src.starts_with('\u{feff}') {
|
||||
i = '\u{feff}'.len_utf8();
|
||||
blank(&mut out[..i]);
|
||||
}
|
||||
let mut in_str = false;
|
||||
while i < src.len() {
|
||||
let rest = &src.as_bytes()[i..];
|
||||
let comment = match rest {
|
||||
[b'\\', ..] if in_str => {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
[b'"', ..] => {
|
||||
in_str = !in_str;
|
||||
None
|
||||
}
|
||||
[b'/', b'/', ..] if !in_str => Some(rest.iter().position(|&b| b == b'\n').unwrap_or(rest.len())),
|
||||
// An unterminated block comment runs to the end, leaving a document that still parses
|
||||
// only if it was complete before it.
|
||||
[b'/', b'*', ..] if !in_str => {
|
||||
Some(rest[2..].windows(2).position(|w| w == b"*/").map_or(rest.len(), |end| end + 4))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
match comment {
|
||||
Some(len) => {
|
||||
blank(&mut out[i..i + len]);
|
||||
i += len;
|
||||
}
|
||||
None => i += 1,
|
||||
}
|
||||
}
|
||||
// Only whole characters were replaced: comments and the mark start and end on ASCII.
|
||||
String::from_utf8(out).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::strip;
|
||||
use super::{blank_comments, strip};
|
||||
|
||||
#[test]
|
||||
fn blanking_comments_keeps_every_offset_and_trailing_commas() {
|
||||
let src = "\u{feff}{// é\r\n\"a//\\\"\": /* ü\n*/ 1,}";
|
||||
let blank = blank_comments(src);
|
||||
assert_eq!(blank.len(), src.len());
|
||||
assert_eq!(blank.split_whitespace().collect::<Vec<_>>(), ["{", "\"a//\\\"\":", "1,}"]);
|
||||
assert_eq!(blank.find('1'), src.find('1'));
|
||||
assert_eq!(blank_comments("{}/* open é"), "{} ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drops_comments_and_trailing_commas_outside_strings() {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
pub mod build_jobs;
|
||||
pub mod cli_process;
|
||||
pub mod cmake_file_api;
|
||||
pub mod editor_settings;
|
||||
pub mod error;
|
||||
pub mod event;
|
||||
|
||||
@@ -37,13 +37,16 @@ pub fn prepare(cmd: &mut Command) -> &mut Command {
|
||||
cmd
|
||||
}
|
||||
|
||||
/// cmd.exe drops an inherited variable longer than this outright, and batch files (`.cmd`,
|
||||
/// `.bat`) always run through it.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
const CMD_ENV_LIMIT: usize = 8191;
|
||||
|
||||
#[cfg(windows)]
|
||||
fn compact_batch_path(cmd: &mut Command) {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::{Component, Prefix};
|
||||
|
||||
// Rust runs these files through cmd.exe, which drops inherited variables over this limit.
|
||||
const CMD_ENV_LIMIT: usize = 8191;
|
||||
// Rust runs these files through cmd.exe.
|
||||
let extension = Path::new(cmd.get_program()).extension();
|
||||
if !extension.is_some_and(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat")) {
|
||||
return;
|
||||
@@ -52,25 +55,80 @@ fn compact_batch_path(cmd: &mut Command) {
|
||||
Some((_, path)) => path.map(OsStr::to_owned),
|
||||
None => std::env::var_os("PATH"),
|
||||
};
|
||||
let Some(path) = path.filter(|p| p.encode_wide().count() > CMD_ENV_LIMIT) else { return };
|
||||
|
||||
// The IDE includes possible locations of as-yet uninstalled tools. Prune paths that are
|
||||
// missing now, keeping search precedence and leaving UNC and relative paths alone.
|
||||
let dirs = std::env::split_paths(&path).filter(|dir| {
|
||||
let Some(path) = path else { return };
|
||||
// The IDE includes possible locations of as-yet uninstalled tools: drop the ones missing
|
||||
// now, leaving UNC and relative paths alone.
|
||||
let present = |dir: &Path| {
|
||||
let local = dir.is_absolute()
|
||||
&& matches!(dir.components().next(), Some(Component::Prefix(p))
|
||||
if matches!(p.kind(), Prefix::Disk(_) | Prefix::VerbatimDisk(_)));
|
||||
!local
|
||||
|| !std::fs::symlink_metadata(dir)
|
||||
.is_err_and(|e| matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory))
|
||||
});
|
||||
if let Ok(compact) = std::env::join_paths(dirs)
|
||||
&& compact.encode_wide().count() <= CMD_ENV_LIMIT
|
||||
{
|
||||
};
|
||||
if let Some(compact) = compact_path_list(&path, CMD_ENV_LIMIT, present, short_path) {
|
||||
cmd.env("PATH", compact);
|
||||
}
|
||||
}
|
||||
|
||||
/// The 8.3 form of `dir`, when the volume has one.
|
||||
#[cfg(windows)]
|
||||
fn short_path(dir: &Path) -> Option<std::path::PathBuf> {
|
||||
use std::os::windows::ffi::{OsStrExt, OsStringExt};
|
||||
use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW;
|
||||
|
||||
let wide: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
|
||||
let mut buf = vec![0u16; wide.len()];
|
||||
let len = u32::try_from(buf.len()).ok()?;
|
||||
// SAFETY: both buffers are valid for their lengths and `wide` is NUL-terminated.
|
||||
let written = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), len) } as usize;
|
||||
// 0 is an error; a value of at least the buffer's length is the size a longer form needs.
|
||||
if written == 0 || written >= buf.len() {
|
||||
return None;
|
||||
}
|
||||
buf.truncate(written);
|
||||
Some(OsString::from_wide(&buf).into())
|
||||
}
|
||||
|
||||
/// `path` (a `PATH` list) made to fit `limit` UTF-16 units where it is longer: later
|
||||
/// duplicates (without case on Windows) and directories `present` rejects are dropped, keeping
|
||||
/// the search order; when that is still too long, directories take `shorten`'s form, longest
|
||||
/// first, until it fits. `None` when `path` fits already or nothing got shorter.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn compact_path_list(
|
||||
path: &OsStr,
|
||||
limit: usize,
|
||||
present: impl Fn(&Path) -> bool,
|
||||
shorten: impl Fn(&Path) -> Option<std::path::PathBuf>,
|
||||
) -> Option<OsString> {
|
||||
let width = |s: &OsStr| s.to_string_lossy().encode_utf16().count();
|
||||
let original = width(path);
|
||||
if original <= limit {
|
||||
return None;
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut dirs: Vec<std::path::PathBuf> = std::env::split_paths(path)
|
||||
.filter(|d| !d.as_os_str().is_empty() && seen.insert(path_entry_key(d)) && present(d))
|
||||
.collect();
|
||||
let mut joined = std::env::join_paths(&dirs).ok()?;
|
||||
if width(&joined) > limit {
|
||||
let mut longest: Vec<usize> = (0..dirs.len()).collect();
|
||||
longest.sort_by_key(|&i| std::cmp::Reverse(width(dirs[i].as_os_str())));
|
||||
let mut total = width(&joined);
|
||||
for i in longest {
|
||||
if total <= limit {
|
||||
break;
|
||||
}
|
||||
if let Some(short) = shorten(&dirs[i]).filter(|s| width(s.as_os_str()) < width(dirs[i].as_os_str())) {
|
||||
total -= width(dirs[i].as_os_str()) - width(short.as_os_str());
|
||||
dirs[i] = short;
|
||||
}
|
||||
}
|
||||
joined = std::env::join_paths(&dirs).ok()?;
|
||||
}
|
||||
(width(&joined) < original).then_some(joined)
|
||||
}
|
||||
|
||||
/// Starts the child as the leader of its own process group on Unix, so [`kill_tree`] and
|
||||
/// [`terminate_tree`] reach what it starts in turn (`gh` → `git`, `npm` → `node`, `mvnw` →
|
||||
/// the JVM). A no-op elsewhere: on Windows the tree is found from the child's process id.
|
||||
@@ -285,6 +343,190 @@ fn taskkill_tree_of(pid: u32) {
|
||||
windows_tree::wait_all(&started, TREE_EXIT_WAIT);
|
||||
}
|
||||
|
||||
/// The registry environment behind [`registry_env_changes`], read with
|
||||
/// `CreateEnvironmentBlock` as Explorer does for the programs it starts after a
|
||||
/// `WM_SETTINGCHANGE`. It is read again only after `HKCU\Environment` or the machine's
|
||||
/// `Environment` key reports a change, so spawning a child costs two event polls.
|
||||
#[cfg(windows)]
|
||||
mod registry_env {
|
||||
use std::ffi::OsString;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
|
||||
use std::sync::Mutex;
|
||||
use windows_sys::Win32::Foundation::{ERROR_SUCCESS, HANDLE, WAIT_OBJECT_0};
|
||||
use windows_sys::Win32::Security::{TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_QUERY};
|
||||
use windows_sys::Win32::System::Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock};
|
||||
use windows_sys::Win32::System::Registry::{
|
||||
HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_NOTIFY, REG_NOTIFY_CHANGE_LAST_SET, REG_NOTIFY_CHANGE_NAME,
|
||||
REG_NOTIFY_THREAD_AGNOSTIC, RegCloseKey, RegNotifyChangeKeyValue, RegOpenKeyExW,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
CreateEventW, GetCurrentProcess, OpenProcessToken, ResetEvent, WaitForSingleObject,
|
||||
};
|
||||
|
||||
type Vars = Vec<(OsString, OsString)>;
|
||||
|
||||
/// An open registry key and the event its next change signals.
|
||||
struct Watch {
|
||||
key: HKEY,
|
||||
event: OwnedHandle,
|
||||
}
|
||||
|
||||
// SAFETY: a registry key handle is a kernel handle, usable from any thread.
|
||||
unsafe impl Send for Watch {}
|
||||
|
||||
impl Watch {
|
||||
fn new(root: HKEY, path: &str) -> Option<Self> {
|
||||
let path: Vec<u16> = path.encode_utf16().chain(Some(0)).collect();
|
||||
let mut key: HKEY = std::ptr::null_mut();
|
||||
// SAFETY: `path` is NUL-terminated; `key` receives a handle the watch owns.
|
||||
if unsafe { RegOpenKeyExW(root, path.as_ptr(), 0, KEY_NOTIFY, &mut key) } != ERROR_SUCCESS {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: plain call; a non-null result is a manual-reset event handle owned here.
|
||||
let event = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) };
|
||||
if event.is_null() {
|
||||
// SAFETY: `key` was opened above and is closed once.
|
||||
unsafe { RegCloseKey(key) };
|
||||
return None;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
let watch = Watch { key, event: unsafe { OwnedHandle::from_raw_handle(event) } };
|
||||
watch.arm().then_some(watch)
|
||||
}
|
||||
|
||||
/// Asks to be told of the key's next change; `false` when it cannot be watched.
|
||||
fn arm(&self) -> bool {
|
||||
let filter = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_THREAD_AGNOSTIC;
|
||||
// SAFETY: both handles are owned by the watch and open.
|
||||
let status = unsafe { RegNotifyChangeKeyValue(self.key, 0, filter, self.event.as_raw_handle(), 1) };
|
||||
status == ERROR_SUCCESS
|
||||
}
|
||||
|
||||
/// Whether the key changed since the last call; re-arms the watch when it did.
|
||||
fn changed(&self) -> bool {
|
||||
let event: HANDLE = self.event.as_raw_handle();
|
||||
// SAFETY: an event handle owned by the watch.
|
||||
if unsafe { WaitForSingleObject(event, 0) } != WAIT_OBJECT_0 {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
unsafe { ResetEvent(event) };
|
||||
self.arm();
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Watch {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the key was opened by `Watch::new` and is closed once.
|
||||
unsafe { RegCloseKey(self.key) };
|
||||
}
|
||||
}
|
||||
|
||||
struct State {
|
||||
startup: Vars,
|
||||
current: Vars,
|
||||
watches: Vec<Watch>,
|
||||
}
|
||||
|
||||
static STATE: Mutex<Option<State>> = Mutex::new(None);
|
||||
|
||||
pub(super) fn record() {
|
||||
let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if state.is_none() {
|
||||
*state = Some(start());
|
||||
}
|
||||
}
|
||||
|
||||
fn start() -> State {
|
||||
// Watch before reading: a change in between is then read again, not missed.
|
||||
let watches = [
|
||||
(HKEY_CURRENT_USER, "Environment"),
|
||||
(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(root, path)| Watch::new(root, path))
|
||||
.collect();
|
||||
let startup = read().unwrap_or_default();
|
||||
State { current: startup.clone(), startup, watches }
|
||||
}
|
||||
|
||||
pub(super) fn changes() -> Vec<(OsString, Option<OsString>)> {
|
||||
let mut guard = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let state = guard.get_or_insert_with(start);
|
||||
// Poll every watch: each one that fired must be re-armed.
|
||||
let changed = state.watches.iter().fold(false, |any, watch| watch.changed() | any);
|
||||
if changed && let Some(fresh) = read() {
|
||||
state.current = fresh;
|
||||
}
|
||||
if state.current == state.startup {
|
||||
return Vec::new();
|
||||
}
|
||||
super::registry_diff(&|k| std::env::var_os(k), &state.startup, &state.current)
|
||||
}
|
||||
|
||||
/// The environment a program Explorer starts now would get; `None` when it cannot be read.
|
||||
pub(super) fn read() -> Option<Vars> {
|
||||
let mut token: HANDLE = std::ptr::null_mut();
|
||||
let access = TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE;
|
||||
// SAFETY: this process's pseudo-handle; `token` receives a handle owned here.
|
||||
if unsafe { OpenProcessToken(GetCurrentProcess(), access, &mut token) } == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
let token = unsafe { OwnedHandle::from_raw_handle(token) };
|
||||
let mut block: *mut core::ffi::c_void = std::ptr::null_mut();
|
||||
// SAFETY: an open token; `block` receives a block destroyed below.
|
||||
if unsafe { CreateEnvironmentBlock(&mut block, token.as_raw_handle(), 0) } == 0 || block.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the block holds `NAME=VALUE` entries, each NUL-terminated, then a final NUL.
|
||||
let vars = unsafe { parse_block(block as *const u16) };
|
||||
// SAFETY: the block was created above and is destroyed once.
|
||||
unsafe { DestroyEnvironmentBlock(block) };
|
||||
Some(vars)
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `block` points to UTF-16 entries, each NUL-terminated, ended by an empty one.
|
||||
unsafe fn parse_block(block: *const u16) -> Vars {
|
||||
let mut vars = Vars::new();
|
||||
let mut at = block;
|
||||
loop {
|
||||
let mut len = 0;
|
||||
// SAFETY: the caller guarantees the terminating NULs.
|
||||
while unsafe { *at.add(len) } != 0 {
|
||||
len += 1;
|
||||
}
|
||||
if len == 0 {
|
||||
return vars;
|
||||
}
|
||||
// SAFETY: the `len` units before the NUL were just read.
|
||||
let entry = unsafe { std::slice::from_raw_parts(at, len) };
|
||||
// Per-drive directories (`=C:=C:\dir`) have an empty name: skip them.
|
||||
if let Some(eq) = entry.iter().skip(1).position(|&c| c == u16::from(b'=')) {
|
||||
let eq = eq + 1;
|
||||
vars.push((OsString::from_wide(&entry[..eq]), OsString::from_wide(&entry[eq + 1..])));
|
||||
}
|
||||
// SAFETY: the entry's NUL is followed by the next entry or the final NUL.
|
||||
at = unsafe { at.add(len + 1) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn reads_this_users_environment() {
|
||||
let vars = super::read().expect("environment block");
|
||||
let get = |k: &str| vars.iter().find(|(n, _)| n.eq_ignore_ascii_case(k)).map(|(_, v)| v.clone());
|
||||
assert!(get("SystemRoot").is_some_and(|v| !v.is_empty()), "{vars:?}");
|
||||
assert!(get("Path").is_some_and(|v| !v.is_empty()), "{vars:?}");
|
||||
assert!(vars.iter().all(|(k, _)| !k.is_empty() && !k.to_string_lossy().contains('=')));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows_tree {
|
||||
use std::collections::HashSet;
|
||||
@@ -676,7 +918,7 @@ pub fn host_var_os_in(dir: &Path, key: impl AsRef<OsStr>) -> Option<OsString> {
|
||||
}
|
||||
|
||||
fn host_var_os_for(dir: Option<&Path>, key: &OsStr) -> Option<OsString> {
|
||||
match child_env_changes(dir).into_iter().find(|(k, _)| k == key) {
|
||||
match child_env_changes(dir).into_iter().find(|(k, _)| same_key(k, key)) {
|
||||
Some((_, fixed)) => fixed,
|
||||
None => std::env::var_os(key).or_else(|| shell_env_for(dir).find(|(k, _)| k == key).map(|(_, v)| v)),
|
||||
}
|
||||
@@ -688,7 +930,7 @@ fn apply_changes(
|
||||
changes: &[(OsString, Option<OsString>)],
|
||||
) -> Vec<(OsString, OsString)> {
|
||||
for (key, value) in changes {
|
||||
let at = vars.iter().position(|(k, _)| k == key);
|
||||
let at = vars.iter().position(|(k, _)| same_key(k, key));
|
||||
match (at, value) {
|
||||
(Some(i), Some(v)) => vars[i].1 = v.clone(),
|
||||
(Some(i), None) => {
|
||||
@@ -701,25 +943,126 @@ fn apply_changes(
|
||||
vars
|
||||
}
|
||||
|
||||
/// The AppImage fixes, the overlay, the manual proxy's, then those of the project holding
|
||||
/// `dir` (a later one wins); one entry per name.
|
||||
/// The registry's changes (Windows), the AppImage fixes, the overlay, the manual proxy's,
|
||||
/// then those of the project holding `dir` (a later one wins); one entry per name.
|
||||
fn child_env_changes(dir: Option<&Path>) -> Vec<(OsString, Option<OsString>)> {
|
||||
let mut changes = appimage_fixes();
|
||||
let mut changes = registry_env_changes();
|
||||
changes.extend(appimage_fixes());
|
||||
let overlay = env_overlay();
|
||||
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| o == k));
|
||||
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| same_key(o, k)));
|
||||
changes.extend(overlay.iter().cloned());
|
||||
// A manual HTTP proxy reaches tools that read `HTTP_PROXY` (language servers, git, curl).
|
||||
let proxy = crate::proxy_settings::proxy().child_env();
|
||||
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| p == k));
|
||||
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| same_key(p, k)));
|
||||
changes.extend(proxy);
|
||||
if let Some(dir) = dir {
|
||||
let project = crate::project_env::for_dir(dir);
|
||||
changes.retain(|(k, _)| !project.iter().any(|(p, _)| p == k));
|
||||
changes.retain(|(k, _)| !project.iter().any(|(p, _)| same_key(p, k)));
|
||||
changes.extend(project.iter().cloned());
|
||||
}
|
||||
changes
|
||||
}
|
||||
|
||||
/// Whether two variable names are the same variable: Windows ignores case (`Path` is `PATH`).
|
||||
fn same_key(a: &OsStr, b: &OsStr) -> bool {
|
||||
if cfg!(windows) { a.eq_ignore_ascii_case(b) } else { a == b }
|
||||
}
|
||||
|
||||
/// What changed in the environment Windows gives new programs (the registry's machine and
|
||||
/// user variables) since this process started. A program installed meanwhile (Node.js, a
|
||||
/// JDK) adds its folder to `Path`; a child of the IDE must find it, as a program started
|
||||
/// from Explorer would, without restarting the IDE. Empty elsewhere.
|
||||
fn registry_env_changes() -> Vec<(OsString, Option<OsString>)> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
registry_env::changes()
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Remembers the registry environment this process starts with, so that later changes reach
|
||||
/// new children. Call at startup (otherwise the first child spawn records it). Does nothing
|
||||
/// outside Windows.
|
||||
pub fn record_startup_registry_env() {
|
||||
#[cfg(windows)]
|
||||
registry_env::record();
|
||||
}
|
||||
|
||||
/// The entry of a `PATH`-like list as compared: without a trailing separator, and on
|
||||
/// Windows without case.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn path_entry_key(dir: &Path) -> String {
|
||||
let text = dir.to_string_lossy();
|
||||
let text = text.trim_end_matches(['\\', '/']);
|
||||
if cfg!(windows) { text.to_ascii_lowercase() } else { text.to_owned() }
|
||||
}
|
||||
|
||||
/// `old` → `fresh` applied to this process's `PATH`-like list `process`: entries that
|
||||
/// `fresh` dropped are removed and those it added are appended, so what the IDE put on
|
||||
/// `PATH` itself (managed tools, the user's `Path`) stays where it is.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn rebase_path_list(process: &OsStr, old: &OsStr, fresh: &OsStr) -> OsString {
|
||||
let entries = |list: &OsStr| -> Vec<std::path::PathBuf> {
|
||||
std::env::split_paths(list).filter(|d| !d.as_os_str().is_empty()).collect()
|
||||
};
|
||||
let old: Vec<String> = entries(old).iter().map(|d| path_entry_key(d)).collect();
|
||||
let fresh = entries(fresh);
|
||||
let fresh_keys: Vec<String> = fresh.iter().map(|d| path_entry_key(d)).collect();
|
||||
let mut out: Vec<std::path::PathBuf> = entries(process)
|
||||
.into_iter()
|
||||
.filter(|d| {
|
||||
let key = path_entry_key(d);
|
||||
!old.contains(&key) || fresh_keys.contains(&key)
|
||||
})
|
||||
.collect();
|
||||
for (dir, key) in fresh.into_iter().zip(fresh_keys) {
|
||||
if !old.contains(&key) && !out.iter().any(|d| path_entry_key(d) == key) {
|
||||
out.push(dir);
|
||||
}
|
||||
}
|
||||
std::env::join_paths(out).unwrap_or_else(|_| process.to_owned())
|
||||
}
|
||||
|
||||
/// The changes that bring this process's environment (`process`) from the registry
|
||||
/// environment it started with (`old`) to the current one (`fresh`): new and changed
|
||||
/// variables; removed ones while this process still has the value it started with; and
|
||||
/// `PATH` rebased ([`rebase_path_list`]).
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn registry_diff(
|
||||
process: &dyn Fn(&OsStr) -> Option<OsString>,
|
||||
old: &[(OsString, OsString)],
|
||||
fresh: &[(OsString, OsString)],
|
||||
) -> Vec<(OsString, Option<OsString>)> {
|
||||
let get =
|
||||
|vars: &[(OsString, OsString)], k: &OsStr| vars.iter().find(|(n, _)| same_key(n, k)).map(|(_, v)| v.clone());
|
||||
let mut out = Vec::new();
|
||||
for (key, value) in fresh {
|
||||
let before = get(old, key);
|
||||
if before.as_ref() == Some(value) {
|
||||
continue;
|
||||
}
|
||||
let current = process(key);
|
||||
if key.eq_ignore_ascii_case("PATH") {
|
||||
let current = current.unwrap_or_default();
|
||||
let rebased = rebase_path_list(¤t, before.as_deref().unwrap_or_default(), value);
|
||||
if rebased != current {
|
||||
out.push((key.clone(), Some(rebased)));
|
||||
}
|
||||
} else if current.as_ref() != Some(value) {
|
||||
out.push((key.clone(), Some(value.clone())));
|
||||
}
|
||||
}
|
||||
for (key, value) in old {
|
||||
if get(fresh, key).is_none() && process(key).as_ref() == Some(value) {
|
||||
out.push((key.clone(), None));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Read on every call, not cached: startup rewrites `PATH` (login shell, managed tools).
|
||||
fn appimage_fixes() -> Vec<(OsString, Option<OsString>)> {
|
||||
if !cfg!(target_os = "linux") || std::env::var_os("APPDIR").is_none() {
|
||||
@@ -1010,6 +1353,26 @@ mod tests {
|
||||
assert_eq!(session, pid, "the child leads its own session");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compacts_a_path_too_long_for_cmd() {
|
||||
let sep = if cfg!(windows) { ";" } else { ":" };
|
||||
let join = |dirs: &[&str]| OsString::from(dirs.join(sep));
|
||||
let long = |name: &str| format!("/tools/{}/{name}", "x".repeat(40));
|
||||
let (a, b, c, gone) = (long("a"), long("b"), long("c"), long("gone"));
|
||||
let present = |d: &Path| !d.ends_with("gone");
|
||||
let never = |_: &Path| None;
|
||||
// Fits already: left alone.
|
||||
assert_eq!(compact_path_list(&join(&[&a, &b]), 200, present, never), None);
|
||||
// Later duplicates and missing directories go, the order stays.
|
||||
let path = join(&[&a, &gone, &b, &a, &format!("{b}/"), "", &c]);
|
||||
assert_eq!(compact_path_list(&path, 160, present, never), Some(join(&[&a, &b, &c])));
|
||||
// Still too long: the longest directories take their short form until it fits.
|
||||
let shorten = |d: &Path| Some(std::path::PathBuf::from(format!("/S/{}", d.file_name()?.to_string_lossy())));
|
||||
let path = join(&[&a, &format!("{b}-longer"), &c]);
|
||||
assert_eq!(compact_path_list(&path, 120, present, shorten), Some(join(&[&a, "/S/b-longer", &c])));
|
||||
assert_eq!(compact_path_list(&path, 60, present, shorten), Some(join(&["/S/a", "/S/b-longer", "/S/c"])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_alive_tells_live_from_dead_pids() {
|
||||
assert!(process_alive(std::process::id()));
|
||||
@@ -1459,6 +1822,118 @@ mod tests {
|
||||
assert!(fixes(&[("APPDIR", "/"), ("PATH", "/usr/bin")]).is_empty());
|
||||
}
|
||||
|
||||
fn os(vars: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
|
||||
vars.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect()
|
||||
}
|
||||
|
||||
fn list(dirs: &[&str]) -> OsString {
|
||||
std::env::join_paths(dirs).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_path_changes_keep_what_the_ide_added_to_path() {
|
||||
// The IDE put `tools` first at startup; meanwhile an installer appended `node`
|
||||
// and an uninstaller removed `old`.
|
||||
let process = list(&["tools", "sys", "old", "user"]);
|
||||
let rebased = rebase_path_list(&process, &list(&["sys", "old", "user"]), &list(&["sys", "user", "node"]));
|
||||
assert_eq!(rebased, list(&["tools", "sys", "user", "node"]));
|
||||
// Nothing to add when the entry is already there (a trailing separator aside).
|
||||
let sep = std::path::MAIN_SEPARATOR.to_string();
|
||||
let rebased =
|
||||
rebase_path_list(&list(&["sys", "node"]), &list(&["sys"]), &list(&["sys", &format!("node{sep}")]));
|
||||
assert_eq!(rebased, list(&["sys", "node"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_changes_are_new_changed_and_removed_variables() {
|
||||
let old = os(&[("KEEP", "1"), ("CHANGED", "a"), ("GONE", "x"), ("OVERRIDDEN", "y"), ("PATH", "sys")]);
|
||||
let fresh = os(&[("KEEP", "1"), ("CHANGED", "b"), ("NEW", "n"), ("PATH", "sys")]);
|
||||
// The IDE was launched with `OVERRIDDEN` set otherwise: that value stays.
|
||||
let process = |k: &OsStr| match k.to_str()?.to_ascii_uppercase().as_str() {
|
||||
"KEEP" => Some("1".into()),
|
||||
"CHANGED" => Some("a".into()),
|
||||
"GONE" => Some("x".into()),
|
||||
"OVERRIDDEN" => Some("launcher".into()),
|
||||
"PATH" => Some(list(&["tools", "sys"])),
|
||||
_ => None,
|
||||
};
|
||||
let got = registry_diff(&process, &old, &fresh);
|
||||
let want: Vec<(OsString, Option<OsString>)> =
|
||||
vec![("CHANGED".into(), Some("b".into())), ("NEW".into(), Some("n".into())), ("GONE".into(), None)];
|
||||
assert_eq!(got, want);
|
||||
assert!(registry_diff(&process, &old, &old).is_empty());
|
||||
// A `Path` change reaches the process `PATH` (another case of the same variable).
|
||||
let got = registry_diff(&process, &os(&[("Path", "sys")]), &os(&[("Path", "sys;node")]));
|
||||
if cfg!(windows) {
|
||||
assert_eq!(got, vec![("Path".into(), Some(list(&["tools", "sys", "node"])))]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_match_variable_names_as_the_platform_does() {
|
||||
let vars = os(&[("Path", "a")]);
|
||||
let got = apply_changes(vars, &[("PATH".into(), Some("b".into()))]);
|
||||
if cfg!(windows) {
|
||||
assert_eq!(got, os(&[("Path", "b")]));
|
||||
} else {
|
||||
assert_eq!(got, os(&[("Path", "a"), ("PATH", "b")]));
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable set in `HKCU\Environment` after startup (as an installer or the System
|
||||
/// Properties dialog does) reaches the next child without a restart.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_user_variable_set_after_startup_reaches_new_children() {
|
||||
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
||||
use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, REG_SZ, RegDeleteKeyValueW, RegSetKeyValueW};
|
||||
|
||||
fn wide(s: &str) -> Vec<u16> {
|
||||
s.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
struct Cleanup(Vec<u16>);
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: NUL-terminated names of a value this test created.
|
||||
unsafe { RegDeleteKeyValueW(HKEY_CURRENT_USER, wide("Environment").as_ptr(), self.0.as_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
record_startup_registry_env();
|
||||
let name = format!("OPENIDEA_REGISTRY_ENV_TEST_{}", std::process::id());
|
||||
let value = wide("installed");
|
||||
let wide_name = wide(&name);
|
||||
// SAFETY: NUL-terminated names; the data is `value`'s bytes, NUL included.
|
||||
let status = unsafe {
|
||||
RegSetKeyValueW(
|
||||
HKEY_CURRENT_USER,
|
||||
wide("Environment").as_ptr(),
|
||||
wide_name.as_ptr(),
|
||||
REG_SZ,
|
||||
value.as_ptr().cast(),
|
||||
(value.len() * 2) as u32,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, ERROR_SUCCESS);
|
||||
let cleanup = Cleanup(wide_name);
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
let seen = loop {
|
||||
let seen = host_var_os(&name);
|
||||
if seen.is_some() || std::time::Instant::now() >= deadline {
|
||||
break seen;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
assert_eq!(seen.as_deref(), Some(OsStr::new("installed")));
|
||||
assert!(spawnable_host_vars().any(|(k, v)| k == name.as_str() && v == "installed"));
|
||||
drop(cleanup);
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while host_var_os(&name).is_some() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(host_var_os(&name), None, "a removed variable is gone again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_env_keeps_what_the_call_site_set() {
|
||||
let mut cmd = Command::new("true");
|
||||
|
||||
@@ -227,6 +227,7 @@ pub struct RunTarget {
|
||||
pub python: String,
|
||||
pub node: String,
|
||||
pub java: String,
|
||||
pub php: String,
|
||||
/// Id of a Docker connection of the Services tool window (Docker, Compose);
|
||||
/// empty = the CLI's own daemon.
|
||||
pub docker_connection: String,
|
||||
|
||||
@@ -68,6 +68,8 @@ pub struct Settings {
|
||||
/// Build, Execution, Deployment › Run Targets.
|
||||
pub run_targets: Vec<RunTarget>,
|
||||
pub cmake: CMakeSettings,
|
||||
/// Build, Execution, Deployment › Toolchains; the first is the default.
|
||||
pub toolchains: Vec<Toolchain>,
|
||||
/// Settings › Agents.
|
||||
pub agents: AgentSettings,
|
||||
/// Agents › MCP Server (global only).
|
||||
@@ -160,6 +162,9 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, AgentMcpServer>)]
|
||||
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
|
||||
/// Custom MCP Registry base URL (`agents.mcpRegistryUrl`); empty = GitHub MCP Registry.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub mcp_registry_url: String,
|
||||
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
|
||||
/// files on disk are never modified.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
@@ -209,6 +214,7 @@ impl Default for AgentSettings {
|
||||
confirm_terminate_on_close: true,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
mcp_registry_url: String::new(),
|
||||
skills: BTreeMap::new(),
|
||||
memory: AgentMemorySettings::default(),
|
||||
plugins: AgentPluginSettings::default(),
|
||||
@@ -251,6 +257,14 @@ pub struct AgentMcpServer {
|
||||
/// empty means enabled for all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
/// Canonical MCP registry server identifier (e.g. `microsoft/playwright-mcp`) when installed from a registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL (e.g. `https://api.mcp.github.com`) when installed from a registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for AgentMcpServer {
|
||||
@@ -264,6 +278,8 @@ impl Default for AgentMcpServer {
|
||||
url: None,
|
||||
headers: BTreeMap::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -296,20 +312,7 @@ impl Default for AgentSkillPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
/// How an agent instruction, rule, or memory entry may load (`[agents.memory.entries.<id>] mode = …`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentMemoryMode {
|
||||
/// Load according to its native rules (always for instructions, matching files for path-scoped rules).
|
||||
#[default]
|
||||
Auto,
|
||||
/// Force-load into every session regardless of path scoping.
|
||||
Always,
|
||||
/// Exclude from sessions where the harness supports it.
|
||||
Off,
|
||||
}
|
||||
|
||||
/// How an agent's automatic cross-session memory runs (`[agents.memory] autoMemory = …`).
|
||||
/// How an agent's automatic cross-session memory runs (`[agents.memory.providers.<id>]`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutoMemoryMode {
|
||||
@@ -324,24 +327,6 @@ pub enum AutoMemoryMode {
|
||||
Off,
|
||||
}
|
||||
|
||||
/// One memory or instruction entry's policy in Settings › Agents › Memory.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemoryEntryPolicy {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentMemoryMode)]
|
||||
pub mode: AgentMemoryMode,
|
||||
/// Agent provider ids this entry applies to; empty means all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for AgentMemoryEntryPolicy {
|
||||
fn default() -> Self {
|
||||
Self { mode: AgentMemoryMode::Auto, agents: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-provider auto-memory policy (`[agents.memory.providers.<id>]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -355,18 +340,10 @@ pub struct AgentProviderMemoryPolicy {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentMemorySettings {
|
||||
/// Default cross-session auto-memory policy across agents.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutoMemoryMode)]
|
||||
pub auto_memory: AutoMemoryMode,
|
||||
/// Optional per-provider auto-memory overrides (`[agents.memory.providers.<provider>]`).
|
||||
/// Per-provider cross-session auto-memory overrides (`[agents.memory.providers.<provider>]`).
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentProviderMemoryPolicy>)]
|
||||
pub providers: BTreeMap<String, AgentProviderMemoryPolicy>,
|
||||
/// Per-entry modes (`[agents.memory.entries.<id>]`).
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentMemoryEntryPolicy>)]
|
||||
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
}
|
||||
|
||||
/// One agent plugin bundle's policy in Settings › Agents › Plugins
|
||||
@@ -703,6 +680,8 @@ pub struct ToolDownloadSettings {
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
/// The managed Vue Language Server release. Empty selects it from the project's Vue dependency.
|
||||
pub vue_language_server_version: String,
|
||||
}
|
||||
|
||||
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
|
||||
@@ -750,9 +729,42 @@ impl Default for SettingsSyncSettings {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CMakeSettings {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
/// Serialized as `null` when absent, so `cmake.profiles` stays a known settings key.
|
||||
#[specta(optional)]
|
||||
pub profiles: Option<Vec<CMakeProfile>>,
|
||||
/// `true` ignores `CMakePresets.json` / `CMakeUserPresets.json`; otherwise every visible
|
||||
/// configure preset whose condition holds is listed after the explicit profiles.
|
||||
pub ignore_presets: bool,
|
||||
/// Configure presets (by name) enabled as profiles. As in CLion, a preset is listed but
|
||||
/// disabled until enabled here.
|
||||
pub enabled_presets: Vec<String>,
|
||||
/// The profile (by name) that build, run and debug use, as CLion's toolbar switcher;
|
||||
/// empty or unknown = the first enabled one.
|
||||
pub active_profile: String,
|
||||
}
|
||||
|
||||
/// The presets a profile made from `CMakePresets.json` runs with.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CMakePresetRef {
|
||||
pub configure: String,
|
||||
/// The first build preset of `configure`, used by `cmake --build --preset`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub build: Option<String>,
|
||||
/// The first test preset of `configure`, used by `ctest --preset`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub test: Option<String>,
|
||||
/// Cache variables the resolved preset sets itself, read when presets are loaded (never
|
||||
/// saved): a toolchain does not override them.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub cache_variables: Vec<String>,
|
||||
/// The preset names a toolchain file, which picks the compilers.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub toolchain_file: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -766,6 +778,23 @@ pub struct CMakeProfile {
|
||||
pub build_dir: String,
|
||||
pub build_args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// `false` keeps the profile listed but unused (CLion's "Enable profile").
|
||||
pub enabled: bool,
|
||||
/// Toolchain name (Settings › Toolchains); empty = the default (first) toolchain.
|
||||
pub toolchain: String,
|
||||
/// Set only on the profiles made from presets: configure with `cmake --preset`, and the
|
||||
/// generator and cache variables come from the preset.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub preset: Option<CMakePresetRef>,
|
||||
/// Resolved from the toolchain when profiles are put to use (never saved): the `cmake`
|
||||
/// to run (`ctest` next to it) and the debugger to prefer.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub cmake_program: Option<std::path::PathBuf>,
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub debugger: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for CMakeProfile {
|
||||
@@ -778,10 +807,50 @@ impl Default for CMakeProfile {
|
||||
build_dir: String::new(),
|
||||
build_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
enabled: true,
|
||||
toolchain: String::new(),
|
||||
preset: None,
|
||||
cmake_program: None,
|
||||
debugger: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ToolchainKind {
|
||||
/// Tools from the chosen paths, else from `PATH`.
|
||||
#[default]
|
||||
System,
|
||||
/// A MinGW / MSYS2 directory: its `bin` goes first on `PATH`, with gcc, g++,
|
||||
/// mingw32-make and gdb from there.
|
||||
#[serde(rename = "mingw")]
|
||||
MinGw,
|
||||
/// A Visual Studio installation: configure, build and run get the environment its
|
||||
/// `vcvarsall.bat` sets up (Windows only).
|
||||
#[serde(rename = "visualStudio")]
|
||||
VisualStudio,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are
|
||||
/// detected from the toolchain installation when it has them, else from `PATH`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Toolchain {
|
||||
pub name: String,
|
||||
pub kind: ToolchainKind,
|
||||
/// The MinGW directory (the one holding `bin`), or the Visual Studio installation directory.
|
||||
pub path: String,
|
||||
/// `vcvarsall.bat`'s architecture argument (`x64`, `x86`, `x64_arm64` …); empty is the host's.
|
||||
pub arch: String,
|
||||
pub cmake: String,
|
||||
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make, nmake or ninja.
|
||||
pub build_tool: String,
|
||||
pub c_compiler: String,
|
||||
pub cxx_compiler: String,
|
||||
pub debugger: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ToolSettings {
|
||||
@@ -893,6 +962,7 @@ impl Default for Settings {
|
||||
deployment: DeploymentSettings::default(),
|
||||
run_targets: Vec::new(),
|
||||
cmake: CMakeSettings::default(),
|
||||
toolchains: Vec::new(),
|
||||
agents: AgentSettings::default(),
|
||||
mcp_server: McpServerSettings::default(),
|
||||
agent_security: AgentSecuritySettings::default(),
|
||||
@@ -984,6 +1054,8 @@ pub struct GeneralSettings {
|
||||
pub close_tabs_with_window: bool,
|
||||
/// Where Open… puts a project while one is open: `ask` | `new` | `same` | `attach`.
|
||||
pub open_project_in: String,
|
||||
/// What closing a remote development window does with its backend: `ask` | `keep` | `stop`.
|
||||
pub close_remote_window: String,
|
||||
/// Initial folder of the Open / Clone dialogs; empty = the OS default.
|
||||
pub default_project_directory: String,
|
||||
/// Save all files after `idle_seconds` without input.
|
||||
@@ -997,6 +1069,8 @@ pub struct GeneralSettings {
|
||||
pub project_name: String,
|
||||
/// Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`.
|
||||
pub update_source: String,
|
||||
/// `stable` | `nightly`; defaults to the running build's channel.
|
||||
pub update_channel: String,
|
||||
pub auto_check_updates: bool,
|
||||
/// System Settings › Updates: open the What's New page after the app starts a new version.
|
||||
pub show_whats_new_after_update: bool,
|
||||
@@ -1012,6 +1086,7 @@ impl Default for GeneralSettings {
|
||||
close_without_welcome: false,
|
||||
close_tabs_with_window: false,
|
||||
open_project_in: "ask".into(),
|
||||
close_remote_window: "ask".into(),
|
||||
default_project_directory: String::new(),
|
||||
save_on_idle: false,
|
||||
idle_seconds: 15,
|
||||
@@ -1019,6 +1094,7 @@ impl Default for GeneralSettings {
|
||||
power_save_mode: false,
|
||||
project_name: String::new(),
|
||||
update_source: "auto".into(),
|
||||
update_channel: crate::updates::UpdateChannel::of_version(env!("CARGO_PKG_VERSION")).as_str().into(),
|
||||
auto_check_updates: true,
|
||||
show_whats_new_after_update: true,
|
||||
last_run_version: String::new(),
|
||||
@@ -1258,6 +1334,7 @@ pub struct FileIconThemeOptions {
|
||||
pub hollow_folders: bool,
|
||||
pub hide_ui_icons: bool,
|
||||
pub hide_psi_icons: bool,
|
||||
pub file_icons_for_code: bool,
|
||||
pub monochrome: Option<String>,
|
||||
pub saturation: Option<u8>,
|
||||
pub opacity: Option<u8>,
|
||||
@@ -1341,6 +1418,10 @@ pub struct CustomColorScheme {
|
||||
pub struct EditorSettings {
|
||||
pub font_family: String,
|
||||
pub font_size: f32,
|
||||
/// Largest document (in MiB) eligible for syntax analysis and language-server features.
|
||||
#[serde(deserialize_with = "code_insight_limit_mb")]
|
||||
#[specta(type = u8)]
|
||||
pub max_code_insight_file_size_mb: u8,
|
||||
pub line_height: f32,
|
||||
pub tab_size: u32,
|
||||
pub insert_spaces: bool,
|
||||
@@ -1358,6 +1439,9 @@ pub struct EditorSettings {
|
||||
/// Color Scheme › Language Defaults › Semantic highlighting: local variables and
|
||||
/// parameters get a colour derived from their name (IDEA's rainbow identifiers).
|
||||
pub semantic_highlighting: bool,
|
||||
/// Color Scheme › Language Defaults › Dim inactive preprocessor code: grey out the
|
||||
/// `#if`/`#ifdef` branches clangd reports as inactive (C and C++).
|
||||
pub dim_inactive_code: bool,
|
||||
/// Docstring markup format whose tags and keywords the Python editor highlights
|
||||
/// (`plain`, `rest`, `epytext`, `google`, `numpy`).
|
||||
pub docstring_format: String,
|
||||
@@ -1394,11 +1478,23 @@ pub struct EditorSettings {
|
||||
pub encodings: EncodingSettings,
|
||||
}
|
||||
|
||||
pub const DEFAULT_CODE_INSIGHT_LIMIT_MB: u8 = 5;
|
||||
pub const MAX_CODE_INSIGHT_LIMIT_MB: u8 = 50;
|
||||
|
||||
fn code_insight_limit_mb<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u8, D::Error> {
|
||||
Ok(serde_json::Value::deserialize(d)?
|
||||
.as_u64()
|
||||
.and_then(|n| u8::try_from(n).ok())
|
||||
.filter(|n| (1..=MAX_CODE_INSIGHT_LIMIT_MB).contains(n))
|
||||
.unwrap_or(DEFAULT_CODE_INSIGHT_LIMIT_MB))
|
||||
}
|
||||
|
||||
impl Default for EditorSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
font_family: "JetBrains Mono".into(),
|
||||
font_size: 13.0,
|
||||
max_code_insight_file_size_mb: DEFAULT_CODE_INSIGHT_LIMIT_MB,
|
||||
line_height: 22.0,
|
||||
tab_size: 4,
|
||||
insert_spaces: true,
|
||||
@@ -1411,6 +1507,7 @@ impl Default for EditorSettings {
|
||||
color_overrides: BTreeMap::new(),
|
||||
custom_schemes: BTreeMap::new(),
|
||||
semantic_highlighting: false,
|
||||
dim_inactive_code: true,
|
||||
docstring_format: "rest".into(),
|
||||
rainbow_brackets: false,
|
||||
rainbow_bracket_kinds: RainbowBracketKinds::default(),
|
||||
@@ -1610,6 +1707,8 @@ pub struct MarkdownSettings {
|
||||
pub preview_layout: MarkdownPreviewLayout,
|
||||
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
|
||||
pub preview_font_size: Option<u32>,
|
||||
/// How single newlines inside a paragraph are rendered in the Markdown preview.
|
||||
pub soft_line_breaks: MarkdownSoftLineBreaks,
|
||||
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
|
||||
/// trusted projects, or stay in static safe mode.
|
||||
pub mdx_execution: MdxExecutionPolicy,
|
||||
@@ -1625,6 +1724,7 @@ impl Default for MarkdownSettings {
|
||||
Self {
|
||||
preview_layout: MarkdownPreviewLayout::default(),
|
||||
preview_font_size: None,
|
||||
soft_line_breaks: MarkdownSoftLineBreaks::default(),
|
||||
mdx_execution: MdxExecutionPolicy::default(),
|
||||
run_commands: true,
|
||||
command_directory: None,
|
||||
@@ -1632,6 +1732,16 @@ impl Default for MarkdownSettings {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MarkdownSoftLineBreaks {
|
||||
/// Standard Markdown: a single newline collapses into a space.
|
||||
#[default]
|
||||
Standard,
|
||||
/// Render each single newline inside a paragraph as a line break (`<br>`).
|
||||
Break,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MdxExecutionPolicy {
|
||||
@@ -1772,8 +1882,9 @@ pub struct PythonSettings {
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (py-spy where it
|
||||
/// is installed and samples without root, else cProfile), `cprofile` or `py-spy`.
|
||||
/// What Profile runs Python under (Settings › Python › Profiler): `auto` (yappi when the
|
||||
/// interpreter can import it, else py-spy where it is installed and samples without root, else
|
||||
/// cProfile), `cprofile`, `py-spy` or `yappi`.
|
||||
pub profiler: String,
|
||||
/// Show matplotlib figures of Python runs in the Plots tool window (the IDE sets `MPLBACKEND`
|
||||
/// unless the run sets it); off: matplotlib's own window.
|
||||
@@ -2049,6 +2160,8 @@ pub struct MavenSettings {
|
||||
pub active_profiles: String,
|
||||
/// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ).
|
||||
pub delegate_build: bool,
|
||||
/// Maven goals (`groupId:artifactId:goal`) the IDE may skip in compile phases. Empty by default.
|
||||
pub ignored_compile_goals: Vec<String>,
|
||||
/// Download `-sources.jar` of dependencies when the Java language server imports the
|
||||
/// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
|
||||
/// from a library class's Download Sources banner.
|
||||
@@ -2455,12 +2568,16 @@ mod tests {
|
||||
let old: Settings = serde_json::from_str(r#"{"languages":{"markdown":{"previewFontSize":16}}}"#).unwrap();
|
||||
assert_eq!(old.languages.markdown.preview_layout, MarkdownPreviewLayout::SideBySide);
|
||||
assert_eq!(old.languages.markdown.preview_font_size, Some(16));
|
||||
assert_eq!(old.languages.markdown.soft_line_breaks, MarkdownSoftLineBreaks::Standard);
|
||||
|
||||
let stacked: Settings =
|
||||
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked"}}}"#).unwrap();
|
||||
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked","softLineBreaks":"break"}}}"#)
|
||||
.unwrap();
|
||||
assert_eq!(stacked.languages.markdown.preview_layout, MarkdownPreviewLayout::Stacked);
|
||||
assert_eq!(stacked.languages.markdown.soft_line_breaks, MarkdownSoftLineBreaks::Break);
|
||||
let saved = serde_json::to_value(&stacked).unwrap();
|
||||
assert_eq!(saved["languages"]["markdown"]["previewLayout"], "stacked");
|
||||
assert_eq!(saved["languages"]["markdown"]["softLineBreaks"], "break");
|
||||
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().languages.markdown, stacked.languages.markdown);
|
||||
}
|
||||
|
||||
@@ -2487,12 +2604,12 @@ mod tests {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"fileIconTheme":"p/t"}}"#).unwrap();
|
||||
assert!(old.appearance.file_icon_theme_options.is_empty());
|
||||
let json = serde_json::json!({"appearance":{"fileIconThemeOptions":{"p/t":{
|
||||
"groups":{"tests":true},"choices":{"arrows":"plusminus"},"hideFiles":true,"hideFolders":false,"hollowFolders":true,"hideUiIcons":true,"hidePsiIcons":false,
|
||||
"groups":{"tests":true},"choices":{"arrows":"plusminus"},"hideFiles":true,"hideFolders":false,"hollowFolders":true,"hideUiIcons":true,"hidePsiIcons":false,"fileIconsForCode":true,
|
||||
"monochrome":"#546e7a","saturation":5,"opacity":80,"iconSize":20,"rowHeight":30,"accent":"#009688"}}}});
|
||||
let settings: Settings = serde_json::from_value(json.clone()).unwrap();
|
||||
let options = &settings.appearance.file_icon_theme_options["p/t"];
|
||||
assert!(options.hide_files && options.hollow_folders && !options.hide_folders);
|
||||
assert!(options.hide_ui_icons && !options.hide_psi_icons);
|
||||
assert!(options.hide_ui_icons && !options.hide_psi_icons && options.file_icons_for_code);
|
||||
assert!(options.groups["tests"]);
|
||||
assert_eq!(options.choices["arrows"], "plusminus");
|
||||
assert_eq!(
|
||||
@@ -2508,6 +2625,7 @@ mod tests {
|
||||
assert_eq!(plain["hideFiles"], false);
|
||||
assert_eq!(plain["hideUiIcons"], false);
|
||||
assert_eq!(plain["hidePsiIcons"], false);
|
||||
assert_eq!(plain["fileIconsForCode"], false);
|
||||
assert_eq!(plain["monochrome"], serde_json::Value::Null);
|
||||
assert_eq!(plain["groups"], serde_json::json!({}));
|
||||
}
|
||||
@@ -2576,6 +2694,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dim_inactive_code_defaults_on_and_round_trips() {
|
||||
let mut settings = Settings::default();
|
||||
assert!(settings.editor.dim_inactive_code);
|
||||
settings.editor.dim_inactive_code = false;
|
||||
let json = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(json["editor"]["dimInactiveCode"], false);
|
||||
let restored: Settings = serde_json::from_value(json).unwrap();
|
||||
assert!(!restored.editor.dim_inactive_code);
|
||||
// Settings written before the option existed keep clangd's inactive-code grey.
|
||||
let old: Settings = serde_json::from_str(r#"{"editor":{"semanticHighlighting":true}}"#).unwrap();
|
||||
assert!(old.editor.dim_inactive_code);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_window_badges_default_on_and_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
|
||||
|
||||
@@ -296,6 +296,14 @@ pub struct OutlineItem {
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub visibility: Option<Visibility>,
|
||||
/// Rust `impl Trait for Type`: the trait's name in the header (its last path segment, where go-to-definition lands), from the syntax tree.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub implements: Option<Range>,
|
||||
/// Rust `impl [Trait for] Type`: the implementing type's name (its last path segment), from the syntax tree.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub self_type: Option<Range>,
|
||||
}
|
||||
|
||||
/// Fuzzy-match highlight: indices (in chars of the displayed string) that matched.
|
||||
|
||||
@@ -8,6 +8,21 @@ use std::collections::HashSet;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Why netcoredbg can't be installed here, for the two platforms Samsung publishes no build
|
||||
/// for; the tool installer and the debugger's "not found" error both say it.
|
||||
pub fn netcoredbg_no_prebuilt(intel_mac: bool, windows_arm64: bool) -> Option<String> {
|
||||
let platform = match (intel_mac, windows_arm64) {
|
||||
(true, _) => "Intel Macs",
|
||||
(_, true) => "Windows on ARM64",
|
||||
_ => return None,
|
||||
};
|
||||
Some(format!(
|
||||
"Samsung publishes no prebuilt netcoredbg for {platform}. Build it from source \
|
||||
(https://github.com/Samsung/netcoredbg#building-from-source-code), then put `netcoredbg` on PATH \
|
||||
or set its executable path in Settings › Languages & Frameworks › Language Servers"
|
||||
))
|
||||
}
|
||||
|
||||
/// Where executables are looked up: this process's `PATH` (the login shell's in the
|
||||
/// app), the login shell's `PATH` as last read, then per-user directories and mise's,
|
||||
/// asdf's and pyenv's shims, for when the shell's setup didn't reach the app. Language server
|
||||
@@ -133,6 +148,7 @@ fn search_dirs(
|
||||
dirs.extend(USER_DIRS.iter().map(|d| home.join(d)));
|
||||
dirs.extend(nvm_bins(&home.join(".nvm/versions/node")));
|
||||
}
|
||||
dirs.extend(RUSTUP_PROXY_DIRS.iter().map(PathBuf::from));
|
||||
// Version managers' shims after real tool directories: a shim exists for a command any
|
||||
// installed version has, and fails when the selected one lacks it. Before the system's,
|
||||
// as the managers' shell setup puts them.
|
||||
@@ -165,6 +181,11 @@ const USER_DIRS: &[&str] = &[
|
||||
"Library/pnpm",
|
||||
];
|
||||
|
||||
/// Homebrew's `rustup` keeps its toolchain proxies (`cargo`, `rust-analyzer`, …) in its own
|
||||
/// prefix, off `PATH` unless the shell adds it: these play the part of `~/.cargo/bin`.
|
||||
pub const RUSTUP_PROXY_DIRS: &[&str] =
|
||||
&["/opt/homebrew/opt/rustup/bin", "/usr/local/opt/rustup/bin", "/home/linuxbrew/.linuxbrew/opt/rustup/bin"];
|
||||
|
||||
const SYSTEM_DIRS: &[&str] = &["/opt/homebrew/bin", "/usr/local/go/bin", "/usr/local/bin", "/usr/bin", "/bin"];
|
||||
|
||||
/// Whether `dir` is one of the system's own bin directories, which [`search_path`] adds
|
||||
@@ -250,13 +271,16 @@ mod tests {
|
||||
assert!(at("/home/me/.npm-global/bin") < at("/home/me/.pyenv/shims"));
|
||||
// Global .NET tools (fsautocomplete, csharp-ls) install here, off PATH.
|
||||
assert!(at("/home/me/.dotnet/tools") < at("/usr/local/bin"));
|
||||
// Homebrew rustup's proxies, after rustup-init's.
|
||||
assert!(at("/home/me/.cargo/bin") < at("/opt/homebrew/opt/rustup/bin"));
|
||||
assert!(at("/opt/homebrew/opt/rustup/bin") < at("/opt/homebrew/bin"));
|
||||
assert!(at("/home/me/.local/share/mise/shims") < at("/usr/local/bin"));
|
||||
assert!(dirs.iter().all(|d| d.is_absolute()));
|
||||
let unique: HashSet<&PathBuf> = dirs.iter().collect();
|
||||
assert_eq!(unique.len(), dirs.len());
|
||||
// A `:` can't be in a `PATH` entry: those below such a home are left out.
|
||||
let dirs = search_dirs(Some(OsStr::new("/usr/bin")), None, None, Some(Path::new("/home/a:b")), &[]);
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home")));
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home/a:b")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -30,6 +30,38 @@ impl UpdateSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// System Settings › Updates › Update channel: which release line updates come from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum UpdateChannel {
|
||||
/// `releases/latest`, never a prerelease, mirrored on CNB.
|
||||
Stable,
|
||||
/// The rolling `nightly` release (nightly.yml), on GitHub only.
|
||||
Nightly,
|
||||
}
|
||||
|
||||
impl UpdateChannel {
|
||||
/// The channel a build of `version` updates from unless the setting says otherwise.
|
||||
pub fn of_version(version: &str) -> Self {
|
||||
if version.contains("-nightly.") { Self::Nightly } else { Self::Stable }
|
||||
}
|
||||
|
||||
/// The `general.updateChannel` setting; anything else follows this build.
|
||||
pub fn resolve(preference: &str) -> Self {
|
||||
match preference {
|
||||
"stable" => Self::Stable,
|
||||
"nightly" => Self::Nightly,
|
||||
_ => Self::of_version(env!("CARGO_PKG_VERSION")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Stable => "stable",
|
||||
Self::Nightly => "nightly",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UpdateInfo {
|
||||
@@ -109,6 +141,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_follows_the_build_unless_chosen() {
|
||||
assert_eq!(UpdateChannel::of_version("0.1.57"), UpdateChannel::Stable);
|
||||
assert_eq!(UpdateChannel::of_version("0.1.58-nightly.20261203"), UpdateChannel::Nightly);
|
||||
assert_eq!(UpdateChannel::of_version("0.1.58-nightly.20261203.2"), UpdateChannel::Nightly);
|
||||
assert_eq!(UpdateChannel::of_version("0.2.0-beta.1"), UpdateChannel::Stable);
|
||||
assert_eq!(UpdateChannel::resolve("stable"), UpdateChannel::Stable);
|
||||
assert_eq!(UpdateChannel::resolve("nightly"), UpdateChannel::Nightly);
|
||||
let build = UpdateChannel::of_version(env!("CARGO_PKG_VERSION"));
|
||||
for other in ["", "auto", "Nightly", "eap"] {
|
||||
assert_eq!(UpdateChannel::resolve(other), build);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checks_at_startup_and_every_four_hours_even_after_failure() {
|
||||
let mut policy = UpdatePolicy::default();
|
||||
|
||||
@@ -31,6 +31,17 @@ pub struct VcsSettings {
|
||||
pub svn: SvnSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Subversion (`vcs.svn`).
|
||||
/// Branch and tag URL layout configured for one Subversion repository.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SvnBranchConfig {
|
||||
/// Trunk URL (e.g. `https://svn.example.com/repos/project/trunk`).
|
||||
pub trunk_url: String,
|
||||
/// Folders holding branches/tags (e.g. `["https://svn.example.com/repos/project/branches"]`).
|
||||
pub branch_locations: Vec<String>,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Subversion (`vcs.svn`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -43,6 +54,8 @@ pub struct SvnSettings {
|
||||
/// Pass `--config-dir config_dir` to every svn command.
|
||||
pub use_custom_config_dir: bool,
|
||||
pub config_dir: String,
|
||||
/// Configured trunk/branch locations keyed by normalized repository root URL or WC root.
|
||||
pub branch_configurations: std::collections::BTreeMap<String, SvnBranchConfig>,
|
||||
}
|
||||
|
||||
impl Default for SvnSettings {
|
||||
@@ -54,6 +67,7 @@ impl Default for SvnSettings {
|
||||
interactive: !cfg!(windows),
|
||||
use_custom_config_dir: false,
|
||||
config_dir: String::new(),
|
||||
branch_configurations: std::collections::BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -477,12 +491,15 @@ pub struct BuildSettings {
|
||||
pub open_tool_window: String,
|
||||
/// When to focus the Build tool window: `always` | `onError` | `never`.
|
||||
pub focus_tool_window: String,
|
||||
/// Build an Xcode project in the background when xcode-build-server has no build log to read
|
||||
/// yet, so cross-file code insight works before the first Run.
|
||||
pub xcode_index_build: bool,
|
||||
}
|
||||
|
||||
impl Default for BuildSettings {
|
||||
fn default() -> Self {
|
||||
// Builds open the tool window without taking focus.
|
||||
Self { open_tool_window: "always".into(), focus_tool_window: "never".into() }
|
||||
Self { open_tool_window: "always".into(), focus_tool_window: "never".into(), xcode_index_build: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -559,6 +576,8 @@ pub struct DebuggerSettings {
|
||||
pub flutter_hot_reload_on_save: bool,
|
||||
/// Java: whether to reload changed classes into running debug sessions after compilation.
|
||||
pub hot_swap_after_compile: HotSwapPolicy,
|
||||
/// Built-in Server: starting loopback port for `/api/file/<path>:<line>` requests.
|
||||
pub built_in_server_port: u16,
|
||||
pub python: PythonDebuggerSettings,
|
||||
pub cpp: CppDebuggerSettings,
|
||||
}
|
||||
@@ -582,6 +601,7 @@ impl Default for DebuggerSettings {
|
||||
debug_server_page: false,
|
||||
flutter_hot_reload_on_save: true,
|
||||
hot_swap_after_compile: HotSwapPolicy::Ask,
|
||||
built_in_server_port: 63342,
|
||||
python: PythonDebuggerSettings::default(),
|
||||
cpp: CppDebuggerSettings::default(),
|
||||
}
|
||||
@@ -664,7 +684,6 @@ pub struct TerminalSettings {
|
||||
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,
|
||||
@@ -704,7 +723,6 @@ impl Default for TerminalSettings {
|
||||
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,
|
||||
@@ -726,6 +744,8 @@ impl Default for TerminalSettings {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ActionsOnSaveSettings {
|
||||
pub optimize_imports: bool,
|
||||
/// Rearrange code: class members in arrangement order, for the languages that have it.
|
||||
pub rearrange: bool,
|
||||
/// Run code cleanup (`source.fixAll`).
|
||||
pub cleanup: bool,
|
||||
}
|
||||
|
||||
@@ -14,4 +14,5 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
dunce.workspace = true
|
||||
tempfile.workspace = true
|
||||
@@ -51,8 +51,14 @@ fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf
|
||||
|
||||
/// Relative sources (and filenames without sources) resolve against `base`.
|
||||
pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Error> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut acc = Accumulator::default();
|
||||
parse_into(xml, base, &mut acc)?;
|
||||
Ok(acc)
|
||||
}
|
||||
|
||||
/// Like [`parse`], merging into the data of other reports.
|
||||
pub(crate) fn parse_into(xml: &str, base: &Path, acc: &mut Accumulator) -> Result<(), quick_xml::Error> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
|
||||
let mut source: Option<String> = None;
|
||||
let mut file: Option<PathBuf> = None;
|
||||
@@ -72,7 +78,8 @@ pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Er
|
||||
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().ok()) else { continue };
|
||||
let line = number.saturating_sub(1);
|
||||
acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0));
|
||||
if attr(&e, "branch").as_deref() == Some("true")
|
||||
// coverlet writes `True`.
|
||||
if attr(&e, "branch").is_some_and(|b| b.eq_ignore_ascii_case("true"))
|
||||
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
|
||||
{
|
||||
acc.has_branches = true;
|
||||
@@ -115,7 +122,7 @@ pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Er
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(acc)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -162,6 +169,16 @@ mod tests {
|
||||
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
|
||||
}
|
||||
|
||||
/// Written by `dotnet test --collect:"XPlat Code Coverage"` (coverlet.collector 6.0.4).
|
||||
#[test]
|
||||
fn reads_a_coverlet_report() {
|
||||
let suite =
|
||||
parse(include_str!("testdata/coverlet.cobertura.xml"), Path::new("/root")).unwrap().finish("coverlet");
|
||||
let [file] = suite.files.as_slice() else { panic!("{:?}", suite.files) };
|
||||
assert!((file.path.as_ref() as &Path).ends_with("home/dev/dn app/Calc/Calculator.cs"));
|
||||
assert_eq!((file.lines_covered, file.lines_total, file.branches_covered, file.branches_total), (6, 7, 1, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filenames_without_sources_resolve_against_the_base() {
|
||||
let xml = r#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! `dotnet test` with coverage: coverlet.collector under VSTest,
|
||||
//! Microsoft.Testing.Extensions.CodeCoverage under Microsoft.Testing.Platform.
|
||||
//!
|
||||
//! The run gets its own results directory, so only this run's reports are read.
|
||||
|
||||
use crate::plan::{missing, ready, unsupported};
|
||||
use crate::{CoveragePrepared, CoverageReportSpec};
|
||||
use ide_run::{RunConfig, wrap};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const COLLECTOR: &str = "coverlet.collector";
|
||||
const CODE_COVERAGE: &str = "Microsoft.Testing.Extensions.CodeCoverage";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Runner {
|
||||
VsTest,
|
||||
/// `global.json` selects the testing platform's `dotnet test`.
|
||||
Mtp,
|
||||
/// A testing-platform project run through the VSTest target: its options go after `--`.
|
||||
MtpLegacy,
|
||||
}
|
||||
|
||||
/// What MSBuild says about a project: (testing-platform project, referenced packages).
|
||||
fn evaluation(json: &str) -> Option<(bool, Vec<String>)> {
|
||||
let json: serde_json::Value = serde_json::from_str(&json[json.find('{')?..]).ok()?;
|
||||
let packages: Vec<String> = json["Items"]["PackageReference"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|p| p["Identity"].as_str().map(str::to_ascii_lowercase))
|
||||
.collect();
|
||||
let mtp = json["Properties"]
|
||||
.as_object()
|
||||
.is_some_and(|p| p.values().any(|v| v.as_str().is_some_and(|v| v.eq_ignore_ascii_case("true"))))
|
||||
|| packages.iter().any(|p| p.starts_with("xunit.v3.mtp"));
|
||||
Some((mtp, packages))
|
||||
}
|
||||
|
||||
/// Whether the nearest `global.json` selects Microsoft.Testing.Platform.
|
||||
fn global_mtp(dir: &Path) -> bool {
|
||||
dir.ancestors().find_map(|d| std::fs::read_to_string(d.join("global.json")).ok()).is_some_and(|text| {
|
||||
serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
|
||||
.is_ok_and(|j| j["test"]["runner"] == "Microsoft.Testing.Platform")
|
||||
})
|
||||
}
|
||||
|
||||
/// The project file the configuration tests; none for a solution or a bare `dotnet test`.
|
||||
fn project_file(config: &RunConfig, dir: &Path) -> Option<PathBuf> {
|
||||
config
|
||||
.extras
|
||||
.params
|
||||
.get("project")
|
||||
.into_iter()
|
||||
.chain(config.args.iter().skip(1))
|
||||
.find(|a| Path::new(a).extension().is_some_and(|e| e.to_string_lossy().to_ascii_lowercase().ends_with("proj")))
|
||||
.map(|p| dir.join(p))
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(config: &RunConfig, dir: &Path, out: &Path) -> CoveragePrepared {
|
||||
if config.args.first().is_none_or(|a| a != "test") {
|
||||
return unsupported(".NET coverage runs `dotnet test` configurations.");
|
||||
}
|
||||
let project = project_file(config, dir);
|
||||
let evaluated = project.as_ref().and_then(|project| {
|
||||
let mut argv = vec![
|
||||
config.command.clone(),
|
||||
"msbuild".into(),
|
||||
project.to_string_lossy().into_owned(),
|
||||
"-nologo".into(),
|
||||
"-getProperty:IsTestingPlatformApplication,TestingPlatformDotnetTestSupport,EnableMSTestRunner".into(),
|
||||
"-getItem:PackageReference".into(),
|
||||
];
|
||||
if let Some(framework) = config.extras.params.get("framework").filter(|f| !f.is_empty()) {
|
||||
argv.push(format!("-p:TargetFramework={framework}"));
|
||||
}
|
||||
evaluation(&wrap::capture(&argv, dir, config)?)
|
||||
});
|
||||
let project_dir = project.as_deref().and_then(Path::parent).unwrap_or(dir);
|
||||
let runner = if global_mtp(project_dir) {
|
||||
Runner::Mtp
|
||||
} else if evaluated.as_ref().is_some_and(|(mtp, _)| *mtp) {
|
||||
Runner::MtpLegacy
|
||||
} else {
|
||||
Runner::VsTest
|
||||
};
|
||||
let package = if runner == Runner::VsTest { COLLECTOR } else { CODE_COVERAGE };
|
||||
if let Some((project, (_, packages))) = project.as_ref().zip(evaluated.as_ref())
|
||||
&& !packages.iter().any(|p| p.eq_ignore_ascii_case(package))
|
||||
{
|
||||
let target = project.strip_prefix(dir).unwrap_or(project).to_string_lossy();
|
||||
let add = [&config.command, "add", &target, "package", package].map(str::to_owned);
|
||||
return missing(
|
||||
package,
|
||||
format!(".NET coverage needs the {package} package in the test project."),
|
||||
Some((add.to_vec(), dir)),
|
||||
);
|
||||
}
|
||||
launch(config, dir, out, runner, package)
|
||||
}
|
||||
|
||||
fn launch(config: &RunConfig, dir: &Path, out: &Path, runner: Runner, package: &str) -> CoveragePrepared {
|
||||
let results = out.to_string_lossy().into_owned();
|
||||
let mut extra: Vec<String> = match runner {
|
||||
Runner::VsTest => vec!["--collect:XPlat Code Coverage".into()],
|
||||
_ => ["--coverage", "--coverage-output-format", "cobertura"].map(str::to_owned).to_vec(),
|
||||
};
|
||||
extra.extend(["--results-directory".into(), results]);
|
||||
let mut launch = config.clone();
|
||||
// A `dotnet test` configuration type rebuilds its command line from the parameters.
|
||||
launch.extras.params.insert("coverageArgs".into(), serde_json::json!(extra).to_string());
|
||||
let boundary = launch.args.iter().position(|a| a == "--");
|
||||
match runner {
|
||||
Runner::VsTest => {
|
||||
let at = boundary.unwrap_or(launch.args.len());
|
||||
launch.args.splice(at..at, extra);
|
||||
}
|
||||
Runner::Mtp => launch.args.extend(extra),
|
||||
Runner::MtpLegacy => {
|
||||
if boundary.is_none() {
|
||||
launch.args.push("--".into());
|
||||
}
|
||||
launch.args.extend(extra);
|
||||
}
|
||||
}
|
||||
let report = CoverageReportSpec::Cobertura {
|
||||
runner: package.to_owned(),
|
||||
dir: out.to_path_buf().into(),
|
||||
base: dir.to_path_buf().into(),
|
||||
hint: format!("Check the test output, and that every test project references {package}."),
|
||||
};
|
||||
ready(package, &launch, launch.command.clone(), launch.args.clone(), report)
|
||||
}
|
||||
|
||||
/// VSTest writes `<dir>/<guid>/coverage.cobertura.xml`, the testing platform
|
||||
/// `<dir>/<name>.cobertura.xml`. Deeper files are the TRX logger's copies of the same data.
|
||||
pub(crate) fn reports(dir: &Path) -> Vec<PathBuf> {
|
||||
let is_report = |p: &Path| p.is_file() && p.to_string_lossy().ends_with(".cobertura.xml");
|
||||
let entries = |d: &Path| std::fs::read_dir(d).into_iter().flatten().flatten().map(|e| e.path()).collect::<Vec<_>>();
|
||||
let mut found: Vec<PathBuf> = entries(dir)
|
||||
.into_iter()
|
||||
.flat_map(|p| if p.is_dir() { entries(&p) } else { vec![p] })
|
||||
.filter(|p| is_report(p))
|
||||
.collect();
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn config(args: &[&str]) -> RunConfig {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"id": "t", "name": "t", "kind": "shell", "command": "dotnet", "args": args,
|
||||
"env": {}, "detected": true, "isTest": true,
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn args(runner: Runner, base: &[&str]) -> Vec<String> {
|
||||
match launch(&config(base), Path::new("/p"), Path::new("/o"), runner, "x") {
|
||||
CoveragePrepared::Ready { launch, .. } => launch.args,
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_go_where_each_runner_reads_them() {
|
||||
assert_eq!(
|
||||
args(Runner::VsTest, &["test", "--", "A=1"]),
|
||||
["test", "--collect:XPlat Code Coverage", "--results-directory", "/o", "--", "A=1"]
|
||||
);
|
||||
let platform = ["--coverage", "--coverage-output-format", "cobertura", "--results-directory", "/o"];
|
||||
assert_eq!(args(Runner::Mtp, &["test"])[1..], platform);
|
||||
let legacy = args(Runner::MtpLegacy, &["test"]);
|
||||
assert_eq!((legacy[1].as_str(), &legacy[2..]), ("--", platform.map(str::to_owned).as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn msbuild_evaluation_names_packages_and_the_platform() {
|
||||
let json = r#"noise {"Properties":{"IsTestingPlatformApplication":""},"Items":{"PackageReference":[{"Identity":"Coverlet.Collector"}]}}"#;
|
||||
assert_eq!(evaluation(json), Some((false, vec!["coverlet.collector".into()])));
|
||||
let json = r#"{"Properties":{"EnableMSTestRunner":"true"},"Items":{"PackageReference":[]}}"#;
|
||||
assert_eq!(evaluation(json), Some((true, vec![])));
|
||||
assert_eq!(evaluation("error MSB1009"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_files_and_global_json() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = project_file(&config(&["test", "a/T.fsproj"]), tmp.path()).unwrap();
|
||||
assert_eq!(project, tmp.path().join("a/T.fsproj"));
|
||||
assert_eq!(project_file(&config(&["test", "All.sln"]), tmp.path()), None);
|
||||
assert!(!global_mtp(&tmp.path().join("a")));
|
||||
std::fs::write(
|
||||
tmp.path().join("global.json"),
|
||||
"{ // x\n\"test\":{\"runner\":\"Microsoft.Testing.Platform\"},}",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(global_mtp(&tmp.path().join("a")));
|
||||
}
|
||||
|
||||
/// One report per test project is merged; the TRX logger's copies are not counted twice.
|
||||
#[test]
|
||||
fn merges_the_reports_of_one_run() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let xml = include_str!("testdata/coverlet.cobertura.xml");
|
||||
for file in
|
||||
["guid-a/coverage.cobertura.xml", "guid-b/coverage.cobertura.xml", "t/In/host/coverage.cobertura.xml"]
|
||||
{
|
||||
let file = tmp.path().join(file);
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(file, xml).unwrap();
|
||||
}
|
||||
let spec = CoverageReportSpec::Cobertura {
|
||||
runner: "coverlet.collector".into(),
|
||||
dir: tmp.path().to_path_buf().into(),
|
||||
base: tmp.path().to_path_buf().into(),
|
||||
hint: "why".into(),
|
||||
};
|
||||
let suite = crate::collect(&spec).unwrap();
|
||||
assert_eq!(suite.files[0].lines[0].hits, 2);
|
||||
std::fs::write(tmp.path().join("direct.cobertura.xml"), xml).unwrap();
|
||||
assert_eq!(reports(tmp.path()).len(), 3);
|
||||
// A cancelled or failed build leaves nothing: say why.
|
||||
let empty = tempfile::tempdir().unwrap();
|
||||
let spec = CoverageReportSpec::Cobertura {
|
||||
runner: "x".into(),
|
||||
dir: empty.path().to_path_buf().into(),
|
||||
base: empty.path().to_path_buf().into(),
|
||||
hint: "why".into(),
|
||||
};
|
||||
assert!(crate::collect(&spec).unwrap_err().to_string().contains("why"));
|
||||
}
|
||||
}
|
||||
@@ -14,11 +14,13 @@
|
||||
//! | Go (`go test`) | `-coverprofile` | Go cover profile |
|
||||
//! | Maven / Gradle tests | JaCoCo (plugin goals / an init script) | JaCoCo XML |
|
||||
//! | Xcode tests (`xcodebuild test`) | `-enableCodeCoverage YES` | the result bundle, read with `xccov` |
|
||||
//! | .NET (`dotnet test`) | coverlet.collector, or Microsoft.Testing.Extensions.CodeCoverage | Cobertura XML |
|
||||
//!
|
||||
//! Lines in the model are 0-based, like every IPC coordinate.
|
||||
|
||||
mod cobertura;
|
||||
mod coveragepy;
|
||||
mod dotnet;
|
||||
mod goprofile;
|
||||
mod import;
|
||||
mod jacoco;
|
||||
@@ -94,6 +96,9 @@ pub enum CoverageReportSpec {
|
||||
SimpleCov { path: IpcPath, base: IpcPath },
|
||||
/// Every JaCoCo XML report (Maven `target/site/jacoco`, Gradle `build/reports/jacoco`) under `dir`.
|
||||
Jacoco { dir: IpcPath },
|
||||
/// The Cobertura reports `dotnet test` left in its results directory `dir`: one per test
|
||||
/// project and target framework. `hint` explains why there might be none.
|
||||
Cobertura { runner: String, dir: IpcPath, base: IpcPath, hint: String },
|
||||
/// The tool's raw data is exported to lcov by `argv` first (coverage.py: `… -m coverage lcov -o <lcov>`).
|
||||
Exported { runner: String, argv: Vec<String>, cwd: IpcPath, env: BTreeMap<String, String>, lcov: IpcPath },
|
||||
/// An Xcode result bundle, read with `xcrun xccov`; only files under `root` are kept.
|
||||
@@ -218,6 +223,19 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
|
||||
}
|
||||
Ok(acc.finish("JaCoCo"))
|
||||
}
|
||||
CoverageReportSpec::Cobertura { runner, dir, base, hint } => {
|
||||
let reports = dotnet::reports(dir);
|
||||
if reports.is_empty() {
|
||||
return Err(IdeError::not_found(format!("the run produced no coverage report. {hint}")));
|
||||
}
|
||||
let mut acc = Accumulator::default();
|
||||
for report in reports {
|
||||
let xml = std::fs::read_to_string(&report)?;
|
||||
cobertura::parse_into(&xml, base, &mut acc)
|
||||
.map_err(|e| IdeError::invalid(format!("{}: {e}", report.display())))?;
|
||||
}
|
||||
Ok(acc.finish(runner))
|
||||
}
|
||||
CoverageReportSpec::Exported { runner, argv, cwd, env, lcov } => {
|
||||
let (program, args) =
|
||||
argv.split_first().ok_or_else(|| IdeError::invalid("empty coverage export command"))?;
|
||||
|
||||
Loaded 100 of 2740 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача