diff --git a/Cargo.lock b/Cargo.lock index 44fdffc10..e27dc5f38 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -474,7 +474,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "457d7ed3f888dfd2c7af56d4975cade43c622f74bdcddfed6d4352f57acc6310" dependencies = [ "futures-util", - "parking_lot", + "parking_lot 0.12.5", "portable-atomic", "tokio", ] @@ -1655,9 +1655,9 @@ dependencies = [ "cfg-if", "crossbeam-utils", "hashbrown 0.14.5", - "lock_api", + "lock_api 0.4.14", "once_cell", - "parking_lot_core", + "parking_lot_core 0.9.12", "serde", ] @@ -2154,7 +2154,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2210,6 +2210,16 @@ dependencies = [ "serde", ] +[[package]] +name = "faster-hex" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4ede54fe330383a5de28c0a1f06668ff9dbf06c8094e1c5150c39488a5e911d" +dependencies = [ + "defmt 0.3.101", + "serde", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -2453,8 +2463,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" dependencies = [ "futures-core", - "lock_api", - "parking_lot", + "lock_api 0.4.14", + "parking_lot 0.12.5", ] [[package]] @@ -2734,9 +2744,9 @@ dependencies = [ [[package]] name = "gix" -version = "0.89.0" +version = "0.90.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2156d2e07fc3afa7632a82bf3cb0db91f995645a2852f642105c9ac9b52e1cb2" +checksum = "b92b20c1560511a9014b16e29db2f3c6f0580d4fe289b70f41131277b065a3b0" dependencies = [ "gix-actor", "gix-attributes", @@ -2788,9 +2798,9 @@ dependencies = [ [[package]] name = "gix-actor" -version = "0.44.0" +version = "0.44.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2127da41042965ed205568a52443465806944f71c8acd73f48ec94b8cd8e798e" +checksum = "78243d3371019288a40a75ba1a58de2815c32591fc87b9f7cb01918bce364ca8" dependencies = [ "bstr", "gix-date", @@ -2799,9 +2809,9 @@ dependencies = [ [[package]] name = "gix-attributes" -version = "0.37.0" +version = "0.37.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0feca0b8919aba9f123b75de54062dd61eb37d2a2130f34be520da6ed8b8ef72" +checksum = "6b9947d93a94d41ddde66ac655674269121cbebaf6cdee30d8d0e7dbe85edb4c" dependencies = [ "bstr", "gix-error", @@ -2816,27 +2826,27 @@ dependencies = [ [[package]] name = "gix-bitmap" -version = "0.6.0" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "408cb9e482e0dcc5fc481850556348dda6981ec054a4a8e81a8e1bbf84f85eef" +checksum = "9543567ee22142c81fdf75b2811160bec749a5b9f48665e4763f88b1789b8612" dependencies = [ "gix-error", ] [[package]] name = "gix-chunk" -version = "0.10.0" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626335faf30ed235744642c2309aa370683b8bb2757f1c22a807e274dff60074" +checksum = "60cd5f0e47ffae98bad241ccbc031693765004fb4c2a419f7fda2963232af1e3" dependencies = [ "gix-error", ] [[package]] name = "gix-command" -version = "0.12.0" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac560c05e19455016a4a94b33a77debe59aaed8783da32a73d31c9975947152e" +checksum = "2986e78ebad43510ccd7dd18bd9f22e9afd52f2de791e2979b9c715bacb6f0a8" dependencies = [ "bstr", "gix-error", @@ -2847,9 +2857,9 @@ dependencies = [ [[package]] name = "gix-commitgraph" -version = "0.41.0" +version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfede9936d4b789867c09722576aea4ceb0e3aacf962eef035ebab0686b41a80" +checksum = "60b53b700d2a506cf98075099df1fcc0558265cbb47fd86bc6d03c231e4bd72a" dependencies = [ "bstr", "gix-chunk", @@ -2861,9 +2871,9 @@ dependencies = [ [[package]] name = "gix-config" -version = "0.62.0" +version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65a9c000fa9a9154f22ffc8f8d74426e9300d759c2029e8701e2ba39d5d464ea" +checksum = "3e11ccf82e9630c4e7befbae07cbe90e79de61dc73a34448c2dec70a13da9ebf" dependencies = [ "bstr", "gix-config-value", @@ -2881,9 +2891,9 @@ dependencies = [ [[package]] name = "gix-config-value" -version = "0.21.0" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab206c2fccfd35e0de7fb1b424997cfd42912062c66dae024e08a06e22d46674" +checksum = "d7666081ef0ecc5e1dc54bc6ce16dac9d7b9490780f6c130393ef9e50c909d4a" dependencies = [ "bitflags 2.13.2", "bstr", @@ -2895,9 +2905,9 @@ dependencies = [ [[package]] name = "gix-date" -version = "0.18.0" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f7eeeecc599082f32b5ea6a8c4c734e38be9730e2c09e3fe2851bb4692393e9" +checksum = "4c538190012dbb536df54734ec38cc1109270c73f2f76585c011dd5b0c9f087c" dependencies = [ "bstr", "gix-error", @@ -2907,9 +2917,9 @@ dependencies = [ [[package]] name = "gix-diff" -version = "0.69.0" +version = "0.70.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa640963fdcbc6b4718e48593c3917f5ae764b59fb5a96313cb5a757246d041d" +checksum = "2c794988335792f85c3ca79c385c950b3a921a71ba3df361cb1f9e5b6bd4a6e4" dependencies = [ "bstr", "gix-attributes", @@ -2931,9 +2941,9 @@ dependencies = [ [[package]] name = "gix-dir" -version = "0.31.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84e916ef77f19161b738ae9913662bc36fed1e48256a943f40277b3a585841da" +checksum = "af939f21c65d4f15457c72d08c874d454893185c51a3596e3c2bd3d9c567618d" dependencies = [ "bstr", "gix-discover", @@ -2951,9 +2961,9 @@ dependencies = [ [[package]] name = "gix-discover" -version = "0.57.0" +version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7d0f8fd2c7e4b458eb3081362d49b54bd0131d23ecd49be802085a11f0d3cee" +checksum = "4a0875f4e5408713fcf92265973cc38bf9dc5a93384ce218beba0572b7785a03" dependencies = [ "bstr", "dunce", @@ -2966,18 +2976,18 @@ dependencies = [ [[package]] name = "gix-error" -version = "0.5.1" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb3308a948a01b94ef13d9ee7a9b28c1303d8d9a9dc33b401ff40c2184d9e04a" +checksum = "50ad6c42fa50280f382026ff838a8afa7ab2ad83e92349cab4392972baae69cd" dependencies = [ "bstr", ] [[package]] name = "gix-filter" -version = "0.36.0" +version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d8d932ee4043f7d77d15ee58d2be2bc95accea5dd1d77fd145de1b7c504551b" +checksum = "f8df8d50fda4684c6ec366f75e4082ab6fc3d437d3deec30ff88462710b68d17" dependencies = [ "bstr", "encoding_rs", @@ -2996,9 +3006,9 @@ dependencies = [ [[package]] name = "gix-fs" -version = "0.24.0" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44a05d043e670c055cd8b53d078562dc0bc1e322bff6b0376b407d37cf72dcc5" +checksum = "808f23d897ddfe847d9b7206bda947901885be623bdf96b226a2dccf87f018c7" dependencies = [ "bstr", "gix-error", @@ -3011,9 +3021,9 @@ dependencies = [ [[package]] name = "gix-glob" -version = "0.29.0" +version = "0.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b0d03ab50fa841621031960679caf7fe94940968d9a0736d12a580f2c03e525" +checksum = "7a12789fa68a150293ad8834d267b31044240532b5ccf2734d228fe985cba2be" dependencies = [ "bitflags 2.13.2", "bstr", @@ -3025,11 +3035,11 @@ dependencies = [ [[package]] name = "gix-hash" -version = "0.28.0" +version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ca156064e378d8c657084365846cedb8dc498c6ea4500965a64d74f12af2be" +checksum = "b4802ffb87e051795822bfdaa8ab9075b23e316684f7054e6ce4a246b2b76f4e" dependencies = [ - "faster-hex", + "faster-hex 0.10.1", "gix-error", "gix-utils", "sha1dc", @@ -3044,7 +3054,7 @@ checksum = "916cb6b2ec42ffaca624e7867bb382a4673015cb4ffcd7330b48085d02e4c615" dependencies = [ "gix-hash", "hashbrown 0.17.1", - "parking_lot", + "parking_lot 0.12.5", ] [[package]] @@ -3062,9 +3072,9 @@ dependencies = [ [[package]] name = "gix-imara-diff" -version = "0.3.1" +version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c48eccd894bd15555b0346470e63491ded94aefe76b3fcb1052084b5a393238" +checksum = "23347fa4a29a440eebf045d0bc21da465c0dc70434c2a4bcdfcc658f16c9e27e" dependencies = [ "bstr", "hashbrown 0.17.1", @@ -3072,9 +3082,9 @@ dependencies = [ [[package]] name = "gix-index" -version = "0.57.0" +version = "0.58.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc6db8b20a3dba8836daf90b24199600bb27dcfce3a127ec24ae61e15a7c5b68" +checksum = "06bfc736774a623307eda890c918d308ef5acd37402bde2d6768fccb1f6ecb5d" dependencies = [ "bitflags 2.13.2", "bstr", @@ -3124,9 +3134,9 @@ dependencies = [ [[package]] name = "gix-note" -version = "0.3.0" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd364f8bdceaed9e7f3ae40f324b16e39f20e9c7e6a6a058f7c6ec66c3e6205c" +checksum = "8473688f2262f4364f521b39ce2a5dbe94494f327fc19c945318d7aff580952e" dependencies = [ "gix-error", "gix-hash", @@ -3135,9 +3145,9 @@ dependencies = [ [[package]] name = "gix-object" -version = "0.66.0" +version = "0.66.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0e38f50177e211642af154f9a7f710b7a3a637e635f9b6adb9d51973b0f9209" +checksum = "beaf9086dd00b9d2a177ca3ae83210ce926cee7c0faa112e053851221cd8f94d" dependencies = [ "bstr", "gix-actor", @@ -3156,9 +3166,9 @@ dependencies = [ [[package]] name = "gix-odb" -version = "0.86.0" +version = "0.87.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca444f33f2140876ed6b5313c2b550b4af699008193c96f3bff5023afa9ef4ea" +checksum = "941b5b99fed282a5b05b54ea486c36c76b558afe151e6804c3acdd5c8f3c3459" dependencies = [ "arc-swap", "crc32fast", @@ -3175,15 +3185,15 @@ dependencies = [ "gix-utils", "gix-zlib", "memmap2", - "parking_lot", + "parking_lot 0.12.5", "tempfile", ] [[package]] name = "gix-pack" -version = "0.76.0" +version = "0.77.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc5024cc503cd29461a705ae90b9eae772fa8f0e6fafc1c48513877dc374de05" +checksum = "e2ef461798b1e6cb652192c69dfc9658dfc1bab457ef812dd1ab85d75104cbef" dependencies = [ "clru", "crc32fast", @@ -3204,45 +3214,46 @@ dependencies = [ [[package]] name = "gix-packetline" -version = "0.24.0" +version = "0.24.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830e51b227f6a925fe9308858ac91170dd00fa2880f5480fc81e8a4594fe2c35" +checksum = "6e198121152a397ad1007e3334931b04b393fa17f6af34f17b33e376b15bf5ea" dependencies = [ "bstr", - "faster-hex", + "faster-hex 2.0.0", "gix-error", "gix-trace", ] [[package]] name = "gix-parallel" -version = "0.50.0" +version = "0.50.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e994cf1eec247ba4be7f9e7c0d58cc73f83eecb5fcb9feb595df5ba3d2078546" +checksum = "d3a5c86eeec0194a3444611b4762ba05cc5029408a617348b4f6a74a34c222cd" dependencies = [ "crossbeam-channel", "gix-trace", "once_cell", - "parking_lot", + "parking_lot 0.13.0", ] [[package]] name = "gix-path" -version = "0.14.0" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6d563d4d0c975ed0df4e853f9ec962a2ba46633b1d324e1a5582541fcae0c6b" +checksum = "615e3ff75800c67022ec8065b67e0846420a88c5f484e6c4fd81c78472e4c77a" dependencies = [ "bstr", "gix-error", "gix-trace", "gix-validate", + "winreg 0.56.0", ] [[package]] name = "gix-pathspec" -version = "0.22.0" +version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e3b7f03e516a8435d18c3cc2d446925940c81d409145ac21edb5a576f0625e4" +checksum = "490aa03a11e0cbb998a0a593b75e27ea2e30df4ebd8f84f60e0641b9b72270e8" dependencies = [ "bitflags 2.13.2", "bstr", @@ -3255,9 +3266,9 @@ dependencies = [ [[package]] name = "gix-protocol" -version = "0.67.0" +version = "0.68.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "832b5dc46a3c0a6f6fa8f8e571c11074add4b545c6789799ae6d6c36ae1a294e" +checksum = "83677ebae6a1a09dc07f2435b5ebe68470dc51afb74052135e98fd7c11f85ba9" dependencies = [ "bstr", "gix-date", @@ -3273,9 +3284,9 @@ dependencies = [ [[package]] name = "gix-quote" -version = "0.10.0" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f92bc1b13c09e88388578e8aa1e987ec35f28fca158c13b1baa7ab1a85b124" +checksum = "5069a7ec021bb47abe9f12dcc075d292e8cf4a9dff5fffd38595b39c6b419aaa" dependencies = [ "bstr", "gix-error", @@ -3284,9 +3295,9 @@ dependencies = [ [[package]] name = "gix-ref" -version = "0.69.0" +version = "0.69.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "073bc0928e1f747823b1eaed94918119dacef4c616532bc3d17e5b7457863471" +checksum = "68686e4697b9cd15d1b152ef51df870513210ed22938eacc13b3672b76035f13" dependencies = [ "gix-actor", "gix-error", @@ -3304,9 +3315,9 @@ dependencies = [ [[package]] name = "gix-refspec" -version = "0.47.0" +version = "0.47.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccc7010dae0df2900aa77cc67f8aca042cd80e35938ccc179010d863b1d42a0c" +checksum = "2569309da6fdc230973cf5b846508154c0e813fda60f2b2da768cc5655ed312c" dependencies = [ "bstr", "gix-error", @@ -3317,9 +3328,9 @@ dependencies = [ [[package]] name = "gix-revision" -version = "0.51.0" +version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63210c1943b67fa700806c3c3486fc16a92b3ea871f5cf092340b8eec10a0ca1" +checksum = "241465fc73530f41d0a1c18320c5e291365b7c2c2a3dfd07afe2a5d6265085c8" dependencies = [ "bitflags 2.13.2", "bstr", @@ -3336,9 +3347,9 @@ dependencies = [ [[package]] name = "gix-revwalk" -version = "0.37.0" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "800479fbbf1e7f94f663e07943a91add5499343e7aac611a81e6a0460fd44af6" +checksum = "8b46edeacd25d9d3131941ae6bc91002bf7ba10e130393b7e9bc23d528625447" dependencies = [ "gix-commitgraph", "gix-date", @@ -3351,9 +3362,9 @@ dependencies = [ [[package]] name = "gix-sec" -version = "0.16.0" +version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5640f642a1b471616d48230b1def7ca743cb30903441ff84800cafbab3c0fddf" +checksum = "9598d1f35baec7038c2d278bfcc18f1d8951f41dcc3f51ab6175661dfe5a6137" dependencies = [ "bitflags 2.13.2", "gix-path", @@ -3363,9 +3374,9 @@ dependencies = [ [[package]] name = "gix-shallow" -version = "0.15.0" +version = "0.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94bc0720a3d6b10f18e3ac382a7780bcfc4c6bee94a8b5857b8e4ec94c50d754" +checksum = "1d805949578724b5164c90ec6d19567832ccaa5ba8a3fe26f7befc52007e2407" dependencies = [ "bstr", "gix-error", @@ -3376,9 +3387,9 @@ dependencies = [ [[package]] name = "gix-status" -version = "0.36.0" +version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d3174a9f3fb991cf25a7a609ab6c50f19baa7d5f8ce05a48c202f7db4ce3ba" +checksum = "31b00c359278210e3cc0803d057db1d61c5d6694c21ed9ad0b8f8f862157247a" dependencies = [ "bstr", "filetime", @@ -3398,14 +3409,13 @@ dependencies = [ "gix-worktree", "hashbrown 0.16.1", "portable-atomic", - "windows-sys 0.61.2", ] [[package]] name = "gix-submodule" -version = "0.36.0" +version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d945257bd0d624ca844a5a36c79d748df080f355b0ac92d68793875aa529a3f" +checksum = "d558a1307b6f3de2a92bd91d0570c53952d4f2329e6860813007508c8ed413dc" dependencies = [ "bstr", "gix-config", @@ -3425,22 +3435,22 @@ dependencies = [ "dashmap", "gix-fs", "libc", - "parking_lot", + "parking_lot 0.12.5", "tempfile", "windows-sys 0.61.2", ] [[package]] name = "gix-trace" -version = "0.3.0" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "133f2de116104d637541831b6acb157898556d5eeec363ab2eb1c583adc6bb56" +checksum = "1c96f84d731a96780e6a7ad5ee70b4ecc398499946b62617945fbaeb6ab878f8" [[package]] name = "gix-transport" -version = "0.61.0" +version = "0.62.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e43d6b0097ea9f2f266d5d6c43b8f615ed3da7c686ec8771cd17c1cb33cb0de" +checksum = "cdcd9cdfd8745aa38f926a4a380c13d76b200d7338de57fc492982cd5a6652ba" dependencies = [ "bstr", "gix-command", @@ -3456,9 +3466,9 @@ dependencies = [ [[package]] name = "gix-traverse" -version = "0.63.0" +version = "0.64.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a668a6e7f7688e5a43eaf161f1471ffc559de1a5fd8471e861c64d59d1699e1e" +checksum = "00171e00e91508300d0361072c4eb110ec0f1322d8b95ed36887231702a38ebc" dependencies = [ "bitflags 2.13.2", "gix-commitgraph", @@ -3473,9 +3483,9 @@ dependencies = [ [[package]] name = "gix-url" -version = "0.40.0" +version = "0.40.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04317dea7a5dd5253bbcab060c230f3de6a57d17cc9600c6cd7030bf4795b414" +checksum = "def12e1016b872f1094442882f627905c59bd73480435291a4958cf373a8f28d" dependencies = [ "bstr", "gix-error", @@ -3486,9 +3496,9 @@ dependencies = [ [[package]] name = "gix-utils" -version = "0.5.1" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8e770b8c34311044d1addc7b18957db0ac27183707e1140dc90e6f674a6354e" +checksum = "b5e6d46894c7a4fd9c5e26d233a0fa836002ba0af9a11aef58923d317c486e10" dependencies = [ "bstr", "bytes", @@ -3501,9 +3511,9 @@ dependencies = [ [[package]] name = "gix-validate" -version = "0.13.0" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbcd59cc52742468bc5c8a0e7123390d154f45e6cbd37461b0dcecdc681f2179" +checksum = "5d6f293fd8abd9bd9bc1e0a23541f73607e932b5a2bde2246320da38edde5726" dependencies = [ "bstr", "gix-error", @@ -3511,9 +3521,9 @@ dependencies = [ [[package]] name = "gix-worktree" -version = "0.58.0" +version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a285c0f6b41e504e8bb81ca3f861c4da00cb3d5ced3210a4591112f22da6d38f" +checksum = "fe92aec0a25cf073394492a6ee2aa4d27632acde91a653d34de0e4da6afb485d" dependencies = [ "bstr", "gix-attributes", @@ -3530,9 +3540,9 @@ dependencies = [ [[package]] name = "gix-worktree-stream" -version = "0.38.0" +version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28d2789610e8179d4e0e8e51170a52a66483c103a8ad3c7db4d075b571856cb6" +checksum = "3fe5d65793848ffb596f6c5596fd120b132038736525628227e2388ca454f64d" dependencies = [ "gix-attributes", "gix-error", @@ -3545,14 +3555,14 @@ dependencies = [ "gix-trace", "gix-traverse", "gix-utils", - "parking_lot", + "parking_lot 0.12.5", ] [[package]] name = "gix-zlib" -version = "0.3.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c2edb206bf06f3c801f4f6789c696396171558ab9b4c7f1fe3ba4d39b00b0f4" +checksum = "81a49a8b263d2a140f1c178ff93375b8d4cc7b1d3252cd87ce1ca88bce62b9b9" dependencies = [ "gix-error", "zlib-rs", @@ -4156,7 +4166,7 @@ dependencies = [ "ide-tools", "ide-vcs", "ide-vfs", - "parking_lot", + "parking_lot 0.12.5", "rustix", "semver", "serde", @@ -4297,7 +4307,7 @@ dependencies = [ "ide-language", "libc", "memchr", - "parking_lot", + "parking_lot 0.12.5", "percent-encoding", "portable-pty", "serde", @@ -4329,7 +4339,7 @@ dependencies = [ "notify", "open", "oracledb", - "parking_lot", + "parking_lot 0.12.5", "reqwest", "rsa", "rustls", @@ -4385,7 +4395,7 @@ dependencies = [ "blake3", "dunce", "ed25519-dalek", - "parking_lot", + "parking_lot 0.12.5", "semver", "serde", "serde_json", @@ -4403,7 +4413,7 @@ version = "0.1.53" dependencies = [ "ide-android", "ide-core", - "parking_lot", + "parking_lot 0.12.5", "serde_json", "tempfile", ] @@ -4510,7 +4520,7 @@ dependencies = [ "ide-workspace", "ignore", "jsonschema", - "parking_lot", + "parking_lot 0.12.5", "quick-xml 0.42.0", "regex-lite", "regex-syntax", @@ -4540,7 +4550,7 @@ dependencies = [ "hyper-util", "ide-core", "ide-vfs", - "parking_lot", + "parking_lot 0.12.5", "reqwest", "rustls", "rustls-platform-verifier", @@ -4565,7 +4575,7 @@ dependencies = [ "ide-language", "ignore", "nucleo-matcher", - "parking_lot", + "parking_lot 0.12.5", "postcard", "rayon", "redb", @@ -4593,7 +4603,7 @@ version = "0.1.53" dependencies = [ "encoding_rs", "ide-core", - "parking_lot", + "parking_lot 0.12.5", "serde", "serde_json", "tempfile", @@ -4634,7 +4644,7 @@ dependencies = [ "ide-extension", "ide-text", "memchr", - "parking_lot", + "parking_lot 0.12.5", "regex-lite", "serde", "serde_json", @@ -4699,7 +4709,7 @@ dependencies = [ "ide-vfs", "ignore", "lsp-types", - "parking_lot", + "parking_lot 0.12.5", "percent-encoding", "serde", "serde_json", @@ -4739,7 +4749,7 @@ dependencies = [ "jupyter-protocol", "jupyter-zmq-client", "libc", - "parking_lot", + "parking_lot 0.12.5", "serde", "serde_json", "specta", @@ -4759,7 +4769,7 @@ dependencies = [ "dunce", "ide-core", "ide-extension", - "parking_lot", + "parking_lot 0.12.5", "semver", "serde", "serde_json", @@ -4798,7 +4808,7 @@ dependencies = [ "ide-run", "ide-ssh", "ignore", - "parking_lot", + "parking_lot 0.12.5", "serde", "serde_json", "specta", @@ -4816,8 +4826,9 @@ dependencies = [ "ide-build", "ide-core", "ide-language", + "ide-workspace", "libc", - "parking_lot", + "parking_lot 0.12.5", "portable-pty", "quick-xml 0.42.0", "serde", @@ -4899,7 +4910,7 @@ name = "ide-spell" version = "0.1.53" dependencies = [ "ide-core", - "parking_lot", + "parking_lot 0.12.5", "serde", "serde_json", "specta", @@ -4916,7 +4927,7 @@ dependencies = [ "ide-core", "keyring", "keyring-core", - "parking_lot", + "parking_lot 0.12.5", "russh", "russh-sftp", "rustls", @@ -4966,7 +4977,7 @@ version = "0.1.53" dependencies = [ "ide-core", "libc", - "parking_lot", + "parking_lot 0.12.5", "portable-pty", "serde", "specta", @@ -4998,7 +5009,7 @@ dependencies = [ "ide-core", "ide-language", "libc", - "parking_lot", + "parking_lot 0.12.5", "serde", "serde_json", "sha2 0.10.9", @@ -5045,7 +5056,7 @@ dependencies = [ "ide-core", "ignore", "notify", - "parking_lot", + "parking_lot 0.12.5", "rayon", "rustix", "serde", @@ -5086,7 +5097,7 @@ dependencies = [ "ide-core", "ide-text", "ide-vfs", - "parking_lot", + "parking_lot 0.12.5", "semver", "serde", "serde_json", @@ -5096,6 +5107,7 @@ dependencies = [ "toml_edit 0.25.17+spec-1.1.0", "tracing", "uuid", + "winreg 0.56.0", "zip", ] @@ -5239,7 +5251,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" dependencies = [ "io-lifetimes 3.0.1", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -5277,7 +5289,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5777,6 +5789,15 @@ dependencies = [ "scopeguard", ] +[[package]] +name = "lock_api" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.34" @@ -6748,7 +6769,7 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "objc2-web-kit 0.3.2", - "parking_lot", + "parking_lot 0.12.5", "percent-encoding", "reqwest", "security-framework", @@ -6938,8 +6959,18 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ - "lock_api", - "parking_lot_core", + "lock_api 0.4.14", + "parking_lot_core 0.9.12", +] + +[[package]] +name = "parking_lot" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9cf937ca4e1d0b7578784559063422fc39ae7c5a00f02471f2614d5486fd226" +dependencies = [ + "lock_api 0.5.0", + "parking_lot_core 0.10.0", ] [[package]] @@ -6950,7 +6981,19 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "parking_lot_core" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cfff060068cc18aa7815010fcaf80c68c7fb9e85fc7f5c0f9bf142c21d19826" +dependencies = [ + "libc", + "redox_syscall 0.9.5", "smallvec", "windows-link", ] @@ -7401,7 +7444,7 @@ version = "31.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf52d87428247c5aa3760ac8e7d8b13ec7b3579b955a8c3f311668b6860acba5" dependencies = [ - "parking_lot", + "parking_lot 0.12.5", ] [[package]] @@ -7597,6 +7640,15 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "redox_users" version = "0.5.3" @@ -7636,7 +7688,7 @@ dependencies = [ "ahash", "fluent-uri 0.3.2", "once_cell", - "parking_lot", + "parking_lot 0.12.5", "percent-encoding", "serde_json", ] @@ -7970,7 +8022,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -8038,7 +8090,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -8712,7 +8764,7 @@ dependencies = [ "objc2-foundation 0.3.2", "objc2-quartz-core 0.3.2", "raw-window-handle", - "redox_syscall", + "redox_syscall 0.5.18", "tracing", "wasm-bindgen", "web-sys", @@ -8812,7 +8864,7 @@ version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" dependencies = [ - "lock_api", + "lock_api 0.4.14", ] [[package]] @@ -9086,7 +9138,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901" dependencies = [ "new_debug_unreachable", - "parking_lot", + "parking_lot 0.12.5", "phf_shared", "precomputed-hash", ] @@ -9274,7 +9326,7 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "objc2-ui-kit 0.3.2", - "parking_lot", + "parking_lot 0.12.5", "percent-encoding", "raw-window-handle", "tao-macros", @@ -9782,10 +9834,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -9965,7 +10017,7 @@ dependencies = [ "bytes", "libc", "mio", - "parking_lot", + "parking_lot 0.12.5", "pin-project-lite", "signal-hook-registry", "socket2", @@ -11622,7 +11674,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -12420,7 +12472,7 @@ dependencies = [ "log", "num-traits", "once_cell", - "parking_lot", + "parking_lot 0.12.5", "rand 0.9.5", "regex", "scc", diff --git a/Cargo.toml b/Cargo.toml index 5dcaec1d2..db289d58d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -108,7 +108,7 @@ jupyter-zmq-client = { version = "=2.0.0", default-features = false, features = jupyter-protocol = "=2.0.3" zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] } lsp-types = "0.97" -gix = { version = "0.89", default-features = false } +gix = { version = "0.90", default-features = false } portable-pty = "0.9" reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] } diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index 1a9c77b64..504b16d4b 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -6,6 +6,12 @@ [Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md). +## DuckDB symbol + +DuckDB is a trademark of the DuckDB Foundation. The data source icon uses the +light and dark symbols from the [DuckDB Design Manual](https://duckdb.org/design/manual/#logo-usage). +The SVG paths and colors are preserved. See the [DuckDB trademark guidelines](https://duckdb.org/trademark_guidelines.html). + ## Agent logos The `src/ui/openidea/agents/` logos of agents listed in the @@ -149,6 +155,7 @@ languages whose JetBrains icons are not open source (Go, Ruby, Dart, Lua, Zig, Svelte, …). Those using the page-with-corner-badge layout (`goMod`, `goWork`, `dotenv`, `readme`, `lock`, `license`) reuse the page outline of the Apache-2.0 expui `fileTypes/h.svg`; that outline is modified from the original by JetBrains. +`goTest` adds a scaled copy of the Apache-2.0 expui `nodes/test.svg` as its badge. `src/ui/openidea/runConfigurations/springBoot*.svg` (the Spring Boot run configuration leaf) is OpenIDEA's own drawing. diff --git a/crates/ide-agent/src/config.rs b/crates/ide-agent/src/config.rs index 8ea57d5dc..88176a534 100644 --- a/crates/ide-agent/src/config.rs +++ b/crates/ide-agent/src/config.rs @@ -155,13 +155,14 @@ pub(crate) fn is_fast_option(id: &str) -> bool { } /// Whether an option's available values and default belong to the selected model -/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`) +/// (`thought_level`, `context_tier`, and `model_config` options like `context`, `fast` and `service_tier`) /// rather than the provider as a whole. pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool { matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config")) || matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning") || is_fast_option(&o.id) || is_context_option(&o.id) + || o.id == "service_tier" } /// A `configOptions` array; only select options are kept (the UI shows them as dropdowns). @@ -531,6 +532,15 @@ mod tests { assert_eq!(ids(&c), [("allow_all", Some("off")), ("approval", Some("ask"))]); } + #[test] + fn service_tier_is_per_model() { + let options = options_of(&json!({ "configOptions": [ + { "id": "service_tier", "type": "select", "currentValue": "false", + "options": [{ "value": "false" }, { "value": "true" }] } + ] })); + assert!(is_per_model_option(&options[0])); + } + #[test] fn effort_context_and_fast_are_per_model_options() { let mut c = options_of(&json!({ diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 2d83171d6..cc0b08876 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -450,10 +450,42 @@ struct TaskFile { /// The user named the task: its agent's own title updates no longer replace it. #[serde(default, skip_serializing_if = "is_false")] title_renamed: bool, + /// [`NewAgentTask::ephemeral`]: the task file is never written, and new sessions ask the + /// agent not to save their history. + #[serde(default, skip_serializing_if = "is_false")] + ephemeral: bool, + /// Start the first session as a fork of a recorded native one (once). + #[serde(default, skip_serializing_if = "Option::is_none")] + pending_native_fork: Option, +} + +/// A session to start as a fork of the recorded one: its source, and the id the host +/// chooses for the fork (claude); codex assigns its own. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct ForkStart { + source: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + target: Option, +} + +/// A canonical lowercase UUID, the only session id shape either native agent writes. +fn canonical_uuid(value: &str) -> bool { + value.len() == 36 + && value.bytes().enumerate().all(|(index, byte)| { + if matches!(index, 8 | 13 | 18 | 23) { + byte == b'-' + } else { + byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte) + } + }) } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] struct PendingModel { + /// Native Codex intent, including when this model cannot expose a Fast control. + #[serde(default, skip_serializing_if = "Option::is_none")] + retained_service_tier: Option, model: AgentConfigChoice, candidate: Option, options: Vec, @@ -469,6 +501,11 @@ impl PendingModel { }); wanted.push(self.model.clone()); wanted.extend(self.choices.iter().cloned()); + if let Some(choice) = &self.retained_service_tier + && !wanted.iter().any(|c| c.id == choice.id) + { + wanted.push(choice.clone()); + } } } @@ -502,6 +539,10 @@ struct TaskState { pending_rollback: u32, /// The user named the task; see `TaskFile::title_renamed`. title_renamed: bool, + /// [`NewAgentTask::ephemeral`]. + ephemeral: bool, + /// See `TaskFile::pending_native_fork`: cleared once a session is established. + pending_native_fork: Option, /// A turn is running or about to (prompts arriving now are queued). busy: bool, /// Background tasks the agent reported as running (`run_in_background` commands and @@ -527,7 +568,12 @@ impl TaskState { } task.config.retain(|o| !config::is_per_model_option(o)); task.config.extend(pending.options.iter().cloned().map(|mut option| { - if let Some(choice) = pending.choices.iter().find(|choice| choice.id == option.id) { + if let Some(choice) = pending + .choices + .iter() + .chain(pending.retained_service_tier.iter()) + .find(|choice| choice.id == option.id) + { option.current = Some(choice.value.clone()); } option @@ -778,6 +824,14 @@ impl AgentManager { provider::set_builtin_command(&dir, self.shared.env_secrets(), id, command.as_deref()) } + /// Sets the extra arguments of a directly launched built-in ACP agent; empty resets them. + pub fn set_builtin_additional_args(&self, id: &str, args: Vec) -> IdeResult<()> { + let Some(dir) = self.shared.paths.custom_agents_dir.as_deref() else { + return Err(IdeError::unavailable("there is no custom agents directory")); + }; + provider::set_builtin_additional_args(dir, self.shared.env_secrets(), id, args) + } + /// Sets the environment variables built-in `id` starts with; empty clears them. pub fn set_builtin_env(&self, id: &str, env: std::collections::BTreeMap) -> IdeResult<()> { let Some(dir) = self.shared.paths.custom_agents_dir.clone() else { @@ -1023,6 +1077,94 @@ impl AgentManager { subagents: Vec::new(), pending_rollback: 0, title_renamed: true, + ephemeral: false, + pending_native_fork: None, + }; + let handle = Task::restore(file, self.shared.clone()); + self.tasks.write().insert(task.id.clone(), handle.clone()); + handle.emit_task(); + handle.persist(); + Ok(task) + } + + /// Forks a recorded external session into a new task: its first turn continues the + /// recording as the agent's own fork, under an id the host chooses. The session must + /// belong to this project and have been recorded in `cwd`. + pub fn fork_session(&self, provider: &str, session_id: &str, cwd: &Path) -> IdeResult { + if !matches!(provider, "claude" | "codex") { + return Err(IdeError::invalid(format!("cannot fork {provider} sessions"))); + } + if !canonical_uuid(session_id) { + return Err(IdeError::invalid("the recorded session has no canonical id")); + } + let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?; + if self.imported_session_ids().contains(session_id) { + return Err(IdeError::invalid("that session is already a task")); + } + let found = self + .external_sessions() + .into_iter() + .find(|s| s.provider == provider && s.session_id == session_id) + .ok_or_else(|| IdeError::not_found(format!("unknown {provider} session {session_id}")))?; + let recorded = found + .cwd + .map(PathBuf::from) + .filter(|p| p.is_absolute()) + .ok_or_else(|| IdeError::invalid("the recorded session has no working directory"))?; + let canonical = |p: &Path| dunce::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + if canonical(cwd) != canonical(&recorded) { + return Err(IdeError::invalid("the session was recorded in another directory")); + } + let root = self.shared.paths.project_root.clone(); + let config = self.shared.known_config(&spec.id); + let now = now_ms(); + let id = uuid::Uuid::new_v4().simple().to_string(); + // The host names the fork's session id for claude; codex assigns its own. + let target = (provider == "claude").then(|| uuid::Uuid::new_v4().to_string()); + let task = AgentTask { + project_root: Some(IpcPath(root)), + id, + title: found.title, + provider: spec.id.clone(), + model: model_of(&config), + status: AgentStatus::Ready, + isolation: Isolation::Local, + cwd: IpcPath(recorded), + branch: None, + base: None, + base_commit: None, + error: None, + created_ms: now, + updated_ms: now, + config, + commands: self.shared.known_commands(&spec.id), + usage: None, + queue: Vec::new(), + capabilities: self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default(), + resets_ms: None, + retry: None, + background: Box::default(), + mcp_overrides: BTreeMap::new(), + skill_overrides: BTreeMap::new(), + stats: Box::default(), + }; + let file = TaskFile { + task: task.clone(), + session_id: target.clone(), + entries: Vec::new(), + wanted: Vec::new(), + pending_model: None, + pending_switch: None, + before: BTreeMap::new(), + saved: None, + touched: Some(BTreeSet::new()), + turn: None, + turns: Vec::new(), + subagents: Vec::new(), + pending_rollback: 0, + title_renamed: true, + ephemeral: false, + pending_native_fork: Some(ForkStart { source: session_id.to_owned(), target }), }; let handle = Task::restore(file, self.shared.clone()); self.tasks.write().insert(task.id.clone(), handle.clone()); @@ -1151,6 +1293,8 @@ impl AgentManager { subagents: Vec::new(), pending_rollback: 0, title_renamed: false, + ephemeral: req.ephemeral, + pending_native_fork: None, }; let handle = Task::restore(file, self.shared.clone()); handle.state.lock().busy = !req.idle; @@ -1516,6 +1660,8 @@ impl AgentManager { subagents: s.conversation.saved_subagents(), pending_rollback: total - keep, title_renamed: s.title_renamed, + ephemeral: s.ephemeral, + pending_native_fork: None, } }; // Copying may have started the source's agent: it stops again once idle. @@ -2386,7 +2532,7 @@ impl Task { turns.push(Some(Arc::new(last))); } let mut wanted = file.wanted; - let pending_model = file.pending_switch.or_else(|| { + let mut pending_model = file.pending_switch.or_else(|| { let id = file.pending_model?; let index = wanted.iter().position(|choice| choice.id == id)?; let model = wanted.remove(index); @@ -2401,8 +2547,14 @@ impl Task { .and_then(|o| o.values.iter().find(|v| v.value == model.value)) .cloned(); let options = catalog.thought_levels.get(&model.value).cloned().unwrap_or_default(); - Some(PendingModel { model, candidate, options, choices: Vec::new() }) + Some(PendingModel { model, candidate, options, choices: Vec::new(), retained_service_tier: None }) }); + if let Some(pending) = &mut pending_model + && pending.retained_service_tier.is_none() + && shared.spec(&task.provider).is_some_and(|spec| spec.driver == provider::Driver::Codex) + { + pending.retained_service_tier = wanted.iter().find(|c| c.id == "service_tier").cloned(); + } Arc::new(Self { id: task.id.clone(), shared, @@ -2420,6 +2572,8 @@ impl Task { turns, pending_rollback: file.pending_rollback, title_renamed: file.title_renamed, + ephemeral: file.ephemeral, + pending_native_fork: file.pending_native_fork, busy: false, background_tasks: Vec::new(), shell_context: Vec::new(), @@ -2675,7 +2829,9 @@ impl Task { let mut file = self.file.lock(); // Read before the copy: whatever was asked for up to now is in it. let asked = self.saves_asked.load(Ordering::Acquire); - if file.deleted || file.saved >= asked { + // A throwaway task is never written: one its caller couldn't delete (a window closed + // while it ran) is gone after a restart. + if file.deleted || file.saved >= asked || self.state.lock().ephemeral { return; } let copy = { @@ -2695,6 +2851,8 @@ impl Task { subagents: s.conversation.saved_subagents(), pending_rollback: s.pending_rollback, title_renamed: s.title_renamed, + ephemeral: s.ephemeral, + pending_native_fork: s.pending_native_fork.clone(), } }; let bytes = serde_json::to_vec(©); @@ -2975,7 +3133,13 @@ impl Task { .filter(|pending| pending.model.value == value) .map(|pending| pending.choices) .unwrap_or_default(); + let retained_service_tier = self + .shared + .spec(&provider) + .filter(|spec| spec.driver == provider::Driver::Codex) + .and_then(|_| s.wanted.iter().find(|c| c.id == "service_tier").cloned()); s.pending_model = Some(PendingModel { + retained_service_tier, model: AgentConfigChoice { id: target.id, value }, candidate: Some(candidate), options, @@ -3357,66 +3521,116 @@ impl Task { let skills_delivery = self.stage_skills(stage_key(spec.driver), cwd).await; // Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`). let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned(); + let pending_native_fork = self.state.lock().pending_native_fork.clone(); + + let mut opening_params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots); + if spec.driver == provider::Driver::Codex { + let s = self.state.lock(); + let mut wanted = s.wanted.clone(); + if let Some(pending) = pending_model { + pending.apply(&mut wanted, &s.task.config); + } + // Restore intent even when the resumed model cannot expose the Fast control. + if let Some(fast) = + wanted.iter().find(|c| c.id == "service_tier").and_then(|c| c.value.parse::().ok()) + { + opening_params["_meta"]["openidea"]["codexFast"] = json!(fast); + } + } let mut tried_auth = false; let mut session = None; - let start_fresh = self.start_fresh.load(Ordering::Acquire); - if pending_model.is_some() && (saved.is_none() || !can_load || start_fresh) { - return Err(SessionOpenError { - message: "The agent does not support resuming this session.".into(), - allow_acp_fallback: false, - }); - } - if let (Some(id), true, false) = (saved, can_load, start_fresh) { - // The replay goes before what this turn already showed (the user's message). - let shown = self.adopts_replay().then(|| self.take_entries()); - self.replaying.store(true, Ordering::Release); - let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots); - params["sessionId"] = json!(&id); - let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await; - tokio::time::sleep(REPLAY_GRACE).await; - self.replaying.store(false, Ordering::Release); - if let Some(shown) = shown { - if loaded.is_ok() { - self.adopting_replay.store(false, Ordering::Release); - let changed = self.state.lock().conversation.end_turn(None); - self.mark_dirty(changed); - } else { - // A failed load may still have replayed part of it. - self.take_entries(); - } - for entry in shown { - self.push_entry(entry); + if let Some(fork) = pending_native_fork { + if !capabilities.fork { + return Err(SessionOpenError { + message: "the agent can't continue a recorded session".into(), + allow_acp_fallback: false, + }); + } + let mut params = opening_params.clone(); + params["sessionId"] = json!(&fork.source); + if let Some(target) = &fork.target { + match params["_meta"].as_object_mut() { + Some(meta) => { + if let Some(openidea) = meta.entry("openidea").or_insert_with(|| json!({})).as_object_mut() { + openidea.insert("forkSessionId".into(), json!(target)); + } + } + None => params["_meta"] = json!({ "openidea": { "forkSessionId": target } }), } } - match loaded { - Ok(v) => session = Some((id, v)), - // Not silently: a new session would lose the conversation and replace the saved id. - Err(e) => { - tracing::info!("agent task {}: session/load failed: {e}", self.id); - if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) { - return Err(SessionOpenError { message, allow_acp_fallback: false }); + let reply = self + .request_with_auth(&peer, &init, &mut tried_auth, "session/fork", params) + .await + .map_err(|e| SessionOpenError { message: self.describe(e), allow_acp_fallback: false })?; + let id = reply + .get("sessionId") + .and_then(Value::as_str) + .ok_or_else(|| SessionOpenError { + message: "the agent returned no session".into(), + allow_acp_fallback: false, + })? + .to_owned(); + session = Some((id, reply)); + } else { + let start_fresh = self.start_fresh.load(Ordering::Acquire); + if pending_model.is_some() && (saved.is_none() || !can_load || start_fresh) { + return Err(SessionOpenError { + message: "The agent does not support resuming this session.".into(), + allow_acp_fallback: false, + }); + } + if let (Some(id), true, false) = (saved, can_load, start_fresh) { + // The replay goes before what this turn already showed (the user's message). + let shown = self.adopts_replay().then(|| self.take_entries()); + self.replaying.store(true, Ordering::Release); + let mut params = opening_params.clone(); + params["sessionId"] = json!(&id); + let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await; + tokio::time::sleep(REPLAY_GRACE).await; + self.replaying.store(false, Ordering::Release); + if let Some(shown) = shown { + if loaded.is_ok() { + self.adopting_replay.store(false, Ordering::Release); + let changed = self.state.lock().conversation.end_turn(None); + self.mark_dirty(changed); + } else { + // A failed load may still have replayed part of it. + self.take_entries(); } - if pending_model.is_some() { + for entry in shown { + self.push_entry(entry); + } + } + match loaded { + Ok(v) => session = Some((id, v)), + // Not silently: a new session would lose the conversation and replace the saved id. + Err(e) => { + tracing::info!("agent task {}: session/load failed: {e}", self.id); + if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) { + return Err(SessionOpenError { message, allow_acp_fallback: false }); + } + if pending_model.is_some() { + return Err(SessionOpenError { + message: format!( + "Couldn't reopen this conversation's {} session: {}", + spec.name, + self.describe(e) + ), + allow_acp_fallback: false, + }); + } + self.start_fresh.store(true, Ordering::Release); return Err(SessionOpenError { message: format!( - "Couldn't reopen this conversation's {} session: {}", + "Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \ + continue in a new session. The agent won't see the earlier conversation.", spec.name, self.describe(e) ), allow_acp_fallback: false, }); } - self.start_fresh.store(true, Ordering::Release); - return Err(SessionOpenError { - message: format!( - "Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \ - continue in a new session. The agent won't see the earlier conversation.", - spec.name, - self.describe(e) - ), - allow_acp_fallback: false, - }); } } } @@ -3424,7 +3638,10 @@ impl Task { let (session_id, result) = match session { Some(s) => s, None => { - let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots); + let mut params = opening_params; + if self.state.lock().ephemeral { + mark_ephemeral(&mut params); + } let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err( |e| match self.sign_in_error(&e, Some(&sign_in_message)) { Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false }, @@ -3535,7 +3752,10 @@ impl Task { if config::is_per_model_option(&o) && !model_options { continue; } - let already = (known || explicit) && o.current.as_deref() == Some(choice.value.as_str()); + // A displayed tier can be inherited. Preserve an explicit Fast/Standard choice + // even when it currently looks the same, so subsequent turns receive the override. + let already = + o.id != "service_tier" && (known || explicit) && o.current.as_deref() == Some(choice.value.as_str()); if already || !o.values.iter().any(|v| v.value == choice.value) { continue; } @@ -3604,6 +3824,8 @@ impl Task { s.pending_model = None; s.task.capabilities = capabilities; s.session_id = Some(session_id.clone()); + // The recorded session is forked (or the fork resumed): the one-shot intent is spent. + s.pending_native_fork = None; self.start_fresh.store(false, Ordering::Release); // The (re)started process runs nothing yet: whatever it reports next is all of it. s.background_tasks = Vec::new(); @@ -4482,6 +4704,15 @@ fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delive params } +/// `_meta.openidea.ephemeral` of `session/new`: the native drivers start the session without +/// saving it (Claude Code `--no-session-persistence`, Codex `ephemeral` threads). +fn mark_ephemeral(params: &mut Value) { + if !params["_meta"]["openidea"].is_object() { + params["_meta"]["openidea"] = json!({}); + } + params["_meta"]["openidea"]["ephemeral"] = json!(true); +} + fn is_false(b: &bool) -> bool { !*b } diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index a9d7251f6..2ee6c0aaf 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -612,6 +612,9 @@ pub struct AgentProvider { /// Executable and arguments actually launched, without flattening paths containing spaces. pub program: String, pub args: Vec, + /// Settings-managed suffix of `args`; absent for launches that cannot be edited. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub additional_args: Option>, pub default_program: Option, pub default_args: Vec, pub login_hint: Option, @@ -700,6 +703,10 @@ pub struct NewAgentTask { /// `!` command runs in it first. #[serde(default)] pub idle: bool, + /// A throwaway task (Generate Commit Message): it isn't saved, so it doesn't outlive a + /// restart, and the agent keeps no session history of its own for it. + #[serde(default)] + pub ephemeral: bool, } /// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the diff --git a/crates/ide-agent/src/native/claude/mod.rs b/crates/ide-agent/src/native/claude/mod.rs index 4abd90aa0..67e14b8df 100644 --- a/crates/ide-agent/src/native/claude/mod.rs +++ b/crates/ide-agent/src/native/claude/mod.rs @@ -178,6 +178,8 @@ struct Session { additional_dirs: Vec, /// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too). skills_settings: Option, + /// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`. + ephemeral: bool, shim: Weak, st: Mutex, /// Serializes (re)starting the process. @@ -376,6 +378,7 @@ impl Shim { skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from), additional_dirs: additional_dirs(params), skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned), + ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false), shim: Arc::downgrade(self), st: Mutex::new(State { proc: None, @@ -460,24 +463,43 @@ impl Shim { Ok(json!({ "configOptions": session.st.lock().settings.options() })) } "session/fork" => { - let source = self.session(¶ms)?; - let id = new_uuid(false); - let (start, settings) = { - let st = source.st.lock(); - let start = match &st.start { - Start::New { .. } if !st.pending && st.titled_or_prompted() => { - Start::Fork { from: source.id.clone(), id: id.clone(), at: None } - } - Start::New { .. } => Start::New { id: id.clone() }, - Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => { - Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() } - } - _ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None }, - }; - (start, st.settings.clone()) + let source_id = + params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?; + let source = self.sessions.lock().get(source_id).cloned(); + // The host names the fork's session id so the task knows it before the CLI + // starts; only a canonical UUID is accepted. + let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str); + if let Some(target) = requested + && !crate::canonical_uuid(target) + { + return Err(invalid("A fork session id must be a canonical UUID")); + } + let id = requested.map_or_else(|| new_uuid(false), str::to_owned); + if self.sessions.lock().contains_key(&id) { + return Err(invalid(format!("session {id} is already open"))); + } + let cwd = source.as_ref().map_or_else(|| self.cwd_of(¶ms), |session| session.cwd.clone()); + let (start, settings) = match &source { + Some(source) => { + let st = source.st.lock(); + let start = match &st.start { + Start::New { .. } if !st.pending && st.titled_or_prompted() => { + Start::Fork { from: source.id.clone(), id: id.clone(), at: None } + } + Start::New { .. } => Start::New { id: id.clone() }, + Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => { + Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() } + } + _ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None }, + }; + (start, st.settings.clone()) + } + // A recorded session is not open in this connection: the CLI forks it + // from its transcript on disk when the task's first prompt starts it. + None => (Start::Fork { from: source_id.to_owned(), id: id.clone(), at: None }, Settings::default()), }; self.save_pending(&id, Some(&start)); - let session = self.add_session(&id, source.cwd.clone(), start, true, ¶ms); + let session = self.add_session(&id, cwd, start, true, ¶ms); session.st.lock().settings = settings; let options = session.st.lock().settings.options(); Ok(json!({ "sessionId": id, "configOptions": options })) @@ -712,6 +734,9 @@ impl Session { if let Some(settings) = &self.skills_settings { args.extend(["--settings".to_owned(), settings.clone()]); } + if self.ephemeral { + args.push("--no-session-persistence".to_owned()); + } args.extend(start.args()); let launch = Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() }; diff --git a/crates/ide-agent/src/native/claude/tests.rs b/crates/ide-agent/src/native/claude/tests.rs index b7a6f5851..6807fddb1 100644 --- a/crates/ide-agent/src/native/claude/tests.rs +++ b/crates/ide-agent/src/native/claude/tests.rs @@ -464,6 +464,7 @@ async fn replay_simple() { let args = r.cli.launched.lock()[0].clone(); assert!(args.windows(2).any(|w| w == ["--session-id", r.session.as_str()]), "{args:?}"); assert!(args.contains(&"--permission-prompt-tool".to_owned())); + assert!(!args.contains(&"--no-session-persistence".to_owned())); let user = r.sent(0).into_iter().find(|m| m["type"] == "user").unwrap(); assert_eq!(user["message"]["content"][0]["text"], "Reply with exactly: hello there"); } @@ -652,6 +653,84 @@ async fn replay_resume() { assert!(args.windows(2).any(|w| w == ["--resume", r.session.as_str()]), "{args:?}"); } +#[tokio::test(flavor = "multi_thread")] +async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() { + /// Registering a fork must not start a process: its first prompt does. + struct NoLaunch; + impl Cli for NoLaunch { + fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result { + panic!("session/fork must not launch the CLI") + } + } + + let config = tempfile::tempdir().unwrap(); + let pending = tempfile::tempdir().unwrap(); + let h = Harness::connect( + Arc::new(NoLaunch), + config.path().to_path_buf(), + pending.path().to_path_buf(), + std::env::temp_dir(), + Vec::new(), + ) + .await; + let source = "11111111-1111-4111-8111-111111111111"; + let target = "22222222-2222-4222-8222-222222222222"; + let reply = h + .request( + "session/fork", + json!({ + "sessionId": source, + "cwd": h.cwd, + "mcpServers": [], + "_meta": { "openidea": { "forkSessionId": target } } + }), + ) + .await + .unwrap(); + assert_eq!(reply["sessionId"], target); + // The host chose this id for the fork: the next process must fork the recorded + // session under exactly it. + let saved: Value = + serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap(); + assert_eq!(saved, json!({ "fork": source, "id": target, "at": null })); +} + +#[tokio::test(flavor = "multi_thread")] +async fn fork_session_rejects_a_requested_id_that_is_not_canonical() { + struct NoLaunch; + impl Cli for NoLaunch { + fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result { + panic!("no process") + } + } + + let config = tempfile::tempdir().unwrap(); + let pending = tempfile::tempdir().unwrap(); + let h = Harness::connect( + Arc::new(NoLaunch), + config.path().to_path_buf(), + pending.path().to_path_buf(), + std::env::temp_dir(), + Vec::new(), + ) + .await; + for rejected in ["../../x", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", ""] { + let error = h + .request( + "session/fork", + json!({ + "sessionId": "11111111-1111-4111-8111-111111111111", + "cwd": h.cwd, + "mcpServers": [], + "_meta": { "openidea": { "forkSessionId": rejected } } + }), + ) + .await + .expect_err("only a canonical id may name the fork"); + assert!(error.to_string().contains("canonical"), "{rejected}: {error}"); + } +} + // ---------- recording ---------- /// Passes the real CLI's stdio through, keeping what went over it. @@ -1350,3 +1429,16 @@ fn additional_directories_are_read_from_the_session_params() { assert_eq!(additional_dirs(¶ms), ["/w/web", "/w/docs"]); assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty()); } + +#[tokio::test(flavor = "multi_thread")] +async fn an_ephemeral_session_is_not_saved() { + let cli = replay_cli(load_fixture("simple")); + let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let cwd_path = std::fs::canonicalize(cwd.path()).unwrap(); + let h = + Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await; + let params = json!({ "cwd": h.cwd, "mcpServers": [], "_meta": { "openidea": { "ephemeral": true } } }); + h.request("session/new", params).await.unwrap(); + let args = cli.launched.lock()[0].clone(); + assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}"); +} diff --git a/crates/ide-agent/src/native/codex/mod.rs b/crates/ide-agent/src/native/codex/mod.rs index 4606631fd..0c963b133 100644 --- a/crates/ide-agent/src/native/codex/mod.rs +++ b/crates/ide-agent/src/native/codex/mod.rs @@ -108,7 +108,7 @@ pub(crate) async fn discover( let options = translate::config_options(&models, &settings); let levels = crate::config::options_of(&json!({ "configOptions": options })) .into_iter() - .filter(|o| o.category.as_deref() == Some("thought_level")) + .filter(|o| matches!(o.category.as_deref(), Some("thought_level" | "model_config"))) .collect(); (model.id.clone(), levels) }) @@ -492,8 +492,14 @@ impl CodexShim { self.prepare_project_trust(params).await; let mut request = json!({ "cwd": params.get("cwd") }); apply_thread_config(params, &mut request); + // Not written to `~/.codex/sessions`, so it isn't listed among the past threads. + if params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool) == Some(true) { + request["ephemeral"] = json!(true); + } let result = self.call("thread/start", request).await?; - let (id, options) = self.open_thread(&result, &models, None); + let mut settings = Settings::of(&result, &models); + settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool); + let (id, options) = self.open_thread(&result, &models, Some(settings)); if id.is_empty() { return Err(error(codes::INTERNAL_ERROR, "codex started no thread")); } @@ -510,7 +516,9 @@ impl CodexShim { let mut request = json!({ "threadId": id, "cwd": params.get("cwd") }); apply_thread_config(params, &mut request); let result = self.call("thread/resume", request).await?; - let (_, options) = self.open_thread(&result, &models, None); + let mut settings = Settings::of(&result, &models); + settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool); + let (_, options) = self.open_thread(&result, &models, Some(settings)); let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone()); let thread = result.get("thread").unwrap_or(&Value::Null); for update in translate::history(thread, cwd.as_deref()) { @@ -613,6 +621,9 @@ impl CodexShim { if let Some(effort) = &s.effort { request["effort"] = json!(effort); } + if let Some(tier) = s.service_tier_override(&models) { + request["serviceTier"] = json!(tier); + } } self.call("turn/start", request).await } @@ -1595,3 +1606,6 @@ fn mcp_text(response: &Value) -> String { .collect::>(); format!("MCP servers:\n{}", lines.join("\n")) } + +#[cfg(test)] +mod reconnect_tests; diff --git a/crates/ide-agent/src/native/codex/reconnect_tests.rs b/crates/ide-agent/src/native/codex/reconnect_tests.rs new file mode 100644 index 000000000..794d32971 --- /dev/null +++ b/crates/ide-agent/src/native/codex/reconnect_tests.rs @@ -0,0 +1,217 @@ +//! User-facing task operations through the native shim, with a local app-server stand-in. +use super::*; +use crate::{AgentManager, AgentPrompt, AgentStatus, Isolation, NewAgentTask}; + +#[derive(Default)] +struct Runtime { + models: Mutex>, + hide_a: std::sync::atomic::AtomicBool, + turns: Mutex>, + tiers: Mutex>, + servers: Mutex>, +} +struct Connection { + runtime: Arc, + peer: OnceLock, +} +impl Handler for Connection { + fn on_notification(&self, _: &str, _: Value) {} + fn on_request(&self, method: &str, p: Value) -> Result { + match method { + "initialize" => Ok(json!({})), + "model/list" => { + let mut data = vec![json!({"id":"b", "model":"b", "serviceTiers":[]})]; + if !self.runtime.hide_a.swap(false, std::sync::atomic::Ordering::SeqCst) { + data.insert(0, json!({"id":"a", "model":"a", "isDefault":true, "serviceTiers":[{"id":"fast"}]})); + } + Ok(json!({"data":data})) + } + "config/read" => Ok(json!({"layers":[]})), + "skills/list" => Ok(json!({"data":[]})), + "thread/start" | "thread/resume" => { + let mut models = self.runtime.models.lock(); + let id = p["threadId"].as_str().map(str::to_owned).unwrap_or_else(|| format!("s{}", models.len())); + let model = models.entry(id.clone()).or_insert_with(|| "a".into()).clone(); + Ok(json!({"thread":{"id":id,"name":"fixture","turns":[]}, "model":model, + "serviceTier":self.runtime.tiers.lock().get(&id).cloned().unwrap_or(json!("fast"))})) + } + "turn/start" => { + let id = p["threadId"].as_str().unwrap(); + self.runtime.models.lock().insert(id.into(), p["model"].as_str().unwrap().into()); + if let Some(tier) = p.get("serviceTier") { + self.runtime.tiers.lock().insert(id.into(), tier.clone()); + } + self.runtime.turns.lock().push(p.clone()); + self.peer + .get() + .unwrap() + .notify( + "turn/completed", + json!({"threadId":id, + "turn":{"id":"t","status":"completed"}}), + ) + .unwrap(); + Ok(json!({"turn":{"id":"t"}})) + } + _ => Err((codes::METHOD_NOT_FOUND, method.into())), + } + } +} +fn manager(dir: &Path, runtime: Arc) -> AgentManager { + let agents = dir.join("agents"); + crate::provider::set_builtin_command(&agents, None, "codex", Some("/missing/fixture-codex")).unwrap(); + AgentManager::with_connector( + crate::AgentPaths { + project_root: dir.into(), + store_dir: dir.join("store"), + worktrees_dir: dir.join("worktrees"), + models_file: dir.join("models.json"), + custom_agents_dir: Some(agents), + home_dir: Some(dir.into()), + env_secrets: None, + catalogs: Arc::default(), + }, + tokio::runtime::Handle::current(), + Arc::new(move |spec, _, client, _| { + assert_eq!(spec.driver, crate::provider::Driver::Codex); + let handler = Arc::new(Connection { runtime: runtime.clone(), peer: OnceLock::new() }); + let (a, b) = tokio::io::duplex(1 << 20); + let (r, w) = tokio::io::split(b); + let server = Peer::connect_framed(r, w, handler.clone(), Framing::Lines); + handler.peer.set(server.clone()).ok().unwrap(); + runtime.servers.lock().push(server); + attach(client, |events| { + let (r, w) = tokio::io::split(a); + Ok(Peer::connect_framed(r, w, events, Framing::Lines)) + }) + }), + ) +} +fn prompt() -> AgentPrompt { + AgentPrompt { text: "fixture".into(), ..Default::default() } +} +async fn ready(mgr: &AgentManager, id: &str) { + tokio::time::timeout(Duration::from_secs(10), async { + loop { + let task = mgr.task(id).unwrap(); + let (status, busy) = { + let s = task.state.lock(); + (s.task.status, s.busy) + }; + assert_ne!(status, AgentStatus::Failed); + if status == AgentStatus::Ready && !busy { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); +} +async fn send(mgr: &AgentManager, id: &str) { + mgr.prompt(id, prompt(), false).await.unwrap(); + ready(mgr, id).await; +} +#[tokio::test(flavor = "multi_thread")] +async fn explicit_tier_survives_standard_only_reconnect_before_immediate_prompt() { + for late_model in [0, 1, 2, 3] { + for choice in [Some("true"), Some("false"), None] { + let tmp = tempfile::tempdir().unwrap(); + let runtime = Arc::new(Runtime::default()); + let mgr = manager(tmp.path(), runtime.clone()); + let task = mgr + .create(NewAgentTask { + provider: "codex".into(), + prompt: prompt(), + isolation: Isolation::Local, + ..Default::default() + }) + .await + .unwrap(); + ready(&mgr, &task.id).await; + let catalog_config = mgr.task(&task.id).unwrap().state.lock().task.config.clone(); + if let Some(value) = choice { + mgr.set_config(&task.id, "service_tier", value.into()).await.unwrap(); + } + send(&mgr, &task.id).await; + assert_eq!( + runtime.turns.lock().last().unwrap().get("serviceTier"), + choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref() + ); + mgr.set_config(&task.id, "model", "b".into()).await.unwrap(); + assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier")); + send(&mgr, &task.id).await; + assert_eq!( + runtime.turns.lock().last().unwrap().get("serviceTier"), + choice.map(|_| json!("default")).as_ref() + ); + mgr.shutdown(); + drop(mgr); + runtime.hide_a.store(late_model >= 2, std::sync::atomic::Ordering::SeqCst); + let mut mgr = manager(tmp.path(), runtime.clone()); + send(&mgr, &task.id).await; // Reconnect while still on Standard-only B. + assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier")); + assert_eq!( + runtime.turns.lock().last().unwrap().get("serviceTier"), + choice.map(|_| json!("default")).as_ref() + ); + if late_model != 0 { + // Catalog knows A, but the session's picker has not received it yet. + let current = mgr.task(&task.id).unwrap(); + let mut s = current.state.lock(); + let catalog = serde_json::from_value( + json!({"fingerprint":"fixture", "schema":2, "config":catalog_config, "thoughtLevels":{"a":catalog_config.iter().filter(|o|crate::config::is_per_model_option(o)).collect::>() }}), + ) + .unwrap(); + mgr.shared + .known + .lock() + .entry("codex".into()) + .or_default() + .catalogs + .insert(mgr.shared.root_key(), catalog); + s.task.config.iter_mut().find(|o| o.id == "model").unwrap().values.retain(|v| v.value != "a"); + } + mgr.set_config(&task.id, "model", "a".into()).await.unwrap(); + if late_model == 3 { + // An older saved pending switch has no retained intent field. + mgr.task(&task.id).unwrap().state.lock().pending_model.as_mut().unwrap().retained_service_tier = None; + mgr.shutdown(); + mgr = manager(tmp.path(), runtime.clone()); + } + let displayed = mgr + .task(&task.id) + .unwrap() + .state + .lock() + .snapshot() + .config + .iter() + .find(|o| o.id == "service_tier") + .unwrap() + .current + .clone(); + assert_eq!(displayed.as_deref(), Some(choice.unwrap_or("true"))); + send(&mgr, &task.id).await; // No sleeps/retries between selecting A and submitting. + assert_eq!( + runtime.turns.lock().last().unwrap().get("serviceTier"), + choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref() + ); + let other = mgr + .create(NewAgentTask { + provider: "codex".into(), + prompt: prompt(), + isolation: Isolation::Local, + ..Default::default() + }) + .await + .unwrap(); + ready(&mgr, &other.id).await; + assert!( + runtime.turns.lock().last().unwrap().get("serviceTier").is_none(), + "choices must not leak to another task" + ); + mgr.shutdown(); + } + } +} diff --git a/crates/ide-agent/src/native/codex/tests.rs b/crates/ide-agent/src/native/codex/tests.rs index 6e8821e0d..4e7394a8e 100644 --- a/crates/ide-agent/src/native/codex/tests.rs +++ b/crates/ide-agent/src/native/codex/tests.rs @@ -110,7 +110,8 @@ for line in sys.stdin: cursor = request['params']['cursor'] model = 'one' if cursor is None else 'two' result = {'data': [{'id': model, 'isDefault': cursor is None, - 'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}]}], + 'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}], + 'serviceTiers': [{'id': 'fast', 'name': 'Fast', 'description': ''}] if cursor is None else []}], 'nextCursor': 'second-page' if cursor is None else None} else: raise RuntimeError('must not create a thread or prompt: ' + method) @@ -125,6 +126,7 @@ for line in sys.stdin: driver: crate::provider::Driver::Codex, command: script.to_string_lossy().into_owned(), args: Vec::new(), + additional_args_len: 0, env: Vec::new(), login_hint: String::new(), source: crate::AgentSource::Builtin, @@ -138,6 +140,9 @@ for line in sys.stdin: .collect(); assert_eq!(models, ["one", "two"]); assert_eq!(found.levels.keys().map(String::as_str).collect::>(), ["one", "two"]); + assert!(found.config.iter().any(|o| o.id == SERVICE_TIER)); + assert!(found.levels["one"].iter().any(|o| o.id == SERVICE_TIER)); + assert!(found.levels["two"].iter().all(|o| o.id != SERVICE_TIER)); let requests = std::fs::read_to_string(tmp.path().join("requests")).unwrap(); let requests: Vec = requests.lines().map(|line| serde_json::from_str(line).unwrap()).collect(); assert_eq!( @@ -162,6 +167,72 @@ for line in sys.stdin: // ---- Pure translations ------------------------------------------------------------- +#[test] +fn fast_is_offered_only_when_the_model_advertises_it() { + for capability in [ + json!({ "additionalSpeedTiers": ["fast"] }), + json!({ "serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }] }), + json!({ "serviceTiers": [{ "id": "priority", "name": "Fast", "description": "" }] }), + ] { + let mut model = json!({ "id": "supported", "isDefault": true }); + model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone()); + let models = models_of(&json!({ "data": [model, { "id": "unsupported" }] })); + let mut settings = Settings::of(&json!({}), &models); + let options = config_options(&models, &settings); + let fast = options.as_array().unwrap().iter().find(|o| o["id"] == "service_tier").expect("Fast option"); + assert_eq!(fast["category"], "model_config"); + assert_eq!(fast["currentValue"], "false"); + assert!(settings.set(&models, "service_tier", "true").is_ok()); + assert!(settings.set(&models, "service_tier", "invalid").is_err()); + let selected = settings.service_tier_override(&models).map(str::to_owned); + settings.set(&models, "model", "unsupported").unwrap(); + assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier")); + assert!(settings.set(&models, "service_tier", "true").is_err()); + assert_eq!(settings.service_tier_override(&models), Some("default")); + settings.set(&models, "model", "supported").unwrap(); + assert_eq!(settings.service_tier_override(&models), selected.as_deref()); + let options = config_options(&models, &settings); + assert_eq!( + options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"], + "true" + ); + } + for capability in [json!({}), json!({ "additionalSpeedTiers": [] }), json!({ "serviceTiers": [] })] { + let mut model = json!({ "id": "old", "isDefault": true }); + model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone()); + let models = models_of(&json!({ "data": [model] })); + let settings = Settings::of(&json!({}), &models); + assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier")); + } +} + +#[test] +fn fast_defaults_do_not_become_user_overrides() { + let models = models_of(&json!({ "data": [{ + "id": "m", "isDefault": true, "defaultServiceTier": "fast", + "serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }] + }] })); + for (reported, current) in [ + (json!({}), "true"), + (json!({ "serviceTier": null }), "false"), + (json!({ "serviceTier": "fast" }), "true"), + (json!({ "serviceTier": "priority" }), "true"), + (json!({ "serviceTier": "default" }), "false"), + ] { + let mut settings = Settings::of(&reported, &models); + let options = config_options(&models, &settings); + assert_eq!( + options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"], + current + ); + assert_eq!(settings.service_tier_override(&models), None); + settings.set(&models, SERVICE_TIER, "true").unwrap(); + assert_eq!(settings.service_tier_override(&models), Some("fast")); + settings.set(&models, SERVICE_TIER, "false").unwrap(); + assert_eq!(settings.service_tier_override(&models), Some("default")); + } +} + fn models() -> Vec { models_of(&json!({"data": [ {"id": "big", "model": "big", "displayName": "Big", "description": "d", "hidden": false, "isDefault": true, @@ -185,6 +256,8 @@ fn settings_follow_the_thread_and_the_models() { Settings { model: "big".into(), effort: Some("low".into()), + service_tier: None, + fast_override: None, mode: Mode::Ask, collaboration_mode: DEFAULT_COLLABORATION_MODE.into(), collaboration_mode_override: None, @@ -648,6 +721,7 @@ enum Scenario { Steer, Simple, MultiTurn, + ServiceTier { first: Option, second: Option }, Approvals, UsageLimit, Subagent, @@ -666,6 +740,7 @@ impl Scenario { Scenario::Steer => "steer", Scenario::Simple => "simple", Scenario::MultiTurn => "multi_turn", + Scenario::ServiceTier { .. } => "multi_turn", Scenario::Approvals => "approvals", Scenario::UsageLimit => "usage_limit", Scenario::Subagent => "subagent", @@ -772,6 +847,16 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa out.push(("effort", request(acp, "session/set_config_option", set(EFFORT, "high")).await)); out.push(("second", request(acp, "session/prompt", prompt("Reply with: two")).await)); } + Scenario::ServiceTier { first, second } => { + for (label, choice) in [("first", first), ("second", second)] { + if let Some(fast) = choice { + request(acp, "session/set_config_option", set(SERVICE_TIER, if fast { "true" } else { "false" })) + .await + .expect("the model advertises Fast"); + } + out.push((label, request(acp, "session/prompt", prompt("Reply with: hi")).await)); + } + } Scenario::Approvals => { client.answers.lock().extend([Some("accept"), None]); out.push(("prompt", request(acp, "session/prompt", prompt("Run `touch b.txt`, then write a.txt.")).await)); @@ -1304,6 +1389,44 @@ fn thread_names_are_the_first_line_of_the_reply() { assert_eq!(thread_name(&"x".repeat(100)).map(|n| n.chars().count()), Some(80)); } +#[tokio::test(flavor = "multi_thread")] +async fn fast_selection_reaches_the_first_and_next_turn_and_standard_clears_it() { + for (first, second, expected) in [ + (Some(true), Some(false), [Some("fast"), Some("default")]), + (Some(false), Some(true), [Some("default"), Some("fast")]), + (Some(true), None, [Some("fast"), Some("fast")]), + (None, None, [None, None]), + ] { + let scenario = Scenario::ServiceTier { first, second }; + let mut transcript = load(scenario.file()); + for (out, frame) in &mut transcript.frames { + if *out { + continue; + } + if let Some(models) = frame.pointer_mut("/result/data").and_then(Value::as_array_mut) { + for model in models { + model["serviceTiers"] = json!([{ "id": "fast", "name": "Fast", "description": "" }]); + model["defaultServiceTier"] = json!("fast"); + } + } + if frame.pointer("/result/thread").is_some() { + frame["result"]["serviceTier"] = json!("fast"); + } + } + let (results, _client, frames, _meta, _codex) = replay_transcript(scenario, transcript).await; + assert!(result(&results, "first").is_ok()); + assert!(result(&results, "second").is_ok()); + let starts = sent(&frames, "turn/start"); + assert_eq!(starts.len(), 2); + for (start, expected) in starts.iter().zip(expected) { + assert_eq!(start["params"].get("serviceTier"), expected.map(|value| json!(value)).as_ref()); + assert!(start["params"].get("serviceTierForTurn").is_none()); + } + assert!(sent(&frames, "turn/settings/update").is_empty()); + assert!(sent(&frames, "config/value/write").is_empty()); + } +} + #[tokio::test(flavor = "multi_thread")] async fn settings_apply_to_the_next_turn() { let (results, client, frames, _) = replay(Scenario::MultiTurn).await; @@ -1891,3 +2014,40 @@ fn workspace_roots_join_the_thread_roots() { apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request); assert!(request.get("runtimeWorkspaceRoots").is_none()); } + +#[tokio::test(flavor = "multi_thread")] +async fn an_ephemeral_session_starts_an_ephemeral_thread() { + for ephemeral in [true, false] { + let tmp = tempfile::tempdir().unwrap(); + let cwd = tmp.path().to_string_lossy().into_owned(); + let server = Arc::new(TrustServer { + cwd: cwd.clone(), + disabled: false, + other_project: false, + write_error: false, + overridden: false, + calls: Mutex::default(), + }); + let client = Arc::new(Client::default()); + let (ours, theirs) = tokio::io::duplex(1 << 16); + let (read, write) = tokio::io::split(theirs); + let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines); + let acp = attach(client.clone(), |events| { + let (read, write) = tokio::io::split(ours); + Ok(Peer::connect_framed(read, write, events, Framing::Lines)) + }) + .unwrap(); + request(&acp, "initialize", json!({})).await.unwrap(); + let mut params = json!({"cwd": cwd, "mcpServers": []}); + if ephemeral { + params["_meta"] = json!({"openidea": {"ephemeral": true}}); + } + request(&acp, "session/new", params).await.unwrap(); + let calls = server.calls.lock(); + let (_, start) = calls.iter().find(|(m, _)| m == "thread/start").unwrap(); + assert_eq!(start.get("ephemeral"), ephemeral.then_some(&Value::Bool(true)), "{start}"); + drop(calls); + acp.kill(); + native.kill(); + } +} diff --git a/crates/ide-agent/src/native/codex/translate.rs b/crates/ide-agent/src/native/codex/translate.rs index de572d83b..63f3a5d7d 100644 --- a/crates/ide-agent/src/native/codex/translate.rs +++ b/crates/ide-agent/src/native/codex/translate.rs @@ -97,6 +97,8 @@ pub(super) struct ModelInfo { /// `(effort, description)`. pub efforts: Vec<(String, String)>, pub default_effort: Option, + pub fast_tier: Option, + pub default_service_tier: Option, pub is_default: bool, pub hidden: bool, } @@ -123,6 +125,22 @@ pub(super) fn models_of(list: &Value) -> Vec { }) .collect(), default_effort: str_of(m, "defaultReasoningEffort"), + fast_tier: m + .get("serviceTiers") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|tier| tier.get("id").and_then(Value::as_str)) + .chain( + m.get("additionalSpeedTiers") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str), + ) + .find(|tier| is_fast_tier(tier)) + .map(str::to_owned), + default_service_tier: str_of(m, "defaultServiceTier"), is_default: m.get("isDefault").and_then(Value::as_bool) == Some(true), hidden: m.get("hidden").and_then(Value::as_bool) == Some(true), id, @@ -137,6 +155,9 @@ pub(super) struct Settings { /// A model id from `model/list`, or the one the thread reported. pub model: String, pub effort: Option, + pub service_tier: Option, + /// No choice preserves the runtime's default; false explicitly selects Standard. + pub fast_override: Option, pub mode: Mode, /// Codex's Default/Plan collaboration mode. It is sent with each turn because it is /// part of the turn contract rather than the sandbox permission mode above. @@ -158,6 +179,12 @@ impl Settings { let mut s = Settings { model, effort: str_of(result, "reasoningEffort"), + service_tier: match result.get("serviceTier") { + // A live thread can explicitly report Standard even when the catalog defaults to Fast. + Some(Value::Null) => Some("default".into()), + _ => str_of(result, "serviceTier"), + }, + fast_override: None, mode: Mode::of( result.get("approvalPolicy").unwrap_or(&Value::Null), result.get("sandbox").unwrap_or(&Value::Null), @@ -205,6 +232,16 @@ impl Settings { } self.effort = Some(value.to_owned()); } + SERVICE_TIER => { + if !models.iter().any(|m| m.id == self.model && m.fast_tier.is_some()) { + return Err(format!("{} has no Fast mode", self.model)); + } + self.fast_override = Some(match value { + "true" => true, + "false" => false, + _ => return Err(format!("unknown Fast mode {value}")), + }); + } MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?, COLLABORATION_MODE => { if !matches!(value, DEFAULT_COLLABORATION_MODE | PLAN_COLLABORATION_MODE) { @@ -217,16 +254,32 @@ impl Settings { } Ok(()) } + + /// `turn/start.serviceTier`: omission inherits; "default" explicitly resets Fast. + pub fn service_tier_override<'a>(&self, models: &'a [ModelInfo]) -> Option<&'a str> { + match self.fast_override { + Some(true) => Some( + models.iter().find(|m| m.id == self.model).and_then(|m| m.fast_tier.as_deref()).unwrap_or("default"), + ), + Some(false) => Some("default"), + None => None, + } + } } pub(super) const MODEL: &str = "model"; pub(super) const EFFORT: &str = "reasoning_effort"; +pub(super) const SERVICE_TIER: &str = "service_tier"; pub(super) const MODE: &str = "mode"; pub(super) const COLLABORATION_MODE: &str = "collaboration_mode"; pub(super) const DEFAULT_COLLABORATION_MODE: &str = "default"; pub(super) const PLAN_COLLABORATION_MODE: &str = "plan"; -/// ACP `configOptions`: model, reasoning effort (for models that have it) and mode. +fn is_fast_tier(tier: &str) -> bool { + matches!(tier, "fast" | "priority") +} + +/// ACP `configOptions`: model, its supported settings and session modes. pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value { let mut model_values: Vec = models .iter() @@ -253,6 +306,16 @@ pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value { "currentValue": effort, "options": values, })); } + if let Some(model) = models.iter().find(|m| m.id == s.model && m.fast_tier.is_some()) { + let fast = s.fast_override.unwrap_or_else(|| { + s.service_tier.as_deref().or(model.default_service_tier.as_deref()).is_some_and(is_fast_tier) + }); + out.push(json!({ + "id": SERVICE_TIER, "name": "Fast", "category": "model_config", "type": "select", + "currentValue": if fast { "true" } else { "false" }, + "options": [select_value("false", "Standard", None), select_value("true", "Fast", None)], + })); + } out.push(json!({ "id": MODE, "name": "Mode", "category": "mode", "type": "select", "currentValue": s.mode.id(), "options": Mode::ALL.iter().map(|m| select_value(m.id(), m.name(), Some(m.description()))).collect::>(), diff --git a/crates/ide-agent/src/provider.rs b/crates/ide-agent/src/provider.rs index 36b59865b..c347c3882 100644 --- a/crates/ide-agent/src/provider.rs +++ b/crates/ide-agent/src/provider.rs @@ -33,6 +33,8 @@ pub(crate) struct ProviderSpec { pub driver: Driver, pub command: String, pub args: Vec, + /// Number of trailing arguments added by the built-in agent's settings. + pub additional_args_len: usize, pub env: Vec<(String, String)>, /// How to sign in when the agent reports it needs authentication. pub login_hint: String, @@ -96,6 +98,7 @@ fn builtins() -> Vec { driver: *driver, command: cmd[0].into(), args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(), + additional_args_len: 0, env: Vec::new(), login_hint: (*hint).into(), source: AgentSource::Builtin, @@ -347,16 +350,28 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool { UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec) } +fn uses_package_runner(command: &str) -> bool { + matches!(command, "npx" | "bunx" | "uvx") +} + +fn allows_additional_args(builtin: &ProviderSpec, driver: Driver) -> bool { + builtin.driver == Driver::Acp && driver == Driver::Acp && !uses_package_runner(&builtin.command) +} + /// Public launch metadata, keeping the built-in defaults separate from agent-file overrides. pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider { let builtin = builtin_spec(&spec.id); let reason = if matches!(spec.source, AgentSource::Registry { .. }) { Some(AgentCommandReadOnlyReason::Registry) } else if let Some(default) = &builtin { - matches!(default.command.as_str(), "npx" | "bunx" | "uvx").then_some(AgentCommandReadOnlyReason::PackageRunner) + uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner) } else { Some(AgentCommandReadOnlyReason::CustomAgent) }; + let additional_args = builtin + .as_ref() + .filter(|b| reason.is_none() && allows_additional_args(b, spec.driver)) + .map(|_| spec.args[spec.args.len() - spec.additional_args_len..].to_vec()); AgentProvider { id: spec.id.clone(), name: spec.name.clone(), @@ -366,6 +381,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider { .join(" "), program: spec.command.clone(), args: spec.args.clone(), + additional_args, default_program: builtin.as_ref().map(|b| b.command.clone()), default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(), login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))), @@ -391,7 +407,24 @@ pub(crate) fn set_builtin_command( command: Option<&str>, ) -> IdeResult<()> { update_builtin(custom_dir, secrets, id, |agent, builtin| { - agent.command = command.unwrap_or(&builtin.command).to_owned() + agent.command = command.unwrap_or(&builtin.command).to_owned(); + Ok(()) + }) +} + +/// Appends arguments to a directly launched built-in ACP agent; an empty list resets them. +pub(crate) fn set_builtin_additional_args( + custom_dir: &Path, + secrets: Option<&dyn EnvSecrets>, + id: &str, + args: Vec, +) -> IdeResult<()> { + update_builtin(custom_dir, secrets, id, |agent, builtin| { + if !allows_additional_args(builtin, agent.driver) { + return Err(IdeError::invalid(format!("{id} does not support additional arguments"))); + } + agent.additional_args = args; + Ok(()) }) } @@ -427,7 +460,10 @@ pub(crate) fn set_builtin_env( return agent.write(&file).map_err(Into::into); } } - update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env) + update_builtin(custom_dir, secrets, id, |agent, _| { + agent.env = env; + Ok(()) + }) } /// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed. @@ -435,7 +471,7 @@ fn update_builtin( custom_dir: &Path, secrets: Option<&dyn EnvSecrets>, id: &str, - change: impl FnOnce(&mut CustomAgent, &ProviderSpec), + change: impl FnOnce(&mut CustomAgent, &ProviderSpec) -> IdeResult<()>, ) -> IdeResult<()> { let Some(builtin) = builtin_spec(id) else { return Err(IdeError::invalid(format!("{id} is not a built-in agent"))); @@ -449,6 +485,7 @@ fn update_builtin( driver: builtin.driver, command: builtin.command.clone(), args: builtin.args.clone(), + additional_args: Vec::new(), env: BTreeMap::new(), registry: None, } @@ -456,11 +493,12 @@ fn update_builtin( if agent.registry.is_some() { return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry"))); } - change(&mut agent, &builtin); + change(&mut agent, &builtin)?; if agent.command == builtin.command && agent.name.as_deref() == Some(builtin.name.as_str()) && agent.driver == builtin.driver && agent.args == builtin.args + && agent.additional_args.is_empty() && agent.env.is_empty() { match std::fs::remove_file(&file) { @@ -502,6 +540,7 @@ pub(crate) fn save_custom( driver: Driver::Acp, command: input.command.clone(), args: input.args.clone(), + additional_args: Vec::new(), env: input.env.clone(), registry: None, } @@ -572,6 +611,7 @@ pub(crate) fn import_acp( driver: Driver::Acp, command: server.command, args: server.args, + additional_args: Vec::new(), env: server.env, registry: None, } @@ -615,6 +655,9 @@ pub(crate) struct CustomAgent { pub command: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub args: Vec, + /// Kept separate from `args` so Settings reset does not erase a hand-written launch line. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub additional_args: Vec, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub env: BTreeMap, /// Set when the agent was installed from the ACP Registry. @@ -746,6 +789,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) driver: agent.driver, command: agent.command, args: agent.args, + additional_args_len: 0, env, login_hint: "Sign in with the agent's own command line first.".into(), source, @@ -763,6 +807,10 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) spec.args = crate::native::copilot::headless_args(&spec.args); } if spec.source == AgentSource::Custom { + if allows_additional_args(existing, spec.driver) { + spec.additional_args_len = agent.additional_args.len(); + spec.args.extend(agent.additional_args); + } spec.source = AgentSource::Builtin; } *existing = spec; @@ -1043,6 +1091,53 @@ mod tests { set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err(); } + #[test] + fn additional_args_append_and_reset_without_replacing_agent_file_overrides() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let omp = || load(Some(root), None).into_iter().find(|spec| spec.id == "omp").unwrap(); + assert_eq!(describe(&omp()).additional_args, Some(vec![])); + set_builtin_additional_args(root, None, "omp", vec!["--extra".into()]).unwrap(); + assert_eq!(omp().args, ["acp", "--extra"]); + set_builtin_additional_args(root, None, "omp", vec![]).unwrap(); + assert!(!root.join("omp.toml").exists()); + + let file = root.join("omp.toml"); + std::fs::write( + &file, + "name = \"My OMP\"\ncommand = \"/opt/my tools/omp\"\nargs = [\"acp\", \"--manual\"]\n[env]\nKEEP = \"value\"\n", + ) + .unwrap(); + let original = omp(); + let extra = vec!["--label".into(), "two words".into(), String::new()]; + set_builtin_additional_args(root, None, "omp", extra.clone()).unwrap(); + let configured = omp(); + assert_eq!(configured.args, ["acp", "--manual", "--label", "two words", ""]); + assert_eq!(describe(&configured).additional_args, Some(extra)); + set_builtin_additional_args(root, None, "omp", vec![]).unwrap(); + assert_eq!(omp(), original); + } + + #[test] + fn additional_args_cannot_modify_managed_or_non_acp_launches() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::write( + root.join("gemini.toml"), + "command = \"gemini\"\nargs = [\"--experimental-acp\"]\n[registry]\nid = \"gemini\"\nversion = \"1\"\n", + ) + .unwrap(); + std::fs::write(root.join("mine.toml"), "command = \"mine\"\n").unwrap(); + std::fs::write(root.join("omp.toml"), "command = \"omp\"\ndriver = \"codex\"\n").unwrap(); + let before = load(Some(root), None); + for id in ["gemini", "mine", "omp", "codex", "claude-acp"] { + let spec = before.iter().find(|spec| spec.id == id).unwrap(); + assert!(describe(spec).additional_args.is_none()); + assert!(set_builtin_additional_args(root, None, id, vec!["--extra".into()]).is_err()); + } + assert_eq!(load(Some(root), None), before); + } + #[test] fn registry_copilot_allows_only_the_github_account_override() { let dir = tempfile::tempdir().unwrap(); @@ -1052,6 +1147,7 @@ mod tests { driver: Driver::Acp, command: "/tools/copilot".into(), args: vec!["--acp".into()], + additional_args: Vec::new(), env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]), registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }), } @@ -1108,6 +1204,7 @@ mod tests { driver: Driver::Acp, command: "amp".into(), args: vec![], + additional_args: Vec::new(), env: BTreeMap::new(), registry: Some(RegistryRef { id: "amp-acp".into(), version: "1.0.0".into() }), } @@ -1133,6 +1230,7 @@ mod tests { driver: Driver::Claude, command: "/old/claude".into(), args: vec![], + additional_args: Vec::new(), env: BTreeMap::new(), registry: None, }; @@ -1186,6 +1284,7 @@ mod tests { driver: Driver::Acp, command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(), args: vec!["acp".into()], + additional_args: Vec::new(), env: BTreeMap::from([("K".to_owned(), "v".to_owned())]), registry: Some(RegistryRef { id: "amp-acp".into(), version: "0.10.0".into() }), }; diff --git a/crates/ide-agent/src/registry.rs b/crates/ide-agent/src/registry.rs index 212ebc8fc..c8dc7d350 100644 --- a/crates/ide-agent/src/registry.rs +++ b/crates/ide-agent/src/registry.rs @@ -443,7 +443,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { /// Installs (or updates to) the registry's current version of `id`, streaming progress /// through `emit`, and points the agent file at it. -pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> { +/// Installs agent `id`; an npm package retries against the public npm registry when the +/// configured one misses it only with `public_npm_fallback`. +pub fn install( + paths: &RegistryPaths, + id: &str, + public_npm_fallback: bool, + cancel: &CancellationToken, + emit: Emit, +) -> IdeResult<()> { let id = canonical_id(id); // The saved index is what the user picked from; fetch only when there is none. let text = match fs::read_to_string(&paths.cache_file) { @@ -455,9 +463,14 @@ pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit .iter() .find(|e| e.id == id) .ok_or_else(|| IdeError::not_found(format!("{id} is not in the ACP Registry")))?; - install_entry(paths, entry, Platform::current(), &on_path, cancel, emit) + let npm_installer = + move |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| { + install_npm(p, entry, dir, platform, public_npm_fallback, cancel, emit) + }; + install_entry_with(paths, entry, Platform::current(), &on_path, &npm_installer, cancel, emit) } +#[cfg(test)] fn install_entry( paths: &RegistryPaths, entry: &Entry, @@ -466,7 +479,10 @@ fn install_entry( cancel: &CancellationToken, emit: Emit, ) -> IdeResult<()> { - install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit) + let npm_installer = |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| { + install_npm(p, entry, dir, platform, true, cancel, emit) + }; + install_entry_with(paths, entry, platform, on_path, &npm_installer, cancel, emit) } type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult; @@ -550,6 +566,7 @@ fn install_entry_with( driver: Driver::Acp, command: exe.to_string_lossy().into_owned(), args, + additional_args: Vec::new(), env, registry: Some(RegistryRef { id: entry.id.clone(), version: entry.version.clone() }), }; @@ -662,20 +679,23 @@ fn install_npm( entry: &Entry, dir: &Path, platform: Platform, + public_fallback: bool, cancel: &CancellationToken, emit: Emit, ) -> IdeResult { let (name, _) = split_npm_spec(&p.package); let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?; - install_npm_with(&npm, p, entry, dir, platform, cancel, emit) + install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit) } +#[allow(clippy::too_many_arguments)] fn install_npm_with( npm: &Path, p: &Package, entry: &Entry, dir: &Path, platform: Platform, + public_fallback: bool, cancel: &CancellationToken, emit: Emit, ) -> IdeResult { @@ -703,6 +723,7 @@ fn install_npm_with( }, &specs, false, + public_fallback, cancel, emit, )?; @@ -941,6 +962,7 @@ mod tests { driver: Driver::Acp, command: "/x".into(), args: vec![], + additional_args: Vec::new(), env: BTreeMap::new(), registry: Some(RegistryRef { id: id.into(), version: version.into() }), }; @@ -1002,7 +1024,7 @@ mod tests { #[cfg(unix)] #[test] - fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() { + fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss_unless_registries_are_configured_only() { let dir = tempfile::tempdir().unwrap(); let install_dir = dir.path().join("acme/1.2.0"); fs::create_dir_all(&install_dir).unwrap(); @@ -1041,8 +1063,8 @@ esac ]}"#; let entry = parse(index).unwrap().remove(0); let pkg = entry.distribution.npx.as_ref().unwrap(); - let exe = - install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap(); + let exe = install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, true, &CancellationToken::new(), &|_| {}) + .unwrap(); let calls: Vec = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect(); assert_eq!(calls.len(), 2, "{calls:?}"); assert!(!calls[0].contains("--registry="), "{calls:?}"); @@ -1050,6 +1072,15 @@ esac assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}"); assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp")); assert!(exe.is_file()); + // Only the configured registries: the miss is the error, and npmjs is never asked. + let only = dir.path().join("acme-only/1.2.0"); + fs::create_dir_all(&only).unwrap(); + let err = + install_npm_with(&npm, pkg, &entry, &only, MAC_ARM, false, &CancellationToken::new(), &|_| {}).unwrap_err(); + let calls: Vec = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect(); + assert_eq!(calls.len(), 3, "{calls:?}"); + assert!(!calls[2].contains("--registry="), "{calls:?}"); + assert!(err.message.contains("notarget"), "{err:?}"); } #[test] @@ -1168,6 +1199,7 @@ esac driver: Driver::Acp, command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(), args: vec!["--acp".into()], + additional_args: Vec::new(), env: BTreeMap::new(), registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.104".into() }), } diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 86c727970..dac9d4998 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -63,6 +63,8 @@ struct FakeAgent { session_steering: bool, /// Records the `mcpServers` array passed to `session/new`, `session/load`, and `session/fork`. mcp_calls: Mutex)>>, + /// The params of every `session/fork`, in order. + forks: Mutex>, /// The content blocks of each `session/prompt`. prompts: Mutex>, } @@ -175,6 +177,9 @@ impl Handler for FakeAgent { }) .unwrap_or_default(); self.mcp_calls.lock().push((method.to_owned(), names)); + if params.pointer("/_meta/openidea/ephemeral") == Some(&json!(true)) { + self.calls.lock().push("ephemeral".into()); + } } let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned(); match method { @@ -203,7 +208,11 @@ impl Handler for FakeAgent { "modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]}, "configOptions": options})) } - "session/fork" => Ok(json!({"sessionId": "s2"})), + "session/fork" => { + self.forks.lock().push(params.clone()); + let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str); + Ok(json!({ "sessionId": requested.unwrap_or("s2") })) + } "_openidea/stop_task" => { self.calls.lock().push(format!("{method} {}", params["taskId"])); Ok(json!({})) @@ -642,6 +651,32 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() { restored.shutdown(); } +#[tokio::test(flavor = "multi_thread")] +async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() { + let tmp = tempfile::tempdir().unwrap(); + for ephemeral in [true, false] { + let agent = Arc::new(FakeAgent::default()); + let mgr = manager(tmp.path(), agent.clone()); + let task = mgr + .create(NewAgentTask { + prompt: text("Write a commit message"), + provider: "claude".into(), + isolation: Isolation::Local, + ephemeral, + ..Default::default() + }) + .await + .unwrap(); + wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await; + assert_eq!(agent.calls.lock().iter().any(|c| c == "ephemeral"), ephemeral); + mgr.shutdown(); + // The caller never deleted it (its window closed): only a saved task comes back. + let restored = manager(tmp.path(), Arc::new(FakeAgent::default())); + assert_eq!(restored.task(&task.id).is_ok(), !ephemeral); + restored.shutdown(); + } +} + #[cfg(unix)] #[tokio::test(flavor = "multi_thread")] async fn claude_commands_share_catalog_discovery_and_persist_results() { @@ -2773,6 +2808,128 @@ async fn forks_rollbacks_and_steering() { restored.shutdown(); } +const NATIVE_SOURCE: &str = "11111111-1111-4111-8111-111111111111"; +const NATIVE_TARGET: &str = "22222222-2222-4222-8222-222222222222"; + +/// Plants a recorded claude transcript for `session_id` under the project's escaped folder. +fn plant_claude_session(mgr: &AgentManager, root: &Path, session_id: &str) { + let config = root.join("claude-config"); + mgr.set_builtin_env( + "claude", + [("CLAUDE_CONFIG_DIR".to_string(), config.to_string_lossy().into_owned())].into_iter().collect(), + ) + .unwrap(); + mgr.reload_providers(); + let escaped: String = + root.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect(); + let transcript = config.join("projects").join(escaped).join(format!("{session_id}.jsonl")); + std::fs::create_dir_all(transcript.parent().unwrap()).unwrap(); + std::fs::write( + &transcript, + format!( + "{}\n", + json!({ + "type": "user", + "uuid": "u1", + "parentUuid": null, + "message": {"role": "user", "content": "fix the login bug"}, + "cwd": root.to_string_lossy(), + }) + ), + ) + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn fork_session_starts_a_ready_task_as_the_recorded_session_s_fork() { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + let mgr = manager(tmp.path(), agent.clone()); + plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE); + + let task = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap(); + assert_eq!(task.provider, "claude"); + assert_eq!(task.status, AgentStatus::Ready); + assert_eq!(task.isolation, Isolation::Local); + + mgr.prompt(&task.id, text("again"), true).await.unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + + let forks = agent.forks.lock().clone(); + assert_eq!(forks.len(), 1, "one fork start"); + assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE); + let target = forks[0]["_meta"]["openidea"]["forkSessionId"].as_str().unwrap(); + assert!(canonical_uuid(target), "the host chooses a canonical fork id: {target}"); + assert_ne!(target, NATIVE_SOURCE); + assert!( + !agent.calls.lock().iter().any(|call| call == "session/new" || call == "session/load"), + "the task forks the recorded session instead of starting or loading another" + ); + assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(target)); + mgr.shutdown(); +} + +/// Plants a recorded codex rollout for `session_id` under the home `.codex/sessions` tree. +fn plant_codex_session(root: &Path, session_id: &str) { + let dir = root.join(".codex").join("sessions").join("2026").join("11").join("23"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join(format!("rollout-{session_id}.jsonl")), + format!( + "{}\n{}\n", + json!({"type": "session_meta", "payload": {"id": session_id, "cwd": root.to_string_lossy()}}), + json!({"type": "event_msg", "payload": {"type": "user_message", "message": "fix the login bug"}}) + ), + ) + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn fork_session_uses_the_id_codex_assigns() { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + let mgr = manager(tmp.path(), agent.clone()); + plant_codex_session(tmp.path(), NATIVE_SOURCE); + + let task = mgr.fork_session("codex", NATIVE_SOURCE, tmp.path()).unwrap(); + assert_eq!(task.status, AgentStatus::Ready); + mgr.prompt(&task.id, text("again"), true).await.unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + + let forks = agent.forks.lock().clone(); + assert_eq!(forks.len(), 1); + assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE); + assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "codex names its own fork"); + assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2")); + mgr.shutdown(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn fork_session_rejects_invalid_input_before_starting() { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + let mgr = manager(tmp.path(), agent.clone()); + plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE); + + // Non-native provider, malformed id, unknown session, wrong directory. + let cases: [(&str, &str, &Path, ide_core::error::ErrorKind); 4] = [ + ("gemini", NATIVE_SOURCE, tmp.path(), ide_core::error::ErrorKind::InvalidInput), + ("claude", "not-a-uuid", tmp.path(), ide_core::error::ErrorKind::InvalidInput), + ("claude", NATIVE_TARGET, tmp.path(), ide_core::error::ErrorKind::NotFound), + ("claude", NATIVE_SOURCE, Path::new("/elsewhere"), ide_core::error::ErrorKind::InvalidInput), + ]; + for (index, (provider, id, cwd, kind)) in cases.into_iter().enumerate() { + let error = mgr.fork_session(provider, id, cwd).unwrap_err(); + assert_eq!(error.kind, kind, "case {index}: {error}"); + } + // A session already held by a task cannot be forked again. + mgr.import_session("claude", NATIVE_SOURCE).unwrap(); + let error = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap_err(); + assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput, "{error}"); + assert!(agent.calls.lock().is_empty(), "no process may start"); + mgr.shutdown(); +} + #[tokio::test(flavor = "multi_thread")] async fn usage_limits_and_late_settings() { let tmp = tempfile::tempdir().unwrap(); @@ -3045,6 +3202,46 @@ async fn rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_compl restored.shutdown(); } +#[tokio::test(flavor = "multi_thread")] +async fn explicit_service_tier_reaches_the_session_even_when_it_matches_the_reported_default() { + for value in [None, Some("false"), Some("true")] { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + *agent.extra_options.lock() = vec![json!({ + "id": "service_tier", "name": "Fast", "category": "model_config", "type": "select", + "currentValue": value.unwrap_or("true"), + "options": [{"value": "false"}, {"value": "true"}] + })]; + let mgr = manager(tmp.path(), agent.clone()); + let task = mgr + .create(NewAgentTask { + prompt: text("again"), + provider: "codex".into(), + config: value + .map(|value| vec![AgentConfigChoice { id: "service_tier".into(), value: value.into() }]) + .unwrap_or_default(), + isolation: Isolation::Local, + ..Default::default() + }) + .await + .unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + let calls = agent.calls.lock(); + let prompt = calls.iter().position(|call| call == "session/prompt").unwrap(); + if let Some(value) = value { + let setting = calls + .iter() + .position(|call| call == &format!("session/set_config_option \"{value}\"")) + .expect("an explicit tier must not be mistaken for an inherited default"); + assert!(setting < prompt); + } else { + assert!(!calls.iter().any(|call| call == "session/set_config_option")); + } + drop(calls); + mgr.shutdown(); + } +} + #[tokio::test(flavor = "multi_thread")] async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() { for (effort, applied) in [("medium", true), ("high", false)] { @@ -5421,6 +5618,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() { mcp_overrides: BTreeMap::from([("slack".into(), false)]), idle: false, skill_overrides: BTreeMap::new(), + ephemeral: false, }) .await .unwrap(); @@ -5483,6 +5681,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl ("tdd".into(), AgentSkillMode::Auto), ("noisy".into(), AgentSkillMode::Off), ]), + ephemeral: false, }) .await .unwrap(); @@ -5626,6 +5825,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails() mcp_overrides: BTreeMap::new(), idle: false, skill_overrides: BTreeMap::new(), + ephemeral: false, }) .await .unwrap(); @@ -5652,6 +5852,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails() mcp_overrides: BTreeMap::new(), idle: false, skill_overrides: BTreeMap::new(), + ephemeral: false, }) .await .unwrap(); diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs index 80a112125..e67f9080e 100644 --- a/crates/ide-build/src/compile/mod.rs +++ b/crates/ide-build/src/compile/mod.rs @@ -9,6 +9,7 @@ mod modules; mod parse; mod single; mod structure; +mod tsc_watch; mod up_to_date; pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint}; @@ -23,6 +24,7 @@ pub use structure::{ StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan, structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts, }; +pub use tsc_watch::{tsc_watch, tsc_watch_roots}; pub use up_to_date::{menu_up_to_date, record_menu_build}; use crate::process::{self, Stream}; @@ -812,6 +814,11 @@ pub fn run( /// Per-file editor / Problems diagnostics of the messages that have a position. pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap> { + diagnostics_from(messages, DIAGNOSTICS_SOURCE) +} + +/// [`diagnostics`] reported by `source`. +pub fn diagnostics_from(messages: &[BuildMessage], source: &str) -> BTreeMap> { let mut out: BTreeMap> = BTreeMap::new(); for m in messages { let (Some(path), Some(range)) = (&m.path, m.range) else { continue }; @@ -819,11 +826,11 @@ pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap) -> Vec { + let referenced: BTreeSet = found.iter().flat_map(|c| references(c)).collect(); + let mut roots: Vec = found.into_iter().filter(|c| !referenced.contains(c)).collect(); + roots.sort_by_key(|c| (c.components().count(), c.clone())); + roots.truncate(MAX_ROOTS); + roots +} + +fn read_json(path: &Path) -> Option { + let text = std::fs::read_to_string(path).ok()?; + serde_json::from_str(&ide_core::jsonc::strip(&text)).ok() +} + +/// The configurations `config` lists in `references` (a folder means its `tsconfig.json`). +fn references(config: &Path) -> Vec { + let Some(json) = read_json(config) else { return Vec::new() }; + let dir = config.parent().unwrap_or(Path::new("")); + let refs = json.get("references").and_then(|r| r.as_array()).into_iter().flatten(); + refs.filter_map(|r| r.get("path")?.as_str()) + .map(|p| { + let p = super::normalize(&dir.join(p)); + if p.extension().is_some_and(|e| e == "json") { p } else { p.join("tsconfig.json") } + }) + .collect() +} + +/// A configuration and the ones it `extends`, most derived first, each with its folder (the +/// base of its relative paths). A package base (`@tsconfig/node20/tsconfig.json`) is looked up +/// in `node_modules` above the configuration. +fn chain(config: &Path) -> Vec<(PathBuf, Value)> { + let mut out = Vec::new(); + let mut next = vec![config.to_path_buf()]; + // A cycle or a deep chain ends here. + while let Some(path) = next.pop().filter(|_| out.len() < 16) { + let Some(json) = read_json(&path) else { continue }; + let dir = path.parent().unwrap_or(Path::new("")).to_path_buf(); + let bases: Vec = match json.get("extends") { + Some(Value::String(s)) => vec![s.clone()], + Some(Value::Array(a)) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(), + _ => Vec::new(), + }; + // Later bases override earlier ones: visit them first. + next.extend(bases.iter().filter_map(|b| resolve_base(&dir, b))); + out.push((dir, json)); + } + out +} + +fn resolve_base(dir: &Path, base: &str) -> Option { + let with_json = |p: PathBuf| { + if p.is_dir() { + p.join("tsconfig.json") + } else if p.extension().is_some_and(|e| e == "json") { + p + } else { + let mut s = p.into_os_string(); + s.push(".json"); + PathBuf::from(s) + } + }; + if base.starts_with('.') || Path::new(base).is_absolute() { + return Some(with_json(super::normalize(&dir.join(base)))); + } + dir.ancestors().map(|a| with_json(a.join("node_modules").join(base))).find(|p| p.is_file()) +} + +/// The first value of `key` (a top-level key, or `compilerOptions.`) along `chain`, with the +/// folder it is relative to. +fn lookup<'a>(chain: &'a [(PathBuf, Value)], key: &str) -> Option<(&'a Path, &'a Value)> { + chain.iter().find_map(|(dir, json)| { + let value = match key.strip_prefix("compilerOptions.") { + Some(option) => json.get("compilerOptions")?.get(option)?, + None => json.get(key)?, + }; + Some((dir.as_path(), value)) + }) +} + +/// The scratch copy of `config` for `tsc -b`: the real configuration with its outputs and +/// `.tsbuildinfo` in `scratch` (file ``), referencing the scratch copies `refs`. Settings that +/// default relative to the configuration's own folder are spelled out, since the copy lives +/// elsewhere: the files (`**/*`), their exclusions (`node_modules`, the output folder) and the +/// `rootDir` of a composite project. +fn scratch_config(config: &Path, scratch: &Path, n: usize, refs: &[PathBuf]) -> Value { + let chain = chain(config); + let dir = config.parent().unwrap_or(Path::new("")); + let out = scratch.join(n.to_string()); + let mut options = json!({ "outDir": out, "tsBuildInfoFile": scratch.join(format!("{n}.tsbuildinfo")) }); + if lookup(&chain, "compilerOptions.declarationDir").is_some() { + options["declarationDir"] = json!(out); + } + if lookup(&chain, "compilerOptions.outFile").is_some() { + options["outFile"] = json!(out.join("out.js")); + } + if lookup(&chain, "compilerOptions.composite").is_some_and(|(_, v)| v == &json!(true)) + && lookup(&chain, "compilerOptions.rootDir").is_none() + { + options["rootDir"] = json!(dir); + } + let mut copy = json!({ + "extends": config, + "compilerOptions": options, + "references": refs.iter().map(|r| json!({ "path": r })).collect::>(), + }); + if lookup(&chain, "include").is_none() && lookup(&chain, "files").is_none() { + copy["include"] = json!([dir.join("**/*")]); + } + if lookup(&chain, "exclude").is_none() { + let mut exclude = vec![dir.join("node_modules")]; + if let Some((base, Value::String(out_dir))) = lookup(&chain, "compilerOptions.outDir") { + exclude.push(super::normalize(&base.join(out_dir))); + } + copy["exclude"] = json!(exclude); + } + copy +} + +/// The `tsc` arguments that watch `config` without writing into the project, writing the +/// scratch configurations a solution needs into `scratch`. +fn watch_args(config: &Path, scratch: &Path) -> std::io::Result> { + let path = |p: &Path| p.to_string_lossy().into_owned(); + let mut args: Vec = if references(config).is_empty() { + let name = config.file_name().map_or_else(|| "tsconfig.json".into(), |n| n.to_string_lossy().into_owned()); + let info = path(&scratch.join("tsconfig.tsbuildinfo")); + ["--noEmit", "-p", &name, "--incremental", "--tsBuildInfoFile", &info].map(String::from).to_vec() + } else { + // Every configuration the solution reaches gets a number: the solution 0, then in order. + let mut numbers: BTreeMap = BTreeMap::from([(config.to_path_buf(), 0)]); + let mut queue = vec![config.to_path_buf()]; + let mut i = 0; + while i < queue.len() { + let current = queue[i].clone(); + let refs: Vec = references(¤t) + .into_iter() + .map(|r| { + let next = numbers.len(); + let n = *numbers.entry(r.clone()).or_insert_with(|| { + queue.push(r); + next + }); + scratch.join(format!("{n}.json")) + }) + .collect(); + let copy = scratch_config(¤t, scratch, numbers[¤t], &refs); + std::fs::write(scratch.join(format!("{}.json", numbers[¤t])), copy.to_string())?; + i += 1; + } + vec!["-b".into(), path(&scratch.join("0.json"))] + }; + args.extend(["--watch", "--pretty", "false", "--preserveWatchOutput"].map(String::from)); + Ok(args) +} + +/// The project's own `tsc` (`node_modules/.bin` from the configuration's folder up to `root`). +fn local_tsc(root: &Path, dir: &Path) -> Option { + dir.ancestors() + .take_while(|d| d.starts_with(root)) + .find_map(|d| ide_core::tool_path::find_command("tsc", d.join("node_modules/.bin").as_os_str(), dir)) +} + +/// The messages of one compilation at a time: tsc ends each with +/// `… - Found 2 errors. Watching for file changes.` `tsc -b` reports the errors of every +/// project of the solution that has some, rebuilt this time or not ("out of date because it had +/// errors"), so each compilation's list replaces the last. +#[derive(Default)] +struct Compilations { + parser: Option, + raws: Vec, +} + +impl Compilations { + fn feed(&mut self, line: &str) -> Option> { + let parser = self.parser.get_or_insert_with(|| OutputParser::new(Format::Tsc)); + if line.contains("Watching for file changes.") { + self.raws.extend(parser.finish()); + return Some(std::mem::take(&mut self.raws)); + } + self.raws.extend(parser.feed(line).messages); + None + } +} + +/// A scratch folder of this process for `config`, removed when dropped. +struct Scratch(PathBuf); + +impl Scratch { + fn new(config: &Path) -> std::io::Result { + use std::hash::{Hash, Hasher}; + let mut hash = std::collections::hash_map::DefaultHasher::new(); + config.hash(&mut hash); + let dir = std::env::temp_dir().join("openidea-tsc-watch").join(format!( + "{}-{:016x}", + std::process::id(), + hash.finish() + )); + // Fresh: a `.tsbuildinfo` left by an earlier run would make tsc skip unchanged projects. + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir)?; + Ok(Scratch(dir)) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// Runs the project's `tsc --watch` on `config` until `cancel` fires or tsc exits, handing the +/// messages of every finished compilation (all of them, an empty list when it passes) to +/// `on_compilation`. Not found when the project has no TypeScript of its own. +pub fn tsc_watch( + root: &Path, + config: &Path, + cancel: &CancellationToken, + mut on_compilation: impl FnMut(Vec), +) -> IdeResult<()> { + let dir = config.parent().ok_or_else(|| IdeError::invalid("no tsconfig folder"))?; + let tsc = local_tsc(root, dir).ok_or_else(|| IdeError::not_found("no local typescript"))?; + let scratch = Scratch::new(config)?; + let args = watch_args(config, &scratch.0)?; + let paths = PathMap::new(root); + let mut compilations = Compilations::default(); + let program = tsc.to_string_lossy(); + process::run_bounded(&program, &args, dir, &BTreeMap::new(), cancel, |_, line| { + if let Some(raws) = compilations.feed(line) { + // Fresh file texts each time: the files changed since the last compilation. + let mut lines = Lines::default(); + on_compilation(raws.into_iter().map(|r| resolve(r, dir, &paths, &mut lines)).collect()); + } + })?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(dir: &Path, rel: &str, text: &str) { + let p = dir.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, text).unwrap(); + } + + #[test] + fn roots_are_the_configurations_no_other_one_references() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + // A solution with references (one by folder, one by file), plus an unrelated package. + write( + root, + "tsconfig.json", + r#"{ "files": [], // solution + "references": [{ "path": "./packages/a" }, { "path": "packages/b/tsconfig.json" },] }"#, + ); + write(root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#); + write(root, "packages/b/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#); + write(root, "tools/cli/tsconfig.json", "{}"); + let found = ["tools/cli", "packages/b", "", "packages/a"].map(|d| root.join(d).join("tsconfig.json")); + assert_eq!(tsc_watch_roots(found.to_vec()), [root.join("tsconfig.json"), root.join("tools/cli/tsconfig.json")]); + } + + #[test] + fn a_solution_is_checked_through_scratch_copies_of_its_configurations() { + let tmp = tempfile::tempdir().unwrap(); + let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch")); + std::fs::create_dir_all(&scratch).unwrap(); + write( + &root, + "tsconfig.json", + r#"{"files": [], "references": [{"path": "./packages/a"}, {"path": "./packages/b"}]}"#, + ); + // a: composite, every setting by default. + write(&root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#); + // b: references a, settles its files, outputs and root in a shared base. + write( + &root, + "packages/b/tsconfig.json", + r#"{"extends": "../../tsconfig.base", "references": [{"path": "../a"}], "compilerOptions": {"outFile": "b.js"}}"#, + ); + write( + &root, + "tsconfig.base.json", + r#"{"compilerOptions": {"composite": true, "rootDir": ".", "outDir": "dist", "declarationDir": "types"}, + "include": ["packages/*/src"]}"#, + ); + let args = watch_args(&root.join("tsconfig.json"), &scratch).unwrap(); + let s = |p: &str| scratch.join(p).to_string_lossy().into_owned(); + assert_eq!(args, ["-b", &s("0.json"), "--watch", "--pretty", "false", "--preserveWatchOutput"]); + let copy = |n: usize| read_json(&scratch.join(format!("{n}.json"))).unwrap(); + let path = |p: &Path| json!(p); + assert_eq!( + copy(0), + json!({ + "extends": path(&root.join("tsconfig.json")), + "compilerOptions": {"outDir": path(&scratch.join("0")), "tsBuildInfoFile": s("0.tsbuildinfo")}, + "references": [{"path": s("1.json")}, {"path": s("2.json")}], + "exclude": [path(&root.join("node_modules"))], + }) + ); + let a = root.join("packages/a"); + assert_eq!( + copy(1), + json!({ + "extends": path(&a.join("tsconfig.json")), + "compilerOptions": { + "outDir": path(&scratch.join("1")), "tsBuildInfoFile": s("1.tsbuildinfo"), "rootDir": path(&a), + }, + "references": [], + "include": [path(&a.join("**/*"))], + "exclude": [path(&a.join("node_modules"))], + }) + ); + let b = root.join("packages/b"); + assert_eq!( + copy(2), + json!({ + "extends": path(&b.join("tsconfig.json")), + "compilerOptions": { + "outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"), + "declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2/out.js")), + }, + "references": [{"path": s("1.json")}], + "exclude": [path(&b.join("node_modules")), path(&root.join("dist"))], + }) + ); + } + + #[test] + fn a_composite_package_base_gets_its_root_folder() { + let tmp = tempfile::tempdir().unwrap(); + let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch")); + write(&root, "node_modules/@acme/tsconfig/base.json", r#"{"compilerOptions": {"composite": true}}"#); + write(&root, "app/tsconfig.json", r#"{"extends": "@acme/tsconfig/base", "include": ["src"]}"#); + let copy = scratch_config(&root.join("app/tsconfig.json"), &scratch, 3, &[]); + assert_eq!(copy["compilerOptions"]["rootDir"], json!(root.join("app"))); + assert_eq!(copy.get("include"), None, "the files come from the real configuration"); + } + + #[test] + fn each_compilation_reports_its_own_messages() { + // `tsc --noEmit --watch --pretty false --preserveWatchOutput`, as printed. + let output = "\ +2:14:08 PM - Starting compilation in watch mode... + +2:14:09 PM - Found 0 errors. Watching for file changes. +2:14:12 PM - File change detected. Starting incremental compilation... + +src/b.ts(1,37): error TS2322: Type 'string' is not assignable to type 'number'. +src/c.ts(2,1): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. + Type 'string' is not assignable to type 'number'. + +2:14:12 PM - Found 2 errors. Watching for file changes. +2:14:15 PM - File change detected. Starting incremental compilation... + +2:14:15 PM - Found 0 errors. Watching for file changes."; + let mut compilations = Compilations::default(); + let found: Vec)>> = output + .lines() + .filter_map(|l| compilations.feed(l)) + .map(|raws| raws.into_iter().map(|r| (r.path.unwrap_or_default(), r.code)).collect()) + .collect(); + assert_eq!( + found, + [ + vec![], + vec![("src/b.ts".into(), Some("TS2322".into())), ("src/c.ts".into(), Some("TS2345".into()))], + vec![] + ] + ); + } + + #[cfg(unix)] + #[test] + fn the_projects_tsc_reports_until_cancelled() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write(root, "app/tsconfig.json", "{}"); + write(root, "app/src/b.ts", "export const b: number = a;\n"); + // A watcher that prints one compilation and keeps running, like `tsc --watch`. + write( + root, + "node_modules/.bin/tsc", + "#!/bin/sh\necho \"$@\" > args.txt\n\ + echo 'src/b.ts(1,26): error TS2322: Type string is not assignable to type number.'\n\ + echo '1:00:00 PM - Found 1 error. Watching for file changes.'\nexec sleep 30\n", + ); + let bin = root.join("node_modules/.bin/tsc"); + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap(); + let cancel = CancellationToken::new(); + let mut compilations = Vec::new(); + let started = std::time::Instant::now(); + let result = tsc_watch(root, &root.join("app/tsconfig.json"), &cancel, |messages| { + compilations.push(messages); + cancel.cancel(); + }); + assert_eq!(result.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled); + assert!(started.elapsed().as_secs() < 10, "cancelling stops the watcher"); + let [messages] = &compilations[..] else { panic!("{compilations:?}") }; + let paths: Vec<_> = messages.iter().map(|m| (m.path.clone().map(PathBuf::from), m.range)).collect(); + let at = |l, c| ide_core::Pos::new(l, c); + assert_eq!(paths, [(Some(root.join("app/src/b.ts")), Some(ide_core::Range::new(at(0, 25), at(0, 26))))]); + let args = std::fs::read_to_string(root.join("app/args.txt")).unwrap(); + let (check, rest) = args.trim().split_once(" --tsBuildInfoFile ").unwrap(); + assert_eq!(check, "--noEmit -p tsconfig.json --incremental"); + let (info, watch) = rest.split_once(' ').unwrap(); + assert_eq!(watch, "--watch --pretty false --preserveWatchOutput"); + // The `.tsbuildinfo` goes to a scratch folder outside the project, gone with the watcher. + let scratch = Path::new(info).parent().unwrap(); + assert!(scratch.starts_with(std::env::temp_dir()) && !scratch.starts_with(root), "{info}"); + assert!(!scratch.exists()); + } + + #[test] + fn no_local_typescript_runs_nothing() { + let tmp = tempfile::tempdir().unwrap(); + write(tmp.path(), "tsconfig.json", "{}"); + let err = tsc_watch(tmp.path(), &tmp.path().join("tsconfig.json"), &CancellationToken::new(), |_| { + panic!("no compilation without typescript") + }) + .unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound); + } +} diff --git a/crates/ide-core/src/editor_settings.rs b/crates/ide-core/src/editor_settings.rs index 181c2f8b5..e99fd1130 100644 --- a/crates/ide-core/src/editor_settings.rs +++ b/crates/ide-core/src/editor_settings.rs @@ -486,6 +486,25 @@ pub struct LanguageCodeStyle { /// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. #[serde(skip_serializing_if = "Option::is_none")] pub identifier_case: Option, + /// Java: organize imports switches to a wildcard import once this many + /// classes of one package are used (jdtls `starThreshold`; IDEA's default + /// 5; unset keeps the language server's default). + #[serde(skip_serializing_if = "Option::is_none")] + pub class_count_to_use_import_with_star: Option, + /// Java: organize imports switches to a wildcard static import once this + /// many statically imported names are used (jdtls `staticStarThreshold`; + /// IDEA's default 3; unset keeps the language server's default). + #[serde(skip_serializing_if = "Option::is_none")] + pub names_count_to_use_static_import_with_star: Option, + /// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. + #[serde(skip_serializing_if = "Option::is_none")] + pub semicolons: Option, + /// JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. + #[serde(skip_serializing_if = "Option::is_none")] + pub quotes: Option, + /// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`). + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub spaces: BTreeMap, } /// Editor › Code Style (General tab + per-language overrides). diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 99613dc3c..7abdda185 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -432,6 +432,12 @@ pub struct ToolDownloadSettings { /// commas or whitespace and tried in order before the official host; empty keeps every /// download on its official host. pub github_mirror: String, + /// Package registries only as configured (a company Nexus or Artifactory): npm and pnpm + /// installs and update checks never retry against the public npm registry, and the IDE + /// fetches nothing from public package registries itself (the JUnit Platform launcher from + /// Maven Central, dependency version completion from Maven Central, npm, PyPI and + /// crates.io). Off by default. + pub configured_registries_only: bool, } /// Absent profiles retain automatic discovery for existing projects. @@ -1212,6 +1218,8 @@ pub struct LanguagesSettings { pub prettier: ExternalFormatterSettings, pub oxfmt: ExternalFormatterSettings, pub biome: ExternalFormatterSettings, + /// dprint formats every file its configuration covers: `languages` is unused. + pub dprint: ExternalFormatterSettings, pub ruff: ExternalFormatterSettings, pub black: ExternalFormatterSettings, pub java: JavaSettings, @@ -1238,6 +1246,7 @@ impl Default for LanguagesSettings { languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(), ..ExternalFormatterSettings::default() }, + dprint: ExternalFormatterSettings { languages: Vec::new(), ..ExternalFormatterSettings::default() }, ruff: ExternalFormatterSettings { languages: vec!["python".into()], ..ExternalFormatterSettings::default() @@ -1315,6 +1324,7 @@ impl LanguagesSettings { ExternalFormatter::Prettier => &self.prettier, ExternalFormatter::Oxfmt => &self.oxfmt, ExternalFormatter::Biome => &self.biome, + ExternalFormatter::Dprint => &self.dprint, ExternalFormatter::Ruff => &self.ruff, ExternalFormatter::Black => &self.black, } @@ -1328,6 +1338,7 @@ pub enum ExternalFormatter { Prettier, Oxfmt, Biome, + Dprint, Ruff, Black, } @@ -1339,6 +1350,7 @@ impl ExternalFormatter { Self::Prettier => "prettier", Self::Oxfmt => "oxfmt", Self::Biome => "biome", + Self::Dprint => "dprint", Self::Ruff => "ruff", Self::Black => "black", } @@ -1349,11 +1361,11 @@ impl ExternalFormatter { pub const BIOME_LANGUAGES: [&str; 8] = ["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"]; -/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats. +/// An external formatter (Prettier, oxfmt, Biome, dprint, Ruff, Black) and the languages it formats. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] pub struct ExternalFormatterSettings { - /// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH. + /// Empty path: project node_modules (Prettier/oxfmt/Biome/dprint), managed installation, then PATH. pub path: String, /// Ruff only: directory containing its configuration, or a configuration file. pub configuration_directory: String, @@ -1724,11 +1736,14 @@ pub struct TypeScriptSettings { /// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the /// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default). pub tsserver_max_memory: u32, + /// Problems › TypeScript project errors: the project's own `tsc --watch` per root + /// `tsconfig.json` reports the errors of files that are not open. + pub watch_problems: bool, } impl Default for TypeScriptSettings { fn default() -> Self { - Self { version: "bundled".into(), tsserver_max_memory: 0 } + Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false } } } diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index 506d5c7b3..06d3448b4 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -157,6 +157,10 @@ pub struct ColumnInfo { pub nullable: bool, pub default: Option, pub primary_key: bool, + /// `None` when it has none, or the engine keeps no comments. + #[serde(default)] + #[specta(optional)] + pub comment: Option, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)] @@ -172,6 +176,10 @@ pub struct IndexInfo { #[serde(rename_all = "camelCase")] #[serde(rename = "DbTableDetails")] pub struct TableDetails { + /// The table's comment; `None` when it has none, or the engine keeps no comments. + #[serde(default)] + #[specta(optional)] + pub comment: Option, pub columns: Vec, pub indexes: Vec, pub foreign_keys: Vec, @@ -1119,11 +1127,18 @@ impl DbManager { let nullable = flag(&it.next().flatten()); let default = it.next().flatten(); let primary_key = flag(&it.next().flatten()); - Some(ColumnInfo { name, data_type, nullable, default, primary_key }) + let comment = it.next().flatten().filter(|c| !c.is_empty()); + Some(ColumnInfo { name, data_type, nullable, default, primary_key, comment }) }) .collect(); if driver == DbDriver::Jdbc { - return Ok(TableDetails { columns, indexes: vec![], foreign_keys: vec![], triggers: vec![] }); + return Ok(TableDetails { + comment: None, + columns, + indexes: vec![], + foreign_keys: vec![], + triggers: vec![], + }); } let mut indexes: Vec = Vec::new(); for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? { @@ -1175,7 +1190,17 @@ impl DbManager { Some(TriggerInfo { name, timing, events }) }) .collect(); - Ok(TableDetails { columns, indexes, foreign_keys, triggers }) + let comment = match sql::table_comment(driver, schema, table) { + Some(q) => pool.rows(&q, 1).await.map_or_else( + |e| { + tracing::warn!("table comment: {}", e.message); + None + }, + |rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()), + ), + None => None, + }; + Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers }) } /// The object privileges granted on `table`; empty, without a query, on the engines diff --git a/crates/ide-db/src/snowflake/meta.rs b/crates/ide-db/src/snowflake/meta.rs index a65a33b0a..b1f137632 100644 --- a/crates/ide-db/src/snowflake/meta.rs +++ b/crates/ide-db/src/snowflake/meta.rs @@ -132,6 +132,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st nullable: yes(r.get("null?")), default: r.get("default").filter(|d| !d.is_empty()).map(str::to_owned), primary_key: yes(r.get("primary key")), + comment: r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned), }) }) .collect(); @@ -140,7 +141,16 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st Ok(keys) => foreign_keys(&keys), Err(_) => Vec::new(), }; - Ok(TableDetails { columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() }) + // `LIKE` matches without case and with wildcards: the exact name picks the row. + let like = format!("SHOW TABLES LIKE {} IN SCHEMA {}", quote_literal(DRIVER, table), schema_path(pool, schema)); + let comment = match show(pool, &like).await { + Ok(shown) => shown + .records() + .find(|r| r.get("name") == Some(table)) + .and_then(|r| r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned)), + Err(_) => None, + }; + Ok(TableDetails { comment, columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() }) } fn foreign_keys(shown: &Shown) -> Vec { diff --git a/crates/ide-db/src/sql.rs b/crates/ide-db/src/sql.rs index dcd5bb57f..2e1ae7cff 100644 --- a/crates/ide-db/src/sql.rs +++ b/crates/ide-db/src/sql.rs @@ -145,7 +145,8 @@ const SNOWFLAKE_TYPE: &str = "CASE WHEN data_type = 'NUMBER' THEN 'NUMBER(' || n WHEN data_type = 'TEXT' THEN 'VARCHAR(' || character_maximum_length || ')' \ WHEN data_type LIKE 'TIME%' THEN data_type || '(' || datetime_precision || ')' ELSE data_type END"; -/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`. +/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`, and the column's +/// comment on the engines that keep one (PostgreSQL, MySQL, Oracle, ClickHouse). pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String { let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table)); match driver { @@ -153,7 +154,7 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String { DbDriver::Clickhouse => format!( "SELECT name, type, CASE WHEN startsWith(type, 'Nullable(') \ OR startsWith(type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, \ - if(default_kind = '', NULL, default_expression), is_in_primary_key \ + if(default_kind = '', NULL, default_expression), is_in_primary_key, comment \ FROM system.columns WHERE database = {s} AND table = {t} ORDER BY position" ), DbDriver::Sqlite => format!( @@ -166,13 +167,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String { JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \ AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \ WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \ - AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END \ + AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \ + col_description(format('%I.%I', c.table_schema, c.table_name)::regclass, c.ordinal_position::int) \ FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \ ORDER BY c.ordinal_position" ), DbDriver::Mysql => format!( "SELECT column_name, column_type, is_nullable, column_default, \ - CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END \ + CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END, column_comment \ FROM information_schema.columns WHERE table_schema = {s} AND table_name = {t} \ ORDER BY ordinal_position" ), @@ -192,8 +194,10 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String { ), DbDriver::Oracle => format!( "SELECT c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), c.data_default, \ - CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END \ + CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, cc.comments \ FROM all_tab_columns c \ + LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \ + AND cc.column_name = c.column_name \ LEFT JOIN (SELECT kc.column_name FROM all_constraints con \ JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \ AND kc.constraint_name = con.constraint_name \ @@ -204,6 +208,28 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String { } } +/// One row, one column: the table's comment (`NULL` or empty for none). `None` for the +/// engines whose comments the IDE doesn't read here (Snowflake reads it with `SHOW`). +pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option { + let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table)); + match driver { + DbDriver::Postgres => Some(format!( + "SELECT obj_description(c.oid, 'pg_class') FROM pg_class c \ + JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = {s} AND c.relname = {t}" + )), + // A view's `table_comment` is the word `VIEW`. + DbDriver::Mysql => Some(format!( + "SELECT CASE WHEN table_type = 'VIEW' THEN NULL ELSE table_comment END \ + FROM information_schema.tables WHERE table_schema = {s} AND table_name = {t}" + )), + DbDriver::Oracle => { + Some(format!("SELECT comments FROM all_tab_comments WHERE owner = {s} AND table_name = {t}")) + } + DbDriver::Clickhouse => Some(format!("SELECT comment FROM system.tables WHERE database = {s} AND name = {t}")), + _ => None, + } +} + /// Rows: `index name, unique (0/1), column` (one row per indexed column, in order). // Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the // most columns an index or key has): unlike a series per catalog row, it lets the planner find the @@ -956,6 +982,22 @@ mod tests { assert_eq!(quote_literal(DbDriver::Mysql, "it's \\"), "'it''s \\\\'"); } + #[test] + fn comments_are_read_where_the_engine_keeps_them() { + assert!(columns(DbDriver::Postgres, "public", "t").contains("col_description(")); + assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment")); + assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments")); + assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment")); + let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap(); + assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}"); + assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment")); + assert!(table_comment(DbDriver::Oracle, "S", "T").unwrap().contains("all_tab_comments")); + assert!(table_comment(DbDriver::Clickhouse, "db", "t").unwrap().contains("system.tables")); + for driver in [DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Snowflake] { + assert_eq!(table_comment(driver, "s", "t"), None); + } + } + #[test] fn clickhouse_escapes_backslashes_and_delimiters() { let driver = DbDriver::Clickhouse; diff --git a/crates/ide-db/tests/jdbc.rs b/crates/ide-db/tests/jdbc.rs index 9fff39921..c939bacf0 100644 --- a/crates/ide-db/tests/jdbc.rs +++ b/crates/ide-db/tests/jdbc.rs @@ -1,5 +1,5 @@ use ide_core::{CancellationToken, IdeResult}; -use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, SortKey}; +use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey}; use std::{path::Path, sync::Arc}; fn manager(dir: &Path) -> DbManager { @@ -89,21 +89,25 @@ async fn named_jdbc_sources_persist_the_type_and_reject_a_profile_for_another_ty Ok(()) } -#[tokio::test] -#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"] -async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> { - let tmp = tempfile::tempdir()?; - let db = manager(tmp.path()); +fn register_duckdb(db: &DbManager, vendor: Option<&str>) -> IdeResult<()> { let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR"); assert_eq!(ide_db::jdbc_driver_classes(std::slice::from_ref(&jar))?, ["org.duckdb.DuckDBDriver"]); db.save_jdbc_driver(DbJdbcDriver { id: "duck".into(), name: "DuckDB".into(), - vendor: None, + vendor: vendor.map(str::to_owned), jars: vec![jar], class_name: "org.duckdb.DuckDBDriver".into(), url_template: "jdbc:duckdb:".into(), - })?; + }) +} + +#[tokio::test] +#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"] +async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> { + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + register_duckdb(&db, None)?; let source = DataSource { id: "test".into(), name: "DuckDB".into(), @@ -157,6 +161,104 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> { Ok(()) } +#[tokio::test] +#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"] +async fn duckdb_named_file_enforces_read_only_at_open() -> IdeResult<()> { + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + register_duckdb(&db, Some("duckdb"))?; + let file = tmp.path().join("example.duckdb"); + let mut source = DataSource { + id: "test".into(), + name: "DuckDB".into(), + driver: DbDriver::Jdbc, + vendor: "duckdb".into(), + global: true, + jdbc_driver: "duck".into(), + url: format!("jdbc:duckdb:{}", file.display()), + file: Some(file.clone().into()), + read_only: true, + ..Default::default() + }; + let cancel = CancellationToken::new(); + let err = db.test(&source, None, None).await.unwrap_err(); + assert!(err.message.contains("existing database file"), "{}", err.message); + assert!(!file.exists()); + + source.read_only = false; + db.save_sources(vec![source.clone()]).await?; + db.execute("test", "create table items (id int)", 1, &cancel).await?; + db.execute("test", "insert into items values (1)", 1, &cancel).await?; + db.disconnect("test").await; + + source.read_only = true; + let reopened = manager(tmp.path()); + assert!(reopened.test(&source, None, None).await?.to_lowercase().contains("duckdb")); + let mut conflicting = source.clone(); + for options in ["; access_mode = READ_WRITE", "; duckdb.read_only = false"] { + conflicting.url = format!("{}{options}", source.url); + let err = reopened.test(&conflicting, None, None).await.unwrap_err(); + assert!(err.message.contains("conflicts with Read-only"), "{}", err.message); + } + conflicting.url = source.url.clone(); + conflicting.properties.push(DbProperty { name: "ACCESS_MODE".into(), value: "READ_WRITE".into() }); + let err = reopened.test(&conflicting, None, None).await.unwrap_err(); + assert!(err.message.contains("conflicts with Read-only"), "{}", err.message); + + reopened.save_sources(vec![source.clone()]).await?; + assert_eq!(reopened.source("test")?.vendor, "duckdb"); + assert_eq!(reopened.execute("test", "select id from items", 1, &cancel).await?.rows, [vec![Some("1".into())]]); + for query in ["insert into items values (2)", "create table added (id int)"] { + let err = reopened.execute("test", query, 1, &cancel).await.unwrap_err(); + assert!(err.message.to_lowercase().contains("read-only"), "{}", err.message); + } + assert!(!reopened.tables("test", "main").await?.iter().any(|table| table.name == "added")); + reopened.disconnect("test").await; + + source.read_only = false; + reopened.save_sources(vec![source]).await?; + reopened.execute("test", "insert into items values (2)", 1, &cancel).await?; + assert_eq!( + reopened.execute("test", "select count(*) from items", 1, &cancel).await?.rows, + [vec![Some("2".into())]] + ); + reopened.disconnect("test").await; + Ok(()) +} + +#[tokio::test] +#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"] +async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> { + let tmp = tempfile::tempdir()?; + let db = manager(tmp.path()); + register_duckdb(&db, Some("duckdb"))?; + let mut source = DataSource { + id: "test".into(), + name: "DuckDB (memory)".into(), + driver: DbDriver::Jdbc, + vendor: "duckdb".into(), + global: true, + jdbc_driver: "duck".into(), + url: "jdbc:duckdb:".into(), + ..Default::default() + }; + let cancel = CancellationToken::new(); + db.save_sources(vec![source.clone()]).await?; + db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?; + assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]); + db.disconnect("test").await; + assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items")); + db.disconnect("test").await; + + source.read_only = true; + for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:"] { + source.url = url.into(); + let err = db.test(&source, None, None).await.unwrap_err(); + assert!(err.message.contains("existing database file"), "{}", err.message); + } + Ok(()) +} + #[tokio::test] #[ignore = "requires CLICKHOUSE_JDBC_CLASSPATH and a loopback ClickHouse fixture on CLICKHOUSE_JDBC_TEST_PORT"] async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> { diff --git a/crates/ide-db/tests/mysql.rs b/crates/ide-db/tests/mysql.rs index 90126046e..50cf0136d 100644 --- a/crates/ide-db/tests/mysql.rs +++ b/crates/ide-db/tests/mysql.rs @@ -40,7 +40,8 @@ async fn create_schemas(db: &DbManager) { format!("DROP DATABASE IF EXISTS `{s}`"), format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"), format!( - "CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin, raw VARBINARY(4))" + "CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin COMMENT '名字', \ + raw VARBINARY(4)) COMMENT = '用户表'" ), format!("CREATE INDEX `名字` ON `{s}`.`用户` (name)"), format!("INSERT INTO `{s}`.`用户` VALUES (1, 'ann', 0xCAFE)"), @@ -59,6 +60,9 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> { let d = db.table_details("m", s, "用户").await?; let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect(); assert_eq!(cols, ["id", "name", "raw"]); + assert_eq!(d.comment.as_deref(), Some("用户表")); + let comments: Vec<_> = d.columns.iter().map(|c| c.comment.as_deref()).collect(); + assert_eq!(comments, [None, Some("名字"), None]); assert!(d.indexes.iter().any(|i| i.name == "名字"), "{:?}", d.indexes); assert!(db.ddl("m", s, "用户").await?.contains("CREATE TABLE `用户`")); } diff --git a/crates/ide-db/tests/postgres.rs b/crates/ide-db/tests/postgres.rs index 36833d6d4..bd86c60ca 100644 --- a/crates/ide-db/tests/postgres.rs +++ b/crates/ide-db/tests/postgres.rs @@ -338,6 +338,8 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult< "CREATE TABLE oi_meta.lines (n INT PRIMARY KEY, o_region INT, o_id INT, \ FOREIGN KEY (o_region, o_id) REFERENCES oi_meta.orders (region, id))", "CREATE INDEX lines_order ON oi_meta.lines (o_id, o_region)", + "COMMENT ON TABLE oi_meta.orders IS 'Customer''s orders'", + "COMMENT ON COLUMN oi_meta.orders.note IS 'Free text'", "CREATE FUNCTION oi_meta.twice(v INT) RETURNS INT AS 'SELECT v * 2' LANGUAGE sql", ] { db.execute("p", stmt, 10, &c).await?; @@ -350,6 +352,10 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult< assert_eq!(details.foreign_keys[0].columns, ["o_region", "o_id"]); assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]); let orders = db.table_details("p", "oi_meta", "orders").await?; + assert_eq!(orders.comment.as_deref(), Some("Customer's orders")); + let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect(); + assert_eq!(comments, [None, None, Some("Free text")]); + assert_eq!(details.comment, None); let key = orders.indexes.iter().find(|i| i.unique).expect("primary key index"); assert_eq!(key.columns, ["region", "id"]); diff --git a/crates/ide-extension/src/capability.rs b/crates/ide-extension/src/capability.rs index 6f7f84fa5..079a6dc90 100644 --- a/crates/ide-extension/src/capability.rs +++ b/crates/ide-extension/src/capability.rs @@ -46,6 +46,13 @@ pub enum Capability { /// the manifest does not list; each answer applies to one host. Plain /// HTTP elsewhere always needs `net.http:`. NetAsk, + /// The host of the `string` setting `key`, approved when the user applies + /// its value in Settings (`net:setting:server`, `net.http:setting:server`). + /// HTTPS (and loopback HTTP) unless `http`. + NetSetting { + http: bool, + key: String, + }, /// Unencrypted HTTP to one host. NetHttp(String), /// A local socket or named pipe on the project machine. @@ -62,6 +69,8 @@ pub enum Capability { /// Load the plugin's Java agent into the JVMs of Java run configurations. Never /// declared: it comes from `[[contributes.javaAgents]]`. JavaAgent, + /// Fork a recorded native agent session into a new task in the open project (API 1.18). + Agents, } /// How a grant is presented (plan 4.2). @@ -87,11 +96,13 @@ impl Capability { | Self::VcsWrite | Self::Net(_) | Self::NetAsk + | Self::NetSetting { .. } | Self::NetHttp(_) | Self::Secrets | Self::InputEvents | Self::Clipboard - | Self::ClipboardRead => Risk::Medium, + | Self::ClipboardRead + | Self::Agents => Risk::Medium, // A trusted project's own files name the programs the IDE starts (its settings, its // build scripts), so writing them is running code. Self::ProjectWrite @@ -136,6 +147,12 @@ impl Capability { "Ask to connect to a host that is not on the list the first time it tries; you allow or refuse each host, and can revoke the allowed ones" .into() } + Self::NetSetting { http, key } if *http => { + format!("Connect to the host set in the `{key}` setting over unencrypted HTTP (from the machine the project is on)") + } + Self::NetSetting { http: _, key } => { + format!("Connect to the host set in the `{key}` setting (from the machine the project is on)") + } Self::NetHttp(host) => { format!("Connect to {host} over unencrypted HTTP (from the machine the project is on)") } @@ -149,6 +166,7 @@ impl Capability { Self::FsRead(path) => format!("Read files under {path}, outside the project"), Self::FsWrite(path) => format!("Change files under {path}, outside the project"), Self::JavaAgent => "Run code inside the Java applications you start".into(), + Self::Agents => "Fork a recorded agent session into a new task in the open project".into(), } } @@ -180,6 +198,19 @@ pub fn host_matches(pattern: &str, host: &str) -> bool { } } +/// Validates a manifest-style host (letters, digits and `-` labels, at most 253 +/// bytes) and returns it lowercased. A `*` is never valid here — only a +/// `net:`/`net.http:` grant itself may carry the `*.` subdomain pattern, and a +/// host taken from a setting value never does. +pub fn manifest_host(host: &str) -> Result { + let valid = !host.is_empty() + && host.len() <= 253 + && host.split('.').all(|label| { + !label.is_empty() && label.len() <= 63 && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + }); + valid.then(|| host.to_ascii_lowercase()).ok_or_else(|| "invalid host".into()) +} + /// Validates a socket path; a grant may use `*` in its last segment only. pub fn validate_ipc_name(name: &str, pattern: bool) -> Result<(), String> { let pipe = name.starts_with(r"\\.\pipe\"); @@ -269,6 +300,8 @@ impl fmt::Display for Capability { Self::ClipboardRead => f.write_str("clipboard.read"), Self::Net(h) => write!(f, "net:{h}"), Self::NetAsk => f.write_str("net:ask"), + Self::NetSetting { http, key } if *http => write!(f, "net.http:setting:{key}"), + Self::NetSetting { http: _, key } => write!(f, "net:setting:{key}"), Self::NetHttp(h) => write!(f, "net.http:{h}"), Self::Ipc(p) => write!(f, "ipc:{p}"), Self::Process(b) => write!(f, "process:{b}"), @@ -276,6 +309,7 @@ impl fmt::Display for Capability { Self::FsRead(p) => write!(f, "fs.read:{p}"), Self::FsWrite(p) => write!(f, "fs.write:{p}"), Self::JavaAgent => f.write_str("java.agent"), + Self::Agents => f.write_str("agents"), } } } @@ -295,23 +329,27 @@ impl FromStr for Capability { if kind == "net" && arg == "ask" { return Ok(Self::NetAsk); } - let host = arg.strip_prefix("*.").unwrap_or(arg); - let valid = !host.is_empty() - && host.len() <= 253 - && host.split('.').all(|label| { - !label.is_empty() - && label.len() <= 63 - && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') - }); - if valid { - Ok(if kind == "net" { - Self::Net(arg.to_ascii_lowercase()) + // `net:setting:` names the plugin's `string` setting the + // host comes from; the same key rule as a settings schema. + if let Some(key) = arg.strip_prefix("setting:") { + let valid_key = !key.is_empty() + && key.len() <= 64 + && key.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)); + return if valid_key { + Ok(Self::NetSetting { http: kind == "net.http", key: key.to_owned() }) } else { - Self::NetHttp(arg.to_ascii_lowercase()) - }) - } else { - Err(format!("invalid host in {s:?}")) + Err(format!("invalid setting key in {s:?}")) + }; } + manifest_host(arg.strip_prefix("*.").unwrap_or(arg)) + .map(|_| { + if kind == "net" { + Self::Net(arg.to_ascii_lowercase()) + } else { + Self::NetHttp(arg.to_ascii_lowercase()) + } + }) + .map_err(|_| format!("invalid host in {s:?}")) } "ipc" => { validate_ipc_name(arg, true)?; @@ -355,6 +393,7 @@ impl FromStr for Capability { "clipboard" => Self::Clipboard, "clipboard.read" => Self::ClipboardRead, "java.agent" => Self::JavaAgent, + "agents" => Self::Agents, _ => return Err(format!("unknown capability {s:?}")), }) } @@ -549,6 +588,77 @@ mod net_ask_tests { } } +#[cfg(test)] +mod net_setting_tests { + use super::*; + + /// `net:setting:` names a settings key instead of a host: the host + /// comes from the setting's value and is approved when the user sets it + /// (#3809). + #[test] + fn setting_derived_grants_parse_and_print() { + for s in ["net:setting:server", "net.http:setting:server"] { + let cap: Capability = s.parse().unwrap(); + assert_eq!(cap.to_string(), s, "{s}"); + assert_eq!(cap.risk(), Risk::Medium, "{s}"); + } + assert_eq!( + "net:setting:server".parse::().unwrap(), + Capability::NetSetting { http: false, key: "server".into() } + ); + assert_eq!( + "net.http:setting:server".parse::().unwrap(), + Capability::NetSetting { http: true, key: "server".into() } + ); + assert!(!"net:setting:server".parse::().unwrap().auto_migrates()); + let derived = "net:setting:server".parse::().unwrap(); + assert!(derived.describe().contains("`server`")); + assert!("net.http:setting:server".parse::().unwrap().describe().contains("unencrypted")); + } + + #[test] + fn setting_derived_grants_stay_strict() { + for s in ["net:setting:", "net:setting:a b", "net:setting:a:b", "net.http:setting:"] { + assert!(s.parse::().is_err(), "{s}"); + } + } + + /// The derivation covers nothing by itself: a literal-host grant and a + /// setting-derived grant are different grants, and the host materializes + /// only after the user approves the setting's value. + #[test] + fn derived_grants_do_not_cover_literal_hosts() { + let derived: Capability = "net:setting:server".parse().unwrap(); + let literal: Capability = "net:gitlab.intranet.example".parse().unwrap(); + assert!(!derived.covers(&literal)); + assert!(!literal.covers(&derived)); + assert!(!derived.covers(&"net.http:gitlab.intranet.example".parse().unwrap())); + assert!(!derived.covers(&"net:setting:other".parse().unwrap())); + } + + /// The host of a setting value passes the same rules as a manifest host, + /// and a `*` is refused (`net:*` stays impossible). + #[test] + fn value_hosts_follow_the_manifest_host_rules() { + assert_eq!(manifest_host("GitLab.Intranet.Example").unwrap(), "gitlab.intranet.example"); + for bad in + ["", "*", "*.example.com", "a b", "under_score.example", "gitlab.intranet.example.", &"a".repeat(254)] + { + assert!(manifest_host(bad).is_err(), "{bad}"); + } + let long = ["a".repeat(61), "b".repeat(61), "c".repeat(61), "d".repeat(61)].join("."); + assert_eq!(long.len(), 247); + assert!(manifest_host(&long).is_ok()); + assert!( + manifest_host(&["a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(63)].join(".")).is_err(), + "over 253 bytes" + ); + assert!(manifest_host(&"a".repeat(64)).is_err(), "over 63 bytes per label"); + // Pattern grants keep working: only a value (and a bare host) refuses `*`. + assert!("net:*.github.com".parse::().is_ok()); + } +} + #[cfg(test)] mod database_tests { use super::*; diff --git a/crates/ide-extension/src/ledger.rs b/crates/ide-extension/src/ledger.rs index c237cf565..d64eac15e 100644 --- a/crates/ide-extension/src/ledger.rs +++ b/crates/ide-extension/src/ledger.rs @@ -58,6 +58,10 @@ pub struct Grant { /// Exact hosts approved through `net:ask`, separate from manifest grants. #[serde(default)] pub net_hosts: BTreeSet, + /// Hosts approved for `net:setting:` / `net.http:setting:` + /// grants, keyed by the grant: the user approved the value in Settings. + #[serde(default)] + pub setting_hosts: BTreeMap, /// Optional capabilities the user declined (not asked again until re-confirmed). #[serde(default)] pub declined: BTreeSet, @@ -209,6 +213,7 @@ impl Ledger { if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) { grant.net_hosts.clear(); } + retain_setting_hosts(grant, req); if !grant.confirmed { return Decision::NeedsConfirmation { new: req.required.clone(), first_time: true }; } @@ -236,6 +241,7 @@ impl Ledger { if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) { grant.net_hosts.clear(); } + retain_setting_hosts(grant, req); grant.plugin_id = req.plugin_id.to_owned(); grant.version = req.version.to_owned(); grant.package_hash = req.package_hash.to_owned(); @@ -269,6 +275,9 @@ impl Ledger { if cap == &Capability::NetAsk { grant.net_hosts.clear(); } + if matches!(cap, Capability::NetSetting { .. }) { + grant.setting_hosts.remove(&s); + } if let Capability::Process(_) | Capability::JavaAgent = cap { grant.binaries.remove(&s); for binaries in grant.project_binaries.values_mut() { @@ -292,6 +301,21 @@ impl Ledger { self.grants.get_mut(subject).is_some_and(|g| g.net_hosts.remove(host)) } + /// Remembers the host the user approved for a `net:setting:` grant: it + /// covers requests only while the setting still holds it. + pub fn remember_setting_host(&mut self, subject: &Subject, cap: &Capability, host: &str) -> bool { + let Some(grant) = self.grants.get_mut(subject) else { return false }; + if !grant.confirmed || !grant.has(cap) || host.contains('*') { + return false; + } + grant.setting_hosts.insert(cap.to_string(), host.to_owned()); + true + } + + pub fn forget_setting_host(&mut self, subject: &Subject, cap: &Capability) -> bool { + self.grants.get_mut(subject).is_some_and(|g| g.setting_hosts.remove(&cap.to_string()).is_some()) + } + /// Records the program approved for a `process:` grant (or the jar of a `java.agent` one). pub fn set_binary(&mut self, subject: &Subject, cap: &Capability, binary: BinaryGrant) { if let Some(grant) = self.grants.get_mut(subject) { @@ -393,6 +417,19 @@ pub fn by_risk(caps: &[Capability]) -> Vec<(Risk, Vec)> { groups.into_iter().map(|(r, v)| (r.0, v)).collect() } +/// Drops setting-derived hosts the manifest no longer asks for, like +/// `net_hosts` are dropped when `net:ask` is removed. +fn retain_setting_hosts(grant: &mut Grant, req: &Request<'_>) { + let declared: Vec = req + .required + .iter() + .chain(&req.optional) + .filter(|c| matches!(c, Capability::NetSetting { .. })) + .map(|c| c.to_string()) + .collect(); + grant.setting_hosts.retain(|cap, _| declared.contains(cap)); +} + /// Pins an explicitly selected executable, retaining a multicall shim's filename. pub fn approve_program(path: &Path) -> Result { if !path.is_absolute() || !is_executable(path) { @@ -589,6 +626,58 @@ mod tests { assert!(l.get(&r.subject).unwrap().net_hosts.is_empty()); } + /// A setting-derived host is approved per grant, survives re-confirmation, + /// is replaced by the next approval, and goes when the grant or the + /// manifest declaration goes (#3809). + #[test] + fn setting_hosts_are_approved_per_grant_and_drop_with_it() { + let mut l = Ledger::in_memory(); + let r = req("1.0.0", "h", &["project.read"], &["net:setting:server", "net.http:setting:server"]); + l.confirm( + &r, + &["net:setting:server".parse().unwrap(), "net.http:setting:server".parse().unwrap()], + BTreeMap::new(), + ); + let cap: Capability = "net:setting:server".parse().unwrap(); + let other: Capability = "net.http:setting:server".parse().unwrap(); + + // Not granted (declined optional, or not confirmed): refused. + let declined = req("1.0.0", "h", &["project.read"], &["net:setting:server"]); + let mut l2 = Ledger::in_memory(); + l2.confirm(&declined, &[], BTreeMap::new()); + assert!(!l2.remember_setting_host(&declined.subject, &cap, "jira.corp.example"), "declined optional"); + let never = req("1.0.0", "h", &["project.read"], &[]); + let mut l3 = Ledger::in_memory(); + assert!(!l3.remember_setting_host(&never.subject, &cap, "jira.corp.example"), "never confirmed"); + + assert!(l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example")); + assert!(!l.remember_setting_host(&r.subject, &cap, "*"), "a wildcard value is refused"); + assert_eq!( + l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str), + Some("gitlab.intranet.example") + ); + // The other transport is its own record; the derived grant itself covers no host. + assert!(l.remember_setting_host(&r.subject, &other, "jira.corp.example")); + assert!(!l.get(&r.subject).unwrap().has(&Capability::Net("gitlab.intranet.example".into()))); + // Re-confirmation keeps the approval; a manifest that drops the grant drops the record. + l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new()); + assert_eq!( + l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str), + Some("gitlab.intranet.example") + ); + let without = req("2.0.0", "h2", &["project.read"], &[]); + assert!(matches!(l.decide(&without), Decision::Allowed { .. }), "same or fewer needs: silent"); + assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty(), "records follow the manifest"); + + // Revoking the capability clears its record. + l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new()); + l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example"); + assert!(l.set(&r.subject, &cap, false)); + assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty()); + // Forgetting without a record is an error. + assert!(!l.forget_setting_host(&r.subject, &cap)); + } + #[test] fn migration_grants_low_risk_only() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-extension/src/lib.rs b/crates/ide-extension/src/lib.rs index 77699bb0e..b29c1ce20 100644 --- a/crates/ide-extension/src/lib.rs +++ b/crates/ide-extension/src/lib.rs @@ -26,7 +26,9 @@ mod resolve; mod ui; mod when; -pub use capability::{Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, validate_ipc_name}; +pub use capability::{ + Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, manifest_host, validate_ipc_name, +}; pub use index::ContributionIndex; pub use manifest::{ ActivationEvent, CATEGORIES, Capabilities, ENGINE_VERSION, EVENT_KINDS, LEGACY_API, MANIFEST_FILE, MAX_CATEGORIES, diff --git a/crates/ide-extension/src/manifest.rs b/crates/ide-extension/src/manifest.rs index ce3a0c8c0..4c100fd0e 100644 --- a/crates/ide-extension/src/manifest.rs +++ b/crates/ide-extension/src/manifest.rs @@ -369,6 +369,12 @@ impl Manifest { if matches!(cap, Capability::ClipboardRead) { self.needs_api(&format!("capability `{cap}`"), 11)?; } + if matches!(cap, Capability::Agents) { + self.needs_api(&format!("capability `{cap}`"), 18)?; + } + if matches!(cap, Capability::NetSetting { .. }) { + self.needs_api(&format!("capability `{cap}`"), 18)?; + } if matches!(cap, Capability::JavaAgent) { return Err( "`java.agent` comes from `[[contributes.javaAgents]]`: remove it from [capabilities]".into() @@ -764,6 +770,20 @@ required = [\"lsp:phoxite\"] assert_eq!(m.capabilities.optional, [Capability::ClipboardRead]); } + #[test] + fn setting_derived_net_capabilities_need_the_current_api_minor() { + for cap in ["net:setting:server", "net.http:setting:server"] { + let caps = format!("[capabilities]\noptional = [\"{cap}\"]\n"); + assert!( + err(&format!("{}{caps}", BASE.replace("^1.2", "^1.17"))).contains("new in plugin API 1.18"), + "{cap}" + ); + let m = Manifest::parse(&format!("{}{caps}", BASE.replace("^1.2", "^1.18"))).unwrap(); + assert_eq!(m.capabilities.optional.len(), 1, "{cap}"); + assert_eq!(m.capabilities.optional[0].to_string(), cap); + } + } + #[test] fn java_agent_capability_is_not_declared() { for list in ["required", "optional"] { diff --git a/crates/ide-host/src/formatter.rs b/crates/ide-host/src/formatter.rs index 39d3e4611..6f983d5bf 100644 --- a/crates/ide-host/src/formatter.rs +++ b/crates/ide-host/src/formatter.rs @@ -15,6 +15,52 @@ const OXFMT_CONFIGS: [&str; 4] = [".oxfmtrc.json", ".oxfmtrc.jsonc", "oxfmt.conf /// A Biome configuration, or Biome installed as a project dependency (it then uses its defaults). const BIOME_MARKERS: [&str; 3] = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome/package.json"]; +/// dprint's configuration files, and dprint installed as a project dependency. +const DPRINT_MARKERS: [&str; 5] = + ["dprint.json", ".dprint.json", "dprint.jsonc", ".dprint.jsonc", "node_modules/dprint/package.json"]; + +/// The nearest of `names` in `file`'s folder or above, up to the project `root` (none outside it). +fn find_in_project(file: &Path, root: &Path, names: &[&str]) -> Option { + file.parent()? + .ancestors() + .take_while(|dir| dir.starts_with(root)) + .find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| p.is_file())) +} + +fn dprint_project(file: &Path, root: &Path) -> bool { + find_in_project(file, root, &DPRINT_MARKERS).is_some() +} + +/// `dprint editor-info` results by configuration file (the project root without one) and the +/// configuration's modification time. Failures are kept too: an offline plugin download would +/// otherwise time out again on every format. +// ponytail: `extends` files and a configuration outside the project are not watched; editing one needs a change of the project's file (or a restart). +type EditorInfo = (Option, IdeResult); +static DPRINT_EDITOR_INFO: std::sync::LazyLock>> = + std::sync::LazyLock::new(Default::default); + +/// Whether the dprint configuration found for `file` (from its folder, as dprint finds it) has a +/// plugin for it. `retry` runs `editor-info` again after a remembered failure. +fn dprint_covers(tools: &Tools, custom: Option<&Path>, file: &Path, root: &Path, retry: bool) -> IdeResult { + let dir = file.parent().ok_or_else(|| IdeError::invalid("dprint: file has no directory"))?; + let config = find_in_project(file, root, &DPRINT_MARKERS[..4]); + let modified = config.as_ref().and_then(|c| std::fs::metadata(c).and_then(|m| m.modified()).ok()); + let key = config.unwrap_or_else(|| root.to_path_buf()); + let cached = { + let cache = DPRINT_EDITOR_INFO.lock().unwrap_or_else(|e| e.into_inner()); + cache.get(&key).filter(|(at, info)| *at == modified && !(retry && info.is_err())).map(|(_, info)| info.clone()) + }; + let info = cached.unwrap_or_else(|| { + let info = tools.formatter_command("dprint", file, custom).and_then(|mut command| { + command.current_dir(dir); + formatter::dprint_editor_info(command) + }); + DPRINT_EDITOR_INFO.lock().unwrap_or_else(|e| e.into_inner()).insert(key, (modified, info.clone())); + info + })?; + formatter::dprint_covers(&info, file) +} + /// Reformat Code uses Biome below a Biome configuration or installation, unless the nearest /// configuration turns its formatter off (Biome lints, another tool formats). fn biome_formats(file: &Path) -> bool { @@ -31,6 +77,69 @@ fn biome_formats(file: &Path) -> bool { } } +const PRETTIER_CONFIGS: [&str; 18] = [ + ".prettierrc", + ".prettierrc.json", + ".prettierrc.json5", + ".prettierrc.yaml", + ".prettierrc.yml", + ".prettierrc.toml", + ".prettierrc.js", + ".prettierrc.cjs", + ".prettierrc.mjs", + ".prettierrc.ts", + ".prettierrc.cts", + ".prettierrc.mts", + "prettier.config.js", + "prettier.config.cjs", + "prettier.config.mjs", + "prettier.config.ts", + "prettier.config.cts", + "prettier.config.mts", +]; + +/// A Prettier configuration applies to `file`: a configuration file or a `prettier` key in a +/// `package.json` above it. +fn prettier_configured(file: &Path) -> bool { + PRETTIER_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some()) + || file.ancestors().skip(1).any(|dir| { + std::fs::read_to_string(dir.join("package.json")) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .is_some_and(|v| v.get("prettier").is_some()) + }) +} + +/// The languages whose server formats in the IDE's code style (`ts_code_style`). +const CODE_STYLE_LANGUAGES: [&str; 4] = ["javascript", "javascriptreact", "typescript", "typescriptreact"]; + +/// In Automatic mode, the project's own configuration of `tool` wins over the TypeScript server, +/// whose output follows the IDE's code style. Not before the tool is installed (`resolves`): a fresh +/// clone keeps formatting with the server until `npm install`. +fn project_takes_over(tool: ExternalFormatter, language: &str, file: &Path, resolves: impl FnOnce() -> bool) -> bool { + CODE_STYLE_LANGUAGES.contains(&language) && project_configured(tool, file) && resolves() +} + +/// Format on save runs the external tool: its own setting, or the editor's when the tool takes over +/// from the language server (Black, dprint, or a project configuration), so saving keeps formatting. +fn runs_on_save(tool: ExternalFormatter, run_on_save: bool, takes_over: bool, format_on_save: bool) -> bool { + run_on_save + || ((matches!(tool, ExternalFormatter::Black | ExternalFormatter::Dprint) || takes_over) && format_on_save) +} + +/// The project configures `tool`. Every formatter needs an arm. dprint is chosen before this check +/// (`dprint_project`), so it never reaches it. +fn project_configured(tool: ExternalFormatter, file: &Path) -> bool { + match tool { + ExternalFormatter::Prettier => prettier_configured(file), + ExternalFormatter::Oxfmt => { + OXFMT_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some()) + } + ExternalFormatter::Biome => biome_formats(file), + ExternalFormatter::Ruff | ExternalFormatter::Black | ExternalFormatter::Dprint => false, + } +} + /// The `pyproject.toml` Black reads for `file`, in the project root Black finds: the nearest folder /// with `.git`, `.hg`, or a `pyproject.toml` that has `[tool.black]` (one without it is skipped). /// `None` when that root has no `pyproject.toml`: Black then reads the user's configuration. @@ -533,18 +642,58 @@ async fn provider_edits( } return Ok(Some(edits)); } - let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?; + // dprint formats what its configuration covers, before the language's own formatters. + let dprint = &settings.languages.dprint; + let forced_dprint = options.tool == Some(ExternalFormatter::Dprint); + let auto_dprint = options.tool.is_none() + && (dprint.prefer || dprint_project(&snap.path, &project.root)) + && project.require_trust().is_ok(); + let mut selected = None; + if forced_dprint || auto_dprint { + host.require_trust(window)?; + let tools = Tools::new(&host.local_data_dir); + let custom = ide_sdk::apply::setting_path(&project.root, &dprint.path); + let (path, root) = (snap.path.clone(), project.root.clone()); + let covers = + tokio::task::spawn_blocking(move || dprint_covers(&tools, custom.as_deref(), &path, &root, forced_dprint)) + .await + .map_err(|e| IdeError::internal(e.to_string()))?; + match covers { + Ok(true) => selected = Some(ExternalFormatter::Dprint), + Ok(false) if forced_dprint => { + return Err( + IdeError::invalid("The dprint configuration has no plugin for this file").with_tool("dprint") + ); + } + Ok(false) => {} + Err(e) if forced_dprint => return Err(e.with_tool("dprint")), + // Not installed, no configuration, plugins not downloadable: the usual formatter. + Err(e) => tracing::warn!("dprint editor-info failed, using the usual formatter: {}", e.message), + } + } + if selected.is_none() { + selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?; + } + let mut takes_over = false; // Black is selected only when configured or preferred: the Ruff server's formatting doesn't replace it. if let Some(tool) = selected && options.tool.is_none() + && tool != ExternalFormatter::Dprint && tool != ExternalFormatter::Black && !settings.languages.formatter(tool).prefer - && match doc { - Some(doc) => project.lsp.can_format(doc).await?, - None => project.lsp.can_format_text(&snap.path, &snap.language).await, - } { - selected = None; + takes_over = project_takes_over(tool, snap.language.as_str(), &snap.path, || { + let custom = ide_sdk::apply::setting_path(&project.root, &settings.languages.formatter(tool).path); + Tools::new(&host.local_data_dir).formatter_command(tool.name(), &snap.path, custom.as_deref()).is_ok() + }); + if !takes_over + && match doc { + Some(doc) => project.lsp.can_format(doc).await?, + None => project.lsp.can_format_text(&snap.path, &snap.language).await, + } + { + selected = None; + } } let Some(selected) = selected else { if options.on_save && !settings.editor.format_on_save { @@ -566,17 +715,24 @@ async fn provider_edits( .map_err(|e| IdeError::internal(e.to_string())); }; let tool_settings = settings.languages.formatter(selected); - // Black takes over from the language server in its projects, so Format on save runs it too. - let runs_on_save = - tool_settings.run_on_save || (selected == ExternalFormatter::Black && settings.editor.format_on_save); - if options.on_save && !runs_on_save { + if options.on_save && !runs_on_save(selected, tool_settings.run_on_save, takes_over, settings.editor.format_on_save) + { return Ok(None); } host.require_trust(window)?; if snap.read_only { return Err(IdeError::invalid("The file is read-only")); } - let config = language.and_then(|l| l.formatter).expect("external_tool selects languages with a formatter"); + let config = language + .and_then(|l| l.formatter) + .or_else(|| { + (selected == ExternalFormatter::Dprint).then(|| ide_language::FormatterConfig { + tool: "dprint".into(), + parser: String::new(), + range: false, + }) + }) + .expect("external_tool selects languages with a formatter"); let tool = selected.name(); let name = formatter::display_name(tool); let mut custom = ide_sdk::apply::setting_path(&project.root, &tool_settings.path); @@ -727,7 +883,7 @@ pub async fn python_import_edits( #[cfg(test)] mod tests { use super::*; - use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff}; + use ExternalFormatter::{Biome, Black, Dprint, Oxfmt, Prettier, Ruff}; use ide_core::LanguageId; use ide_language::LanguageRegistry; @@ -945,6 +1101,90 @@ mod tests { assert_eq!(black_pyproject(&file), Some(repo.join("pkg/pyproject.toml"))); } + #[test] + fn a_dprint_configuration_or_dependency_in_the_project_marks_a_dprint_project() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("home/project"); + let file = root.join("web/src/app.ts"); + assert!(!dprint_project(&file, &root)); + for marker in DPRINT_MARKERS { + let path = root.join("web").join(marker); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, "{}").unwrap(); + assert!(dprint_project(&file, &root), "{marker}"); + assert!(!dprint_project(&root.join("api/main.ts"), &root), "{marker}"); + // A file outside the project is not below the project's dprint. + assert!(!dprint_project(&dir.path().join("elsewhere/web/src/app.ts"), &root), "{marker}"); + std::fs::remove_file(&path).unwrap(); + } + // dprint installed above the project (a stray `~/node_modules/dprint`) doesn't count. + let stray = dir.path().join("home/node_modules/dprint/package.json"); + std::fs::create_dir_all(stray.parent().unwrap()).unwrap(); + std::fs::write(&stray, "{}").unwrap(); + std::fs::write(dir.path().join("home/dprint.json"), "{}").unwrap(); + assert!(!dprint_project(&file, &root)); + } + + #[cfg(unix)] + #[test] + fn dprint_coverage_comes_from_editor_info_cached_per_configuration() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::create_dir_all(root.join("src")).unwrap(); + let config = root.join("dprint.json"); + std::fs::write(&config, "{}").unwrap(); + // Shell builtins only: the command runs with the tools' empty PATH. + let info = r#"{"plugins":[{"fileExtensions":["ts"],"fileNames":["Dockerfile"]}]}"#; + let fake = root.join("fake-dprint"); + let script = format!( + "#!/bin/sh\necho run >> \"$0.runs\"\n[ -f fail ] && {{ echo 'bad config' >&2; exit 1; }}\nprintf '%s' '{info}'\n" + ); + std::fs::write(&fake, script).unwrap(); + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + let tools = Tools::with_paths(root.join("tools"), Default::default(), ide_tools::platform::Platform::current()); + let runs = || std::fs::read_to_string(root.join("fake-dprint.runs")).unwrap_or_default().lines().count(); + let covers = |file: &str, retry| dprint_covers(&tools, Some(&fake), &root.join(file), root, retry); + + assert!(covers("src/app.ts", false).unwrap()); + assert!(covers("src/Dockerfile", false).unwrap()); + // Not covered: the usual formatter takes the file. + assert!(!covers("src/main.py", false).unwrap()); + assert_eq!(runs(), 1); + + // A changed configuration is read again, and its error is dprint's. + std::fs::write(root.join("src/fail"), "").unwrap(); + let later = std::fs::metadata(&config).unwrap().modified().unwrap() + std::time::Duration::from_secs(5); + std::fs::File::options().write(true).open(&config).unwrap().set_modified(later).unwrap(); + let error = covers("src/app.ts", false).unwrap_err(); + assert!(error.message.contains("bad config"), "{}", error.message); + assert_eq!(error.data, Some(ide_core::error::ErrorData::Tool { tool: "dprint".into(), missing: false })); + assert_eq!(runs(), 2); + // The failure is remembered (an offline download would time out again), unless retried. + assert!(covers("src/app.ts", false).is_err()); + assert_eq!(runs(), 2); + std::fs::remove_file(root.join("src/fail")).unwrap(); + assert!(covers("src/app.ts", true).unwrap()); + assert_eq!(runs(), 3); + } + + #[cfg(unix)] + #[test] + fn dprint_without_a_project_configuration_runs_once_per_project() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::create_dir_all(root.join("a/b")).unwrap(); + let fake = root.join("fake-dprint"); + std::fs::write(&fake, "#!/bin/sh\necho run >> \"$0.runs\"\nprintf '%s' '{\"plugins\":[]}'\n").unwrap(); + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + let tools = Tools::with_paths(root.join("tools"), Default::default(), ide_tools::platform::Platform::current()); + for file in ["a/x.ts", "a/b/y.ts", "z.ts"] { + assert!(!dprint_covers(&tools, Some(&fake), &root.join(file), root, false).unwrap()); + } + assert_eq!(std::fs::read_to_string(root.join("fake-dprint.runs")).unwrap().lines().count(), 1); + } + #[test] fn biome_config_or_dependency_selects_biome_for_its_languages() { let dir = tempfile::tempdir().unwrap(); @@ -1011,6 +1251,55 @@ mod tests { assert_eq!(tool(None, "typescript", file, &settings).unwrap(), None); } + #[test] + fn a_project_configuration_of_the_formatter_wins_over_the_language_server() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::create_dir_all(root.join("a/src")).unwrap(); + std::fs::create_dir_all(root.join("b/src")).unwrap(); + std::fs::create_dir_all(root.join("c/src")).unwrap(); + std::fs::write(root.join("a/.prettierrc.json"), "{}").unwrap(); + std::fs::write(root.join("b/package.json"), r#"{ "prettier": { "semi": false } }"#).unwrap(); + std::fs::write(root.join("c/package.json"), r#"{ "name": "c" }"#).unwrap(); + std::fs::write(root.join("c/biome.json"), "{}").unwrap(); + assert!(project_configured(Prettier, &root.join("a/src/app.ts"))); + assert!(project_configured(Prettier, &root.join("b/src/app.ts"))); + assert!(!project_configured(Prettier, &root.join("c/src/app.ts"))); + assert!(project_configured(Biome, &root.join("c/src/app.ts"))); + assert!(!project_configured(Oxfmt, &root.join("c/src/app.ts"))); + std::fs::write(root.join("c/.oxfmtrc.json"), "{}").unwrap(); + assert!(project_configured(Oxfmt, &root.join("c/src/app.ts"))); + } + + #[test] + fn only_the_typescript_server_languages_give_way_to_an_installed_project_formatter() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join(".prettierrc"), "{}").unwrap(); + let file = |name: &str| dir.path().join(name); + for language in ["typescript", "typescriptreact", "javascript", "javascriptreact"] { + assert!(project_takes_over(Prettier, language, &file("a.ts"), || true), "{language}"); + } + for language in ["json", "css", "html", "yaml", "markdown", "vue"] { + assert!(!project_takes_over(Prettier, language, &file("a.json"), || true), "{language}"); + } + // Configured but not installed yet (before `npm install`): the language server formats. + assert!(!project_takes_over(Prettier, "typescript", &file("a.ts"), || false)); + // No configuration: the tool isn't even looked up. + assert!(!project_takes_over(Biome, "typescript", &file("a.ts"), || panic!("resolved"))); + } + + #[test] + fn format_on_save_keeps_running_when_the_project_formatter_takes_over() { + // Format on save formatted with the language server before; the tool that replaces it does too. + assert!(runs_on_save(Prettier, false, true, true)); + assert!(!runs_on_save(Prettier, false, true, false)); + assert!(runs_on_save(Black, false, false, true)); + assert!(runs_on_save(Dprint, false, false, true)); + // Selected by the settings, not taking over: only its own Run on save. + assert!(!runs_on_save(Prettier, false, false, true)); + assert!(runs_on_save(Prettier, true, false, false)); + } + #[test] fn forced_tool_runs_that_formatter_or_reports_why_not() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 16c591a12..80f1a92cc 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -27,6 +27,8 @@ mod requests; pub mod rpc; pub mod shell_env; pub mod trust; +mod ts_code_style; +mod tsc_watch; pub mod web_server; pub use project::{Project, history_retention}; @@ -425,6 +427,9 @@ impl Host { if let Some(phpstan) = &project.phpstan { phpstan.stop(); } + if let Some(watch) = &project.tsc_watch { + watch.stop(); + } project.documents.clear_workspace_edit_history(); project.agents.detach_sinks(); project.flutter.stop(); @@ -654,6 +659,9 @@ impl Host { if let Some(phpstan) = &project.phpstan { phpstan.stop(); } + if let Some(watch) = &project.tsc_watch { + watch.stop(); + } project.documents.clear_workspace_edit_history(); project.notebooks.stop_admission(); project.agents.shutdown(); @@ -693,6 +701,12 @@ impl Host { self.requests.begin(id) } + /// Settings › Tools › Download Mirrors › Use only the configured package registries: nothing + /// is fetched from public package registries the user's tools weren't pointed at. + pub fn configured_registries_only(&self) -> bool { + self.global_settings.effective().tool_downloads.configured_registries_only + } + pub fn begin_project_request(&self, window: &str, id: RequestId) -> CancellationToken { let token = self.begin_project_read_request(window, id); if self.project(window).is_ok_and(|p| !p.is_trusted()) { diff --git a/crates/ide-host/src/menu.rs b/crates/ide-host/src/menu.rs index dc220ab21..19887870b 100644 --- a/crates/ide-host/src/menu.rs +++ b/crates/ide-host/src/menu.rs @@ -380,6 +380,7 @@ pub fn spec(os: Os) -> Vec { "Appearance", vec![ act("editor.toggleZen", "Enter Distraction Free Mode"), + act("view.toggleZenMode", "Enter Zen Mode"), act("window.toggleFullScreen", "Toggle Full Screen"), toggle("view.toggleCompactMode", "Compact Mode"), toggle("view.togglePresentationAssistant", "Presentation Assistant"), @@ -587,6 +588,7 @@ pub fn spec(os: Os) -> Vec { act("refactor.extractParameter", "Introduce Parameter…"), act("refactor.extractMethod", "Extract Method…"), act("refactor.extractInterface", "Extract Interface…"), + act("refactor.extractTypeAlias", "Extract Type Alias…"), act("refactor.inline", "Inline…"), SEP, act("refactor.pullMembersUp", "Pull Members Up…"), @@ -622,6 +624,7 @@ pub fn spec(os: Os) -> Vec { act("run.debugContext", "Debug Context Configuration"), act("run.coverage", "Run with Coverage"), act("run.profile", "Profile"), + act("profiler.openSnapshot", "Open Profiler Snapshot…"), act("run.stop", "Stop"), SEP, act("run.chooseConfig", "Run…"), diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index ccbb28630..9cfce637e 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -88,6 +88,13 @@ pub fn agent_set_command(host: &Host, window: &str, id: String, command: Option< host.project(window)?.agents.set_builtin_command(&id, command) } +/// Sets additional launch arguments for a built-in ACP agent; an empty list resets them. +#[command(trust = trusted)] +pub fn agent_set_additional_args(host: &Host, window: &str, id: String, args: Vec) -> IdeResult<()> { + host.require_trust(window)?; + host.project(window)?.agents.set_builtin_additional_args(&id, args) +} + /// Environment variables built-in agent `id` starts with (saved in its agent file); /// an empty map clears them. #[command(trust = trusted)] @@ -178,6 +185,7 @@ pub async fn agent_registry_install( ) -> IdeResult<()> { // The agent then shows in `agent_providers`. let paths = registry_paths(host); + let public_npm_fallback = !host.configured_registries_only(); let installing = Installing::begin(&id)?; let cancel = host.begin_request(request); // Also a background task of every project window, so it stays visible and can be @@ -204,7 +212,7 @@ pub async fn agent_registry_install( move || cancel.cancel() }); report(None, None, false); - let result = ide_agent::registry::install(&paths, &id, &cancel, &|e| { + let result = ide_agent::registry::install(&paths, &id, public_npm_fallback, &cancel, &|e| { match &e { InstallEvent::Line { text } => report(Some(text.clone()), None, false), InstallEvent::Progress { fraction, message } => { @@ -281,6 +289,21 @@ pub async fn agent_import_session( blocking(move || agents.import_session(&provider, &session_id)).await } +/// Forks a recorded external session into a new task: its first turn continues the recording +/// as the agent's own fork, under an id the host chooses. `cwd` must be where it was recorded. +#[command(trust = trusted)] +pub async fn agent_fork_session( + host: &Host, + window: &str, + provider: String, + session_id: String, + cwd: String, +) -> IdeResult { + host.require_trust(window)?; + let agents = host.project(window)?.agents.clone(); + blocking(move || agents.fork_session(&provider, &session_id, std::path::Path::new(&cwd))).await +} + #[command(trust = trusted)] pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> IdeResult { host.require_trust(window)?; @@ -1445,6 +1468,7 @@ ide_command::domain!( agent_entries, agent_external_sessions, agent_fork, + agent_fork_session, agent_grouped_changes, agent_hermes_profiles, agent_import_session, @@ -1469,6 +1493,7 @@ ide_command::domain!( agent_rollback, agent_rollback_changes, agent_send_queued_now, + agent_set_additional_args, agent_set_command, agent_shell, agent_set_config, diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index 4c82c5118..326e970af 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -767,6 +767,7 @@ pub async fn maven_dependency_completion( use ide_build::maven::completion::{PomCompletionKind, local_options}; let project = host.project(window)?; let cache = host.dependency_versions.clone(); + let central = !host.configured_registries_only(); let cancel = host.begin_project_read_request(window, request); let result = host .blocking(move || { @@ -785,7 +786,10 @@ pub async fn maven_dependency_completion( // The local repository answers at once: Central gets `CENTRAL_WAIT`, then the // lookup finishes in the background and fills the cache for the next request. // Offline, behind a proxy or rate-limited, a failed fetch never fails completion. - let remote = { + // Only the configured package registries: the local repository alone. + let remote = if !central { + Vec::new() + } else { let (cache, target) = (cache.clone(), target.clone()); let (tx, rx) = std::sync::mpsc::channel(); std::thread::spawn(move || { diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index a0ec5bf56..9bf9dc599 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -34,9 +34,10 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide }; let mut config = config; let enhanced = take_enhanced_redefinition(&mut config); + let executor = take_executor(&mut config); let java_exec = java_exec_path(&config); let mut agents = if is_jvm_launch(&config) { - ide_run::java_agent::current_for(java_exec.as_deref()) + ide_run::java_agent::current_for_executor(java_exec.as_deref(), executor.as_deref()) } else { ide_run::java_agent::Agents::default() }; @@ -271,6 +272,19 @@ fn take_enhanced_redefinition(config: &mut LaunchConfig) -> Option Option { + let Some(serde_json::Value::Object(mut extra)) = + config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok()) + else { + return None; + }; + let executor = extra.remove("executor")?; + config.extra_json = Some(serde_json::Value::Object(extra).to_string()); + executor.as_str().filter(|s| !s.is_empty()).map(str::to_owned) +} + /// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options: /// java-debug's and java-analyzer's `vmArgs` (one line, or a list) or the Kotlin debugger's /// `vmArguments` (a list). @@ -995,6 +1009,21 @@ mod tests { } } + #[test] + fn the_executor_is_taken_out_of_the_launch_extras() { + let extras = |config: &LaunchConfig| { + serde_json::from_str::(config.extra_json.as_deref().unwrap()).unwrap() + }; + let mut config = + launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g", "executor": "acme.reload"})); + assert_eq!(take_executor(&mut config).as_deref(), Some("acme.reload")); + assert!(extras(&config).get("executor").is_none(), "not passed on to the adapter"); + assert_eq!(extras(&config)["vmArgs"], "-Xmx1g"); + let mut plain = launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g"})); + assert_eq!(take_executor(&mut plain), None); + assert_eq!(extras(&plain)["vmArgs"], "-Xmx1g"); + } + #[test] fn debug_server_port_only_for_local_java_debug() { let port = |adapter: &str, request: &str, extra| debug_server_port(&launch(adapter, request, extra)); diff --git a/crates/ide-host/src/ops/dependencies.rs b/crates/ide-host/src/ops/dependencies.rs index 2239631c6..d7bea14ae 100644 --- a/crates/ide-host/src/ops/dependencies.rs +++ b/crates/ide-host/src/ops/dependencies.rs @@ -212,6 +212,8 @@ pub async fn dependency_versions( let project = host.project(window)?; let cache = host.dependency_versions.clone(); let config_dir = host.config_dir.clone(); + // npm and crates.io are asked directly; `go` goes through the configured GOPROXY. + let public_registries = !host.configured_registries_only(); let cancel = host.begin_project_read_request(window, request); let result = host .blocking(move || { @@ -228,6 +230,9 @@ pub async fn dependency_versions( let versions = cache.versions(&source, &dependency.package, &cancel)?; return Ok(vec![DependencyVersions { dependency, versions, update: None }]); } + if !public_registries { + return Ok(Vec::new()); + } if snap.path.file_name().is_some_and(|name| name == "package.json") { let Some(dependency) = offset.and_then(|offset| npm::dependency_at(&snap.text, offset)) else { return Ok(Vec::new()); @@ -310,6 +315,9 @@ pub async fn pypi_package( request: RequestId, ) -> IdeResult> { let url = pypi::project_url(name.trim()).ok_or_else(|| IdeError::invalid("not a package name"))?; + if host.configured_registries_only() { + return Ok(None); + } let cancel = host.begin_project_read_request(window, request); let result = host .blocking(move || { @@ -334,6 +342,9 @@ pub async fn pypi_package( /// PyPI's name list, which the first search downloads and a search a day later refreshes. #[command(trust = outside_restricted)] pub async fn pypi_search(host: &Host, window: &str, query: String, request: RequestId) -> IdeResult> { + if host.configured_registries_only() { + return Ok(Vec::new()); + } let names = host.pypi_names.clone(); let cancel = host.begin_project_read_request(window, request); let result = host diff --git a/crates/ide-host/src/ops/java.rs b/crates/ide-host/src/ops/java.rs index 9aef49c5a..781a50041 100644 --- a/crates/ide-host/src/ops/java.rs +++ b/crates/ide-host/src/ops/java.rs @@ -142,7 +142,8 @@ pub(crate) async fn resolve_launch( }; if let Some(outputs) = built { progress("Resolving the classpath"); - let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?; + let server = project.lsp.java_launch(&module, test, false, false, false, cancel); + let mut info = server_launch_extras(server, SERVER_EXTRAS_WAIT).await?; let data_dir = host.local_data_dir.clone(); let cancel = cancel.clone(); return tokio::task::spawn_blocking(move || { @@ -393,6 +394,33 @@ fn is_maven_aggregator(root: &Path, model: &BuildModel, module: &Path) -> bool { /// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless /// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module /// when Settings › Gradle › Build and run using asks for the IDE. +/// How long a launch whose classpath the IDE's Java build resolved waits for what jdtls adds +/// (the JDK it compiles against, the Java project root). jdtls can be busy for minutes importing +/// a Maven project (resolving plugin dependencies), and the run doesn't need it: +/// [`finish_launch`] picks the project's JDK or an installed one. +const SERVER_EXTRAS_WAIT: std::time::Duration = std::time::Duration::from_secs(5); + +/// jdtls' launch info, or an empty one when it doesn't answer within `wait` or fails. +async fn server_launch_extras( + server: impl std::future::Future>, + wait: std::time::Duration, +) -> IdeResult { + let fallback = + || JavaLaunchInfo { path_list_separator: if cfg!(windows) { ";" } else { ":" }.into(), ..Default::default() }; + match tokio::time::timeout(wait, server).await { + Ok(Ok(info)) => Ok(info), + Ok(Err(e)) if e.kind == ErrorKind::Cancelled => Err(e), + Ok(Err(e)) => { + tracing::warn!("Java launch without the language server's JDK: {}", e.message); + Ok(fallback()) + } + Err(_) => { + tracing::info!(wait_ms = wait.as_millis(), "Java language server busy; launching without its JDK"); + Ok(fallback()) + } + } +} + pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool { let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true))); let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false))); @@ -922,7 +950,7 @@ pub async fn java_build_workspace( /// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath: /// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the /// classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from -/// Maven Central), and, +/// Maven Central unless only the configured package registries are allowed), and, /// for a Maven module, what its Surefire configuration gives the forked test JVM. #[command(trust = trusted)] pub async fn java_junit_runner( @@ -935,6 +963,7 @@ pub async fn java_junit_runner( let project = host.project(window)?; let module = ide_core::project_roots::resolve(&project.root, &module); let data_dir = host.local_data_dir.clone(); + let registries_only = host.configured_registries_only(); tokio::task::spawn_blocking(move || { let scope = workspace::scope_for(&project, &module)?; let model = load_launch_model(&scope); @@ -948,7 +977,9 @@ pub async fn java_junit_runner( let launcher = match ide_sdk::java::junit_launcher(&class_paths) { ide_sdk::java::JunitLauncher::OnClasspath | ide_sdk::java::JunitLauncher::Junit4 => None, ide_sdk::java::JunitLauncher::Found(path) => Some(path), - ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?), + ide_sdk::java::JunitLauncher::Missing(version) => { + Some(download_junit_launcher(&data_dir, &version, registries_only)?) + } ide_sdk::java::JunitLauncher::NoPlatform => { return Err(IdeError::unavailable( "Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \ @@ -1017,7 +1048,9 @@ fn junit_launch( } } -fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult { +/// The launcher jar downloaded once from Maven Central; with only the configured package +/// registries allowed (Settings › Tools › Download Mirrors), only one downloaded before. +fn download_junit_launcher(data_dir: &Path, version: &str, registries_only: bool) -> IdeResult { if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) { return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'"))); } @@ -1026,6 +1059,14 @@ fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult if dest.is_file() { return Ok(dest); } + if registries_only { + return Err(IdeError::unavailable(format!( + "{name} is not on the test classpath, and Settings › Tools › Download Mirrors allows only the \ + configured package registries, so it is not downloaded from Maven Central. Add \ + org.junit.platform:junit-platform-launcher to the test dependencies, or set Settings › Build Tools › \ + Maven › Run tests using to Maven." + ))); + } std::fs::create_dir_all(dest.parent().expect("has a parent"))?; let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}"); let partial = dest.with_extension("jar.part"); @@ -1060,6 +1101,22 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) { mod tests { use super::*; + #[tokio::test(start_paused = true)] + async fn a_busy_or_failing_language_server_does_not_block_a_resolved_launch() { + let wait = std::time::Duration::from_secs(5); + // jdtls importing a Maven project: no answer for minutes (#6122). + let busy = server_launch_extras(std::future::pending(), wait).await.unwrap(); + assert!(busy.java_home.is_none() && busy.class_paths.is_empty()); + assert!(!busy.path_list_separator.is_empty()); + let failed = server_launch_extras(async { Err(IdeError::unavailable("timed out")) }, wait).await.unwrap(); + assert!(failed.java_home.is_none()); + let home = JavaLaunchInfo { java_home: Some(PathBuf::from("/jdk").into()), ..Default::default() }; + let answered = server_launch_extras(async { Ok(home) }, wait).await.unwrap(); + assert!(answered.java_home.is_some()); + let cancelled = server_launch_extras(async { Err(IdeError::cancelled()) }, wait).await; + assert_eq!(cancelled.unwrap_err().kind, ErrorKind::Cancelled); + } + #[test] fn junit_launch_applies_the_surefire_configuration() { let surefire = ide_build::surefire::SurefireConfig { diff --git a/crates/ide-host/src/ops/nav.rs b/crates/ide-host/src/ops/nav.rs index 9cfbe3415..c110d842f 100644 --- a/crates/ide-host/src/ops/nav.rs +++ b/crates/ide-host/src/ops/nav.rs @@ -7,7 +7,7 @@ use crate::Project; use ide_command::command; use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos}; use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch}; -use ide_language::{FileReference, WebReference}; +use ide_language::{CSS_VARIABLE, FileReference, WebReference}; use ide_workspace::file_refs::{self, PathCompletion}; use serde::{Deserialize, Serialize}; use specta::Type; @@ -25,6 +25,18 @@ pub struct WebGoto { const MAX_WEB_TARGETS: usize = 200; +/// A custom property declaration (`--accent: #3b82f6`), for `var(--…)` completion and hover. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CssVariable { + pub name: String, + /// The declared value, whitespace collapsed. + pub value: Option, + pub location: Location, +} + +const MAX_CSS_VARIABLES: usize = 5000; + /// A Python class definition and the base names written in its source. The UI builds a /// name → locations index from every class in the project (attached dependency roots /// included) to compute ↑ overrides / ↓ overridden gutter markers without a language @@ -185,6 +197,41 @@ pub async fn web_goto(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeRes .await } +/// Custom properties declared in `doc` (from its current text, first) and in the project's +/// other stylesheets (from the index, so kept up to date as files change). +#[command(trust = always)] +pub async fn web_css_variables(host: &Host, window: &str, doc: DocId) -> IdeResult> { + let project = host.project(window)?; + let syntax = host.syntax(); + blocking(move || { + let snap = project.documents.snapshot(doc)?; + let own = if snap.large { Vec::new() } else { syntax.web_definitions(&snap.language, &snap.text) }; + let mut out: Vec = own + .into_iter() + .filter(|t| t.kind == CSS_VARIABLE) + .map(|t| CssVariable { + name: t.name, + value: t.container, + location: Location { path: snap.path.clone(), range: t.range, uri: None }, + }) + .collect(); + out.extend( + project + .index + .symbols_prefixed("--", CSS_VARIABLE, MAX_CSS_VARIABLES) + .into_iter() + .filter(|m| *m.path != *snap.path) + .map(|m| CssVariable { + name: m.name, + value: m.container, + location: Location { path: m.path, range: m.range, uri: None }, + }), + ); + Ok(out) + }) + .await +} + /// The file a Python import path (`a.b.c`, or `.x` relative to `from`) names; `None` when /// no project or content root has it. #[command(trust = always)] @@ -450,6 +497,7 @@ ide_command::domain!( recent_files, remove_recent, scope_files, + web_css_variables, web_goto, web_unresolved_references, ); diff --git a/crates/ide-host/src/ops/project.rs b/crates/ide-host/src/ops/project.rs index b4011225b..29f13b3a2 100644 --- a/crates/ide-host/src/ops/project.rs +++ b/crates/ide-host/src/ops/project.rs @@ -22,6 +22,8 @@ pub struct ProjectInfo { pub workspace: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub unity: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub unreal: Option, } pub fn info(project: &Project) -> ProjectInfo { @@ -45,6 +47,7 @@ pub fn info(project: &Project) -> ProjectInfo { root: project.root.clone().into(), workspace, unity: ide_workspace::unity::detect(&project.root), + unreal: ide_workspace::unreal::detect(&project.root), } } @@ -125,6 +128,11 @@ pub fn settings_set( if key == "terminal" || key.starts_with("terminal.") { super::term::apply_output_rate(host, window); } + if "languages.typescript.watchProblems".starts_with(&key) + && let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone()) + { + watch.apply(&host.runtime); + } let sink = host.window_sink(window); sink.emit(IdeEvent::SettingsChanged { key }); if let Some(root) = applied.roots_changed { diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 43aa2ebf7..06247f3e2 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -559,7 +559,8 @@ async fn start_inner( /// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an /// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a -/// run target gets none; the console says so, and why an approved agent was left out. +/// run target gets none; the console says so, and why an approved agent was left out. A launch +/// through a plugin executor (`extras.executor`) also gets that plugin's executor-bound agent. fn add_java_agents(config: &mut RunConfig, on_output: &Emit, run_dir: Option<&Path>) { if !ide_run::java_agent::applies(&config.kind) { return; @@ -575,7 +576,7 @@ fn add_java_agents(config: &mut RunConfig, on_output: &Emit, run_di .or_else(|| std::env::var_os("JAVA_HOME").map(std::path::PathBuf::from)); ide_run::java_agent::launched_java(&config.command, &search, home.as_deref()) }); - let agents = ide_run::java_agent::current_for(java.as_deref()); + let agents = ide_run::java_agent::current_for_executor(java.as_deref(), config.extras.executor.as_deref()); let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") }); if run_dir.is_none() { if !agents.options.is_empty() { diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs index d9ee4dbcc..8d24c6852 100644 --- a/crates/ide-host/src/ops/vcs/commands.rs +++ b/crates/ide-host/src/ops/vcs/commands.rs @@ -24,6 +24,12 @@ struct LogAccess { cache: PathBuf, } +fn external_log_of(host: &Host, window: &str, path: &Path) -> Option> { + host.external_logs.read().get(host.owner_window(window)).and_then(|repos| { + repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned() + }) +} + /// Immutable Git objects exposed through the editor's ordinary read-only VFS. /// `encoding` re-decodes the blob with it ("Reload with Encoding") instead of /// the project's detection. @@ -81,9 +87,7 @@ async fn revision_text( encoding: Option<&str>, ) -> IdeResult> { let project = host.project(window).ok(); - let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| { - rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned() - }); + let external = external_log_of(host, window, path); let (path, rev, encoding) = (path.to_path_buf(), rev.to_owned(), encoding.map(str::to_owned)); blocking(move || { fn with_repo( @@ -622,9 +626,7 @@ pub async fn vcs_staging_line_hunks( #[command(trust = always)] pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option) -> IdeResult> { let project = host.project(window).ok(); - let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| { - rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned() - }); + let external = external_log_of(host, window, &path); blocking(move || { if let Some(project) = project { return project.with_log_backend_of(&path, |r| { @@ -640,14 +642,37 @@ pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option IdeResult> { + let project = host.project(window).ok(); + let external = external_log_of(host, window, &path); + blocking(move || { + let mime = ide_vfs::image_mime(&path) + .ok_or_else(|| ide_core::IdeError::invalid(format!("{} is not a supported image", path.display())))?; + let read = |repo: &Repo| repo.file_bytes_at_bounded(&path, &rev, ide_vfs::MAX_IMAGE_SIZE as usize); + let bytes = if let Some(project) = project { + if !ide_vfs::on_local_drive(&path) + && external.is_none() + && !project.repos().all().iter().any(|repo| ide_vfs::same_share(repo.root(), &path)) + { + return Err(ide_core::IdeError::invalid("image is not on a local drive or an opened share")); + } + project.with_log_repo_of(&path, read)? + } else { + read(external.as_deref().ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?)? + }; + Ok(bytes.map(|bytes| format!("data:{mime};base64,{}", ide_vfs::base64(&bytes)))) + }) + .await +} + /// The file's git mode at `rev` (`100644`, `100755`, `120000`…), `"WT"` for the /// worktree; `None` when absent there. Lets the diff viewer report a mode-only change. #[command(trust = trusted)] pub async fn vcs_file_mode(host: &Host, window: &str, path: PathBuf, rev: Option) -> IdeResult> { let project = host.project(window).ok(); - let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| { - rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned() - }); + let external = external_log_of(host, window, &path); blocking(move || { if let Some(project) = project { return project.with_log_backend_of(&path, |r| r.file_mode_at(&path, rev.as_deref())); @@ -3200,6 +3225,7 @@ ide_command::domain!( vcs_discard, vcs_edit_remote, vcs_file_at, + vcs_image_at, vcs_file_mode, vcs_diff_entries, vcs_git_version, diff --git a/crates/ide-host/src/plugins/api.rs b/crates/ide-host/src/plugins/api.rs index 43fe9b4f3..29c7b3dde 100644 --- a/crates/ide-host/src/plugins/api.rs +++ b/crates/ide-host/src/plugins/api.rs @@ -68,6 +68,17 @@ pub trait PluginWorkspace: Send + Sync { fn problems(&self, _client: &str, _path: Option<&Path>) -> Result, HostError> { Ok(Vec::new()) } + /// Fork a recorded native agent session into a new task in the invoking + /// window's project, returning the new task id (API 1.18). + fn fork_agent_session( + &self, + _client: &str, + _agent: &str, + _session_id: &str, + _cwd: &Path, + ) -> Result { + Err(HostError::Failed("agent fork unavailable".into())) + } /// Roots of the open projects. fn projects(&self) -> Vec; @@ -206,6 +217,61 @@ impl SecretStore for FileSecretStore { } } +/// Plugin secrets in the OS credential store (Secret Service, Windows Credential +/// Manager), like saved SSH and agent values. Without a credential store a value +/// stays in the owner-only [`FileSecretStore`] file, which also still answers for +/// values saved there by an older version until they are set again. +pub struct CredentialSecretStore { + store: ide_ssh::secrets::SecretFile, + fallback: FileSecretStore, +} + +impl CredentialSecretStore { + /// `dir`: the plugins' data directory (the index file and the fallback files live there). + pub fn new(dir: PathBuf) -> Self { + Self::with_store(ide_ssh::secrets::SecretFile::new(dir.join("plugin-secrets.json")), dir) + } + + fn with_store(store: ide_ssh::secrets::SecretFile, dir: PathBuf) -> Self { + Self { store, fallback: FileSecretStore { dir } } + } + + fn key(plugin: &str, name: &str) -> String { + format!("{plugin}/{name}") + } + + /// Drops a value from the fallback file, writing it only when it held one. + fn forget_fallback(&self, plugin: &str, name: &str) -> Result<(), String> { + if self.fallback.get(plugin, name).is_none() { + return Ok(()); + } + self.fallback.set(plugin, name, None) + } +} + +impl SecretStore for CredentialSecretStore { + fn get(&self, plugin: &str, name: &str) -> Option { + self.store.get(&Self::key(plugin, name)).or_else(|| self.fallback.get(plugin, name)) + } + + fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> { + let key = Self::key(plugin, name); + match value { + Some(v) => match self.store.set(&key, v) { + Ok(()) => self.forget_fallback(plugin, name), + Err(e) => { + tracing::warn!("plugin secrets: {key} is kept in the plugin's data directory: {}", e.message); + self.fallback.set(plugin, name, Some(v)) + } + }, + None => { + self.store.delete(&key); + self.forget_fallback(plugin, name) + } + } + } +} + /// Largest response body a plugin receives. const MAX_RESPONSE: usize = 16 << 20; /// Largest stdout / stderr kept from a process by default. @@ -675,6 +741,9 @@ pub(super) struct Shared { net_prompts: Mutex>>, pub net_hosts_session_only: AtomicBool, session_net_hosts: Mutex>>, + /// Setting-derived approvals kept for the session only (remote hosts), + /// plugin → `net:setting:` grant → its approved host. + pub(super) session_setting_hosts: Mutex>>, pub(super) next_prompt: AtomicU64, pub(super) run_configurations: super::run_detectors::DynamicConfigurations, pub(super) run_targets: Mutex, @@ -722,6 +791,29 @@ pub(super) struct Shared { /// A window's log tabs of one plugin: key → what it runs, oldest first. type LogTabs = Vec<(String, ide_plugin::ServiceLog)>; +/// The settings key a `net:setting:` grant derives its host from. +fn setting_key(cap: &Capability) -> String { + match cap { + Capability::NetSetting { key, .. } => key.clone(), + _ => String::new(), + } +} + +/// The host a setting value names: a bare host, or a URL the user pasted +/// (`https://jira.corp.example/`), checked with the manifest host rules — a `*` +/// is refused. `Ok(None)` when the value is empty (the setting is cleared). +pub(super) fn setting_host(value: &str) -> Result, String> { + let value = value.trim(); + if value.is_empty() { + return Ok(None); + } + let host = + if value.contains("://") { ide_plugin::net_host(value)? } else { value.trim_end_matches('.').to_owned() }; + ide_extension::manifest_host(&host) + .map(Some) + .map_err(|_| format!("{value:?} is not a host (example.com) or a URL (https://example.com/)")) +} + /// Log tabs a plugin's code may have open in one window; opening more forgets /// the oldest (that tab can no longer start its program). const MAX_LOG_TABS: usize = 32; @@ -760,6 +852,7 @@ impl Shared { net_prompts: Mutex::default(), net_hosts_session_only: AtomicBool::new(false), session_net_hosts: Mutex::default(), + session_setting_hosts: Mutex::default(), next_prompt: AtomicU64::new(1), run_configurations: Arc::default(), run_targets: Mutex::default(), @@ -1027,6 +1120,7 @@ impl Shared { self.withdraw_prompts(plugin); self.net_prompts.lock().remove(plugin); self.session_net_hosts.lock().remove(plugin); + self.session_setting_hosts.lock().remove(plugin); let removed: Vec<(Option, String)> = { let mut contexts = self.contexts.lock(); let keys: Vec<_> = contexts.keys().filter(|(_, p, _)| p == plugin).cloned().collect(); @@ -1545,6 +1639,51 @@ fn project_subdirectory(root: &Path, cwd: &str) -> Result { Ok(dir) } +impl PluginApi { + /// The value of `key` the user set for this plugin, as a plain string + /// (`None` when unset or not a string). + pub(super) fn setting_value(&self, key: &str) -> Option { + let raw = self.setting(None, key)?; + serde_json::from_str::(&raw).ok() + } + + /// The plugin's `net:setting:` grants with their hosts: the approved host + /// while the setting still holds it, and the pending one to approve + /// otherwise (`None` when the value is unset or not a host). + pub(super) fn net_setting_hosts(&self, subject: &Subject) -> Vec<(Capability, Option, Option)> { + let derived: Vec = self + .pkg + .manifest + .capabilities + .all() + .filter(|c| matches!(c, Capability::NetSetting { .. })) + .cloned() + .collect(); + if derived.is_empty() { + return Vec::new(); + } + let ledger = self.shared.ledger.lock(); + let grant = ledger.get(subject).filter(|g| g.confirmed); + let session = self.shared.session_setting_hosts.lock().get(self.id()).cloned().unwrap_or_default(); + derived + .into_iter() + .map(|cap| { + let current = self.setting_value(&setting_key(&cap)).and_then(|v| setting_host(&v).ok()).flatten(); + let record = grant.and_then(|g| g.setting_hosts.get(&cap.to_string())).map(String::as_str); + let session_host = session.get(&cap.to_string()).map(String::as_str); + // An approval covers requests only while the setting still holds it. + let approved = [record, session_host] + .into_iter() + .flatten() + .find(|host| current.as_deref() == Some(host)) + .map(str::to_owned); + let pending = current.filter(|host| approved.as_deref() != Some(host)); + (cap, approved, pending) + }) + .collect() + } +} + impl HostApi for PluginApi { fn database_upsert(&self, root: &Path, source: ide_plugin::PluginDataSource) -> Result<(), HostError> { let (host, db) = self.database_host(root)?; @@ -1918,6 +2057,12 @@ impl HostApi for PluginApi { fn file_icon_decorations(&self, set: &str, items: Vec<(PathBuf, String)>) -> Result<(), HostError> { self.set_file_icon_decorations(set, items) } + fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result { + self.shared + .workspace() + .ok_or_else(|| HostError::NotFound("window project".into()))? + .fork_agent_session(client, agent, session_id, cwd) + } fn console_rules(&self, rules: Vec) -> Result<(), HostError> { let rules = super::console_rules::normalize(rules).map_err(HostError::Invalid)?; let mut all = self.shared.console_rules.lock(); @@ -2781,6 +2926,16 @@ impl HostApi for PluginApi { return Ok(None); } let host = host.trim_end_matches('.').to_ascii_lowercase(); + // A host the plugin derives from a setting is approved in Settings, + // not asked about here: pending or revoked, it stays denied without a + // dialog (#3809). + if self.pkg.manifest.capabilities.all().any(|cap| { + matches!(cap, Capability::NetSetting { http: false, key: _ }) + && self.setting_value(&setting_key(cap)).and_then(|v| setting_host(&v).ok()).flatten().as_deref() + == Some(host.as_str()) + }) { + return Ok(None); + } { let ledger = self.shared.ledger.lock(); if let Some(grant) = ledger.get(subject) @@ -3602,6 +3757,14 @@ impl PluginWorkspace for HostWorkspace { Ok(config) } + fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result { + let host = self.0.upgrade().ok_or(HostError::Cancelled)?; + let project = host.project(client).map_err(failed)?; + project.require_trust().map_err(failed)?; + // Scans the recorded transcripts on disk; plugin calls already run off the UI thread. + Ok(project.agents.fork_session(agent, session_id, cwd).map_err(failed)?.id) + } + fn buffer_text_in(&self, client: Option<&str>, path: &Path) -> Option { client .and_then(|w| self.0.upgrade()?.project(w).ok()?.documents.text_of(path)) @@ -4102,6 +4265,67 @@ mod tests { assert_eq!(std::fs::read_to_string(&outside).unwrap(), "unchanged"); } + /// Plugin secrets go to the credential store; a value an older version left in + /// the owner-only file keeps working until it is set again, and then leaves the file. + #[test] + fn plugin_secrets_go_to_the_credential_store() { + ide_ssh::secrets::testing::use_memory_store(); + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("plugins"); + FileSecretStore { dir: dir.clone() }.set("acme.lint", "old", Some("legacy-3f9a")).unwrap(); + let secrets = CredentialSecretStore::new(dir.clone()); + assert_eq!(secrets.get("acme.lint", "old").as_deref(), Some("legacy-3f9a")); + + secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap(); + secrets.set("acme.lint", "old", Some("moved-5d2b")).unwrap(); + let on_disk = ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e"); + assert_eq!(on_disk, Vec::::new()); + assert_eq!(ide_ssh::secrets::testing::files_containing(tmp.path(), "legacy-3f9a"), Vec::::new()); + let again = CredentialSecretStore::new(dir); + assert_eq!(again.get("acme.lint", "token").as_deref(), Some("value-7c1e")); + assert_eq!(again.get("acme.lint", "old").as_deref(), Some("moved-5d2b")); + assert_eq!(again.get("other.plugin", "token"), None); + + again.set("acme.lint", "token", None).unwrap(); + assert_eq!(again.get("acme.lint", "token"), None); + } + + /// Without a credential store a value stays in the owner-only file. + #[test] + fn plugin_secrets_without_a_credential_store_stay_in_the_file() { + struct NoStore; + impl ide_ssh::secrets::Vault for NoStore { + fn available(&self) -> bool { + false + } + fn get(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult { + Err(ide_ssh::secrets::StoreError::NoDefaultStore) + } + fn set(&self, _: &str, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> { + Err(ide_ssh::secrets::StoreError::NoDefaultStore) + } + fn delete(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> { + Err(ide_ssh::secrets::StoreError::NoDefaultStore) + } + } + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("plugins"); + let store = ide_ssh::secrets::SecretFile::with_vault( + dir.join("plugin-secrets.json"), + |v| serde_json::from_value(v).ok(), + Arc::new(NoStore), + ); + let secrets = CredentialSecretStore::with_store(store, dir.clone()); + secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap(); + assert_eq!( + ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e"), + [dir.join("acme.lint").join("secrets.json")] + ); + assert_eq!(secrets.get("acme.lint", "token").as_deref(), Some("value-7c1e")); + secrets.set("acme.lint", "token", None).unwrap(); + assert_eq!(secrets.get("acme.lint", "token"), None); + } + #[cfg(unix)] #[test] fn storage_and_secrets_refuse_symlinked_private_directories() { diff --git a/crates/ide-host/src/plugins/java_agents.rs b/crates/ide-host/src/plugins/java_agents.rs index a450d98d4..d29975556 100644 --- a/crates/ide-host/src/plugins/java_agents.rs +++ b/crates/ide-host/src/plugins/java_agents.rs @@ -8,8 +8,13 @@ //! args = "optional-arguments" # optional //! vmOptions = ["-XX:+AllowEnhancedClassRedefinition"] # optional, API 1.14 //! jdk = "jetbrains" # optional: only those VM options on JBR +//! executor = "Hot Reload" # optional, API 1.18: see below //! ``` //! +//! With `executor`, the agent is not added to every launch: the plugin contributes an +//! executor beside Run and Debug ("Run with Hot Reload", "Debug with Hot Reload"), and only +//! launches through it get the agent and its `vmOptions`. +//! //! One agent per plugin. The declaration derives the optional high-risk `java.agent` //! capability; granting it records the jar's hash, and a launch adds the agent only //! while the jar still has it ([`ide_run::java_agent`]). @@ -28,6 +33,7 @@ pub const POINT_ID: &str = "javaAgents"; const MAX_ARGS: usize = 4096; const MAX_VM_OPTION: usize = 512; const MAX_VM_OPTIONS: usize = 32; +const MAX_EXECUTOR: usize = 40; #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] @@ -39,6 +45,8 @@ struct Decl { vm_options: Vec, #[serde(default)] jdk: Option, + #[serde(default)] + executor: Option, } #[derive(Clone, Debug)] @@ -48,6 +56,8 @@ pub(super) struct Agent { pub(super) args: Option, pub(super) vm_options: Vec, pub(super) jdk: Option, + /// The executor title: only launches through it get the agent. + pub(super) executor: Option, } /// Agents of enabled plugins. @@ -111,9 +121,16 @@ impl ExtensionPoint for JavaAgentsPoint { if !vm_options.is_empty() || jdk.is_some() { pkg.manifest.needs_api("contributes.javaAgents.vmOptions", 14)?; } - let label = label(&d.path, args.as_deref(), &vm_options); + let executor = validate_executor(d.executor)?; + if executor.is_some() { + pkg.manifest.needs_api("contributes.javaAgents.executor", 18)?; + } + let mut label = label(&d.path, args.as_deref(), &vm_options); + if let Some(title) = &executor { + label = format!("{label} (Run with {title})"); + } let (store, plugin) = (self.store.clone(), pkg.id().to_owned()); - let agent = Agent { jar, args, vm_options, jdk }; + let agent = Agent { jar, args, vm_options, jdk, executor }; Ok(Prepared::new(label, move || Ok(store.add(plugin, agent))).file(d.path).capability(Capability::JavaAgent)) } } @@ -153,6 +170,17 @@ fn validate_jdk(jdk: Option) -> Result, String> { Ok(Some(raw)) } +/// The executor's title: one line, short enough for "Debug '' with ". +fn validate_executor(executor: Option<String>) -> Result<Option<String>, String> { + let Some(title) = executor.map(|s| s.trim().to_owned()) else { return Ok(None) }; + if title.is_empty() || title.chars().count() > MAX_EXECUTOR || title.contains(|c: char| c.is_control()) { + return Err(format!( + "contributes.javaAgents: `executor` must be a title of 1–{MAX_EXECUTOR} characters on one line" + )); + } + Ok(Some(title)) +} + /// What Settings › Plugins shows: jar name, args, and any JVM options. fn label(path: &Path, args: Option<&str>, vm_options: &[String]) -> String { let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); @@ -224,6 +252,7 @@ impl JavaAgentSource for PluginJavaAgents { vm_options: agent.vm_options.clone(), jdk: agent.jdk.clone(), approved_hash: pins.get(&(plugin.clone(), cap.clone())).map(|pin| pin.hash.clone()), + executor: agent.executor.clone(), }) .collect() } @@ -306,6 +335,33 @@ mod tests { assert_eq!(agent.jdk.as_deref(), Some("jetbrains")); } + #[test] + fn parses_an_executor_from_api_18() { + let tmp = tempfile::tempdir().unwrap(); + let manifest = MANIFEST.replace("^1.10", "^1.18"); + let decl = "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \" Hot Reload \"\n"; + let pkg = package(&tmp.path().join("ok"), &format!("{manifest}{decl}")); + assert_eq!(prepare(&pkg).unwrap().label, "spring agent.jar (Run with Hot Reload)"); + let store: Arc<JavaAgents> = Arc::default(); + let point = JavaAgentsPoint::new(store.clone()); + let _keep = (point.prepare(&pkg, pkg.manifest.declarations(POINT_ID).remove(0)).unwrap().commit)().unwrap(); + assert_eq!(store.for_plugin("acme.spring").unwrap().executor.as_deref(), Some("Hot Reload")); + let source = PluginJavaAgents { store, pins: Arc::default() }; + assert_eq!(source.agents()[0].executor.as_deref(), Some("Hot Reload")); + + let old = package(&tmp.path().join("old"), &format!("{MANIFEST_14}{decl}")); + assert!(prepare(&old).map(|_| ()).unwrap_err().contains("new in plugin API 1.18")); + let long = format!( + "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \"{}\"\n", + "x".repeat(41) + ); + let long = package(&tmp.path().join("long"), &format!("{manifest}{long}")); + assert!(prepare(&long).map(|_| ()).unwrap_err().contains("`executor`")); + let empty = "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \" \"\n"; + let empty = package(&tmp.path().join("empty"), &format!("{manifest}{empty}")); + assert!(prepare(&empty).map(|_| ()).unwrap_err().contains("`executor`")); + } + #[test] fn refuses_what_would_fail_at_launch() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-host/src/plugins/market.rs b/crates/ide-host/src/plugins/market.rs index 32a8f720a..846b3e04a 100644 --- a/crates/ide-host/src/plugins/market.rs +++ b/crates/ide-host/src/plugins/market.rs @@ -700,7 +700,10 @@ mod tests { // tampered package — and the official host must still be asked. let candidates = mirror::candidates( "https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin", - &ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() }, + &ide_core::settings::ToolDownloadSettings { + github_mirror: "https://gh-proxy.com/".into(), + ..Default::default() + }, ); let asked: std::cell::RefCell<Vec<usize>> = std::cell::RefCell::new(Vec::new()); let picked = try_sources(&candidates, |index, candidate| { @@ -731,7 +734,10 @@ mod tests { let url = "https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin"; let through = mirror::candidates( url, - &ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() }, + &ide_core::settings::ToolDownloadSettings { + github_mirror: "https://gh-proxy.com/".into(), + ..Default::default() + }, ); assert_eq!(through.len(), 2); assert_eq!(through[0].url, format!("https://gh-proxy.com/{url}")); @@ -741,7 +747,10 @@ mod tests { // A local index's own package is not on GitHub: no prefix may carry it. let local = mirror::candidates( "/srv/market/a.oiplugin", - &ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() }, + &ide_core::settings::ToolDownloadSettings { + github_mirror: "https://gh-proxy.com/".into(), + ..Default::default() + }, ); assert_eq!(local.len(), 1); assert_eq!(local[0].url, "/srv/market/a.oiplugin"); diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index f632b74ef..5e946512e 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -63,7 +63,7 @@ pub mod views; pub mod web; mod websocket; -pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore}; +pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore}; pub use build_graph::{BuildGraph, GradleModule}; pub(crate) use hover::merge as merge_hover; pub use icons::{ @@ -1174,6 +1174,92 @@ impl PluginHost { self.info_of(id) } + /// Approves the host the plugin's `net:setting:<key>` grant derives from + /// the setting's value right now: the dialog when the user applies the + /// value in Settings, or the pending row's Approve action. `expected` is + /// the host the user was shown: when the setting changed since (the plugin + /// can write its own settings), nothing is approved. On a remote host the + /// approval is kept for the session only, like `net:ask` (#3809). + pub fn approve_net_setting(&self, id: &str, setting: &str, http: bool, expected: &str) -> IdeResult<PluginInfo> { + let _guard = self.lifecycle.lock(); + let plugin = self.get(id)?; + self.check_not_uninstalling(&plugin)?; + let cap = Capability::NetSetting { http, key: setting.to_owned() }; + if !plugin.manifest().declares(&cap) { + return Err(IdeError::invalid(format!("plugin {id:?} does not declare {cap}"))); + } + let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() }; + let value = api + .setting_value(setting) + .ok_or_else(|| IdeError::invalid(format!("setting {setting:?} holds no value")))?; + let host = api::setting_host(&value) + .map_err(IdeError::invalid)? + .ok_or_else(|| IdeError::invalid(format!("setting {setting:?} holds no host")))?; + if host != expected { + return Err(IdeError::invalid(format!( + "setting {setting:?} now holds {host}, not {expected}: approve the new value instead" + ))); + } + let session_only = self.shared.net_hosts_session_only.load(std::sync::atomic::Ordering::Relaxed); + if !session_only { + let mut ledger = self.ledger.lock(); + if !ledger.remember_setting_host(&plugin.subject(), &cap, &host) { + return Err(IdeError::invalid(format!("plugin {id:?} does not have {cap} granted"))); + } + self.save_ledger(&ledger); + } + self.stop(&plugin); + if session_only { + self.shared.session_setting_hosts.lock().entry(id.to_owned()).or_default().insert(cap.to_string(), host); + } + if !self.state.lock().disabled.contains(id) { + self.start(&plugin); + } + // Plugins that need this one follow it: running again, or blocked while it can't run. + self.settle_dependents(id); + self.changed(); + self.info_of(id) + } + + /// The host a `net:setting:<key>` grant derives from `value` (a bare host + /// or a URL), for the approval dialog; an error refuses the value. + pub fn net_setting_host(&self, id: &str, setting: &str, value: &str) -> IdeResult<String> { + let plugin = self.get(id)?; + let cap = Capability::NetSetting { http: false, key: setting.to_owned() }; + if !plugin.manifest().declares(&cap) + && !plugin.manifest().declares(&Capability::NetSetting { http: true, key: setting.to_owned() }) + { + return Err(IdeError::invalid(format!("plugin {id:?} does not declare a setting grant for {setting:?}"))); + } + api::setting_host(value) + .map_err(IdeError::invalid)? + .ok_or_else(|| IdeError::invalid(format!("{value:?} holds no host"))) + } + + /// Drops the approved host of a `net:setting:<key>` grant (its revoke + /// action, or the setting's value being cleared). Nothing recorded: still + /// fine, the state is already as asked. + pub fn forget_net_setting(&self, id: &str, setting: &str, http: bool) -> IdeResult<PluginInfo> { + let _guard = self.lifecycle.lock(); + let plugin = self.get(id)?; + self.check_not_uninstalling(&plugin)?; + let cap = Capability::NetSetting { http, key: setting.to_owned() }; + { + let mut ledger = self.ledger.lock(); + ledger.forget_setting_host(&plugin.subject(), &cap); + self.save_ledger(&ledger); + } + self.shared.session_setting_hosts.lock().get_mut(id).map(|hosts| hosts.remove(&cap.to_string())); + self.stop(&plugin); + if !self.state.lock().disabled.contains(id) { + self.start(&plugin); + } + // Plugins that need this one follow it: running again, or blocked while it can't run. + self.settle_dependents(id); + self.changed(); + self.info_of(id) + } + /// Grants or revokes one declared capability (Settings › Plugins › Permissions). /// Revoking a required one stops the plugin until consent is given again. pub fn set_capability(&self, id: &str, capability: &str, granted: bool) -> IdeResult<PluginInfo> { @@ -1191,6 +1277,10 @@ impl PluginHost { return Err(IdeError::invalid(format!("plugin {id:?} has not been confirmed yet"))); } ledger.set(&subject, &cap, granted); + if !granted { + // A session-only approval of a setting-derived host goes with its grant. + self.shared.session_setting_hosts.lock().get_mut(id).map(|hosts| hosts.remove(&cap.to_string())); + } if granted && cap == Capability::JavaAgent && let Some(jar) = agent_jar_grant(plugin.manifest(), plugin.dir()) @@ -1859,6 +1949,12 @@ impl PluginHost { *self.shared.secrets.write() = store; } + /// Keeps plugin secrets in the OS credential store, with the owner-only + /// files under the plugins directory as the fallback. + pub fn use_credential_store(&self) { + self.set_secret_store(Arc::new(CredentialSecretStore::new(self.shared.data_dir.clone()))); + } + /// Stores (or, with `None`, deletes) a secret the plugin declares under /// `[[contributes.secrets]]`. pub fn set_secret(&self, id: &str, name: &str, value: Option<&str>) -> IdeResult<()> { @@ -2748,6 +2844,7 @@ impl PluginHost { fn prepare(&self, pkg: &Package) -> Result<ide_extension::PreparedSet, String> { plugin_icon(pkg)?; let mut set = self.registry.prepare(pkg)?; + check_setting_grants(pkg)?; for icon in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten() { if !set.files.contains(icon) { set.files.push(icon.clone()); @@ -2906,7 +3003,7 @@ impl PluginHost { meta.declared_extra = set.capabilities.clone(); meta.error = None; } - let (granted, pending) = match decision { + let (mut granted, pending) = match decision { Decision::Allowed { granted, pending } => (granted, pending), Decision::NeedsConfirmation { new, .. } => { let mut meta = plugin.meta.lock(); @@ -2919,6 +3016,19 @@ impl PluginHost { if let Err(e) = self.registry.commit(set) { return self.set_failed(plugin, e); } + // Setting-derived network grants materialize their approved host while + // the setting holds it: `net:setting:server` acts as `net:<host>`, so + // the request path keeps its rules (`net_capability` / `covers`). + let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() }; + for (cap, approved, _pending) in api.net_setting_hosts(&plugin.subject()) { + if let Some(host) = approved { + match cap { + Capability::NetSetting { http: false, key: _ } => granted.push(Capability::Net(host)), + Capability::NetSetting { http: true, key: _ } => granted.push(Capability::NetHttp(host)), + _ => {} + } + } + } { let mut meta = plugin.meta.lock(); meta.granted = granted; @@ -3374,6 +3484,21 @@ impl PluginHost { .filter(|g| g.confirmed && g.has(&Capability::NetAsk) && m.declares(&Capability::NetAsk)) .map(|g| g.net_hosts.iter().cloned().collect()) .unwrap_or_default(); + // Setting-derived hosts, listed next to the `net:ask` ones: the + // approved host, and a pending one the setting now holds. + let net_settings = if m.capabilities.all().any(|c| matches!(c, Capability::NetSetting { .. })) { + let api = api::PluginApi { pkg: p.pkg.clone(), shared: self.shared.clone() }; + api.net_setting_hosts(&p.subject()) + .into_iter() + .filter(|(cap, ..)| grant.as_ref().is_some_and(|g| g.confirmed && g.has(cap))) + .map(|(cap, approved, pending)| { + let Capability::NetSetting { http, key } = cap else { unreachable!() }; + types::PluginNetSetting { setting: key, http, host: approved, pending } + }) + .collect() + } else { + Vec::new() + }; PluginInfo { id: m.id.clone(), name: m.name.clone(), @@ -3403,6 +3528,7 @@ impl PluginHost { vm_options: agent.vm_options, jdk: agent.jdk, approved, + executor: agent.executor, } }), source: p.source, @@ -3413,6 +3539,7 @@ impl PluginHost { has_code: m.wasm.is_some(), capabilities, net_hosts, + net_settings, contributions: self.registry.contributions(&m.id), activation: m.activation.iter().map(ToString::to_string).collect(), warnings: meta.warnings.clone(), @@ -3441,6 +3568,37 @@ fn agent_jar_grant(manifest: &Manifest, dir: &Path) -> Option<BinaryGrant> { Some(BinaryGrant { path, hash }) } +/// `net:setting:<key>` grants name a `string` setting of the plugin's own +/// settings schema; checked like the other manifest checks, at install and +/// start (#3809). +fn check_setting_grants(pkg: &Package) -> Result<(), String> { + let derived: Vec<&Capability> = + pkg.manifest.capabilities.all().filter(|c| matches!(c, Capability::NetSetting { .. })).collect(); + if derived.is_empty() { + return Ok(()); + } + let mut strings = BTreeSet::new(); + for decl in pkg.manifest.declarations(ui_points::SETTINGS) { + let decl = ui_points::settings(pkg, decl)?; + for property in decl.json.get("properties").and_then(|p| p.as_array()).into_iter().flatten() { + if property.get("type").and_then(|t| t.as_str()) == Some("string") + && let Some(key) = property.get("key").and_then(|k| k.as_str()) + { + strings.insert(key.to_owned()); + } + } + } + for cap in derived { + let Capability::NetSetting { http: _, key } = cap else { continue }; + if !strings.contains(key.as_str()) { + return Err(format!( + "capability `{cap}` needs a `string` setting {key:?} in the plugin's own settings schema" + )); + } + } + Ok(()) +} + /// Consent / Settings: surface exact contributed JVM flags on the `java.agent` permission. fn annotate_java_agent_vm_options(capabilities: &mut [CapabilityInfo], manifest: &Manifest) { let opts = java_agents::declared_vm_options(manifest); diff --git a/crates/ide-host/src/plugins/types.rs b/crates/ide-host/src/plugins/types.rs index c97832d3a..0095c62ec 100644 --- a/crates/ide-host/src/plugins/types.rs +++ b/crates/ide-host/src/plugins/types.rs @@ -70,6 +70,24 @@ pub struct PluginJavaAgent { pub jdk: Option<String>, /// The jar still has the hash recorded when `java.agent` was granted. pub approved: bool, + /// The title of the executor the agent is bound to (API 1.18): "Run with <title>" and + /// "Debug with <title>" launch with it; other launches leave it out. + #[serde(default)] + pub executor: Option<String>, +} + +/// A `net:setting:` grant's host for Settings › Plugins: the approved one while the setting holds it, else the pending one. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PluginNetSetting { + /// The setting key the host comes from (`server` of `net:setting:server`). + pub setting: String, + /// Plain HTTP (`net.http:setting:`) instead of HTTPS (and loopback HTTP). + pub http: bool, + /// The approved host, while the setting still holds it. + pub host: Option<String>, + /// The host the setting holds now when it is not the approved one. + pub pending: Option<String>, } #[derive(Clone, Debug, Serialize, Deserialize, Type)] @@ -97,6 +115,8 @@ pub struct PluginInfo { /// HTTPS hosts the user allowed through `net:ask` ("always allow"), /// none of them declared by the manifest; each can be revoked. pub net_hosts: Vec<String>, + /// Setting-derived hosts (`net:setting:`), approved in Settings, listed next to the `net:ask` ones. + pub net_settings: Vec<PluginNetSetting>, /// What it contributes while live (point + label). pub contributions: Vec<ContributionInfo>, /// `activation` events of the manifest. diff --git a/crates/ide-host/src/plugins/ui_points.rs b/crates/ide-host/src/plugins/ui_points.rs index d77d9a1ec..8d5ba3f6e 100644 --- a/crates/ide-host/src/plugins/ui_points.rs +++ b/crates/ide-host/src/plugins/ui_points.rs @@ -5,7 +5,8 @@ //! //! ```toml //! [[contributes.menus]] -//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context, commit.message +//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context, commit.message, +//! # services.context / services.toolbar (API 1.18: the Services tree's own nodes) //! command = "check" //! when = "editorLang == java" //! # view = "<view id>" # required for (only allowed on) viewItem.context @@ -112,7 +113,10 @@ pub const SERVER_COMMANDS: &str = "serverCommands"; const VIEW_ITEM_MENU: &str = "viewItem.context"; /// The toolbar above the commit message (Commit tool window and dialog). const COMMIT_MESSAGE_MENU: &str = "commit.message"; -const MENU_IDS: [&str; 10] = [ +/// The Services tool window's context menu and toolbar for the IDE's own nodes (run +/// configurations, Docker containers…): the command gets the selected services. +const SERVICES_MENUS: [&str; 2] = ["services.context", "services.toolbar"]; +const MENU_IDS: [&str; 12] = [ "editor.context", "projectView.context", "editorTab.context", @@ -123,6 +127,8 @@ const MENU_IDS: [&str; 10] = [ "mainToolbar", "problems.context", "searchResults.context", + SERVICES_MENUS[0], + SERVICES_MENUS[1], ]; const MAX_TITLE: usize = 256; const MAX_SETTINGS: usize = 200; @@ -187,6 +193,9 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> { if d.menu == COMMIT_MESSAGE_MENU { pkg.manifest.needs_api(&format!("contributes.menus: {COMMIT_MESSAGE_MENU}"), 3)?; } + if SERVICES_MENUS.contains(&d.menu.as_str()) { + pkg.manifest.needs_api(&format!("contributes.menus: {}", d.menu), 18)?; + } if let Some(w) = &d.when { validate_when(w).map_err(|e| format!("contributes.menus: {e}"))?; } @@ -1372,6 +1381,27 @@ mod tests { } } + #[test] + fn services_menus_require_api_1_18() { + for location in SERVICES_MENUS { + for (api, valid) in [("^1.17", false), ("^1.18", true)] { + let manifest = ide_extension::Manifest::parse(&format!("id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='reload'\ntitle='Reload'")).unwrap(); + let pkg = Package::new(manifest, std::path::PathBuf::from("/unused")); + let decl = toml::from_str(&format!( + "menu='{location}'\ncommand='reload'\nwhen=\"serviceKind == 'spring-boot' && serviceRunning\"" + )) + .unwrap(); + assert_eq!(menu(&pkg, decl).is_ok(), valid, "{api}:{location}"); + } + } + let manifest = ide_extension::Manifest::parse("id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='^1.18'\n[[contributes.commands]]\nid='reload'\ntitle='Reload'").unwrap(); + let pkg = Package::new(manifest, std::path::PathBuf::from("/unused")); + let grouped = toml::from_str("menu='services.context'\ncommand='reload'\nsubmenu='Hot Reload'").unwrap(); + assert!(menu(&pkg, grouped).is_ok()); + let toolbar = toml::from_str("menu='services.toolbar'\ncommand='reload'\nsubmenu='Hot Reload'").unwrap(); + assert!(menu(&pkg, toolbar).unwrap_err().contains("only for context menus")); + } + #[test] fn escape_bindings_need_api_1_10_and_a_when_clause() { let pkg = |api: &str| { diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index 8738d17d3..e5581adae 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -73,6 +73,7 @@ pub struct Project { pub(crate) widget_preview: ide_flutter::ToolServer, pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>, pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>, + pub(crate) tsc_watch: Option<Arc<crate::tsc_watch::TscWatch>>, pub(crate) watcher: Arc<Watcher>, /// Watchers of the Project Structure content roots outside the project folder. pub(crate) content_watchers: Mutex<Vec<(PathBuf, Watcher)>>, @@ -207,7 +208,9 @@ impl Host { let root = member.as_ref().unwrap_or(window_root); ide_sdk::apply::server_launch_overrides(cfg, &effective); ide_sdk::apply::configure_server(cfg, root, server_root, &effective); + crate::ts_code_style::configure(cfg, server_root, &effective); ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir); + ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir); let container_python = effective.languages.python.run_target().is_some(); crate::ops::sdk::container_python::configure_server(cfg, &data_dir, root, &effective); // Attached dependency projects are source, so basedpyright/Pyright should @@ -396,6 +399,8 @@ impl Host { trusted.clone(), ); documents.add_observer(phpstan.clone()); + let tsc_watch = crate::tsc_watch::TscWatch::new(root.clone(), settings.clone(), sink.clone(), trusted.clone()); + documents.add_observer(tsc_watch.clone()); let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?)); for repo in repos.read().all() { repo.set_execution_allowed(trusted.load(Ordering::Acquire)); @@ -690,6 +695,7 @@ impl Host { notebooks, kotlin_bridge: Some(kotlin_bridge), phpstan: Some(phpstan), + tsc_watch: Some(tsc_watch), watcher, content_watchers: Mutex::new(content_watchers), lsp_watchers: Mutex::new(Vec::new()), @@ -750,6 +756,9 @@ impl Host { if let Some(phpstan) = &project.phpstan { phpstan.start(&self.runtime); } + if let Some(watch) = &project.tsc_watch { + watch.apply(&self.runtime); + } if let Some(cmd) = post_start { self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone()); } @@ -950,6 +959,7 @@ impl Host { notebooks, kotlin_bridge: None, phpstan: None, + tsc_watch: None, watcher: Arc::new(watcher), content_watchers: Mutex::new(Vec::new()), lsp_watchers: Mutex::new(Vec::new()), diff --git a/crates/ide-host/src/trust.rs b/crates/ide-host/src/trust.rs index 144fe8112..f37581abe 100644 --- a/crates/ide-host/src/trust.rs +++ b/crates/ide-host/src/trust.rs @@ -267,6 +267,9 @@ impl crate::Host { if let Some(phpstan) = &project.phpstan { phpstan.interrupt(); } + if let Some(watch) = &project.tsc_watch { + watch.apply(&self.runtime); + } if !trusted { if let Some(plugins) = self.plugin_host() { plugins.withdraw_project_run_targets(&project.root); diff --git a/crates/ide-host/src/ts_code_style.rs b/crates/ide-host/src/ts_code_style.rs new file mode 100644 index 000000000..61e78f042 --- /dev/null +++ b/crates/ide-host/src/ts_code_style.rs @@ -0,0 +1,183 @@ +//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation) as the TypeScript +//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for +//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes: +//! quick fixes, auto-imports, refactorings and organize imports. + +use ide_core::editor_settings::LanguageCodeStyle; +use ide_core::settings::Settings; +use ide_language::LanguageServerConfig; +use ide_workspace::EditorConfig; +use serde_json::{Map, Value, json}; +use std::collections::HashMap; +use std::path::Path; + +const SERVERS: [&str; 2] = ["vtsls", "typescript-language-server"]; + +/// tsserver's space options the Spaces tab sets, with the IntelliJ `.editorconfig` property +/// (`ij_<language>_<name>`) that sets the same thing. +const SPACES: [(&str, Option<&str>); 14] = [ + ("insertSpaceAfterCommaDelimiter", Some("space_after_comma")), + ("insertSpaceAfterSemicolonInForStatements", Some("space_after_semicolon")), + ("insertSpaceBeforeAndAfterBinaryOperators", None), + ("insertSpaceAfterKeywordsInControlFlowStatements", None), + ("insertSpaceAfterFunctionKeywordForAnonymousFunctions", Some("space_before_function_left_parenth")), + ("insertSpaceBeforeFunctionParenthesis", Some("space_before_method_parentheses")), + ("insertSpaceAfterConstructor", None), + ("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis", None), + ("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets", Some("spaces_within_brackets")), + ("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", Some("spaces_within_object_literal_braces")), + ("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces", None), + ("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces", Some("spaces_within_interpolation_expressions")), + ("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces", None), + ("insertSpaceAfterTypeAssertion", None), +]; + +/// Adds the code style of JavaScript and TypeScript to a TypeScript server's settings. A file's +/// `.editorconfig` comes first, as in the editor (resolved for the server root's `index.ts` / +/// `index.js`: the servers take one configuration per project); the server's own settings win. +pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &Settings) { + if !SERVERS.contains(&cfg.name.as_str()) { + return; + } + let code_style = &settings.editor.code_style; + let editorconfig = code_style.editorconfig.then(EditorConfig::new); + let mut layer = Map::new(); + for (language, ext) in [("typescript", "ts"), ("javascript", "js")] { + let pairs = editorconfig + .as_ref() + .and_then(|e| e.resolve_pairs(&server_root.join(format!("index.{ext}")))) + .unwrap_or_default(); + let section = section(language, code_style.languages.get(language), &pairs); + if !section.is_empty() { + layer.insert(language.into(), Value::Object(section)); + } + } + if layer.is_empty() { + return; + } + let mut merged = Value::Object(layer); + if let Some(own) = cfg.settings.take() { + ide_sdk::apply::merge(&mut merged, own); + } + cfg.settings = Some(merged); +} + +/// The `format` and `preferences` of one language's section. +fn section( + language: &str, + style: Option<&LanguageCodeStyle>, + editorconfig: &HashMap<String, String>, +) -> Map<String, Value> { + let get = |key: &str| editorconfig.get(key).map(|v| v.to_ascii_lowercase()); + let flag = |name: &str| match get(&format!("ij_{language}_{name}")).as_deref() { + Some("true") => Some(true), + Some("false") => Some(false), + _ => None, + }; + let pick = |value: Option<&String>, allowed: &[&str]| value.filter(|v| allowed.contains(&v.as_str())).cloned(); + + let mut format = Map::new(); + for (key, ij) in SPACES { + if let Some(on) = ij.and_then(flag).or_else(|| style.and_then(|s| s.spaces.get(key).copied())) { + format.insert(key.into(), json!(on)); + } + } + let semicolons = flag("use_semicolon_after_statement") + .map(|on| if on { "insert" } else { "remove" }.to_owned()) + .or_else(|| pick(style.and_then(|s| s.semicolons.as_ref()), &["ignore", "insert", "remove"])); + if let Some(semicolons) = semicolons { + format.insert("semicolons".into(), json!(semicolons)); + } + let quotes = pick(get("quote_type").as_ref(), &["auto", "single", "double"]) + .or_else(|| flag("use_double_quotes").map(|on| if on { "double" } else { "single" }.to_owned())) + .or_else(|| pick(style.and_then(|s| s.quotes.as_ref()), &["auto", "single", "double"])); + + let mut section = Map::new(); + if !format.is_empty() { + section.insert("format".into(), Value::Object(format)); + } + // vtsls reads `quoteStyle` (VS Code's name), typescript-language-server tsserver's `quotePreference`. + if let Some(quotes) = quotes { + section.insert("preferences".into(), json!({ "quoteStyle": quotes, "quotePreference": quotes })); + } + section +} + +#[cfg(test)] +mod tests { + use super::*; + + fn server(name: &str) -> LanguageServerConfig { + serde_json::from_value(json!({ "name": name, "command": name })).unwrap() + } + + #[test] + fn code_style_reaches_typescript_and_javascript_sections() { + let mut settings = Settings::default(); + let ts = LanguageCodeStyle { + semicolons: Some("remove".into()), + quotes: Some("single".into()), + spaces: [("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces".into(), false)].into(), + ..Default::default() + }; + settings.editor.code_style.languages.insert("typescript".into(), ts); + let js = LanguageCodeStyle { semicolons: Some("insert".into()), ..Default::default() }; + settings.editor.code_style.languages.insert("javascript".into(), js); + let dir = tempfile::tempdir().unwrap(); + let mut cfg = server("vtsls"); + cfg.settings = Some(json!({ "typescript": { "preferences": { "quoteStyle": "double" } } })); + configure(&mut cfg, dir.path(), &settings); + assert_eq!( + cfg.settings.unwrap(), + json!({ + "typescript": { + "format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false }, + // The server's own settings win. + "preferences": { "quoteStyle": "double", "quotePreference": "single" }, + }, + "javascript": { "format": { "semicolons": "insert" } }, + }) + ); + + let mut eslint = server("eslint"); + configure(&mut eslint, dir.path(), &settings); + assert_eq!(eslint.settings, None); + let mut untouched = server("vtsls"); + configure(&mut untouched, dir.path(), &Settings::default()); + assert_eq!(untouched.settings, None, "nothing set: the server's defaults"); + } + + #[test] + fn editorconfig_comes_first() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join(".editorconfig"), + "root = true\n[*.ts]\nquote_type = double\nij_typescript_use_semicolon_after_statement = false\n\ + ij_typescript_space_after_comma = false\n[*.js]\nij_javascript_use_double_quotes = false\n", + ) + .unwrap(); + let mut settings = Settings::default(); + let ts = LanguageCodeStyle { + semicolons: Some("insert".into()), + quotes: Some("single".into()), + ..Default::default() + }; + settings.editor.code_style.languages.insert("typescript".into(), ts); + let mut cfg = server("typescript-language-server"); + configure(&mut cfg, dir.path(), &settings); + let s = cfg.settings.unwrap(); + assert_eq!( + s["typescript"]["format"], + json!({ "semicolons": "remove", "insertSpaceAfterCommaDelimiter": false }) + ); + assert_eq!(s["typescript"]["preferences"]["quotePreference"], "double"); + assert_eq!(s["javascript"]["preferences"]["quoteStyle"], "single"); + + settings.editor.code_style.editorconfig = false; + let mut cfg = server("vtsls"); + configure(&mut cfg, dir.path(), &settings); + let s = cfg.settings.unwrap(); + assert_eq!(s["typescript"]["format"], json!({ "semicolons": "insert" })); + assert_eq!(s.get("javascript"), None); + } +} diff --git a/crates/ide-host/src/tsc_watch.rs b/crates/ide-host/src/tsc_watch.rs new file mode 100644 index 000000000..50a79788c --- /dev/null +++ b/crates/ide-host/src/tsc_watch.rs @@ -0,0 +1,359 @@ +//! Problems › TypeScript project errors (`languages.typescript.watchProblems`): the project's own +//! `tsc --watch` per root `tsconfig.json` -> `tsc` diagnostics. Files open in an editor keep only +//! the language server's errors, so the watcher's are held back for them until they close. + +use ide_core::{CancellationToken, Diagnostic, IdeEvent, SharedSink}; +use ide_workspace::SettingsStore; +use ide_workspace::documents::{DocumentInfo, DocumentObserver}; +use parking_lot::Mutex; +use std::collections::{BTreeMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +const SOURCE: &str = "tsc"; +/// How deep below the project the walk looks for `tsconfig.json` (`apps/web/tsconfig.json` is 3). +const MAX_DEPTH: usize = 4; +/// Folders whose configurations are not the project's own: test inputs and samples, often +/// broken on purpose. +const SKIPPED: [&str; 6] = ["node_modules", "fixtures", "__fixtures__", "testdata", "examples", "example"]; + +/// The `tsconfig.json` files of the project, without the ones in ignored (`.gitignore`), hidden, +/// excluded (`excludes`) or [`SKIPPED`] folders. +fn configs(root: &Path, excludes: &[String]) -> Vec<PathBuf> { + let excludes = ide_vfs::ExcludeMatcher::new(excludes); + let base = root.to_path_buf(); + let mut walk = ignore::WalkBuilder::new(root); + walk.max_depth(Some(MAX_DEPTH)).require_git(ide_core::ignored::inside_git_repo(root)).follow_links(false); + walk.filter_entry(move |entry| { + let skipped = entry.file_type().is_some_and(|t| t.is_dir()) + && entry.file_name().to_str().is_some_and(|name| SKIPPED.contains(&name)); + !skipped && entry.path().strip_prefix(&base).is_ok_and(|rel| !excludes.is_match(rel)) + }); + let mut found: Vec<PathBuf> = walk + .build() + .flatten() + .filter(|e| e.file_name() == "tsconfig.json" && e.file_type().is_some_and(|t| t.is_file())) + .map(ignore::DirEntry::into_path) + .collect(); + found.sort(); + found +} + +pub(crate) struct TscWatch { + root: PathBuf, + settings: Arc<SettingsStore>, + sink: SharedSink, + trusted: Arc<AtomicBool>, + state: Mutex<State>, +} + +#[derive(Default)] +struct State { + /// The running watchers, cancelled to stop them. + running: Option<CancellationToken>, + /// The project closed: nothing starts again. + closed: bool, + /// The last compilation's diagnostics of each root configuration. + results: BTreeMap<PathBuf, BTreeMap<PathBuf, Vec<Diagnostic>>>, + /// Files open in an editor. + open: HashSet<PathBuf>, + /// What the UI was last sent. + shown: BTreeMap<PathBuf, Vec<Diagnostic>>, +} + +impl State { + /// Every root's diagnostics of the files not open, a problem two roots report listed once. + fn wanted(&self) -> BTreeMap<PathBuf, Vec<Diagnostic>> { + let mut out: BTreeMap<PathBuf, Vec<Diagnostic>> = BTreeMap::new(); + for files in self.results.values() { + for (path, items) in files.iter().filter(|(p, _)| !self.open.contains(*p)) { + let list = out.entry(path.clone()).or_default(); + for d in items { + if !list.iter().any(|o| o.range == d.range && o.message == d.message) { + list.push(d.clone()); + } + } + } + } + out + } + + /// The files whose diagnostics change, with their new list (empty clears them). + fn refresh(&mut self) -> Vec<(PathBuf, Vec<Diagnostic>)> { + let wanted = self.wanted(); + let mut changes: Vec<(PathBuf, Vec<Diagnostic>)> = + self.shown.keys().filter(|p| !wanted.contains_key(*p)).map(|p| (p.clone(), Vec::new())).collect(); + changes.extend( + wanted.iter().filter(|(p, items)| self.shown.get(*p) != Some(items)).map(|(p, i)| (p.clone(), i.clone())), + ); + self.shown = wanted; + changes + } +} + +impl TscWatch { + pub(crate) fn new( + root: PathBuf, + settings: Arc<SettingsStore>, + sink: SharedSink, + trusted: Arc<AtomicBool>, + ) -> Arc<Self> { + Arc::new(Self { root, settings, sink, trusted, state: Mutex::new(State::default()) }) + } + + /// Starts the watchers when the option is on in a trusted project, else stops them and + /// clears their errors. Called on open, on a settings change and on a trust change. + pub(crate) fn apply(self: &Arc<Self>, runtime: &tokio::runtime::Handle) { + let wanted = + self.trusted.load(Ordering::Acquire) && self.settings.effective().languages.typescript.watch_problems; + if !wanted { + return self.halt(false); + } + let mut state = self.state.lock(); + if !state.closed && state.running.is_none() { + let cancel = CancellationToken::new(); + state.running = Some(cancel.clone()); + let this = self.clone(); + runtime.spawn_blocking(move || this.start(&cancel)); + } + } + + /// The project closed. + pub(crate) fn stop(&self) { + self.halt(true); + } + + fn halt(&self, closed: bool) { + let mut state = self.state.lock(); + state.closed |= closed; + if let Some(cancel) = state.running.take() { + cancel.cancel(); + state.results.clear(); + self.publish(&mut state); + } + } + + /// One thread per root configuration, each running its `tsc --watch` until `cancel`. + fn start(self: &Arc<Self>, cancel: &CancellationToken) { + let excludes = self.settings.effective().exclude_globs(); + for config in ide_build::compile::tsc_watch_roots(configs(&self.root, &excludes)) { + if cancel.is_cancelled() { + return; + } + let (this, cancel) = (self.clone(), cancel.clone()); + std::thread::spawn(move || this.watch(&config, &cancel)); + } + } + + fn watch(&self, config: &Path, cancel: &CancellationToken) { + let result = ide_build::compile::tsc_watch(&self.root, config, cancel, |messages| { + tracing::debug!(config = %config.display(), messages = messages.len(), "tsc --watch compiled"); + let mut files = ide_build::compile::diagnostics_from(&messages, SOURCE); + // Messages about the scratch configurations or files outside the project. + files.retain(|path, _| path.starts_with(&self.root)); + self.compiled(config, files, cancel); + }); + match result { + Ok(()) => tracing::debug!(config = %config.display(), "tsc --watch ended"), + Err(e) => tracing::debug!(config = %config.display(), %e, "tsc --watch did not run"), + } + // Without a watcher its errors would go stale. + self.compiled(config, BTreeMap::new(), cancel); + } + + fn compiled(&self, config: &Path, files: BTreeMap<PathBuf, Vec<Diagnostic>>, cancel: &CancellationToken) { + let mut state = self.state.lock(); + // Under the lock: `apply` cancels and clears under it, so a stopped watcher adds nothing. + if cancel.is_cancelled() { + return; + } + if files.is_empty() { + state.results.remove(config); + } else { + state.results.insert(config.to_path_buf(), files); + } + self.publish(&mut state); + } + + /// Sends the changes, under the lock so they reach the UI in the order decided here. + fn publish(&self, state: &mut State) { + for (path, items) in state.refresh() { + self.sink.emit(IdeEvent::Diagnostics { path: path.into(), source: SOURCE.into(), items }); + } + } + + fn set_open(&self, path: &Path, open: bool) { + let mut state = self.state.lock(); + let changed = if open { state.open.insert(path.to_path_buf()) } else { state.open.remove(path) }; + if changed { + self.publish(&mut state); + } + } +} + +impl DocumentObserver for TscWatch { + fn opened(&self, info: &DocumentInfo) { + self.set_open(&info.path.0, true); + } + + fn closed(&self, _doc: ide_core::DocId, path: &Path) { + self.set_open(path, false); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ide_core::{Pos, Range, Severity}; + + fn diag(line: u32, message: &str) -> Diagnostic { + Diagnostic { + range: Range::new(Pos::new(line, 0), Pos::new(line, 1)), + severity: Severity::Error, + message: message.into(), + source: Some(SOURCE.into()), + code: None, + unnecessary: false, + deprecated: false, + server: Some(SOURCE.into()), + } + } + + fn files(entries: &[(&str, Vec<Diagnostic>)]) -> BTreeMap<PathBuf, Vec<Diagnostic>> { + entries.iter().map(|(p, d)| (PathBuf::from(p), d.clone())).collect() + } + + #[test] + fn open_files_keep_only_the_language_servers_errors() { + let mut state = State::default(); + let b = diag(0, "Type 'string' is not assignable to type 'number'."); + state + .results + .insert("/p/tsconfig.json".into(), files(&[("/p/b.ts", vec![b.clone()]), ("/p/c.ts", vec![diag(1, "c")])])); + // The same problem from a second root is listed once. + state.results.insert("/p/src/tsconfig.json".into(), files(&[("/p/b.ts", vec![b.clone()])])); + assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![b.clone()]), ("/p/c.ts".into(), vec![diag(1, "c")])]); + assert!(state.refresh().is_empty(), "nothing changed, nothing sent"); + + state.open.insert("/p/b.ts".into()); + assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![])]); + state.open.remove(Path::new("/p/b.ts")); + assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![b])]); + + // Fixed: the next compilation reports nothing for the files. + state.results.clear(); + assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![]), ("/p/c.ts".into(), vec![])]); + } + + #[test] + fn configs_skip_ignored_excluded_and_sample_folders() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + for dir in + ["", "apps/web", "test/fixtures/broken", "examples/demo", "generated", "vendor/lib", ".cache", "a/b/c/d"] + { + std::fs::create_dir_all(root.join(dir)).unwrap(); + std::fs::write(root.join(dir).join("tsconfig.json"), "{}").unwrap(); + } + std::fs::write(root.join(".gitignore"), "/vendor/\n").unwrap(); + let found = configs(root, &["generated".into()]); + assert_eq!(found, [root.join("apps/web/tsconfig.json"), root.join("tsconfig.json")]); + } + + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_option_starts_and_stops_the_projects_tsc() { + use std::os::unix::fs::PermissionsExt; + use std::time::{Duration, Instant}; + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap().join("p"); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::create_dir_all(root.join("node_modules/.bin")).unwrap(); + std::fs::write(root.join("tsconfig.json"), "{}").unwrap(); + std::fs::write(root.join("src/b.ts"), "export const b: number = a;\n").unwrap(); + // Records its process, prints one compilation and keeps watching, like `tsc --watch`. + let tsc = root.join("node_modules/.bin/tsc"); + std::fs::write( + &tsc, + "#!/bin/sh\necho $$ >> pids.txt\n\ + echo 'src/b.ts(1,26): error TS2322: Type string is not assignable to type number.'\n\ + echo '1:00:00 PM - Found 1 error. Watching for file changes.'\nexec sleep 60\n", + ) + .unwrap(); + std::fs::set_permissions(&tsc, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let settings = Arc::new(SettingsStore::load(&tmp.path().join("config"), Some(&root))); + let events: Arc<Mutex<Vec<(PathBuf, usize)>>> = Arc::default(); + let sink: SharedSink = Arc::new({ + let events = events.clone(); + move |e: IdeEvent| { + if let IdeEvent::Diagnostics { path, source, items } = e { + assert_eq!(source, SOURCE); + events.lock().push((path.0, items.len())); + } + } + }); + let trusted = Arc::new(AtomicBool::new(true)); + let watch = TscWatch::new(root.clone(), settings.clone(), sink, trusted.clone()); + let runtime = tokio::runtime::Handle::current(); + let b = root.join("src/b.ts"); + let pids = || -> Vec<u32> { + std::fs::read_to_string(root.join("pids.txt")) + .unwrap_or_default() + .lines() + .filter_map(|l| l.parse().ok()) + .collect() + }; + let until = |what: &str, ok: &dyn Fn() -> bool| { + let deadline = Instant::now() + Duration::from_secs(10); + while !ok() { + assert!(Instant::now() < deadline, "timed out waiting for {what}"); + std::thread::sleep(Duration::from_millis(50)); + } + }; + let last = || events.lock().iter().rev().find(|(p, _)| *p == b).map(|(_, n)| *n); + let set = |on: bool| { + settings + .set(ide_workspace::settings::SettingsScope::Project, "languages.typescript.watchProblems", on.into()) + .unwrap(); + watch.apply(&runtime); + }; + + // Off by default: nothing runs. + watch.apply(&runtime); + tokio::time::sleep(Duration::from_millis(500)).await; + assert!(pids().is_empty() && events.lock().is_empty()); + + set(true); + until("the error of b.ts", &|| last() == Some(1)); + let first = pids()[0]; + // Applying again (another setting changed) keeps the one watcher. + watch.apply(&runtime); + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!(pids(), [first]); + + set(false); + assert_eq!(last(), Some(0), "turning it off clears its errors at once"); + until("tsc to stop", &|| !ide_core::process::process_alive(first)); + + // Restricted Mode stops it too, and trusting the project starts it again. + set(true); + until("a second tsc", &|| pids().len() == 2 && last() == Some(1)); + trusted.store(false, Ordering::Release); + watch.apply(&runtime); + assert_eq!(last(), Some(0)); + until("tsc to stop", &|| !ide_core::process::process_alive(pids()[1])); + trusted.store(true, Ordering::Release); + watch.apply(&runtime); + until("a third tsc", &|| pids().len() == 3 && last() == Some(1)); + + // Closing the project stops it for good. + watch.stop(); + assert_eq!(last(), Some(0)); + until("tsc to stop", &|| !ide_core::process::process_alive(pids()[2])); + watch.apply(&runtime); + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!(pids().len(), 3, "nothing starts after the project closed"); + } +} diff --git a/crates/ide-host/tests/distribution.rs b/crates/ide-host/tests/distribution.rs index fee4b45e0..ea82cd625 100644 --- a/crates/ide-host/tests/distribution.rs +++ b/crates/ide-host/tests/distribution.rs @@ -211,7 +211,7 @@ fn write_index( /// The download sources setting with `mirror` as the GitHub proxy prefix (Tools › Download sources). fn download_sources(mirror: &str) -> ide_core::settings::ToolDownloadSettings { - ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into() } + ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into(), ..Default::default() } } /// Security audit lead 5: an index entry's id and version name the download file, diff --git a/crates/ide-host/tests/external_log.rs b/crates/ide-host/tests/external_log.rs index 946c07e52..9c9786ac2 100644 --- a/crates/ide-host/tests/external_log.rs +++ b/crates/ide-host/tests/external_log.rs @@ -110,3 +110,49 @@ async fn external_history_is_readable_and_never_becomes_a_write_target() { assert!(!deleted.exists()); host.close_project("main"); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn revision_images_use_the_selected_git_blob_and_window() { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let root = base.join("repo"); + std::fs::create_dir(&root).unwrap(); + git(&root, &["init", "-b", "main"]); + let old = root.join("old.PNG"); + let new = root.join("new.webp"); + std::fs::write(&old, [0x89, 0x00, 0xff]).unwrap(); + std::fs::write(root.join("icon.svg"), b"<svg/>").unwrap(); + std::fs::write(root.join("photo.jpeg"), [0xff, 0xd8]).unwrap(); + git(&root, &["add", "."]); + git(&root, &["commit", "-m", "old image"]); + let first = git(&root, &["rev-parse", "HEAD"]); + git(&root, &["mv", "old.PNG", "new.webp"]); + std::fs::write(&new, [0xff, 0xfe]).unwrap(); + git(&root, &["commit", "-am", "rename and change image"]); + std::fs::write(&new, [0x00, 0x80]).unwrap(); + git(&root, &["add", "new.webp"]); + std::fs::write(&new, "working tree only").unwrap(); + + let host = Host::new(common::host_config(&base)); + let read = |window, path: &Path, rev: &str| vcs::vcs_image_at(&host, window, path.to_owned(), rev.to_owned()); + assert!(read("standalone", &old, &first).await.is_err()); + vcs::vcs_open_external_log(&host, "standalone", root.clone()).await.unwrap(); + assert_eq!(read("standalone", &old, &first).await.unwrap().as_deref(), Some("data:image/png;base64,iQD/")); + assert!(read("another-window", &old, &first).await.is_err()); + + host.trust.decide(&root, false, false).unwrap(); + host.open_project("project", &root).unwrap(); + assert_eq!(read("project", &new, "HEAD").await.unwrap().as_deref(), Some("data:image/webp;base64,//4=")); + assert_eq!(read("project", &new, ":0").await.unwrap().as_deref(), Some("data:image/webp;base64,AIA=")); + assert_eq!(read("project", &old, "HEAD").await.unwrap(), None); + assert_eq!( + read("project", &root.join("icon.svg"), "HEAD").await.unwrap().as_deref(), + Some("data:image/svg+xml;base64,PHN2Zy8+") + ); + assert_eq!( + read("project", &root.join("photo.jpeg"), "HEAD").await.unwrap().as_deref(), + Some("data:image/jpeg;base64,/9g=") + ); + assert!(read("project", &base.join("outside.png"), "HEAD").await.is_err()); + assert!(read("project", &root.join("file.txt"), "HEAD").await.is_err()); +} diff --git a/crates/ide-host/tests/language_smoke.rs b/crates/ide-host/tests/language_smoke.rs index b55ff283c..903cdaef3 100644 --- a/crates/ide-host/tests/language_smoke.rs +++ b/crates/ide-host/tests/language_smoke.rs @@ -696,6 +696,131 @@ async fn typescript() { smoke("typescript", TYPESCRIPT).await; } +/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any. +fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> { + events.lock().unwrap().iter().rev().find_map(|e| match e { + IdeEvent::Diagnostics { path: p, source, items } if source == "tsc" && **p == *path => { + Some(items.iter().map(|d| d.message.clone()).collect()) + } + _ => None, + }) +} + +/// Problems › TypeScript Project Errors (#6073): the project's own `tsc --watch` reports the error +/// an edit of one file causes in another that is not open, holds it back while that file is open, +/// clears it once fixed, checks a solution with project references as well, and writes nothing +/// into the project. TypeScript comes from `OPENIDEA_SMOKE_TYPESCRIPT` (a `typescript` package +/// folder), else the global npm install. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[ignore = "language smoke: needs typescript"] +async fn typescript_project_errors() { + let typescript = std::env::var_os("OPENIDEA_SMOKE_TYPESCRIPT").map_or_else( + || { + let out = std::process::Command::new("npm").args(["root", "-g"]).output().expect("npm root -g"); + PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()).join("typescript") + }, + PathBuf::from, + ); + assert!(typescript.join("bin/tsc").is_file(), "no TypeScript in {}", typescript.display()); + let checks = Checks { + files: &[ + // Fails from the start: its error marks the end of the first compilation. + ("src/probe.ts", "export const probe: number = \"x\";\n"), + ("packages/tsconfig.json", r#"{"files": [], "references": [{"path": "./core"}, {"path": "./app"}]}"#), + ( + "packages/core/tsconfig.json", + r#"{"compilerOptions": {"composite": true, "strict": true, "outDir": "out"}}"#, + ), + ("packages/core/index.ts", "export const version: number = 1;\n"), + ( + "packages/app/tsconfig.json", + r#"{"compilerOptions": {"composite": true, "strict": true, "outDir": "out"}, "references": [{"path": "../core"}]}"#, + ), + ( + "packages/app/index.ts", + "import { version } from \"../core/index\";\nexport const label: string = version;\n", + ), + ], + ..TYPESCRIPT + }; + let smoke = Smoke::start("typescript", &checks).await; + let root = smoke.root.clone(); + std::fs::create_dir_all(root.join("node_modules/.bin")).unwrap(); + std::os::unix::fs::symlink(&typescript, root.join("node_modules/typescript")).unwrap(); + std::os::unix::fs::symlink("../typescript/bin/tsc", root.join("node_modules/.bin/tsc")).unwrap(); + async fn wait(what: &str, ok: impl Fn() -> bool) { + let deadline = Instant::now() + Duration::from_secs(60); + while !ok() { + assert!(Instant::now() < deadline, "timed out waiting for {what}"); + tokio::time::sleep(Duration::from_millis(200)).await; + } + } + let errors = |file: &str| tsc_errors(&smoke.events, &root.join(file)); + let has = |file: &'static str, text: &'static str| { + move || errors(file).is_some_and(|e| e.iter().any(|m| m.contains(text))) + }; + let clear = |file: &'static str| move || errors(file).is_some_and(|e| e.is_empty()); + let set = |on: bool| { + let scope = ide_workspace::settings::SettingsScope::Project; + ops::project::settings_set( + &smoke.host, + WINDOW, + scope, + "languages.typescript.watchProblems".into(), + on.to_string(), + ) + .unwrap(); + }; + + set(true); + wait("the first compilation", has("src/probe.ts", "not assignable")).await; + wait("the solution's error", has("packages/app/index.ts", "not assignable to type 'string'")).await; + + // Renaming an export in money.ts breaks index.ts, which is not open. + let money = root.join("src/money.ts"); + let original = std::fs::read_to_string(&money).unwrap(); + std::fs::write(&money, original.replace("export function formatMoney", "export function formatPrice")).unwrap(); + wait("index.ts to break", has("src/index.ts", "formatMoney")).await; + assert_eq!(errors("src/money.ts"), None, "the edited file itself is fine"); + + // Open, it shows the language server's errors only; closed again, the watcher's. + let doc = ops::doc::doc_open(&smoke.host, WINDOW, root.join("src/index.ts")).await.unwrap(); + wait("index.ts held back while open", clear("src/index.ts")).await; + ops::doc::doc_close(&smoke.host, WINDOW, doc.id).await.unwrap(); + wait("index.ts back once closed", has("src/index.ts", "formatMoney")).await; + + std::fs::write(&money, &original).unwrap(); + // The fixture's own error (an unused function) stays. + let fixed = + move || errors("src/index.ts").is_some_and(|e| !e.is_empty() && !e.iter().any(|m| m.contains("formatMoney"))); + wait("index.ts fixed", fixed).await; + + set(false); + wait("every error cleared", || { + ["src/probe.ts", "src/index.ts", "packages/app/index.ts"].into_iter().all(|f| clear(f)()) + }) + .await; + + // A background check writes nothing into the project: no `.js`, `.d.ts` or `.tsbuildinfo`. + fn outputs(dir: &Path, out: &mut Vec<PathBuf>) { + for entry in std::fs::read_dir(dir).unwrap().flatten() { + let path = entry.path(); + if entry.file_name() == "node_modules" { + continue; + } + if path.is_dir() { + outputs(&path, out); + } else if [".js", ".d.ts", ".tsbuildinfo"].iter().any(|ext| path.to_string_lossy().ends_with(ext)) { + out.push(path); + } + } + } + let mut written = Vec::new(); + outputs(&root, &mut written); + assert_eq!(written, Vec::<PathBuf>::new()); +} + const PYTHON: Checks = Checks { fixture: "python-app", // Ruff (lint, quick fixes, formatting) starts in projects configured for it. diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index f64e0d6a8..afb5a3bc7 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -1391,6 +1391,65 @@ fn ungranted_capabilities_are_denied_not_trapped() { assert_eq!(f.workspace.text("src/notes.txt"), "one two three\nfour five\n"); } +/// A missing `agents` grant is an error the plugin can handle, not a trap. +#[test] +fn ungranted_agents_fork_is_denied_not_trapped() { + let f = fixture(Limits::default()); + f.install(&misbehave_pkg()); + let err = f + .host + .run_command("misbehave", "fork-session", Some("claude 11111111-2222-3333-4444-555555555555 /tmp"), f.inv()) + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err:?}"); + assert!(err.message.contains("agents"), "{err:?}"); + let info = f.host.info_of("misbehave").unwrap(); + assert_eq!((info.status, info.stats.crashes), (PluginStatus::Active, 0), "the instance lives on"); + assert_eq!(info.stats.errors, 0, "a missing grant is not the plugin failing"); +} + +/// With the `agents` grant the call reaches the core fork over a real project: +/// an unknown session is the core's `not-found`, not a denial or a host stub. +#[tokio::test] +async fn granted_agents_fork_reaches_the_core() { + let f = fixture(Limits::default()); + // Hermetic: the core scans the home transcript folders; a real ~/.codex with + // thousands of rollouts would time the command out. + // SAFETY: set before the Host reads HOME; nextest isolates this test's process. + unsafe { std::env::set_var("HOME", f._tmp.path().join("home")) }; + let host = Arc::new(Host::new(HostConfig { + config_dir: f._tmp.path().join("config"), + data_dir: f._tmp.path().join("data"), + local_data_dir: f._tmp.path().join("local"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(ide_core::NullSink)), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + })); + host.trust.decide(&f.project, true, false).unwrap(); + host.open_project("main", &f.project).unwrap(); + f.host.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host))))); + + // `misbehave` with the `agents` grant, which needs API 1.18. + let pkg = f._tmp.path().join("misbehave-agents"); + copy_dir(&misbehave_pkg(), &pkg); + let manifest = pkg.join("plugin.toml"); + let text = std::fs::read_to_string(&manifest).unwrap(); + let text = text + .replace("required = [\"project.read\"]", "required = [\"project.read\", \"agents\"]") + .replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.18\""); + std::fs::write(&manifest, text).unwrap(); + f.install(&pkg); + + let session = "11111111-2222-3333-4444-555555555555"; + let arg = format!("claude {session} {}", f.project.to_str().unwrap()); + let err = f.run("misbehave", "fork-session", Some(&arg)).unwrap_err(); + assert!(err.contains("unknown claude session"), "{err}"); + // Detached: the blocking close joins the LSP/index workers, which can stall under nextest. + host.close_project_detached("main"); +} + /// A trap drops the instance, which restarts on next use after a /// backoff that doubles; only consecutive crashes stop the plugin. #[test] @@ -1652,7 +1711,7 @@ fn idle_instances_are_reclaimed_and_schedules_reactivate() { assert_eq!(f.host.instances(), 0); let info = f.host.info_of("misbehave").unwrap(); assert_eq!((info.status, info.stats.reclaims), (PluginStatus::Inactive, 1)); - assert_eq!(f.command_titles("misbehave").len(), 24, "contributions stay"); + assert_eq!(f.command_titles("misbehave").len(), 25, "contributions stay"); assert_eq!(f.run("misbehave", "echo", Some("y")).unwrap().as_deref(), Some("y")); assert_eq!(f.host.info_of("misbehave").unwrap().stats.activations, 2); @@ -2274,6 +2333,45 @@ fn java_agent_loads_only_while_granted_and_unchanged() { assert_eq!(launch(), (plain, vec![])); } +/// A Java agent bound to an executor (`executor = "Hot Reload"`, API 1.18): the plugin's +/// "Run/Debug with Hot Reload" launches get it, plain launches don't, and the same grant +/// and jar pin apply. +#[test] +fn an_executor_bound_java_agent_loads_only_through_its_executor() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("java-agent"); + copy_dir(&sample("java-agent"), &pkg); + let manifest = std::fs::read_to_string(pkg.join("plugin.toml")).unwrap(); + let manifest = manifest + .replace("^1.10", "^1.18") + .replace("args = \"mode=test\"", "args = \"mode=test\"\nexecutor = \"Hot Reload\""); + std::fs::write(pkg.join("plugin.toml"), manifest).unwrap(); + + let info = f.host.install_from_dir(&pkg, &Consent::default()).unwrap(); + assert!(info.contributions.iter().any(|c| c.label == "fixture agent.jar=mode=test (Run with Hot Reload)")); + let agent = info.java_agent.expect("agent metadata"); + assert_eq!(agent.executor.as_deref(), Some("Hot Reload")); + assert!(!agent.approved); + let source = f.host.java_agents(); + let ungranted = ide_run::java_agent::for_executor(&source.agents(), None, Some("java-agent")); + assert!(ungranted.options.is_empty()); + assert!(ungranted.notes[0].contains("needs the java.agent permission"), "{:?}", ungranted.notes); + + f.host.set_capability("java-agent", "java.agent", true).unwrap(); + let jar = dunce::canonicalize(f.installed("java-agent").join("agent/fixture agent.jar")).unwrap(); + let option = format!("-javaagent:{}=mode=test", jar.display()); + let plain = ide_run::java_agent::for_executor(&source.agents(), None, None); + assert_eq!(plain, ide_run::java_agent::Agents::default(), "a plain Run leaves it out"); + let through = ide_run::java_agent::for_executor(&source.agents(), None, Some("java-agent")); + assert_eq!(through.options, [option]); + assert!(through.notes.is_empty()); + + f.host.set_enabled("java-agent", false).unwrap(); + let gone = ide_run::java_agent::for_executor(&source.agents(), None, Some("java-agent")); + assert!(gone.options.is_empty() && gone.notes.len() == 1); +} + /// Compiled components are cached across runs (keyed by module and /// engine), so a cold activation only deserializes. #[test] @@ -6533,6 +6631,272 @@ fn net_ask_session_hosts_are_ephemeral_and_cleared_with_plugin_grants() { assert_eq!(seen.lock().len(), 9); } +/// Sets a plugin's global setting value in the test workspace. +fn set_setting(f: &Fixture, plugin: &str, value: &str) { + let mut map = serde_json::Map::new(); + map.insert("server".into(), serde_json::Value::String(value.into())); + f.workspace.global_settings.lock().insert(plugin.to_owned(), map); +} + +fn net_setting_of<'a>(info: &'a PluginInfo, setting: &str) -> Option<&'a PluginNetSetting> { + info.net_settings.iter().find(|s| s.setting == setting && !s.http) +} + +fn http_setting_of<'a>(info: &'a PluginInfo, setting: &str) -> Option<&'a PluginNetSetting> { + info.net_settings.iter().find(|s| s.setting == setting && s.http) +} + +/// `net:setting:` grants: the host is approved in Settings, materializes while +/// the setting holds it, replaces and clears with it, and never asks at +/// request time — a pending host stays denied without a dialog (#3809). +#[test] +fn net_setting_grants_approve_replace_and_clear_with_the_setting() { + use ide_extension::ledger::{Ledger, Subject}; + let f = fixture(Limits::default()); + f.install(&sample("net-setting")); + let subject = Subject::Installed("netsetting".into()); + let (port, seen) = http_server("relay ok", |_| Duration::ZERO); + let url = format!("http://127.0.0.1:{port}/"); + + // Unset: denied exactly as today, unattended and attended, no dialog. + let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err(); + assert!(err.contains("net:127.0.0.1") && err.contains("not granted"), "{err}"); + let err = f.host.run_command("netsetting", "fetch", Some(&url), Invocation::default()).unwrap_err(); + assert!(err.message.contains("not granted"), "{err:?}"); + assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. }))); + assert_eq!(seen.lock().len(), 0); + + // Approved when the value is applied in Settings: the host materializes. + set_setting(&f, "netsetting", &url); + // The host the user was shown must still be the setting's value: a value + // the plugin wrote after the dialog opened is not approved in its place. + let err = f.host.approve_net_setting("netsetting", "server", false, "jira.corp.example").unwrap_err(); + assert!(err.message.contains("now holds 127.0.0.1"), "{err:?}"); + assert_eq!(net_setting_of(&f.host.info_of("netsetting").unwrap(), "server").unwrap().host, None); + f.host.approve_net_setting("netsetting", "server", false, "127.0.0.1").unwrap(); + let info = f.host.info_of("netsetting").unwrap(); + let entry = net_setting_of(&info, "server").unwrap(); + assert_eq!(entry.host.as_deref(), Some("127.0.0.1")); + assert_eq!(entry.pending, None); + assert_eq!(seen.lock().len(), 0); + for invocation in [f.inv(), Invocation::default()] { + let result = f.host.run_command("netsetting", "fetch", Some(&url), invocation).unwrap(); + assert_eq!(result.as_deref(), Some("relay ok")); + } + assert_eq!(seen.lock().len(), 2); + assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. }))); + assert_eq!( + Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str), + Some("127.0.0.1") + ); + + // A value that changed anywhere else is not approved: pending, and a call + // to it is denied without a dialog — unattended and from a window. + set_setting(&f, "netsetting", "jira.corp.example"); + let info = f.host.info_of("netsetting").unwrap(); + let entry = net_setting_of(&info, "server").unwrap(); + assert_eq!(entry.host, None); + assert_eq!(entry.pending.as_deref(), Some("jira.corp.example")); + let err = f.run("netsetting", "fetch", Some("http://jira.corp.example/")).unwrap_err(); + assert!(err.contains("not granted"), "{err}"); + let err = f + .host + .run_command("netsetting", "fetch", Some("http://jira.corp.example/"), Invocation::default()) + .unwrap_err(); + assert!(err.message.contains("not granted"), "{err:?}"); + assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. }))); + assert_eq!(seen.lock().len(), 2); + + // The old host no longer materializes either: it is not the setting's value. + f.host.set_enabled("netsetting", false).unwrap(); + f.host.set_enabled("netsetting", true).unwrap(); + let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err(); + assert!(err.contains("not granted"), "{err}"); + assert_eq!(seen.lock().len(), 2); + + // The Approve action replaces the approval only after the user confirms it. + f.host.approve_net_setting("netsetting", "server", false, "jira.corp.example").unwrap(); + let info = f.host.info_of("netsetting").unwrap(); + let entry = net_setting_of(&info, "server").unwrap(); + assert_eq!(entry.host.as_deref(), Some("jira.corp.example")); + assert_eq!(entry.pending, None); + assert_eq!( + Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str), + Some("jira.corp.example") + ); + // And the old loopback host stays denied now. + let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err(); + assert!(err.contains("not granted"), "{err}"); + assert_eq!(seen.lock().len(), 2); + + // Revoking the manifest grant drops the record; granting it back asks for + // a fresh approval. + f.host.set_capability("netsetting", "net:setting:server", false).unwrap(); + assert!(Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.is_empty()); + f.host.set_capability("netsetting", "net:setting:server", true).unwrap(); + let info = f.host.info_of("netsetting").unwrap(); + let entry = net_setting_of(&info, "server").unwrap(); + assert_eq!(entry.host, None); + assert_eq!(entry.pending.as_deref(), Some("jira.corp.example")); + + // Clearing the setting removes the grant. + f.host.approve_net_setting("netsetting", "server", false, "jira.corp.example").unwrap(); + set_setting(&f, "netsetting", ""); + f.host.forget_net_setting("netsetting", "server", false).unwrap(); + assert!(Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.is_empty()); + let info = f.host.info_of("netsetting").unwrap(); + let entry = net_setting_of(&info, "server").unwrap(); + assert_eq!(entry.host, None); + assert_eq!(entry.pending, None); + let err = f + .host + .run_command("netsetting", "fetch", Some("http://jira.corp.example/"), Invocation::default()) + .unwrap_err(); + assert!(err.message.contains("not granted"), "{err:?}"); + assert_eq!(seen.lock().len(), 2); +} + +/// `net.http:setting:` reaches plain HTTP on a non-loopback address; its +/// record is kept per transport, next to the HTTPS one. +#[test] +fn net_http_setting_grants_reach_plain_http_per_transport() { + use std::io::{BufRead, BufReader, Read, Write}; + let f = fixture(Limits::default()); + f.install(&sample("net-setting")); + // 127.0.0.2 is this machine's loopback too, but not in the loopback list + // of `net_capability`: its plain HTTP needs the `net.http:` grant. + // macOS only configures 127.0.0.1 on lo0 by default. + let Ok(listener) = std::net::TcpListener::bind("127.0.0.2:0") else { + eprintln!("skipped: 127.0.0.2 is not bound to a loopback interface here"); + return; + }; + let port = listener.local_addr().unwrap().port(); + let url = format!("http://127.0.0.2:{port}/"); + let seen: Arc<Mutex<Vec<String>>> = Arc::default(); + { + let seen = seen.clone(); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut writer = stream; + let mut line = String::new(); + let mut len = 0; + loop { + let read = reader.read_line(&mut line).unwrap_or(0); + if read == 0 || line == "\r\n" { + break; + } + if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") { + len = v.trim().parse().unwrap_or(0); + } + line.clear(); + } + let mut req = vec![0; len]; + let _ = reader.read_exact(&mut req); + let body = "plain ok"; + let _ = writer.write_all( + format!( + "HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\n\r\n{body}", + body.len() + ) + .as_bytes(), + ); + seen.lock().push("served".into()); + } + }); + } + + // Plain HTTP elsewhere stays out of the ask flow entirely, unattended and attended. + let err = f.run("netsetting", "fetch", Some(&url)).unwrap_err(); + assert!(err.contains("net.http:127.0.0.2") && err.contains("not granted"), "{err}"); + assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. }))); + + // Approved for the `net.http:` transport only: the record is its own. + set_setting(&f, "netsetting", &url); + f.host.approve_net_setting("netsetting", "server", true, "127.0.0.2").unwrap(); + let info = f.host.info_of("netsetting").unwrap(); + let entry = http_setting_of(&info, "server").unwrap(); + assert_eq!(entry.host.as_deref(), Some("127.0.0.2")); + assert!(entry.http); + // The HTTPS transport has no approval of its own: the setting's host is pending there. + let https = net_setting_of(&info, "server").unwrap(); + assert_eq!(https.host, None); + assert_eq!(https.pending.as_deref(), Some("127.0.0.2")); + for invocation in [f.inv(), Invocation::default()] { + let result = f.host.run_command("netsetting", "fetch", Some(&url), invocation).unwrap(); + assert_eq!(result.as_deref(), Some("plain ok")); + } + assert_eq!(seen.lock().len(), 2); + assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. }))); + + // A `net:` grant for the same host would not cover plain HTTP; without the + // `net.http:` approval the request stays denied (redirect rules unchanged). + f.host.forget_net_setting("netsetting", "server", true).unwrap(); + let err = f.host.run_command("netsetting", "fetch", Some(&url), Invocation::default()).unwrap_err(); + assert!(err.message.contains("net.http:127.0.0.2") && err.message.contains("not granted"), "{err:?}"); + assert_eq!(seen.lock().len(), 2); +} + +/// On a remote host, a setting-derived approval is kept for the session only, +/// like the `net:ask` answers (#3809). +#[test] +fn net_setting_approvals_are_session_only_on_remote_hosts() { + use ide_extension::ledger::{Ledger, Subject}; + let f = fixture(Limits::default()); + f.host.set_net_hosts_session_only(); + f.install(&sample("net-setting")); + let subject = Subject::Installed("netsetting".into()); + let (port, seen) = http_server("session ok", |_| Duration::ZERO); + let url = format!("http://127.0.0.1:{port}/"); + + set_setting(&f, "netsetting", &url); + f.host.approve_net_setting("netsetting", "server", false, "127.0.0.1").unwrap(); + for invocation in [f.inv(), Invocation::default()] { + let result = f.host.run_command("netsetting", "fetch", Some(&url), invocation).unwrap(); + assert_eq!(result.as_deref(), Some("session ok")); + } + assert_eq!(seen.lock().len(), 2); + assert!(Ledger::load(&f.plugins_dir).get(&subject).unwrap().setting_hosts.is_empty()); + + // Nothing was written: the approval dies with the session (disable/enable). + f.host.set_enabled("netsetting", false).unwrap(); + f.host.set_enabled("netsetting", true).unwrap(); + let err = f.host.run_command("netsetting", "fetch", Some(&url), Invocation::default()).unwrap_err(); + assert!(err.message.contains("not granted"), "{err:?}"); + assert!(!f.take_events().iter().any(|(_, e)| matches!(e, PluginEvent::PromptRequested { .. }))); + assert_eq!(seen.lock().len(), 2); +} + +/// A `net:setting:` grant must name a `string` setting in the plugin's own +/// schema; checked at install like the other manifest checks (#3809). +#[test] +fn a_setting_grant_needs_a_string_setting_in_the_own_schema() { + let f = fixture(Limits::default()); + let dir = tempfile::tempdir().unwrap(); + let pkg = dir.path().join("net-setting-bad"); + copy_dir(&sample("net-setting"), &pkg); + let manifest = pkg.join("plugin.toml"); + let text = std::fs::read_to_string(&manifest).unwrap(); + std::fs::write(&manifest, text.replace("net:setting:server", "net:setting:missing")).unwrap(); + let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err(); + assert!(err.message.contains("`net:setting:missing`") && err.message.contains("string"), "{err:?}"); + + let pkg = dir.path().join("net-setting-number"); + copy_dir(&sample("net-setting"), &pkg); + let schema = pkg.join("settings.json"); + let text = std::fs::read_to_string(&schema).unwrap(); + std::fs::write( + &schema, + text.replace( + "\"type\":\"string\",\"title\":\"Server\",\"default\":\"\"", + "\"type\":\"number\",\"title\":\"Server\",\"default\":0", + ), + ) + .unwrap(); + let err = f.host.install_from_dir(&pkg, &Consent::all()).unwrap_err(); + assert!(err.message.contains("net:setting:server") && err.message.contains("string"), "{err:?}"); +} + /// Runs api14's `fetch` in its window; once the `net:ask` question arrives, /// answers it (`None`: dismisses). Returns the command's result and the prompt. fn net_ask_run_and_answer( @@ -7630,7 +7994,7 @@ fn contributes_skills_needs_api_1_15_and_warns_without_failing_plugin_on_bad_ent "id = \"acme.mixed-skills\"\n\ name = \"Mixed Skills\"\n\ version = \"1.0.0\"\n\ - engines.openidea = \"^1.15\"\n\n\ + engines.openidea = \"^1.18\"\n\n\ [[contributes.skills]]\npath = \"skills/good-skill/SKILL.md\"\n\ [[contributes.skills]]\npath = \"../outside/SKILL.md\"\n\ [[contributes.skills]]\npath = \"skills/not-skill-md/README.md\"\n\ diff --git a/crates/ide-host/tests/trust_vcs_sweep.rs b/crates/ide-host/tests/trust_vcs_sweep.rs index 6ad0c067b..0e5e3b540 100644 --- a/crates/ide-host/tests/trust_vcs_sweep.rs +++ b/crates/ide-host/tests/trust_vcs_sweep.rs @@ -52,6 +52,7 @@ fn arm(root: &Path, markers: &Path) -> Armed { git(root, &["config", key, value]); } std::fs::write(root.join("src/a.txt"), "one\ntwo\n").unwrap(); + std::fs::write(root.join("asset.jpg"), [0xff, 0xd8]).unwrap(); git(root, &["add", "."]); git(root, &["commit", "-qm", "first"]); let first = git(root, &["rev-parse", "HEAD"]); @@ -168,6 +169,7 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() { call!("vcs_line_hunks", "", vcs::vcs_line_hunks(host, w, file.clone())), call!("vcs_staging_line_hunks", "", vcs::vcs_staging_line_hunks(host, w, file.clone(), None)), call!("vcs_file_at", "", vcs::vcs_file_at(host, w, file.clone(), None)), + call!("vcs_image_at", "", vcs::vcs_image_at(host, w, project.root.join("asset.jpg"), ":0".into())), call!( "vcs_diff_entries", "", diff --git a/crates/ide-index/src/data.rs b/crates/ide-index/src/data.rs index 087ee5f8c..f9bdb83e1 100644 --- a/crates/ide-index/src/data.rs +++ b/crates/ide-index/src/data.rs @@ -42,8 +42,8 @@ pub(crate) fn mask_bit(b: u8) -> u64 { match b.to_ascii_lowercase() { c @ b'a'..=b'z' => 1 << (c - b'a'), c @ b'0'..=b'9' => 1 << (26 + c - b'0'), - b'_' => 1 << 36, - b'-' => 1 << 37, + // One bit: file and folder matching takes `-` and `_` for each other. + b'_' | b'-' => 1 << 36, b'.' => 1 << 38, b'/' => 1 << 39, b'$' => 1 << 40, diff --git a/crates/ide-index/src/lib.rs b/crates/ide-index/src/lib.rs index 837042fa2..46a84501f 100644 --- a/crates/ide-index/src/lib.rs +++ b/crates/ide-index/src/lib.rs @@ -391,6 +391,11 @@ impl ProjectIndex { matching::symbols_named_within(&self.shared.data.read(), name, kind, roots, limit) } + /// Symbols of `kind` whose name starts with `prefix`, by path then position. + pub fn symbols_prefixed(&self, prefix: &str, kind: SymbolKind, limit: usize) -> Vec<SymbolMatch> { + matching::symbols_prefixed(&self.shared.data.read(), prefix, kind, limit) + } + /// Symbols named exactly one of `names` whose file is inside `root`, at most `limit` per name. pub fn symbols_named_any(&self, names: &[String], root: &Path, limit: usize) -> Vec<SymbolMatch> { matching::symbols_named_any(&self.shared.data.read(), names, root, limit) diff --git a/crates/ide-index/src/matching.rs b/crates/ide-index/src/matching.rs index 5421835ff..1a3810e3b 100644 --- a/crates/ide-index/src/matching.rs +++ b/crates/ide-index/src/matching.rs @@ -31,6 +31,8 @@ const TYPE_LIKE: u32 = 20; thread_local! { static MATCHER: RefCell<Matcher> = RefCell::new(Matcher::new(Config::DEFAULT.match_paths())); + /// An ASCII candidate with `_` read as `-`, for a folding [`Needle`]. + static FOLDED: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) }; } fn with_matcher<R>(f: impl FnOnce(&mut Matcher) -> R) -> R { @@ -43,30 +45,74 @@ struct Needle { original: String, utf32: Utf32String, mask: u64, + /// A file or folder needle with `-` or `_`: either matches both in a candidate + /// (`bit_matcher` finds `bit-matcher/`); both sides are matched with `_` read as `-`. + fold: bool, } impl Needle { fn new(s: &str) -> Self { let lower = s.to_lowercase(); - Self { mask: char_mask(&lower), utf32: Utf32String::from(lower.as_str()), lower, original: s.to_owned() } + Self { + mask: char_mask(&lower), + utf32: Utf32String::from(lower.as_str()), + lower, + original: s.to_owned(), + fold: false, + } + } + + /// A needle for file and folder names, whose `-` and `_` match each other. + fn file(s: &str) -> Self { + let mut needle = Self::new(s); + needle.fold = needle.lower.contains(['-', '_']); + if needle.fold { + needle.utf32 = Utf32String::from(needle.lower.replace('_', "-").as_str()); + } + needle } fn is_empty(&self) -> bool { self.lower.is_empty() } + /// `hay` as the matcher reads it; for a folding needle, a copy with `_` as `-`. + fn hay<'a>(&self, hay: &'a str, buf: &'a mut Vec<char>) -> Utf32Str<'a> { + if !self.fold { + return Utf32Str::new(hay, buf); + } + // The same characters `Utf32Str::new` would give, so match indices stay valid. + if matches!(Utf32Str::new(hay, &mut *buf), Utf32Str::Ascii(_)) { + buf.clear(); + buf.extend(hay.bytes().map(char::from)); + } + for c in buf.iter_mut() { + if *c == '_' { + *c = '-'; + } + } + Utf32Str::Unicode(buf) + } + fn score(&self, m: &mut Matcher, hay: &str, buf: &mut Vec<char>) -> Option<u32> { - m.fuzzy_match(Utf32Str::new(hay, buf), self.utf32.slice(..)).map(u32::from) + m.fuzzy_match(self.hay(hay, buf), self.utf32.slice(..)).map(u32::from) } /// `hay` is pure ASCII: skip `Utf32Str::new`'s check and UTF-32 conversion. fn score_ascii(&self, m: &mut Matcher, hay: &str) -> Option<u32> { - m.fuzzy_match(Utf32Str::Ascii(hay.as_bytes()), self.utf32.slice(..)).map(u32::from) + if !self.fold { + return m.fuzzy_match(Utf32Str::Ascii(hay.as_bytes()), self.utf32.slice(..)).map(u32::from); + } + FOLDED.with_borrow_mut(|folded| { + folded.clear(); + folded.extend(hay.bytes().map(|b| if b == b'_' { b'-' } else { b })); + m.fuzzy_match(Utf32Str::Ascii(folded), self.utf32.slice(..)).map(u32::from) + }) } fn indices(&self, m: &mut Matcher, hay: &str, buf: &mut Vec<char>, out: &mut Vec<u32>) -> Option<u32> { out.clear(); - let s = m.fuzzy_indices(Utf32Str::new(hay, buf), self.utf32.slice(..), out).map(u32::from); + let s = m.fuzzy_indices(self.hay(hay, buf), self.utf32.slice(..), out).map(u32::from); out.sort_unstable(); out.dedup(); s @@ -282,8 +328,8 @@ pub(crate) fn find_files( .collect(); } let fq = match q.rsplit_once('/') { - Some((dir, name)) => FileQuery::Path { dir: Needle::new(dir), name: Needle::new(name) }, - None => FileQuery::Name(Needle::new(&q)), + Some((dir, name)) => FileQuery::Path { dir: Needle::file(dir), name: Needle::file(name) }, + None => FileQuery::Name(Needle::file(&q)), }; let tiebreak = |a: &Cand, b: &Cand| a.len.cmp(&b.len).then_with(|| data.hot.rel(a.slot).cmp(data.hot.rel(b.slot))); let pool = limit * 4 + 64; @@ -350,7 +396,7 @@ pub(crate) fn find_dirs(data: &IndexData, query: &str, root: Option<&Path>, limi return Vec::new(); } let by_path = q.contains('/'); - let needle = Needle::new(q.trim_end_matches('/')); + let needle = Needle::file(q.trim_end_matches('/')); let text = data.dirs_hot.text(); // (score, rel without the trailing `/`, char offset of the name when it matched by name) let (mut best, _): (Vec<_>, Vec<char>) = data @@ -670,6 +716,34 @@ pub(crate) fn symbols_named_within( out } +/// Symbols of `kind` whose name starts with `prefix` (CSS custom properties: `--`), by path +/// then position. +pub(crate) fn symbols_prefixed(data: &IndexData, prefix: &str, kind: SymbolKind, limit: usize) -> Vec<SymbolMatch> { + let syms = &data.syms; + let mut out: Vec<SymbolMatch> = data + .files + .iter() + .flatten() + .flat_map(|e| { + (e.sym_start..e.sym_start + e.sym_len) + .filter(|&i| syms.kind(i) == kind && syms.name(i).starts_with(prefix)) + .map(move |i| SymbolMatch { + name: syms.name(i).to_string(), + kind, + container: syms.container(i).map(str::to_owned), + path: e.path.clone().into(), + rel_path: e.rel.to_string(), + range: syms.range(i), + score: 0, + indices: Vec::new(), + }) + }) + .collect(); + out.sort_by(|a, b| a.rel_path.cmp(&b.rel_path).then_with(|| a.range.cmp(&b.range))); + out.truncate(limit); + out +} + /// Symbols named exactly one of `names` whose file is inside `root`, at most `limit` per /// name, by path then position: one walk over the index for every name an agent reply shows. pub(crate) fn symbols_named_any(data: &IndexData, names: &[String], root: &Path, limit: usize) -> Vec<SymbolMatch> { @@ -734,4 +808,53 @@ mod tests { assert!(hump_bonus("OrderController", &[0, 5, 6]) > hump_bonus("OrderController", &[0, 3, 6])); assert_eq!(hump_bonus("abc", &[]), 0); } + + fn index(rels: &[&str]) -> IndexData { + let mut data = IndexData::default(); + for rel in rels { + let record = + crate::data::FileRecord { mtime: 0, size: 0, hash: [0; 32], symbols: Vec::new(), ignored: false }; + let (entry, symbols) = FileEntry::new(Path::new("/p").join(rel), (*rel).to_owned(), record); + data.insert(entry, symbols); + } + data + } + + fn files(data: &IndexData, q: &str) -> Vec<String> { + find_files(data, &Recents::new(&[]), q, None, 20).into_iter().map(|m| m.rel_path).collect() + } + + fn dirs(data: &IndexData, q: &str) -> Vec<String> { + find_dirs(data, q, None, 20).into_iter().map(|m| m.rel_path).collect() + } + + #[test] + fn dash_and_underscore_match_each_other_in_file_and_folder_names() { + let data = + index(&["bit-matcher/lib.rs", "line_parser/lib.rs", "docs/token-stream.rs", "docs/frame_sampler.rs"]); + assert_eq!(dirs(&data, "bit_matcher"), ["bit-matcher/"]); + assert_eq!(dirs(&data, "line-parser"), ["line_parser/"]); + assert_eq!(files(&data, "token_stream"), ["docs/token-stream.rs"]); + assert_eq!(files(&data, "frame-sampler"), ["docs/frame_sampler.rs"]); + assert_eq!(files(&data, "docs/token_stream"), ["docs/token-stream.rs"]); + // As before: a space or no separator matches any; `.` is not a word separator here. + assert_eq!(dirs(&data, "bit matcher"), ["bit-matcher/"]); + assert_eq!(dirs(&data, "bitmatcher"), ["bit-matcher/"]); + assert!(dirs(&data, "bit.matcher").is_empty()); + } + + #[test] + fn the_exact_separator_ranks_first() { + let data = index(&["src/bit-matcher.rs", "src/bit_matcher.rs"]); + assert_eq!(files(&data, "bit_matcher"), ["src/bit_matcher.rs", "src/bit-matcher.rs"]); + assert_eq!(files(&data, "bit-matcher"), ["src/bit-matcher.rs", "src/bit_matcher.rs"]); + } + + #[test] + fn highlights_the_other_separator() { + let data = index(&["bit-matcher/lib.rs", "docs/token-stream.rs"]); + assert_eq!(find_dirs(&data, "bit_matcher", None, 1)[0].indices, (0..11).collect::<Vec<u32>>()); + let file = &find_files(&data, &Recents::new(&[]), "token_stream", None, 1)[0]; + assert_eq!(file.indices, (5..17).collect::<Vec<u32>>()); + } } diff --git a/crates/ide-index/src/tests.rs b/crates/ide-index/src/tests.rs index 63aaf14df..cd067cd26 100644 --- a/crates/ide-index/src/tests.rs +++ b/crates/ide-index/src/tests.rs @@ -675,6 +675,37 @@ fn css_selectors_are_found_by_exact_name() { assert!(idx.symbols_named(".card", Some(SymbolKind::Field), 10).is_empty()); } +#[test] +fn css_custom_properties_are_listed_with_their_values_and_follow_edits() { + let f = Fixture::new(&[ + ("theme/light.css", ":root {\n --bg: #fff;\n --gap:\n 4px 8px;\n}\n"), + ("theme/dark.scss", "[data-theme=dark] { .x { --bg: rgb(0 0 0) !important; } }\n"), + ("theme/extra.less", ".a { --ring: var(--bg); color: red; }\n"), + ]); + let idx = f.open(); + let vars = |idx: &ProjectIndex| -> Vec<(String, String, Option<String>)> { + idx.symbols_prefixed("--", SymbolKind::Variable, 100) + .into_iter() + .map(|m| (m.rel_path, m.name, m.container)) + .collect() + }; + assert_eq!( + vars(&idx), + vec![ + ("theme/dark.scss".into(), "--bg".into(), Some("rgb(0 0 0) !important".into())), + ("theme/extra.less".into(), "--ring".into(), Some("var(--bg)".into())), + ("theme/light.css".into(), "--bg".into(), Some("#fff".into())), + ("theme/light.css".into(), "--gap".into(), Some("4px 8px".into())), + ] + ); + let light = f.root.join("theme/light.css"); + std::fs::write(&light, ":root { --fg: #222; }\n").unwrap(); + idx.update(std::slice::from_ref(&light), &[]); + assert!(idx.wait_idle(WAIT)); + let names: Vec<String> = vars(&idx).into_iter().filter(|v| v.0 == "theme/light.css").map(|v| v.1).collect(); + assert_eq!(names, vec!["--fg".to_string()]); +} + #[test] fn symbols_named_within_keeps_out_of_root_matches_from_evicting_a_root() { let f = Fixture::new(&[ diff --git a/crates/ide-language/src/lib.rs b/crates/ide-language/src/lib.rs index c238298ed..380450f64 100644 --- a/crates/ide-language/src/lib.rs +++ b/crates/ide-language/src/lib.rs @@ -28,7 +28,9 @@ pub use syntax::{ VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, merge_visibility, set_external_syntax, shift_pos, shift_range, }; -pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression}; +pub use syntax::{ + MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression, bundler_aliases, +}; /// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`]. #[derive(Clone, Debug, Serialize, Deserialize)] diff --git a/crates/ide-language/src/syntax/bundler_aliases.rs b/crates/ide-language/src/syntax/bundler_aliases.rs new file mode 100644 index 000000000..6cb1fb4a6 --- /dev/null +++ b/crates/ide-language/src/syntax/bundler_aliases.rs @@ -0,0 +1,277 @@ +//! Path aliases of a Vite, Rollup (`@rollup/plugin-alias`) or esbuild configuration, read +//! without running it. + +use super::parse; +use std::path::{Component, Path, PathBuf}; +use tree_sitter::{Language, Node}; + +/// `[alias, target]` pairs of the bundler configuration `text` in `dir`: every `alias` +/// property (Vite's `resolve.alias`, esbuild's `alias`) and, when the file uses +/// `@rollup/plugin-alias`, its `entries`. Both object (`{ '@': … }`) and array +/// (`[{ find, replacement }]`) forms. Targets are string literals, `path.resolve` / +/// `path.join` of `__dirname`, `process.cwd()` and literals, or +/// `fileURLToPath(new URL(…, import.meta.url))`, with `dir` as the configuration's +/// directory and working directory; relative literals stay relative. Aliases computed any +/// other way (variables, functions, regular expressions) are skipped. +pub fn bundler_aliases(text: &str, dir: &Path) -> Vec<(String, String)> { + let language = Language::new(tree_sitter_typescript::LANGUAGE_TYPESCRIPT); + let Some(tree) = parse(&language, text, None) else { return Vec::new() }; + let rollup = text.contains("@rollup/plugin-alias"); + let cx = Cx { src: text, dir }; + let mut out = Vec::new(); + let mut stack = vec![tree.root_node()]; + while let Some(node) = stack.pop() { + if node.kind() == "pair" + && let (Some(key), Some(value)) = (node.child_by_field_name("key"), node.child_by_field_name("value")) + && match cx.name(key) { + Some("alias") => true, + Some("entries") => rollup, + _ => false, + } + { + cx.collect(value, &mut out); + } + stack.extend(node.named_children(&mut node.walk())); + } + out +} + +struct Cx<'a> { + src: &'a str, + dir: &'a Path, +} + +impl Cx<'_> { + fn text(&self, n: Node) -> &str { + n.utf8_text(self.src.as_bytes()).unwrap_or("") + } + + /// A non-computed property key's name. + fn name(&self, key: Node) -> Option<&str> { + match key.kind() { + "property_identifier" => Some(self.text(key)), + "string" => self.literal(key), + _ => None, + } + } + + /// The value of a string literal without escapes. + fn literal(&self, s: Node) -> Option<&str> { + match s.named_children(&mut s.walk()).collect::<Vec<_>>()[..] { + [] => Some(""), + [f] if f.kind() == "string_fragment" => Some(self.text(f)), + _ => None, + } + } + + fn collect(&self, value: Node, out: &mut Vec<(String, String)>) { + let value = unwrap(value); + match value.kind() { + "object" => { + for pair in value.named_children(&mut value.walk()).filter(|n| n.kind() == "pair") { + let name = pair.child_by_field_name("key").and_then(|k| self.name(k)); + let target = pair.child_by_field_name("value").and_then(|v| self.eval(v)); + if let (Some(name), Some(target)) = (name, target) { + out.push((name.to_owned(), target)); + } + } + } + "array" => { + for entry in value.named_children(&mut value.walk()).map(unwrap).filter(|n| n.kind() == "object") { + let field = |field: &str| { + entry.named_children(&mut entry.walk()).find_map(|p| { + let key = p.child_by_field_name("key").filter(|_| p.kind() == "pair")?; + (self.name(key) == Some(field)).then(|| p.child_by_field_name("value")).flatten() + }) + }; + let name = field("find").filter(|f| f.kind() == "string").and_then(|f| self.literal(f)); + let target = field("replacement").and_then(|r| self.eval(r)); + if let (Some(name), Some(target)) = (name, target) { + out.push((name.to_owned(), target)); + } + } + } + _ => {} + } + } + + /// The path `n` statically evaluates to. + fn eval(&self, n: Node) -> Option<String> { + let n = unwrap(n); + match n.kind() { + "string" => self.literal(n).map(str::to_owned), + "template_string" => { + let mut s = String::new(); + for part in n.named_children(&mut n.walk()) { + match part.kind() { + "string_fragment" => s.push_str(self.text(part)), + "template_substitution" => s.push_str(&self.eval(part.named_child(0)?)?), + _ => return None, + } + } + Some(s) + } + "identifier" if self.text(n) == "__dirname" => Some(self.dir_string()), + "call_expression" => { + let callee = n.child_by_field_name("function")?; + let args = n.child_by_field_name("arguments")?; + let args: Vec<Node> = args.named_children(&mut args.walk()).collect(); + match self.callee_name(callee)? { + "resolve" => { + let mut path = self.dir.to_path_buf(); + for arg in args { + path.push(self.eval(arg)?); + } + Some(normalize(&path)) + } + "join" => { + let parts: Option<Vec<String>> = args.into_iter().map(|a| self.eval(a)).collect(); + Some(normalize(Path::new(&parts?.join("/")))) + } + "fileURLToPath" if args.len() == 1 => self.file_url(args[0]), + "cwd" if args.is_empty() && self.text(callee) == "process.cwd" => Some(self.dir_string()), + _ => None, + } + } + // `new URL('./src', import.meta.url).pathname` + "member_expression" if n.child_by_field_name("property").is_some_and(|p| self.text(p) == "pathname") => { + self.file_url(n.child_by_field_name("object")?) + } + _ => None, + } + } + + /// `path.resolve` / `resolve` / `path.posix.join` / … → `resolve`. + fn callee_name(&self, callee: Node) -> Option<&str> { + match callee.kind() { + "identifier" => Some(self.text(callee)), + "member_expression" => callee.child_by_field_name("property").map(|p| self.text(p)), + _ => None, + } + } + + /// `new URL('./src', import.meta.url)` → `<dir>/src`. + fn file_url(&self, n: Node) -> Option<String> { + let n = unwrap(n); + if n.kind() != "new_expression" || n.child_by_field_name("constructor").map(|c| self.text(c)) != Some("URL") { + return None; + } + let args = n.child_by_field_name("arguments")?; + let [spec, base] = args.named_children(&mut args.walk()).collect::<Vec<_>>()[..] else { return None }; + if self.text(base) != "import.meta.url" { + return None; + } + let spec = self.eval(spec)?; + Some(normalize(&self.dir.join(spec.trim_start_matches('/')))) + } + + fn dir_string(&self) -> String { + self.dir.to_string_lossy().into_owned() + } +} + +/// Through `( … )`, `… as T`, `… satisfies T`. +fn unwrap(n: Node) -> Node { + match n.kind() { + "parenthesized_expression" | "as_expression" | "satisfies_expression" | "non_null_expression" => { + n.named_child(0).map_or(n, unwrap) + } + _ => n, + } +} + +/// Lexical `.` / `..` removal, like Node's `path.resolve`. +fn normalize(path: &Path) -> String { + let mut out = PathBuf::new(); + for c in path.components() { + match c { + Component::CurDir => {} + Component::ParentDir => { + if !out.pop() && !out.has_root() { + out.push(".."); + } + } + c => out.push(c), + } + } + out.to_string_lossy().into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// With `/` separators, so that the expectations hold on Windows too. + fn aliases(text: &str) -> Vec<(String, String)> { + bundler_aliases(text, Path::new("/p")).into_iter().map(|(a, t)| (a, t.replace('\\', "/"))).collect() + } + + fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> { + list.iter().map(|(a, b)| ((*a).to_owned(), (*b).to_owned())).collect() + } + + #[test] + fn reads_vite_object_aliases() { + let text = r#"import { defineConfig } from 'vite'; +import path from 'node:path'; +import { fileURLToPath, URL } from 'node:url'; +export default defineConfig({ + resolve: { + alias: { + '@': path.resolve(__dirname, 'src'), + comps: path.resolve(__dirname, './src/components'), + '~lib': fileURLToPath(new URL('./lib', import.meta.url)), + up: path.join(__dirname, '..', 'shared'), + root: '/src', + tpl: `${__dirname}/tpl`, + cwd: path.resolve(process.cwd(), 'app'), + vue: 'vue/dist/vue.esm-bundler.js', + dynamic: someDir, + [computed]: path.resolve(__dirname, 'x'), + }, + }, +});"#; + assert_eq!( + aliases(text), + pairs(&[ + ("@", "/p/src"), + ("comps", "/p/src/components"), + ("~lib", "/p/lib"), + ("up", "/shared"), + ("root", "/src"), + ("tpl", "/p/tpl"), + ("cwd", "/p/app"), + ("vue", "vue/dist/vue.esm-bundler.js"), + ]) + ); + } + + #[test] + fn reads_array_aliases_and_rollup_entries() { + let vite = r#"export default { + resolve: { alias: [ + { find: '@', replacement: resolve(__dirname, 'src') }, + { find: /^~(.*)$/, replacement: '$1' }, + { find: 'x', replacement: compute() }, + ] }, +};"#; + assert_eq!(aliases(vite), pairs(&[("@", "/p/src")])); + let rollup = r#"import alias from '@rollup/plugin-alias'; +export default { plugins: [alias({ entries: [{ find: 'utils', replacement: './src/utils' }] })] };"#; + assert_eq!(aliases(rollup), pairs(&[("utils", "./src/utils")])); + // `entries` means nothing without the alias plugin. + assert!(aliases("export default { entries: { a: './a' } };").is_empty()); + let esbuild = r#"require('esbuild').build({ entryPoints: ['a.js'], alias: { '@': './src' } });"#; + assert_eq!(aliases(esbuild), pairs(&[("@", "./src")])); + } + + #[test] + fn dynamic_configurations_yield_nothing() { + assert!( + aliases("export default defineConfig(({ mode }) => ({ resolve: { alias: makeAliases(mode) } }));") + .is_empty() + ); + assert!(aliases("this is not { javascript").is_empty()); + assert!(aliases("").is_empty()); + } +} diff --git a/crates/ide-language/src/syntax/mod.rs b/crates/ide-language/src/syntax/mod.rs index b79b253bf..5dff200a5 100644 --- a/crates/ide-language/src/syntax/mod.rs +++ b/crates/ide-language/src/syntax/mod.rs @@ -1,5 +1,6 @@ //! Tree-sitter driven structure: outline, folding, symbol tags, selection ranges, highlighting. +mod bundler_aliases; mod cache; mod configuration; mod external; @@ -21,6 +22,7 @@ mod vue; mod web; use crate::{FoldRange, LanguageConfig, LanguageRegistry, ScriptRegion, SymbolTag}; +pub use bundler_aliases::bundler_aliases; pub use cache::{MAX_CACHED_TREES, SyntaxCache, SyntaxCacheStats}; pub use configuration::ConfigurationKey; pub use external::{ExternalFold, ExternalSymbol, ExternalSyntax, ExternalToken, set_external_syntax}; diff --git a/crates/ide-language/src/syntax/web.rs b/crates/ide-language/src/syntax/web.rs index b7d817ecd..4d1ae2da5 100644 --- a/crates/ide-language/src/syntax/web.rs +++ b/crates/ide-language/src/syntax/web.rs @@ -4,7 +4,8 @@ //! //! Definitions (`.card`, `#main`, `--accent`) come from stylesheets and the //! `<style>` elements of HTML documents and feed the symbol index (see -//! [`super::Syntax::tags`]), so a lookup is an exact index query. +//! [`super::Syntax::tags`]), so a lookup is an exact index query. A `--name` symbol carries +//! its declared value as its container. use super::lines::{LineIndex, byte_at}; use super::{Grammar, parse}; @@ -119,17 +120,17 @@ pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text: walk(css_tree.root_node(), &mut |n| { let def = match n.kind() { "class_name" if n.parent().is_some_and(|p| p.kind() == "class_selector") => { - Some((format!(".{}", text_of(n, css_text)), CSS_CLASS)) + Some((format!(".{}", text_of(n, css_text)), CSS_CLASS, None)) } - "id_name" => Some((format!("#{}", text_of(n, css_text)), CSS_ID)), + "id_name" => Some((format!("#{}", text_of(n, css_text)), CSS_ID, None)), "property_name" if text_of(n, css_text).starts_with("--") => { - Some((text_of(n, css_text).to_owned(), CSS_VARIABLE)) + Some((text_of(n, css_text).to_owned(), CSS_VARIABLE, declared_value(n, css_text))) } _ => None, }; - if let Some((name, kind)) = def { + if let Some((name, kind, container)) = def { let range = idx.range(base + n.start_byte(), base + n.end_byte()); - out.push(SymbolTag { name, kind, container: None, range, bases: Vec::new() }); + out.push(SymbolTag { name, kind, container, range, bases: Vec::new() }); } true }); @@ -137,6 +138,18 @@ pub(crate) fn definitions(g: &Grammar, css: Option<&Grammar>, tree: &Tree, text: out } +/// The value a custom property declares (`n` is its `property_name`), whitespace collapsed and +/// cut at [`MAX_VALUE_CHARS`]: the container of its `--name` symbol, so completion and hover +/// show it without reading the file. +fn declared_value(n: Node, text: &str) -> Option<String> { + let decl = n.parent().filter(|p| p.kind() == "declaration")?; + let rest = text.get(n.end_byte()..decl.end_byte())?.trim_start().strip_prefix(':')?; + let value = rest.trim().trim_end_matches(';').split_whitespace().collect::<Vec<_>>().join(" "); + (!value.is_empty()).then(|| value.chars().take(MAX_VALUE_CHARS).collect()) +} + +const MAX_VALUE_CHARS: usize = 120; + /// The whitespace-separated token of `value` (starting at byte `base`) around byte `at`. fn token_at(value: &str, base: usize, at: usize) -> Option<(usize, &str)> { let rel = at.checked_sub(base)?; diff --git a/crates/ide-lsp/src/jdtls/formatter.rs b/crates/ide-lsp/src/jdtls/formatter.rs index 18c2b3cd0..c5ac92691 100644 --- a/crates/ide-lsp/src/jdtls/formatter.rs +++ b/crates/ide-lsp/src/jdtls/formatter.rs @@ -34,6 +34,20 @@ fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, Strin Some(settings) } +/// Java organize-imports thresholds as jdtls settings (IDEA's "Class count to use import with +/// '*'" and "Names count to use static import with '*'"). Unset ones are IDEA's defaults, 5 and 3: +/// jdtls' own are 99 (single imports), and it keeps a value it was sent until another one comes. +/// A threshold the server configuration sets explicitly is kept. +fn organize_imports_settings(style: Option<&LanguageCodeStyle>, inherited: &serde_json::Value) -> serde_json::Value { + let explicit = |key: &str| inherited.pointer(&format!("/java/sources/organizeImports/{key}")).cloned(); + let class_count = style.and_then(|s| s.class_count_to_use_import_with_star).unwrap_or(5); + let static_count = style.and_then(|s| s.names_count_to_use_static_import_with_star).unwrap_or(3); + json!({ + "starThreshold": explicit("starThreshold").unwrap_or(json!(class_count)), + "staticStarThreshold": explicit("staticStarThreshold").unwrap_or(json!(static_count)), + }) +} + fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String { for (id, value) in settings { let marker = format!(r#"<setting id="{id}" value=""#); @@ -84,6 +98,7 @@ pub fn configure_formatter( }); let mut settings = cfg.settings.take().unwrap_or_else(|| json!({})); settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides); + settings["java"]["sources"]["organizeImports"] = organize_imports_settings(style, &inherited); cfg.settings = Some(settings); let Some(style) = style else { return Ok(()) }; let indent = indent_settings(style); @@ -300,6 +315,44 @@ mod tests { } } + #[test] + fn organize_imports_thresholds_default_to_idea_and_keep_explicit_server_settings() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("project"); + std::fs::create_dir_all(&root).unwrap(); + let imports = |cfg: &LanguageServerConfig| { + crate::handler::all_settings(cfg)["java"]["sources"]["organizeImports"].clone() + }; + + let mut cfg = config("jdtls"); + let style = LanguageCodeStyle { + class_count_to_use_import_with_star: Some(7), + names_count_to_use_static_import_with_star: Some(4), + ..Default::default() + }; + configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap(); + assert_eq!(imports(&cfg), json!({"starThreshold": 7, "staticStarThreshold": 4})); + + // Unset: IDEA's 5 and 3, not jdtls' 99 (#6026). + let mut cfg = config("jdtls"); + let style = LanguageCodeStyle { names_count_to_use_static_import_with_star: Some(2), ..Default::default() }; + configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap(); + assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 2})); + let mut cfg = config("jdtls"); + configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap(); + assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 3})); + + // A threshold set in the server configuration wins. + let mut cfg = config("jdtls"); + cfg.settings = Some(json!({"java": {"sources": {"organizeImports": {"starThreshold": 99}}}})); + configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap(); + assert_eq!(imports(&cfg), json!({"starThreshold": 99, "staticStarThreshold": 2})); + + let mut cfg = config("rust-analyzer"); + configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap(); + assert!(crate::handler::all_settings(&cfg)["java"].is_null()); + } + #[test] fn default_keeps_explicit_server_configuration_and_custom_accepts_absolute_paths() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-lsp/tests/real_servers.rs b/crates/ide-lsp/tests/real_servers.rs index 879ed6ecb..ef50d6f0f 100644 --- a/crates/ide-lsp/tests/real_servers.rs +++ b/crates/ide-lsp/tests/real_servers.rs @@ -881,6 +881,94 @@ async fn vue_hybrid_mode_end_to_end() { } } +/// The path-alias tsserver plugin (`ide-sdk/src/path-aliases.js`) on vtsls: a Vite alias the +/// tsconfig doesn't define resolves, completes and isn't reported; one it defines keeps the +/// tsconfig's target. Set `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/language-server typescript@6`. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "requires @vtsls/language-server (OPENIDEA_TEST_NPM_TOOLS)"] +async fn bundler_path_aliases_resolve_below_tsconfig_paths() { + let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS")); + let dir = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(dir.path()).unwrap(); + let slash = |p: &Path| p.to_string_lossy().replace('\\', "/"); + for dir in ["src", "own", "plugin/node_modules/openidea-path-aliases"] { + std::fs::create_dir_all(root.join(dir)).unwrap(); + } + // What the settings hook writes for `alias: { '@': path.resolve(__dirname, 'src') }`. + let plugin = root.join("plugin/node_modules/openidea-path-aliases"); + std::fs::write(plugin.join("index.js"), include_str!("../../ide-sdk/src/path-aliases.js")).unwrap(); + let src = slash(&root.join("src")); + let paths = serde_json::json!({ slash(&root): { "@": [src], "@/*": [format!("{src}/*")] } }); + std::fs::write(plugin.join("paths.json"), paths.to_string()).unwrap(); + std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap(); + let tsconfig = |paths: &str| { + format!( + "{{\"compilerOptions\":{{\"strict\":true,\"module\":\"ESNext\",\"moduleResolution\":\"Bundler\"{paths}}},\"include\":[\"src\"]}}" + ) + }; + std::fs::write(root.join("tsconfig.json"), tsconfig("")).unwrap(); + std::fs::write(root.join("src/a.ts"), "export const answer = 42;\n").unwrap(); + std::fs::write(root.join("own/a.ts"), "export const answer = 1;\n").unwrap(); + let main = root.join("src/main.ts"); + let text = "import { answer } from '@/a';\nimport '@/';\nconst n: number = answer + '';\n"; + std::fs::write(&main, text).unwrap(); + let init = serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [{ + "name": "openidea-path-aliases", + "location": root.join("plugin").to_string_lossy(), + "enableForWorkspaceTypeScriptVersions": true, + }] } } }); + let ts = || lang("typescript", "ts", npm_server(&tools, "vtsls", "vtsls", Some(init.clone()))); + + let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![ts()])); + let doc = DocId::next(); + mgr.did_open(doc, &main, &LanguageId::new("typescript"), 1, text); + let defs = retry("definition through the alias", Duration::from_secs(90), || { + let mgr = mgr.clone(); + let a = root.join("src/a.ts"); + // The syntax server answers with the import itself until the project is loaded. + async move { + mgr.goto(doc, Pos::new(0, 10), GotoKind::Definition).await.ok().filter(|d| d.iter().any(|d| d.path == a)) + } + }) + .await; + assert_eq!(defs.len(), 1); + retry("path completion after @/", Duration::from_secs(30), || { + let mgr = mgr.clone(); + async move { + let list = mgr.completion(doc, Pos::new(1, 10), Some("/".into()), Default::default()).await.ok()?; + list.items.iter().any(|i| i.label == "a" || i.label == "a.ts").then_some(()) + } + }) + .await; + // The deliberate type error is reported; the aliased import is not. + let diagnostics = retry("diagnostics", Duration::from_secs(30), || { + let found = events.lock().iter().rev().find_map(|e| match e { + IdeEvent::Diagnostics { path, items, .. } if path == &main && !items.is_empty() => Some(items.clone()), + _ => None, + }); + async move { found } + }) + .await; + assert!(diagnostics.iter().all(|d| !d.message.contains("Cannot find module")), "{diagnostics:?}"); + tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap(); + + // The tsconfig's own `@/*` wins. + std::fs::write(root.join("tsconfig.json"), tsconfig(",\"paths\":{\"@/*\":[\"./own/*\"]}")).unwrap(); + let (mgr, _events) = manager(&root, LanguageRegistry::from_configs(vec![ts()])); + let doc = DocId::next(); + mgr.did_open(doc, &main, &LanguageId::new("typescript"), 1, text); + let defs = retry("definition through the tsconfig paths", Duration::from_secs(90), || { + let mgr = mgr.clone(); + let own = root.join("own/a.ts"); + async move { + mgr.goto(doc, Pos::new(0, 10), GotoKind::Definition).await.ok().filter(|d| d.iter().any(|d| d.path == own)) + } + }) + .await; + assert_eq!(defs.len(), 1); + tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap(); +} + const NG_APP_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.html',\n})\nexport class App {\n title = 'demo';\n}\n"; const NG_APP_HTML: &str = "<h1>{{ title }}</h1>\n<p>{{ missing }}</p>\n"; const NG_INLINE_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-inline',\n template: `<b>{{ count }}</b>`,\n})\nexport class Inline {\n count = 1;\n}\n"; diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index 63c753061..4add874e2 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -208,6 +208,9 @@ pub trait HostApi: Send + Sync { ) -> Result<(), HostError>; /// Replace all `(path, icon)` entries of a tree decoration set at once (API 1.8). fn file_icon_decorations(&self, set: &str, items: Vec<(PathBuf, String)>) -> Result<(), HostError>; + /// Fork a recorded native agent session into a new task in the invoking + /// window's project, returning the new task id (API 1.18). + fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result<String, HostError>; /// Trusted repository history. fn vcs_log( &self, diff --git a/crates/ide-plugin/src/wit_host.rs b/crates/ide-plugin/src/wit_host.rs index a9c24f028..f89bc32e3 100644 --- a/crates/ide-plugin/src/wit_host.rs +++ b/crates/ide-plugin/src/wit_host.rs @@ -3321,6 +3321,19 @@ impl bindings::openidea::plugin::mcp::Host for StoreData { } } +impl bindings::openidea::plugin::agents::Host for StoreData { + fn fork_session(&mut self, agent: String, session_id: String, cwd: String) -> Fallible<String> { + if let Err(e) = self.require(Capability::Agents) { + return Ok(Err(e)); + } + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + let client = self.invocation.client.clone().unwrap_or_default(); + Ok(self.host.fork_agent_session(&client, &agent, &session_id, Path::new(&cwd)).map_err(to_wit)) + } +} + pub(crate) mod mcp_bindings { wasmtime::component::bindgen!({ world: "mcp-tools", path: "../../wit", with: { diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm index c0094a265..8e1f266d0 100644 Binary files a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources index 597183bb6..af4dba612 100644 --- a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources @@ -1 +1 @@ -9857fa3a9b1d22d3b2c91a58fbf2c948267d87a6586ade7e0362fd6b6f4dd2ab +ba019d950ae83c45845a5cfcb2e890eca25c6f102b78f8cd3090f604c56aaf17 diff --git a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm index bac3d68b4..3d94a0cd2 100644 Binary files a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources index 8994e660a..54b54632d 100644 --- a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources @@ -1 +1 @@ -ba19f794de91eeac3a2509a9495b443ab7b0c90404156d8e4049e5eae777ab66 +926ca24c9a08166e34fb8a6b2c6dd06a92cf3370dc01ff3054b533356314c84b diff --git a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm index 919674f6f..cf7d311e2 100644 Binary files a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources index 9187f97fd..8ab2d80a3 100644 --- a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources @@ -1 +1 @@ -0692fd551f6cc80338f8f655ad2384f37aef5c9498a0396532afa0e54a25f477 +dd7e4dcc429bf44b839cabe682f36cb3951a3dcf535f500f90cb60ff749e31e6 diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm index 121a726e9..26c0c9df1 100644 Binary files a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources index 8885e8bd5..d23346bcf 100644 --- a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources @@ -1 +1 @@ -6a25f9c9f9486468f1885cf81bccd90240014009ba3c507e478ce9b32468d594 +1acae0035935e9f6e7b52826e9731aeb15dafb5cfcc561a2b98dae10676f53f8 diff --git a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm index 799812ea3..7b6a98f84 100644 Binary files a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources index 02d1acbaa..3be144049 100644 --- a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources @@ -1 +1 @@ -84bb08e094ec85d49abe713df02ac03a47dc7dbb6d8dfc754491083e0d0c46f5 +d3b940a7899ed3a303b51c529d2771ec9ac20a22d996dbc9760dd118dc10dbc1 diff --git a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm index 5d1654a88..fbc089cea 100644 Binary files a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources index f991d17fa..1ad5317fa 100644 --- a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -958ef1f5cd54a9b4c6fb99ee8e02793ca70a81698620da9ddf2b1b3f25b535c8 +955e804453e7e8ea37a49ab7b65289d31fef1216eda4f1834e912375196adb17 diff --git a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm index 4cc96de87..a23d3e2e1 100644 Binary files a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources index da710a6b4..f9b0d140f 100644 --- a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources @@ -1 +1 @@ -a846c18a1282242e25f0b61624c319fe10bdf322c224276a4a8edffd470ef940 +42caf6ccd73e3d622894416b0fd5007b8a1d773d6bf7e81c0ff4d0e97f888e43 diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm index 8bfa94d53..88508ec30 100644 Binary files a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources index 5c023cab0..d2c4a2c0b 100644 --- a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources @@ -1 +1 @@ -35f393de3ed681d206885612ae085b69dfef81ff8baa701a737c1914ac1412fb +5795a3b4a25a7563c3a43ed0d414d3e520badd09066d5e5d2bcbc23ba4b8e1c8 diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm index 9d3187022..4f9201d4a 100644 Binary files a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources index f848f31ba..6cbdc5344 100644 --- a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources @@ -1 +1 @@ -e75dad45fb2a6bb8823b8edfb41b29403ec77f8e6e533bad42d0ae0cb1d68286 +1e53f7713c294be551fa4641cfda5b2497d7a57a35116ca4dd29783e63a7a9f6 diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm index e974866ef..b2ac84881 100644 Binary files a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources index a67d8c6c0..7dd4d0713 100644 --- a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources @@ -1 +1 @@ -2cb47ff4fb3d401e95b742d78e026b872200dc503bf933ff9ce31d0557d69426 +650a8e88e4e6999e77159fb25516b5990f6ae7805167e89a8e3193d53fd57822 diff --git a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm index b0fb32d92..a2d5aed89 100644 Binary files a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources index 58069fc19..e38de5b99 100644 --- a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources @@ -1 +1 @@ -e121d0fd2cc841ebb911904ada80921d01af392ccaa295b2fe0b2e7f4f51c58c +6ee319bf6071871f7d9d0674b83be11d7b6f8ed2693572303f15d7e450a86b4b diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm index 879589a06..5ae8c34e9 100644 Binary files a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources index 562553107..aaf01f8d9 100644 --- a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources @@ -1 +1 @@ -c0ebc0e6b8601044ab88eba4929c8c73ab1278d3401b6594df35407f1a93cc24 +61f41c0d8ce0bf2243c8cb3b2d2a84037a07958fb18d6ebb016abb08b469a80c diff --git a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm index edced1df7..f4b540172 100644 Binary files a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources index 0b73cace1..fff8ec63b 100644 --- a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources @@ -1 +1 @@ -cea7369e69efee782e6a7b62736832e90890cd7af089884f3ed6e144542e0589 +e5877e2978f8d36c1d8b684e84bfd21f9047b0153bed952e89299a69968029c0 diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm index c42eb35f9..2e4095733 100644 Binary files a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources index 6e0c021d8..4b07f823c 100644 --- a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources @@ -1 +1 @@ -f348c5ee1ce6d911ae53ea4aff185bdb6079729aee83561d3adb9d13eeb376fb +7fe7457184144c93b761b8fa26e45f1b8a55cc6753d91a7353bd67d7a5bd09a9 diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm index 0ecd31685..d8139ad4c 100644 Binary files a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources index 5b7654183..3008d58a9 100644 --- a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources @@ -1 +1 @@ -5cd09b0da42f015faae666fbe210203b7ced9cf19d6ee542dadd236b7926b77b +19480e0dd6ae1e36aadabbda9ea49a34ee0aa37d4c7182c297b6d84c9b13991f diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm index 7a26f20b9..5ed2c0dd0 100644 Binary files a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources index 79071ee77..b1d89bff3 100644 --- a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources @@ -1 +1 @@ -ff2d1eac3fe4a2856e6310f36ed29d9a2ccffc8eeb41ded729dd01eadc244857 +7bd6651b0fd45032847868c341bc815b115ac678dcaaf26e752ae72ac1b0549f diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm index f51f8612b..1745c75f9 100644 Binary files a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources index a5970d9b7..68f2538f3 100644 --- a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources @@ -1 +1 @@ -e37a64052eef340a8482d8129badc50f29e8949316a33e6172a64e1a00f0718c +9c99195f1c7efdb27f3715158559218db2f7db03325cc04af455b8f60653da24 diff --git a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm index f06f7815c..dab2a7d4e 100644 Binary files a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources index bd2903b85..18248e5f8 100644 --- a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources @@ -1 +1 @@ -5f4dfb76c879bbbeb38f7c1b45c88818517743d742129a147e185bc7d2db7abc +875df930f71fa22112dbafddb6de460b9828d0aa10812ee1eeedc4052bc88061 diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm index 513258d73..94124fad3 100644 Binary files a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources index 39ae74f5f..ce478afea 100644 --- a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources @@ -1 +1 @@ -efe6d6c88d0bab2484f90cef6affe256c480297731ce585a5e3441e2648d9392 +d10b1225ab4228d3906e88e79ef346302a4db89aa4dd5a82da694cec408e5496 diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm index d9df8ca70..b1707f93c 100644 Binary files a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources index f16818864..1d578a0de 100644 --- a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources @@ -1 +1 @@ -7b606308ee272adb1f659e7fd21069409b3bdbf12cd54b93232205bc8213f52a +12cb92d4b45279bbdc345dbdd4c8d4827abc5054d0324d35b85b648840d9c556 diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm index 883af0da3..d100882bb 100644 Binary files a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources index f8a275044..88ab3deeb 100644 --- a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources @@ -1 +1 @@ -6be054362a3c1f3545fdfba5c9b66d9eadcbeea3b160952068494c02bce3a4a1 +e8c1116c94c82ea4ed0fd7e33070bc878e88dcfe8f08632cd700bb3418b712cc diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm index 1c3441e8c..090ec5f17 100644 Binary files a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources index 88e6589ae..adc73f23f 100644 --- a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources @@ -1 +1 @@ -3cd84b9876d2e5a5294877ac14d69b18319be3208c192f67b6c3848039c48a79 +9bd13ae90217e4355014512bce62de8b471a466484100abb7cc8b9197c008c93 diff --git a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm index 4cece283e..eb269acd6 100644 Binary files a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources index e015b4112..0dea9a9cc 100644 --- a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources @@ -1 +1 @@ -e2c282bd0add6de51b6b275d16b950213fcdd24d1d882895b7d3099b0a7d569a +f3d78da579d47985908f8e7ce63793ff58b2d255992df97a0acdec1c56a039ee diff --git a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm index e7d54c167..732679689 100644 Binary files a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources index cec204066..36397622f 100644 --- a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources @@ -1 +1 @@ -84739ec73aa6b7b27d7a5062b78645d7342729806bc728f35a7b97c945c1a4fd +123a768fd0e531c6f8ce63648f10ddef2d309d01e5e8ac1386c16e45a9c0329b diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm index 26517e1ac..83a6c6440 100644 Binary files a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources index 1fee0dfde..750b026c5 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources @@ -1 +1 @@ -ad43fa07182ff3d90154fdd788599d60db5fe0ab736dad03c6ae2cc2a1055eff +6a57f349ba434cdc10ddbdd2fedb1578a18dcada080f6d8b9096a95174a2ab79 diff --git a/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml b/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml index 96de5c9ac..b07982333 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml +++ b/crates/ide-plugin/tests/fixtures/misbehave/plugin.toml @@ -54,6 +54,10 @@ title = "projwrite" id = "insert" title = "insert" +[[contributes.commands]] +id = "fork-session" +title = "fork-session" + [[contributes.commands]] id = "cancel" title = "cancel" diff --git a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs index 7d7e351ce..94e108e3c 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs +++ b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs @@ -209,6 +209,16 @@ impl commands::Guest for Misbehave { let editor = ctx.editor().ok_or_else(|| failed("no editor"))?; editor.apply_edits(0, &[]).map(|_| None) } + // `agents.fork-session`: arg is "agent session-id cwd". Without the + // `agents` grant this is `denied`, not a trap. + "fork-session" => { + let arg = arg.unwrap_or_default(); + let mut parts = arg.splitn(3, ' '); + let agent = parts.next().unwrap_or_default(); + let session_id = parts.next().unwrap_or_default(); + let cwd = parts.next().unwrap_or_default(); + openidea::plugin::agents::fork_session(agent, session_id, cwd).map(Some) + } // The user gave up: not the plugin failing. "cancel" => Err(types::Error::Cancelled), // Event kinds are names: one this IDE doesn't know is refused. diff --git a/crates/ide-plugin/tests/fixtures/net-setting/Cargo.lock b/crates/ide-plugin/tests/fixtures/net-setting/Cargo.lock new file mode 100644 index 000000000..7084cb755 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/net-setting/Cargo.lock @@ -0,0 +1,337 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-netsetting" +version = "0.1.0" +dependencies = [ + "openidea-plugin", + "serde_json", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/ide-plugin/tests/fixtures/net-setting/Cargo.toml b/crates/ide-plugin/tests/fixtures/net-setting/Cargo.toml new file mode 100644 index 000000000..c4cbd8fec --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/net-setting/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-plugin-netsetting" +version = "0.1.0" +edition = "2024" +publish = false + +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" } +serde_json = "1" + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm new file mode 100644 index 000000000..f759262f9 Binary files /dev/null and b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm.sources new file mode 100644 index 000000000..23ccfd9df --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm.sources @@ -0,0 +1 @@ +04c8f881e25aae1b7298f554f3c4ab38251eec48e8d88656d73cad019eb1644c diff --git a/crates/ide-plugin/tests/fixtures/net-setting/plugin.toml b/crates/ide-plugin/tests/fixtures/net-setting/plugin.toml new file mode 100644 index 000000000..a3ad4594a --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/net-setting/plugin.toml @@ -0,0 +1,17 @@ +id = "netsetting" +name = "Setting-derived network grants" +version = "0.1.0" +engines.openidea = "^1.18" +wasm = "dist/plugin.wasm" +activation = ["on-command:*"] + +[capabilities] +required = ["storage"] +optional = ["net:setting:server", "net.http:setting:server"] + +[contributes.settings] +schema = "settings.json" + +[[contributes.commands]] +id = "fetch" +title = "fetch" diff --git a/crates/ide-plugin/tests/fixtures/net-setting/settings.json b/crates/ide-plugin/tests/fixtures/net-setting/settings.json new file mode 100644 index 000000000..cb8fb199f --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/net-setting/settings.json @@ -0,0 +1 @@ +{"properties":{"server":{"type":"string","title":"Server","default":""}}} diff --git a/crates/ide-plugin/tests/fixtures/net-setting/src/lib.rs b/crates/ide-plugin/tests/fixtures/net-setting/src/lib.rs new file mode 100644 index 000000000..2e0ff7114 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/net-setting/src/lib.rs @@ -0,0 +1,178 @@ +use openidea_plugin::{Error, Event, Invocation, Plugin, StatusItem, StatusMenuEntry, host, register_plugin}; +#[derive(Default)] +struct Api14; +impl Plugin for Api14 { + fn run_command(&mut self, id: &str, ctx: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> { + let arg = arg.unwrap_or_default(); + match id { + "open-editors" => Ok(Some(format!("{:?}", host::open_editors()?))), + "open-editor" => { + host::open_editor(arg, Some(openidea_plugin::Range::default()))?; + Ok(None) + } + "set-selections" => { + ctx.editor().unwrap().set_selections(&[openidea_plugin::Range::default()])?; + Ok(None) + } + "reveal" => { + ctx.editor().unwrap().reveal(openidea_plugin::Range::default())?; + Ok(None) + } + "search-text" => { + let result = ctx + .project() + .unwrap() + .search_text(&openidea_plugin::TextQuery { pattern: arg.into(), ..Default::default() }, 10)?; + Ok(Some(format!("{result:?}"))) + } + "read-bytes" => Ok(Some(format!("{:?}", ctx.project().unwrap().read_bytes(arg)?))), + "problems" => Ok(Some(format!("{:?}", host::problems(if arg.is_empty() { None } else { Some(arg) })?))), + "decorations" => { + host::set_decorations( + arg, + "test", + &[openidea_plugin::Decoration { + range: openidea_plugin::Range::default(), + style: "highlight".into(), + hover: Some("hover".into()), + after: Some("after".into()), + }], + )?; + Ok(None) + } + "clear-decorations" => { + host::clear_decorations("test")?; + Ok(None) + } + "file-decoration" => { + host::set_file_decoration( + arg, + "test", + &openidea_plugin::FileDecoration { badge: Some("OK".into()), style: "added".into(), tooltip: None }, + )?; + Ok(None) + } + "clear-file-decorations" => { + host::clear_file_decorations("test")?; + Ok(None) + } + "vcs-log" => Ok(Some(format!( + "{:?}", + ctx.project().unwrap().vcs_log(if arg.is_empty() { None } else { Some(arg) }, 10)? + ))), + "vcs-blame" => Ok(Some(format!("{:?}", ctx.project().unwrap().vcs_blame(arg)?))), + "vcs-diff" => ctx.project().unwrap().vcs_diff(if arg.is_empty() { None } else { Some(arg) }, None), + "ipc" => { + let stream = host::ipc_connect(arg)?; + stream.write(b"echo")?; + let bytes = stream.read(4, 2000)?; + stream.close()?; + Ok(Some(String::from_utf8_lossy(&bytes).into())) + } + "fetch" => { + let response = host::fetch(&openidea_plugin::HttpRequest::get(arg))?; + Ok(Some(String::from_utf8_lossy(&response.body).into())) + } + "global-status" | "window-status" => { + let item = StatusItem { text: arg.into(), tooltip: None, command: Some("events".into()) }; + if id == "global-status" { + host::set_status_item("state", &item); + } else { + host::set_window_status_item("state", &item)?; + } + Ok(None) + } + "menu-status" | "bad-menu-status" => { + let item = StatusItem { text: arg.into(), tooltip: None, command: None }; + let command = if id == "menu-status" { "events" } else { "undeclared" }; + let menu = [ + StatusMenuEntry::Header("App".into()), + StatusMenuEntry::action("Open", command).with_description("https://app.test").with_argument("web"), + StatusMenuEntry::Separator, + ]; + host::set_status_item_menu("menu", &item, &menu)?; + Ok(None) + } + "remove-window-status" => { + host::remove_window_status_item("state")?; + Ok(None) + } + "execute" => host::execute_command(arg, Some("argument")), + "oauth" => { + let redirect = host::begin_loopback("oauth/callback")?; + host::output_append("oauth", &redirect.redirect_uri())?; + redirect.wait(2000) + } + "secret" => { + host::secret_set("token", arg)?; + Ok(None) + } + "delete-secret" => { + host::secret_delete("token")?; + Ok(None) + } + "undeclared-secret" => { + host::secret_set("undeclared", arg)?; + Ok(None) + } + "output" => { + host::output_append("test", arg)?; + host::output_reveal("test")?; + Ok(None) + } + "process-run" => Ok(Some(host::run_process("api14-tool", &[], None)?.stdout)), + "process-run-command" => Ok(Some(host::run_command(&host::Command::new("api14-tool"), None, None)?.stdout)), + "process-start" => { + let child = host::start(&host::Command::new("api14-tool"), None)?; + Ok(Some(child.wait(2000)?.stdout)) + } + "terminal" => { + host::open_terminal("API test", "api14-tool", &[])?; + Ok(None) + } + "log" => { + host::open_log_tab( + "api-test", + "API test", + &openidea_plugin::details::ProcessLog { + program: "api14-tool".into(), + args: Vec::new(), + toggles: Vec::new(), + }, + )?; + Ok(None) + } + "events" => host::storage::get("events"), + _ => Err(Error::NotFound(id.into())), + } + } + fn handle_events(&mut self, events: &[Event], ctx: &Invocation) { + let mut received: Vec<serde_json::Value> = + host::storage::get("events").unwrap().map(|s| serde_json::from_str(&s).unwrap()).unwrap_or_default(); + for event in events { + if let Event::Other { kind, data } = event { + let editor = ctx.editor().map(|e| { + ( + e.path(), + e.selections() + .unwrap() + .into_iter() + .map(|r| [r.start.line, r.start.character, r.end.line, r.end.character]) + .collect::<Vec<_>>(), + ) + }); + received.push(serde_json::json!({ "kind": kind, "data": data, "editor": editor })); + } + } + host::storage::set("events", &serde_json::to_string(&received).unwrap()).unwrap(); + } +} +impl openidea_plugin::TestResults for Api14 { + fn parse(&mut self, _config: &str, _chunk: &str) -> Vec<openidea_plugin::PluginTestEvent> { + vec![] + } + fn select_tests(&mut self, config: &str, tests: &[Vec<String>]) -> Option<Vec<String>> { + (config == "tests").then(|| tests.iter().map(|p| p.join("::")).collect()) + } +} +register_plugin!(Api14, test_results); diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm index ffe2685eb..fb54043f6 100644 Binary files a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources index d99ed7cce..00e236c8f 100644 --- a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources @@ -1 +1 @@ -639a93e98dd0fe3114ef7be3597ab559b69e4c54fdb5e96951cb19b894a020b9 +a689eca7666880c1096bf9bcaaba3d355a76666a7abe7524e5bb6f641a7d67fd diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm index 9c6133442..cdbbc6f1f 100644 Binary files a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources index 56a9d34ac..fd11770a9 100644 --- a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources @@ -1 +1 @@ -20aa26598608efac79c941531d4b5cd26b4e71a9b09e261560bc086410eb5c83 +eff2b16fcdf47f7f0a204bb229438b585917c3be62fd9ea9a02898b415530d6e diff --git a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm index aa189f66d..f1bda9f85 100644 Binary files a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources index 9dceeb79e..d15ae4a74 100644 --- a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources @@ -1 +1 @@ -ca76bdb76b364ec445e06b893fdfb56cad1f05e4a1ff10affaa116b34c3160ec +97177d6d25b9a205c1cf1cf9bd8e50ad88a119e9876dddd786d72575d2cbae5c diff --git a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm index 87b51e0ed..838cb1332 100644 Binary files a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources index cdbdb7302..8bcdda539 100644 --- a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources @@ -1 +1 @@ -7307879ddca36b6a944bb3b5d3011916a3074e50d7f187aa258394c8c5123d91 +14559c777048bef5ec800dc6ea4e3f263268a6bd16000023c27f1f82a0d89ca6 diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm index d6f3575e0..8236dd0f6 100644 Binary files a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources index ca7d04bff..39b9b9c29 100644 --- a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources @@ -1 +1 @@ -82a408bddf01af0e7a34a585a60d165e12ad5982e7843d6091a2f4e6fac15c55 +24060000f8040dbd6ba007b8da84e2800f93f3090aaafc0fb864ecc03266df82 diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm index a568005ba..8ceef2294 100644 Binary files a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources index 569b2112d..6aa0060e0 100644 --- a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources @@ -1 +1 @@ -04b1807c79763f6e2f74503d545007dbdb478f7aae010dd8330e768c1dc3a9ad +ce8e3742bdfa1e9f232b01af7569a72a2349c93e16866436d6a4d051a5aa9fdf diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm index 69799c2d1..4fdfa4c07 100644 Binary files a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources index f62290414..66ac11ba5 100644 --- a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources @@ -1 +1 @@ -53e4f47e38a8622e2ef0d03e4ed2369fb906e941d9e9734ed9d57fe5cbc5ead3 +687b349d2b55cbd0220fdd33cddf98d8bab735f5e6716d8b9a27029ab4973953 diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm index 03edc05f7..09fa423cb 100644 Binary files a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources index 86fe4da29..82acff949 100644 --- a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources @@ -1 +1 @@ -d6bd0b261c6db62d04197c28b251a03acc5f32cb21c5133ac3aaeb3e37fe5eab +00ae790cecb1fd107e407d0c6a1e149713b2969af220de0267dbe9b55fc628ef diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm index e2ae99203..c0d8e54a7 100644 Binary files a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources index dc2da5e5a..ef398eb05 100644 --- a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources @@ -1 +1 @@ -a7728793d40c78dc5ebfd74c013425358c888da87a2cce15a5e8c306ab5b6b30 +d1d5e658f86af183a9ce21d3ad6230ddd00a05b7c3bd447b9fabfa171aa92920 diff --git a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm index 8ca6fe86c..237778b89 100644 Binary files a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources index 099402687..f20a0cac4 100644 --- a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources @@ -1 +1 @@ -1fca4a563944897ea1e55c49533c157f005e5efbc1aeabac65037cad1f05c2ba +213aa998dfcc309f8abd24f12a44db4ac12b676bb7d3567309378ef650e05602 diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm index b74dd56d6..358c31ccf 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources index 20919566a..1c84a53bc 100644 --- a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources @@ -1 +1 @@ -2be637ed5d3c72adf1a8b92aaea86602ab81ffaeeff99a719f6f67c244b82137 +ad698b8393a15b8af0065d97a73ade1cc98626ffe5ffd20cb1de6c06aef4611a diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm index ef266e621..b03f6d7be 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources index fe4453dfe..5578799a2 100644 --- a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources @@ -1 +1 @@ -3a1aad965fa557b13e2aab2b714c68845d1890a6e98ab9155ccfc952ab2c64d5 +046020f3a6500bedba728a132353024201e7c59cbe5fa819dfe8b8aba3a87bab diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm index 16745710a..50465ea59 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources index a6ef4040a..101e10bea 100644 --- a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources @@ -1 +1 @@ -0ad7071e1674170ae360d873fda38656dbba6740514c7bfca642e7881cbd9c18 +8c0718c8d732965a6a87a68695a22c37c6ebdd26877019d47c8e2de3dfc7b10d diff --git a/crates/ide-profiler/src/formats.rs b/crates/ide-profiler/src/formats.rs index 60423e936..87c924c97 100644 --- a/crates/ide-profiler/src/formats.rs +++ b/crates/ide-profiler/src/formats.rs @@ -123,7 +123,7 @@ fn source_location(entry: &Value) -> Option<(PathBuf, u32)> { /// Adds a V8 CPU profile (`node --cpu-prof`), weighted by sampled time in milliseconds. pub(crate) fn add_cpuprofile(b: &mut TreeBuilder, json: &str) -> Result<(), String> { let v: Value = serde_json::from_str(json).map_err(|e| e.to_string())?; - let nodes = v.get("nodes").and_then(Value::as_array).ok_or("not a CPU profile: no nodes")?; + let nodes = v.get("nodes").and_then(Value::as_array).ok_or("no nodes")?; let mut by_id: HashMap<i64, &Value> = HashMap::new(); let mut parent: HashMap<i64, i64> = HashMap::new(); for n in nodes { diff --git a/crates/ide-profiler/src/lib.rs b/crates/ide-profiler/src/lib.rs index 60f6b1429..4a6513255 100644 --- a/crates/ide-profiler/src/lib.rs +++ b/crates/ide-profiler/src/lib.rs @@ -109,6 +109,8 @@ pub enum ProfileSpec { /// ran no code of `root` (the package manager of an npm script) are left /// out when another one did. CpuProfiles { dir: IpcPath, root: IpcPath }, + /// One `.cpuprofile` the user opened (saved by `node --cpu-prof`, Chrome DevTools, CI). + CpuProfileFile { path: IpcPath }, /// Collapsed-stack files with extension `ext` in `dir`; relative frame files resolve /// against `base`. `jvm_root`: map JVM class frames to sources below it. For the /// allocation modes the last frame of a JVM stack is the allocated type. @@ -172,6 +174,26 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> { } Ok(b.finish("node --cpu-prof", "ms", ProfileMode::Cpu)) } + ProfileSpec::CpuProfileFile { path } => { + let path: &Path = path.as_ref(); + let name = + path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned()); + let text = + std::fs::read_to_string(path).map_err(|e| IdeError::invalid(format!("Cannot read {name}: {e}")))?; + formats::add_cpuprofile(&mut b, &text) + .map_err(|e| IdeError::invalid(format!("{name} is not a V8 CPU profile ({e}).")))?; + if b.is_empty() { + return Err(IdeError::invalid(format!("{name} has no samples."))); + } + let mut profile = b.finish("V8 CPU profile", "ms", ProfileMode::Cpu); + // A profile recorded on another machine (CI) names files that aren't here. + for f in &mut profile.frames { + if f.file.as_ref().is_some_and(|p| !p.is_file()) { + (f.file, f.line) = (None, None); + } + } + Ok(profile) + } ProfileSpec::Folded { profiler, dir, ext, base, jvm_root, mode } => { for f in files_with_ext(dir, ext) { formats::add_folded(&mut b, &std::fs::read_to_string(&f)?, base, *mode != ProfileMode::Cpu); @@ -251,6 +273,48 @@ mod tests { assert!(p.frames.iter().any(|f| f.name == "byte[]" && f.kind == ProfileFrameKind::AllocatedType)); } + #[test] + fn an_opened_cpuprofile_keeps_only_local_sources() { + let dir = tempfile::tempdir().unwrap(); + let src = dir.path().join("index.js"); + std::fs::write(&src, "").unwrap(); + let url = |p: &Path| format!("file://{}", p.display()).replace('\\', "/"); + let json = format!( + r#"{{"nodes":[ + {{"id":1,"callFrame":{{"functionName":"(root)","url":"","lineNumber":-1}},"children":[2,3]}}, + {{"id":2,"callFrame":{{"functionName":"here","url":"{}","lineNumber":3}}}}, + {{"id":3,"callFrame":{{"functionName":"onCi","url":"file:///home/runner/work/app/x.js","lineNumber":1}}}}], + "samples":[2,3,2],"timeDeltas":[0,1000,1000]}}"#, + url(&src) + ); + let path = dir.path().join("CPU.cpuprofile"); + std::fs::write(&path, json).unwrap(); + let p = collect(&ProfileSpec::CpuProfileFile { path: path.into() }).unwrap(); + assert_eq!((p.unit.as_str(), p.mode), ("ms", ProfileMode::Cpu)); + let frame = |name: &str| p.frames.iter().find(|f| f.name == name).unwrap(); + assert_eq!(frame("here").file.as_deref(), Some(src.as_path())); + assert_eq!(frame("here").line, Some(3)); + assert_eq!((frame("onCi").file.as_ref(), frame("onCi").line), (None, None)); + } + + #[test] + fn an_opened_file_that_is_no_cpuprofile_is_an_error() { + let dir = tempfile::tempdir().unwrap(); + for (file, text, says) in [ + ("notes.cpuprofile", "hello", "is not a V8 CPU profile"), + ("other.cpuprofile", r#"{"a":1}"#, "is not a V8 CPU profile (no nodes)"), + ("empty.cpuprofile", r#"{"nodes":[],"samples":[],"timeDeltas":[]}"#, "has no samples"), + ] { + let path = dir.path().join(file); + std::fs::write(&path, text).unwrap(); + let err = collect(&ProfileSpec::CpuProfileFile { path: path.into() }).unwrap_err(); + assert_eq!(err.message.split_once(' ').unwrap().0, file); + assert!(err.message.contains(says), "{}", err.message); + } + let missing = collect(&ProfileSpec::CpuProfileFile { path: dir.path().join("gone.cpuprofile").into() }); + assert!(missing.unwrap_err().message.starts_with("Cannot read gone.cpuprofile")); + } + #[test] fn cpu_profile_stays_in_samples() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-run/Cargo.toml b/crates/ide-run/Cargo.toml index e2328b041..9b442c6ab 100644 --- a/crates/ide-run/Cargo.toml +++ b/crates/ide-run/Cargo.toml @@ -8,6 +8,7 @@ license.workspace = true [dependencies] ide-core.workspace = true ide-language.workspace = true +ide-workspace.workspace = true dunce.workspace = true encoding_rs.workspace = true serde.workspace = true diff --git a/crates/ide-run/src/config.rs b/crates/ide-run/src/config.rs index 8a306f0b2..9c7bca004 100644 --- a/crates/ide-run/src/config.rs +++ b/crates/ide-run/src/config.rs @@ -120,6 +120,8 @@ struct FileConfig { target: Option<String>, #[serde(alias = "testRunner")] test_runner: Option<String>, + #[serde(default)] + watch: bool, } pub(crate) fn slug(s: &str) -> String { @@ -186,6 +188,8 @@ fn convert(configs: Vec<FileConfig>, local: bool) -> Vec<RunConfig> { stop_command: non_empty(c.stop_command), target: non_empty(c.target), test_runner: non_empty(c.test_runner), + watch: c.watch, + executor: None, }, }); } @@ -287,6 +291,7 @@ fn to_table(c: &RunConfig) -> Table { ("show-on-stderr", x.show_on_stderr), ("focus-tool-window", x.focus_tool_window), ("emulate-terminal", x.emulate_terminal), + ("watch", x.watch), ] { if on { t.insert(key, value(true)); diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs index 89d613f1c..050f52c3a 100644 --- a/crates/ide-run/src/detect.rs +++ b/crates/ide-run/src/detect.rs @@ -84,11 +84,16 @@ pub(crate) fn detect_with_profiles( } } detect_projects(root, &["build.zig"], zig::detect, &mut out); - dotnet::detect(root, &mut out); + // A UE project's `.sln` lists the engine's own tool projects; expanding it would bury the + // run menu under dozens of `.NET Project` entries that cannot run from here. + if !ide_workspace::unreal::is_project(root) { + dotnet::detect(root, &mut out); + } detect_projects(root, &["Makefile", "makefile", "GNUmakefile"], detect_make, &mut out); detect_projects(root, &["justfile", "Justfile", ".justfile"], detect_just, &mut out); detect_godot(root, &mut out); detect_projects(root, &["pubspec.yaml"], detect_flutter, &mut out); + detect_unreal(root, &mut out); crate::external::detect(root, &mut out); let mut seen = HashSet::new(); @@ -235,16 +240,23 @@ pub(crate) fn is_test_script(name: &str) -> bool { } /// The test runner a `package.json` script starts, when its output and test selection differ -/// from Jest / Vitest's: `playwright test`, `mocha`, or `node --test` (`tsx --test`) with Node's own +/// from Jest / Vitest's: `playwright test`, `cypress run`, `mocha`, or `node --test` (`tsx --test`) with Node's own /// reporters (the IDE adds its reporter next to them, which a reporter chosen here would clash with). fn script_test_runner(script: &str) -> Option<&'static str> { let tokens: Vec<&str> = script.split(|c: char| c.is_whitespace() || matches!(c, '&' | '|' | ';')).collect(); if tokens.windows(2).any(|w| w[0] == "playwright" && w[1] == "test") { return Some("playwright"); } + if tokens.windows(2).any(|w| w[0] == "cypress" && w[1] == "run") { + return Some("cypress"); + } if tokens.iter().any(|t| matches!(t.rsplit('/').next(), Some("mocha" | "_mocha"))) { return Some("mocha"); } + // Jasmine too, through the IDE's hook like Mocha. + if tokens.iter().any(|t| matches!(t.rsplit('/').next(), Some("jasmine" | "jasmine.js"))) { + return Some("jasmine"); + } let node = tokens.iter().position(|t| matches!(*t, "node" | "tsx"))?; // Node's own options: up to the script (`node server.js --test` passes `--test` to the program). let mut options = Vec::new(); @@ -271,6 +283,15 @@ const PLAYWRIGHT_CONFIGS: &[&str] = &[ "playwright.config.cjs", ]; +const CYPRESS_CONFIGS: &[&str] = &[ + "cypress.config.ts", + "cypress.config.js", + "cypress.config.mts", + "cypress.config.mjs", + "cypress.config.cts", + "cypress.config.cjs", +]; + /// Pushes the package's scripts; returns the test runners they start. fn push_scripts( pkg: &Json, @@ -325,6 +346,29 @@ fn push_playwright( out.push(c); } +/// `npx cypress run` for a package that depends on Cypress or has its configuration, when no script runs it. +fn push_cypress( + dir: &Path, + pkg: &Json, + runners: &HashSet<&str>, + prefix: Option<&str>, + cwd: Option<PathBuf>, + out: &mut Vec<RunConfig>, +) { + let depends = + ["dependencies", "devDependencies"].iter().any(|k| pkg.get(k).and_then(|d| d.get("cypress")).is_some()); + if runners.contains("cypress") || !(depends || first_existing(dir, CYPRESS_CONFIGS).is_some()) { + return; + } + let (id, name) = match prefix { + Some(p) => (format!("cypress:{p}"), format!("{p}: cypress run")), + None => ("cypress".to_owned(), "cypress run".to_owned()), + }; + let mut c = config(id, name, "cypress", "npx", &["cypress", "run"]).in_dir(cwd.clone()).test(); + c.extras.module = cwd.as_deref().map(ide_core::ipc_path::to_ipc); + out.push(c); +} + fn detect_node(root: &Path, out: &mut Vec<RunConfig>) { let mut covered = HashSet::new(); let projects = @@ -342,7 +386,8 @@ fn detect_node(root: &Path, out: &mut Vec<RunConfig>) { let prefix = (dir != root).then_some(label.as_str()); let cwd = (dir != root).then_some(rel); let runners = push_scripts(&pkg, pm, prefix, cwd.clone(), out); - push_playwright(&dir, &runners, prefix, cwd, out); + push_playwright(&dir, &runners, prefix, cwd.clone(), out); + push_cypress(&dir, &pkg, &runners, prefix, cwd, out); for member_dir in ide_core::project_roots::node_workspace_members(&dir) { if !covered.insert(member_dir.clone()) { continue; @@ -356,7 +401,8 @@ fn detect_node(root: &Path, out: &mut Vec<RunConfig>) { .unwrap_or_else(|| ide_core::ipc_path::to_ipc(&rel)); let name = if dir == root { name } else { format!("{label}:{name}") }; let runners = push_scripts(&member, pm, Some(&name), Some(rel.clone()), out); - push_playwright(&member_dir, &runners, Some(&name), Some(rel), out); + push_playwright(&member_dir, &runners, Some(&name), Some(rel.clone()), out); + push_cypress(&member_dir, &member, &runners, Some(&name), Some(rel), out); } } } @@ -1567,6 +1613,49 @@ pub(crate) fn just_recipes(src: &str) -> Vec<String> { // ---------------------------------------------------------------- godot +// ---------------------------------------------------------------- unreal + +/// Unreal Engine projects (`.uproject`) run through the engine's editor executable, which reads +/// its start-up mode from the command line: no flag is the editor, `-game` the game and `-server` +/// a dedicated server. All three exist for every project, blueprint-only ones included, because +/// the mode is decided at start-up rather than built. +fn detect_unreal(root: &Path, out: &mut Vec<RunConfig>) { + detect_projects_matching(root, |dir| ide_workspace::unreal::project_file(dir).is_some(), detect_one_unreal, out); +} + +/// One Unreal project: the editor, the game and a dedicated server, all run by the same +/// `UnrealEditor.exe` and differing only in the flag. +fn detect_one_unreal(root: &Path, out: &mut Vec<RunConfig>) { + let Some(info) = ide_workspace::unreal::detect(root) else { return }; + // Detection already resolved the engine; a project without one offers nothing to run. + let Some(found) = info.engine.as_ref() else { + tracing::debug!("no Unreal Engine installation for {}", root.display()); + return; + }; + let engine = + ide_workspace::unreal::engine::EngineInstall { id: found.id.clone(), root: PathBuf::from(&found.root) }; + let Some(project) = ide_workspace::unreal::project_file(root) else { return }; + let editor = engine.editor().to_string_lossy().into_owned(); + out.extend(unreal_configs(&project, &editor)); +} + +/// The editor, the game and a dedicated server: the three start-up modes the engine documents, +/// all run by `UnrealEditor.exe` and differing only in the flag. +fn unreal_configs(project: &Path, editor: &str) -> Vec<RunConfig> { + let project = project.to_string_lossy().into_owned(); + [ + ("unreal:editor", "Unreal Editor", None), + ("unreal:game", "Unreal Game", Some("-game")), + ("unreal:server", "Unreal Server", Some("-server")), + ] + .into_iter() + .map(|(id, name, flag)| { + let args: Vec<&str> = std::iter::once(project.as_str()).chain(flag).collect(); + config(id.to_owned(), name, "unreal", editor, &args).debug("lldb-dap") + }) + .collect() +} + // ---------------------------------------------------------------- rebar3 / mix /// rebar3 (Erlang): the shell with the applications started, the EUnit tests and, with @@ -1649,3 +1738,23 @@ fn detect_just(root: &Path, out: &mut Vec<RunConfig>) { out.push(c); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_unreal_project_offers_the_editor_the_game_and_a_dedicated_server() { + let configs = unreal_configs(Path::new("/p/Game.uproject"), "UE/UnrealEditor.exe"); + let listed: Vec<(&str, &str)> = configs.iter().map(|c| (c.id.as_str(), c.name.as_str())).collect(); + assert_eq!( + listed, + [("unreal:editor", "Unreal Editor"), ("unreal:game", "Unreal Game"), ("unreal:server", "Unreal Server"),] + ); + assert_eq!(configs[0].args, ["/p/Game.uproject"]); + assert_eq!(configs[1].args, ["/p/Game.uproject", "-game"]); + assert_eq!(configs[2].args, ["/p/Game.uproject", "-server"]); + assert!(configs.iter().all(|c| c.command == "UE/UnrealEditor.exe" && c.cwd.is_none())); + assert!(configs.iter().all(|c| c.debug_adapter.as_deref() == Some("lldb-dap") && c.kind == "unreal")); + } +} diff --git a/crates/ide-run/src/detect/dotnet.rs b/crates/ide-run/src/detect/dotnet.rs index ce1f433e0..fb8025370 100644 --- a/crates/ide-run/src/detect/dotnet.rs +++ b/crates/ide-run/src/detect/dotnet.rs @@ -19,11 +19,15 @@ pub(crate) fn detect(root: &Path, out: &mut Vec<RunConfig>) { let path = entry.path(); let name = entry.file_name().to_string_lossy().into_owned(); if entry.file_type().is_ok_and(|t| t.is_dir()) { - if !name.starts_with('.') + // Case-insensitive: Unreal's generated trees (`Binaries`, `Intermediate`, …) hold + // tens of thousands of files and copies of the engine's own tool projects. + let lower = name.to_ascii_lowercase(); + if !lower.starts_with('.') && !matches!( - name.as_str(), + lower.as_str(), "bin" | "obj" | "node_modules" | "target" | "build" | "dist" | "vendor" | "packages" ) + && !ide_workspace::unreal::GENERATED_DIRS.iter().any(|dir| dir.eq_ignore_ascii_case(&lower)) { dirs.push(path); } diff --git a/crates/ide-run/src/import/vscode.rs b/crates/ide-run/src/import/vscode.rs index 2cb62cb7f..57db68fc9 100644 --- a/crates/ide-run/src/import/vscode.rs +++ b/crates/ide-run/src/import/vscode.rs @@ -45,7 +45,7 @@ const COMMON: &[&str] = &["cwd", "env", "envFile"]; const PYTHON_LAUNCH: &[&str] = &["program", "module", "args", "python", "pythonArgs"]; const PYTHON_ATTACH: &[&str] = &["connect", "host", "port", "pathMappings"]; const NODE_LAUNCH: &[&str] = &["program", "args", "runtimeExecutable", "runtimeArgs"]; -const NODE_ATTACH: &[&str] = &["address", "port", "localRoot", "remoteRoot"]; +const NODE_ATTACH: &[&str] = &["address", "port", "localRoot", "remoteRoot", "restart"]; const NODE_TERMINAL: &[&str] = &["command"]; const BROWSER_LAUNCH: &[&str] = &["url", "webRoot"]; const DART_LAUNCH: &[&str] = &["program", "args", "toolArgs", "deviceId", "flutterMode"]; @@ -254,6 +254,10 @@ impl Cx<'_> { if obj.get("pathMappings").and_then(Value::as_array).is_some_and(|m| m.len() > 1) { ignored.push("pathMappings".into()); } + // A restart policy's delays and attempts: the option reconnects with js-debug's defaults. + if handled.contains(&"restart") && obj.get("restart").is_some_and(Value::is_object) { + ignored.push("restart".into()); + } ignored.sort(); Ok(Found { config, members: Vec::new(), ignored }) } @@ -349,6 +353,10 @@ impl Cx<'_> { let port = self.string(obj, "port")?.unwrap_or_else(|| "9229".into()); let mut c = config(name, "node-remote", String::new(), Vec::new(), Some("js-debug")); c.extras.params = BTreeMap::from([("host".into(), host), ("port".into(), port)]); + // Reconnect automatically: `true`, or a restart policy object (its delays are noted as ignored). + if matches!(obj.get("restart"), Some(Value::Bool(true) | Value::Object(_))) { + c.extras.params.insert("restart".into(), "true".into()); + } self.roots(obj, &mut c)?; Ok(c) } diff --git a/crates/ide-run/src/java_agent.rs b/crates/ide-run/src/java_agent.rs index c96adc5bd..e274d5fed 100644 --- a/crates/ide-run/src/java_agent.rs +++ b/crates/ide-run/src/java_agent.rs @@ -3,6 +3,10 @@ //! per plugin whose `java.agent` capability the user granted, for Run and Debug alike, //! plus any `vmOptions` the declaration lists (before the agent). //! +//! An agent bound to a plugin executor (`executor = "<title>"`, API 1.18) is added only to +//! launches through that executor ("Run with <title>" / "Debug with <title>"), whose id is +//! the plugin's id. +//! //! The grant records the jar's content hash; an agent whose jar no longer has it is //! left out (with a console line) until the user approves it again. The desktop //! installs the [`JavaAgentSource`]; elsewhere (`openidea-server`) there is none, so @@ -33,6 +37,8 @@ pub struct ContributedAgent { pub jdk: Option<String>, /// The jar's hash recorded when the user granted `java.agent`; `None`: not granted. pub approved_hash: Option<String>, + /// The title of the plugin executor the agent is bound to: added only to its launches. + pub executor: Option<String>, } /// The agents of the enabled plugins. @@ -61,8 +67,42 @@ pub fn current() -> Agents { /// Like [`current`], gating `vmOptions` with `jdk = "jetbrains"` against `java`. pub fn current_for(java: Option<&Path>) -> Agents { + current_for_executor(java, None) +} + +/// Like [`current_for`] for a launch through `executor` (a plugin id) or a plain one. +pub fn current_for_executor(java: Option<&Path>, executor: Option<&str>) -> Agents { let source = SOURCE.read().clone(); - source.map(|s| approved_for(&s.agents(), java)).unwrap_or_default() + match source { + Some(s) => for_executor(&s.agents(), java, executor), + None => { + Agents { options: Vec::new(), notes: executor.map(|e| missing_executor(e, None)).into_iter().collect() } + } + } +} + +/// The agents a launch gets: those bound to no executor, plus the one of `executor` (a plugin +/// id). A launch through an executor whose agent is not there or not granted says so. +pub fn for_executor(agents: &[ContributedAgent], java: Option<&Path>, executor: Option<&str>) -> Agents { + let chosen: Vec<ContributedAgent> = + agents.iter().filter(|a| a.executor.is_none() || (executor == Some(a.plugin.as_str()))).cloned().collect(); + let mut out = approved_for(&chosen, java); + if let Some(executor) = executor { + let own = agents.iter().find(|a| a.plugin == executor && a.executor.is_some()); + if own.is_none_or(|a| a.approved_hash.is_none()) { + out.notes.push(missing_executor(executor, own.and_then(|a| a.executor.as_deref()))); + } + } + out +} + +fn missing_executor(plugin: &str, title: Option<&str>) -> String { + match title { + Some(title) => format!( + "{title} was not applied: the Java agent of plugin {plugin} needs the java.agent permission (Settings › Plugins)." + ), + None => format!("The executor of plugin {plugin} is not available: the plugin is disabled or was removed."), + } } /// Granted agents whose jar still has the hash approved for it; an ungranted one is @@ -311,6 +351,7 @@ mod tests { vm_options: Vec::new(), jdk: None, approved_hash: granted.then(|| jar.hash.clone()), + executor: None, } } @@ -452,6 +493,34 @@ mod tests { assert_eq!(again, strings(&["-XX:+AllowEnhancedClassRedefinition", "-cp", "x", &javaagent, "Main"])); } + #[test] + fn an_executor_agent_loads_only_through_its_executor() { + let (plain_jar, bound_jar) = (jar(), jar()); + let plain = agent(&plain_jar, None, true); + let mut bound = agent(&bound_jar, None, true); + bound.plugin = "acme.reload".into(); + bound.executor = Some("Hot Reload".into()); + let agents = [plain, bound.clone()]; + let plain_opt = format!("-javaagent:{}", plain_jar.path.display()); + let bound_opt = format!("-javaagent:{}", bound_jar.path.display()); + + let run = for_executor(&agents, None, None); + assert_eq!(run.options, std::slice::from_ref(&plain_opt), "a plain launch leaves the executor's agent out"); + assert!(run.notes.is_empty()); + let with = for_executor(&agents, None, Some("acme.reload")); + assert_eq!(with.options, [plain_opt.clone(), bound_opt]); + assert!(with.notes.is_empty()); + // Another plugin's executor id: only the plain agent, and a note. + let other = for_executor(&agents, None, Some("acme.spring")); + assert_eq!(other.options, std::slice::from_ref(&plain_opt)); + assert_eq!(other.notes.len(), 1); + + bound.approved_hash = None; + let ungranted = for_executor(&[bound], None, Some("acme.reload")); + assert!(ungranted.options.is_empty()); + assert!(ungranted.notes[0].starts_with("Hot Reload was not applied"), "{:?}", ungranted.notes); + } + #[test] fn jetbrains_vm_options_skip_on_other_jdks() { let jar = jar(); diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index 5aa61f8f3..4cabf8e72 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -188,6 +188,15 @@ pub struct RunExtras { #[serde(default, skip_serializing_if = "Option::is_none")] #[specta(optional)] pub test_runner: Option<String>, + /// Jest / Vitest "Watch for changes": the run stays alive and reruns the tests after each edit. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + #[specta(optional)] + pub watch: bool, + /// The plugin executor a launch goes through ("Run with <title>"): the plugin's id. Set + /// on the launched copy, not saved; the plugin's executor-bound Java agent loads only then. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub executor: Option<String>, } impl Default for RunExtras { @@ -212,6 +221,8 @@ impl Default for RunExtras { stop_command: None, target: None, test_runner: None, + watch: false, + executor: None, } } } diff --git a/crates/ide-run/tests/config.rs b/crates/ide-run/tests/config.rs index ef565b4f0..822332890 100644 --- a/crates/ide-run/tests/config.rs +++ b/crates/ide-run/tests/config.rs @@ -134,6 +134,7 @@ fn extras_round_trip_and_local_file() { shared.extras.open_tool_window = Some(false); shared.extras.focus_tool_window = true; shared.extras.emulate_terminal = true; + shared.extras.watch = true; shared.extras.stop_command = Some("docker stop server".into()); let mut local = sample().remove(1); local.extras.local = true; diff --git a/crates/ide-run/tests/detect.rs b/crates/ide-run/tests/detect.rs index b9b63b512..84b1a433c 100644 --- a/crates/ide-run/tests/detect.rs +++ b/crates/ide-run/tests/detect.rs @@ -76,6 +76,31 @@ fn playwright_scripts_and_configs() { assert_eq!(site.debug_adapter.as_deref(), Some("js-debug")); } +#[test] +fn cypress_scripts_dependencies_and_configs() { + let dir = project(&[ + ("package.json", r#"{"scripts":{"cy:run":"cypress run --browser chrome","cy:open":"cypress open"}}"#), + ("cypress.config.ts", ""), + ("web/package.json", r#"{"devDependencies":{"cypress":"^15.0.0"}}"#), + ("docs/package.json", r#"{"scripts":{"build":"vite build"}}"#), + ("docs/cypress.config.js", ""), + ]); + let c = detect(dir.path()); + let run = find(&c, "npm:cy:run"); + assert!(run.is_test); + assert_eq!(run.extras.test_runner.as_deref(), Some("cypress")); + assert!(!find(&c, "npm:cy:open").is_test); + // The root's script runs Cypress already. + assert!(!ids(&c).contains(&"cypress")); + let web = find(&c, "cypress:web"); + assert_eq!(cmdline(web), "npx cypress run"); + assert_eq!(web.name, "web: cypress run"); + assert!(web.is_test && web.detected); + assert_eq!(web.kind, "cypress"); + assert_eq!(web.cwd.as_deref(), Some(Path::new("web"))); + assert_eq!(find(&c, "cypress:docs").kind, "cypress"); +} + #[test] fn node_test_scripts() { let dir = project(&[( @@ -106,6 +131,20 @@ fn mocha_scripts() { assert!(!find(&c, "npm:lint").is_test); } +#[test] +fn jasmine_scripts() { + let dir = project(&[( + "package.json", + r#"{"scripts":{"spec":"jasmine --config=spec/support/jasmine.json","test":"tsc && node node_modules/jasmine/bin/jasmine.js","browser":"jasmine-browser-runner runSpecs"}}"#, + )]); + let c = detect(dir.path()); + let spec = find(&c, "npm:spec"); + assert!(spec.is_test); + assert_eq!(spec.extras.test_runner.as_deref(), Some("jasmine")); + assert_eq!(find(&c, "npm:test").extras.test_runner.as_deref(), Some("jasmine")); + assert!(!find(&c, "npm:browser").is_test); +} + #[test] fn package_manager_selection() { for (lock, pm) in [("yarn.lock", "yarn"), ("bun.lockb", "bun"), ("bun.lock", "bun"), ("package-lock.json", "npm")] { @@ -1378,3 +1417,40 @@ fn sbt_projects() { assert_eq!(cmdline(&detect(dir.path())[1]), "./sbt test"); } } + +/// UE writes a `.sln` listing the engine's own tool projects; expanding it buries the run menu. +#[test] +fn a_solution_in_a_unreal_project_is_not_expanded_into_dotnet_configurations() { + let dir = project(&[ + ("Game.uproject", r#"{"FileVersion":3,"EngineAssociation":"5.8"}"#), + ( + "Game.sln", + r#"Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Game", "Source\Game\Game.csproj", "{00000000-0000-0000-0000-000000000000}" +EndProject +"#, + ), + ( + "Source/Game/Game.csproj", + r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType></PropertyGroup></Project>"#, + ), + ]); + let c = detect(dir.path()); + assert!(c.iter().all(|c| !c.kind.starts_with("dotnet")), "{:?}", ids(&c)); +} + +/// The engine keeps copies of its tool projects under the generated trees, which hold no code +/// anyone runs from here — and on a real project they are deep enough to slow detection down. +#[test] +fn csproj_under_unreal_generated_directories_is_not_detected() { + let exe = + r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType></PropertyGroup></Project>"#; + let dir = project(&[ + ("Intermediate/ProjectFiles/UnrealBuildTool/UnrealBuildTool.csproj", exe), + ("Binaries/Win64/ShaderCopy/ShaderCopy.csproj", exe), + ("Saved/Tools/Helper/Helper.csproj", exe), + ("DerivedDataCache/Worker/Worker.csproj", exe), + ]); + let c = detect(dir.path()); + assert!(c.is_empty(), "{:?}", ids(&c)); +} diff --git a/crates/ide-run/tests/import_vscode.rs b/crates/ide-run/tests/import_vscode.rs index 840d21546..091e4afb0 100644 --- a/crates/ide-run/tests/import_vscode.rs +++ b/crates/ide-run/tests/import_vscode.rs @@ -380,6 +380,9 @@ fn attach_requests_become_remote_debug_configurations() { "pathMappings": [{ "localRoot": "${workspaceFolder}", "remoteRoot": "/app" }] }, { "name": "Attach to Node", "type": "node", "request": "attach", "port": 9230, "localRoot": "${workspaceFolder}/web", "remoteRoot": "/usr/src/app", "restart": true }, + { "name": "Attach (no restart)", "type": "pwa-node", "request": "attach", "restart": false }, + { "name": "Attach (restart policy)", "type": "node", "request": "attach", + "restart": { "delay": 500, "maxAttempts": 5 } }, { "name": "Attach to PID", "type": "debugpy", "request": "attach", "processId": "${command:pickProcess}" }, { "name": "Odd", "type": "node", "request": "test" } ] @@ -402,7 +405,13 @@ fn attach_requests_become_remote_debug_configurations() { assert_eq!(node.extras.params["port"], "9230"); assert_eq!(node.extras.params["localRoot"], "web"); assert_eq!(node.extras.params["remoteRoot"], "/usr/src/app"); - assert_eq!(ignored(&r, "Attach to Node"), ["restart"]); + assert_eq!(node.extras.params["restart"], "true"); + assert!(ignored(&r, "Attach to Node").is_empty()); + let off = get(&r, "Attach (no restart)"); + assert!(!off.extras.params.contains_key("restart")); + assert!(ignored(&r, "Attach (no restart)").is_empty()); + assert_eq!(get(&r, "Attach (restart policy)").extras.params["restart"], "true"); + assert_eq!(ignored(&r, "Attach (restart policy)"), ["restart"]); assert_eq!(reason(&r, "Attach to PID"), &SkipReason::UnsupportedAttach); assert_eq!(reason(&r, "Odd"), &SkipReason::UnsupportedRequest { request: "test".into() }); diff --git a/crates/ide-sdk/src/apply.rs b/crates/ide-sdk/src/apply.rs index d2805dd80..2d0c78eb0 100644 --- a/crates/ide-sdk/src/apply.rs +++ b/crates/ide-sdk/src/apply.rs @@ -905,7 +905,7 @@ pub fn native_tsdk(root: &Path, s: &Settings) -> Option<PathBuf> { const PYTHON_SERVERS: [&str; 8] = ["basedpyright", "pyright", "ty", "pyrefly", "pylsp", "jedi-language-server", "ruff", "djlsp"]; -pub(crate) fn merge(base: &mut Value, layer: Value) { +pub fn merge(base: &mut Value, layer: Value) { match (base, layer) { (Value::Object(base), Value::Object(layer)) => { for (k, v) in layer { @@ -1513,7 +1513,10 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root && !server_root.ancestors().any(|d| d.join("tsconfig.json").is_file() || d.join("jsconfig.json").is_file()) { let node = node_dir(root, s).map(|d| d.join(exe("node"))).filter(|p| p.is_file()).or_else(|| which("node")); - cfg.tsserver_project_extras.paths = vue::cli_paths(server_root, node.as_deref()); + let mut paths = vue::cli_paths(server_root, node.as_deref()); + // The project's own Vite / Rollup / esbuild aliases replace the Vue template's `@`. + paths.extend(crate::path_aliases::paths(server_root)); + cfg.tsserver_project_extras.paths = paths; } if name == vue::SERVER { configure_vue_typescript(cfg, root, server_root, s); @@ -1610,6 +1613,42 @@ pub fn configure_vue_module_resolution(cfg: &mut LanguageServerConfig, data_dir: true } +/// Registers the tsserver plugin that adds the Vite / Rollup / esbuild path aliases of each +/// package under `server_root` to that package's tsserver projects' `paths`, below +/// tsconfig.json / jsconfig.json's own (#6020). Only vtsls hosts tsserver plugins (not +/// TypeScript 7's native server). No-op without aliases. +pub fn configure_path_aliases(cfg: &mut LanguageServerConfig, server_root: &Path, data_dir: &Path) -> bool { + if cfg.name != "vtsls" || !cfg.tsserver_project { + return false; + } + let packages = crate::path_aliases::packages(server_root); + if packages.is_empty() { + return false; + } + let Some(plugin) = crate::path_aliases::tsserver_plugin(data_dir, server_root, &packages) else { + return false; + }; + let mut current = + cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok()).unwrap_or_else(|| json!({})); + let mut node = &mut current; + for key in ["vtsls", "tsserver"] { + node = object_entry(node, key); + } + let plugins = + node.as_object_mut().expect("made an object above").entry("globalPlugins").or_insert_with(|| json!([])); + if !plugins.is_array() { + *plugins = json!([]); + } + let plugins = plugins.as_array_mut().expect("made an array above"); + plugins.retain(|p| p.get("name").and_then(Value::as_str) != Some(crate::path_aliases::PLUGIN)); + plugins.push(plugin); + match toml::Value::try_from(current) { + Ok(v) => cfg.initialization_options = Some(v), + Err(e) => tracing::warn!("{}: cannot apply settings to initialization options: {e}", cfg.name), + } + true +} + /// The servers `language` uses after Settings › Language Servers: the /// definition's ones that aren't disabled, then the ones defined in settings for it. pub fn language_servers(language: &str, defined: &[LanguageServerConfig], s: &Settings) -> Vec<LanguageServerConfig> { diff --git a/crates/ide-sdk/src/lib.rs b/crates/ide-sdk/src/lib.rs index e615c4e66..0ec726508 100644 --- a/crates/ide-sdk/src/lib.rs +++ b/crates/ide-sdk/src/lib.rs @@ -23,6 +23,7 @@ pub mod locate; pub mod lombok; pub mod maven_profiles; mod npm; +mod path_aliases; pub mod php; pub mod pinned; pub mod python; diff --git a/crates/ide-sdk/src/path-aliases.js b/crates/ide-sdk/src/path-aliases.js new file mode 100644 index 000000000..7bccc2765 --- /dev/null +++ b/crates/ide-sdk/src/path-aliases.js @@ -0,0 +1,53 @@ +"use strict"; +// Adds a project's Vite / Rollup / esbuild path aliases to every tsserver project's +// `compilerOptions.paths`, below the project's own `paths`: tsserver reads only +// tsconfig.json / jsconfig.json, so `@/` imports resolved by the bundler resolve to nothing +// in the editor and complete no paths. The IDE writes the aliases of each directory holding +// a bundler configuration, as absolute `paths` entries, to `paths.json` next to this file. +const fs = require("fs"); +const path = require("path"); + +const key = (dir) => { + const resolved = path.resolve(dir); + return process.platform === "win32" ? resolved.toLowerCase() : resolved; +}; + +// The aliases of the configuration nearest `dir` within its package: a workspace member +// gets its own configuration's, never the monorepo root's. +function aliasesFor(packages, dir) { + for (dir = path.resolve(dir); ; dir = path.dirname(dir)) { + const aliases = packages.get(key(dir)); + if (aliases) return aliases; + if (fs.existsSync(path.join(dir, "package.json")) || path.dirname(dir) === dir) return undefined; + } +} + +module.exports = () => ({ + create(info) { + const host = info.languageServiceHost; + let aliases; + try { + const packages = JSON.parse(fs.readFileSync(path.join(__dirname, "paths.json"), "utf8")); + const byDir = new Map(Object.entries(packages).map(([dir, paths]) => [key(dir), paths])); + aliases = aliasesFor(byDir, info.project.getCurrentDirectory()); + } catch { + return info.languageService; + } + if (!aliases || !host || typeof host.getCompilationSettings !== "function") { + return info.languageService; + } + const getCompilationSettings = host.getCompilationSettings.bind(host); + // The same options object while the project's own stay the same, so the program is kept. + let own; + let merged; + host.getCompilationSettings = () => { + const options = getCompilationSettings(); + if (options !== own) { + own = options; + merged = { ...options, paths: { ...aliases, ...options.paths } }; + } + return merged; + }; + return info.languageService; + }, +}); diff --git a/crates/ide-sdk/src/path_aliases.rs b/crates/ide-sdk/src/path_aliases.rs new file mode 100644 index 000000000..4e8d57ad6 --- /dev/null +++ b/crates/ide-sdk/src/path_aliases.rs @@ -0,0 +1,250 @@ +//! Path aliases of the project's Vite, Rollup (`@rollup/plugin-alias`) or esbuild +//! configuration, for tsserver (vtsls), which only reads tsconfig.json / jsconfig.json +//! `paths`. Read statically: the configuration is never run. + +use sha2::{Digest, Sha256}; +use std::path::Path; + +pub(crate) type Paths = std::collections::BTreeMap<String, Vec<String>>; +/// [`paths`] of each directory holding a bundler configuration, by directory (`/` separated). +pub(crate) type Packages = std::collections::BTreeMap<String, Paths>; + +/// The tsserver plugin that adds a project's [`Packages`] entry to its `compilerOptions.paths`. +pub(crate) const PLUGIN: &str = "openidea-path-aliases"; +const PLUGIN_JS: &str = include_str!("path-aliases.js"); + +/// Configurations read, in priority order (the first one defining an alias wins). +const CONFIGS: &[&str] = &[ + "vite.config.ts", + "vite.config.mts", + "vite.config.cts", + "vite.config.js", + "vite.config.mjs", + "vite.config.cjs", + "rollup.config.ts", + "rollup.config.mts", + "rollup.config.js", + "rollup.config.mjs", + "rollup.config.cjs", + "esbuild.config.ts", + "esbuild.config.mts", + "esbuild.config.js", + "esbuild.config.mjs", + "esbuild.config.cjs", +]; + +/// `compilerOptions.paths` (`@/*` → `<root>/src/*`) for the directory aliases of the +/// bundler configurations in `root` itself. Empty without any. +pub(crate) fn paths(root: &Path) -> Paths { + let mut aliases: Vec<(String, String)> = Vec::new(); + for config in CONFIGS.iter().map(|f| root.join(f)) { + let Ok(text) = std::fs::read_to_string(&config) else { continue }; + for (name, target) in ide_language::bundler_aliases(&text, root) { + if !aliases.iter().any(|(n, _)| *n == name) { + aliases.push((name, target_dir(root, &target))); + } + } + } + crate::vue::alias_paths(&aliases) +} + +/// The aliases of every package (workspace member) under `root`: the bundler configurations +/// of each directory down to a monorepo's `apps/web` / `packages/ui/demo`, honouring ignore +/// files and skipping `node_modules`. The plugin gives a tsserver project the entry of its +/// own package only. +pub(crate) fn packages(root: &Path) -> Packages { + // ponytail: bounded walk; deeper workspace members go without aliases. + const MAX_DEPTH: usize = 4; + const MAX_ENTRIES: usize = 50_000; + let mut walker = ignore::WalkBuilder::new(root); + walker + .max_depth(Some(MAX_DEPTH)) + .require_git(ide_core::ignored::inside_git_repo(root)) + .follow_links(false) + .filter_entry(|e| e.file_name() != "node_modules"); + let mut dirs: Vec<std::path::PathBuf> = walker + .build() + .take(MAX_ENTRIES) + .flatten() + .filter(|e| CONFIGS.iter().any(|c| e.file_name() == *c)) + .filter_map(|e| e.path().parent().map(Path::to_path_buf)) + .collect(); + dirs.sort(); + dirs.dedup(); + dirs.into_iter() + .map(|dir| (dir.to_string_lossy().replace('\\', "/"), paths(&dir))) + .filter(|(_, paths)| !paths.is_empty()) + .collect() +} + +/// Vite resolves `/src` from the project root; esbuild a relative target from the working +/// directory (the project root here). A `/`-rooted target without a drive or UNC prefix is +/// root-relative on Windows too, unless it is an existing directory elsewhere. +fn target_dir(root: &Path, target: &str) -> String { + let path = Path::new(target); + let path = if path.is_absolute() && (path.is_dir() || !target.starts_with('/')) { + path.to_path_buf() + } else { + root.join(target.trim_start_matches('/').trim_start_matches("./")) + }; + path.to_string_lossy().into_owned() +} + +/// The vtsls `globalPlugins` entry of the plugin, written with `packages` under `data_dir`. +/// Each server root gets its own copy, as the plugin reads its aliases next to itself. +/// `None` when the data dir cannot be written. +pub(crate) fn tsserver_plugin(data_dir: &Path, root: &Path, packages: &Packages) -> Option<serde_json::Value> { + let key = Sha256::digest(root.to_string_lossy().as_bytes()); + let key: String = key.iter().take(8).map(|b| format!("{b:02x}")).collect(); + let location = data_dir.join("tsplugins").join("path-aliases").join(key); + let dir = location.join("node_modules").join(PLUGIN); + std::fs::create_dir_all(&dir).ok()?; + let json = serde_json::to_string(packages).ok()?; + for (file, content) in [("index.js", PLUGIN_JS), ("paths.json", json.as_str())] { + if std::fs::read(dir.join(file)).ok().as_deref() != Some(content.as_bytes()) { + std::fs::write(dir.join(file), content).ok()?; + } + } + Some(serde_json::json!({ + "name": PLUGIN, + "location": location.to_string_lossy(), + "enableForWorkspaceTypeScriptVersions": true, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vite_aliases_become_paths() { + let tmp = tempfile::tempdir().unwrap(); + let t = &dunce::canonicalize(tmp.path()).unwrap(); + std::fs::create_dir_all(t.join("src/components")).unwrap(); + std::fs::create_dir_all(t.join("lib")).unwrap(); + assert!(paths(t).is_empty()); + std::fs::write( + t.join("vite.config.ts"), + r#"import path from 'path'; +export default { resolve: { alias: [ + { find: '@', replacement: path.resolve(__dirname, 'src') }, + { find: 'comps', replacement: '/src/components' }, + { find: 'vue', replacement: 'vue/dist/vue.esm-bundler.js' }, +] } };"#, + ) + .unwrap(); + // A later configuration adds aliases but doesn't override the Vite ones. + std::fs::write( + t.join("rollup.config.mjs"), + "import alias from '@rollup/plugin-alias';\nexport default { plugins: [alias({ entries: { '@': './lib', lib: './lib' } })] };", + ) + .unwrap(); + let slash = |p: std::path::PathBuf| p.to_string_lossy().replace('\\', "/"); + let (src, comps, lib) = (slash(t.join("src")), slash(t.join("src/components")), slash(t.join("lib"))); + assert_eq!( + paths(t), + Paths::from([ + ("@".into(), vec![src.clone()]), + ("@/*".into(), vec![format!("{src}/*")]), + ("comps".into(), vec![comps.clone()]), + ("comps/*".into(), vec![format!("{comps}/*")]), + ("lib".into(), vec![lib.clone()]), + ("lib/*".into(), vec![format!("{lib}/*")]), + ]) + ); + } + + #[test] + fn each_workspace_member_gets_its_own_configuration() { + let tmp = tempfile::tempdir().unwrap(); + let t = &dunce::canonicalize(tmp.path()).unwrap(); + let vite = |dir: &str| { + std::fs::create_dir_all(t.join(dir).join("src")).unwrap(); + let config = "export default { resolve: { alias: { '@': path.resolve(__dirname, 'src') } } };"; + std::fs::write(t.join(dir).join("vite.config.ts"), config).unwrap(); + }; + vite(""); + vite("apps/web"); + vite("node_modules/dep"); + std::fs::create_dir_all(t.join("packages/ui")).unwrap(); + let slash = |p: std::path::PathBuf| p.to_string_lossy().replace('\\', "/"); + let packages = packages(t); + assert_eq!(packages.keys().cloned().collect::<Vec<_>>(), [slash(t.to_path_buf()), slash(t.join("apps/web"))]); + assert_eq!(packages[&slash(t.join("apps/web"))]["@"], [slash(t.join("apps/web/src"))]); + } + + #[test] + fn root_relative_targets_stay_in_the_root_on_every_platform() { + let root = Path::new("/p"); + let slash = |s: String| s.replace('\\', "/"); + assert_eq!(slash(target_dir(root, "/src/components")), "/p/src/components"); + assert_eq!(slash(target_dir(root, "./lib")), "/p/lib"); + let here = std::env::current_dir().unwrap(); + assert_eq!(target_dir(root, &here.to_string_lossy()), here.to_string_lossy()); + } + + #[test] + fn the_plugin_is_written_with_its_aliases() { + let tmp = tempfile::tempdir().unwrap(); + let packages = Packages::from([("/p".into(), Paths::from([("@/*".into(), vec!["/p/src/*".into()])]))]); + let plugin = tsserver_plugin(tmp.path(), Path::new("/p"), &packages).unwrap(); + assert_eq!(plugin["name"], PLUGIN); + let dir = Path::new(plugin["location"].as_str().unwrap()).join("node_modules").join(PLUGIN); + assert_eq!(std::fs::read_to_string(dir.join("index.js")).unwrap(), PLUGIN_JS); + assert_eq!(std::fs::read_to_string(dir.join("paths.json")).unwrap(), r#"{"/p":{"@/*":["/p/src/*"]}}"#); + let other = tsserver_plugin(tmp.path(), Path::new("/q"), &packages).unwrap(); + assert_ne!(other["location"], plugin["location"], "one copy per server root"); + } + + #[test] + fn the_plugin_adds_the_aliases_of_the_projects_package_below_its_own_paths() { + let Some(node) = crate::exec::which("node") else { return }; + let tmp = tempfile::tempdir().unwrap(); + let t = &dunce::canonicalize(tmp.path()).unwrap(); + for dir in ["", "apps/web/nested", "apps/api"] { + std::fs::create_dir_all(t.join(dir)).unwrap(); + } + for dir in ["", "apps/web", "apps/api"] { + std::fs::write(t.join(dir).join("package.json"), "{}").unwrap(); + } + let slash = |p: std::path::PathBuf| p.to_string_lossy().replace('\\', "/"); + let packages = Packages::from([ + (slash(t.to_path_buf()), Paths::from([("@/*".into(), vec!["/root/*".into()])])), + ( + slash(t.join("apps/web")), + Paths::from([("@/*".into(), vec!["/web/*".into()]), ("~/*".into(), vec!["/web/lib/*".into()])]), + ), + ]); + let plugin = tsserver_plugin(&t.join("data"), t, &packages).unwrap(); + let index = Path::new(plugin["location"].as_str().unwrap()).join("node_modules").join(PLUGIN); + // tsserver calls the factory, then `create` with the project and its host. + let script = "const create = (dir, settings) => { const host = { getCompilationSettings: settings }; \ + require(process.argv[1])({}).create({ project: { getCurrentDirectory: () => dir }, \ + languageServiceHost: host, languageService: {} }); return host; }; \ + let own = { strict: true, paths: { '@/*': ['./own/*'] } }; \ + const web = create(process.argv[2] + '/apps/web/nested', () => own); \ + const a = web.getCompilationSettings(); const same = a === web.getCompilationSettings(); \ + own = { strict: false }; const b = web.getCompilationSettings(); \ + const api = create(process.argv[2] + '/apps/api', () => ({})).getCompilationSettings(); \ + const root = create(process.argv[2], () => ({})).getCompilationSettings(); \ + process.stdout.write(JSON.stringify({ a, same, b, api, root }));"; + let out = crate::exec::query_in( + &node, + &["-e", script, &index.to_string_lossy(), &t.to_string_lossy()], + None, + &[], + std::time::Duration::from_secs(30), + ); + let out: serde_json::Value = serde_json::from_str(&out.unwrap()).unwrap(); + assert_eq!( + out, + serde_json::json!({ + "a": { "strict": true, "paths": { "@/*": ["./own/*"], "~/*": ["/web/lib/*"] } }, + "same": true, + "b": { "strict": false, "paths": { "@/*": ["/web/*"], "~/*": ["/web/lib/*"] } }, + "api": {}, + "root": { "paths": { "@/*": ["/root/*"] } }, + }) + ); + } +} diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs index d4d1d8582..6f53ffd50 100644 --- a/crates/ide-sdk/src/tests.rs +++ b/crates/ide-sdk/src/tests.rs @@ -3511,6 +3511,44 @@ fn vue_module_resolution_plugin_follows_the_vue_plugin() { assert_eq!(plugins.len(), 2); } +#[test] +fn vtsls_gets_the_path_alias_plugin_for_vite_aliases() { + let tmp = tempfile::tempdir().unwrap(); + let (root, data) = (tmp.path().join("app"), tmp.path().join("data")); + std::fs::create_dir_all(root.join("src")).unwrap(); + let mut cfg = server("vtsls"); + cfg.tsserver_project = true; + assert!(!crate::apply::configure_path_aliases(&mut cfg, &root, &data), "no bundler configuration"); + std::fs::write( + root.join("vite.config.js"), + "import path from 'path';\nexport default { resolve: { alias: { '@': path.resolve(__dirname, 'src') } } };", + ) + .unwrap(); + let mut other = server("typescript-language-server"); + other.tsserver_project = true; + assert!(!crate::apply::configure_path_aliases(&mut other, &root, &data)); + // TypeScript 7's native server hosts no plugins. + let mut native = server("vtsls"); + assert!(!crate::apply::configure_path_aliases(&mut native, &root, &data)); + crate::apply::merge_init_options( + &mut cfg, + serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [crate::vue::tsserver_plugin(Path::new("/vue"))] } } }), + ); + for _ in 0..2 { + assert!(crate::apply::configure_path_aliases(&mut cfg, &root, &data)); + let init = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap(); + let names: Vec<_> = init + .pointer("/vtsls/tsserver/globalPlugins") + .unwrap() + .as_array() + .unwrap() + .iter() + .map(|p| p["name"].clone()) + .collect(); + assert_eq!(names, ["@vue/typescript-plugin", "openidea-path-aliases"], "kept once, after the others"); + } +} + #[test] fn without_the_vue_plugin_the_module_resolution_plugin_stays_out() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-sdk/src/vue.rs b/crates/ide-sdk/src/vue.rs index 929fdbf8e..09b5a20c1 100644 --- a/crates/ide-sdk/src/vue.rs +++ b/crates/ide-sdk/src/vue.rs @@ -152,9 +152,11 @@ fn webpack_aliases(root: &Path, config: &Path, node: &Path) -> Option<Vec<(Strin } /// Directory aliases as `paths`; `name$` (exact module) and file aliases have no equivalent. -fn alias_paths(aliases: &[(String, String)]) -> Paths { +pub(crate) fn alias_paths(aliases: &[(String, String)]) -> Paths { let mut paths = Paths::new(); for (name, target) in aliases { + // `'@/': '/src/'` is the `@` alias too. + let name = name.trim_end_matches('/'); let dir = Path::new(target); if name.is_empty() || name.ends_with('$') || name.contains('*') || !dir.is_absolute() || !dir.is_dir() { continue; @@ -162,7 +164,7 @@ fn alias_paths(aliases: &[(String, String)]) -> Paths { let dir = target.replace('\\', "/"); let dir = dir.trim_end_matches('/'); paths.insert(format!("{name}/*"), vec![format!("{dir}/*")]); - paths.insert(name.clone(), vec![dir.to_owned()]); + paths.insert(name.to_owned(), vec![dir.to_owned()]); } paths } diff --git a/crates/ide-ssh/src/manager.rs b/crates/ide-ssh/src/manager.rs index ee35ca6ea..2c05b9b90 100644 --- a/crates/ide-ssh/src/manager.rs +++ b/crates/ide-ssh/src/manager.rs @@ -152,6 +152,8 @@ impl SshManager { let config = self.config(id)?; let secret = self.secret(&config); let session = Arc::new(self.connect(id, &SshTarget::from(&config), secret.as_deref()).await?); + // The shared session carries the config's port forwards, restarted on every reconnect. + session.start_forwards().await; self.sessions.lock().insert(id.to_owned(), session.clone()); Ok(session) } diff --git a/crates/ide-ssh/src/session.rs b/crates/ide-ssh/src/session.rs index 9ea118da4..cba0f00ac 100644 --- a/crates/ide-ssh/src/session.rs +++ b/crates/ide-ssh/src/session.rs @@ -7,7 +7,9 @@ //! (or is recorded silently under `StrictHostKeyChecking accept-new`), and a //! changed key is refused unless host key checking is off. -use crate::target::{Hop, HostKeyPolicy, SshFiles, SshTarget, expand, home, resolve_hops}; +use crate::target::{ + ForwardDirection, Hop, HostKeyPolicy, PortForward, SshFiles, SshTarget, expand, home, resolve_hops, +}; use ide_core::remote_settings::SshAuth; use ide_core::{IdeError, IdeResult, error::ErrorKind}; use parking_lot::Mutex; @@ -113,6 +115,18 @@ pub struct Session { /// Sessions of the `ProxyJump` hosts, kept alive under `handle`. _jumps: Vec<Handle<Client>>, label: String, + /// The config's `LocalForward` / `RemoteForward`s, started by [`Session::start_forwards`]. + forwards: Vec<PortForward>, + /// `LocalForward` listeners, stopped with the session. + listeners: Mutex<Vec<tokio::task::AbortHandle>>, +} + +impl Drop for Session { + fn drop(&mut self) { + for listener in self.listeners.lock().drain(..) { + listener.abort(); + } + } } impl Session { @@ -158,8 +172,50 @@ impl Session { sessions.push(handle); } let handle = sessions.pop().expect("at least one hop"); - let label = hops.last().expect("at least one hop").label(); - Ok(Session { handle, _jumps: sessions, label }) + let last = hops.last().expect("at least one hop"); + Ok(Session { + handle, + _jumps: sessions, + label: last.label(), + forwards: last.forwards.clone(), + listeners: Mutex::default(), + }) + } + + /// Starts the config's `LocalForward` / `RemoteForward`s, as `ssh` does on connecting: the + /// SSH host listens for each `RemoteForward` (`tcpip-forward`), this machine for each + /// `LocalForward`, until the session closes. A port that cannot be forwarded (in use, refused + /// by the server) is skipped with a warning, as `ssh` goes on without it. + pub async fn start_forwards(self: &Arc<Self>) { + for f in &self.forwards { + let what = format!("{}:{} → {}:{}", f.bind, f.port, f.host, f.host_port); + match f.direction { + ForwardDirection::Remote => match self.handle.tcpip_forward(f.bind.clone(), u32::from(f.port)).await { + Ok(_) => tracing::info!("{}: RemoteForward {what}", self.label), + Err(e) => tracing::warn!("{}: RemoteForward {what} failed: {e}", self.label), + }, + ForwardDirection::Local => { + let bind = match f.bind.as_str() { + "localhost" => "127.0.0.1", + "" => "0.0.0.0", + b => b, + }; + match tokio::net::TcpListener::bind((bind, f.port)).await { + Ok(listener) => { + let task = tokio::spawn(local_forward( + listener, + Arc::downgrade(self), + f.host.clone(), + f.host_port, + )); + self.listeners.lock().push(task.abort_handle()); + tracing::info!("{}: LocalForward {what}", self.label); + } + Err(e) => tracing::warn!("{}: LocalForward {what} failed: {e}", self.label), + } + } + } + } } /// `user@host:port` of the target. @@ -404,6 +460,39 @@ fn io(message: impl Into<String>) -> IdeError { IdeError::new(ErrorKind::Io, message) } +/// A `LocalForward` listener: each connection goes through a `direct-tcpip` channel to +/// `host:port` from the SSH host, while the session lives. +async fn local_forward(listener: tokio::net::TcpListener, session: std::sync::Weak<Session>, host: String, port: u16) { + while let Ok((mut socket, _)) = listener.accept().await { + let Some(session) = session.upgrade().filter(|s| !s.is_closed()) else { return }; + let host = host.clone(); + tokio::spawn(async move { + match session.direct_tcpip(&host, port).await { + Ok(mut stream) => { + drop(session); + let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await; + } + Err(e) => tracing::warn!("LocalForward: cannot open a channel to {host}:{port}: {e}"), + } + }); + } +} + +/// A `RemoteForward` connection: accepted once `host:port` here answers, then copied both ways. +async fn remote_forward(channel: russh::Channel<Msg>, reply: client::ChannelOpenHandle, host: String, port: u16) { + match tokio::net::TcpStream::connect((host.as_str(), port)).await { + Ok(mut socket) => { + reply.accept().await; + let mut stream = channel.into_stream(); + let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await; + } + Err(e) => { + tracing::warn!("RemoteForward: cannot connect to {host}:{port}: {e}"); + reply.reject(russh::ChannelOpenFailure::ConnectFailed).await; + } + } +} + // --- connection ---------------------------------------------------------------- #[derive(Debug)] @@ -418,6 +507,8 @@ pub struct Client { known_hosts: PathBuf, host_key_policy: HostKeyPolicy, issue: Arc<Mutex<Option<HostKeyIssue>>>, + /// The `RemoteForward`s whose connections this client accepts. + remote_forwards: Vec<PortForward>, } impl client::Handler for Client { @@ -442,6 +533,26 @@ impl client::Handler for Client { *self.issue.lock() = Some(issue); Ok(false) } + + async fn server_channel_open_forwarded_tcpip( + &mut self, + channel: russh::Channel<Msg>, + _connected_address: &str, + connected_port: u32, + _originator_address: &str, + _originator_port: u32, + reply: client::ChannelOpenHandle, + _session: &mut client::Session, + ) -> Result<(), Self::Error> { + // Only a port this client asked the server to forward is accepted. + match self.remote_forwards.iter().find(|f| u32::from(f.port) == connected_port) { + Some(f) => { + tokio::spawn(remote_forward(channel, reply, f.host.clone(), f.host_port)); + } + None => reply.reject(russh::ChannelOpenFailure::AdministrativelyProhibited).await, + } + Ok(()) + } } impl Client { @@ -600,6 +711,7 @@ where known_hosts: effective_known_hosts, host_key_policy: hop.host_key_policy, issue: issue.clone(), + remote_forwards: hop.forwards.iter().filter(|f| f.direction == ForwardDirection::Remote).cloned().collect(), }; let result = match stream { None => client::connect(config, (hop.host.as_str(), hop.port), handler).await, diff --git a/crates/ide-ssh/src/target.rs b/crates/ide-ssh/src/target.rs index baa40579e..0041afbc2 100644 --- a/crates/ide-ssh/src/target.rs +++ b/crates/ide-ssh/src/target.rs @@ -54,6 +54,63 @@ pub(crate) struct Hop { pub host_key_policy: HostKeyPolicy, pub known_hosts: Option<PathBuf>, pub agent: Agent, + /// `LocalForward` / `RemoteForward` of the config (the target's; jump hosts forward nothing). + pub forwards: Vec<PortForward>, +} + +/// A `LocalForward` or `RemoteForward` of `~/.ssh/config`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PortForward { + pub direction: ForwardDirection, + /// Address the listening side binds: empty for every address, `localhost` by default. + pub bind: String, + pub port: u16, + /// Where each connection goes, as the other side sees it. + pub host: String, + pub host_port: u16, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ForwardDirection { + /// `LocalForward`: this machine listens, connections go to `host:host_port` from the SSH host. + Local, + /// `RemoteForward`: the SSH host listens, connections go to `host:host_port` from this machine. + Remote, +} + +/// `[bind_address:]port host:hostport` (or the one-argument `-L` / `-R` form with colons); IPv6 +/// addresses in brackets. `None` for what isn't a TCP forward: a Unix socket, or `RemoteForward`'s +/// dynamic (SOCKS) form. +pub(crate) fn parse_forward(direction: ForwardDirection, value: &str) -> Option<PortForward> { + let spec = split_args(value).join(":"); + let mut parts: Vec<String> = Vec::new(); + let mut cur = String::new(); + let mut bracket = false; + for ch in spec.chars() { + match ch { + '[' if cur.is_empty() => bracket = true, + ']' if bracket => bracket = false, + ':' if !bracket => parts.push(std::mem::take(&mut cur)), + '/' => return None, + _ => cur.push(ch), + } + } + parts.push(cur); + let (bind, port, host, host_port) = match parts.as_slice() { + [port, host, host_port] => (None, port, host, host_port), + [bind, port, host, host_port] => (Some(bind.as_str()), port, host, host_port), + _ => return None, + }; + let bind = match bind { + None => "localhost".to_owned(), + Some("*") | Some("") => String::new(), + Some(b) => b.to_owned(), + }; + let (port, host_port) = (port.parse().ok()?, host_port.parse().ok()?); + if host.is_empty() || host_port == 0 { + return None; + } + Some(PortForward { direction, bind, port, host: host.clone(), host_port }) } /// Where the SSH agent of a hop listens (`IdentityAgent`). @@ -158,6 +215,8 @@ struct RawConfig { host_key_policy: Option<HostKeyPolicy>, user_known_hosts_file: Option<String>, identity_agent: Option<String>, + forwards: Vec<PortForward>, + clear_forwardings: bool, } fn strip_quotes(s: &str) -> &str { @@ -516,6 +575,23 @@ fn parse_config_file( out.user_known_hosts_file = Some(first); } } + "localforward" | "remoteforward" => { + let direction = if key.eq_ignore_ascii_case("localforward") { + ForwardDirection::Local + } else { + ForwardDirection::Remote + }; + match parse_forward(direction, value) { + Some(f) if !out.forwards.contains(&f) => out.forwards.push(f), + Some(_) => {} + None => tracing::debug!("ssh config: {key} {value} is not a TCP port forward; skipped"), + } + } + "clearallforwardings" => { + if matches!(strip_quotes(value).to_ascii_lowercase().as_str(), "yes" | "true") { + out.clear_forwardings = true; + } + } _ => {} } } @@ -559,7 +635,8 @@ fn config_hop( if null_known_hosts { HostKeyPolicy::Off } else { raw.host_key_policy.unwrap_or(HostKeyPolicy::Ask) }; let agent = identity_agent(raw.identity_agent.as_deref(), |p| expand(&expand_tokens(p, alias, &host, port, &user, &local))); - let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent }; + let forwards = if raw.clear_forwardings { Vec::new() } else { raw.forwards }; + let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent, forwards }; (hop, proxy_jump) } @@ -574,7 +651,7 @@ fn jump_hop(config: Option<&Path>, spec: &str) -> Hop { _ => (rest, None), }; let (hop, _) = config_hop(config, host, port, user); - hop + Hop { forwards: Vec::new(), ..hop } } /// The SSH hosts to go through, the target last. @@ -597,6 +674,7 @@ pub(crate) fn resolve_hops(target: &SshTarget, config: Option<&Path>) -> IdeResu host_key_policy: HostKeyPolicy::Ask, known_hosts: None, agent: Agent::Default, + forwards: Vec::new(), }, None, ) @@ -636,6 +714,40 @@ pub fn openssh_args(target: &SshTarget) -> Vec<String> { mod tests { use super::*; + #[test] + fn parses_port_forwards_like_openssh() { + let f = |d, v: &str| parse_forward(d, v).map(|f| (f.bind, f.port, f.host, f.host_port)); + let remote = ForwardDirection::Remote; + assert_eq!(f(remote, "9222 127.0.0.1:9222"), Some(("localhost".into(), 9222, "127.0.0.1".into(), 9222))); + assert_eq!(f(remote, "0.0.0.0:8080 web:80"), Some(("0.0.0.0".into(), 8080, "web".into(), 80))); + assert_eq!(f(remote, "*:8080 web:80"), Some((String::new(), 8080, "web".into(), 80))); + assert_eq!(f(remote, "[::1]:8080 [::1]:80"), Some(("::1".into(), 8080, "::1".into(), 80))); + assert_eq!(f(ForwardDirection::Local, "5432:db:5432"), Some(("localhost".into(), 5432, "db".into(), 5432))); + // Dynamic (SOCKS) and Unix socket forwards aren't TCP port forwards. + assert_eq!(f(remote, "1080"), None); + assert_eq!(f(remote, "/tmp/a.sock /tmp/b.sock"), None); + assert_eq!(f(remote, "8080 web:http"), None); + } + + #[test] + fn config_forwards_belong_to_the_target_and_clear_all_forwardings_drops_them() { + let dir = tempfile::tempdir().unwrap(); + let config = dir.path().join("config"); + std::fs::write( + &config, + "Host box\n RemoteForward 9222 127.0.0.1:9222\n LocalForward 5432 db:5432\n ProxyJump gate\n\ + Host gate\n LocalForward 1 a:1\nHost quiet\n RemoteForward 9222 127.0.0.1:9222\n ClearAllForwardings yes\n", + ) + .unwrap(); + let target = |host: &str| SshTarget { host: host.into(), auth: SshAuth::OpenSsh, ..Default::default() }; + let hops = resolve_hops(&target("box"), Some(&config)).unwrap(); + assert_eq!(hops.len(), 2); + assert!(hops[0].forwards.is_empty(), "jump hosts forward nothing"); + let dirs: Vec<_> = hops[1].forwards.iter().map(|f| (f.direction, f.port)).collect(); + assert_eq!(dirs, [(ForwardDirection::Remote, 9222), (ForwardDirection::Local, 5432)]); + assert!(resolve_hops(&target("quiet"), Some(&config)).unwrap()[0].forwards.is_empty()); + } + #[test] fn resolves_aliases_and_proxy_jumps_from_ssh_config() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-ssh/tests/session.rs b/crates/ide-ssh/tests/session.rs index 2e9e1a792..b68e963fe 100644 --- a/crates/ide-ssh/tests/session.rs +++ b/crates/ide-ssh/tests/session.rs @@ -98,6 +98,32 @@ impl server::Handler for Sshd { }); Ok(()) } + + /// `RemoteForward`: listens on 127.0.0.1:`port` and forwards each connection back to the client. + async fn tcpip_forward( + &mut self, + address: &str, + port: &mut u32, + session: &mut ServerSession, + ) -> Result<bool, Self::Error> { + let Ok(listener) = TcpListener::bind(("127.0.0.1", *port as u16)).await else { return Ok(false) }; + let (handle, address, port) = (session.handle(), address.to_owned(), *port); + tokio::spawn(async move { + while let Ok((mut socket, peer)) = listener.accept().await { + let Ok(channel) = handle + .channel_open_forwarded_tcpip(address.clone(), port, "127.0.0.1", u32::from(peer.port())) + .await + else { + continue; + }; + tokio::spawn(async move { + let mut stream = channel.into_stream(); + let _ = tokio::io::copy_bidirectional(&mut stream, &mut socket).await; + }); + } + }); + Ok(true) + } } /// Echo server standing in for a remote service. @@ -443,3 +469,50 @@ async fn accept_new_records_an_unknown_key_and_still_refuses_a_changed_one() { let msg = denied(env.connect(&target, None).await); assert!(msg.contains("has changed"), "{msg}"); } + +/// A free local port (bound and released). +fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() +} + +async fn echoes(port: u16) { + let mut s = TcpStream::connect(("127.0.0.1", port)).await.expect("forwarded port listens"); + s.write_all(b"ping").await.unwrap(); + let mut buf = [0u8; 4]; + s.read_exact(&mut buf).await.unwrap(); + assert_eq!(&buf, b"ping"); +} + +/// `RemoteForward` and `LocalForward` of `~/.ssh/config` are forwarded while the session lives (#6031). +#[tokio::test] +async fn config_port_forwards_follow_the_session() { + let mut env = env().await; + let (remote, local) = (free_port(), free_port()); + let config = env._tmp.path().join("ssh_config"); + std::fs::write( + &config, + format!( + "Host box\n\tHostName 127.0.0.1\n\tStrictHostKeyChecking=no\n\tUserKnownHostsFile=/dev/null\n\ + \tRemoteForward {remote} 127.0.0.1:{echo}\n\tLocalForward 127.0.0.1:{local} localhost:{echo}\n\ + \tRemoteForward /tmp/remote.sock /tmp/local.sock\n", + echo = env.echo_port + ), + ) + .unwrap(); + env.files.config = Some(config); + let target = SshTarget { + host: "box".into(), + port: Some(env.ssh_port), + user: "coder".into(), + auth: SshAuth::OpenSsh, + ..Default::default() + }; + let session = Arc::new(env.connect(&target, None).await.expect("connects")); + session.start_forwards().await; + // The SSH host's port reaches the echo server here; the local port reaches it from the SSH host. + echoes(remote).await; + echoes(local).await; + drop(session); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + assert!(TcpStream::connect(("127.0.0.1", local)).await.is_err(), "a closed session stops its LocalForward"); +} diff --git a/crates/ide-tools/src/formatter.rs b/crates/ide-tools/src/formatter.rs index b2c108c2c..bb016dd02 100644 --- a/crates/ide-tools/src/formatter.rs +++ b/crates/ide-tools/src/formatter.rs @@ -172,6 +172,10 @@ pub fn arguments( args.push("-".into()); return args; } + if tool == "dprint" { + // dprint finds its configuration from the working directory, the file's folder. + return vec!["fmt".into(), "--stdin".into(), file.as_os_str().to_owned()]; + } if tool == "biome" { // Biome finds its `biome.json` and ignore files from the file's path itself. let mut path = OsString::from("--stdin-file-path="); @@ -292,6 +296,30 @@ pub fn run_php_cs_fixer(mut command: Command, cancel: &CancellationToken) -> Ide .map_err(|e| IdeError::invalid(format!("PHP-CS-Fixer: {}", e.message.trim()))) } +/// `dprint editor-info`: the plugins of the configuration dprint finds. The first run downloads +/// them, hence the longer timeout. +pub fn dprint_editor_info(mut command: Command) -> IdeResult<String> { + command.arg("editor-info"); + crate::process::run_input(&mut command, "", Duration::from_secs(120), &Default::default()) + .map_err(|e| e.with_tool("dprint")) +} + +/// Whether a plugin listed by `dprint editor-info` formats `file`, by its extension or file name. +pub fn dprint_covers(editor_info: &str, file: &Path) -> IdeResult<bool> { + let info: serde_json::Value = serde_json::from_str(editor_info) + .map_err(|e| IdeError::invalid(format!("dprint: unexpected editor-info output: {e}")).with_tool("dprint"))?; + let Some(name) = file.file_name().and_then(|n| n.to_str()) else { return Ok(false) }; + let lower = name.to_lowercase(); + fn strings(v: &serde_json::Value) -> impl Iterator<Item = &str> { + v.as_array().into_iter().flatten().filter_map(|s| s.as_str()) + } + Ok(info["plugins"].as_array().into_iter().flatten().any(|plugin| { + strings(&plugin["fileNames"]).any(|n| n == name) + || strings(&plugin["fileExtensions"]) + .any(|ext| lower.strip_suffix(&ext.to_lowercase()).is_some_and(|rest| rest.ends_with('.'))) + })) +} + pub fn run(tool: &str, mut command: Command, text: &str, cancel: &CancellationToken) -> IdeResult<String> { crate::process::run_input(&mut command, text, Duration::from_secs(15), cancel).map_err(|e| e.with_tool(tool)) } @@ -457,6 +485,40 @@ mod tests { assert!(!supports_range("biome", &config)); } + #[test] + fn dprint_runs_the_nearest_package_on_stdin_for_what_its_plugins_cover() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + std::fs::create_dir_all(root.join("node_modules/dprint")).unwrap(); + std::fs::write(root.join("node_modules/dprint/package.json"), r#"{"bin":"bin.cjs"}"#).unwrap(); + std::fs::write(root.join("node_modules/dprint/bin.cjs"), "").unwrap(); + let file = root.join("packages/web/src/app.ts"); + let path = std::env::var_os("PATH").unwrap_or_default(); + let tools = Tools::with_paths(root.join("tools"), path, crate::platform::Platform::current()); + let command = tools.formatter_command("dprint", &file, None).unwrap(); + assert_eq!(Path::new(command.get_program()).file_stem().unwrap(), "node"); + + let config = FormatterConfig { tool: "prettier".into(), parser: "typescript".into(), range: true }; + let range = + Some(FormatRange { start_offset: 3, end_offset: 9, start_line: 1, start_col: 1, end_line: 1, end_col: 7 }); + assert_eq!( + arguments("dprint", &config, &file, 4, false, range, None), + ["fmt".into(), "--stdin".into(), file.clone().into_os_string()] + ); + assert!(!supports_range("dprint", &config)); + + let info = r#"{"schemaVersion":5,"plugins":[ + {"fileExtensions":["ts","tsx","d.mts"],"fileNames":[]}, + {"fileExtensions":["toml"],"fileNames":["Dockerfile"]}]}"#; + let covers = |name: &str| dprint_covers(info, &root.join(name)).unwrap(); + assert!(covers("src/app.ts") && covers("src/App.TSX") && covers("types/x.d.mts")); + assert!(covers("Cargo.toml") && covers("Dockerfile")); + assert!(!covers("README.md") && !covers("main.mts") && !covers("ts") && !covers("dockerfile")); + assert!(!dprint_covers(r#"{"plugins":[]}"#, &file).unwrap()); + let invalid = dprint_covers("No config file found", &file).unwrap_err(); + assert_eq!(invalid.data, Some(ide_core::error::ErrorData::Tool { tool: "dprint".into(), missing: false })); + } + #[test] fn ruff_formats_stdin_and_uses_its_config_and_range_flags() { let config = FormatterConfig { tool: "ruff".into(), parser: "python".into(), range: true }; diff --git a/crates/ide-tools/src/lib.rs b/crates/ide-tools/src/lib.rs index 4efe10d0d..a8204af06 100644 --- a/crates/ide-tools/src/lib.rs +++ b/crates/ide-tools/src/lib.rs @@ -1078,6 +1078,7 @@ impl Tools { }, &specs, pnpm, + !self.downloads.configured_registries_only, cancel, emit, ) @@ -1463,6 +1464,12 @@ impl Tools { sources::openvsx_pick(&json, assets, self.platform) } ReleaseSource::MavenCentral { group, artifact } => { + if self.downloads.configured_registries_only { + return Err(IdeError::unavailable(format!( + "{group}:{artifact} is downloaded from Maven Central, and Settings › Tools › Download Mirrors \ + allows only the configured package registries" + ))); + } let xml = http.get_text(&sources::maven_metadata_url(group, artifact), cancel)?; sources::maven_pick(group, artifact, &xml) } @@ -1690,7 +1697,7 @@ impl Tools { // on a slow registry takes several seconds per package, more when run side by side. let out = match view(&[]) { Some((true, out)) => Some(out), - Some((false, out)) if is_npm_registry_miss(&out) => { + Some((false, out)) if !self.downloads.configured_registries_only && is_npm_registry_miss(&out) => { let extra = npm_public_registry_args([packages[0]], pnpm); view(&extra).and_then(|(ok, retry)| ok.then_some(retry)) } diff --git a/crates/ide-tools/src/mirror.rs b/crates/ide-tools/src/mirror.rs index 2e75f03da..d1110ee56 100644 --- a/crates/ide-tools/src/mirror.rs +++ b/crates/ide-tools/src/mirror.rs @@ -112,7 +112,7 @@ mod tests { const ASSET: &str = "https://github.com/LuaLS/lua-language-server/releases/download/3.13.5/x.zip"; fn settings(mirror: &str) -> ToolDownloadSettings { - ToolDownloadSettings { github_mirror: mirror.into() } + ToolDownloadSettings { github_mirror: mirror.into(), ..Default::default() } } #[test] diff --git a/crates/ide-tools/src/process.rs b/crates/ide-tools/src/process.rs index 4f5c570b8..296fc6e73 100644 --- a/crates/ide-tools/src/process.rs +++ b/crates/ide-tools/src/process.rs @@ -110,13 +110,15 @@ pub fn run_streamed_picking( } /// Runs an `npm` / `pnpm` command against the user's configured registry first (preserving -/// corporate mirrors, proxies, and CAs), and retries once against [`PUBLIC_NPM_REGISTRY`] when -/// the configured registry misses the package/version or rejects auth. Preserves the primary -/// error if the public registry is unreachable. +/// corporate mirrors, proxies, and CAs), and with `public_fallback` retries once against +/// [`PUBLIC_NPM_REGISTRY`] when the configured registry misses the package/version or rejects +/// auth. Preserves the primary error if the public registry is unreachable. Without +/// `public_fallback` (Settings › Tools › Download Mirrors) the configured registry's error stands. pub fn run_npm_with_public_fallback( mut build: impl FnMut(&[String]) -> Command, specs: &[String], pnpm: bool, + public_fallback: bool, cancel: &CancellationToken, emit: Emit, ) -> IdeResult<String> { @@ -127,7 +129,7 @@ pub fn run_npm_with_public_fallback( return Ok(output); } let err = failed_command(&label, &output, &status); - if cancel.is_cancelled() || !is_npm_registry_miss(&output) { + if !public_fallback || cancel.is_cancelled() || !is_npm_registry_miss(&output) { return Err(err); } emit(InstallEvent::Line { diff --git a/crates/ide-tools/src/registry.rs b/crates/ide-tools/src/registry.rs index aa117f194..0119bbb06 100644 --- a/crates/ide-tools/src/registry.rs +++ b/crates/ide-tools/src/registry.rs @@ -192,6 +192,17 @@ pub static TOOLS: &[ToolSpec] = &[ needs: NODE, homepage: "https://oxc.rs/docs/guide/usage/formatter", }, + ToolSpec { + name: "dprint", + display: "dprint", + kind: Formatter, + commands: &["dprint"], + method: Method::Npm { packages: &["dprint"] }, + fallback: None, + version: ver("dprint"), + needs: NODE, + homepage: "https://dprint.dev", + }, ToolSpec { name: "oxlint", display: "oxlint", @@ -1355,7 +1366,7 @@ mod tests { known.insert((d.adapter.clone(), d.command.clone())); } } - // The host selects the formatter of each file (Prettier, oxfmt or Biome) and runs its own CLIs. + // The host selects the formatter of each file (Prettier, oxfmt, Biome or dprint) and runs its own CLIs. for t in TOOLS.iter().filter(|t| !matches!(t.kind, Plugin | Formatter | Cli)) { assert!( known.contains(&(t.name.to_string(), t.commands[0].to_string())), diff --git a/crates/ide-tools/src/tests.rs b/crates/ide-tools/src/tests.rs index 2f6bb4b42..f45461b73 100644 --- a/crates/ide-tools/src/tests.rs +++ b/crates/ide-tools/src/tests.rs @@ -603,6 +603,34 @@ esac"#, assert!(!err.message.contains("ECONNRESET"), "{}", err.message); } +/// Settings › Tools › Download Mirrors › Use only the configured package registries: a registry +/// that refuses a package (a firewall's 403) is the answer. +#[cfg(unix)] +#[test] +fn configured_registries_only_never_reach_public_registries() { + let env = Env::new(); + let log = env.root.parent().unwrap().join("npm-only.txt"); + env.script(&env.sys, "node", "exit 0"); + env.script( + &env.sys, + "npm", + &format!( + r#"echo "$@" >> '{log}' +echo "npm error code E403" >&2 +echo "npm error 403 Forbidden - GET https://nexus.example/yaml-language-server - quarantined" >&2 +exit 1"#, + log = log.display() + ), + ); + let only = ToolDownloadSettings { configured_registries_only: true, ..Default::default() }; + let tools = env.tools().with_downloads(only); + let err = tools.install("yaml-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err(); + assert!(err.message.contains("quarantined"), "{}", err.message); + let calls = fs::read_to_string(&log).unwrap(); + assert_eq!(calls.lines().count(), 1, "{calls}"); + assert!(!calls.contains("registry.npmjs.org"), "{calls}"); +} + /// Servers that load TypeScript as a library get one with its JS API: `@latest` /// is TypeScript 7 (native, no `ts.server`), which crashed vue-language-server (#25). /// Uninstalling one keeps the TypeScript another installed server still uses. @@ -1344,7 +1372,10 @@ esac"#, ), ); // The first mirror is down: the next one is tried before the official host. - let downloads = ToolDownloadSettings { github_mirror: "https://down.mirror.test/, https://mirror.test/".into() }; + let downloads = ToolDownloadSettings { + github_mirror: "https://down.mirror.test/, https://mirror.test/".into(), + ..Default::default() + }; let emit = |_: InstallEvent| {}; env.tools() .with_downloads(downloads) diff --git a/crates/ide-vcs/src/push_preview.rs b/crates/ide-vcs/src/push_preview.rs index 80f72daa3..19fe39868 100644 --- a/crates/ide-vcs/src/push_preview.rs +++ b/crates/ide-vcs/src/push_preview.rs @@ -288,6 +288,13 @@ pub(crate) fn outgoing_commits( ) -> Option<OutgoingCommits> { let name = source.shorten().to_str_lossy(); let remote = repo.find_remote(default_push_remote(repo, remotes, Some(&name))?).ok()?; + // As in IDEA, only a destination the branch is set up with: its upstream or a push refspec. + // The remote branch of the same name is only what Push proposes for a new branch. + if repo.branch_remote_ref_name(source, gix::remote::Direction::Fetch).is_none() + && configured_destination(repo, source, &name, remote.refspecs(gix::remote::Direction::Push)).is_none() + { + return None; + } let target = branch_push_target(repo, source, &remote).ok()?.selection; if target.special_ref { return None; diff --git a/crates/ide-vcs/src/repo.rs b/crates/ide-vcs/src/repo.rs index 323cadb2c..de5630568 100644 --- a/crates/ide-vcs/src/repo.rs +++ b/crates/ide-vcs/src/repo.rs @@ -162,6 +162,29 @@ impl Repo { blob_at(&repo, &indexed, rev) } + /// Raw bytes of the selected commit or index entry, bounded before loading its blob. + pub fn file_bytes_at_bounded(&self, path: &Path, rev: &str, max: usize) -> IdeResult<Option<Vec<u8>>> { + let _scope = self.execution_scope(); + let repo = self.gix()?; + let given = self.given_rel_path(path)?; + let indexed = self.index_spelling(given.clone()); + let Some((mode, id)) = revision_entry(&repo, &given, &indexed, rev)? else { return Ok(None) }; + if !mode.is_blob_or_symlink() { + return Ok(None); + } + if let Some(header) = repo.try_find_header(id).map_err(gx)? { + if header.size() > max as u64 { + return Err(IdeError::invalid(format!("{} is too large to preview", path.display()))); + } + return Ok(Some(repo.find_object(id).map_err(gx)?.detach().data)); + } + // A partial clone may only have the tree. Keep Git's on-demand fetch under + // the repository's execution policy and cap the bytes captured from it. + let args = ["cat-file", "blob", &id.to_string()]; + let out = crate::cli::run_bounded(self.root(), &args, &ide_core::CancellationToken::new(), max)?; + Ok(Some(out.stdout)) + } + pub fn diff_entry_at(&self, path: &Path, rev: &str) -> IdeResult<Option<DiffEntry>> { let _scope = self.execution_scope(); let repo = self.gix()?; @@ -183,14 +206,7 @@ impl Repo { .and_then(|child| child.head().ok()?.1); return Ok(Some(DiffEntry { mode: "160000".into(), gitlink })); } - let entry = if !rev.starts_with(':') && indexed != given { - match entry_at(&repo, &given, rev)? { - Some(entry) => Some(entry), - None => entry_at(&repo, &indexed, rev)?, - } - } else { - entry_at(&repo, &indexed, rev)? - }; + let entry = revision_entry(&repo, &given, &indexed, rev)?; Ok(entry.map(|(mode, id)| DiffEntry { mode: format!("{:o}", mode.value()), gitlink: mode.is_commit().then(|| id.to_string()), @@ -334,6 +350,22 @@ pub(crate) fn mode_at(repo: &gix::Repository, rel: &str, rev: &str) -> IdeResult Ok(entry_at(repo, rel, rev)?.map(|(mode, _)| format!("{:o}", mode.value()))) } +/// Prefer the spelling in the revision to a later case-only rename in the index. +fn revision_entry( + repo: &gix::Repository, + given: &str, + indexed: &str, + rev: &str, +) -> IdeResult<Option<(gix::objs::tree::EntryMode, gix::ObjectId)>> { + if !rev.starts_with(':') + && indexed != given + && let Some(entry) = entry_at(repo, given, rev)? + { + return Ok(Some(entry)); + } + entry_at(repo, indexed, rev) +} + fn entry_at( repo: &gix::Repository, rel: &str, diff --git a/crates/ide-vcs/tests/git_workflows.rs b/crates/ide-vcs/tests/git_workflows.rs index 152250a24..8ad9717cc 100644 --- a/crates/ide-vcs/tests/git_workflows.rs +++ b/crates/ide-vcs/tests/git_workflows.rs @@ -1808,6 +1808,37 @@ fn outgoing_commits_follow_the_push_target_and_its_fetch_refspec() { assert!(repo.inspect_push(&selection, false, &cancel).unwrap().remote_tip.is_none()); } +#[test] +fn outgoing_commits_need_an_upstream_or_a_push_refspec() { + // A new branch reuses the name of an old one still on the server. + let (fx, _) = Fixture::with_origin(); + fx.git(&["switch", "-q", "-c", "topic"]); + fx.write("b.txt", "old topic\n"); + fx.commit_all("Old topic"); + fx.git(&["push", "-q", "origin", "topic"]); + fx.git(&["switch", "-q", "main"]); + fx.git(&["branch", "-q", "-D", "topic"]); + fx.write("c.txt", "main\n"); + fx.commit_all("Main moves on"); + fx.git(&["push", "-q", "origin", "main"]); + fx.git(&["switch", "-q", "--no-track", "-c", "topic", "origin/main"]); + let repo = fx.repo(); + + let info = repo.branch_info().unwrap(); + assert!(info.upstream.is_none()); + assert!(info.outgoing.is_none()); + assert!(repo.branches().unwrap().iter().find(|b| b.current).unwrap().outgoing.is_none()); + // Push still proposes the remote branch of the same name. + let selection = repo.default_push_target(None).unwrap().unwrap().selection; + assert_eq!((&*selection.remote, &*selection.target), ("origin", "topic")); + + fx.git(&["config", "remote.origin.push", "refs/heads/topic:refs/heads/topic"]); + assert_eq!(repo.branch_info().unwrap().outgoing.map(|o| o.count), Some(1)); + fx.git(&["config", "--unset", "remote.origin.push"]); + fx.git(&["branch", "-q", "--set-upstream-to=origin/topic"]); + assert_eq!(repo.branch_info().unwrap().outgoing.map(|o| o.count), Some(1)); +} + #[test] fn push_up_to_commit_prefers_a_containing_local_branch_and_only_publishes_the_selection() { let (fx, bare) = Fixture::with_origin(); diff --git a/crates/ide-vcs/tests/repo.rs b/crates/ide-vcs/tests/repo.rs index aa95049fe..dfc92356b 100644 --- a/crates/ide-vcs/tests/repo.rs +++ b/crates/ide-vcs/tests/repo.rs @@ -963,6 +963,21 @@ fn file_at_revisions_and_index() { assert_eq!(repo.file_at(&p, Some("no-such-rev"), encoding_rs::UTF_8).unwrap_err().kind, ErrorKind::NotFound); } +#[test] +fn bounded_revision_bytes_check_the_selected_blob_size() { + let fx = Fixture::new(); + let path = fx.path("image.png"); + std::fs::write(&path, [0xff, 0x00, 0xfe]).unwrap(); + fx.commit_all("image"); + std::fs::write(&path, [0x80]).unwrap(); + fx.git(&["add", "image.png"]); + let repo = fx.repo(); + assert_eq!(repo.file_bytes_at_bounded(&path, "HEAD", 3).unwrap().unwrap(), [0xff, 0x00, 0xfe]); + assert_eq!(repo.file_bytes_at_bounded(&path, ":0", 1).unwrap().unwrap(), [0x80]); + assert_eq!(repo.file_bytes_at_bounded(&path, "HEAD", 2).unwrap_err().kind, ErrorKind::InvalidInput); + assert_eq!(repo.file_bytes_at_bounded(&fx.path("absent.png"), "HEAD", 0).unwrap(), None); +} + #[test] fn file_at_in_a_blobless_clone() { let fx = Fixture::new(); diff --git a/crates/ide-vfs/src/lib.rs b/crates/ide-vfs/src/lib.rs index b0c597693..5ced5289c 100644 --- a/crates/ide-vfs/src/lib.rs +++ b/crates/ide-vfs/src/lib.rs @@ -24,8 +24,8 @@ pub use archive::{ read_archive_entry, split_archive_path, }; pub use bytes::{ - ByteRange, FileProbe, MAX_RANGE_LEN, base64, content_path_allowed, image_mime, on_local_drive, probe, - read_data_url, read_range, same_share, + ByteRange, FileProbe, MAX_IMAGE_SIZE, MAX_RANGE_LEN, base64, content_path_allowed, image_mime, on_local_drive, + probe, read_data_url, read_range, same_share, }; pub use compare::{ DirectoryCompareEntry, DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, DirectorySyncAction, diff --git a/crates/ide-workspace/Cargo.toml b/crates/ide-workspace/Cargo.toml index 1a1b5d029..f3e8d275e 100644 --- a/crates/ide-workspace/Cargo.toml +++ b/crates/ide-workspace/Cargo.toml @@ -25,5 +25,8 @@ uuid.workspace = true zip.workspace = true encoding_rs.workspace = true +[target.'cfg(windows)'.dependencies] +winreg = "0.56" + [dev-dependencies] tempfile.workspace = true diff --git a/crates/ide-workspace/src/documents.rs b/crates/ide-workspace/src/documents.rs index 8525c771d..35c6f6c28 100644 --- a/crates/ide-workspace/src/documents.rs +++ b/crates/ide-workspace/src/documents.rs @@ -191,6 +191,35 @@ impl DocState { self.disk_conflict = false; self.clean_text = (!self.large).then(|| self.doc.clone()); } + + /// The bytes saving `doc` with this document's encoding, BOM and conversion would write. + fn bytes_for_save(&self, doc: &Document) -> IdeResult<Vec<u8>> { + let text = doc.text_for_save(); + Ok(if self.native_to_ascii { + ide_vfs::encode_properties_ascii(&text).into_bytes() + } else { + ide_vfs::encode(&text, &self.encoding, self.has_bom)? + }) + } + + /// Whether the file changed on disk since the buffer last matched it. A moved stamp with the + /// same bytes (touch, a tool rewriting the file unchanged) is no change and its stamp is adopted. Reads the file + /// only when the mtime moved but the length did not; without a clean text to compare (large + /// files, a pending encoding, line-ending or BOM change, a reported conflict) a moved stamp counts. + fn changed_on_disk(&mut self, meta: &std::fs::Metadata) -> bool { + let mtime = ide_vfs::mtime_ms(meta); + if mtime == self.disk_mtime && meta.len() == self.disk_len { + return false; + } + let same_bytes = meta.len() == self.disk_len + && self.clean_text.as_ref().is_some_and(|clean| { + self.bytes_for_save(clean).is_ok_and(|bytes| std::fs::read(&self.path).is_ok_and(|disk| disk == bytes)) + }); + if same_bytes { + self.disk_mtime = mtime; + } + !same_bytes + } } fn keys_for(path: &Path) -> Vec<PathBuf> { @@ -924,7 +953,7 @@ impl Documents { && !st.disk_conflict && st.uri.is_none() && let Ok(meta) = std::fs::metadata(&st.path) - && (ide_vfs::mtime_ms(&meta) != st.disk_mtime || meta.len() != st.disk_len) + && st.changed_on_disk(&meta) { st.disk_mtime = ide_vfs::mtime_ms(&meta); st.disk_len = meta.len(); @@ -1411,6 +1440,9 @@ impl Documents { return Ok(()); } if st.dirty { + if !st.changed_on_disk(&meta) { + return Ok(()); + } st.disk_mtime = mtime; st.disk_len = meta.len(); st.disk_conflict = true; diff --git a/crates/ide-workspace/src/documents/workspace_edit.rs b/crates/ide-workspace/src/documents/workspace_edit.rs index f01a6adaa..c6eb1a532 100644 --- a/crates/ide-workspace/src/documents/workspace_edit.rs +++ b/crates/ide-workspace/src/documents/workspace_edit.rs @@ -314,12 +314,7 @@ fn hash_disk(hash: &mut blake3::Hasher, path: &Path, unsaved: &HashMap<PathBuf, /// The bytes saving `state` would write. fn saved_bytes(state: &DocState) -> IdeResult<Vec<u8>> { - let text = state.doc.text_for_save(); - Ok(if state.native_to_ascii { - ide_vfs::encode_properties_ascii(&text).into_bytes() - } else { - ide_vfs::encode(&text, &state.encoding, state.has_bom)? - }) + state.bytes_for_save(&state.doc) } /// A reverted edit may leave the dirty flag set even when all saved bytes match. diff --git a/crates/ide-workspace/src/editorconfig.rs b/crates/ide-workspace/src/editorconfig.rs index 18ff511ee..ffb2dc483 100644 --- a/crates/ide-workspace/src/editorconfig.rs +++ b/crates/ide-workspace/src/editorconfig.rs @@ -260,6 +260,13 @@ impl EditorConfig { /// Effective properties for `file` (absolute); `None` when no section applies. pub fn resolve(&self, file: &Path) -> Option<EditorConfigProps> { + let props = props_from(&self.resolve_pairs(file)?); + (!props.is_empty()).then_some(props) + } + + /// Every `key = value` that applies to `file` (keys lower-cased), domain-specific ones + /// (`quote_type`, `ij_*`) included; `None` when no section applies. + pub fn resolve_pairs(&self, file: &Path) -> Option<HashMap<String, String>> { let mut chain: Vec<(PathBuf, Arc<ParsedFile>)> = Vec::new(); for dir in file.ancestors().skip(1) { if let Some(parsed) = self.load(&dir.join(FILE_NAME)) { @@ -286,11 +293,7 @@ impl EditorConfig { } } } - if !matched { - return None; - } - let props = props_from(&map); - (!props.is_empty()).then_some(props) + matched.then_some(map) } } diff --git a/crates/ide-workspace/src/lib.rs b/crates/ide-workspace/src/lib.rs index 9791bb478..b39a3a922 100644 --- a/crates/ide-workspace/src/lib.rs +++ b/crates/ide-workspace/src/lib.rs @@ -18,6 +18,7 @@ pub mod roots; pub mod settings; pub mod text_refs; pub mod unity; +pub mod unreal; pub mod window_groups; pub mod workspace; diff --git a/crates/ide-workspace/src/unreal.rs b/crates/ide-workspace/src/unreal.rs new file mode 100644 index 000000000..5032e4806 --- /dev/null +++ b/crates/ide-workspace/src/unreal.rs @@ -0,0 +1,88 @@ +//! Unreal Engine project identity, read from the `.uproject` at the root. +//! +//! Only the root and the engine tree are looked at: everything else in a UE project is +//! content, generated output, or engine code, and must never be walked. + +pub mod engine; + +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::path::{Path, PathBuf}; + +/// Generated directory beside the project root; excluded from the index, the search and the tree. +pub const GENERATED_DIRS: &[&str] = &["Binaries", "Intermediate", "Saved", "DerivedDataCache"]; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct UnrealProjectInfo { + /// The engine the project builds against. `None` means none could be located, which is the + /// only reason such a project offers no run configuration at all. + pub engine: Option<UnrealEngine>, +} + +/// A located engine, shown so a project without run configurations says why. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct UnrealEngine { + /// `5.8` for a launcher install, or the registry key a source build registered under. + pub id: String, + /// Absolute engine root. + pub root: String, +} + +/// The `.uproject` directly inside `root`, picked by name order when a folder has several. +pub fn project_file(root: &Path) -> Option<PathBuf> { + let mut found: Vec<PathBuf> = std::fs::read_dir(root) + .ok()? + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_file())) + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("uproject"))) + .collect(); + found.sort(); + found.into_iter().next() +} + +pub fn is_project(root: &Path) -> bool { + project_file(root).is_some() +} + +pub fn detect(root: &Path) -> Option<UnrealProjectInfo> { + let file = project_file(root)?; + let association = std::fs::read_to_string(&file) + .ok() + .and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok()) + .and_then(|json| json.get("EngineAssociation")?.as_str().map(|v| v.trim().to_owned())) + .filter(|v| !v.is_empty()); + let engine = engine::locate(association.as_deref()) + .map(|found| UnrealEngine { id: found.id, root: found.root.to_string_lossy().into_owned() }); + Some(UnrealProjectInfo { engine }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + #[test] + fn a_directory_holding_a_uproject_is_a_project() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + write(&root.join("Arts.uproject"), r#"{"FileVersion":3,"EngineAssociation":"5.8","Plugins":[]}"#); + std::fs::create_dir_all(root.join("Content")).unwrap(); + assert!(is_project(root)); + assert!(detect(root).is_some()); + } + + #[test] + fn a_directory_without_a_uproject_is_not_a_project() { + let temp = tempfile::tempdir().unwrap(); + write(&temp.path().join("Source/Game.Target.cs"), ""); + assert!(!is_project(temp.path())); + assert!(detect(temp.path()).is_none()); + } +} diff --git a/crates/ide-workspace/src/unreal/engine.rs b/crates/ide-workspace/src/unreal/engine.rs new file mode 100644 index 000000000..6355c80f8 --- /dev/null +++ b/crates/ide-workspace/src/unreal/engine.rs @@ -0,0 +1,92 @@ +//! Locating an installed Unreal Engine. +//! +//! A launcher install registers its directory per version under `HKLM` and a source build under +//! `HKCU`, keyed by whatever the `.uproject`'s `EngineAssociation` names. + +use std::path::PathBuf; + +/// A registered engine, keyed by whatever the machine calls it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EngineInstall { + /// `5.8` for a launcher install, a GUID-like key for a source build. + pub id: String, + pub root: PathBuf, +} + +impl EngineInstall { + /// The editor executable, which runs every start-up mode. + pub fn editor(&self) -> PathBuf { + self.root.join("Engine").join("Binaries").join("Win64").join("UnrealEditor.exe") + } +} + +/// The engine `association` names, following Unreal's own lookup: the association is the key a +/// registered directory is stored under, so an unknown or empty one locates nothing. +pub fn locate(association: Option<&str>) -> Option<EngineInstall> { + pick(installed(), association) +} + +fn pick(installs: Vec<EngineInstall>, association: Option<&str>) -> Option<EngineInstall> { + let id = association?; + // A registered directory that is gone is a leftover from an uninstalled engine. + installs.into_iter().find(|i| i.id.eq_ignore_ascii_case(id) && i.root.is_dir()) +} + +#[cfg(windows)] +fn installed() -> Vec<EngineInstall> { + use winreg::RegKey; + use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE}; + + let mut out = Vec::new(); + if let Ok(key) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(r"SOFTWARE\EpicGames\Unreal Engine") { + for id in key.enum_keys().flatten() { + let Ok(sub) = key.open_subkey(&id) else { continue }; + let Ok(dir) = sub.get_value::<String, _>("InstalledDirectory") else { continue }; + if !dir.trim().is_empty() { + out.push(EngineInstall { id, root: PathBuf::from(dir) }); + } + } + } + if let Ok(key) = RegKey::predef(HKEY_CURRENT_USER).open_subkey(r"SOFTWARE\Epic Games\Unreal Engine\Builds") { + for (id, _) in key.enum_values().flatten() { + let Ok(dir) = key.get_value::<String, _>(&id) else { continue }; + if !dir.trim().is_empty() { + out.push(EngineInstall { id, root: PathBuf::from(dir) }); + } + } + } + out +} + +#[cfg(not(windows))] +fn installed() -> Vec<EngineInstall> { + Vec::new() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A fake install whose directory exists, so `pick` treats it as usable. + fn install(dir: &std::path::Path, id: &str) -> EngineInstall { + let root = dir.join(format!("UE_{id}")); + std::fs::create_dir_all(root.join("Engine/Binaries/Win64")).unwrap(); + EngineInstall { id: id.to_owned(), root } + } + + #[test] + fn the_association_picks_that_install_and_nothing_else() { + let temp = tempfile::tempdir().unwrap(); + let installs = vec![install(temp.path(), "5.8"), install(temp.path(), "5.3")]; + assert_eq!(pick(installs.clone(), Some("5.3")).unwrap().id, "5.3"); + assert_eq!(pick(installs, Some("4.27")), None); + assert_eq!(pick(Vec::new(), None), None); + } + + #[test] + fn a_registered_engine_that_was_deleted_is_not_picked() { + let temp = tempfile::tempdir().unwrap(); + let ghost = EngineInstall { id: "5.8".to_owned(), root: temp.path().join("gone") }; + assert_eq!(pick(vec![ghost], Some("5.8")), None); + } +} diff --git a/crates/ide-workspace/tests/documents.rs b/crates/ide-workspace/tests/documents.rs index 8e5c834a8..e13ba0cbf 100644 --- a/crates/ide-workspace/tests/documents.rs +++ b/crates/ide-workspace/tests/documents.rs @@ -350,6 +350,61 @@ fn autosave_checks_the_disk_before_the_watcher_reports_a_change() { ); } +/// Writes `bytes` with an mtime clearly after the current one, whatever the filesystem's granularity. +fn rewrite_later(path: &Path, bytes: &[u8]) { + let mtime = fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(2); + fs::write(path, bytes).unwrap(); + fs::File::options().write(true).open(path).unwrap().set_modified(mtime).unwrap(); +} + +#[test] +fn rewriting_the_same_bytes_is_no_disk_conflict() { + let f = fixture(); + let path = f.root.join("notes.txt"); + fs::write(&path, "alpha\nbeta\n").unwrap(); + let info = f.docs.open(&path).unwrap(); + f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap(); + // A touch, or a tool rewriting the file unchanged: only the mtime moves. + rewrite_later(&path, b"alpha\nbeta\n"); + f.docs.on_disk_changed(std::slice::from_ref(&path)); + assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change"); + assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n"); + assert!(!f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocDiskConflict { .. }))); +} + +#[test] +fn autosave_ignores_a_rewrite_of_the_same_bytes_before_the_watcher_reports_it() { + let f = fixture(); + let path = f.root.join("notes.txt"); + fs::write(&path, "alpha\nbeta\n").unwrap(); + let info = f.docs.open(&path).unwrap(); + f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap(); + rewrite_later(&path, b"alpha\nbeta\n"); + assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change"); + assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n"); +} + +/// Opens `bytes`, edits the buffer, then rewrites the file as `external` (same text, other bytes). +fn assert_other_bytes_conflict(name: &str, bytes: &[u8], external: &[u8]) { + let f = fixture(); + let path = f.root.join(name); + fs::write(&path, bytes).unwrap(); + let info = f.docs.open(&path).unwrap(); + f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap(); + rewrite_later(&path, external); + f.docs.on_disk_changed(std::slice::from_ref(&path)); + assert!(!f.docs.autosave(info.id).unwrap(), "{name}: autosave overwrote other bytes of the same text"); + assert_eq!(fs::read(&path).unwrap(), external); +} + +#[test] +fn the_same_text_in_other_bytes_is_still_a_disk_conflict() { + assert_other_bytes_conflict("crlf.txt", b"alpha\nbeta\n", b"alpha\r\nbeta\r\n"); + assert_other_bytes_conflict("bom.txt", b"alpha\n", b"\xEF\xBB\xBFalpha\n"); + // Same length: only the byte comparison tells them apart. + assert_other_bytes_conflict("utf16.txt", b"\xFF\xFEa\x00\n\x00", b"\xFE\xFF\x00a\x00\n"); +} + #[test] fn autosave_leaves_a_file_changed_on_disk_after_an_edit() { let f = fixture(); diff --git a/crates/ide-workspace/tests/workspace_edits.rs b/crates/ide-workspace/tests/workspace_edits.rs index af69190c3..0ec927192 100644 --- a/crates/ide-workspace/tests/workspace_edits.rs +++ b/crates/ide-workspace/tests/workspace_edits.rs @@ -138,17 +138,18 @@ fn rollback_keeps_a_disk_conflict_of_an_unsaved_buffer() { let info = docs.open(&first).unwrap(); docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] }) .unwrap(); - docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap(); - // An external write the undo record still accepts (same bytes, new mtime) under the unsaved buffer. - std::thread::sleep(std::time::Duration::from_millis(10)); - std::fs::write(&first, "old\n").unwrap(); + // An external write under the unsaved buffer, warned about before the refactoring. + let mtime = std::fs::metadata(&first).unwrap().modified().unwrap() + std::time::Duration::from_secs(2); + std::fs::write(&first, "ext\n").unwrap(); + std::fs::File::options().write(true).open(&first).unwrap().set_modified(mtime).unwrap(); docs.on_disk_changed(std::slice::from_ref(&first)); + docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap(); docs.undo_workspace_edit(undo_id(&events)).unwrap(); let snap = docs.snapshot(info.id).unwrap(); assert_eq!(snap.text, "own\n"); assert!(snap.dirty); assert!(!docs.autosave(info.id).unwrap(), "autosave must not overwrite the external change"); - assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n"); + assert_eq!(std::fs::read_to_string(&first).unwrap(), "ext\n"); } #[test] diff --git a/docs/en/guide/agents.mdx b/docs/en/guide/agents.mdx index f01ea3550..100904df3 100644 --- a/docs/en/guide/agents.mdx +++ b/docs/en/guide/agents.mdx @@ -130,6 +130,8 @@ Tasks are saved per project and survive restarts. When the agent supports resumi - **Built-in**: for each built-in agent, whether its executable was found on `PATH`, a field to point at a **Custom executable**, **Environment variables** for the agent process (written as `NAME=value; OTHER=value`; the values are kept in the OS credential store) and how to sign in. Changes apply to new sessions. When the agent is a global npm install (such as Claude Code, Codex or Gemini CLI), **Check for updates** compares it with npm's latest stable release and **Update to…** updates that installation. - **ACP Registry**: agents published in the [ACP Registry](https://agentclientprotocol.com). Search, **Install**, **Update** and **Remove**. Installed agents are kept in OpenIDEA's data directory; downloads are checked against the registry's SHA-256 when it provides one. +For a built-in ACP agent launched directly, such as OMP, **Launch › Additional arguments** appends arguments to its existing launch command. Separate arguments with spaces and quote values that contain spaces. **Apply** saves the arguments for the next process launch; the command preview shows the saved result. **Reset additional arguments** clears just this field, leaving the executable, environment and any hand-written `args` in the agent file alone. + **Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**. ### External MCP servers diff --git a/docs/en/guide/database.mdx b/docs/en/guide/database.mdx index 4e9cb9c17..c8978cfeb 100644 --- a/docs/en/guide/database.mdx +++ b/docs/en/guide/database.mdx @@ -20,12 +20,19 @@ Open it from **Tools › Database** or **View › Tool Windows › Database**. T | ClickHouse | ClickHouse (over HTTP) | | Snowflake | Snowflake (over HTTPS, see below) | | SQLite | SQLite | +| DuckDB | DuckDB (official JDBC driver) | Presets set the default port and, where needed, SSL (for example Redshift, Neon and Supabase require SSL). +## DuckDB + +Choose **New › Data Source › DuckDB**. In **Manage Drivers…**, add the [official DuckDB JDBC JAR](https://duckdb.org/docs/stable/clients/java) and save the profile. OpenIDEA fills in the driver class and URL template. A Java 17 or newer runtime is required. + +Choose **File** to open an existing database or create a new file, **In memory** for a temporary database that lasts until disconnect, or **JDBC URL** to enter a DuckDB URL directly. To inspect an existing file without changing it, enable **Read-only** in **Options**. The official driver applies this setting when it opens the file. + ## JDBC drivers -In a named data source's **General** tab, **Driver** defaults to **Built-in**. Use **Manage Drivers…** to view or add JDBC profiles for that data source type. Select the profile from **Driver** to use JDBC while keeping the source type and icon. **Go to Driver** opens the selected profile and its JAR list. Choose **New › Data Source › Custom JDBC** for databases without a preset, or open its **Manage Drivers…** to see all profiles and change their associated types. +For presets with a built-in driver, **Driver** defaults to **Built-in** in the **General** tab. Use **Manage Drivers…** to view or add JDBC profiles for that data source type. Select the profile from **Driver** to use JDBC while keeping the source type and icon. **Go to Driver** opens the selected profile and its JAR list. Choose **New › Data Source › Custom JDBC** for databases without a preset, or open its **Manage Drivers…** to see all profiles and change their associated types. Add a named profile with the vendor's driver JAR, any dependency JARs, the fully qualified driver class, and an optional JDBC URL template. OpenIDEA reads the driver classes declared in the selected JARs. You can choose a different class or enter its full name manually. Use `{host}`, `{port}`, `{database}` or `{file}` in a template to get matching connection fields, or edit the JDBC URL directly. Only import drivers you trust. OpenIDEA loads their code in a separate process using an installed Java 17 or newer runtime. @@ -42,7 +49,7 @@ Profiles are reused across projects. If a project file changes a connection's UR Click **+** in the Database tool window (or press `⌘N` / `Alt+Insert` there) and choose: - **Data Source ›** a preset from the list above. -- **Data Source from File…** to open a SQLite file. +- **Data Source from File…** to open a DuckDB (`.duckdb`) or SQLite file. - **Data Source from URL…** to paste a URL such as `postgresql://user@localhost:5432/db`. Schemes like `mysql://`, `mariadb://`, `sqlserver://`, `oracle://`, `clickhouse://`, `sqlite:path` and `jdbc:` URLs are accepted. - **Import from Clipboard** to read a connection URL from the clipboard. diff --git a/docs/en/guide/editor.mdx b/docs/en/guide/editor.mdx index 3f800ae0e..0b9cb8be5 100644 --- a/docs/en/guide/editor.mdx +++ b/docs/en/guide/editor.mdx @@ -55,6 +55,8 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below **Move Caret Forward a Paragraph** / **Backward a Paragraph** jump each caret over a run of non-blank lines to the blank line after or before it (a line of only spaces or tabs counts as blank), or to the end or start of the file; their **with Selection** variants select up to there. They have no default shortcut. +**Move Caret to Next Word** / **Previous Word in Different "CamelHumps" Mode** (and their **with Selection** variants), **Delete to Word Start** and **Delete to Word End in Different "CamelHumps" Mode** move or delete by word the other way from **Settings › Editor › General › Smart Keys › Use "CamelHumps" words**: by hump (`parse|HTML|Document`) while it is off, by whole word while it is on. They have no default shortcut. + **Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones. **Cut up to Line End** cuts from each caret to the end of its line, together with the line break when only whitespace is left (or the caret is already at the line end), so pressing it again on the same caret cuts the next line too; those repeated cuts collect into one clipboard entry. **Delete to Line Start** and **Delete to Line End** delete the same way without copying (to the line start, or the line break before the caret at the line start), or delete the selection. They have no default shortcut except in the Eclipse keymaps (`⇧⌘⌦` / `Ctrl+Shift+Delete` for Delete to Line End). @@ -108,10 +110,12 @@ All folding commands are also in **Code › Folding**. Fold regions come from th | **Auto-Indent Lines** | `⌃⌥I` | `Ctrl+Alt+I` | | **Optimize Imports** | `⌃⌥O` | `Ctrl+Alt+O` | -**Reformat Code** formats the selection, or the whole file when nothing is selected, as one undo step. The formatting comes from the file's language server or from the formatter the language is configured with (for example Ruff for Python, Prettier, oxfmt or Biome for web languages; find their commands as **Reformat with …** in Find Action). **Reformat File…** also lets you choose the scope and optimize imports. +**Reformat Code** formats the selection, or the whole file when nothing is selected, as one undo step. The formatting comes from the file's language server or from the formatter the language is configured with (for example Ruff for Python, Prettier, oxfmt or Biome for web languages, dprint in dprint projects; find their commands as **Reformat with …** in Find Action). **Reformat File…** also lets you choose the scope and optimize imports. Indentation and other style options are under **Settings › Editor › Code Style**, with a page per language. `.editorconfig` files in the project are read too. +Java has an **Imports** tab for IntelliSort-style options: **Class count to use import with '\*'** switches to a wildcard import once that many classes of one package are used, and **Names count to use static import with '\*'** does the same for statically imported names (999 keeps single imports). Both are passed through to the Java language server, whose defaults are 5 and 3, as in IDEA. + To format on every save, enable **Reformat code** (and optionally **Optimize imports**) in **Settings › Tools › Actions on Save**. Trailing spaces and the final line break on save are set in **Settings › Editor › General**, section **Save Files**. ## Tabs @@ -143,21 +147,24 @@ With tabs placed left or right, the tab column is as wide as its longest name, u ## View options -| Action | macOS | Windows / Linux | -| ---------------------- | ----- | --------------- | -| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` | -| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` | -| **Scroll to Center** | `⌃L` | `Ctrl+M` | -| **Scroll Up** | — | `Ctrl+Up` | -| **Scroll Down** | — | `Ctrl+Down` | -| **Scroll to Top** | — | — | -| **Scroll to Bottom** | — | — | +| Action | macOS | Windows / Linux | +| ------------------------------------- | ----- | --------------- | +| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` | +| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` | +| **Scroll to Center** | `⌃L` | `Ctrl+M` | +| **Scroll Up** | — | `Ctrl+Up` | +| **Scroll Down** | — | `Ctrl+Down` | +| **Scroll Up and Move if Necessary** | — | — | +| **Scroll Down and Move if Necessary** | — | — | +| **Scroll to Top** | — | — | +| **Scroll to Bottom** | — | — | -**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**. +**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll Up and Move if Necessary** and **Scroll Down and Move if Necessary** also move the view by one line, but bring a caret the view doesn't show to its first or last line. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**. - **View › Active Editor › Soft-Wrap** wraps long lines in the current editor. To wrap some file types by default, use **Settings › Editor › General**, section **Soft Wraps**. - **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**. - **View › Appearance › Enter Distraction Free Mode** hides tool windows, tabs, the status bar and the gutter and centres the text. Run the same command again to leave. +- **View › Appearance › Enter Zen Mode** turns on Distraction Free Mode and full screen together; **Exit Zen Mode** turns both off. - **Show Line Numbers**, **Show Indent Guides**, **Show Sticky Lines** and **Show Whitespaces** turn these on or off in every editor. Run them from Find Action, or right-click the gutter and open **Appearance**. - Line numbers, whitespace, indent guides, caret style and the intention bulb are in **Settings › Editor › General › Appearance**. Breadcrumbs and sticky lines (the enclosing declarations pinned at the top while you scroll) have their own pages under **Settings › Editor › General**. diff --git a/docs/en/guide/refactoring.mdx b/docs/en/guide/refactoring.mdx index 37394e2b3..0e7e377cc 100644 --- a/docs/en/guide/refactoring.mdx +++ b/docs/en/guide/refactoring.mdx @@ -24,7 +24,8 @@ The **Refactor** menu has IntelliJ IDEA's refactorings with their usual shortcut | **Introduce Field…** | `⌥⌘F` | `Ctrl+Alt+F` | Language server | | **Introduce Parameter…** | `⌥⌘P` | `Ctrl+Alt+P` | Language server | | **Extract Method…** | `⌥⌘M` | `Ctrl+Alt+M` | Language server | -| **Extract Interface…** | — | — | Java | +| **Extract Interface…** | — | — | Java (dialog); TypeScript: language server | +| **Extract Type Alias…** | — | — | TypeScript, JavaScript (`@typedef`): language server | | **Inline…** | `⌥⌘N` | `Ctrl+Alt+N` | Language server | | **Move…** | `F6` | `F6` | Language server (symbols); the IDE (files and folders) | | **Safe Delete…** | `⌘⌦` | `Alt+Delete` | The IDE, using the server's references | @@ -87,6 +88,8 @@ These move fields and methods between a class and its superclasses or subclasses In Java, **Refactor › Extract Interface…** creates an interface from the class of the current file. In the dialog, enter the interface name, choose its package and check the methods (and constants) it should declare. **Refactor** creates the interface, makes the class implement it, replaces the class with the interface wherever that is possible, and opens the new file; **Preview** lists the changes first. +In TypeScript, select an object type literal (for example `{ name: string; age: number }`) and choose **Refactor › Extract Interface…**: the language server declares an `interface` for it and uses it in its place. **Refactor › Extract Type Alias…** does the same with a `type` declaration for any selected type, and in JavaScript adds a JSDoc `@typedef`. Afterwards the new name is renamed in place, as after **Introduce Variable…**. When the server has nothing to extract at the selection, the editor says so. + ## Change Signature In Java, **Change Signature…** (`⌘F6`) on a method opens a dialog to change its visibility, return type and name, and to add, remove and reorder its parameters. A new parameter needs a default value, which is passed at every existing call; **Delegate via overloading method** keeps the old signature as an overload that calls the new one. The preview line shows the resulting declaration. **Refactor** updates the method, its overrides and all calls in one step; **Preview** lists the changes first. In other languages it appears when the server offers a signature rewrite as a code action. diff --git a/docs/en/guide/run.mdx b/docs/en/guide/run.mdx index 7038e4b17..a5d9398b8 100644 --- a/docs/en/guide/run.mdx +++ b/docs/en/guide/run.mdx @@ -20,6 +20,7 @@ When a project opens, OpenIDEA scans its build files (also in nested projects of | `package.json` | One per `scripts` entry, run with the package manager of the lock file (npm, pnpm, yarn or bun). `test`, `test:*`, `jest` and `vitest` scripts are marked as tests. | | `deno.json` / `deno.jsonc` | Deno tasks | | `playwright.config.*` | Scripts that run `playwright test` are tests; without one, `npx playwright test` | +| `cypress.config.*` / `cypress` dependency | Scripts that run `cypress run` are tests; without one, `npx cypress run` (a Cypress configuration) | | `Cargo.toml` | `cargo run` for each binary, `cargo test`, `cargo build`; workspace members are included | | `build.gradle(.kts)` / `pom.xml` | Gradle and Maven run configurations | | `go.mod` / `go.work` | Go programs and tests | diff --git a/docs/en/guide/search.mdx b/docs/en/guide/search.mdx index 7632cbaba..b74fe2892 100644 --- a/docs/en/guide/search.mdx +++ b/docs/en/guide/search.mdx @@ -41,6 +41,7 @@ Classes and symbols come from the IDE's own index (available as soon as a file i - **Recent Files** lists recently opened files and the tool windows; type to filter. - **Recent Locations** shows the places you visited or edited with a few lines of code around each. Press the shortcut again (or check **Show changed only**) to see only edited places. - **Switcher** works like an application switcher: hold `⌃` / `Ctrl`, press `⇥` / `Tab` to move through open files and tool windows, and release to switch. +- **Back** / **Forward** walks your navigation history across editor locations, split panes, and non-file editor tabs (such as diffs, agent chats, and terminal tabs), skipping entries for deleted tasks or closed terminal sessions. - **Select In…** reveals the current file in the Project view or another tool window. ## Find and replace in a file diff --git a/docs/en/guide/testing.mdx b/docs/en/guide/testing.mdx index 00f0d3b59..9a50764f6 100644 --- a/docs/en/guide/testing.mdx +++ b/docs/en/guide/testing.mdx @@ -32,7 +32,7 @@ Running a single test creates a temporary run configuration based on the project | Language | Gutter icons on | Runs with | | --------------------------- | --------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | | Rust | `#[test]` functions, `mod tests` | `cargo test`, `cargo nextest` | -| JavaScript / TypeScript | `test`, `it`, `describe`, `suite`, `context` (also `.each`, `.only`, `.skip`) | Jest or Vitest via the test script; Playwright Test; Deno, Bun | +| JavaScript / TypeScript | `test`, `it`, `describe`, `suite`, `context` (also `.each`, `.only`, `.skip`) | Jest or Vitest via test script; Playwright; Cypress; Deno, Bun | | Python | pytest `def test_*` and `class Test*`, unittest `TestCase` subclasses | pytest, Django `manage.py test` | | Go | `func TestX(t *testing.T)`, benchmarks | `go test` | | Java, Kotlin, Scala, Groovy | JUnit `@Test`, `@ParameterizedTest`, `@RepeatedTest`, `@TestFactory`, `@TestTemplate`; TestNG | Maven Surefire (`-Dtest=`) or Gradle (`--tests`) | @@ -68,7 +68,13 @@ Detected test configurations show results in the tree automatically. For your ow | **Rerun** (in the Run tool window) | `⌘R` | `Ctrl+F5` | | **Rerun Failed Tests** | — | — | -**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, `node --test`, Mocha, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks. +**Rerun Failed Tests** (in the Run tool window toolbar and Find Action) runs only the tests that failed in the last run, using each tool's filter syntax. It works for Cargo, Jest / Vitest, Playwright, Cypress (with `@cypress/grep`), `node --test`, Mocha, pytest, Django, PHPUnit, Go, Maven / Gradle and .NET runs, and for plugin test frameworks. + +Jasmine runs get it too, selecting the failed specs with `--filter=`. + +### Watch mode (Jest, Vitest) + +Turn on **Modify options › Watch for changes** in a Jest or Vitest test configuration, or the **Rerun Automatically** toggle in the test tree toolbar, to keep the runner watching (`jest --watchAll`, `vitest watch`). After each edit the tests run again in the same tab, and each cycle's results replace the previous ones in the tree. **Stop**, turning the toggle off, or closing the tab ends the watcher. Debug, **Rerun Failed Tests** and runs of selected tests run once. A script that runs `vitest run` is started as `vitest watch` through the package manager; a script that runs more than Jest or Vitest (`jest && eslint .`, `tsc && vitest run`) runs once. ## Navigate between code and tests diff --git a/docs/en/languages/javascript.mdx b/docs/en/languages/javascript.mdx index 52a0310ed..cdf855461 100644 --- a/docs/en/languages/javascript.mdx +++ b/docs/en/languages/javascript.mdx @@ -22,10 +22,16 @@ OpenIDEA edits JavaScript (`.js`, `.mjs`, `.cjs`, `.jsx`) and TypeScript (`.ts`, The TypeScript servers start for a workspace marked by `tsconfig.json`, `jsconfig.json` or `package.json`. Files outside any `tsconfig.json` / `jsconfig.json` are still registered with tsserver, so loose scripts get code insight too. +Path aliases from `vite.config.*` (`resolve.alias`), `rollup.config.*` (`@rollup/plugin-alias` `entries`) and `esbuild.config.*` (`alias`) are added to tsserver's `paths`; in a monorepo each package (`apps/web`, …) gets its own configuration's aliases, so imports such as `@/components/Button` resolve, navigate and complete. The configuration is read without running it: object and `[{ find, replacement }]` forms with string, `path.resolve(__dirname, …)` or `fileURLToPath(new URL(…, import.meta.url))` targets; aliases computed any other way are skipped. `paths` in `tsconfig.json` / `jsconfig.json` take priority. Aliases are read when the language server starts. + Two behaviours differ from the servers' defaults: renaming a symbol never introduces an `import { a as b }` alias, and moving a file does not make the server rewrite imports on its own; the IDE asks for the import updates first and shows them as a preview you can undo. Inlay hints show parameter names at literal arguments, inferred variable types and enum member values; turn kinds off in **Settings › Editor › Inlay Hints**. +### Project-wide type errors + +The language server checks open files only. To keep the type errors of the whole project in the Problems tool window, turn on **TypeScript Project Errors (tsc --watch)** in the Problems tool window's ⋮ menu (off by default, saved in the project settings). The IDE then runs the project's own `node_modules/.bin/tsc --noEmit --watch` for each `tsconfig.json` that no other one references (`tsc -b --watch` for a solution with project references) and replaces the errors after every compilation. It never writes into the project: outputs and `.tsbuildinfo` files go to a temporary folder. Configurations in folders that are ignored (`.gitignore`), excluded, hidden, or named `fixtures`, `examples` or `testdata` are skipped. Files open in an editor show the language server's errors instead, and an error that Build also reported is listed once. Nothing runs without a local `typescript` or in Restricted Mode. + ### TypeScript version **Settings › Languages & Frameworks › TypeScript** picks the TypeScript that `vtsls` and `typescript-language-server` load: @@ -52,7 +58,7 @@ All servers, debuggers and formatters are listed in **Settings › Languages & F | `vue-language-server`, `svelte-language-server`, `astro-ls`, `angular-language-server` | npm | | `oxlint` | npm | | `tailwindcss-language-server` | npm (`@tailwindcss/language-server`) | -| Prettier, oxfmt, Biome | npm | +| Prettier, oxfmt, Biome, dprint | npm | | JavaScript Debugger (vscode-js-debug) | GitHub release (`microsoft/vscode-js-debug`) | The Astro and Angular servers also run from the project's own `node_modules/.bin` when it has them. @@ -73,9 +79,16 @@ The Astro and Angular servers also run from the project's own `node_modules/.bin - **Prettier** (**Settings › Languages & Frameworks › Prettier**) formats JavaScript, JSX, TypeScript, TSX, JSON, Vue, HTML, CSS, SCSS, Less, GraphQL, YAML and Markdown by default. The executable is found in the project's `node_modules`, then the managed installation, then `PATH`, unless you set **Prettier path**. - **oxfmt** (**Settings › Languages & Frameworks › oxfmt**) replaces Prettier for an enabled language in files below an oxfmt configuration (`.oxfmtrc.json`, `oxfmt.config.ts`), or when it is the selected provider. - **Biome** (**Settings › Languages & Frameworks › Biome**) replaces Prettier and oxfmt for JavaScript, JSX, TypeScript, TSX, JSON, CSS and GraphQL in files below a `biome.json` / `biome.jsonc` or an installed `@biomejs/biome` (unless the configuration sets `formatter.enabled` to `false`), or when it is the selected provider. It formats whole files and reads its own configuration. +- **dprint** (**Settings › Languages & Frameworks › dprint**) formats every file its configuration's plugins cover (`dprint editor-info`), whatever the language, in files below a `dprint.json` / `.dprint.json` / `dprint.jsonc` or an installed `dprint`, or when it is the selected provider. It runs the project's own `dprint fmt --stdin` and formats whole files; files its plugins don't cover keep their usual formatter, and so do all files when dprint can't run there (not installed, plugins not downloadable); **Reformat with dprint** reports why. With **Format on save** on, saving runs it too. On these pages, **Formatting provider** chooses between **Automatic (language server first)** and the tool itself, **Run on save** formats on save, and **Enabled languages** limits which languages the tool handles. +With **Automatic**, a JavaScript or TypeScript file below the tool's own configuration (a Prettier configuration file or `prettier` key in `package.json`, an oxfmt configuration, or Biome's) is formatted by that tool rather than by the language server, once the tool is installed (before `npm install`, the language server formats). **Settings › Editor › General › Reformat code on save** then runs the tool too. + +### Code style + +**Settings › Editor › Code Style › JavaScript** and **TypeScript** have **Spaces** (after commas, around operators, within braces and so on) and **Punctuation** (semicolons: keep, use or don't use; quotes: as in the file, single or double). They are saved per project with the other code style settings and sent to the TypeScript server, which applies them to **Reformat Code** and to the code it adds: quick fixes, auto-imports, refactorings and **Optimize Imports**. JSX files follow JavaScript and TSX files TypeScript. When EditorConfig support is on, the project's `.editorconfig` comes first where it sets `quote_type` or the IntelliJ properties `ij_typescript_use_semicolon_after_statement`, `ij_typescript_use_double_quotes`, `ij_typescript_space_after_comma`, `ij_typescript_spaces_within_object_literal_braces` and the like (`ij_javascript_*` for JavaScript). tsserver has no trailing-comma option, so trailing commas stay as written. + ### Biome lint In a Biome project, Biome's diagnostics show in the editor and the Problems tool window, and `⌥⏎` / `Alt+Enter` offers its quick fixes and suppressions. Biome's safe fixes (`source.fixAll.biome`) run with **Code › Code Cleanup** and, when **Settings › Tools › Actions on Save › Run code cleanup** is on, on save. When Biome's formatter is enabled, its fix-all formats the file too. @@ -84,8 +97,9 @@ In a Biome project, Biome's diagnostics show in the editor and the Problems tool OpenIDEA detects run configurations when the project opens: -- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*`, and scripts that run `playwright test`, `node --test` or `mocha`, are test configurations. +- One configuration per `package.json` script (`npm run build`, `pnpm run dev`, …), for the root package, nested packages and workspace members. Scripts named `test`, `jest`, `vitest` or `test:*`, and scripts that run `playwright test`, `node --test`, `mocha` or `jasmine`, are test configurations. - `playwright test` (through `npx`) for a package with a `playwright.config.*` that no script runs. +- `cypress run` (through `npx`) for a package that depends on `cypress` or has a `cypress.config.*`, when no script runs `cypress run` (scripts that do are test configurations). Its **Cypress** configuration chooses the testing type (end-to-end or component), the browser, the specs and further options. - One per task in `deno.json` / `deno.jsonc` (`deno task <name>`). In `package.json`, the gutter shows run icons on each `scripts` entry to run or debug it. @@ -96,14 +110,16 @@ In `package.json`, the gutter shows run icons on each `scripts` entry to run or - Any other `.js` file runs with `node` (with `deno run` or `bun run` in a project with `deno.json` or `bun.lock`). - A `.ts` file runs with Node.js directly on 22.18+ / 23.6+, with `--experimental-strip-types` on 22.6–22.17 and 23.0–23.5, else through `tsx` or `ts-node`. -Jest, Vitest, Playwright Test, `node --test` and Mocha output is turned into the test tree, with **Rerun Failed Tests**. Playwright runs report through its `list` reporter unless the configuration names another; a test in the gutter runs by its line (`file:line`), and runs with several projects show each project under its file. `node --test` runs report through the IDE's reporter next to `spec`, added to `NODE_OPTIONS` (a script that chooses its own `--test-reporter` runs without the tree); single tests and reruns are selected by full name (`--test-name-pattern`). Mocha runs keep their reporter and load an IDE hook through `NODE_OPTIONS` that reports each test with its line; single tests and reruns use `--grep`, and in projects that test with Mocha or `node --test`, tests in `test/` get gutter icons whatever their file name. **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage). +Jest, Vitest, Playwright Test, `node --test`, Mocha and Jasmine output is turned into the test tree, with **Rerun Failed Tests**. Playwright runs report through its `list` reporter unless the configuration names another; a test in the gutter runs by its line (`file:line`), and runs with several projects show each project under its file. `node --test` runs report through the IDE's reporter next to `spec`, added to `NODE_OPTIONS` (a script that chooses its own `--test-reporter` runs without the tree); single tests and reruns are selected by full name (`--test-name-pattern`). Mocha runs keep their reporter and load an IDE hook through `NODE_OPTIONS` that reports each test with its line; single tests and reruns use `--grep`, and in projects that test with Mocha or `node --test`, tests in `test/` get gutter icons whatever their file name. Jasmine runs work the same way, with `--filter=` in place of `--grep`; `fdescribe`, `fit` and `xit` get gutter icons too, and in projects that test with Jasmine so do specs in `spec/` (`cartSpec.js`). **Run with Coverage** works for scripts that run `vitest` or `jest` (Vitest needs a coverage provider such as `@vitest/coverage-v8`; the IDE offers to add it) and for `node` / `tsx` / `ts-node` runs through `c8`. See [Testing](/en/guide/testing) and [Coverage](/en/guide/coverage). + +Cypress runs report through Cypress's built-in `teamcity` reporter unless the configuration names another, and show each spec's suites and tests in the test tree; selecting a test opens its declaration. `*.cy.*` files get gutter icons, and run on the project's Cypress configuration (other tests stay on its other runner); a spec runs with `--spec`, and a spec that mounts components (`cy.mount`) or sits in `cypress/component/` runs with `--component`. `cypress run` can't select tests by name, so single tests, suites and **Rerun Failed Tests** pass their full titles to the [`@cypress/grep`](https://github.com/cypress-io/cypress/tree/develop/npm/grep) plugin: as `--expose grep=…` on Cypress 15.10 and later (`@cypress/grep` 7), and in the `CYPRESS_grep` environment variable (earlier versions). Without a grep plugin among the dependencies (`@cypress/grep`, `cypress-grep`), they run their whole spec files, a notification says so, and the tree shows every test that ran. ## Debugging Debugging uses the JavaScript Debugger (vscode-js-debug); if it is missing, the first debug session offers to install it. - **Debug** works for npm script configurations, Node.js files and `deno run` / `deno test`. Child processes are attached automatically. -- **Attach to Node.js** is a run configuration type for a process started with `--inspect` on this or another machine (default port 9229), with local and remote root mapping. +- **Attach to Node.js** is a run configuration type for a process started with `--inspect` on this or another machine (default port 9229), with local and remote root mapping. With **Reconnect automatically** on, the session waits while the process restarts (nodemon, `node --watch`, `tsx watch`) and attaches to it again with the same breakpoints. - **Attach to Process…** in the Run menu lists running Node.js processes. - **JavaScript Debug** is a run configuration type that opens a URL in Chrome or Edge and debugs the page's JavaScript and TypeScript through source maps. Start the page's server first (for example with the `dev` npm script); **Web root** is the folder the URL serves, the project root by default. diff --git a/docs/en/plugins/capabilities.mdx b/docs/en/plugins/capabilities.mdx index 236681bce..1e45f13d9 100644 --- a/docs/en/plugins/capabilities.mdx +++ b/docs/en/plugins/capabilities.mdx @@ -45,6 +45,7 @@ Later: | `events.input` | Medium | `action-performed` and `input-mode-changed` events (keystrokes and editor input) | 1.0 | | `clipboard` | Medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | 1.0 | | `clipboard.read` | Medium | `host::read_clipboard`: the clipboard's text and image, only in commands and view actions the user ran (event handlers and other unattended calls are denied) | 1.11 | +| `agents` | Medium | `host::fork_agent_session`: fork a recorded native agent session (`claude` or `codex`) into a new task in the invoking window's project; trusted projects only | 1.18 | | `secrets` | Medium | `{{secret:<name>}}` in request headers, `secret_is_set`, `secret_set`, `secret_delete` | 1.0 | | `net:<host>` | Medium | `host::fetch` over HTTPS (and loopback HTTP) to that host; `*.example.com` matches subdomains | 1.0 | | `net:ask` | Medium | Ask the user at the first request to an HTTPS host that isn't declared | 1.5 | diff --git a/docs/en/plugins/guides/commands.mdx b/docs/en/plugins/guides/commands.mdx index 9c894087f..3771e811e 100644 --- a/docs/en/plugins/guides/commands.mdx +++ b/docs/en/plugins/guides/commands.mdx @@ -159,18 +159,20 @@ command = "test-selection" when = "editorLangId == markdown" # optional ``` -| `menu` | Where | API | -| ----------------------- | ----------------------------------------------------------------------------- | --- | -| `editor.context` | Editor right-click menu | 1.0 | -| `projectView.context` | Project tool window right-click menu | 1.0 | -| `editorTab.context` | Editor tab right-click menu | 1.0 | -| `tools` | **Tools** in the main menu | 1.0 | -| `viewItem.context` | Right-click menu of the items of one of the plugin's own views (needs `view`) | 1.2 | -| `commit.message` | Toolbar above the commit message (Commit tool window and Commit dialog) | 1.3 | -| `editor.title` | Actions area of the editor tab bar | 1.4 | -| `mainToolbar` | Main toolbar | 1.4 | -| `problems.context` | Right-click menu of a problem in the Problems tool window | 1.4 | -| `searchResults.context` | Right-click menu of a search result | 1.4 | +| `menu` | Where | API | +| ----------------------- | ----------------------------------------------------------------------------- | ---- | +| `editor.context` | Editor right-click menu | 1.0 | +| `projectView.context` | Project tool window right-click menu | 1.0 | +| `editorTab.context` | Editor tab right-click menu | 1.0 | +| `tools` | **Tools** in the main menu | 1.0 | +| `viewItem.context` | Right-click menu of the items of one of the plugin's own views (needs `view`) | 1.2 | +| `commit.message` | Toolbar above the commit message (Commit tool window and Commit dialog) | 1.3 | +| `editor.title` | Actions area of the editor tab bar | 1.4 | +| `mainToolbar` | Main toolbar | 1.4 | +| `problems.context` | Right-click menu of a problem in the Problems tool window | 1.4 | +| `searchResults.context` | Right-click menu of a search result | 1.4 | +| `services.context` | Right-click menu of the IDE's own Services nodes (run configurations, Docker) | 1.18 | +| `services.toolbar` | Services toolbar, for the selected IDE-owned nodes | 1.18 | Using a menu newer than 1.0 means declaring at least that API in `engines.openidea`. Every entry names a command the plugin declares. The menu's `when` applies alongside the @@ -205,6 +207,28 @@ command = "kube.logs" when = "viewItemKind == pod" ``` +**Services menus** (API 1.18). `services.context` and `services.toolbar` act on the nodes +the IDE puts in Services itself: run configurations and Docker containers. The `when` +clause sees, for each selected service, `serviceProvider` (`runConfigurations` or +`docker`), `serviceKind` (the configuration kind, such as `spring-boot`, or +`docker-container`), `serviceId`, `serviceName`, `serviceRunning`, `runConfigurationId` +(empty for a container) and `serviceSelectionCount`. An entry shows only when its `when` +holds for every selected service. The command's argument is JSON text, +`{"services": [{"provider", "id", "kind", "name", "running", "runConfigurationId"}]}`. +A toolbar entry shows the command's `icon`, else the plugin's. + +```toml +[[contributes.menus]] +menu = "services.context" +command = "hotreload.attach" +submenu = "Hot Reload" +when = "serviceKind == 'spring-boot' && serviceRunning" +``` + +To launch the selected configuration with the plugin's Java agent, bind the agent to an +executor instead (`executor` on `[[contributes.javaAgents]]`): **Run … with** and +**Debug … with** entries then appear beside Run and Debug, also in this menu. + ## Status bar items ```toml diff --git a/docs/en/plugins/manifest.mdx b/docs/en/plugins/manifest.mdx index 33b6af4d5..0a8466c0c 100644 --- a/docs/en/plugins/manifest.mdx +++ b/docs/en/plugins/manifest.mdx @@ -100,38 +100,38 @@ The user approves **required** capabilities as a whole when installing. **Option Each contribution point is a table (`[contributes.settings]`) or an array of tables (`[[contributes.commands]]`). Contributions are live as soon as the plugin is enabled, before its code loads. -| Point | Declaration | Code needed | Guide | -| ------------------- | -------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) | -| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) | -| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) | -| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) | -| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) | -| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) | -| `providers` | `kinds`, `languages` | yes | [Language features](/en/plugins/guides/language-features) | -| `documentIndexers` | `extensions` | yes | [Indexing](/en/plugins/guides/indexing) | -| `endpoints` | `files` (API 1.3) | yes | [README: Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) | -| `searchCategories` | `id`, `title` (API 1.13) | yes | [Custom search categories](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) | -| `views` | `id`, `title`, `icon?`, `location`, `web?`, `group?`, `when?` | without `web` | [Views and decorations](/en/plugins/guides/views) | -| `customEditors` | `id`, `title`, `patterns`, `priority`, `layout?`, `web?` | without `web` | [Views and decorations](/en/plugins/guides/views) | -| `markerIcons` | `id`, `icon`, `iconDark?`, `markers?`, `tooltip?` (API 1.3): gutter marker icons | no | [Language features](/en/plugins/guides/language-features) | -| `editorPanels` | `id`, `web`, `width`, `when?` (API 1.9; needs `editor.read`) | no | [README: Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) | -| `overlays` | `id`, `web`, `width`, `height`, `anchor?`, `when?`, `interactive?` (API 1.18) | no | [README: Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) | -| `runAnything` | `prefix`, `title?` (API 1.18) | no | [README: Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) | -| `dialogs` | `id`, `title`, `web`, `width`, `height` (API 1.18) | no | [README: Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) | -| `fileIcons` | `id`, `patterns`, `icon`, `iconDark?` | no | [Icon themes](/en/plugins/guides/icon-themes) | -| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables` | no | [File actions](/en/plugins/guides/file-actions) | -| `snippets` | `language`, `path` (API 1.4) | no | [Language features](/en/plugins/guides/language-features) | -| `commitChecks` | `id`, `title` | yes | [README: Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) | -| `serverCommands` | `server`, `command`, `run` (API 1.9) | yes | [README: Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) | -| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?`, `outputMode?` | no | [Run targets](/en/plugins/guides/run-targets) | -| `runConfigurations` | `files` (API 1.4) | yes | [Run targets](/en/plugins/guides/run-targets) | -| `javaAgents` | `path`, `args?` (API 1.10); `vmOptions?`, `jdk?` (API 1.14) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | -| `skills` | `path` (`skills/<name>/SKILL.md`, API 1.15) | no | [README: API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | -| `mcpTools` | `name`, `description`, `inputSchema`, `readOnly`, `destructive` (API 1.4) | yes | [MCP tools](/en/plugins/guides/mcp) | -| `themes` | `path`, `editor-scheme?` | no | [Themes](/en/plugins/guides/themes) | -| `iconThemes` | `id`, `label`, `path` | no | [Icon themes](/en/plugins/guides/icon-themes) | -| `languages` | `path` (a `languages/<id>.toml` file) | no | [Adding a language](/en/languages/adding) | +| Point | Declaration | Code needed | Guide | +| ------------------- | ----------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) | +| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) | +| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) | +| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) | +| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) | +| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) | +| `providers` | `kinds`, `languages` | yes | [Language features](/en/plugins/guides/language-features) | +| `documentIndexers` | `extensions` | yes | [Indexing](/en/plugins/guides/indexing) | +| `endpoints` | `files` (API 1.3) | yes | [README: Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) | +| `searchCategories` | `id`, `title` (API 1.13) | yes | [Custom search categories](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) | +| `views` | `id`, `title`, `icon?`, `location`, `web?`, `group?`, `when?` | without `web` | [Views and decorations](/en/plugins/guides/views) | +| `customEditors` | `id`, `title`, `patterns`, `priority`, `layout?`, `web?` | without `web` | [Views and decorations](/en/plugins/guides/views) | +| `markerIcons` | `id`, `icon`, `iconDark?`, `markers?`, `tooltip?` (API 1.3): gutter marker icons | no | [Language features](/en/plugins/guides/language-features) | +| `editorPanels` | `id`, `web`, `width`, `when?` (API 1.9; needs `editor.read`) | no | [README: Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) | +| `overlays` | `id`, `web`, `width`, `height`, `anchor?`, `when?`, `interactive?` (API 1.18) | no | [README: Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) | +| `runAnything` | `prefix`, `title?` (API 1.18) | no | [README: Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) | +| `dialogs` | `id`, `title`, `web`, `width`, `height` (API 1.18) | no | [README: Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) | +| `fileIcons` | `id`, `patterns`, `icon`, `iconDark?` | no | [Icon themes](/en/plugins/guides/icon-themes) | +| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables` | no | [File actions](/en/plugins/guides/file-actions) | +| `snippets` | `language`, `path` (API 1.4) | no | [Language features](/en/plugins/guides/language-features) | +| `commitChecks` | `id`, `title` | yes | [README: Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) | +| `serverCommands` | `server`, `command`, `run` (API 1.9) | yes | [README: Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) | +| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?`, `outputMode?` | no | [Run targets](/en/plugins/guides/run-targets) | +| `runConfigurations` | `files` (API 1.4) | yes | [Run targets](/en/plugins/guides/run-targets) | +| `javaAgents` | `path`, `args?` (API 1.10); `vmOptions?`, `jdk?` (API 1.14); `executor?` (API 1.18) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | +| `skills` | `path` (`skills/<name>/SKILL.md`, API 1.15) | no | [README: API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | +| `mcpTools` | `name`, `description`, `inputSchema`, `readOnly`, `destructive` (API 1.4) | yes | [MCP tools](/en/plugins/guides/mcp) | +| `themes` | `path`, `editor-scheme?` | no | [Themes](/en/plugins/guides/themes) | +| `iconThemes` | `id`, `label`, `path` | no | [Icon themes](/en/plugins/guides/icon-themes) | +| `languages` | `path` (a `languages/<id>.toml` file) | no | [Adding a language](/en/languages/adding) | Item ids (commands, views, themes, …) match `[a-z0-9][a-z0-9._-]*`, at most 64 characters. Menus, shortcuts and status bar items refer to the plugin's own declared commands; inside the IDE a command's action id is `plugin.<plugin id>.<command id>`. diff --git a/docs/en/plugins/versioning.mdx b/docs/en/plugins/versioning.mdx index 1b054be36..a7935580b 100644 --- a/docs/en/plugins/versioning.mdx +++ b/docs/en/plugins/versioning.mdx @@ -1,9 +1,9 @@ --- title: "API versions and compatibility" -description: "engines.openidea, the plugin API versions from 1.0 to 1.13, and the rules that keep released plugins loading in newer IDEs." +description: "engines.openidea, the plugin API versions from 1.0 to 1.18, and the rules that keep released plugins loading in newer IDEs." --- -The plugin API has one version number: the version of the WIT package in [`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) (`openidea:plugin@1.14.0` on `main`). The host's engine version and the SDK's `API_VERSION` always agree with it, and the SDK carries an identical copy of the WIT files. +The plugin API has one version number: the version of the WIT package in [`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) (`openidea:plugin@1.18.0` on `main`). The host's engine version and the SDK's `API_VERSION` always agree with it, and the SDK carries an identical copy of the WIT files. <Note> The plugin system is a preview. The compatibility rules below hold for released 1.x versions; what is still unreleased @@ -12,27 +12,27 @@ The plugin API has one version number: the version of the WIT package in [`wit/` ## Versions -| API | Shipped with | Highlights | -| ------ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 1.0.0 | OpenIDEA 0.1.36 | The base API: commands, events, storage, tasks, project and editor access, VCS, diagnostics, network and secrets, processes, declarative views and custom editors, settings, editor providers, syntax provider | -| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`, `ui.copy-to-clipboard`, `ui.open-url`, opening a project file at a line from a view | -| 1.2.0 | OpenIDEA 0.1.38 | Background document indexers, pickers, input boxes and confirmations, plugin context keys for `when` clauses, the files selected in the Project view, a manifest `icon`, the `viewItem.context` menu | -| 1.3.0 | OpenIDEA 0.1.39 | Commit message and before-commit checks, Services detail panes, diagnostics while typing, hover, inlay hints, semantic tokens, file-changing code actions, HTTP endpoints, files outside the project (`fs.read`/`fs.write`, `project.write`, private plugin directory), batched `files-changed` events and path filters, workspace symbols, long-running processes, notifications with buttons, translations, multi-page settings, file template variables, web view PTYs, log tabs and content tabs | -| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`, `ipc:`, `ide.commands` and `database.sources` capabilities; editor and project snapshots, decorations, text search, Problems, Git log/blame/diff; output channels; OAuth loopback; runs, terminal sessions, run configurations, test result parsing and run targets; formatting and other language features; embedded languages; snippets; more menu locations; database sources; MCP tools | -| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify` (a notification in one project's window), the `net:ask` capability, run target validation, per-command run target working-directory arguments | -| 1.6.0 | OpenIDEA 0.1.43 | Bounded, project-bound background WebSockets for event-stream plugins | -| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`: two texts in the diff viewer, such as a review's file before and after | -| 1.8.0 | OpenIDEA 0.1.45 | The `problems-changed` workbench event: the host keeps every producer's diagnostics per file, so an annotation follows the file rather than the invoking window | -| 1.9.0 | OpenIDEA 0.1.46 | Run configurations with an environment and a debugger, requests to a running language server (`lsp:<server>`), server commands routed to plugins, editor panels | -| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`: the Maven / Gradle dependency graph the IDE resolved (`build.read`) | -| 1.11.0 | In development on `main` | `ui.read-clipboard`: the clipboard's text and image in commands the user ran (`clipboard.read`) | -| 1.12.0 | In development on `main` | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output | -| 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries | -| 1.14.0 | In development on `main` | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item | -| 1.15.0 | In development on `main` | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills/<name>/SKILL.md"`) for bundling agent skills in plugins | -| 1.16.0 | OpenIDEA 0.1.52 | Optional `completion-list-provider` export: completion marked incomplete is asked again while typing on, without re-asking the language server or other plugins; `decorations.set-markdown`: line-end decorations whose hover is a Markdown card | -| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette | -| 1.18.0 | In development on `main` | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations | +| API | Shipped with | Highlights | +| ------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| 1.0.0 | OpenIDEA 0.1.36 | The base API: commands, events, storage, tasks, project and editor access, VCS, diagnostics, network and secrets, processes, declarative views and custom editors, settings, editor providers, syntax provider | +| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`, `ui.copy-to-clipboard`, `ui.open-url`, opening a project file at a line from a view | +| 1.2.0 | OpenIDEA 0.1.38 | Background document indexers, pickers, input boxes and confirmations, plugin context keys for `when` clauses, the files selected in the Project view, a manifest `icon`, the `viewItem.context` menu | +| 1.3.0 | OpenIDEA 0.1.39 | Commit message and before-commit checks, Services detail panes, diagnostics while typing, hover, inlay hints, semantic tokens, file-changing code actions, HTTP endpoints, files outside the project (`fs.read`/`fs.write`, `project.write`, private plugin directory), batched `files-changed` events and path filters, workspace symbols, long-running processes, notifications with buttons, translations, multi-page settings, file template variables, web view PTYs, log tabs and content tabs | +| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`, `ipc:`, `ide.commands` and `database.sources` capabilities; editor and project snapshots, decorations, text search, Problems, Git log/blame/diff; output channels; OAuth loopback; runs, terminal sessions, run configurations, test result parsing and run targets; formatting and other language features; embedded languages; snippets; more menu locations; database sources; MCP tools | +| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify` (a notification in one project's window), the `net:ask` capability, run target validation, per-command run target working-directory arguments | +| 1.6.0 | OpenIDEA 0.1.43 | Bounded, project-bound background WebSockets for event-stream plugins | +| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`: two texts in the diff viewer, such as a review's file before and after | +| 1.8.0 | OpenIDEA 0.1.45 | The `problems-changed` workbench event: the host keeps every producer's diagnostics per file, so an annotation follows the file rather than the invoking window | +| 1.9.0 | OpenIDEA 0.1.46 | Run configurations with an environment and a debugger, requests to a running language server (`lsp:<server>`), server commands routed to plugins, editor panels | +| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`: the Maven / Gradle dependency graph the IDE resolved (`build.read`) | +| 1.11.0 | In development on `main` | `ui.read-clipboard`: the clipboard's text and image in commands the user ran (`clipboard.read`) | +| 1.12.0 | In development on `main` | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output | +| 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries | +| 1.14.0 | In development on `main` | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item | +| 1.15.0 | In development on `main` | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills/<name>/SKILL.md"`) for bundling agent skills in plugins | +| 1.16.0 | OpenIDEA 0.1.52 | Optional `completion-list-provider` export: completion marked incomplete is asked again while typing on, without re-asking the language server or other plugins; `decorations.set-markdown`: line-end decorations whose hover is a Markdown card | +| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette | +| 1.18.0 | In development on `main` | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '<name>' with <title>" beside Run and Debug, the only launches that get that agent; grant-scoped `agents.fork-session`: fork a recorded native agent session (`claude` or `codex`) into a new task in the invoking window's project (`agents` capability), with the host validating the session and building the fork invocation itself | The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md). diff --git a/docs/en/reference/settings.mdx b/docs/en/reference/settings.mdx index 5149c4700..0c7db2222 100644 --- a/docs/en/reference/settings.mdx +++ b/docs/en/reference/settings.mdx @@ -55,7 +55,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"] | Plugins | Plugins | | Version Control | Commit; Confirmation; Directory Mappings; Issue Navigation; Log; Shelf; Git; GitHub | | Build, Execution, Deployment | CMake; Gradle; Maven; Console; Debugger (Data Views, Stepping); Python Debugger; Run/Debug; Run Targets; Deployment (Options) | -| Languages & Frameworks | Language Servers; Go (Build Tags, Go Modules); Java; Markdown; Node.js; PHP; Python Interpreter; Prettier; oxfmt; Biome; Ruff; Black formatter; Ruby; Rust; TypeScript | +| Languages & Frameworks | Language Servers; Go (Build Tags, Go Modules); Java; Markdown; Node.js; PHP; Python Interpreter; Prettier; oxfmt; Biome; dprint; Ruff; Black formatter; Ruby; Rust; TypeScript | | Tools | Agents (Chat); Terminal; Actions on Save; External Tools; SSH Configurations; MCP Server | | Security | Project Trust | @@ -90,7 +90,7 @@ Settings › Appearance & Behavior › System Settings, unless noted. | `dateFormat.overrideSystem` | `false` | **Override system date and time format** (Date Formats page). | | `dateFormat.pattern` | `"dd.MM.yyyy"` | Date pattern with `dd`, `MM`, `MMM`, `yy`, `yyyy`. | | `dateFormat.use24Hour` | `true` | 24-hour time. | -| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago". | +| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago" (in lists with time, in the annotate gutter as the day alone). | ### `[appearance]` diff --git a/docs/zh/guide/agents.mdx b/docs/zh/guide/agents.mdx index 420725a5f..0c7cb0270 100644 --- a/docs/zh/guide/agents.mdx +++ b/docs/zh/guide/agents.mdx @@ -130,6 +130,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的 - **内置**:每个内置 agent 的可执行文件是否在 `PATH` 中找到、指定 **自定义可执行文件** 的输入框、传给 agent 进程的 **环境变量**(格式为 `NAME=value; OTHER=value`;这些值保存在系统凭据存储中)以及登录方式。改动对新会话生效。如果 agent 是 npm 全局安装(例如 Claude Code、Codex、Gemini CLI),**检查更新** 会与 npm 的最新稳定版比较,点击 **更新至…** 即可更新这份安装。 - **ACP 注册表**:[ACP Registry](https://agentclientprotocol.com) 中发布的 agent,可以搜索、**安装**、**更新** 和 **移除**。安装的 agent 保存在 OpenIDEA 的数据目录中;注册表提供 SHA-256 时会校验下载内容。 +对于直接启动的内置 ACP agent(例如 OMP),**启动 › 附加实参**会追加到现有启动命令末尾。用空格分隔参数,含空格的值请加引号。点击**应用**保存,下一次启动进程时生效;命令预览显示已保存的结果。**重置附加参数**只清除此字段,不会改动可执行文件、环境变量或配置文件中手写的 `args`。 + **设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。 ### 外部 MCP 服务器 diff --git a/docs/zh/guide/database.mdx b/docs/zh/guide/database.mdx index b40908acc..f4acee200 100644 --- a/docs/zh/guide/database.mdx +++ b/docs/zh/guide/database.mdx @@ -20,12 +20,19 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行 | ClickHouse | ClickHouse(通过 HTTP) | | Snowflake | Snowflake(通过 HTTPS,见下文) | | SQLite | SQLite | +| DuckDB | DuckDB(官方 JDBC 驱动) | 预设会填好默认端口,必要时还会设置 SSL(例如 Redshift、Neon 和 Supabase 要求 SSL)。 +## DuckDB + +选择 **新建 › 数据源 › DuckDB**。在 **管理驱动…** 中添加 [DuckDB 官方 JDBC JAR](https://duckdb.org/docs/stable/clients/java),然后保存驱动配置。OpenIDEA 会预填驱动类和 URL 模板。运行驱动需要 Java 17 或更高版本。 + +选择 **文件** 可打开已有数据库或创建新文件,选择 **内存** 可创建断开连接后即释放的临时数据库,选择 **JDBC URL** 可直接输入 DuckDB URL。要以只读方式检查已有文件,请在 **选项** 中启用 **只读**。官方驱动会在打开文件时应用此设置。 + ## JDBC 驱动 -在预设数据源的 **常规** 选项卡中,**驱动** 默认为 **内置**。通过 **管理驱动…** 查看或添加该数据源类型的 JDBC 驱动配置。在 **驱动** 中选中配置后,数据源会使用 JDBC,同时保留原有类型及图标。选择 **转到驱动** 可查看所选配置及其 JAR 文件。对于没有预设的数据库,请选择 **新建 › 数据源 › 自定义 JDBC**。也可以在其中选择 **管理驱动…** 查看所有配置并修改关联类型。 +对于提供内置驱动的预设,**常规** 选项卡中的 **驱动** 默认为 **内置**。通过 **管理驱动…** 查看或添加该数据源类型的 JDBC 驱动配置。在 **驱动** 中选中配置后,数据源会使用 JDBC,同时保留原有类型及图标。选择 **转到驱动** 可查看所选配置及其 JAR 文件。对于没有预设的数据库,请选择 **新建 › 数据源 › 自定义 JDBC**。也可以在其中选择 **管理驱动…** 查看所有配置并修改关联类型。 为驱动配置命名,添加厂商提供的驱动 JAR 及依赖 JAR,填写完整的驱动类名和可选的 JDBC URL 模板。请仅导入可信来源的驱动。OpenIDEA 使用已安装的 Java 17 或更高版本运行时在单独的进程中加载驱动。 IDE 会读取 JAR 声明的驱动类,也支持手动输入完整类名。URL 模板支持 `{host}`、`{port}`、`{database}` 和 `{file}`,也可直接填写 JDBC URL。 URL 和高级属性会写入数据源配置,密码请填在密码栏,以使用系统凭据存储。“只读”选项会请求 JDBC 驱动建立只读连接。使用具备只读权限的数据库账号可强制限制写入。取消查询时,如果驱动停止了语句,会话及其临时表会保留。如果驱动在三秒内未响应,OpenIDEA 会关闭该会话。已提交的语句仍可能在服务器上完成。 @@ -42,7 +49,7 @@ description: "连接 SQL 数据库、浏览架构、在查询控制台中执行 在数据库工具窗口中点击 **+**(或在窗口内按 `⌘N` / `Alt+Insert`),然后选择: - **数据源 ›** 上表中的某个预设。 -- **从文件创建数据源…**:打开一个 SQLite 文件。 +- **从文件创建数据源…**:打开 DuckDB(`.duckdb`)或 SQLite 文件。 - **从 URL 创建数据源…**:粘贴 `postgresql://user@localhost:5432/db` 这样的 URL。也接受 `mysql://`、`mariadb://`、`sqlserver://`、`oracle://`、`clickhouse://`、`sqlite:path` 以及 `jdbc:` 开头的 URL。 - **从剪贴板导入**:从剪贴板读取连接 URL。 diff --git a/docs/zh/guide/editor.mdx b/docs/zh/guide/editor.mdx index e3073d834..2630e295e 100644 --- a/docs/zh/guide/editor.mdx +++ b/docs/zh/guide/editor.mdx @@ -55,6 +55,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、 **将光标移至下一段落** / **上一段落** 让每个光标越过一段连续的非空行,跳到其后或其前的空行(只含空格或制表符的行也算空行),没有空行时跳到文件末尾或开头;对应的 **并选择** 版本选择到该处。它们默认没有快捷键。 +**以另一种“驼峰”模式将光标移至下一个单词** / **上一个单词**(及其 **并选择** 版本)、**以另一种“驼峰”模式删除到单词开头** 和 **删除到单词结尾** 按与 **设置 › 编辑器 › 常规 › 智能键 › 使用“驼峰”单词** 相反的方式按单词移动或删除:该选项关闭时按驼峰片段(`parse|HTML|Document`),开启时按整个单词。它们默认没有快捷键。 + **剪切到行尾** 从每个光标剪切到所在行的行尾;光标后只剩空白(或光标已在行尾)时连同换行符一起剪切,所以在同一光标处再按一次会剪切下一行,这些连续的剪切合并为剪贴板中的一条内容。**删除到行首** 和 **删除到行尾** 以同样方式删除但不复制(删除到行首时,若光标在行首则删除前面的换行符),有选区时删除选区。除 Eclipse 键位映射(删除到行尾为 `⇧⌘⌦` / `Ctrl+Shift+Delete`)外,它们默认没有快捷键。 **贪婪退格** 一次删除每个光标前的所有空格、制表符和换行符,直到前一个非空白字符;光标前是其他字符或有选区时,它与 `⌫` / `Backspace` 相同。它默认没有快捷键。 @@ -108,7 +110,7 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、 | **自动缩进行** | `⌃⌥I` | `Ctrl+Alt+I` | | **优化导入** | `⌃⌥O` | `Ctrl+Alt+O` | -**重新格式化代码** 格式化选区,没有选区时格式化整个文件,整体算一步撤销。格式化由文件的语言服务器或该语言配置的格式化工具完成(例如 Python 用 Ruff,Web 语言用 Prettier、oxfmt 或 Biome;在查找操作里搜 **使用 … 重新格式化** 可以指定工具)。**重新格式化文件…** 还能选择范围并顺便优化导入。 +**重新格式化代码** 格式化选区,没有选区时格式化整个文件,整体算一步撤销。格式化由文件的语言服务器或该语言配置的格式化工具完成(例如 Python 用 Ruff,Web 语言用 Prettier、oxfmt 或 Biome,dprint 项目用 dprint;在查找操作里搜 **使用 … 重新格式化** 可以指定工具)。**重新格式化文件…** 还能选择范围并顺便优化导入。 缩进等代码风格选项在 **设置 › 编辑器 › 代码样式** 中,每种语言一个页面。项目里的 `.editorconfig` 也会生效。 @@ -143,21 +145,24 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、 ## 显示选项 -| 操作 | macOS | Windows / Linux | -| -------------- | ----- | --------------- | -| **增大字体** | `⌥⇧.` | `Alt+Shift+.` | -| **减小字体** | `⌥⇧,` | `Alt+Shift+,` | -| **滚动到中央** | `⌃L` | `Ctrl+M` | -| **向上滚动** | — | `Ctrl+Up` | -| **向下滚动** | — | `Ctrl+Down` | -| **滚动到顶部** | — | — | -| **滚动到底部** | — | — | +| 操作 | macOS | Windows / Linux | +| ------------------------------ | ----- | --------------- | +| **增大字体** | `⌥⇧.` | `Alt+Shift+.` | +| **减小字体** | `⌥⇧,` | `Alt+Shift+,` | +| **滚动到中央** | `⌃L` | `Ctrl+M` | +| **向上滚动** | — | `Ctrl+Up` | +| **向下滚动** | — | `Ctrl+Down` | +| **向上滚动并在必要时移动光标** | — | — | +| **向下滚动并在必要时移动光标** | — | — | +| **滚动到顶部** | — | — | +| **滚动到底部** | — | — | -**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。 +**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。 - **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。 - **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。 - **视图 › 外观 › 进入无干扰模式** 隐藏工具窗口、标签页、状态栏和装订区域,并让正文居中。再执行一次即可退出。 +- **视图 › 外观 › 进入 Zen 模式** 同时开启无干扰模式和全屏;**退出 Zen 模式** 同时关闭两者。 - **显示行号**、**显示缩进参考线**、**显示粘滞行** 和 **显示空白** 在所有编辑器中打开或关闭对应显示。可从查找操作运行,或右键单击装订区域并打开 **外观**。 - 行号、空白字符、缩进参考线、光标样式和意图灯泡在 **设置 › 编辑器 › 常规 › 外观** 中设置。痕迹导航和粘滞行(滚动时把所在的声明固定在顶部)在 **设置 › 编辑器 › 常规** 下各有单独的页面。 diff --git a/docs/zh/guide/refactoring.mdx b/docs/zh/guide/refactoring.mdx index c6cc52201..1c29a556c 100644 --- a/docs/zh/guide/refactoring.mdx +++ b/docs/zh/guide/refactoring.mdx @@ -15,21 +15,22 @@ description: "重命名、引入与提取、内联、移动、更改签名和安 ## 可用的重构 -| 重构 | macOS | Windows / Linux | 实现方式 | -| ------------- | ----- | --------------- | --------------------------------------- | -| **重命名…** | `⇧F6` | `Shift+F6` | 语言服务器;局部变量没有服务器也可以 | -| **更改签名…** | `⌘F6` | `Ctrl+F6` | Java(对话框);其他语言:语言服务器 | -| **引入变量…** | `⌥⌘V` | `Ctrl+Alt+V` | 语言服务器;简单情况没有服务器也可以 | -| **引入常量…** | `⌥⌘C` | `Ctrl+Alt+C` | 语言服务器;简单情况没有服务器也可以 | -| **引入字段…** | `⌥⌘F` | `Ctrl+Alt+F` | 语言服务器 | -| **引入参数…** | `⌥⌘P` | `Ctrl+Alt+P` | 语言服务器 | -| **提取方法…** | `⌥⌘M` | `Ctrl+Alt+M` | 语言服务器 | -| **提取接口…** | — | — | Java | -| **内联…** | `⌥⌘N` | `Ctrl+Alt+N` | 语言服务器 | -| **移动…** | `F6` | `F6` | 语言服务器(符号);IDE(文件和文件夹) | -| **安全删除…** | `⌘⌦` | `Alt+Delete` | IDE,借助服务器查找引用 | -| **上拉成员…** | — | — | Java;PHP(使用 Phoxite) | -| **下推成员…** | — | — | Java;PHP(使用 Phoxite) | +| 重构 | macOS | Windows / Linux | 实现方式 | +| ----------------- | ----- | --------------- | ------------------------------------------------ | +| **重命名…** | `⇧F6` | `Shift+F6` | 语言服务器;局部变量没有服务器也可以 | +| **更改签名…** | `⌘F6` | `Ctrl+F6` | Java(对话框);其他语言:语言服务器 | +| **引入变量…** | `⌥⌘V` | `Ctrl+Alt+V` | 语言服务器;简单情况没有服务器也可以 | +| **引入常量…** | `⌥⌘C` | `Ctrl+Alt+C` | 语言服务器;简单情况没有服务器也可以 | +| **引入字段…** | `⌥⌘F` | `Ctrl+Alt+F` | 语言服务器 | +| **引入参数…** | `⌥⌘P` | `Ctrl+Alt+P` | 语言服务器 | +| **提取方法…** | `⌥⌘M` | `Ctrl+Alt+M` | 语言服务器 | +| **提取接口…** | — | — | Java(对话框);TypeScript:语言服务器 | +| **提取类型别名…** | — | — | TypeScript、JavaScript(`@typedef`):语言服务器 | +| **内联…** | `⌥⌘N` | `Ctrl+Alt+N` | 语言服务器 | +| **移动…** | `F6` | `F6` | 语言服务器(符号);IDE(文件和文件夹) | +| **安全删除…** | `⌘⌦` | `Alt+Delete` | IDE,借助服务器查找引用 | +| **上拉成员…** | — | — | Java;PHP(使用 Phoxite) | +| **下推成员…** | — | — | Java;PHP(使用 Phoxite) | ## 重命名 @@ -80,6 +81,8 @@ description: "重命名、引入与提取、内联、移动、更改签名和安 在 Java 中,**重构 › 提取接口…** 会从当前文件的类创建一个接口。在对话框中输入接口名称,选择所在软件包,并勾选接口要声明的方法(以及常量)。**重构** 会创建接口、让该类实现它、在可行的地方把对该类的使用替换为接口,并打开新文件;**预览** 会先列出所有改动。 +在 TypeScript 中,选中一个对象类型字面量(例如 `{ name: string; age: number }`)后选择 **重构 › 提取接口…**,语言服务器会为它声明一个 `interface` 并在原处使用它。**重构 › 提取类型别名…** 对任意选中的类型做同样的事,生成 `type` 声明;在 JavaScript 中则添加 JSDoc `@typedef`。完成后会就地重命名新名称,与 **引入变量…** 之后一样。如果服务器在选区处没有可提取的内容,编辑器会给出提示。 + ## 更改签名 在 Java 方法上执行 **更改签名…**(`⌘F6`)会打开对话框,可以修改可见性、返回类型和方法名,添加、删除和调整形参顺序。新形参需要填写默认值,所有已有调用处都会传入这个值;勾选 **通过重载方法委托** 会保留旧签名作为重载并调用新方法。签名预览显示修改后的声明。**重构** 会一次更新方法本身、覆盖它的方法和所有调用;**预览** 先列出改动。其他语言在服务器把签名重写作为代码操作提供时才会出现。 diff --git a/docs/zh/guide/run.mdx b/docs/zh/guide/run.mdx index 9f44e4783..f6f048cdb 100644 --- a/docs/zh/guide/run.mdx +++ b/docs/zh/guide/run.mdx @@ -20,6 +20,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码, | `package.json` | 每个 `scripts` 条目一个,使用锁文件对应的包管理器(npm、pnpm、yarn 或 bun)。`test`、`test:*`、`jest`、`vitest` 脚本会标记为测试。 | | `deno.json` / `deno.jsonc` | Deno task | | `playwright.config.*` | 运行 `playwright test` 的脚本是测试配置;没有这样的脚本时为 `npx playwright test` | +| `cypress.config.*` / `cypress` 依赖 | 运行 `cypress run` 的脚本是测试配置;没有这样的脚本时为 `npx cypress run`(Cypress 配置) | | `Cargo.toml` | 每个二进制一个 `cargo run`,以及 `cargo test`、`cargo build`;包含 workspace 成员 | | `build.gradle(.kts)` / `pom.xml` | Gradle、Maven 运行配置 | | `go.mod` / `go.work` | Go 程序和测试 | diff --git a/docs/zh/guide/search.mdx b/docs/zh/guide/search.mdx index 2aae30e85..c58f7afce 100644 --- a/docs/zh/guide/search.mdx +++ b/docs/zh/guide/search.mdx @@ -41,6 +41,7 @@ description: "随处搜索,转到文件、类和符号,在文件中查找和 - **最近的文件** 列出最近打开的文件和工具窗口,输入文字可以过滤。 - **最近的位置** 列出你浏览或编辑过的位置,每处都带几行上下文代码。再按一次快捷键(或勾选 **仅显示已更改的**)只看编辑过的位置。 - **切换器** 的用法类似系统的应用切换:按住 `⌃` / `Ctrl`,按 `⇥` / `Tab` 在打开的文件和工具窗口之间移动,松开即切换。 +- **后退** / **前进** 会在编辑器位置、拆分窗格以及非文件编辑器标签页(如差异视图、Agent 对话和终端标签页)之间沿导航历史往返,并自动跳过已删除的任务或已关闭的终端会话。 - **选择位置…** 在项目视图或其他工具窗口中定位当前文件。 ## 在当前文件中查找和替换 diff --git a/docs/zh/guide/testing.mdx b/docs/zh/guide/testing.mdx index 190ecde5e..a42253422 100644 --- a/docs/zh/guide/testing.mdx +++ b/docs/zh/guide/testing.mdx @@ -28,7 +28,7 @@ OpenIDEA 直接使用项目自己的测试工具(Cargo、Jest、pytest、Maven | 语言 | 装订区图标位置 | 运行方式 | | --------------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | Rust | `#[test]` 函数、`mod tests` | `cargo test`、`cargo nextest` | -| JavaScript / TypeScript | `test`、`it`、`describe`、`suite`、`context`(含 `.each`、`.only`、`.skip`) | 用测试脚本运行 Jest 或 Vitest;Playwright;Deno、Bun | +| JavaScript / TypeScript | `test`、`it`、`describe`、`suite`、`context`(含 `.each`、`.only`、`.skip`) | Jest / Vitest(脚本);Playwright;Cypress;Deno、Bun | | Python | pytest 的 `def test_*`、`class Test*`,unittest 的 `TestCase` 子类 | pytest、Django `manage.py test` | | Go | `func TestX(t *testing.T)`、基准测试 | `go test` | | Java、Kotlin、Scala、Groovy | JUnit `@Test`、`@ParameterizedTest`、`@RepeatedTest`、`@TestFactory`、`@TestTemplate`;TestNG | Maven Surefire(`-Dtest=`)或 Gradle(`--tests`) | @@ -64,7 +64,13 @@ RSpec 有自己的配置类型(**RSpec 测试**)和检测到的 `rspec` 配 | **重新运行**(在“运行”工具窗口中) | `⌘R` | `Ctrl+F5` | | **重新运行失败的测试** | — | — | -**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、`node --test`、Mocha、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。 +**重新运行失败的测试**(在“运行”工具窗口工具栏和“查找操作”中)只运行上一次失败的测试,会按各个工具自己的过滤语法生成命令。支持 Cargo、Jest / Vitest、Playwright、Cypress(需 `@cypress/grep`)、`node --test`、Mocha、pytest、Django、PHPUnit、Go、Maven / Gradle 和 .NET,以及插件接入的测试框架。 + +Jasmine 运行也支持,用 `--filter=` 选出失败的测试。 + +### 监视模式(Jest、Vitest) + +在 Jest 或 Vitest 测试配置中打开 **修改选项 › 监视更改**,或在测试树工具栏打开 **自动重新运行**,测试运行器会持续监视文件(`jest --watchAll`、`vitest watch`)。每次编辑后测试会在同一个标签页中重新运行,每一轮的结果替换树中上一轮的结果。点击 **停止**、关闭这个开关或关闭标签页都会结束监视进程。调试、**重新运行失败的测试**和运行选中的测试都只运行一次。运行 `vitest run` 的脚本会通过包管理器以 `vitest watch` 启动;除了 Jest 或 Vitest 还运行其他命令的脚本(`jest && eslint .`、`tsc && vitest run`)只运行一次。 ## 在代码和测试之间跳转 diff --git a/docs/zh/languages/javascript.mdx b/docs/zh/languages/javascript.mdx index 60302cac6..f7b63af93 100644 --- a/docs/zh/languages/javascript.mdx +++ b/docs/zh/languages/javascript.mdx @@ -22,10 +22,16 @@ OpenIDEA 打开 JavaScript(`.js`、`.mjs`、`.cjs`、`.jsx`)和 TypeScript TypeScript 服务器以 `tsconfig.json`、`jsconfig.json` 或 `package.json` 所在目录为工作区根。不属于任何 `tsconfig.json` / `jsconfig.json` 的文件也会注册给 tsserver,零散脚本同样有代码智能。 +`vite.config.*`(`resolve.alias`)、`rollup.config.*`(`@rollup/plugin-alias` 的 `entries`)和 `esbuild.config.*`(`alias`)中的路径别名会加入 tsserver 的 `paths`;monorepo 里每个包(`apps/web` 等)只用它自己目录下配置的别名,`@/components/Button` 这类 import 可以解析、跳转和补全。配置文件不会被执行,只静态读取:支持对象和 `[{ find, replacement }]` 两种写法,目标可以是字符串、`path.resolve(__dirname, …)` 或 `fileURLToPath(new URL(…, import.meta.url))`;用其他方式计算的别名会被跳过。`tsconfig.json` / `jsconfig.json` 中的 `paths` 优先。别名在语言服务器启动时读取。 + 有两处行为与服务器默认值不同:重命名符号时不会生成 `import { a as b }` 这样的别名;移动文件时服务器不会自行改写 import,而是由 IDE 先给出需要更新的 import,以预览形式展示,并可撤销。 嵌入提示会显示字面量实参的参数名、推断出的变量类型和枚举成员的值;可以在 **设置 › 编辑器 › 嵌入提示** 中按类型关闭。 +### 整个项目的类型错误 + +语言服务器只检查已打开的文件。要在 Problems 工具窗口里保留整个项目的类型错误,在 Problems 工具窗口的 ⋮ 菜单中打开 **TypeScript 项目错误(tsc --watch)**(默认关闭,保存在项目设置中)。IDE 会对每个没有被其他配置引用的 `tsconfig.json` 运行项目自己的 `node_modules/.bin/tsc --noEmit --watch`(带项目引用的解决方案配置运行 `tsc -b --watch`),每次编译后替换这些错误。它不会向项目写入任何文件:编译输出和 `.tsbuildinfo` 都写到临时目录。被 `.gitignore` 忽略、被排除、隐藏或名为 `fixtures`、`examples`、`testdata` 的目录里的配置会被跳过。在编辑器中打开的文件改为显示语言服务器的错误;Build 也报告过的同一个错误只列出一次。没有本地 `typescript` 或处于受限模式时不会运行。 + ### TypeScript 版本 **设置 › 语言和框架 › TypeScript** 决定 `vtsls` 和 `typescript-language-server` 加载哪个 TypeScript: @@ -53,7 +59,7 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript | `oxlint` | npm | | `tailwindcss-language-server` | npm(`@tailwindcss/language-server`) | | Prettier、oxfmt | npm | -| Prettier、oxfmt、Biome | npm | +| Prettier、oxfmt、Biome、dprint | npm | | JavaScript 调试器(vscode-js-debug) | GitHub release(`microsoft/vscode-js-debug`) | 如果项目自己的 `node_modules/.bin` 里有 Astro 或 Angular 服务器,会优先使用项目里的。 @@ -74,9 +80,16 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript - **Prettier**(**设置 › 语言和框架 › Prettier**)默认处理 JavaScript、JSX、TypeScript、TSX、JSON、Vue、HTML、CSS、SCSS、Less、GraphQL、YAML 和 Markdown。未设置 **Prettier 路径** 时,依次查找项目 `node_modules`、IDE 管理的安装、`PATH`。 - **oxfmt**(**设置 › 语言和框架 › oxfmt**)在 oxfmt 配置文件(`.oxfmtrc.json`、`oxfmt.config.ts`)所在目录之下,或被选为格式化工具时,替代 Prettier 处理已启用的语言。 - **Biome**(**设置 › 语言和框架 › Biome**)在 `biome.json` / `biome.jsonc` 所在目录或安装了 `@biomejs/biome` 的项目之下(配置里 `formatter.enabled` 为 `false` 时除外),或被选为格式化工具时,替代 Prettier 和 oxfmt 处理 JavaScript、JSX、TypeScript、TSX、JSON、CSS 和 GraphQL。它总是格式化整个文件,并读取自己的配置。 +- **dprint**(**设置 › 语言和框架 › dprint**)在 `dprint.json` / `.dprint.json` / `dprint.jsonc` 所在目录或安装了 `dprint` 的项目之下,或被选为格式化工具时,格式化其配置中插件覆盖的所有文件(`dprint editor-info`),不限语言。它运行项目自己的 `dprint fmt --stdin`,总是格式化整个文件;插件不覆盖的文件仍使用原来的格式化工具;dprint 无法运行时(未安装、插件无法下载),所有文件也都使用原来的格式化工具,**使用 dprint 重新格式化** 会给出原因。开启 **保存时格式化** 时,保存也会运行它。 这些页面上,**格式化工具** 可选 **自动(优先语言服务器)** 或工具本身,**保存时运行** 控制保存时格式化,**启用的语言** 限定工具处理哪些语言。 +选 **自动** 时,位于该工具自身配置之下的 JavaScript、TypeScript 文件(Prettier 配置文件或 `package.json` 里的 `prettier` 键、oxfmt 配置、Biome 配置)由该工具格式化,而不是语言服务器;前提是该工具已安装(`npm install` 之前仍由语言服务器格式化)。这时 **设置 › 编辑器 › 常规 › 保存时重新格式化代码** 也会运行该工具。 + +### 代码样式 + +**设置 › 编辑器 › 代码样式 › JavaScript** 和 **TypeScript** 有 **空格**(逗号后、运算符两侧、花括号内等)和 **标点**(分号:保持原样、使用或不使用;引号:与文件一致、单引号或双引号)两个标签页。它们和其他代码样式设置一起按项目保存,并发送给 TypeScript 服务器:服务器将其用于 **重新格式化代码**,以及它添加的代码,包括快速修复、自动导入、重构和 **优化导入**。JSX 文件跟随 JavaScript,TSX 文件跟随 TypeScript。启用 EditorConfig 支持时,项目 `.editorconfig` 中设置的 `quote_type` 或 IntelliJ 属性 `ij_typescript_use_semicolon_after_statement`、`ij_typescript_use_double_quotes`、`ij_typescript_space_after_comma`、`ij_typescript_spaces_within_object_literal_braces` 等(JavaScript 用 `ij_javascript_*`)优先。tsserver 没有尾随逗号选项,尾随逗号保持原样。 + ### Biome 检查 在 Biome 项目中,Biome 的诊断显示在编辑器和“问题”工具窗口里,`⌥⏎` / `Alt+Enter` 提供它的快速修复和抑制。Biome 的安全修复(`source.fixAll.biome`)随 **代码 › 代码清理** 运行;开启 **设置 › 工具 › 保存时操作 › 运行代码清理** 后,保存时也会运行。Biome 的格式化器开启时,它的全部修复也会格式化文件。 @@ -85,8 +98,9 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript 打开项目时,OpenIDEA 会自动检测运行配置: -- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本,以及运行 `playwright test`、`node --test` 或 `mocha` 的脚本,是测试配置。 +- 每个 `package.json` 脚本一个配置(`npm run build`、`pnpm run dev` 等),覆盖根包、嵌套包和 workspace 成员。名为 `test`、`jest`、`vitest` 或 `test:*` 的脚本,以及运行 `playwright test`、`node --test`、`mocha` 或 `jasmine` 的脚本,是测试配置。 - 有 `playwright.config.*` 但没有脚本运行它的包:通过 `npx` 运行的 `playwright test`。 +- 依赖 `cypress` 或有 `cypress.config.*`、但没有脚本运行 `cypress run` 的包:通过 `npx` 运行的 `cypress run`(运行它的脚本是测试配置)。它的 **Cypress** 配置可以选择测试类型(端到端或组件)、浏览器、spec 文件和其他选项。 - `deno.json` / `deno.jsonc` 中每个 task 一个配置(`deno task <name>`)。 在 `package.json` 中,每个 `scripts` 条目旁的边栏图标可以直接运行或调试该脚本。 @@ -97,14 +111,16 @@ Vue、Astro 和 Angular 服务器也会使用这里选择的版本。TypeScript - 其他 `.js` 文件用 `node` 运行(项目含 `deno.json` 或 `bun.lock` 时改用 `deno run` 或 `bun run`)。 - `.ts` 文件在 Node.js 22.18+ / 23.6+ 上直接运行,在 22.6–22.17 和 23.0–23.5 上加 `--experimental-strip-types`,更早的版本则通过 `tsx` 或 `ts-node` 运行。 -Jest、Vitest、Playwright Test、`node --test` 和 Mocha 的输出会解析成测试树,支持 **重新运行失败的测试**。Playwright 运行时使用它的 `list` 报告器(配置里指定了其他报告器时除外);从行号栏运行单个测试时按行号选择(`file:line`),有多个 project 的运行会在文件下按 project 分组。`node --test` 运行时,IDE 通过 `NODE_OPTIONS` 在 `spec` 旁加上自己的报告器(脚本自己指定了 `--test-reporter` 时不显示测试树);单个测试和重新运行按完整名称选择(`--test-name-pattern`)。Mocha 运行保留它自己的报告器,并通过 `NODE_OPTIONS` 加载 IDE 的钩子,逐个报告测试及其所在行;单个测试和重新运行使用 `--grep`,在用 Mocha 或 `node --test` 测试的项目里,`test/` 目录下的测试不论文件名都有行号栏图标。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。 +Jest、Vitest、Playwright Test、`node --test`、Mocha 和 Jasmine 的输出会解析成测试树,支持 **重新运行失败的测试**。Playwright 运行时使用它的 `list` 报告器(配置里指定了其他报告器时除外);从行号栏运行单个测试时按行号选择(`file:line`),有多个 project 的运行会在文件下按 project 分组。`node --test` 运行时,IDE 通过 `NODE_OPTIONS` 在 `spec` 旁加上自己的报告器(脚本自己指定了 `--test-reporter` 时不显示测试树);单个测试和重新运行按完整名称选择(`--test-name-pattern`)。Mocha 运行保留它自己的报告器,并通过 `NODE_OPTIONS` 加载 IDE 的钩子,逐个报告测试及其所在行;单个测试和重新运行使用 `--grep`,在用 Mocha 或 `node --test` 测试的项目里,`test/` 目录下的测试不论文件名都有行号栏图标。Jasmine 运行的方式相同,用 `--filter=` 代替 `--grep`;`fdescribe`、`fit` 和 `xit` 也有行号栏图标,在用 Jasmine 测试的项目里,`spec/` 目录下的测试(`cartSpec.js`)也有。**使用覆盖率运行** 支持调用 `vitest` 或 `jest` 的脚本(Vitest 需要 `@vitest/coverage-v8` 之类的覆盖率 provider,缺失时 IDE 会提示添加),以及通过 `c8` 运行的 `node` / `tsx` / `ts-node`。详见[测试](/zh/guide/testing)和[覆盖率](/zh/guide/coverage)。 + +Cypress 运行时使用 Cypress 内置的 `teamcity` 报告器(配置里指定了其他报告器时除外),测试树按 spec 列出其中的 suite 和测试;选中测试会打开它的声明处。`*.cy.*` 文件有行号栏图标,并用项目的 Cypress 配置运行(其他测试仍用项目的另一个测试运行器);运行 spec 时使用 `--spec`,挂载组件(`cy.mount`)或位于 `cypress/component/` 的 spec 会加上 `--component`。`cypress run` 不能按名称选择测试,所以单个测试、suite 和 **重新运行失败的测试** 会把完整标题交给 [`@cypress/grep`](https://github.com/cypress-io/cypress/tree/develop/npm/grep) 插件:Cypress 15.10 及以上用 `--expose grep=…`(`@cypress/grep` 7),更早的版本用环境变量 `CYPRESS_grep`。依赖中没有 grep 插件(`@cypress/grep`、`cypress-grep`)时,会运行整个 spec 文件,并弹出通知说明,测试树显示实际运行的所有测试。 ## 调试 调试使用 JavaScript 调试器(vscode-js-debug);未安装时,第一次调试会提示安装。 - **调试** 适用于 npm 脚本配置、Node.js 文件以及 `deno run` / `deno test`,子进程会自动附加。 -- **附加到 Node.js** 是一种运行配置类型,用于附加到本机或其他机器上以 `--inspect` 启动的进程(默认端口 9229),可设置本地与远程根目录映射。 +- **附加到 Node.js** 是一种运行配置类型,用于附加到本机或其他机器上以 `--inspect` 启动的进程(默认端口 9229),可设置本地与远程根目录映射。勾选 **自动重新连接** 后,进程重启时(nodemon、`node --watch`、`tsx watch`)会话会等待,并以相同的断点重新附加。 - 运行菜单中的 **附加到进程…** 会列出正在运行的 Node.js 进程。 - **JavaScript 调试** 是一种运行配置类型:在 Chrome 或 Edge 中打开一个 URL,通过 source map 调试页面中的 JavaScript 和 TypeScript。先启动页面的服务(例如 `dev` npm 脚本);**Web 根目录** 是该 URL 对应的文件夹,默认为项目根目录。 diff --git a/docs/zh/plugins/capabilities.mdx b/docs/zh/plugins/capabilities.mdx index caa596e45..dd0e68448 100644 --- a/docs/zh/plugins/capabilities.mdx +++ b/docs/zh/plugins/capabilities.mdx @@ -45,6 +45,7 @@ optional = ["net:api.example.com", "secrets"] | `events.input` | 中 | `action-performed` 和 `input-mode-changed` 事件(按键和编辑器输入) | 1.0 | | `clipboard` | 中 | `host::copy_to_clipboard`,以及插件 Web 视图中的剪贴板 API | 1.0 | | `clipboard.read` | 中 | `host::read_clipboard`:读取剪贴板的文本和图片,仅限用户运行的命令和视图操作(事件处理器等无人值守的调用会被拒绝) | 1.11 | +| `agents` | 中 | `host::fork_agent_session`:把录制的原生 agent 会话(`claude` 或 `codex`)派生为当前窗口项目中的新任务;仅限受信任项目 | 1.18 | | `secrets` | 中 | 请求头中的 `{{secret:<name>}}`、`secret_is_set`、`secret_set`、`secret_delete` | 1.0 | | `net:<host>` | 中 | `host::fetch` 通过 HTTPS(以及回环地址的 HTTP)访问该主机;`*.example.com` 匹配子域名 | 1.0 | | `net:ask` | 中 | 第一次请求未声明的 HTTPS 主机时询问用户 | 1.5 | diff --git a/docs/zh/plugins/guides/commands.mdx b/docs/zh/plugins/guides/commands.mdx index fa3492224..0d7238043 100644 --- a/docs/zh/plugins/guides/commands.mdx +++ b/docs/zh/plugins/guides/commands.mdx @@ -143,18 +143,20 @@ command = "test-selection" when = "editorLangId == markdown" # 可选 ``` -| `menu` | 位置 | API | -| ----------------------- | ------------------------------------------------ | --- | -| `editor.context` | 编辑器右键菜单 | 1.0 | -| `projectView.context` | 项目工具窗口右键菜单 | 1.0 | -| `editorTab.context` | 编辑器标签页右键菜单 | 1.0 | -| `tools` | 主菜单中的 **工具** | 1.0 | -| `viewItem.context` | 插件自有视图中条目的右键菜单(需要 `view`) | 1.2 | -| `commit.message` | 提交信息上方的工具栏(提交工具窗口和提交对话框) | 1.3 | -| `editor.title` | 编辑器标签栏的动作区 | 1.4 | -| `mainToolbar` | 主工具栏 | 1.4 | -| `problems.context` | 问题工具窗口中问题条目的右键菜单 | 1.4 | -| `searchResults.context` | 搜索结果的右键菜单 | 1.4 | +| `menu` | 位置 | API | +| ----------------------- | ---------------------------------------------------- | ---- | +| `editor.context` | 编辑器右键菜单 | 1.0 | +| `projectView.context` | 项目工具窗口右键菜单 | 1.0 | +| `editorTab.context` | 编辑器标签页右键菜单 | 1.0 | +| `tools` | 主菜单中的 **工具** | 1.0 | +| `viewItem.context` | 插件自有视图中条目的右键菜单(需要 `view`) | 1.2 | +| `commit.message` | 提交信息上方的工具栏(提交工具窗口和提交对话框) | 1.3 | +| `editor.title` | 编辑器标签栏的动作区 | 1.4 | +| `mainToolbar` | 主工具栏 | 1.4 | +| `problems.context` | 问题工具窗口中问题条目的右键菜单 | 1.4 | +| `searchResults.context` | 搜索结果的右键菜单 | 1.4 | +| `services.context` | IDE 自带 Services 节点(运行配置、Docker)的右键菜单 | 1.18 | +| `services.toolbar` | 选中 IDE 自带节点时的 Services 工具栏 | 1.18 | 使用 1.0 之后加入的菜单,需要在 `engines.openidea` 中至少声明对应的 API 版本。每个条目都必须指向插件声明过的命令。 菜单的 `when` 与命令自身的 `when` 同时生效。 @@ -185,6 +187,24 @@ command = "kube.logs" when = "viewItemKind == pod" ``` +**Services 菜单**(API 1.18)。`services.context` 和 `services.toolbar` 作用于 IDE 自己放进 Services 的节点: +运行配置和 Docker 容器。`when` 可以对每个选中的服务使用 `serviceProvider`(`runConfigurations` 或 `docker`)、 +`serviceKind`(运行配置类型,例如 `spring-boot`;容器为 `docker-container`)、`serviceId`、`serviceName`、 +`serviceRunning`、`runConfigurationId`(容器为空)和 `serviceSelectionCount`。只有 `when` 对每个选中的服务都成立时 +才显示该条目。命令参数是 JSON 文本:`{"services": [{"provider", "id", "kind", "name", "running", "runConfigurationId"}]}`。 +工具栏条目显示命令的 `icon`,否则使用插件图标。 + +```toml +[[contributes.menus]] +menu = "services.context" +command = "hotreload.attach" +submenu = "Hot Reload" +when = "serviceKind == 'spring-boot' && serviceRunning" +``` + +要用插件的 Java 代理启动选中的配置,请把代理绑定到执行器(`[[contributes.javaAgents]]` 的 `executor`): +“使用 … 运行”和“使用 … 调试”会出现在运行和调试旁边,也会出现在这个菜单中。 + ## 状态栏项 ```toml diff --git a/docs/zh/plugins/manifest.mdx b/docs/zh/plugins/manifest.mdx index bf1b3f6d3..adcaddfbe 100644 --- a/docs/zh/plugins/manifest.mdx +++ b/docs/zh/plugins/manifest.mdx @@ -126,7 +126,7 @@ optional = ["net:api.openai.com", "secrets"] | `serverCommands` | `server`、`command`、`run`(API 1.9) | 是 | [README:Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) | | `runDetectors` | `id`、`name`、`files`、`command`、`args?`、`test?`、`framework?`、`outputMode?`(API 1.18) | 否 | [运行目标](/zh/plugins/guides/run-targets) | | `runConfigurations` | `files`(API 1.4) | 是 | [运行目标](/zh/plugins/guides/run-targets) | -| `javaAgents` | `path`、`args?`(API 1.10);`vmOptions?`、`jdk?`(API 1.14) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | +| `javaAgents` | `path`、`args?`(API 1.10);`vmOptions?`、`jdk?`(API 1.14);`executor?`(API 1.18) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | | `skills` | `path`(`skills/<name>/SKILL.md`,API 1.15) | 否 | [README:API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | | `mcpTools` | `name`、`description`、`inputSchema`、`readOnly`、`destructive`(API 1.4) | 是 | [MCP 工具](/zh/plugins/guides/mcp) | | `themes` | `path`、`editor-scheme?` | 否 | [主题](/zh/plugins/guides/themes) | diff --git a/docs/zh/plugins/versioning.mdx b/docs/zh/plugins/versioning.mdx index 6b21535f1..00088a247 100644 --- a/docs/zh/plugins/versioning.mdx +++ b/docs/zh/plugins/versioning.mdx @@ -1,35 +1,35 @@ --- title: "API 版本与兼容" -description: "engines.openidea、插件 API 从 1.0 到 1.13 的各个版本,以及让已发布插件在新 IDE 中继续加载的规则。" +description: "engines.openidea、插件 API 从 1.0 到 1.18 的各个版本,以及让已发布插件在新 IDE 中继续加载的规则。" --- -插件 API 只有一个版本号:[`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) 中 WIT 包的版本(`main` 上是 `openidea:plugin@1.14.0`)。宿主的引擎版本和 SDK 的 `API_VERSION` 始终与它一致,SDK 里也带着一份完全相同的 WIT 文件。 +插件 API 只有一个版本号:[`wit/`](https://github.com/l0ng-ai/openidea/tree/main/wit) 中 WIT 包的版本(`main` 上是 `openidea:plugin@1.18.0`)。宿主的引擎版本和 SDK 的 `API_VERSION` 始终与它一致,SDK 里也带着一份完全相同的 WIT 文件。 <Note>插件系统目前是预览版。下面的兼容规则适用于已发布的 1.x 版本;`main` 上尚未发布的内容在发布前仍可能变化。</Note> ## 版本历史 -| API | 随哪个版本发布 | 主要内容 | -| ------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 1.0.0 | OpenIDEA 0.1.36 | 基础 API:命令、事件、存储、任务、项目和编辑器访问、VCS、诊断、网络与密钥、进程、声明式视图和自定义编辑器、设置、编辑器 provider、syntax provider | -| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`、`ui.copy-to-clipboard`、`ui.open-url`,从视图中打开项目文件的指定行 | -| 1.2.0 | OpenIDEA 0.1.38 | 后台文档索引器;选择器、输入框和确认框;插件自定义的 `when` 上下文键;项目视图中选中的文件;清单 `icon`;`viewItem.context` 菜单 | -| 1.3.0 | OpenIDEA 0.1.39 | 提交信息和提交前检查、Services 详情面板、输入时诊断、悬停、内嵌提示、语义 token、改动文件的代码操作、HTTP 端点、项目外文件(`fs.read`/`fs.write`、`project.write`、插件私有目录)、批量 `files-changed` 事件和路径过滤、工作区符号、长时间运行的进程、带按钮的通知、翻译、多页设置、文件模板变量、Web 视图 PTY、日志标签页和内容标签页 | -| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`、`ipc:`、`ide.commands` 和 `database.sources` 能力;编辑器与项目快照、装饰、文本搜索、问题视图、Git log/blame/diff;输出通道;OAuth 回环;运行、终端会话、运行配置、测试结果解析和运行目标;格式化等语言功能;嵌入语言;代码片段;更多菜单位置;数据库数据源;MCP 工具 | -| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify`(只在某个项目的窗口中显示通知)、`net:ask` 能力、运行目标启动前校验、运行目标按命令设置工作目录参数 | -| 1.6.0 | OpenIDEA 0.1.43 | 面向事件流插件、受容量限制且绑定项目的后台 WebSocket | -| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`:在差异查看器中对比两段文本,例如评审中某个文件的修改前后 | -| 1.8.0 | OpenIDEA 0.1.45 | `problems-changed` 工作台事件:宿主按文件保存每个生产者的诊断,注解跟着文件走,而不是跟着调用它的窗口 | -| 1.9.0 | OpenIDEA 0.1.46 | 带环境变量和调试器的运行配置、向正在运行的语言服务器发送请求(`lsp:<server>`)、交给插件处理的服务器命令、编辑器面板 | -| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`:IDE 已解析的 Maven / Gradle 依赖图(`build.read`) | -| 1.11.0 | `main` 上开发中 | `ui.read-clipboard`:在用户运行的命令中读取剪贴板的文本和图片(`clipboard.read`) | -| 1.12.0 | `main` 上开发中 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) | -| 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 | -| 1.14.0 | `main` 上开发中 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 | -| 1.15.0 | `main` 上开发中 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills/<name>/SKILL.md"`),在插件包中打包代理技能 | -| 1.16.0 | OpenIDEA 0.1.52 | 可选 `completion-list-provider` 导出:标记为不完整的补全在继续输入时再次询问,不会重新询问语言服务器和其他插件;`decorations.set-markdown`:悬停显示 Markdown 卡片的行尾装饰 | -| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 | -| 1.18.0 | `main` 上开发中 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段 | +| API | 随哪个版本发布 | 主要内容 | +| ------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1.0.0 | OpenIDEA 0.1.36 | 基础 API:命令、事件、存储、任务、项目和编辑器访问、VCS、诊断、网络与密钥、进程、声明式视图和自定义编辑器、设置、编辑器 provider、syntax provider | +| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`、`ui.copy-to-clipboard`、`ui.open-url`,从视图中打开项目文件的指定行 | +| 1.2.0 | OpenIDEA 0.1.38 | 后台文档索引器;选择器、输入框和确认框;插件自定义的 `when` 上下文键;项目视图中选中的文件;清单 `icon`;`viewItem.context` 菜单 | +| 1.3.0 | OpenIDEA 0.1.39 | 提交信息和提交前检查、Services 详情面板、输入时诊断、悬停、内嵌提示、语义 token、改动文件的代码操作、HTTP 端点、项目外文件(`fs.read`/`fs.write`、`project.write`、插件私有目录)、批量 `files-changed` 事件和路径过滤、工作区符号、长时间运行的进程、带按钮的通知、翻译、多页设置、文件模板变量、Web 视图 PTY、日志标签页和内容标签页 | +| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`、`ipc:`、`ide.commands` 和 `database.sources` 能力;编辑器与项目快照、装饰、文本搜索、问题视图、Git log/blame/diff;输出通道;OAuth 回环;运行、终端会话、运行配置、测试结果解析和运行目标;格式化等语言功能;嵌入语言;代码片段;更多菜单位置;数据库数据源;MCP 工具 | +| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify`(只在某个项目的窗口中显示通知)、`net:ask` 能力、运行目标启动前校验、运行目标按命令设置工作目录参数 | +| 1.6.0 | OpenIDEA 0.1.43 | 面向事件流插件、受容量限制且绑定项目的后台 WebSocket | +| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`:在差异查看器中对比两段文本,例如评审中某个文件的修改前后 | +| 1.8.0 | OpenIDEA 0.1.45 | `problems-changed` 工作台事件:宿主按文件保存每个生产者的诊断,注解跟着文件走,而不是跟着调用它的窗口 | +| 1.9.0 | OpenIDEA 0.1.46 | 带环境变量和调试器的运行配置、向正在运行的语言服务器发送请求(`lsp:<server>`)、交给插件处理的服务器命令、编辑器面板 | +| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`:IDE 已解析的 Maven / Gradle 依赖图(`build.read`) | +| 1.11.0 | `main` 上开发中 | `ui.read-clipboard`:在用户运行的命令中读取剪贴板的文本和图片(`clipboard.read`) | +| 1.12.0 | `main` 上开发中 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) | +| 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 | +| 1.14.0 | `main` 上开发中 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 | +| 1.15.0 | `main` 上开发中 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills/<name>/SKILL.md"`),在插件包中打包代理技能 | +| 1.16.0 | OpenIDEA 0.1.52 | 可选 `completion-list-provider` 导出:标记为不完整的补全在继续输入时再次询问,不会重新询问语言服务器和其他插件;`decorations.set-markdown`:悬停显示 Markdown 卡片的行尾装饰 | +| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 | +| 1.18.0 | `main` 上开发中 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 <title> 运行/调试 '<name>'”,只有经它启动时才加载该代理;需授权的 `agents.fork-session`:把录制的原生 agent 会话(`claude` 或 `codex`)派生为调用窗口项目中的新任务(`agents` 能力),宿主自行校验会话并构造 fork 调用 | 每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。 diff --git a/docs/zh/reference/settings.mdx b/docs/zh/reference/settings.mdx index d7b8bb0e9..bab3290a8 100644 --- a/docs/zh/reference/settings.mdx +++ b/docs/zh/reference/settings.mdx @@ -55,7 +55,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"] | 插件 | 插件 | | 版本控制 | 提交;确认;目录映射;问题导航;日志;搁置;Git;GitHub | | 构建、执行、部署 | CMake;Gradle;Maven;控制台;调试器(数据视图、单步执行);Python 调试器;运行/调试;运行目标;部署(选项) | -| 语言和框架 | 语言服务器;Go(构建标签、Go 模块);Java;Markdown;Node.js;PHP;Python 解释器;Prettier;oxfmt;Biome;Ruff;Black 格式化工具;Ruby;Rust;TypeScript | +| 语言和框架 | 语言服务器;Go(构建标签、Go 模块);Java;Markdown;Node.js;PHP;Python 解释器;Prettier;oxfmt;Biome;dprint;Ruff;Black 格式化工具;Ruby;Rust;TypeScript | | 工具 | 智能体(聊天);终端;保存时操作;外部工具;SSH 配置;MCP 服务器 | | 安全 | 项目信任 | @@ -90,7 +90,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"] | `dateFormat.overrideSystem` | `false` | **覆盖系统日期和时间格式**(日期格式页)。 | | `dateFormat.pattern` | `"dd.MM.yyyy"` | 日期格式,可用 `dd`、`MM`、`MMM`、`yy`、`yyyy`。 | | `dateFormat.use24Hour` | `true` | 使用 24 小时制。 | -| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间。 | +| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间(列表中带时间,注解装订区域仅显示日期)。 | ### `[appearance]` diff --git a/e2e/agentLaunchArguments.spec.ts b/e2e/agentLaunchArguments.spec.ts new file mode 100644 index 000000000..c552b6ca3 --- /dev/null +++ b/e2e/agentLaunchArguments.spec.ts @@ -0,0 +1,76 @@ +import type { Page } from "@playwright/test"; +import type { AgentProvider } from "../src/bindings"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +async function openAgents(page: Page) { + // Load the Settings module in the Vite browser realm, not Playwright's Node process. + const settings = "/src/features/settings/model/staging.ts"; + await page.evaluate(async (path) => (await import(/* @vite-ignore */ path)).openSettings("agents.list"), settings); + return page.getByRole("dialog", { name: "Settings", exact: true }); +} + +test("applies and resets built-in ACP arguments without changing the executable or environment", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await page.evaluate(() => { + let extra: string[] = []; + Object.assign(window.__ipc.handlers, { + agent_providers: () => { + const provider = { + id: "omp", + name: "OMP", + command: "/opt/my tools/omp acp", + program: "/opt/my tools/omp", + args: ["acp", ...extra], + additionalArgs: extra, + defaultProgram: "omp", + defaultArgs: ["acp"], + loginHint: null, + commandOverridden: true, + commandEditable: true, + commandReadOnlyReason: null, + installed: true, + env: { OMP_SETTING: "value" }, + config: [], + commands: [], + source: { kind: "builtin" }, + } satisfies AgentProvider; + return [provider]; + }, + agent_registry_list: () => ({ agents: [], warning: null }), + agent_set_additional_args: ({ args }: { args: string[] }) => { + extra = args; + return null; + }, + settings_get_global: () => ({}), + }); + }); + const dialog = await openAgents(page); + const launch = dialog.getByRole("region", { name: "Launch" }); + await expect(launch.getByRole("textbox", { name: "Executable" })).toHaveValue("/opt/my tools/omp"); + const args = launch.getByRole("textbox", { name: "Additional arguments" }); + const apply = dialog.getByRole("button", { name: "Apply", exact: true }); + + await args.fill('--label "two words" ""'); + await apply.click(); + await expect(launch.getByText("'/opt/my tools/omp' acp --label 'two words' ''", { exact: true })).toBeVisible(); + expect(await ipcCalls(page, "agent_set_additional_args")).toEqual([ + { id: "omp", args: ["--label", "two words", ""] }, + ]); + + await args.fill("--discard"); + await dialog.getByRole("button", { name: "Cancel", exact: true }).click(); + await openAgents(page); + await expect(args).toHaveValue("--label 'two words' ''"); + await launch.getByRole("button", { name: "Reset additional arguments" }).click(); + await apply.click(); + await expect(launch.getByText("'/opt/my tools/omp' acp", { exact: true })).toBeVisible(); + await expect(args).toHaveValue(""); + await expect(launch.getByRole("textbox", { name: "Executable" })).toHaveValue("/opt/my tools/omp"); + await expect(launch.getByRole("textbox", { name: "Environment variables" })).toHaveValue("OMP_SETTING=value"); + expect(await ipcCalls(page, "agent_set_additional_args")).toEqual([ + { id: "omp", args: ["--label", "two words", ""] }, + { id: "omp", args: [] }, + ]); +}); diff --git a/e2e/branchesPopupRepoAim.spec.ts b/e2e/branchesPopupRepoAim.spec.ts new file mode 100644 index 000000000..019fe857b --- /dev/null +++ b/e2e/branchesPopupRepoAim.spec.ts @@ -0,0 +1,101 @@ +/** + * Git Branches of a project with several repositories: the current repository is listed first, + * and moving the pointer from a repository row toward its open branch list keeps that list open + * while it crosses the other repository rows (like a submenu of a menu). Git is stubbed at the + * IPC layer. + */ +import type { Page } from "@playwright/test"; +import { expect, stubDesktop, test } from "./fixtures"; + +const ROOTS = ["/dev/acme/app", "/dev/acme/lib", "/dev/acme/tools", "/dev/acme/web"]; + +async function openBranches(page: Page) { + await stubDesktop(page); + await page.evaluate( + async ({ roots }) => { + const h = window.__ipc.handlers; + const branch = (name: string, current = false) => ({ + name, + current, + remote: false, + upstream: null, + ahead: 0, + behind: 0, + lastCommitMs: null, + commit: "1111111", + }); + const repoName = (root: string) => root.split("/").pop()!; + h.vcs_roots = () => + roots.map((root) => ({ root, operation: null, head: "main", headCommit: "1111111", hasRemotes: false })); + h.vcs_branch_info = () => ({ + head: "main", + headCommit: "1111111", + upstream: null, + ahead: 0, + behind: 0, + operation: null, + }); + h.vcs_status = () => []; + h.vcs_tags = () => []; + h.vcs_branches = (args: { repo?: string | null }) => [ + branch("main", true), + branch(`only-${repoName(args?.repo ?? roots[0]!)}`), + ]; + const vcsModule = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow, loadBranches } = await import(/* @vite-ignore */ vcsModule); + // The window works on the third repository. + useVcs.setState({ available: true, root: roots[0], repo: roots[2], branchesLoaded: false }); + await refreshNow(); + await loadBranches(); + const actionsModule = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsModule); + await executeAction("vcs.branches"); + }, + { roots: ROOTS }, + ); + const list = page.getByRole("listbox", { name: "Repositories and branches" }); + await expect(list).toBeVisible(); + return list; +} + +const center = async (locator: ReturnType<Page["locator"]>) => { + const box = (await locator.boundingBox())!; + return { x: box.x + box.width / 2, y: box.y + box.height / 2, box }; +}; + +test("multi-repository Git Branches lists the current repository first and keeps a branch list open on the way to it", async ({ + workbench: page, +}) => { + const list = await openBranches(page); + const rows = list.getByRole("option").filter({ has: page.locator("[data-row-key^='repo:']") }); + await expect(rows).toHaveCount(4); + await expect(rows.first()).toContainText("tools"); + + // Open the first repository's branches, then head diagonally into the list across the rows below. + const first = await center(rows.nth(0)); + await page.mouse.move(first.x, first.y); + const branchesOfTools = page.getByRole("dialog", { name: "Branches of tools" }); + await expect(branchesOfTools).toBeVisible(); + const target = (await branchesOfTools.boundingBox())!; + const last = await center(rows.nth(3)); + await page.mouse.move(target.x + 12, last.y, { steps: 12 }); + await expect(branchesOfTools).toBeVisible(); + await expect(branchesOfTools.getByText("only-tools", { exact: true })).toBeVisible(); + + // Moving straight onto another repository row switches to its branches. + const second = await center(rows.nth(1)); + await page.mouse.move(second.x - 40, second.y); + await page.mouse.move(second.x - 60, second.y); + const branchesOfApp = page.getByRole("dialog", { name: "Branches of app" }); + await expect(branchesOfApp).toBeVisible(); + await expect(branchesOfTools).toBeHidden(); + + // Stopping on a row while heading for the open list switches only after a short delay. + const third = await center(rows.nth(2)); + const appList = (await branchesOfApp.boundingBox())!; + await page.mouse.move(appList.x - 30, second.y); + await page.mouse.move(appList.x - 6, third.y); + await expect(branchesOfApp).toBeVisible(); + await expect(page.getByRole("dialog", { name: "Branches of lib" })).toBeVisible(); + await expect(branchesOfApp).toBeHidden(); +}); diff --git a/e2e/copyPathLayout.spec.ts b/e2e/copyPathLayout.spec.ts index 8d67729a9..d04c3a1cc 100644 --- a/e2e/copyPathLayout.spec.ts +++ b/e2e/copyPathLayout.spec.ts @@ -41,3 +41,19 @@ test("Copy Path/Reference keeps its preview and shortcut visible and can be resi await expect(popup).toBeHidden(); await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(path); }); + +test("Copy Path/Reference… in the Project view previews what each row copies", async ({ workbench: page, context }) => { + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await page.getByRole("treeitem", { name: "build.gradle.kts" }).click({ button: "right" }); + await page.getByRole("menuitem", { name: "Copy Path/Reference…" }).click(); + + const popup = page.getByRole("dialog", { name: "Copy Path/Reference…" }); + const name = popup.getByRole("option", { name: /^File Name/ }); + await expect(name.locator('[title="build.gradle.kts"]')).toBeVisible(); + await expect(popup.getByRole("option", { name: /^Path From Content Root/ })).toBeVisible(); + await page.keyboard.type("file name"); + await expect(name).toHaveAttribute("aria-selected", "true"); + await page.keyboard.press("Enter"); + await expect(popup).toBeHidden(); + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("build.gradle.kts"); +}); diff --git a/e2e/databaseResultTabs.spec.ts b/e2e/databaseResultTabs.spec.ts index 7cc55326d..8b7c3cbff 100644 --- a/e2e/databaseResultTabs.spec.ts +++ b/e2e/databaseResultTabs.spec.ts @@ -411,7 +411,8 @@ test("rename owns deletion and Cmd+Enter without editing the previously focused await page.keyboard.press("Meta+a"); const query = "SELECT 'keep this query';\nSELECT 2;"; await page.keyboard.insertText(query); - await page.keyboard.press("Meta+ArrowUp"); + // Caret on the first line (Cmd+Up is Jump to Navigation Bar, not a caret move). + await content.locator(".cm-line").first().click(); await expect(content).toHaveText(query.replace("\n", "")); await choose(page, "Result 1", "Rename Tab"); @@ -439,8 +440,7 @@ test("rename owns deletion and Cmd+Enter without editing the previously focused await expect(content).toHaveText(query.replace("\n", "")); // The editor's own Delete Line shortcut still works after the dialog closes. - await content.click(); - await page.keyboard.press("Meta+ArrowUp"); + await content.locator(".cm-line").first().click(); await page.keyboard.press("Meta+Backspace"); await expect(content.locator(".cm-line").filter({ hasText: /SELECT/ })).toHaveCount(1); }); diff --git a/e2e/extractTypeAlias.spec.ts b/e2e/extractTypeAlias.spec.ts new file mode 100644 index 000000000..b099c0a32 --- /dev/null +++ b/e2e/extractTypeAlias.spec.ts @@ -0,0 +1,113 @@ +import type { Page } from "@playwright/test"; +import { expect, stubDesktop, test } from "./fixtures"; + +const file = "/dev/acme-api/shapes.ts"; +const literal = "{ width: number; height: number }"; +const text = `export function area(shape: ${literal}): number {\n return shape.width * shape.height;\n}\n`; + +/** Opens `file`, stubs tsserver with `actions` (titles and kinds as typescript-language-server reports them) and selects the type literal. */ +async function open(page: Page, actions: { title: string; kind: string; declaration: string }[]) { + await page.evaluate( + async ({ file, text }) => { + const backend = "/src/editor/core/backend.ts"; + (await import(/* @vite-ignore */ backend)).docBackend().files.set(file, text); + const contributions = "/src/workbench/contributions.ts"; + await (await import(/* @vite-ignore */ contributions)).editorService().openFile(file, { focus: true }); + }, + { file, text }, + ); + const content = page.locator(".cm-editor .cm-content").first(); + await expect(content).toContainText("export function area"); + await stubDesktop(page); + await page.evaluate( + ({ actions, literal }) => { + const toAction = (a: (typeof actions)[number]) => ({ + title: a.title, + kind: a.kind, + isPreferred: false, + disabledReason: null, + edit: null, + command: null, + data: a.declaration, + server: 1, + }); + window.__ipc.handlers.lsp_code_action_query = () => ({ actions: actions.map(toAction), advertisedKinds: null }); + window.__ipc.handlers.lsp_resolve_code_action = (args) => args.action; + // tsserver's edit: the declaration above the function, its name in place of the literal. + window.__ipc.handlers.lsp_execute_code_action = async (args) => { + const api = "/src/editor/api.ts"; + const { view } = (await import(/* @vite-ignore */ api)).activeEditor(); + const doc = view.state.doc.toString(); + const from = doc.indexOf(literal); + view.dispatch({ + changes: [ + { from: 0, insert: `${(args.action as { data: string }).data}\n\n` }, + { from, to: from + literal.length, insert: "NewType" }, + ], + }); + return []; + }; + }, + { actions, literal }, + ); + await page.evaluate( + async ({ literal }) => { + const api = "/src/editor/api.ts"; + const { view } = (await import(/* @vite-ignore */ api)).activeEditor(); + const from = view.state.doc.toString().indexOf(literal); + view.dispatch({ selection: { anchor: from, head: from + literal.length } }); + }, + { literal }, + ); + return content; +} + +async function refactorMenu(page: Page, content: ReturnType<Page["locator"]>, item: string) { + await content + .locator(".cm-line") + .first() + .click({ button: "right", position: { x: 260, y: 8 } }); + await page.getByRole("menuitem", { name: "Refactor", exact: true }).hover(); + await page.getByRole("menuitem", { name: new RegExp(`^${item}`) }).click(); +} + +test("Extract Type Alias… declares a type from the selection and renames it in place", async ({ workbench: page }) => { + const content = await open(page, [ + { title: "Extract to type alias", kind: "refactor.extract.type", declaration: `type NewType = ${literal};` }, + { + title: "Extract to interface", + kind: "refactor.extract.interface", + declaration: "interface NewType {\n width: number;\n height: number;\n}", + }, + ]); + await refactorMenu(page, content, "Extract Type Alias…"); + await expect(content).toContainText(`type NewType = ${literal};`); + await expect(content.locator(".cm-lsp-inplace-primary")).toHaveText("NewType"); + await page.keyboard.type("Size"); + await page.keyboard.press("Enter"); + await expect(content.locator(".cm-lsp-inplace")).toHaveCount(0); + await expect(content).toContainText(`type Size = ${literal};`); + await expect(content).toContainText("area(shape: Size)"); +}); + +test("Extract Interface… in TypeScript runs tsserver's Extract to interface", async ({ workbench: page }) => { + const content = await open(page, [ + { title: "Extract to type alias", kind: "refactor.extract.type", declaration: `type NewType = ${literal};` }, + { + title: "Extract to interface", + kind: "refactor.extract.interface", + declaration: "interface NewType {\n width: number;\n height: number;\n}", + }, + ]); + await refactorMenu(page, content, "Extract Interface…"); + await expect(content).toContainText("interface NewType {"); + await expect(content.locator(".cm-lsp-inplace-primary")).toHaveText("NewType"); +}); + +test("says why when tsserver has no type to extract at the selection", async ({ workbench: page }) => { + const content = await open(page, []); + await refactorMenu(page, content, "Extract Interface…"); + await expect(page.getByRole("status")).toHaveText( + "Cannot perform refactoring. Selected block should represent an object type", + ); +}); diff --git a/e2e/imageDiff.spec.ts b/e2e/imageDiff.spec.ts new file mode 100644 index 000000000..229bca371 --- /dev/null +++ b/e2e/imageDiff.spec.ts @@ -0,0 +1,248 @@ +import type { Page } from "@playwright/test"; +import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures"; + +const ROOT = "/dev/acme-api"; + +async function pngVersions(page: Page) { + return page.evaluate(() => { + const canvas = document.createElement("canvas"); + canvas.width = 4; + canvas.height = 3; + const ctx = canvas.getContext("2d")!; + ctx.fillStyle = "teal"; + ctx.fillRect(0, 0, 4, 3); + const head = canvas.toDataURL(); + ctx.clearRect(2, 1, 1, 1); + ctx.fillStyle = "rgba(0, 128, 128, 0.5)"; + ctx.fillRect(2, 1, 1, 1); + const index = canvas.toDataURL(); + ctx.clearRect(0, 0, 2, 1); + return { head, index, local: canvas.toDataURL() }; + }); +} + +async function expectCount(page: Page, count: number) { + await expect( + page.getByRole("status").filter({ hasText: new RegExp(`^${count} changed pixels?$`, "i") }), + ).toBeVisible(); +} + +test("Commit Changes renders a PNG and highlights one alpha-only change", async ({ workbench: page }) => { + await openFromTree(page, "build.gradle.kts"); + await stubDesktop(page); + const { head, index: local } = await pngVersions(page); + const file = "status.png"; + const path = ROOT + "/" + file; + await page.evaluate( + async ({ root, path, file, head, local }) => { + const handlers = window.__ipc.handlers; + const branch = { head: "main", headCommit: "1111111", operation: null, upstream: null, ahead: 0, behind: 0 }; + handlers.vcs_roots = () => [{ root, ...branch }]; + handlers.vcs_branch_info = () => branch; + handlers.vcs_branches = () => []; + handlers.vcs_stashes = () => []; + handlers.vcs_status = () => [{ path, relPath: file, staged: null, unstaged: "modified", renamedFrom: null }]; + handlers.vcs_image_at = ({ rev }) => (rev === "HEAD" ? head : null); + handlers.fs_read_image = () => local; + const store = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ store); + useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); + await refreshNow(); + }, + { root: ROOT, path, file, head, local }, + ); + await page.keyboard.press("Meta+k"); + await page.getByRole("tree", { name: "Changes" }).getByText(file, { exact: true }).dblclick(); + const toolbar = page.getByRole("toolbar", { name: "Image diff" }); + const highlight = toolbar.getByRole("button", { name: "Highlight changed pixels" }); + await highlight.click(); + await expectCount(page, 1); + const mask = page.getByLabel("Pixel difference mask"); + await expect(mask).toBeVisible(); + const pixels = await mask.evaluate((element) => { + const canvas = element as HTMLCanvasElement; + const data = canvas.getContext("2d")!.getImageData(0, 0, canvas.width, canvas.height).data; + return Array.from({ length: canvas.width * canvas.height }, (_, i) => data.slice(4 * i, 4 * i + 4).join(",")); + }); + expect(pixels).toHaveLength(12); + expect(pixels.filter((pixel) => pixel !== pixels[0])).toEqual([pixels[6]]); + expect(pixels[6]).not.toBe(pixels[0]); + await highlight.click(); + await expect(mask).toBeHidden(); + expect(await ipcCalls(page, "vcs_image_at")).toContainEqual({ path, rev: "HEAD" }); + expect(await ipcCalls(page, "fs_read_image")).toContainEqual({ path }); +}); + +test("staged and unstaged PNG diffs compare the index with the specified side", async ({ workbench: page }) => { + await stubDesktop(page); + const images = await pngVersions(page); + await page.evaluate(({ head, index, local }) => { + window.__ipc.handlers.vcs_image_at = ({ rev }) => (rev === "HEAD" ? head : rev === ":0" ? index : null); + window.__ipc.handlers.fs_read_image = () => local; + }, images); + for (const [side, count] of [ + ["staged", 1], + ["unstaged", 2], + ] as const) { + await page.evaluate( + async ({ side, root }) => { + const input = "/src/features/vcs/diffInput.ts"; + const { openDiff, workingDiffData } = await import(/* @vite-ignore */ input); + const path = root + "/status.png"; + const status = { path, relPath: "status.png", staged: "modified", unstaged: "modified", renamedFrom: null }; + await openDiff(workingDiffData(path, undefined, side, status)); + }, + { side, root: ROOT }, + ); + const highlight = page.getByRole("button", { name: "Highlight changed pixels" }); + await highlight.click(); + await expectCount(page, count); + await highlight.click(); + } +}); + +test("the three-way PNG diff labels each revision and compares all three pairs", async ({ workbench: page }) => { + await stubDesktop(page); + const images = await pngVersions(page); + await page.evaluate(async ({ head, index, local }) => { + window.__ipc.handlers.vcs_image_at = ({ rev }) => (rev === "HEAD" ? head : rev === ":0" ? index : null); + window.__ipc.handlers.fs_read_image = () => local; + const input = "/src/features/vcs/diffInput.ts"; + const { openDiff, stagingGutterDiffData } = await import(/* @vite-ignore */ input); + await openDiff(stagingGutterDiffData("/dev/acme-api/status.png")); + }, images); + for (const [label, url] of [ + ["HEAD", images.head], + ["Staged (index)", images.index], + ["Local Version", images.local], + ] as const) { + await expect(page.getByRole("img", { name: label, exact: true })).toHaveAttribute("src", url); + } + const toolbar = page.getByRole("toolbar", { name: "Image diff" }); + await toolbar.getByRole("button", { name: "Highlight changed pixels" }).click(); + await expectCount(page, 1); + for (const [pair, count] of [ + ["Staged (index) ↔ Local Version", 2], + ["HEAD ↔ Local Version", 3], + ] as const) { + await toolbar.getByRole("button", { name: "Compare revisions" }).click(); + await page.getByRole("option", { name: pair }).click(); + await expectCount(page, count); + } +}); + +for (const ext of ["jpg", "jpeg", "webp", "svg"] as const) { + test(`renders both historical revisions of a renamed .${ext} without a working file`, async ({ workbench: page }) => { + await stubDesktop(page); + const path = `${ROOT}/current.${ext}`; + const oldPath = `${ROOT}/original.${ext}`; + await page.evaluate( + async ({ path, oldPath, ext }) => { + const before = + '<svg xmlns="http://www.w3.org/2000/svg" width="8" height="6"><rect width="8" height="6"/></svg>'; + const after = before.replace("<rect ", '<rect id="same-shape" '); + const url = (source: string) => "data:image/svg+xml;base64," + btoa(source); + const canvas = document.createElement("canvas"); + canvas.width = 8; + canvas.height = 6; + const ctx = canvas.getContext("2d")!; + const encode = (color: string) => { + ctx.fillStyle = color; + ctx.fillRect(0, 0, 8, 6); + // WebKit can decode WebP even when its canvas encoder would return PNG. + if (ext === "webp") { + const bytes = + color === "white" + ? "UklGRiIAAABXRUJQVlA4TBYAAAAvB0ABAAfQ//73v/8BgCD8b5uI6H8I" + : "UklGRiAAAABXRUJQVlA4TBMAAAAvB0ABAAcQEf0PAAThf9tERP9DAA=="; + return "data:image/webp;base64," + bytes; + } + return canvas.toDataURL("image/jpeg"); + }; + const left = ext === "svg" ? url(before) : encode("white"); + const right = ext === "svg" ? url(after) : encode("black"); + const handlers = window.__ipc.handlers; + handlers.vcs_image_at = (args) => { + if (args.path === oldPath && args.rev === "11111111") return left; + if (args.path === path && args.rev === "22222222") return right; + return null; + }; + handlers.vcs_file_at = (args) => (args.path === oldPath ? before : after); + const input = "/src/features/vcs/diffInput.ts"; + const { openDiff, commitFileDiffData } = await import(/* @vite-ignore */ input); + await openDiff( + commitFileDiffData( + { id: "22222222", shortId: "22222222", parents: ["11111111"], repo: "/dev/acme-api" }, + { path: "current." + ext, oldPath: "original." + ext, kind: "renamed" }, + ), + ); + }, + { path, oldPath, ext }, + ); + const toolbar = page.getByRole("toolbar", { name: "Image diff" }); + await toolbar.getByRole("button", { name: "Highlight changed pixels" }).click(); + await expectCount(page, ext === "svg" ? 0 : 48); + expect(await ipcCalls(page, "fs_read_image")).toEqual([]); + if (ext === "svg") { + await toolbar.getByRole("button", { name: "View source diff" }).click(); + const xml = page.locator(".cm-content").filter({ hasText: "same-shape" }); + await expect(xml).toBeVisible(); + await page.getByRole("button", { name: "Image preview" }).click(); + await expect(xml).toBeHidden(); + await expect(page.getByRole("button", { name: "View source diff" })).toBeVisible(); + } + }); +} + +// Identical opaque teal RGBA rows encoded with zlib levels 0 and 9. The cropped version removes the rightmost column. +const originalPng = + "iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAPklEQVR4AQEzAMz/AACAgP8AgID/AICA/wCAgP8AAICA/wCAgP8AgID/AICA/wAAgID/AICA/wCAgP8AgID/UTEX9btCu2YAAAAASUVORK5CYII="; +const recompressedPng = + "iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAEUlEQVR42mNgaGj4j4IJCgAAUTEX9X/prpgAAAAASUVORK5CYII="; +const croppedPng = + "iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAYAAABWKLW/AAAAEElEQVR42mNgaGj4D8c4OQBRFBH4p8q4GwAAAABJRU5ErkJggg=="; + +for (const [scenario, count] of [ + ["recompressed", 0], + ["cropped", 3], + ["added", 12], + ["deleted", 12], +] as const) { + test(`shows ${count} changed pixels for historical PNGs (${scenario})`, async ({ workbench: page }) => { + await stubDesktop(page); + await page.evaluate( + async ({ scenario, before, after }) => { + const input = "/src/features/vcs/diffInput.ts"; + const { openDiff, commitFileDiffData } = await import(/* @vite-ignore */ input); + window.__ipc.handlers.vcs_image_at = ({ rev }) => + "data:image/png;base64," + (rev === "11111111" ? before : after); + const kind = scenario === "added" || scenario === "deleted" ? scenario : "modified"; + await openDiff( + commitFileDiffData( + { id: "22222222", shortId: "22222222", parents: ["11111111"], repo: "/dev/acme-api" }, + { path: "snapshot.png", kind }, + ), + ); + }, + { scenario, before: originalPng, after: scenario === "cropped" ? croppedPng : recompressedPng }, + ); + if (scenario === "added" || scenario === "deleted") { + const missing = scenario === "added" ? "(does not exist)" : "(deleted)"; + await expect(page.getByRole("region", { name: missing }).getByText("No image on this side")).toBeVisible(); + const rev = scenario === "added" ? "22222222" : "11111111"; + await expect(page.getByRole("img", { name: rev })).toBeVisible(); + const reads = await ipcCalls(page, "vcs_image_at"); + expect(new Set(reads.map((call) => call.rev))).toEqual(new Set([rev])); + } + await page.getByRole("button", { name: "Highlight changed pixels" }).click(); + await expectCount(page, count); + if (scenario === "cropped") { + const changed = await page.getByLabel("Pixel difference mask").evaluate((element) => { + const ctx = (element as HTMLCanvasElement).getContext("2d")!; + const rgba = ctx.getImageData(0, 0, 4, 3).data; + return Array.from({ length: 12 }, (_, i) => i).filter((i) => rgba[i * 4] !== rgba[i * 4 + 1]); + }); + expect(changed).toEqual([3, 7, 11]); + } + }); +} diff --git a/e2e/jdbc-source.spec.ts b/e2e/jdbc-source.spec.ts index ca52768a0..716f16ad7 100644 --- a/e2e/jdbc-source.spec.ts +++ b/e2e/jdbc-source.spec.ts @@ -164,3 +164,78 @@ test("uses a local JDBC profile for a named data source through mocked IPC", asy await expect(choices).toHaveText(["Existing ClickHouse JDBC", "Example local driver"]); await page.screenshot({ path: info.outputPath("jdbc-go-to-driver-dropdown.png"), animations: "disabled" }); }); + +test("opens the named DuckDB source and keeps its connection mode after saving", async ({ workbench: page }, info) => { + await stubDesktop(page); + await page.evaluate(async () => { + let sources: DataSource_Deserialize[] = []; + Object.assign(window.__ipc.handlers, { + db_sources: () => sources, + db_connected: () => [], + db_jdbc_drivers: () => [ + { + id: "duckdb-fixture", + vendor: "duckdb", + name: "DuckDB JDBC", + className: "org.duckdb.DuckDBDriver", + jars: ["/mock/duckdb_jdbc.jar"], + urlTemplate: "jdbc:duckdb:{file}", + }, + ], + db_test: () => "DuckDB (mock)", + db_approve_jdbc_source: () => null, + db_save_sources: ({ sources: next }: { sources: DataSource_Deserialize[] }) => { + sources = next; + }, + }); + const path = "/src/features/database/store.ts"; + (await import(/* @vite-ignore */ path)).openSourceDialog(null); + }); + const dialog = page.getByRole("dialog", { name: "New Data Source", exact: true }); + await dialog.getByRole("button", { name: "Data source type", exact: true }).click(); + await page.getByRole("option", { name: "DuckDB", exact: true }).click(); + const driver = dialog.getByRole("button", { name: "Connection driver" }); + await expect(driver).toHaveText("DuckDB JDBC"); + await driver.click(); + const profile = page.getByRole("option", { name: "DuckDB JDBC", exact: true }); + await expect(profile.locator('svg[width="14"]')).toBeVisible(); + await page.screenshot({ path: info.outputPath("duckdb-driver-list.png"), animations: "disabled" }); + await profile.click(); + await dialog.getByRole("button", { name: "Go to Driver" }).click(); + const manager = page.getByRole("dialog", { name: "JDBC Driver Profiles", exact: true }); + await manager.getByRole("button", { name: "JDBC driver profiles" }).click(); + await expect(profile.locator('svg[width="14"]')).toBeVisible(); + await profile.click(); + await manager.getByRole("button", { name: "Close", exact: true }).last().click(); + await dialog.getByLabel("File:", { exact: true }).fill("/tmp/example.duckdb"); + await expect(dialog.locator("#db-url")).toHaveValue("jdbc:duckdb:/tmp/example.duckdb"); + await dialog.screenshot({ path: info.outputPath("duckdb-file.png"), animations: "disabled" }); + await dialog.getByRole("button", { name: "In memory", exact: true }).click(); + await expect(dialog.locator("#db-url")).toHaveValue("jdbc:duckdb:"); + await dialog.getByRole("button", { name: "Test Connection", exact: true }).click(); + await expect(dialog.getByRole("status")).toContainText("Succeeded"); + await dialog.screenshot({ path: info.outputPath("duckdb-memory.png"), animations: "disabled" }); + await dialog.getByRole("button", { name: "OK", exact: true }).click(); + await expect(dialog).not.toBeVisible(); + const [save] = await ipcCalls(page, "db_save_sources"); + expect(save?.sources).toEqual([ + expect.objectContaining({ + driver: "jdbc", + vendor: "duckdb", + jdbcDriver: "duckdb-fixture", + url: "jdbc:duckdb:", + file: null, + }), + ]); + await page.evaluate(async () => { + const path = "/src/features/database/store.ts"; + const { openSourceDialog, useDatabase } = await import(/* @vite-ignore */ path); + openSourceDialog(useDatabase.getState().sources[0]); + }); + const reopened = page.getByRole("dialog", { name: "Data Source: DuckDB", exact: true }); + await expect(reopened.getByRole("button", { name: "In memory", exact: true })).toHaveAttribute( + "aria-pressed", + "true", + ); + await expect(reopened.getByRole("button", { name: "Connection driver" })).toHaveText("DuckDB JDBC"); +}); diff --git a/e2e/navigateHistory.spec.ts b/e2e/navigateHistory.spec.ts new file mode 100644 index 000000000..00eecf1e7 --- /dev/null +++ b/e2e/navigateHistory.spec.ts @@ -0,0 +1,224 @@ +/** Navigate Back / Forward (⌘[ / ⌘], ⌥⌘← / ⌥⌘→) across text files, non-file editor tabs, and split panes. */ +import type { Page } from "@playwright/test"; +import { expect, test } from "./fixtures"; + +const AGENT_TASKS = [ + { + id: "task-k8s", + title: "Inspect rollout logs", + status: "ready" as const, + isolation: "local" as const, + provider: "codex", + model: null, + cwd: "/dev/acme-api", + branch: null, + base: null, + baseCommit: null, + error: null, + createdMs: 1, + updatedMs: 2, + config: [], + commands: [], + usage: null, + queue: [], + }, + { + id: "task-api", + title: "Refactor health check", + status: "ready" as const, + isolation: "local" as const, + provider: "claude", + model: null, + cwd: "/dev/acme-api", + branch: null, + base: null, + baseCommit: null, + error: null, + createdMs: 1, + updatedMs: 1, + config: [], + commands: [], + usage: null, + queue: [], + }, +]; + +async function seedAgents(page: Page) { + await page.evaluate(async (tasks) => { + const agentsStorePath = "/src/features/agents/store.ts"; + const { useAgents } = await import(/* @vite-ignore */ agentsStorePath); + useAgents.setState({ + loaded: true, + error: null, + providers: [], + tasks: new Map(tasks.map((t) => [t.id, t])), + entries: new Map([ + [ + "task-k8s", + [ + { type: "user", text: "Check why acme-api pod restarted in prod-us-west", attachments: [] }, + { + type: "agent", + text: "Checked `acme-api-7f9b4` rollout events: liveness probe timed out during migration warm-up.", + }, + ], + ], + [ + "task-api", + [ + { type: "user", text: "Simplify /healthz handler in App.tsx", attachments: [] }, + { type: "agent", text: "Ready to split liveness and readiness checks." }, + ], + ], + ]), + unread: new Set(), + docked: null, + homeOpen: false, + sessionLocation: "editor", + }); + }, AGENT_TASKS); +} + +async function activeEditorState(page: Page) { + return page.evaluate(async () => { + const ctrlPath = "/src/editor/core/controller.ts"; + const twPath = "/src/workbench/toolwindows/store.ts"; + const { editorController, useTabs } = await import(/* @vite-ignore */ ctrlPath); + const { useToolWindowLayout } = await import(/* @vite-ignore */ twPath); + return { + key: editorController().activeInput()?.key ?? null, + pane: useTabs.getState().activePane, + toolWindow: useToolWindowLayout.getState().focused, + }; + }); +} + +test("navigates back and forward across text files, agent chat tabs, and terminal editor tabs, skipping closed terminal tabs", async ({ + workbench: page, +}) => { + await seedAgents(page); + + // 1. Open App.tsx. + await page.getByRole("treeitem", { name: "App.tsx", exact: true }).dblclick(); + await expect(page.getByRole("tab", { name: "App.tsx" })).toBeVisible(); + await expect(page.getByRole("textbox", { name: "Editor for /dev/acme-api/App.tsx" })).toBeFocused(); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "file:/dev/acme-api/App.tsx" }); + + // 2. Open an Agent chat tab (no file path). + await page.evaluate(async () => { + const agentsStorePath = "/src/features/agents/store.ts"; + const { openTask } = await import(/* @vite-ignore */ agentsStorePath); + openTask("task-k8s"); + }); + await expect(page.getByRole("tab", { name: "Inspect rollout logs" })).toBeVisible(); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "agent:task-k8s" }); + + // 3. Open a Terminal editor tab (no file path). + await page.evaluate(async () => { + const actionsPath = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsPath); + await executeAction("terminal.newInEditor"); + }); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: expect.stringMatching(/^cli:/) }); + const cliKey = (await activeEditorState(page)).key!; + + // 4. Open README.md. + await page.getByRole("treeitem", { name: "README.md", exact: true }).dblclick(); + await expect(page.getByRole("tab", { name: "README.md" })).toBeVisible(); + await expect(page.getByRole("textbox", { name: "Editor for /dev/acme-api/README.md" })).toBeFocused(); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "file:/dev/acme-api/README.md" }); + + // 5. Move focus to Project tool window, then press ⌘[ — IDEA behavior: goes to the previous editor place (CLI tab), not a tool window. + await page.getByRole("tree", { name: "Project" }).focus(); + await expect.poll(() => activeEditorState(page)).toMatchObject({ toolWindow: "project" }); + + await page.keyboard.press("Meta+["); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: cliKey, toolWindow: null }); + + // 6. Walk Back from Terminal editor tab → Agent chat tab → App.tsx. + await page.keyboard.press("Meta+Alt+ArrowLeft"); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "agent:task-k8s" }); + + await page.keyboard.press("Meta+["); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "file:/dev/acme-api/App.tsx" }); + + // 7. Walk Forward all the way back to README.md. + await page.keyboard.press("Meta+]"); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "agent:task-k8s" }); + + await page.keyboard.press("Meta+Alt+ArrowRight"); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: cliKey }); + + await page.keyboard.press("Meta+]"); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "file:/dev/acme-api/README.md" }); + + // 8. Close the ephemeral CLI terminal tab: Back from README.md skips it and lands directly on the Agent chat tab. + await page.evaluate(async (key) => { + const ctrlPath = "/src/editor/core/controller.ts"; + const { editorController } = await import(/* @vite-ignore */ ctrlPath); + await editorController().closeInput(key); + }, cliKey); + await page.keyboard.press("Meta+["); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "agent:task-k8s" }); +}); + +test("tracks split panes across same-file splits, non-text split tabs, and moved tabs", async ({ workbench: page }) => { + await seedAgents(page); + + // Open App.tsx in left pane and split it right (same file in both panes). + await page.getByRole("treeitem", { name: "App.tsx", exact: true }).dblclick(); + await expect(page.locator("[data-editor-area] .cm-content").first()).toBeFocused(); + const leftPane = (await activeEditorState(page)).pane; + + await page.evaluate(async () => { + const ctrlPath = "/src/editor/core/controller.ts"; + const { editorController, useTabs } = await import(/* @vite-ignore */ ctrlPath); + editorController().split(useTabs.getState().activePane, "row"); + }); + await expect(page.locator("[data-pane-id]")).toHaveCount(2); + const rightPane = (await activeEditorState(page)).pane; + expect(rightPane).not.toBe(leftPane); + await expect(page.locator(`[data-pane-id="${rightPane}"] .cm-content`)).toBeFocused(); + + // Open an Agent chat tab in the right split pane. + await page.evaluate(async () => { + const ctrlPath = "/src/editor/core/controller.ts"; + const { editorController } = await import(/* @vite-ignore */ ctrlPath); + await editorController().openInput( + { kind: "agent-session", key: "agent:task-api", data: { task: "task-api", title: "Refactor health check" } }, + { focus: true }, + ); + }); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "agent:task-api", pane: rightPane }); + + // Click into the left split pane's editor, then click back into the right split pane's Agent chat composer. + await page.locator(`[data-pane-id="${leftPane}"] .cm-content`).click(); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "file:/dev/acme-api/App.tsx", pane: leftPane }); + + await page.locator(`[data-pane-id="${rightPane}"]`).getByRole("textbox", { name: "Message" }).click(); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "agent:task-api", pane: rightPane }); + + // Walk Back through the split-pane history: Agent Chat (right) → App.tsx (left) → Agent Chat (right) → App.tsx (right) → App.tsx (left). + await page.keyboard.press("Meta+["); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "file:/dev/acme-api/App.tsx", pane: leftPane }); + + await page.keyboard.press("Meta+["); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "agent:task-api", pane: rightPane }); + + await page.keyboard.press("Meta+["); + await expect + .poll(() => activeEditorState(page)) + .toMatchObject({ key: "file:/dev/acme-api/App.tsx", pane: rightPane }); + + await page.keyboard.press("Meta+["); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "file:/dev/acme-api/App.tsx", pane: leftPane }); + + // Forward returns across the splits in exact order. + await page.keyboard.press("Meta+]"); + await expect + .poll(() => activeEditorState(page)) + .toMatchObject({ key: "file:/dev/acme-api/App.tsx", pane: rightPane }); + + await page.keyboard.press("Meta+]"); + await expect.poll(() => activeEditorState(page)).toMatchObject({ key: "agent:task-api", pane: rightPane }); +}); diff --git a/e2e/toolwindowIframeFocus.spec.ts b/e2e/toolwindowIframeFocus.spec.ts new file mode 100644 index 000000000..4aec79a12 --- /dev/null +++ b/e2e/toolwindowIframeFocus.spec.ts @@ -0,0 +1,146 @@ +/** Focus activation for tool windows with hidden inputs (docked Agents) and sandboxed plugin webview iframes. */ +import { expect, test } from "./fixtures"; + +const TASK = { + id: "task-1", + title: "Inspect rollout logs", + status: "ready" as const, + isolation: "local" as const, + provider: "codex", + model: null, + cwd: "/dev/acme-api", + branch: null, + base: null, + baseCommit: null, + error: null, + createdMs: 1, + updatedMs: 2, + config: [], + commands: [], + usage: null, + queue: [], +}; + +test("focuses docked Agents tool window instead of getting stuck on its hidden file input", async ({ + workbench: page, +}) => { + await page.getByRole("treeitem", { name: "App.tsx", exact: true }).dblclick(); + await expect(page.getByRole("textbox", { name: "Editor for /dev/acme-api/App.tsx" })).toBeFocused(); + + await page.evaluate(async (task) => { + const agentsStorePath = "/src/features/agents/store.ts"; + const { useAgents, dockTask } = await import(/* @vite-ignore */ agentsStorePath); + useAgents.setState({ + loaded: true, + error: null, + providers: [], + tasks: new Map([[task.id, task]]), + entries: new Map([[task.id, [{ type: "user", text: "Check pods", attachments: [] }]]]), + unread: new Set(), + docked: null, + homeOpen: false, + sessionLocation: "toolWindow", + }); + dockTask(task.id); + }, TASK); + + const agents = page.locator('[data-toolwindow="agents"]'); + await expect(agents).toBeVisible(); + await expect(agents).toHaveAttribute("data-focus-active", ""); + await expect + .poll(() => + page.evaluate(async () => { + const storePath = "/src/workbench/toolwindows/store.ts"; + const { useToolWindowLayout } = await import(/* @vite-ignore */ storePath); + return useToolWindowLayout.getState().focused; + }), + ) + .toBe("agents"); +}); + +test("tracks focus and focus-scope highlighting when clicking into a sandboxed plugin webview iframe", async ({ + workbench: page, +}) => { + await page.getByRole("treeitem", { name: "App.tsx", exact: true }).dblclick(); + await expect(page.getByRole("textbox", { name: "Editor for /dev/acme-api/App.tsx" })).toBeFocused(); + + await page.evaluate(async () => { + const pluginsBackendPath = "/src/features/plugins/backend.ts"; + const pluginsStorePath = "/src/features/plugins/store.ts"; + const bridgeRawPath = "/src/features/plugins/views/frame-bridge.js?raw"; + const { createMemoryPluginsBackend, setPluginsBackend } = await import(/* @vite-ignore */ pluginsBackendPath); + const { usePlugins } = await import(/* @vite-ignore */ pluginsStorePath); + const { default: bridgeSource } = await import(/* @vite-ignore */ bridgeRawPath); + const bridgeFn = bridgeSource.trim().replace(/;\s*$/, ""); + + const html = `<!doctype html> +<html> +<head> +<meta charset="utf-8" /> +<script>(${bridgeFn})(null);</script> +</head> +<body> + <button id="pod-api" type="button">acme-api-7f9b4</button> +</body> +</html>`; + const url = URL.createObjectURL(new Blob([html], { type: "text/html" })); + const base = createMemoryPluginsBackend(); + const template = (await base.list()).plugins[0]!; + const plugin = { ...template, id: "demo.k8s", name: "Kubernetes", status: "active" as const }; + setPluginsBackend({ + ...base, + webPageUrl: async (pluginId: string) => (pluginId === "demo.k8s" ? url : base.webPageUrl(pluginId, "v")), + }); + usePlugins.setState({ + plugins: [plugin], + ui: [ + { + pluginId: "demo.k8s", + point: "views", + key: "kubernetes", + decl: { id: "kubernetes", title: "Kubernetes", location: "right", web: "web/index.html", header: "default" }, + }, + ], + }); + }); + + // Put Project in Undock mode so clicking into the plugin iframe also verifies unpinned/undocked auto-hide. + await page.evaluate(async () => { + const storePath = "/src/workbench/toolwindows/store.ts"; + const { setToolWindowViewMode, focusToolWindow } = await import(/* @vite-ignore */ storePath); + setToolWindowViewMode("project", "undock"); + focusToolWindow("project"); + }); + const project = page.getByRole("region", { name: "Project", exact: true }); + await expect(project).toBeVisible(); + + const k8sStripe = page.locator('[data-stripe-button="plugin.demo.k8s.kubernetes"]'); + await expect(k8sStripe).toBeVisible(); + await k8sStripe.click(); + const k8sRegion = page.locator('[data-toolwindow="plugin.demo.k8s.kubernetes"]'); + await expect(k8sRegion).toBeVisible(); + + await page.frameLocator('iframe[data-plugin-webview="demo.k8s"]').locator("#pod-api").click(); + + await expect(k8sRegion).toHaveAttribute("data-focus-active", ""); + await expect(project).toBeHidden(); + await expect + .poll(() => + page.evaluate(async () => { + const storePath = "/src/workbench/toolwindows/store.ts"; + const ctxPath = "/src/platform/context.ts"; + const { useToolWindowLayout } = await import(/* @vite-ignore */ storePath); + const { getContext } = await import(/* @vite-ignore */ ctxPath); + return { + focused: useToolWindowLayout.getState().focused, + toolWindowFocus: getContext().toolWindowFocus, + activeToolWindow: getContext().activeToolWindow, + }; + }), + ) + .toEqual({ + focused: "plugin.demo.k8s.kubernetes", + toolWindowFocus: true, + activeToolWindow: "plugin.demo.k8s.kubernetes", + }); +}); diff --git a/fixtures/README.md b/fixtures/README.md index afe2b0c32..099471bc0 100644 --- a/fixtures/README.md +++ b/fixtures/README.md @@ -10,8 +10,10 @@ something to show. | `rust-app/` | cargo | `cargo run` | `cargo test` | `cargo test --features failing-tests` | unused variable in `src/parser.rs` | | `ts-app/` | Node 22+, pnpm/npm | `pnpm start` | `pnpm test` (vitest) | `OPENIDEA_FAIL=1 pnpm test` | unused function in `src/index.ts` | | `playwright-app/` | Node 22+, npm (Playwright Test, no browser needed) | — | `npm test` | `OPENIDEA_FAIL=1 npm test` | unused function in `src/checkout.ts` | +| `cypress-app/` | Node 22+, npm (Cypress 16 with its Electron, no server needed) | — | `npm run e2e` | `npm run e2e -- --expose fail=1` | unused function in `src/cart.ts` | | `node-test-app/` | Node 22+, npm (no dependencies) | — | `npm test` (node:test) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/inventory.js` | | `mocha-app/` | Node 22+, npm | — | `npm test` (Mocha) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/pricing.js` | +| `jasmine-app/` | Node 22+, npm | — | `npm test` (Jasmine) | `OPENIDEA_FAIL=1 npm test` | unused constant in `src/cart.js` | | `python-app/` | Python 3.10+, pytest | `python -m tasks.cli` (from `src/`) | `pytest` | `OPENIDEA_FAIL=1 pytest` | unused imports in `models.py` | | `go-app/` | Go 1.22+ | `go run ./cmd/server` | `go test ./...` | `OPENIDEA_FAIL=1 go test ./...` | unused `fmt.Sprintf` result in `internal/store/store.go` | | `kotlin-gradle/` | JDK 21, Gradle 8 (no wrapper) | `gradle run` | `gradle test` | `gradle test -PopenideaFail` | unused variable in `App.kt` | @@ -22,6 +24,7 @@ something to show. | `tailwind-app/` | Node 22+, pnpm/npm, Tailwind CSS 4, React | `pnpm dev` | — | — | `flex` conflicting with `block` in `src/App.tsx` | | `zig-app/` | Zig 0.17 | `zig build run` | `zig build test` | — | — | | `biome-app/` | Node 22+, `@biomejs/biome` (`npm install`) | `npm start` | — | — | `let` never reassigned, `==` and a duplicate CSS `color` (Biome) | +| `dprint-app/` | Node 22+, `dprint` (`npm install`) | `npm start` | — | — | unformatted `src/index.ts` / `src/data.json` (dprint); `README.md` keeps Prettier | | `stylelint-app/` | Node 22+, `stylelint` (`npm install`) | — | — | — | long hex colour, unknown property, empty block, duplicate selector (Stylelint) | | `polyglot/` | Go, TS, Python, C, shell, SQL, TOML/YAML/JSON, proto, Terraform | `make` | `make test` | — | unused variable in `native/hash.c` | @@ -45,7 +48,7 @@ git init -q && git add -A && git commit -qm "initial" # for the VCS checks ``` Then open the folder with **File › Open…** (`⌘⇧⌥O`) or from the Welcome screen. -For `ts-app` / `playwright-app` / `mocha-app` / `polyglot/web` run `pnpm install` first (`npm install` for `biome-app` and `stylelint-app`); for `python-app` create a +For `ts-app` / `playwright-app` / `mocha-app` / `polyglot/web` run `pnpm install` first (`npm install` for `biome-app`, `cypress-app`, `dprint-app` and `stylelint-app`); for `python-app` create a venv (`python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'`); for `php-app` run `composer install` (debugging it needs Xdebug in the PHP on `PATH`). diff --git a/fixtures/cypress-app/.gitignore b/fixtures/cypress-app/.gitignore new file mode 100644 index 000000000..3d8e2cf92 --- /dev/null +++ b/fixtures/cypress-app/.gitignore @@ -0,0 +1,4 @@ +node_modules +cypress/screenshots +cypress/videos +cypress/downloads diff --git a/fixtures/cypress-app/cypress.config.ts b/fixtures/cypress-app/cypress.config.ts new file mode 100644 index 000000000..379149a70 --- /dev/null +++ b/fixtures/cypress-app/cypress.config.ts @@ -0,0 +1,5 @@ +import { defineConfig } from "cypress"; + +export default defineConfig({ + e2e: { video: false, screenshotOnRunFailure: false }, +}); diff --git a/fixtures/cypress-app/cypress/e2e/cart.cy.ts b/fixtures/cypress-app/cypress/e2e/cart.cy.ts new file mode 100644 index 000000000..01ece405e --- /dev/null +++ b/fixtures/cypress-app/cypress/e2e/cart.cy.ts @@ -0,0 +1,33 @@ +import { discount, subtotal, withTax, type Item } from "../../src/cart"; + +const mug: Item = { sku: "mug", price: 12, quantity: 2 }; +const lamp: Item = { sku: "lamp", price: 40, quantity: 1 }; + +describe("cart", () => { + it("adds up the items", () => { + cy.wrap(subtotal([mug, lamp])).should("eq", 64); + }); + + context("totals", () => { + it("adds the tax", () => { + cy.wrap(withTax(64)).should("eq", 70.4); + }); + + // Fails on purpose with `--expose fail=1`. + it("rounds to cents", () => { + cy.wrap(withTax(Cypress.expose("fail") ? 1.01 : 1)).should("eq", 1.1); + }); + }); + + it.skip("keeps the cart between visits", () => {}); +}); + +describe("discounts", () => { + it("halves the total", () => { + expect(discount(64, "HALF")).to.equal(32); + }); + + it("rejects unknown codes", () => { + expect(() => discount(64, "NOPE")).to.throw("unknown code"); + }); +}); diff --git a/fixtures/cypress-app/cypress/support/e2e.ts b/fixtures/cypress-app/cypress/support/e2e.ts new file mode 100644 index 000000000..8420dff48 --- /dev/null +++ b/fixtures/cypress-app/cypress/support/e2e.ts @@ -0,0 +1,4 @@ +// Lets the IDE run single tests, suites and failed tests by title. +import { register } from "@cypress/grep"; + +register(); diff --git a/fixtures/cypress-app/package.json b/fixtures/cypress-app/package.json new file mode 100644 index 000000000..1b4c6ec11 --- /dev/null +++ b/fixtures/cypress-app/package.json @@ -0,0 +1,15 @@ +{ + "name": "openidea-fixture-cart", + "version": "0.1.0", + "private": true, + "description": "OpenIDEA QA fixture: Cypress specs for a cart module (Cypress's own Electron, no server needed)", + "scripts": { + "e2e": "cypress run", + "lint": "tsc -p . --noEmit" + }, + "devDependencies": { + "@cypress/grep": "^7.0.0", + "cypress": "^16.0.0", + "typescript": "^5.6.0" + } +} diff --git a/fixtures/cypress-app/src/cart.ts b/fixtures/cypress-app/src/cart.ts new file mode 100644 index 000000000..4eab9ce4a --- /dev/null +++ b/fixtures/cypress-app/src/cart.ts @@ -0,0 +1,26 @@ +export interface Item { + sku: string; + price: number; + quantity: number; +} + +const TAX_RATE = 0.1; + +export function subtotal(items: Item[]): number { + return items.reduce((sum, i) => sum + i.price * i.quantity, 0); +} + +export function withTax(total: number): number { + // FIXME: tax rates differ by region + return Math.round(total * (1 + TAX_RATE) * 100) / 100; +} + +export function discount(total: number, code: string): number { + if (code === "HALF") return Math.round(total * 50) / 100; + throw new Error(`unknown code: ${code}`); +} + +// An intentional warning: never used. +function roundDown(value: number): number { + return Math.floor(value); +} diff --git a/fixtures/cypress-app/tsconfig.json b/fixtures/cypress-app/tsconfig.json new file mode 100644 index 000000000..cd083c696 --- /dev/null +++ b/fixtures/cypress-app/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noUnusedLocals": true, + "skipLibCheck": true, + "noEmit": true, + "types": ["cypress"] + }, + "include": ["src", "cypress", "cypress.config.ts"] +} diff --git a/fixtures/dprint-app/README.md b/fixtures/dprint-app/README.md new file mode 100644 index 000000000..82898e7f9 --- /dev/null +++ b/fixtures/dprint-app/README.md @@ -0,0 +1,4 @@ +# dprint fixture + +* `src/index.ts` and `src/data.json` are formatted by dprint. +* This file is not: dprint has no Markdown plugin here, so Prettier keeps it. diff --git a/fixtures/dprint-app/dprint.json b/fixtures/dprint-app/dprint.json new file mode 100644 index 000000000..eb30a79a2 --- /dev/null +++ b/fixtures/dprint-app/dprint.json @@ -0,0 +1,10 @@ +{ + "indentWidth": 4, + "lineWidth": 100, + "typescript": { "semiColons": "asi", "quoteStyle": "alwaysSingle" }, + "excludes": ["**/node_modules"], + "plugins": [ + "https://plugins.dprint.dev/typescript-0.95.0.wasm", + "https://plugins.dprint.dev/json-0.20.0.wasm" + ] +} diff --git a/fixtures/dprint-app/package.json b/fixtures/dprint-app/package.json new file mode 100644 index 000000000..1b490f514 --- /dev/null +++ b/fixtures/dprint-app/package.json @@ -0,0 +1,15 @@ +{ + "name": "openidea-fixture-dprint", + "version": "0.1.0", + "private": true, + "description": "OpenIDEA QA fixture: formatting with the project's dprint", + "type": "module", + "scripts": { + "start": "node --experimental-strip-types src/index.ts", + "format": "dprint fmt", + "check": "dprint check" + }, + "devDependencies": { + "dprint": "0.65.0" + } +} diff --git a/fixtures/dprint-app/src/cart.ts b/fixtures/dprint-app/src/cart.ts new file mode 100644 index 000000000..059a7b8a7 --- /dev/null +++ b/fixtures/dprint-app/src/cart.ts @@ -0,0 +1,9 @@ +export interface Item { + name: string + price: number + quantity: number +} + +export function total(items: Item[]): number { + return items.reduce((sum, item) => sum + item.price * item.quantity, 0) +} diff --git a/fixtures/dprint-app/src/data.json b/fixtures/dprint-app/src/data.json new file mode 100644 index 000000000..39f250cbc --- /dev/null +++ b/fixtures/dprint-app/src/data.json @@ -0,0 +1,2 @@ +{"currency":"EUR","rates":[1,2, +3]} diff --git a/fixtures/dprint-app/src/index.ts b/fixtures/dprint-app/src/index.ts new file mode 100644 index 000000000..2b6ee0c9b --- /dev/null +++ b/fixtures/dprint-app/src/index.ts @@ -0,0 +1,5 @@ +import {total,type Item} from "./cart.ts"; + +const items:Item[]=[{name:"Notebook",price:4.5,quantity:2},{name:"Pen",price:1.25,quantity:4}]; + +console.log("Total:",total(items).toFixed(2)); diff --git a/fixtures/jasmine-app/.gitignore b/fixtures/jasmine-app/.gitignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/fixtures/jasmine-app/.gitignore @@ -0,0 +1 @@ +node_modules diff --git a/fixtures/jasmine-app/package.json b/fixtures/jasmine-app/package.json new file mode 100644 index 000000000..c4aabe39e --- /dev/null +++ b/fixtures/jasmine-app/package.json @@ -0,0 +1,13 @@ +{ + "name": "openidea-fixture-cart", + "version": "0.1.0", + "private": true, + "description": "OpenIDEA QA fixture: Jasmine specs for a small shopping cart module", + "type": "module", + "scripts": { + "test": "jasmine" + }, + "devDependencies": { + "jasmine": "^5.13.0" + } +} diff --git a/fixtures/jasmine-app/spec/cartSpec.js b/fixtures/jasmine-app/spec/cartSpec.js new file mode 100644 index 000000000..8c55e982d --- /dev/null +++ b/fixtures/jasmine-app/spec/cartSpec.js @@ -0,0 +1,28 @@ +import { addItem, total } from "../src/cart.js"; + +describe("cart", () => { + describe("total", () => { + it("is zero for an empty cart", () => { + expect(total([])).toBe(0); + }); + + it("multiplies price by quantity", () => { + expect(total([{ price: 2.5, quantity: 4 }])).toBe(10); + }); + }); + + describe("addItem", () => { + it("appends the item", () => { + expect(addItem([], { price: 1, quantity: 1 }).length).toBe(1); + }); + + it("rejects a zero quantity", () => { + expect(() => addItem([], { price: 1, quantity: 0 })).toThrowError(RangeError); + }); + }); + + it("intentionally fails (set OPENIDEA_FAIL=1)", () => { + if (!process.env.OPENIDEA_FAIL) pending("set OPENIDEA_FAIL=1"); + expect(total([{ price: 3, quantity: 2 }])).toBe(7); + }); +}); diff --git a/fixtures/jasmine-app/spec/support/jasmine.json b/fixtures/jasmine-app/spec/support/jasmine.json new file mode 100644 index 000000000..3e31b90be --- /dev/null +++ b/fixtures/jasmine-app/spec/support/jasmine.json @@ -0,0 +1,7 @@ +{ + "spec_dir": "spec", + "spec_files": ["**/*[sS]pec.?(m)js"], + "env": { + "random": false + } +} diff --git a/fixtures/jasmine-app/src/cart.js b/fixtures/jasmine-app/src/cart.js new file mode 100644 index 000000000..a08055509 --- /dev/null +++ b/fixtures/jasmine-app/src/cart.js @@ -0,0 +1,11 @@ +export function total(items) { + return items.reduce((sum, item) => sum + item.price * item.quantity, 0); +} + +export function addItem(items, item) { + if (item.quantity <= 0) throw new RangeError("quantity must be positive"); + return [...items, item]; +} + +// An intentional warning: never used. +const MAX_ITEMS = 50; diff --git a/java/jdbc-bridge/openidea-jdbc-bridge.jar b/java/jdbc-bridge/openidea-jdbc-bridge.jar index c62bcdbc5..6c7db320d 100644 Binary files a/java/jdbc-bridge/openidea-jdbc-bridge.jar and b/java/jdbc-bridge/openidea-jdbc-bridge.jar differ diff --git a/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java b/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java index a75be8d6a..95be208e3 100644 --- a/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java +++ b/java/jdbc-bridge/src/ai/openidea/jdbc/OpenIdeaJdbc.java @@ -47,7 +47,19 @@ public final class OpenIdeaJdbc { private static class UnsupportedUrl extends SQLException {} - private static class ReadOnlyUnavailable extends SQLException {} + private static class ReadOnlyUnavailable extends SQLException { + ReadOnlyUnavailable(String message) { super(message); } + } + + static void checkDuckDbReadOnly(String key, String value) throws ReadOnlyUnavailable { + String option = key.trim(); + String setting = value.trim().toLowerCase(Locale.ROOT); + if (("access_mode".equalsIgnoreCase(option) && !"read_only".equals(setting)) + || ("duckdb.read_only".equalsIgnoreCase(option) + && !Set.of("true", "1", "yes", "on").contains(setting))) { + throw new ReadOnlyUnavailable("A DuckDB connection option conflicts with Read-only. Check access_mode and duckdb.read_only."); + } + } void open(List<String> a, DataOutputStream out) throws Exception { String className = a.get(0), url = a.get(1); @@ -56,12 +68,28 @@ public final class OpenIdeaJdbc { for (int i = 5; i < a.size(); i += 2) props.setProperty(a.get(i), a.get(i+1)); if (!a.get(2).isEmpty()) props.setProperty("user", a.get(2)); if (!a.get(3).isEmpty()) props.setProperty("password", a.get(3)); - connection = driver.connect(url, props); + boolean readOnly = Boolean.parseBoolean(a.get(4)); + boolean duckDbReadOnly = readOnly && className.equals("org.duckdb.DuckDBDriver") && url.startsWith("jdbc:duckdb:"); + if (duckDbReadOnly) { + // DuckDB fixes its access mode at open, and options in the URL take precedence. + for (String key : props.stringPropertyNames()) checkDuckDbReadOnly(key, props.getProperty(key)); + String[] parts = url.split(";"); + for (int i = 1; i < parts.length; i++) { + String[] option = parts[i].split("=", 2); + if (option.length == 2) checkDuckDbReadOnly(option[0], option[1]); + } + props.setProperty("duckdb.read_only", "true"); + } + try { connection = driver.connect(url, props); } + catch (SQLException e) { + if (!duckDbReadOnly) throw e; + throw new ReadOnlyUnavailable("DuckDB could not open in Read-only. Choose an existing database file and check the connection options."); + } if (connection == null) throw new UnsupportedUrl(); - if (Boolean.parseBoolean(a.get(4))) { + if (readOnly && !duckDbReadOnly) { try { connection.setReadOnly(true); } catch (SQLException | UnsupportedOperationException e) { - throw new ReadOnlyUnavailable(); + throw new ReadOnlyUnavailable("The JDBC driver rejected Read-only. Check the driver settings and database account privileges."); } } var m = connection.getMetaData(); @@ -306,7 +334,7 @@ public final class OpenIdeaJdbc { && e.getMessage() != null && e.getMessage().matches("[A-Za-z0-9_.$/]+")) { text(reply, "JDBC class " + e.getMessage() + " was not found. Check the driver class and include its dependency JARs."); } else if (e instanceof ReadOnlyUnavailable) { - text(reply, "The JDBC driver rejected Read-only. Check the driver settings and database account privileges."); + text(reply, e.getMessage()); } else if (e instanceof UnsupportedUrl) { text(reply, "The selected JDBC driver does not accept this URL"); } else if (op.equals("open")) { diff --git a/languages/json.toml b/languages/json.toml index 94f29d350..d34e64a2d 100644 --- a/languages/json.toml +++ b/languages/json.toml @@ -1,7 +1,7 @@ id = "json" name = "JSON" formatter = { tool = "prettier", parser = "json", range = true } -extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map"] +extensions = ["json", "geojson", "topojson", "webmanifest", "har", "avsc", "jsonl", "ndjson", "json.map", "uproject", "uplugin"] filenames = [".prettierrc", ".watchmanconfig", "composer.lock", ".arcconfig"] indent = { tab-size = 2, insert-spaces = true } ui-mode = "JSON" diff --git a/plugins/README.md b/plugins/README.md index 182c9479e..01905f4af 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -136,34 +136,34 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK. ### Contribution points -| Point | Declaration | Code needed | -| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -| `commands` | `id`, `title`, `category?`, `when?` | to run them | -| `themes` | `path` (theme JSON), `editor-scheme?` | no | -| `iconThemes` | `id`, `label`, `path` (icon theme JSON, see §5) | no | -| `languages` | `path` (`languages/<id>.toml` format, see §6) | no | -| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` (API 1.4; §6.2) | no | -| `runConfigurations` | `files`: marker files for the optional `run-configurations` export (API 1.4) | yes | -| `javaAgents` | `path` (a jar in the package), `args?`, `vmOptions?`, `jdk?` — a Java agent for Java run configurations, behind `java.agent` (API 1.10; `vmOptions`/`jdk` in 1.14; _Java agents_) | no | -| `skills` | `path` (`skills/<name>/SKILL.md` in the package) — agent skill folder staged into coding-agent sessions (API 1.15) | no | -| `mcpTools` | `name`, `description`, `inputSchema` (package JSON Schema path), `readOnly`, `destructive` (API 1.4; see _Plugin MCP tools_) | yes | -| `snippets` | `language`, `path` (named JSON snippets; API 1.4) | no | -| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes | -| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them | -| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`; API 1.4: `editor.title`, `mainToolbar`, `problems.context`, `searchResults.context`), `view?`, `command`, `when?` | no | -| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no | -| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | -| `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no | -| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `frames?` (API 1.16), `group?`, `when?` (API 1.3) | without `web` | -| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?`, `frames?`, `binary?` (API 1.16) | without `web` | -| `editorPanels` | `id`, `web`, `width` (pixels, 40–400), `when?`, `frames?` (API 1.16) — needs `editor.read` (API 1.9; _Editor panels_) | no | -| `overlays` | `id`, `web`, `width`, `height` (pixels, 40–800), `anchor?`, `when?`, `interactive?` — floats over the workbench, never takes the focus (API 1.18; _Overlays_) | no | -| `runAnything` | `prefix`, `title?` — Run Anything lines starting with `prefix`, answered by the `run-anything-provider` export (API 1.18; _Run Anything entries_) | no | -| `dialogs` | `id`, `title`, `web`, `width` (320–1600), `height` (200–1200) — a modal, resizable dialog opened by `views::reveal(id)` (API 1.18; _Dialogs_) | no | -| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no | -| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables = [{ name, prompt }]` — New menu | no | -| `commitChecks` | `id`, `title` — a before-commit check in Commit Options (see _Commits_) | yes | -| `serverCommands` | `server`, `command`, `run` — a language server's client command run by this plugin's command (API 1.9; see _Commands a server hands to the client_) | +| Point | Declaration | Code needed | +| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | +| `commands` | `id`, `title`, `category?`, `when?` | to run them | +| `themes` | `path` (theme JSON), `editor-scheme?` | no | +| `iconThemes` | `id`, `label`, `path` (icon theme JSON, see §5) | no | +| `languages` | `path` (`languages/<id>.toml` format, see §6) | no | +| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` (API 1.4; §6.2) | no | +| `runConfigurations` | `files`: marker files for the optional `run-configurations` export (API 1.4) | yes | +| `javaAgents` | `path` (a jar in the package), `args?`, `vmOptions?`, `jdk?`, `executor?` — a Java agent for Java run configurations, behind `java.agent` (API 1.10; `vmOptions`/`jdk` in 1.14; `executor` in 1.18; _Java agents_) | no | +| `skills` | `path` (`skills/<name>/SKILL.md` in the package) — agent skill folder staged into coding-agent sessions (API 1.15) | no | +| `mcpTools` | `name`, `description`, `inputSchema` (package JSON Schema path), `readOnly`, `destructive` (API 1.4; see _Plugin MCP tools_) | yes | +| `snippets` | `language`, `path` (named JSON snippets; API 1.4) | no | +| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes | +| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them | +| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`; API 1.4: `editor.title`, `mainToolbar`, `problems.context`, `searchResults.context`; API 1.18: `services.context`, `services.toolbar`), `view?`, `command`, `when?` | no | +| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no | +| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | +| `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no | +| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `frames?` (API 1.16), `group?`, `when?` (API 1.3) | without `web` | +| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?`, `frames?`, `binary?` (API 1.16) | without `web` | +| `editorPanels` | `id`, `web`, `width` (pixels, 40–400), `when?`, `frames?` (API 1.16) — needs `editor.read` (API 1.9; _Editor panels_) | no | +| `overlays` | `id`, `web`, `width`, `height` (pixels, 40–800), `anchor?`, `when?`, `interactive?` — floats over the workbench, never takes the focus (API 1.18; _Overlays_) | no | +| `runAnything` | `prefix`, `title?` — Run Anything lines starting with `prefix`, answered by the `run-anything-provider` export (API 1.18; _Run Anything entries_) | no | +| `dialogs` | `id`, `title`, `web`, `width` (320–1600), `height` (200–1200) — a modal, resizable dialog opened by `views::reveal(id)` (API 1.18; _Dialogs_) | no | +| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no | +| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables = [{ name, prompt }]` — New menu | no | +| `commitChecks` | `id`, `title` — a before-commit check in Commit Options (see _Commits_) | yes | +| `serverCommands` | `server`, `command`, `run` — a language server's client command run by this plugin's command (API 1.9; see _Commands a server hands to the client_) | A `viewItem.context` menu needs `view`, the id of one of the plugin's own views. It adds the commands to the right-click menu of the items in that @@ -351,32 +351,35 @@ installing (or when a new version asks for more). Low-risk capabilities are listed; high-risk ones are called out as equivalent to running code on the machine. Users can revoke optional capabilities in Settings › Plugins. -| Capability | Risk | Unlocks today | -| ------------------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `ide.commands` | high | Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing. API 1.4; declared own commands are exempt. | -| `database.sources` | medium | API 1.4: manage only the plugin's own project database sources, write their secure credentials and request connection; trusted projects only. | -| `project.read` | low | `Project::root`, `read_file`, `read_bytes`, `find_files`, `symbols`, `search_text`, `host::projects`, `publish_diagnostics`, `problems`, editor opening and decorations | -| `project.write` | high | `Project::write_file` — creates and replaces text files inside the open projects, the settings and build scripts a trusted project runs included | -| `fs.read:<path>` | high | `host::fs::read_file`, `read_bytes`, `stat`, `read_dir` — files outside the projects, under the grant's directory | -| `fs.write:<path>` | high | `host::fs::write_file`, `write_bytes` — files under that path; doesn't imply reading | -| `editor.read` | low | `TextEditor::document`, `selections`, `host::open_editors` | -| `editor.write` | medium | `TextEditor::apply_edits` | -| `vcs.read` | low | `Project::vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff` (new reads require trust), `host::pending_commit`, before-commit checks | -| `vcs.write` | medium | `Project::vcs_fetch` (trusted projects only), `host::set_commit_message` | -| `build.read` | low | API 1.10: `Project::build_dependencies`, the Maven / Gradle dependency graph the IDE resolved; trusted projects only | -| `storage` | low | `host::storage` (64 MiB per plugin, counting UTF-8 bytes of keys and values) | -| `events` | low | file opened/saved, editor focused, repository changed events | -| `events.input` | medium | `action-performed` and `input-mode-changed` events | -| `process:<program>` | high | `Project::run_process`, language servers, debug adapters, runs | -| `lsp:<server>` | high | API 1.9: `Project::language_server_request` / `language_server_notify` to that running language server (its name in the language definition); trusted projects only | -| `java.agent` | high | API 1.10: the `[[contributes.javaAgents]]` jar runs inside the Java applications you start; derived from that declaration, never listed | -| `net:<host>` | medium | `host::fetch` over HTTPS (also loopback HTTP); `*.example.com` matches subdomains | -| `net:ask` | medium | Ask the user at the first request to an HTTPS (or loopback) host that is not declared; one answer per host, revocable; API 1.5 | -| `net.http:<host>` | medium | Unencrypted HTTP to that host; API 1.4, same wildcard rules as `net:` | -| `ipc:<path>` | high | Local Unix sockets or Windows named pipes on the project machine; API 1.4 | -| `secrets` | medium | `{{secret:<name>}}` in request headers, `host::secret_is_set`, `secret_set`, `secret_delete` | -| `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | -| `clipboard.read` | medium | API 1.11: `host::read_clipboard`, the clipboard's text and image, only in commands and view actions the user ran | +| Capability | Risk | Unlocks today | +| ------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `ide.commands` | high | Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing. API 1.4; declared own commands are exempt. | +| `database.sources` | medium | API 1.4: manage only the plugin's own project database sources, write their secure credentials and request connection; trusted projects only. | +| `project.read` | low | `Project::root`, `read_file`, `read_bytes`, `find_files`, `symbols`, `search_text`, `host::projects`, `publish_diagnostics`, `problems`, editor opening and decorations | +| `project.write` | high | `Project::write_file` — creates and replaces text files inside the open projects, the settings and build scripts a trusted project runs included | +| `fs.read:<path>` | high | `host::fs::read_file`, `read_bytes`, `stat`, `read_dir` — files outside the projects, under the grant's directory | +| `fs.write:<path>` | high | `host::fs::write_file`, `write_bytes` — files under that path; doesn't imply reading | +| `editor.read` | low | `TextEditor::document`, `selections`, `host::open_editors` | +| `editor.write` | medium | `TextEditor::apply_edits` | +| `vcs.read` | low | `Project::vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff` (new reads require trust), `host::pending_commit`, before-commit checks | +| `vcs.write` | medium | `Project::vcs_fetch` (trusted projects only), `host::set_commit_message` | +| `build.read` | low | API 1.10: `Project::build_dependencies`, the Maven / Gradle dependency graph the IDE resolved; trusted projects only | +| `storage` | low | `host::storage` (64 MiB per plugin, counting UTF-8 bytes of keys and values) | +| `events` | low | file opened/saved, editor focused, repository changed events | +| `events.input` | medium | `action-performed` and `input-mode-changed` events | +| `process:<program>` | high | `Project::run_process`, language servers, debug adapters, runs | +| `lsp:<server>` | high | API 1.9: `Project::language_server_request` / `language_server_notify` to that running language server (its name in the language definition); trusted projects only | +| `java.agent` | high | API 1.10: the `[[contributes.javaAgents]]` jar runs inside the Java applications you start; derived from that declaration, never listed | +| `net:<host>` | medium | `host::fetch` over HTTPS (also loopback HTTP); `*.example.com` matches subdomains | +| `net:ask` | medium | Ask the user at the first request to an HTTPS (or loopback) host that is not declared; one answer per host, revocable; API 1.5 | +| `net.http:<host>` | medium | Unencrypted HTTP to that host; API 1.4, same wildcard rules as `net:` | +| `net:setting:<key>` | medium | API 1.18: the host of the plugin's `string` setting `<key>` over HTTPS (also loopback HTTP), approved when the user applies the value in Settings; bare host or URL | +| `net.http:setting:<key>` | medium | API 1.18: the same setting's host over unencrypted HTTP, approved the same way | +| `ipc:<path>` | high | Local Unix sockets or Windows named pipes on the project machine; API 1.4 | +| `secrets` | medium | `{{secret:<name>}}` in request headers, `host::secret_is_set`, `secret_set`, `secret_delete` | +| `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | +| `clipboard.read` | medium | API 1.11: `host::read_clipboard`, the clipboard's text and image, only in commands and view actions the user ran | +| `agents` | medium | API 1.18: `host::fork_agent_session`, fork a recorded native agent session into a new task in the project; trusted projects only | `process:` capabilities are also derived from what the contributions start: a language's `language-servers` and `debugger` commands and a run detector's @@ -562,6 +565,11 @@ matching SDK. Plugins for 1.14 and earlier keep working. New in 1.15: sessions while the plugin is enabled; workspace and user skills take precedence on a name clash, and invalid entries report a plugin load warning rather than failing the plugin. +- [Forking agent sessions](#forking-agent-sessions-api-115): + `host::fork_agent_session` (`agents.fork-session`) continues a recorded native + agent session (`claude` or `codex`) as a new task in the invoking window's + project, returning the task id. Requires the `agents` capability; the host + validates the session and builds the fork invocation itself. ### API 1.14 @@ -897,93 +905,94 @@ then run `openidea-plugin check`. ### The API -| Rust SDK | WIT | Notes | -| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Plugin::run_command(id, ctx, arg)` | export `commands.run` | `ctx` is the window: `ctx.project()`, `ctx.editor()`. An error shows _"<title> failed: …"_; the plugin keeps running. `"msg".into()` is `Error::Failed`; `Cancelled` and `Denied` don't count as the plugin failing. | -| `Plugin::handle_events(events, ctx)` | export `event-handler.handle` | Batches of subscribed events, oldest first, per window. | -| `Plugin::activate` / `deactivate` | export `lifecycle` | Per instance: after a crash or idle reclaim a new one is activated. | -| `TextEditor::document()` → `{version, text}` | `editor.text-editor.document` | `selections()` are those when the command ran (0-based lines, UTF-16 columns). | -| `Project::document`, `apply_document_edits` | `editor.{document,apply-edits}-at` | API 1.6: versioned access to an explicitly named open project document from background events. Requires `project.read` and `editor.read`/`editor.write`; stale edits change nothing. | -| `WebSocket::{connect,send,drain,close}` | `net.websocket-*` | API 1.6: project-bound, bounded host-owned WSS transport with secret-filled headers, close state and event-driven wakeups. | -| `Project::{upsert_data_source,remove_data_source,data_sources,set_data_source_credential,connect_data_source}` | `database` | API 1.4: owned project sources; requires `database.sources` and trust. See _Database sources_. | -| `host::mcp_stdio_command()` | `mcp.stdio-command` | API 1.4: invoking project bridge argv, `None` while off. No URL/token. | -| `McpProvider::call(tool, arguments, ctx)` | export `mcp-provider.call` | API 1.4: declared tools under plugin grants and command budget. See _Plugin MCP tools_. | -| `host::open_editors()` | `editor.open-editors` | API 1.4: invoking window's path/language/dirty/active snapshots; requires `editor.read`. Commands/events of a window only. | -| `host::open_editor(path, selection)` | `editor.open` | API 1.4: open/select a project file (`project.read`), plugin-dir file, or install-directory file (read-only); same path rules as `views.open-location`. Commands/events of a window only. | -| `TextEditor::set_selections(ranges)`, `reveal(range)` | `editor.text-editor` | API 1.4: selections or scrolling in this window's already open editor; no capability. Commands/events only, UTF-16 coordinates. | -| `host::set_decorations`, `clear_decorations` | `decorations.{set,clear}` | API 1.4: project-scoped editor annotations cleared on plugin stop. Requires `project.read`. | -| `host::set_markdown_decorations` | `decorations.set-markdown` | API 1.16: the same sets with `markdown_hover` cards; shares set ids and limits with `set_decorations`. Requires `project.read`. | -| `host::set_styled_decorations` | `decorations.set-styled` | API 1.17: those items with their own `#rrggbb` / `#rrggbbaa` `colors`; `style` may be empty when colors are set; shares set ids and limits with `set_decorations`. Requires `project.read`. | -| `host::set_file_decoration`, `clear_file_decorations` | `decorations.{set-file,clear-file}` | API 1.4: project-tree badges/styles. Requires `project.read`. | -| `host::set_file_note` | `decorations.set-file-note` | API 1.7: a note after the name in the project tree (one line, at most 200 characters). Requires `project.read`. | -| `host::set_file_icon`, `set_file_icons` | `decorations.{set-file-icon,set-file-icons}` | API 1.8: assign one of the plugin's declared `[[contributes.fileIcons]]` icons to a file or plain folder by path (individually or up to 10,000 entries per set). Requires `project.read`. | -| `Project::search_text(query, limit)` | `workspace.project.search-text` | API 1.4: cancellable Find in Files with unsaved documents and project excludes, at most 10,000 matches. Requires `project.read`. | -| `host::problems(path)` | `diagnostics.problems` | API 1.4: project Problems reports grouped by file/source, optional file filter. Requires `project.read` and an invoking window. Empty for remote projects. | -| `Project::vcs_log(path, limit)` | `vcs.log` | API 1.4: newest first, at most 1000 commits, optional file history. Requires `vcs.read` and trust. | -| `Project::vcs_blame(path)` | `vcs.blame` | API 1.4: attribution including unsaved editor text. Requires `vcs.read` and trust. | -| `Project::build_dependencies(module)` | `build.dependencies` | API 1.10: the Maven / Gradle dependency graph the IDE resolved, flat, each module a root; nothing is resolved for the call. Requires `build.read` and trust. | -| `Project::vcs_diff(path, against)` | `vcs.diff` | API 1.4: disk working tree against HEAD/revision, optionally one file. None outside Git; fails above 4 MiB. Requires `vcs.read` and trust. | -| `TextEditor::apply_edits(version, edits)` | `editor.text-editor.apply-edits` | One undoable change, only if the document is still at `version` — else `Error::Stale` and nothing changes. `transform_selections` retries once. | -| `Project::root()`, `read_file(path)` | `workspace.project` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB; unsaved editor contents win; a missing path is `Error::NotFound`. | -| `Project::read_bytes(path)` | `workspace.project.read-bytes` | API 1.5: the exact bytes of a file inside the project (binary content is the point), at most 16 MiB, the file on disk. Same paths and `Error::NotFound` as `read_file`. | -| `Project::exists(path)`, `stat(path)` | `workspace.project` | `exists` covers files and directories, hidden and ignored included, without reading content; `stat` gives kind, size and modified time (`Error::NotFound` for a missing path). | -| `host::projects()` | `workspace.projects` | Every open project (for scheduled work without a window). | -| `Project::vcs_status()`, `vcs_remotes()`, `vcs_fetch()` | `vcs` | `vcs_remotes` returns `(name, url)` pairs; fetch runs git, so only in trusted projects (call it inside a task). | -| `host::pending_commit()`, `host::set_commit_message(revision, text)` | `commit` | The commit being prepared in the calling window and its message; see _Commits_. | -| `host::subscribe(kind)` | `events.subscribe` | For the session, across idle reclaim (an event activates the plugin). Or declare `on-event:<kind>`. | -| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. | -| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. | -| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. | -| `host::set_window_status_item(id, item)`, `remove_window_status_item(id)` | `ui.{set,remove}-window-status-item` | API 1.4: window-only override; removed on window close or plugin stop; removing falls back to the global item. Click runs its command in that window. | -| `host::set_status_item_menu(id, item, menu)`, `set_window_status_item_menu` | `ui.set-{,window-}status-item-menu` | API 1.14: the item with a menu that a click opens instead of running its command; actions run declared commands with their argument. | -| `host::execute_command(id, arg)` → `Option<String>` | `command-runner.execute` | API 1.4: requires high-risk `ide.commands` for IDE actions and other plugins; this plugin's own commands are exempt. Stable IDE action or `plugin.<plugin-id>.<command-id>` in the invoking window. IDE actions return none; plugin commands return their result. Unknown ids are not-found; at most 8 nested calls, no re-entry into a waiting instance. | -| `host::ipc_connect(name)` → `Connection` | `ipc.connect` | API 1.4: `write(bytes)`, `read(max_bytes, timeout_ms)`, `close()`; requires `ipc:<path>`, at most 8 connections, closed on drop or plugin stop. Runs on the project server in remote projects. | -| `host::secret_set(name, value)`, `secret_delete(name)` | `secrets.{set,delete}` | API 1.4: requires `secrets` and a declared name. Never returns the value. | -| `host::begin_loopback(path)` → `Loopback` | `auth.begin-loopback` | API 1.4: `redirect_uri()`, `wait(timeout_ms)` → raw query or none on timeout. Desktop-only, even for remote projects; no capability. At most 2 listeners; one-shot, closed on timeout, drop or stop. Waiting excludes the call budget. | -| `host::output_append(channel, text)`, `output_clear`, `output_reveal` | `output.{append,clear,reveal}` | API 1.4: read-only Output tabs; 32 named channels per plugin, each a 1 MiB UTF-8 ring buffer. Reveal requires the invoking window. | -| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. | -| `host::set_console_rules(rules)` | `ui.set-console-rules` | API 1.12: replaces the plugin's highlight rules for Run and Debug console output (regex, palette colours, styles, whole line or match); no capability. See _Console highlight rules_. | -| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). | -| `Project::notify(level, title, body, actions)` | `ui.notify-project` | API 1.5: balloon only in a window of that project (the most recently focused one), with or without an invoking window; see _Notifications with commands_. | -| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. | -| `host::read_clipboard()` → `ClipboardContent` | `ui.read-clipboard` | API 1.11: the clipboard's `text` and `image` (PNG bytes), `None` for what it doesn't hold. Needs `clipboard.read`; only in a command the user ran or a view action, else `denied`. See _Reading the clipboard_. | -| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. | -| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Picks key(s) from `PickItem`s, or `None` when dismissed. From a command/event or code-action resolution in its editor window (else `invalid`); waiting is excluded from the budget. | -| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. | -| `host::input_multiline(prompt, value)` | `ui.input-multiline` | A multi-line text box pre-filled with `value`; `None` when dismissed; Cmd/Ctrl+Enter confirms. Only from a command or event of a window. | -| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. | -| `host::locale()` | `ui.locale` | The IDE's UI language as a BCP 47 tag (`en`, `fr`, `zh-CN`); no capability. See _Translations_. | -| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. | -| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. | -| `Project::symbols(query, limit)` | `workspace.symbols` | New in 1.3; `project.read`. Fuzzy in-memory search (no LSP): name, camelCase kind, container and UTF-16 location. Queries ≤ 256 UTF-8 bytes; limits capped at 1000. Snapshot notes below. | -| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. | -| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. | -| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; up to 16 MiB of stdout (fails if exceeded); killed when the call is cancelled or times out. | -| `host::run_command(cmd, project, stdin)` → `{code, stdout, stderr}` | `process.run-command` | API 1.3: same limits as `run_process`, with append-only environment variables; needs the pinned `process:<program>` grant. | -| `host::start(cmd, project)` → `Child` | `process.start` | API 1.3: `poll(max_bytes)`, `write(text)`, `close_stdin()`, `wait(timeout_ms)`, `kill()`; at most 8 handles; dropping one kills its process. | -| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. | -| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. | -| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. | -| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. | -| `host::register_run_target(project, target)` | `run-targets.register` | API 1.4: project-scoped, read-only argv wrapper; requires its process grant, executable pin and project trust; remote projects run on the server. | -| `host::unregister_run_target(project, id)` | `run-targets.unregister` | Withdraw this plugin's target; remembered prompt answers remain. | -| `host::start_run(config, args, debug)` | `run.start` | API 1.4: start an owned configuration in this window's Run tool window; returns an id, followed by `run-exited`. Approved `process:` program; commands/events only. | -| `host::start_run_with_options(config, args, options)` | `run.start-with-options` | API 1.18: start an owned configuration with `RunStartOptions` (`debug` and optional per-launch `output_mode`); user-saved override wins over `options.output_mode`, which wins over plugin default. | -| `host::open_terminal_session(key, title, cmd)` | `views.open-terminal-session` | API 1.4: keyed, pinned terminal in this window, append-only env; returns its operation id and later `terminal-exited`. | -| `host::open_terminal_session_in(key, title, cmd, cwd)` | `views.open-terminal-session-in` | API 1.18: the same, started in `cwd`, a directory of the project relative to its root. | -| `host::write_terminal(key, text)` | `views.write-terminal` | API 1.4: write only to this plugin's still-running terminal in this window; trusted project, commands/events only. | -| `host::open_content_tab(tab)` | `views.open-content-tab` | API 1.4: the shared content editor protocol, without a web view; actions arrive as `content-tab-action`. | -| `host::reply_content_tab(request_id, reply)` | `views.reply-content-tab` | API 1.4: reply to an owned action in the originating window. No capability; commands/events only. | -| `host::open_diff(diff, file_name)` | `views.open-diff` | API 1.7: two texts in the invoking window's diff viewer; `file_name` (at most 256 characters) picks the highlighting. Commands/events only; each side at most 8 MiB (earlier hosts: 1 MiB), a larger side fails with `Invalid("diff too large: …")`. | -| `host::open_file_diff(diff, file_name)` | `views.open-file-diff` | API 1.10: `open_diff` where a side may be `None` (the file doesn't exist there: added or deleted); the viewer shows the other side alone. Both `None` fails with `Invalid`. | -| `RunConfigurations::configurations(root)` | export `run-configurations.configurations` | API 1.4: optional `plugin-run-configurations` world; SDK registration `run_configurations`. Full project list, refreshed on configuration listing. | -| `LaunchConfigurations::launch_configurations(root)` | export `launch-configurations` | API 1.9: optional `plugin-launch-configurations` world; SDK registration `launch_configurations`. The same list with `env` and `debugger`; preferred over `run-configurations`. | -| `ExecutionConfigurations::execution_configurations(root)` | export `execution-configurations` | API 1.18: optional `plugin-execution-configurations` world; SDK registration `execution_configurations`. Adds a default `output_mode` (`Pipes` or `Pty`); preferred over `launch-configurations` and `run-configurations`. | -| `RunConfigurationCompletion::complete(project, config, field, text, caret)` | export `run-configuration-completion` | API 1.18: optional `plugin-run-configuration-completion` world; SDK registration `run_configuration_completion`. Completes the Arguments field (`field = "arguments"`) of the plugin's own configurations; items replace a UTF-16 range; 200 items, 300 ms. | -| `TestResults::parse(config, chunk)` | export `test-results.parse` | API 1.4: optional `plugin-test-results` world; SDK registration `test_results`. Bounded output batches for `framework = "plugin"`; failures use built-in parsers. | -| `TestResults::select_tests(config, tests)` | export `test-results.select-tests` | API 1.4: full replacement argv for test-tree name paths, or `None` when unsupported (the SDK default). Enables rerunning failed tests and running tree selections. | -| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. | -| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. | +| Rust SDK | WIT | Notes | +| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `Plugin::run_command(id, ctx, arg)` | export `commands.run` | `ctx` is the window: `ctx.project()`, `ctx.editor()`. An error shows _"<title> failed: …"_; the plugin keeps running. `"msg".into()` is `Error::Failed`; `Cancelled` and `Denied` don't count as the plugin failing. | +| `Plugin::handle_events(events, ctx)` | export `event-handler.handle` | Batches of subscribed events, oldest first, per window. | +| `Plugin::activate` / `deactivate` | export `lifecycle` | Per instance: after a crash or idle reclaim a new one is activated. | +| `TextEditor::document()` → `{version, text}` | `editor.text-editor.document` | `selections()` are those when the command ran (0-based lines, UTF-16 columns). | +| `Project::document`, `apply_document_edits` | `editor.{document,apply-edits}-at` | API 1.6: versioned access to an explicitly named open project document from background events. Requires `project.read` and `editor.read`/`editor.write`; stale edits change nothing. | +| `WebSocket::{connect,send,drain,close}` | `net.websocket-*` | API 1.6: project-bound, bounded host-owned WSS transport with secret-filled headers, close state and event-driven wakeups. | +| `Project::{upsert_data_source,remove_data_source,data_sources,set_data_source_credential,connect_data_source}` | `database` | API 1.4: owned project sources; requires `database.sources` and trust. See _Database sources_. | +| `host::mcp_stdio_command()` | `mcp.stdio-command` | API 1.4: invoking project bridge argv, `None` while off. No URL/token. | +| `McpProvider::call(tool, arguments, ctx)` | export `mcp-provider.call` | API 1.4: declared tools under plugin grants and command budget. See _Plugin MCP tools_. | +| `host::open_editors()` | `editor.open-editors` | API 1.4: invoking window's path/language/dirty/active snapshots; requires `editor.read`. Commands/events of a window only. | +| `host::open_editor(path, selection)` | `editor.open` | API 1.4: open/select a project file (`project.read`), plugin-dir file, or install-directory file (read-only); same path rules as `views.open-location`. Commands/events of a window only. | +| `TextEditor::set_selections(ranges)`, `reveal(range)` | `editor.text-editor` | API 1.4: selections or scrolling in this window's already open editor; no capability. Commands/events only, UTF-16 coordinates. | +| `host::set_decorations`, `clear_decorations` | `decorations.{set,clear}` | API 1.4: project-scoped editor annotations cleared on plugin stop. Requires `project.read`. | +| `host::set_markdown_decorations` | `decorations.set-markdown` | API 1.16: the same sets with `markdown_hover` cards; shares set ids and limits with `set_decorations`. Requires `project.read`. | +| `host::set_styled_decorations` | `decorations.set-styled` | API 1.17: those items with their own `#rrggbb` / `#rrggbbaa` `colors`; `style` may be empty when colors are set; shares set ids and limits with `set_decorations`. Requires `project.read`. | +| `host::set_file_decoration`, `clear_file_decorations` | `decorations.{set-file,clear-file}` | API 1.4: project-tree badges/styles. Requires `project.read`. | +| `host::set_file_note` | `decorations.set-file-note` | API 1.7: a note after the name in the project tree (one line, at most 200 characters). Requires `project.read`. | +| `host::set_file_icon`, `set_file_icons` | `decorations.{set-file-icon,set-file-icons}` | API 1.8: assign one of the plugin's declared `[[contributes.fileIcons]]` icons to a file or plain folder by path (individually or up to 10,000 entries per set). Requires `project.read`. | +| `Project::search_text(query, limit)` | `workspace.project.search-text` | API 1.4: cancellable Find in Files with unsaved documents and project excludes, at most 10,000 matches. Requires `project.read`. | +| `host::problems(path)` | `diagnostics.problems` | API 1.4: project Problems reports grouped by file/source, optional file filter. Requires `project.read` and an invoking window. Empty for remote projects. | +| `Project::vcs_log(path, limit)` | `vcs.log` | API 1.4: newest first, at most 1000 commits, optional file history. Requires `vcs.read` and trust. | +| `Project::vcs_blame(path)` | `vcs.blame` | API 1.4: attribution including unsaved editor text. Requires `vcs.read` and trust. | +| `Project::build_dependencies(module)` | `build.dependencies` | API 1.10: the Maven / Gradle dependency graph the IDE resolved, flat, each module a root; nothing is resolved for the call. Requires `build.read` and trust. | +| `Project::vcs_diff(path, against)` | `vcs.diff` | API 1.4: disk working tree against HEAD/revision, optionally one file. None outside Git; fails above 4 MiB. Requires `vcs.read` and trust. | +| `TextEditor::apply_edits(version, edits)` | `editor.text-editor.apply-edits` | One undoable change, only if the document is still at `version` — else `Error::Stale` and nothing changes. `transform_selections` retries once. | +| `Project::root()`, `read_file(path)` | `workspace.project` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB; unsaved editor contents win; a missing path is `Error::NotFound`. | +| `Project::read_bytes(path)` | `workspace.project.read-bytes` | API 1.5: the exact bytes of a file inside the project (binary content is the point), at most 16 MiB, the file on disk. Same paths and `Error::NotFound` as `read_file`. | +| `Project::exists(path)`, `stat(path)` | `workspace.project` | `exists` covers files and directories, hidden and ignored included, without reading content; `stat` gives kind, size and modified time (`Error::NotFound` for a missing path). | +| `host::projects()` | `workspace.projects` | Every open project (for scheduled work without a window). | +| `Project::vcs_status()`, `vcs_remotes()`, `vcs_fetch()` | `vcs` | `vcs_remotes` returns `(name, url)` pairs; fetch runs git, so only in trusted projects (call it inside a task). | +| `host::pending_commit()`, `host::set_commit_message(revision, text)` | `commit` | The commit being prepared in the calling window and its message; see _Commits_. | +| `host::subscribe(kind)` | `events.subscribe` | For the session, across idle reclaim (an event activates the plugin). Or declare `on-event:<kind>`. | +| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. | +| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. | +| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. | +| `host::set_window_status_item(id, item)`, `remove_window_status_item(id)` | `ui.{set,remove}-window-status-item` | API 1.4: window-only override; removed on window close or plugin stop; removing falls back to the global item. Click runs its command in that window. | +| `host::set_status_item_menu(id, item, menu)`, `set_window_status_item_menu` | `ui.set-{,window-}status-item-menu` | API 1.14: the item with a menu that a click opens instead of running its command; actions run declared commands with their argument. | +| `host::execute_command(id, arg)` → `Option<String>` | `command-runner.execute` | API 1.4: requires high-risk `ide.commands` for IDE actions and other plugins; this plugin's own commands are exempt. Stable IDE action or `plugin.<plugin-id>.<command-id>` in the invoking window. IDE actions return none; plugin commands return their result. Unknown ids are not-found; at most 8 nested calls, no re-entry into a waiting instance. | +| `host::ipc_connect(name)` → `Connection` | `ipc.connect` | API 1.4: `write(bytes)`, `read(max_bytes, timeout_ms)`, `close()`; requires `ipc:<path>`, at most 8 connections, closed on drop or plugin stop. Runs on the project server in remote projects. | +| `host::secret_set(name, value)`, `secret_delete(name)` | `secrets.{set,delete}` | API 1.4: requires `secrets` and a declared name. Never returns the value. | +| `host::begin_loopback(path)` → `Loopback` | `auth.begin-loopback` | API 1.4: `redirect_uri()`, `wait(timeout_ms)` → raw query or none on timeout. Desktop-only, even for remote projects; no capability. At most 2 listeners; one-shot, closed on timeout, drop or stop. Waiting excludes the call budget. | +| `host::output_append(channel, text)`, `output_clear`, `output_reveal` | `output.{append,clear,reveal}` | API 1.4: read-only Output tabs; 32 named channels per plugin, each a 1 MiB UTF-8 ring buffer. Reveal requires the invoking window. | +| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. | +| `host::set_console_rules(rules)` | `ui.set-console-rules` | API 1.12: replaces the plugin's highlight rules for Run and Debug console output (regex, palette colours, styles, whole line or match); no capability. See _Console highlight rules_. | +| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). | +| `Project::notify(level, title, body, actions)` | `ui.notify-project` | API 1.5: balloon only in a window of that project (the most recently focused one), with or without an invoking window; see _Notifications with commands_. | +| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. | +| `host::read_clipboard()` → `ClipboardContent` | `ui.read-clipboard` | API 1.11: the clipboard's `text` and `image` (PNG bytes), `None` for what it doesn't hold. Needs `clipboard.read`; only in a command the user ran or a view action, else `denied`. See _Reading the clipboard_. | +| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. | +| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Picks key(s) from `PickItem`s, or `None` when dismissed. From a command/event or code-action resolution in its editor window (else `invalid`); waiting is excluded from the budget. | +| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. | +| `host::input_multiline(prompt, value)` | `ui.input-multiline` | A multi-line text box pre-filled with `value`; `None` when dismissed; Cmd/Ctrl+Enter confirms. Only from a command or event of a window. | +| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. | +| `host::locale()` | `ui.locale` | The IDE's UI language as a BCP 47 tag (`en`, `fr`, `zh-CN`); no capability. See _Translations_. | +| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. | +| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. | +| `Project::symbols(query, limit)` | `workspace.symbols` | New in 1.3; `project.read`. Fuzzy in-memory search (no LSP): name, camelCase kind, container and UTF-16 location. Queries ≤ 256 UTF-8 bytes; limits capped at 1000. Snapshot notes below. | +| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. | +| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. | +| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; up to 16 MiB of stdout (fails if exceeded); killed when the call is cancelled or times out. | +| `host::run_command(cmd, project, stdin)` → `{code, stdout, stderr}` | `process.run-command` | API 1.3: same limits as `run_process`, with append-only environment variables; needs the pinned `process:<program>` grant. | +| `host::start(cmd, project)` → `Child` | `process.start` | API 1.3: `poll(max_bytes)`, `write(text)`, `close_stdin()`, `wait(timeout_ms)`, `kill()`; at most 8 handles; dropping one kills its process. | +| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. | +| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. | +| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. | +| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. | +| `host::register_run_target(project, target)` | `run-targets.register` | API 1.4: project-scoped, read-only argv wrapper; requires its process grant, executable pin and project trust; remote projects run on the server. | +| `host::unregister_run_target(project, id)` | `run-targets.unregister` | Withdraw this plugin's target; remembered prompt answers remain. | +| `host::start_run(config, args, debug)` | `run.start` | API 1.4: start an owned configuration in this window's Run tool window; returns an id, followed by `run-exited`. Approved `process:` program; commands/events only. | +| `host::start_run_with_options(config, args, options)` | `run.start-with-options` | API 1.18: start an owned configuration with `RunStartOptions` (`debug` and optional per-launch `output_mode`); user-saved override wins over `options.output_mode`, which wins over plugin default. | +| `host::open_terminal_session(key, title, cmd)` | `views.open-terminal-session` | API 1.4: keyed, pinned terminal in this window, append-only env; returns its operation id and later `terminal-exited`. | +| `host::open_terminal_session_in(key, title, cmd, cwd)` | `views.open-terminal-session-in` | API 1.18: the same, started in `cwd`, a directory of the project relative to its root. | +| `host::write_terminal(key, text)` | `views.write-terminal` | API 1.4: write only to this plugin's still-running terminal in this window; trusted project, commands/events only. | +| `host::open_content_tab(tab)` | `views.open-content-tab` | API 1.4: the shared content editor protocol, without a web view; actions arrive as `content-tab-action`. | +| `host::reply_content_tab(request_id, reply)` | `views.reply-content-tab` | API 1.4: reply to an owned action in the originating window. No capability; commands/events only. | +| `host::open_diff(diff, file_name)` | `views.open-diff` | API 1.7: two texts in the invoking window's diff viewer; `file_name` (at most 256 characters) picks the highlighting. Commands/events only; each side at most 8 MiB (earlier hosts: 1 MiB), a larger side fails with `Invalid("diff too large: …")`. | +| `host::open_file_diff(diff, file_name)` | `views.open-file-diff` | API 1.10: `open_diff` where a side may be `None` (the file doesn't exist there: added or deleted); the viewer shows the other side alone. Both `None` fails with `Invalid`. | +| `RunConfigurations::configurations(root)` | export `run-configurations.configurations` | API 1.4: optional `plugin-run-configurations` world; SDK registration `run_configurations`. Full project list, refreshed on configuration listing. | +| `LaunchConfigurations::launch_configurations(root)` | export `launch-configurations` | API 1.9: optional `plugin-launch-configurations` world; SDK registration `launch_configurations`. The same list with `env` and `debugger`; preferred over `run-configurations`. | +| `ExecutionConfigurations::execution_configurations(root)` | export `execution-configurations` | API 1.18: optional `plugin-execution-configurations` world; SDK registration `execution_configurations`. Adds a default `output_mode` (`Pipes` or `Pty`); preferred over `launch-configurations` and `run-configurations`. | +| `RunConfigurationCompletion::complete(project, config, field, text, caret)` | export `run-configuration-completion` | API 1.18: optional `plugin-run-configuration-completion` world; SDK registration `run_configuration_completion`. Completes the Arguments field (`field = "arguments"`) of the plugin's own configurations; items replace a UTF-16 range; 200 items, 300 ms. | +| `TestResults::parse(config, chunk)` | export `test-results.parse` | API 1.4: optional `plugin-test-results` world; SDK registration `test_results`. Bounded output batches for `framework = "plugin"`; failures use built-in parsers. | +| `TestResults::select_tests(config, tests)` | export `test-results.select-tests` | API 1.4: full replacement argv for test-tree name paths, or `None` when unsupported (the SDK default). Enables rerunning failed tests and running tree selections. | +| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. | +| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. | +| `host::fork_agent_session(agent, session_id, cwd)` → `String` | `agents.fork-session` | API 1.18: fork a recorded native agent session (`claude` or `codex`) into a new task in the invoking window's project, returning the new task id. Requires the `agents` capability and project trust; the session must belong to the project and have been recorded in `cwd`. The host builds the fork invocation; claude forks under a host-chosen id, codex assigns its own. See _Forking agent sessions_. | `Project::symbols` reads the current in-memory index: results may be partial while indexing, and locations can lag unsaved edits. Normal saves and filesystem @@ -1251,6 +1260,23 @@ host::set_console_rules(&[ In tests, `MockHost::console_rules()` returns the last list set. The mock checks the count and pattern length only, not the complexity. +### Forking agent sessions (API 1.18) + +`host::fork_agent_session(agent, session_id, cwd)` (`agents.fork-session`) continues a +recorded native agent session as a new task in the invoking window's project, returning +the task id. `agent` is a native provider (`claude` or `codex`); `session_id` is the +recorded session's canonical UUID; `cwd` must be the directory the session was recorded +in. The host validates all three against its own session discovery (the same list Import +Sessions shows) and builds the agent's fork invocation itself, naming the fork's session id +for claude while codex assigns its own — a plugin never supplies CLI arguments. The new task +starts ready; its first turn continues the recording as the agent's own fork, leaving the +original session unchanged. + +Requires the `agents` capability (granted like other capabilities, listed separately with +its purpose) and a trusted project. Without the grant the call returns `error::denied`. +An unknown session, a malformed id, a session another task already holds, or a `cwd` that +does not match the recording is an invalid or not-found error, not a fork. + ### Database sources (API 1.4) Declare `database.sources` (medium risk). All five calls require it and a @@ -2020,6 +2046,23 @@ so the plugin should tell the user to run the action once interactively. Plain H to other hosts never goes through this flow: declare `net.http:<host>`. A manifest using `net:ask` declares `engines.openidea = "^1.5"`. +A setting-derived grant, `net:setting:<key>` (API 1.18), names a `string` setting of +the plugin's own schema instead of a host; `net.http:setting:<key>` is the same +over plain HTTP. The key is checked at install like the other manifest checks, and +the manifest declares `engines.openidea = "^1.18"`. When the user applies the +setting's value in Settings, a dialog names the plugin, the setting and the host — +which may be a bare host or a URL — and states plainly that a `net.http:` connection +is unencrypted. **Deny is the default**: only an explicit approval materializes the +host, which then behaves exactly like a `net:<host>` (or `net.http:<host>`) grant — +all ports, no subdomains, `*` refused, redirects unchanged. A value that reaches the +plugin any other way (a hand-edited settings file, a project settings file, a value +written by the plugin itself) is not approved: the plugin's permissions show the host +as pending with an **Approve** action. Changing the setting replaces the approval only +after the user confirms it; clearing the setting removes it. The approved hosts are +listed next to the `net:ask` ones and revocable. Unattended calls to a pending or +revoked host return `denied` without a dialog, like `net:ask`; on remote hosts the +approval is kept for the session only. + A host answer covers all ports of that host, like `net:<host>`, and never covers subdomains or wildcard patterns. IDNs are shown in ASCII (punycode); IP literals use their canonical form. Redirects are checked against the @@ -2284,6 +2327,46 @@ use (ANSI stripped, the last 5000 lines and 16 KiB per line, Soft-wrap, Clear, the exit code at the end). A toggle appends its `args` and starts the program again. It stops when the node's pane closes or the Services window is hidden. +#### Actions on the IDE's own Services nodes (API 1.18) + +A plugin can also act on the nodes the IDE puts in Services itself: run +configurations (Spring Boot, Application, …) and Docker containers. Two menus +take its commands, with `engines.openidea = "^1.18"`: + +```toml +[[contributes.menus]] +menu = "services.context" # right-click menu of the selected services +command = "hotreload.attach" +submenu = "Hot Reload" +when = "serviceKind == 'spring-boot' && serviceRunning" + +[[contributes.menus]] +menu = "services.toolbar" # Services toolbar button (the command's icon, else the plugin's) +command = "hotreload.attach" +when = "serviceSelectionCount == 1 && serviceKind == 'spring-boot'" +``` + +The `when` clause sees, for each selected service, `serviceProvider` +(`runConfigurations` or `docker`), `serviceKind` (the run configuration's kind, +such as `spring-boot`, `application` or `jar-application`, or +`docker-container`), `serviceId`, `serviceName`, `serviceRunning`, +`runConfigurationId` (empty for a container) and `serviceSelectionCount`. An +entry shows only when its `when` holds for every selected service, and not when +the selection includes a group node. The command gets the selection as its +argument, JSON text: + +```json +{"services": [{"provider": "runConfigurations", "id": "app", "kind": "spring-boot", + "name": "App", "running": true, "runConfigurationId": "app"}]} +``` + +`host::start_run` still starts only the plugin's own configurations. To launch +the user's configuration with the plugin's Java agent, bind the agent to an +executor (_Java agents_): **Run '`<name>`' with `<title>`** and **Debug '`<name>`' +with `<title>`** then appear in this menu for Application, Spring Boot and JAR +Application configurations, and go through the normal launch (build, +classpath, JDK, debugger, Stop). + #### Web views A view or custom editor can instead be a web page of the package, for UIs the @@ -2806,6 +2889,25 @@ jdk = "jetbrains" # optional: only those VM options on when the launcher is not JetBrains Runtime; the agent still loads. Arguments are separate argv items (no shell), so a path with spaces needs no quoting; a shortened command line moves only the classpath into its argument file. +- **Executors** (API 1.18). With `executor = "<title>"` (1–40 characters) the + agent no longer loads into every launch. The plugin gets an executor beside + Run and Debug instead, as IDEA's "Run with JRebel" or "Profile": **Run '`<name>`' + with `<title>`** and **Debug '`<name>`' with `<title>`** in the run widget's ⋮ menu, + the gutter's ▶ menu, the context menus' run entries and the Services context + menu of those configurations, plus the actions **Run with `<title>`** and + **Debug with `<title>`** (Find Action, Keymap). Only launches through them get + the agent and its `vmOptions`; the grant and jar pin are the same. Without + `java.agent` the IDE says so instead of launching, and a configuration on a + run target is refused the same way. + + ```toml + [[contributes.javaAgents]] + path = "agent/hotreload-agent.jar" + vmOptions = ["-XX:+AllowEnhancedClassRedefinition"] + jdk = "jetbrains" + executor = "Hot Reload" + ``` + - Not in this version: tests (JUnit), Maven and Gradle goals (an Application set to _Build and run using: Gradle_ runs as a Gradle task), application servers (Tomcat), remote JVM debug, configurations on a run target, and @@ -3674,7 +3776,7 @@ no generic env-forwarding flags are added. Container env is forwarded only if the wrapper's own conventions allow it. Registration never changes a selection. The first registration prompts the -project's windows: “Use <name> for running PHP / Node / Composer in this project?” +project's windows: “Use `<name>` for running PHP / Node / Composer in this project?” with **Use** / **Not now**. The first answer is remembered on the host per project + plugin + target id. Use sets the project's default run target and its PHP and Node run-target choices; Not now leaves settings alone. Interpreters diff --git a/plugins/official/ai-completion/dist/plugin.wasm b/plugins/official/ai-completion/dist/plugin.wasm index f04eab0b6..a66d6b4e4 100644 Binary files a/plugins/official/ai-completion/dist/plugin.wasm and b/plugins/official/ai-completion/dist/plugin.wasm differ diff --git a/plugins/official/ai-completion/dist/plugin.wasm.sources b/plugins/official/ai-completion/dist/plugin.wasm.sources index 7732761d3..90871b02f 100644 --- a/plugins/official/ai-completion/dist/plugin.wasm.sources +++ b/plugins/official/ai-completion/dist/plugin.wasm.sources @@ -1 +1 @@ -81f868bbdc6d1962a210d80c0bcc3d308aae4778074a7c0fc186f63c2ff61eac +4d117cb0757b72193decd8cd06e1667d52bf4bbabf3cf015bde1367b5219b708 diff --git a/plugins/official/blame-annotations/dist/plugin.wasm b/plugins/official/blame-annotations/dist/plugin.wasm index 12c6cdd57..607a20f45 100644 Binary files a/plugins/official/blame-annotations/dist/plugin.wasm and b/plugins/official/blame-annotations/dist/plugin.wasm differ diff --git a/plugins/official/blame-annotations/dist/plugin.wasm.sources b/plugins/official/blame-annotations/dist/plugin.wasm.sources index 0ae4703fa..b30e2b6af 100644 --- a/plugins/official/blame-annotations/dist/plugin.wasm.sources +++ b/plugins/official/blame-annotations/dist/plugin.wasm.sources @@ -1 +1 @@ -f7fe1f6c6dd7d0ca6d6d00822e9befb2be9dac290e43857fa34e25da58ea3404 +01670e76944a2bff7845f8e06ef548a380c57d927a83e5ebf134f26c3736b6fb diff --git a/plugins/official/checkstyle/dist/plugin.wasm b/plugins/official/checkstyle/dist/plugin.wasm index 562800618..53d0edb9a 100644 Binary files a/plugins/official/checkstyle/dist/plugin.wasm and b/plugins/official/checkstyle/dist/plugin.wasm differ diff --git a/plugins/official/checkstyle/dist/plugin.wasm.sources b/plugins/official/checkstyle/dist/plugin.wasm.sources index 01296cd7f..8d5f57684 100644 --- a/plugins/official/checkstyle/dist/plugin.wasm.sources +++ b/plugins/official/checkstyle/dist/plugin.wasm.sources @@ -1 +1 @@ -160dc378e930f137643b36a28a6eba4da6c1fa67e15348e82df93904a8cd6eeb +f5817cb75f4a4d9ba34074e6637572414d46ce2313e050ba81583af1ad5a639d diff --git a/plugins/official/container-runner/dist/plugin.wasm b/plugins/official/container-runner/dist/plugin.wasm index aa7ad3416..657173e8f 100644 Binary files a/plugins/official/container-runner/dist/plugin.wasm and b/plugins/official/container-runner/dist/plugin.wasm differ diff --git a/plugins/official/container-runner/dist/plugin.wasm.sources b/plugins/official/container-runner/dist/plugin.wasm.sources index 97928d3c2..6089d40f2 100644 --- a/plugins/official/container-runner/dist/plugin.wasm.sources +++ b/plugins/official/container-runner/dist/plugin.wasm.sources @@ -1 +1 @@ -84c49b6c40314c5b8f4f366d51575abda6b3645d60010a2f6492bba9e18fa62a +ecdab1590c6f64b59ee7dfa7095ed8e2bfcccaa59ecf833f0a16bac6dd4a1ccf diff --git a/plugins/official/csv-editor/dist/plugin.wasm b/plugins/official/csv-editor/dist/plugin.wasm index 7383cd282..74d953cd1 100644 Binary files a/plugins/official/csv-editor/dist/plugin.wasm and b/plugins/official/csv-editor/dist/plugin.wasm differ diff --git a/plugins/official/csv-editor/dist/plugin.wasm.sources b/plugins/official/csv-editor/dist/plugin.wasm.sources index b91558c6f..d00135802 100644 --- a/plugins/official/csv-editor/dist/plugin.wasm.sources +++ b/plugins/official/csv-editor/dist/plugin.wasm.sources @@ -1 +1 @@ -50d106a7b96c240652da5f25f0e2fc083a135c587879080687eb72a5b3d90769 +f67d34142192720ed748cb3fee8e198617232539f4f1381073c84fa8beda58e6 diff --git a/plugins/official/git-toolbox/dist/plugin.wasm b/plugins/official/git-toolbox/dist/plugin.wasm index 0a39487a5..c5145b667 100644 Binary files a/plugins/official/git-toolbox/dist/plugin.wasm and b/plugins/official/git-toolbox/dist/plugin.wasm differ diff --git a/plugins/official/git-toolbox/dist/plugin.wasm.sources b/plugins/official/git-toolbox/dist/plugin.wasm.sources index 3109e5649..c6d1a298e 100644 --- a/plugins/official/git-toolbox/dist/plugin.wasm.sources +++ b/plugins/official/git-toolbox/dist/plugin.wasm.sources @@ -1 +1 @@ -6c3045316db235e129cc211040dd62ba4e3ed9bfc6c997aba61c5946929100b2 +fad90a072702f13b64e276a48eb2ea66bdaae1c043fe7cb074388ac260756611 diff --git a/plugins/official/graphviz/dist/plugin.wasm b/plugins/official/graphviz/dist/plugin.wasm index b3dac2544..572a14e23 100644 Binary files a/plugins/official/graphviz/dist/plugin.wasm and b/plugins/official/graphviz/dist/plugin.wasm differ diff --git a/plugins/official/graphviz/dist/plugin.wasm.sources b/plugins/official/graphviz/dist/plugin.wasm.sources index 658f0d6c4..1334add74 100644 --- a/plugins/official/graphviz/dist/plugin.wasm.sources +++ b/plugins/official/graphviz/dist/plugin.wasm.sources @@ -1 +1 @@ -006ecb56f6657044b54e8752c95fb3dbcaf98384124042f25298d27ab5c66773 +19020226d8ad23739f52e8f527a9ec43de31529e288d88687a90a906df265351 diff --git a/plugins/official/key-promoter/dist/plugin.wasm b/plugins/official/key-promoter/dist/plugin.wasm index 49433dd24..cb9614456 100644 Binary files a/plugins/official/key-promoter/dist/plugin.wasm and b/plugins/official/key-promoter/dist/plugin.wasm differ diff --git a/plugins/official/key-promoter/dist/plugin.wasm.sources b/plugins/official/key-promoter/dist/plugin.wasm.sources index 06e010511..e9c720624 100644 --- a/plugins/official/key-promoter/dist/plugin.wasm.sources +++ b/plugins/official/key-promoter/dist/plugin.wasm.sources @@ -1 +1 @@ -2c749192ea33f65d0396103371d3f8f21d4ce467268efb821705d806aa45973e +675472e967a2fa8e15155f939a5d734aa1892474506725e7b6ef1dd843990e88 diff --git a/plugins/official/license-header/dist/plugin.wasm b/plugins/official/license-header/dist/plugin.wasm index d09145f16..4e224d199 100644 Binary files a/plugins/official/license-header/dist/plugin.wasm and b/plugins/official/license-header/dist/plugin.wasm differ diff --git a/plugins/official/license-header/dist/plugin.wasm.sources b/plugins/official/license-header/dist/plugin.wasm.sources index a87b7b133..fa3d368e8 100644 --- a/plugins/official/license-header/dist/plugin.wasm.sources +++ b/plugins/official/license-header/dist/plugin.wasm.sources @@ -1 +1 @@ -3d8838b8444bd7191d33d11b2e1e40b3f88b96b3bddd8ecf5e4936bac299437d +00f67f0116dfd51dd6e7597c06547bb5a6ac38462f8b1bf63c3863268b3684b7 diff --git a/plugins/official/mybatis/dist/plugin.wasm b/plugins/official/mybatis/dist/plugin.wasm index c04777256..307286232 100644 Binary files a/plugins/official/mybatis/dist/plugin.wasm and b/plugins/official/mybatis/dist/plugin.wasm differ diff --git a/plugins/official/mybatis/dist/plugin.wasm.sources b/plugins/official/mybatis/dist/plugin.wasm.sources index 3699b6805..877c4e8df 100644 --- a/plugins/official/mybatis/dist/plugin.wasm.sources +++ b/plugins/official/mybatis/dist/plugin.wasm.sources @@ -1 +1 @@ -2e788c8bd398ee5386e92e0ff8747e8470e12cb37eb6f8ca1cea9c9c79fc3366 +4eb13361d05380d220fc6db31280003b91696e37ebdcfa16160e86eb879be048 diff --git a/plugins/official/regex-tester/dist/plugin.wasm b/plugins/official/regex-tester/dist/plugin.wasm index e87f3e8c0..ddba2ed43 100644 Binary files a/plugins/official/regex-tester/dist/plugin.wasm and b/plugins/official/regex-tester/dist/plugin.wasm differ diff --git a/plugins/official/regex-tester/dist/plugin.wasm.sources b/plugins/official/regex-tester/dist/plugin.wasm.sources index 318f62ec5..e19e86f1d 100644 --- a/plugins/official/regex-tester/dist/plugin.wasm.sources +++ b/plugins/official/regex-tester/dist/plugin.wasm.sources @@ -1 +1 @@ -ba45d5376905a5602c1badb0ec94b351447b4eaf57cd0f19628b13ba59da961f +64f8783667f14707f51859c766d2e3beb691996e147e7cb8a87ceb9bf292dc4f diff --git a/plugins/official/solidity/dist/plugin.wasm b/plugins/official/solidity/dist/plugin.wasm index bf14886d1..8f582fa9d 100644 Binary files a/plugins/official/solidity/dist/plugin.wasm and b/plugins/official/solidity/dist/plugin.wasm differ diff --git a/plugins/official/solidity/dist/plugin.wasm.sources b/plugins/official/solidity/dist/plugin.wasm.sources index fba71d026..dbd2a9e48 100644 --- a/plugins/official/solidity/dist/plugin.wasm.sources +++ b/plugins/official/solidity/dist/plugin.wasm.sources @@ -1 +1 @@ -5ec6de5a1d9a00e5f57fcf1ee6e6f04115061c08c4db6f9c1c7d83611caccc65 +b9864d2ea64473cbeeabf8b97d9dac551d8f3b84d5dba435c090119a020ce1b6 diff --git a/plugins/official/string-tools/dist/plugin.wasm b/plugins/official/string-tools/dist/plugin.wasm index 66abce39f..c9c9154bd 100644 Binary files a/plugins/official/string-tools/dist/plugin.wasm and b/plugins/official/string-tools/dist/plugin.wasm differ diff --git a/plugins/official/string-tools/dist/plugin.wasm.sources b/plugins/official/string-tools/dist/plugin.wasm.sources index 33673ef82..2c2226318 100644 --- a/plugins/official/string-tools/dist/plugin.wasm.sources +++ b/plugins/official/string-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -4234fcfd105b5c6413372f4eca1bf707f912888d051ebed21f3959389c261def +9935722246fceecf99cd18ffc4d7b365ef060478f2cba0142f17b19374b31205 diff --git a/plugins/official/test-runner/dist/plugin.wasm b/plugins/official/test-runner/dist/plugin.wasm index 0b4352bb9..d45d6c590 100644 Binary files a/plugins/official/test-runner/dist/plugin.wasm and b/plugins/official/test-runner/dist/plugin.wasm differ diff --git a/plugins/official/test-runner/dist/plugin.wasm.sources b/plugins/official/test-runner/dist/plugin.wasm.sources index f75d156f6..a487ff493 100644 --- a/plugins/official/test-runner/dist/plugin.wasm.sources +++ b/plugins/official/test-runner/dist/plugin.wasm.sources @@ -1 +1 @@ -70fbad5fc1d16069629e670fce2b4076113dd13cac3c794723d551dfdd500ce3 +a37ecea6b1e7baa012d45386a107078ada84671f8a51e01211e2fd45c761ae32 diff --git a/plugins/official/todo-finder/dist/plugin.wasm b/plugins/official/todo-finder/dist/plugin.wasm index 37b1f1040..4ad402aba 100644 Binary files a/plugins/official/todo-finder/dist/plugin.wasm and b/plugins/official/todo-finder/dist/plugin.wasm differ diff --git a/plugins/official/todo-finder/dist/plugin.wasm.sources b/plugins/official/todo-finder/dist/plugin.wasm.sources index 9a28a7645..d6d738997 100644 --- a/plugins/official/todo-finder/dist/plugin.wasm.sources +++ b/plugins/official/todo-finder/dist/plugin.wasm.sources @@ -1 +1 @@ -d38a8314d156e1a4143cb1eb9dccb2fe01d3add4760570af4152f346307df297 +46437e4729fd25b9e1f19452ed97a907eef5f7b797033ff93efeaae47509debf diff --git a/sdk/rust/openidea-plugin/src/host.rs b/sdk/rust/openidea-plugin/src/host.rs index 6a08b9b41..6970282c3 100644 --- a/sdk/rust/openidea-plugin/src/host.rs +++ b/sdk/rust/openidea-plugin/src/host.rs @@ -1096,6 +1096,10 @@ mod imp { Ok(list.into_iter().map(|c| crate::Contribution { plugin: c.plugin, data: c.data }).collect()) } + pub fn fork_agent_session(agent: &str, session_id: &str, cwd: &str) -> Result<String, Error> { + wit::agents::fork_session(agent, session_id, cwd).map_err(error) + } + pub fn run_process( program: &str, args: &[String], @@ -2315,3 +2319,14 @@ pub fn mcp_stdio_command() -> Option<Vec<String>> { pub fn extension_contributions(point: &str) -> Result<Vec<crate::Contribution>, Error> { imp::extension_contributions(point) } + +/// Fork a recorded native agent session into a new task in the open project, +/// returning the new task id (API 1.18). Requires the `agents` capability and an +/// invoking window. The session must belong to that window's project and have +/// been recorded in `cwd`; the host builds the fork invocation and names the +/// fork's session id for claude (codex assigns its own). `agent` is a +/// native provider (`claude` or `codex`). The new task's first turn continues the +/// recording as the agent's own fork. Needs `engines.openidea = "^1.18"`. +pub fn fork_agent_session(agent: &str, session_id: &str, cwd: &str) -> Result<String, Error> { + imp::fork_agent_session(agent, session_id, cwd) +} diff --git a/sdk/rust/openidea-plugin/src/mock.rs b/sdk/rust/openidea-plugin/src/mock.rs index 9d9592fa1..3ff110fa2 100644 --- a/sdk/rust/openidea-plugin/src/mock.rs +++ b/sdk/rust/openidea-plugin/src/mock.rs @@ -206,6 +206,8 @@ struct State { run_remote_targets: BTreeSet<String>, configuration_runs: Vec<(String, String, Vec<String>, bool)>, configuration_run_options: Vec<(String, String, Vec<String>, crate::RunStartOptions, crate::OutputMode)>, + /// `(agent, session_id, cwd)` of each `fork_agent_session` call. + agent_forks: Vec<(String, String, String)>, log_tabs: Vec<MockLogTab>, locations: Vec<(String, u32, u32)>, settings: BTreeMap<String, String>, @@ -747,6 +749,10 @@ impl MockHost { ) -> Vec<(String, String, Vec<String>, crate::RunStartOptions, crate::OutputMode)> { self.state.borrow().configuration_run_options.clone() } + /// Recorded `fork_agent_session` calls as `(agent, session_id, cwd)` (API 1.18). + pub fn agent_forks(&self) -> Vec<(String, String, String)> { + self.state.borrow().agent_forks.clone() + } /// Makes the language server `server` run and answer `method` with `result` (JSON). /// A server with no answer set is not running: requests to it are not-found. pub fn set_language_server_response(&self, server: &str, method: &str, result: &str) { @@ -2791,6 +2797,14 @@ pub mod current { .ok_or_else(|| Error::NotFound(format!("no running plugin declares {point}"))) }) } + pub fn fork_agent_session(agent: &str, session_id: &str, cwd: &str) -> Result<String, Error> { + with(|s| { + require(s, "agents")?; + let id = format!("mock-agent-task-{}", s.agent_forks.len()); + s.agent_forks.push((agent.into(), session_id.into(), cwd.into())); + Ok(id) + }) + } pub fn register_run_target(project: &ProjectRes, target: &crate::PluginRunTarget) -> Result<(), Error> { register_run_target_with_overrides(project, &target.clone().into()) diff --git a/sdk/rust/openidea-plugin/wit/agents.wit b/sdk/rust/openidea-plugin/wit/agents.wit new file mode 100644 index 000000000..b833f3b91 --- /dev/null +++ b/sdk/rust/openidea-plugin/wit/agents.wit @@ -0,0 +1,14 @@ +package openidea:plugin@1.18.0; + +/// Forking recorded native agent sessions into new tasks (API 1.18). Requires +/// the `agents` capability. The session must belong to the invoking window's +/// project and have been recorded in `cwd`; the host builds the fork invocation +/// and names the fork's id for claude (codex assigns its own). +interface agents { + use types.{error}; + /// Fork the recorded session `session-id` of `agent` (a native provider, + /// `claude` or `codex`) into a new task in the open project, returning the + /// new task id. `cwd` must be where the session was recorded. The first + /// turn continues the recording as the agent's own fork. + fork-session: func(agent: string, session-id: string, cwd: string) -> result<string, error>; +} \ No newline at end of file diff --git a/sdk/rust/openidea-plugin/wit/plugin.wit b/sdk/rust/openidea-plugin/wit/plugin.wit index 8cc725b88..ec2debc26 100644 --- a/sdk/rust/openidea-plugin/wit/plugin.wit +++ b/sdk/rust/openidea-plugin/wit/plugin.wit @@ -40,6 +40,7 @@ world plugin { import mcp; import settings; import extensions; + import agents; export lifecycle; export commands; diff --git a/smoke/debug.test.ts b/smoke/debug.test.ts index 0fd4d979d..4f6a1ebb1 100644 --- a/smoke/debug.test.ts +++ b/smoke/debug.test.ts @@ -5,8 +5,20 @@ * variables, evaluation, Step Over and Resume, with the debugger the IDE installs (GDB: * the toolchain's own, 14+ for its DAP interpreter). */ -import { execFileSync } from "node:child_process"; -import { cpSync, existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"; +import { type ChildProcess, execFileSync, spawn } from "node:child_process"; +import { + appendFileSync, + cpSync, + existsSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { createServer } from "node:net"; import { get } from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -21,9 +33,19 @@ import { activate as activateBuildTools } from "@/features/build-tools"; import { useBuild } from "@/features/build-tools/store"; import { activate as activateDebugger } from "@/features/debugger"; import { addBreakpoint, flushBreakpoints } from "@/features/debugger/breakpoints/store"; -import { activeSession, evaluate, rootOf, sessionSupports, useDebug } from "@/features/debugger/state"; +import { nodeRemoteType, remoteWaitingNote } from "@/features/debugger/remote"; +import { + activeSession, + evaluate, + isLive, + rootOf, + selectSession, + sessionSupports, + useDebug, +} from "@/features/debugger/state"; import { activate as activateRun } from "@/features/run"; import { resetRuns, useRun } from "@/features/run/store"; +import { newConfigOfType, withParams } from "@/features/run/types"; import { activateWorkbench } from "@/workbench/activate"; import { useNotifications } from "@/workbench/notificationStore"; import { connectDesktop } from "./desktop"; @@ -220,14 +242,18 @@ beforeAll(() => { }); afterAll(() => deactivate?.()); -afterEach(async () => { +async function teardown() { resetRuns(); disconnect?.(); + disconnect = null; // `close` kills the server and what it started (debug adapters, language servers) // and waits until they're gone, so the removal below can't race their writes. await server?.close(); + server = null; if (base) rmSync(base, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 }); -}); + base = ""; +} +afterEach(teardown); async function open(c: Case): Promise<string> { base = realpathSync(mkdtempSync(join(tmpdir(), "openidea-smoke-"))); @@ -615,6 +641,102 @@ async function traceStream(language: string, t: NonNullable<Case["streamTrace"]> ]); } +/** More of a language's debugging, each with a project of its own (CI runs one test per language). */ +const MORE: Record<string, Array<() => Promise<void>>> = { + typescript: [() => nodeReconnect(true), () => nodeReconnect(false)], +}; + for (const language of Object.keys(CASES)) { - test(language, () => smoke(language)); + test(language, async () => { + await smoke(language); + for (const more of MORE[language] ?? []) { + // oxlint-disable-next-line no-await-in-loop -- each case starts its own server after the last one is gone. + await teardown(); + // oxlint-disable-next-line no-await-in-loop -- see above. + await more(); + } + }); +} + +/** A free TCP port on the loopback interface. */ +const freePort = () => + new Promise<number>((resolve, reject) => { + const srv = createServer(); + srv.once("error", reject); + srv.listen(0, "127.0.0.1", () => { + const { port } = srv.address() as { port: number }; + srv.close(() => resolve(port)); + }); + }); + +/** + * Attach to Node.js on a `node --watch` process that restarts when its file changes: with + * Reconnect automatically the session waits and attaches again, stopping at the same + * breakpoint; without it the session ends with the process. + */ +async function nodeReconnect(restart: boolean) { + const root = await open({ fixture: "node-test-app" } as Case); + await install("js-debug"); + const path = join(root, "watched.js"); + writeFileSync(path, "function work(n) {\n return n * 2;\n}\nsetInterval(() => work(21), 300);\n"); + addBreakpoint(path, 1); + const port = await freePort(); + const node: ChildProcess = spawn("node", ["--watch", `--inspect=127.0.0.1:${port}`, "watched.js"], { + cwd: root, + stdio: "ignore", + }); + try { + const blank = newConfigOfType(nodeRemoteType, []); + const params = { ...blank.params, host: "127.0.0.1", port: String(port), ...(restart ? { restart: "true" } : {}) }; + const config = withParams({ ...blank, name: "Attach" }, params, nodeRemoteType); + // The inspector comes up once node has started the program. + await new Promise((r) => setTimeout(r, 1000)); + const stops = useDebug.getState().stopSeq; + await executeAction("debug.startConfig", config); + const first = await until("the breakpoint", stoppedAfter(stops)); + expect([first.frames[0]!.path, first.frames[0]!.line], shown()).toEqual([path, 1]); + const rootId = rootOf(first).id; + const processes = () => Object.values(useDebug.getState().sessions).filter((c) => c.parent === rootId); + // What the Frames pane shows for the session: the note once its process has ended and none is attached. + const note = () => + remoteWaitingNote( + useDebug.getState().sessions[rootId]?.runConfig, + processes().length > 0 && !processes().some(isLive), + ); + expect(note(), "no note while attached the first time").toBeNull(); + await executeAction("debug.resume"); + + // `node --watch` restarts the program when its file changes. + appendFileSync(path, "// changed\n"); + if (!restart) { + await until("the end", () => Object.values(useDebug.getState().sessions).every((d) => !isLive(d))); + return; + } + let waited = ""; + const again = await until("the breakpoint after the restart", () => { + if (!isLive(useDebug.getState().sessions[rootId])) + throw new Error(`the session ended with the process\n${shown()}`); + waited ||= note() ?? ""; + const s = paused(); + return s && s.id !== first.id && s; + }); + expect([again.frames[0]!.path, again.frames[0]!.line], shown()).toEqual([path, 1]); + expect(rootOf(again).id, "the same debug session").toBe(rootId); + expect(again.id, "a new process").not.toBe(first.id); + expect( + processes().map((c) => c.id), + "one process tab", + ).toEqual([again.id]); + expect(waited).toBe(`Waiting to reconnect to Node.js on 127.0.0.1:${port}`); + + // With the process gone, the session waits for it; Stop ends it. + await executeAction("debug.resume"); + node.kill(); + await until("the wait for the process", () => note()); + selectSession(rootId); + await executeAction("debug.stop"); + await until("the end", () => Object.values(useDebug.getState().sessions).every((d) => !isLive(d))); + } finally { + node.kill(); + } } diff --git a/smoke/run.test.ts b/smoke/run.test.ts index 8d9e9f2af..4fdb278c6 100644 --- a/smoke/run.test.ts +++ b/smoke/run.test.ts @@ -100,6 +100,17 @@ const CASES: Record<string, Case | Case[]> = { file: "test/pricing.spec.js", }, }, + { + fixture: "jasmine-app", + setup: npmInstall, + tests: { + config: "npm:test", + failing: (c) => env(c, { OPENIDEA_FAIL: "1" }), + passed: 4, + failed: "intentionally fails (set OPENIDEA_FAIL=1)", + file: "spec/cartSpec.js", + }, + }, ], python: { fixture: "python-app", diff --git a/src-tauri/src/commands/plugin.rs b/src-tauri/src/commands/plugin.rs index 05fa5f5d1..b41d89f11 100644 --- a/src-tauri/src/commands/plugin.rs +++ b/src-tauri/src/commands/plugin.rs @@ -118,6 +118,9 @@ pub fn create_host(app: &AppHandle, data_dir: &Path, project_host: &Arc<ide_host host.set_downloads(project_host.global_settings.effective().tool_downloads); #[cfg(target_os = "macos")] host.set_secret_store(Arc::new(KeychainSecrets)); + // Secret Service / Windows Credential Manager elsewhere, like saved SSH and agent values. + #[cfg(not(target_os = "macos"))] + host.use_credential_store(); ide_host::plugins::set_editor_providers(Some(&host)); let weak = Arc::downgrade(project_host); host.set_project_policy(Arc::new(move |root| { @@ -252,6 +255,52 @@ pub async fn plugin_revoke_net_host(state: State<'_, AppState>, id: String, host blocking(move || plugins.revoke_net_host(&id, &host)).await } +/// The host a `net:setting:` grant derives from `value` (a bare host or a +/// URL), validated with the manifest host rules; an error refuses the value. +#[desktop_command(trust = always)] +#[tauri::command] +#[specta::specta] +pub async fn plugin_net_setting_host( + state: State<'_, AppState>, + id: String, + setting: String, + value: String, +) -> IdeResult<String> { + let plugins = state.plugins.clone(); + blocking(move || plugins.net_setting_host(&id, &setting, &value)).await +} + +/// Approves `host` for the plugin's `net:setting:<key>` grant (applied in +/// Settings, or the pending row); refused when the setting no longer holds it. +#[desktop_command(trust = outside_restricted)] +#[tauri::command] +#[specta::specta] +pub async fn plugin_approve_net_setting( + state: State<'_, AppState>, + id: String, + setting: String, + http: bool, + host: String, +) -> IdeResult<PluginInfo> { + let plugins = state.plugins.clone(); + blocking(move || plugins.approve_net_setting(&id, &setting, http, &host)).await +} + +/// Drops the approved host of a `net:setting:<key>` grant (revoked, or the +/// setting's value cleared). +#[desktop_command(trust = outside_restricted)] +#[tauri::command] +#[specta::specta] +pub async fn plugin_forget_net_setting( + state: State<'_, AppState>, + id: String, + setting: String, + http: bool, +) -> IdeResult<PluginInfo> { + let plugins = state.plugins.clone(); + blocking(move || plugins.forget_net_setting(&id, &setting, http)).await +} + /// Links a development plugin folder (`openidea-plugin link` does the same from a terminal). #[desktop_command(trust = trusted)] #[tauri::command] @@ -650,8 +699,10 @@ pub fn plugin_set_theme_frame(state: State<'_, AppState>, color: Option<String>) ide_command::desktop_domain!( plugin_activation_event, + plugin_approve_net_setting, plugin_assets, plugin_catalog, + plugin_forget_net_setting, plugin_grant, plugin_install_dir, plugin_installed_intellij_themes, @@ -661,6 +712,7 @@ ide_command::desktop_domain!( plugin_market, plugin_market_download, plugin_market_url, + plugin_net_setting_host, plugin_preview_install, plugin_read_intellij_theme, plugin_reload, diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index dc41117f2..6dc1d02b7 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -849,6 +849,7 @@ mod tests { "window.toggleFullScreen", "view.toggleTheme", "editor.toggleZen", + "view.toggleZenMode", "view.toggleToolbar", "view.toggleToolWindowBars", "view.toggleStatusBar", diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rs index 820887725..5a54f0464 100644 --- a/src-tauri/src/remote_dev.rs +++ b/src-tauri/src/remote_dev.rs @@ -1529,6 +1529,7 @@ mod tests { settings: Default::default(), workspace: None, unity: None, + unreal: None, }) .unwrap()) } diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index f2543fe1f..388e403bb 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -18,6 +18,7 @@ agent_delete trusted project_host bin agent_entries always project_host bindings async agent_external_sessions trusted project_host bindings async agent_fork trusted project_host bindings async +agent_fork_session trusted project_host bindings async agent_grouped_changes trusted project_host bindings async agent_hermes_profiles trusted project_host bindings async agent_import_session trusted project_host bindings async @@ -42,6 +43,7 @@ agent_respond trusted project_host bin agent_rollback trusted project_host bindings async agent_rollback_changes trusted project_host bindings async agent_send_queued_now trusted project_host bindings async +agent_set_additional_args trusted project_host bindings sync agent_set_command trusted project_host bindings sync agent_set_config trusted project_host bindings async agent_set_env trusted project_host bindings sync @@ -454,6 +456,7 @@ plugin_answer_command trusted project_host bin plugin_answer_commit trusted project_host bindings sync plugin_answer_prompt trusted project_host bindings sync plugin_answer_run_target trusted project_host bindings async +plugin_approve_net_setting outside_restricted desktop bindings async plugin_assets always desktop bindings async plugin_cancel_task trusted project_host bindings sync plugin_catalog always desktop bindings async @@ -468,6 +471,7 @@ plugin_decoration_sets trusted project_host bin plugin_endpoints trusted project_host bindings async plugin_event_kinds trusted project_host bindings async plugin_finish_operation trusted project_host bindings sync +plugin_forget_net_setting outside_restricted desktop bindings async plugin_formatters trusted project_host bindings sync plugin_grant outside_restricted desktop bindings async plugin_install_dir outside_restricted desktop bindings async @@ -485,6 +489,7 @@ plugin_navigation_goto trusted project_host bin plugin_navigation_index trusted project_host bindings async plugin_navigation_invalidate trusted project_host bindings sync plugin_navigation_markers trusted project_host bindings async +plugin_net_setting_host always desktop bindings async plugin_parse_test_results trusted project_host bindings async plugin_post_events trusted project_host bindings sync plugin_prepare_debug_run trusted project_host bindings async @@ -750,6 +755,7 @@ vcs_has_commit always project_host bin vcs_has_hook always project_host bindings async vcs_ignore_blame_revision trusted project_host bindings async vcs_ignored_files always project_host bindings async +vcs_image_at always project_host bindings async vcs_init always project_host bindings async vcs_inspect_push trusted project_host bindings async vcs_invalidate_log_signatures always project_host bindings async @@ -831,6 +837,7 @@ vcs_worktree_include always project_host bin vcs_worktrees always project_host bindings async vcs_write_patch always project_host bindings async web_browsers always desktop bindings async +web_css_variables always project_host bindings async web_goto always project_host bindings async web_open always desktop bindings async web_serves_page trusted desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index f81fd8143..4e1573e9b 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -64,6 +64,11 @@ export const commands = { agentExternalSessions: () => typedError<ExternalSession[], IdeError>(__TAURI_INVOKE("agent_external_sessions")), /** Copies the task's conversation into a new task, up to its first `turns` turns (all when `None`). */ agentFork: (task: string, turns: number | null) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_fork", { task, turns })), + /** + * Forks a recorded external session into a new task: its first turn continues the recording + * as the agent's own fork, under an id the host chooses. `cwd` must be where it was recorded. + */ + agentForkSession: (provider: string, sessionId: string, cwd: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_fork_session", { provider, sessionId, cwd })), /** The task's uncommitted changes and the commits made since it started. */ agentGroupedChanges: (task: string) => typedError<AgentChanges, IdeError>(__TAURI_INVOKE("agent_grouped_changes", { task })), /** Hermes Agent profiles on this machine (`default` first); empty without Hermes. */ @@ -102,7 +107,7 @@ export const commands = { * Reads the ACP registry's install state for every provider from disk, so it runs on the * blocking pool. */ - agentProviders: () => typedError<AgentProvider[], IdeError>(__TAURI_INVOKE("agent_providers")), + agentProviders: () => typedError<AgentProvider_Serialize[], IdeError>(__TAURI_INVOKE("agent_providers")), /** Refreshes the model catalog; force bypasses freshness, not the cooldown. */ agentRefreshModels: (provider: string, force: boolean, model: string | null) => typedError<AgentModelCatalog, IdeError>(__TAURI_INVOKE("agent_refresh_models", { provider, force, model })), /** @@ -139,6 +144,8 @@ export const commands = { "lastTurn" | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_rollback_changes", { task, paths, view })), /** Sends a queued message now, interrupting the current turn. */ agentSendQueuedNow: (task: string, queued: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_send_queued_now", { task, queued })), + /** Sets additional launch arguments for a built-in ACP agent; an empty list resets them. */ + agentSetAdditionalArgs: (id: string, args: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_additional_args", { id, args })), /** * Overrides built-in agent `id`'s command with `command` (its agent file keeps the * built-in's driver and arguments), or returns it to auto-detection with `None`. @@ -854,7 +861,7 @@ export const commands = { * The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath: * the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the * classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from - * Maven Central), and, + * Maven Central unless only the configured package registries are allowed), and, * for a Maven module, what its Surefire configuration gives the forked test JVM. */ javaJunitRunner: (module: string, classPaths: string[]) => typedError<JunitLaunch, IdeError>(__TAURI_INVOKE("java_junit_runner", { module, classPaths })), @@ -1219,6 +1226,11 @@ export const commands = { */ pluginAnswerPrompt: (promptId: string, answer: string[] | null) => __TAURI_INVOKE<boolean>("plugin_answer_prompt", { promptId, answer }), pluginAnswerRunTarget: (id: string, useTarget: boolean) => typedError<Settings_Serialize, IdeError>(__TAURI_INVOKE("plugin_answer_run_target", { id, useTarget })), + /** + * Approves `host` for the plugin's `net:setting:<key>` grant (applied in + * Settings, or the pending row); refused when the setting no longer holds it. + */ + pluginApproveNetSetting: (id: string, setting: string, http: boolean, host: string) => typedError<PluginInfo, IdeError>(__TAURI_INVOKE("plugin_approve_net_setting", { id, setting, http, host })), /** Validated assets of a plugin whose id starts with `prefix` (icon theme mapping and SVGs). */ pluginAssets: (pluginId: string, prefix: string) => typedError<([string, string])[], IdeError>(__TAURI_INVOKE("plugin_assets", { pluginId, prefix })), /** Cancels a plugin task (`taskStarted` with `cancellable`). */ @@ -1251,6 +1263,11 @@ export const commands = { pluginEventKinds: () => __TAURI_INVOKE<EventKind[]>("plugin_event_kinds"), /** Reports exactly one completion from the operation's launching window. */ pluginFinishOperation: (id: string, status: number | null, stopped: boolean) => typedError<boolean, IdeError>(__TAURI_INVOKE("plugin_finish_operation", { id, status, stopped })), + /** + * Drops the approved host of a `net:setting:<key>` grant (revoked, or the + * setting's value cleared). + */ + pluginForgetNetSetting: (id: string, setting: string, http: boolean) => typedError<PluginInfo, IdeError>(__TAURI_INVOKE("plugin_forget_net_setting", { id, setting, http })), pluginFormatters: () => typedError<FormatterChoice[], IdeError>(__TAURI_INVOKE("plugin_formatters")), /** Confirms a plugin waiting for consent (project plugins, new capabilities). */ pluginGrant: (id: string, consent: Consent) => typedError<PluginInfo, IdeError>(__TAURI_INVOKE("plugin_grant", { id, consent })), @@ -1290,6 +1307,11 @@ export const commands = { pluginNavigationIndex: (paths: string[], request: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_navigation_index", { paths, request })), pluginNavigationInvalidate: (paths: string[] | null) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_navigation_invalidate", { paths })), pluginNavigationMarkers: (paths: string[]) => typedError<FileMarkers[], IdeError>(__TAURI_INVOKE("plugin_navigation_markers", { paths })), + /** + * The host a `net:setting:` grant derives from `value` (a bare host or a + * URL), validated with the manifest host rules; an error refuses the value. + */ + pluginNetSettingHost: (id: string, setting: string, value: string) => typedError<string, IdeError>(__TAURI_INVOKE("plugin_net_setting_host", { id, setting, value })), /** Parses one batch of an owned test configuration's output. */ pluginParseTestResults: (config: string, chunk: string) => typedError<PluginTestEvent[] | null, IdeError>(__TAURI_INVOKE("plugin_parse_test_results", { config, chunk })), /** Workbench events from this window (only the kinds of `plugin_event_kinds`). */ @@ -1441,6 +1463,7 @@ export const commands = { settings: Settings_Serialize, workspace?: Workspace_Serialize | null, unity?: UnityProjectInfo | null, + unreal?: UnrealProjectInfo | null, } | null>("project_current"), /** * File › Rename Project…: the project's display name (title bar, recent @@ -2124,6 +2147,8 @@ export const commands = { vcsHasHook: (repo: string | null, name: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("vcs_has_hook", { repo, name })), vcsIgnoreBlameRevision: (path: string, commit: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_ignore_blame_revision", { path, commit })), vcsIgnoredFiles: () => typedError<FileStatus[], IdeError>(__TAURI_INVOKE("vcs_ignored_files")), + /** An image at the selected Git revision or index stage as a data URL, absent if the path is missing. */ + vcsImageAt: (path: string, rev: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("vcs_image_at", { path, rev })), /** * `git init` in `dir` (VCS › Create Git Repository…): with the git of the window's project when * it is trusted, the default one in a window without a project. @@ -2287,6 +2312,11 @@ export const commands = { vcsWritePatch: (path: string, patch: string, encoding: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_write_patch", { path, patch, encoding })), /** The browsers installed on this machine. */ webBrowsers: () => typedError<Browser[], IdeError>(__TAURI_INVOKE("web_browsers")), + /** + * Custom properties declared in `doc` (from its current text, first) and in the project's + * other stylesheets (from the index, so kept up to date as files change). + */ + webCssVariables: (doc: DocId) => typedError<CssVariable[], IdeError>(__TAURI_INVOKE("web_css_variables", { doc })), /** The web reference at `pos` of `doc` and its targets; `None` when there is no reference. */ webGoto: (doc: DocId, pos: Pos) => typedError<{ reference: WebReference, @@ -2963,7 +2993,9 @@ export type AgentPrompt = { images: AgentImage[], }; -export type AgentProvider = { +export type AgentProvider = AgentProvider_Serialize | AgentProvider_Deserialize; + +export type AgentProvider_Deserialize = { id: string, name: string, /** The command line that starts its ACP server. */ @@ -2971,6 +3003,8 @@ export type AgentProvider = { /** Executable and arguments actually launched, without flattening paths containing spaces. */ program: string, args: string[], + /** Settings-managed suffix of `args`; absent for launches that cannot be edited. */ + additionalArgs?: string[] | null, defaultProgram: string | null, defaultArgs: string[], loginHint: string | null, @@ -2992,6 +3026,37 @@ export type AgentProvider = { source: AgentSource, }; +export type AgentProvider_Serialize = { + id: string, + name: string, + /** The command line that starts its ACP server. */ + command: string, + /** Executable and arguments actually launched, without flattening paths containing spaces. */ + program: string, + args: string[], + /** Settings-managed suffix of `args`; absent for launches that cannot be edited. */ + additionalArgs?: string[] | null, + defaultProgram: string | null, + defaultArgs: string[], + loginHint: string | null, + commandOverridden: boolean, + commandEditable: boolean, + commandReadOnlyReason: AgentCommandReadOnlyReason | null, + /** Whether the command was found (on `PATH`). */ + installed: boolean, + /** The built-in command can be owned by a global npm package. */ + canCheckCliUpdate: boolean, + /** Environment variables it starts with (from its agent file). */ + env: { [key in string]: string }, + /** Settings (models, modes…) the agent offered last time it ran; empty before its first session. */ + config: AgentConfigOption[], + /** Thinking-level options by model value; absent models have not reported their levels. */ + thoughtLevels: { [key in string]: AgentConfigOption[] }, + /** Slash commands it offered last time. */ + commands: AgentCommand[], + source: AgentSource, +}; + /** A question the agent asks with `AskUserQuestion`, answered by picking options or typing. */ export type AgentQuestion = { /** Stable answer identity when the provider supplies question ids. */ @@ -4971,6 +5036,14 @@ export type CreateRequest = { values: { [key in string]: string }, }; +/** A custom property declaration (`--accent: #3b82f6`), for `var(--…)` completion and hover. */ +export type CssVariable = { + name: string, + /** The declared value, whitespace collapsed. */ + value: string | null, + location: Location, +}; + /** * Payload for creating a custom ACP agent (always the ACP driver); the id * becomes the `<config>/agents/<id>.toml` file name. @@ -5183,6 +5256,8 @@ export type DbColumnInfo = { nullable: boolean, default: string | null, primaryKey: boolean, + /** `None` when it has none, or the engine keeps no comments. */ + comment?: string | null, }; /** The schema model SQL completion and resolution work from. */ @@ -5605,6 +5680,8 @@ export type DbStatementOutcome = { }; export type DbTableDetails = { + /** The table's comment; `None` when it has none, or the engine keeps no comments. */ + comment?: string | null, columns: DbColumnInfo[], indexes: DbIndexInfo[], foreignKeys: DbForeignKey[], @@ -6994,11 +7071,11 @@ export type ExternalDiffSide = { }; /** A formatter that runs outside the language servers, with its own settings group. */ -export type ExternalFormatter = "prettier" | "oxfmt" | "biome" | "ruff" | "black"; +export type ExternalFormatter = "prettier" | "oxfmt" | "biome" | "dprint" | "ruff" | "black"; -/** An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats. */ +/** An external formatter (Prettier, oxfmt, Biome, dprint, Ruff, Black) and the languages it formats. */ export type ExternalFormatterSettings = { - /** Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH. */ + /** Empty path: project node_modules (Prettier/oxfmt/Biome/dprint), managed installation, then PATH. */ path?: string, /** Ruff only: directory containing its configuration, or a configuration file. */ configurationDirectory?: string, @@ -9085,6 +9162,24 @@ export type LanguageCodeStyle_Deserialize = { keywordCase?: string | null, /** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */ identifierCase?: string | null, + /** + * Java: organize imports switches to a wildcard import once this many + * classes of one package are used (jdtls `starThreshold`; IDEA's default + * 5; unset keeps the language server's default). + */ + classCountToUseImportWithStar?: number | null, + /** + * Java: organize imports switches to a wildcard static import once this + * many statically imported names are used (jdtls `staticStarThreshold`; + * IDEA's default 3; unset keeps the language server's default). + */ + namesCountToUseStaticImportWithStar?: number | null, + /** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */ + semicolons?: string | null, + /** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */ + quotes?: string | null, + /** JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`). */ + spaces?: { [key in string]: boolean }, }; /** Editor › Code Style › <Language> › Tabs and Indents (unset fields inherit). */ @@ -9109,6 +9204,24 @@ export type LanguageCodeStyle_Serialize = { keywordCase?: string | null, /** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */ identifierCase?: string | null, + /** + * Java: organize imports switches to a wildcard import once this many + * classes of one package are used (jdtls `starThreshold`; IDEA's default + * 5; unset keeps the language server's default). + */ + classCountToUseImportWithStar?: number | null, + /** + * Java: organize imports switches to a wildcard static import once this + * many statically imported names are used (jdtls `staticStarThreshold`; + * IDEA's default 3; unset keeps the language server's default). + */ + namesCountToUseStaticImportWithStar?: number | null, + /** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */ + semicolons?: string | null, + /** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */ + quotes?: string | null, + /** JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`). */ + spaces?: { [key in string]: boolean }, }; /** Language identifier, e.g. `rust`, `typescript`, `kotlin`. Matches LSP `languageId`. */ @@ -9253,6 +9366,8 @@ export type LanguagesSettings = { prettier?: ExternalFormatterSettings, oxfmt?: ExternalFormatterSettings, biome?: ExternalFormatterSettings, + /** dprint formats every file its configuration covers: `languages` is unused. */ + dprint?: ExternalFormatterSettings, ruff?: ExternalFormatterSettings, black?: ExternalFormatterSettings, java?: JavaSettings, @@ -10328,6 +10443,11 @@ export type NewAgentTask = { * `!` command runs in it first. */ idle?: boolean, + /** + * A throwaway task (Generate Commit Message): it isn't saved, so it doesn't outlive a + * restart, and the agent keeps no session history of its own for it. + */ + ephemeral?: boolean, }; /** The approvals new agent tasks start with. */ @@ -11009,6 +11129,8 @@ export type PluginInfo = { * none of them declared by the manifest; each can be revoked. */ netHosts: string[], + /** Setting-derived hosts (`net:setting:`), approved in Settings, listed next to the `net:ask` ones. */ + netSettings: PluginNetSetting[], /** What it contributes while live (point + label). */ contributions: ContributionInfo[], /** `activation` events of the manifest. */ @@ -11041,6 +11163,11 @@ export type PluginJavaAgent = { jdk: string | null, /** The jar still has the hash recorded when `java.agent` was granted. */ approved: boolean, + /** + * The title of the executor the agent is bound to (API 1.18): "Run with <title>" and + * "Debug with <title>" launch with it; other launches leave it out. + */ + executor?: string | null, }; /** @@ -11060,6 +11187,18 @@ export type PluginLocation = { range: Range, }; +/** A `net:setting:` grant's host for Settings › Plugins: the approved one while the setting holds it, else the pending one. */ +export type PluginNetSetting = { + /** The setting key the host comes from (`server` of `net:setting:server`). */ + setting: string, + /** Plain HTTP (`net.http:setting:`) instead of HTTPS (and loopback HTTP). */ + http: boolean, + /** The approved host, while the setting still holds it. */ + host: string | null, + /** The host the setting holds now when it is not the approved one. */ + pending: string | null, +}; + /** A line a view's `process` body printed. */ export type PluginOutputLine = { stderr: boolean, @@ -11472,6 +11611,8 @@ export type ProfileSpec = * out when another one did. */ { kind: "cpuProfiles"; dir: IpcPath; root: IpcPath } | +/** One `.cpuprofile` the user opened (saved by `node --cpu-prof`, Chrome DevTools, CI). */ +{ kind: "cpuProfileFile"; path: IpcPath } | /** * Collapsed-stack files with extension `ext` in `dir`; relative frame files resolve * against `base`. `jvm_root`: map JVM class frames to sources below it. For the @@ -11514,6 +11655,7 @@ export type ProjectInfo_Deserialize = { settings: Settings_Deserialize, workspace?: Workspace_Deserialize | null, unity?: UnityProjectInfo | null, + unreal?: UnrealProjectInfo | null, }; export type ProjectInfo_Serialize = { @@ -11525,6 +11667,7 @@ export type ProjectInfo_Serialize = { settings: Settings_Serialize, workspace?: Workspace_Serialize | null, unity?: UnityProjectInfo | null, + unreal?: UnrealProjectInfo | null, }; /** An interpreter another project uses: the project root and the SDK itself. */ @@ -12535,6 +12678,13 @@ export type RunExtras_Deserialize = { * test output parser and how a single test is selected. */ testRunner?: string | null, + /** Jest / Vitest "Watch for changes": the run stays alive and reruns the tests after each edit. */ + watch?: boolean, + /** + * The plugin executor a launch goes through ("Run with <title>"): the plugin's id. Set + * on the launched copy, not saved; the plugin's executor-bound Java agent loads only then. + */ + executor?: string | null, }; export type RunExtras_Serialize = { @@ -12585,6 +12735,13 @@ export type RunExtras_Serialize = { * test output parser and how a single test is selected. */ testRunner?: string | null, + /** Jest / Vitest "Watch for changes": the run stays alive and reruns the tests after each edit. */ + watch?: boolean, + /** + * The plugin executor a launch goes through ("Run with <title>"): the plugin's id. Set + * on the launched copy, not saved; the plugin's executor-bound Java agent loads only then. + */ + executor?: string | null, }; /** A process started from a run configuration. */ @@ -14035,6 +14192,14 @@ export type ToolDownloadSettings = { * download on its official host. */ githubMirror?: string, + /** + * Package registries only as configured (a company Nexus or Artifactory): npm and pnpm + * installs and update checks never retry against the public npm registry, and the IDE + * fetches nothing from public package registries itself (the JUnit Platform launcher from + * Maven Central, dependency version completion from Maven Central, npm, PyPI and + * crates.io). Off by default. + */ + configuredRegistriesOnly?: boolean, }; /** UI-facing state of one tool. */ @@ -14181,6 +14346,11 @@ export type TypeScriptSettings = { * vtsls default 3072 dies in a GC death spiral), else unset (vtsls default). */ tsserverMaxMemory?: number, + /** + * Problems › TypeScript project errors: the project's own `tsc --watch` per root + * `tsconfig.json` reports the errors of files that are not open. + */ + watchProblems?: boolean, }; /** A misspelt word. */ @@ -14229,6 +14399,22 @@ export type UnityProjectInfo = { projects: string[], }; +/** A located engine, shown so a project without run configurations says why. */ +export type UnrealEngine = { + /** `5.8` for a launcher install, or the registry key a source build registered under. */ + id: string, + /** Absolute engine root. */ + root: string, +}; + +export type UnrealProjectInfo = { + /** + * The engine the project builds against. `None` means none could be located, which is the + * only reason such a project offers no run configuration at all. + */ + engine: UnrealEngine | null, +}; + /** A requirement the project's interpreter does not satisfy. */ export type UnsatisfiedRequirement = { dependency: ManifestDependency, diff --git a/src/editor/api.ts b/src/editor/api.ts index 233272d9a..87d81a402 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -34,7 +34,7 @@ import type { LanguageDescription } from "@codemirror/language"; import type { HunkKind } from "@/bindings"; import type { LineEnding } from "@/platform/ipc"; import { create } from "zustand"; -import { maybeEditorService, type EditorInput } from "@/workbench/contributions"; +import { maybeEditorService, type EditorInput, type MenuGroupContext } from "@/workbench/contributions"; import { isSameOrInside } from "@/platform/paths"; import { useProject } from "@/platform/project"; import { rootOfPath } from "@/platform/projectRoots"; @@ -254,6 +254,25 @@ export function editorsFor(path: string): TextEditorHandle[] { return [...useEditorRegistry.getState().editors].filter((e) => e.ctx.path === path); } +/** + * While a cell editor of a custom editor (a notebook) has focus, it stands in for the + * active editor's view: the notebook publishes the editor context keys for it and + * editor actions resolve to it, like a text tab's view. The owner keeps this current + * on focus changes (see `_setFocusedCellEditor`); editor/core re-reads it whenever it + * republishes contexts, so actions never fall back to the last text tab. + */ +let focusedCell: EditorView | null = null; + +/** The focused cell editor standing in for the active editor's view, if any. */ +export function focusedCellEditor(): EditorView | null { + return focusedCell; +} + +/** Published by the custom editor owning the cell editors (a notebook); `null` once none has focus. */ +export function _setFocusedCellEditor(view: EditorView | null) { + focusedCell = view; +} + // --- called by editor/core only --------------------------------------------- export function _setActiveEditor(handle: TextEditorHandle | null) { @@ -614,8 +633,10 @@ export interface NavigationLocation { col: number; /** `Date.now()` when the location was last visited. */ time: number; - /** A place that is a tab rather than a text position (a diff), opened with this input on Back. */ + /** A place that is a tab rather than a text position (diff, agent chat, terminal tab…), opened with this input on Back. */ input?: EditorInput; + /** Split pane holding the editor tab when recorded, so Back/Forward returns to the same split when it still exists. */ + paneId?: string; } export interface NavigationHistorySnapshot { @@ -996,6 +1017,37 @@ export function _provideCodePreview(provider: typeof codePreviewProvider) { codePreviewProvider = provider; } +/** A row of the Copy Path/Reference… chooser. */ +export interface CopyPathRow { + /** The action whose shortcut the row shows. */ + id: string; + /** English label, translated by the chooser. */ + label: string; + /** The copied text; a row without one is left out. */ + preview: string | null; + run: () => void; +} + +type CopyPathChooser = ( + anchor: { x: number; y: number } | "center", + rows: readonly CopyPathRow[], + ctx: MenuGroupContext, +) => void; +let copyPathChooser: CopyPathChooser | null = null; + +/** + * The editor's Copy Path/Reference… chooser for files outside an editor (the Project view's + * selection): `rows`, then the rows contributed to the `copyPath` menu for `ctx`, with previews. + */ +export function openCopyPathChooser(...args: Parameters<CopyPathChooser>): void { + copyPathChooser?.(...args); +} + +/** @internal editor/core only. */ +export function _provideCopyPathChooser(open: CopyPathChooser) { + copyPathChooser = open; +} + let workspaceHistory: ((id: number, redo: boolean) => Promise<void>) | null = null; /** Undo/redo a refactoring through the same history used by editor commands. */ diff --git a/src/editor/core/actions.ts b/src/editor/core/actions.ts index e73e3444c..2c4cdf65e 100644 --- a/src/editor/core/actions.ts +++ b/src/editor/core/actions.ts @@ -7,6 +7,7 @@ import { foldEffect, syntaxTree, toggleFold } from "@codemirror/language"; import { acceptCompletion, completionStatus } from "@codemirror/autocomplete"; import { executeAction, registerActions, type Action } from "@/platform/actions"; import { getContext } from "@/platform/context"; +import { focusedCellEditor } from "@/editor/api"; import { focusedSoftWrapSurface } from "@/workbench/softWrap"; import { resetSurfaceFontZoom, stepFocusedSurfaceFontZoom, stepSurfaceFontZoomIn } from "@/workbench/contributions"; import { editorController, useGotoLine, useTabs } from "./controller"; @@ -19,6 +20,7 @@ import { deleteLine, duplicateEntireLines, duplicateLineOrSelection, + inDifferentHumpsMode, joinLines, moveStatementDown, moveStatementUp, @@ -68,7 +70,8 @@ import { customRegions } from "./cm/regions"; import { toggleRenderedViewAtCaret } from "./cm/renderedDocs"; import { enclosingHeaders } from "./cm/stickyScroll"; import { moveElementLeft, moveElementRight } from "./cm/moveElement"; -import { caretAnchor, openPopup, updatePopup, useLspPopup, type LspPopup } from "@/editor/lsp/popupStore"; +import { caretAnchor, openPopup, updatePopup, useLspPopup } from "@/editor/lsp/popupStore"; +import { copyPathPopup } from "./copyPathChooser"; import { cursorCodeBlockEnd, cursorCodeBlockStart, @@ -78,10 +81,12 @@ import { cursorParagraphBackward, cursorParagraphForward, scrollDown, + scrollDownAndMove, scrollToBottom, scrollToCenter, scrollToTop, scrollUp, + scrollUpAndMove, selectCodeBlockEnd, selectCodeBlockStart, selectPageBottom, @@ -109,7 +114,7 @@ import { import { useProject } from "@/platform/project"; import { call, commands } from "@/platform/ipc"; import { editorPrefs } from "@/platform/editorSettings"; -import { menuGroupItems, notifications } from "@/workbench/contributions"; +import { notifications } from "@/workbench/contributions"; import { togglePinSelectedContent } from "@/workbench/toolwindows/content"; import { useToolWindowLayout } from "@/workbench/toolwindows/store"; import { toggleReadOnly } from "./fileAttributes"; @@ -165,8 +170,15 @@ function withTextView(run: (view: EditorView) => unknown, editable: boolean) { }; } -function withView(run: (view: EditorView, slot: EditorSlot) => unknown) { +function withView(run: (view: EditorView, slot: EditorSlot | null) => unknown) { return () => { + // While a notebook cell editor has focus it is the editor the action runs in + // (the notebook publishes the editor context keys for it), never the last text tab. + const cell = focusedCellEditor(); + if (cell) { + run(cell, null); + return; + } const slot = activeSlot(); if (!slot?.view) return; run(slot.view, slot); @@ -636,24 +648,10 @@ function pathWithLines(state: EditorState, path: string, kind: "relative" | "abs return `${pathToCopy(kind, path)}:${first}${last > first ? `-${last}` : ""}`; } -function copyPathReferencePopup(view: EditorView, slot: EditorSlot) { +function copyPathReferencePopup(view: EditorView, slot: EditorSlot | null) { + // The popup's items resolve against the open document; a notebook cell has none. + if (!slot) return; const path = slot.model.path; - const contributed = menuGroupItems("copyPath", { - paths: [path], - ...selectedLineContext(view.state), - }).flatMap((item) => - (item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview - ? [ - { - id: item.id, - label: item.verbatim ? item.label : tx(item.label), - preview: item.preview, - shortcut: shortcutLabel(item.id), - run: item.run, - }, - ] - : [], - ); const flavours = [ { id: "project.copyAbsolutePath", label: "Absolute Path", value: pathToCopy("absolute", path) }, { @@ -670,26 +668,20 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) { value: pathWithLines(view.state, path), }, ]; - const popup: Extract<LspPopup, { kind: "list" }> = { - kind: "list", - title: tx("Copy Path/Reference…"), - layout: "copyPath", - anchor: caretAnchor(view, view.state.selection.main.head), - items: [ - ...flavours - .filter((f) => f.value !== null) - .map((f) => ({ - id: f.id, - label: tx(f.label), - preview: f.value!, - shortcut: shortcutLabel(f.id), - run: () => { - const lineNumbered = - f.id === "editor.copyPathWithLineNumber" || f.id === "editor.copyAbsolutePathWithLineNumber"; - void executeAction(f.id, lineNumbered ? f.value : path); - }, - })), - ...contributed, + const popup = copyPathPopup( + caretAnchor(view, view.state.selection.main.head), + flavours.map((f) => ({ + id: f.id, + label: f.label, + preview: f.value, + run: () => { + const lineNumbered = + f.id === "editor.copyPathWithLineNumber" || f.id === "editor.copyAbsolutePathWithLineNumber"; + void executeAction(f.id, lineNumbered ? f.value : path); + }, + })), + { paths: [path], ...selectedLineContext(view.state) }, + [ { id: "editor.copyReference", label: tx("Reference"), @@ -699,7 +691,7 @@ function copyPathReferencePopup(view: EditorView, slot: EditorSlot) { run: () => {}, }, ], - }; + ); openPopup(popup); void resolveReference(view, slot) .then((reference) => { @@ -792,7 +784,7 @@ export function registerEditorActions(): () => void { const text = ( id: string, title: string, - run: (view: EditorView, slot: EditorSlot) => unknown, + run: (view: EditorView, slot: EditorSlot | null) => unknown, extra: Partial<Action> = {}, ): Action => ({ id, @@ -920,6 +912,18 @@ export function registerEditorActions(): () => void { category: "Editor Actions", keyWhen: "editorTextFocus || diffEditorFocus", }), + edit( + "code.deleteToWordStartInDifferentHumpsMode", + 'Delete to Word Start in Different "CamelHumps" Mode', + (v) => inDifferentHumpsMode("deleteToStart", editorPrefs().smartKeys.camelHumps)(v), + { category: "Editor Actions", keyWhen: "editorTextFocus || diffEditorFocus" }, + ), + edit( + "code.deleteToWordEndInDifferentHumpsMode", + 'Delete to Word End in Different "CamelHumps" Mode', + (v) => inDifferentHumpsMode("deleteToEnd", editorPrefs().smartKeys.camelHumps)(v), + { category: "Editor Actions", keyWhen: "editorTextFocus || diffEditorFocus" }, + ), edit("code.moveLineUp", "Move Line Up", (v) => moveLineUp(v)), edit("code.moveLineDown", "Move Line Down", (v) => moveLineDown(v)), edit("code.moveElementLeft", "Move Element Left", (v) => moveElementLeft(v), { @@ -928,24 +932,38 @@ export function registerEditorActions(): () => void { edit("code.moveElementRight", "Move Element Right", (v) => moveElementRight(v), { keywords: ["swap argument", "move parameter"], }), - text("code.moveStatementUp", "Move Statement Up", (v, slot) => moveStatement(v, slot, true)), - text("code.moveStatementDown", "Move Statement Down", (v, slot) => moveStatement(v, slot, false)), - text("code.extendSelection", "Extend Selection", (_v, slot) => void queueSelection(slot, extend), { - category: "Edit", - }), - text("code.shrinkSelection", "Shrink Selection", (_v, slot) => void queueSelection(slot, shrink), { - category: "Edit", - }), + text("code.moveStatementUp", "Move Statement Up", (v, slot) => slot && moveStatement(v, slot, true)), + text("code.moveStatementDown", "Move Statement Down", (v, slot) => slot && moveStatement(v, slot, false)), + text( + "code.extendSelection", + "Extend Selection", + (_v, slot) => { + if (slot) void queueSelection(slot, extend); + }, + { + category: "Edit", + }, + ), + text( + "code.shrinkSelection", + "Shrink Selection", + (_v, slot) => { + if (slot) void queueSelection(slot, shrink); + }, + { + category: "Edit", + }, + ), text("code.fold", "Collapse", (v) => foldAtCaret(v), { category: "Folding", keywords: ["fold"] }), text("code.unfold", "Expand", (v) => unfoldAtCaret(v), { category: "Folding", keywords: ["unfold"] }), text("code.foldToggle", "Toggle Fold", (v) => toggleFold(v), { category: "Folding" }), - text("code.cyclicExpandWord", "Cyclic Expand Word", (v, slot) => expandWord(v, slot, "backward"), { + text("code.cyclicExpandWord", "Cyclic Expand Word", (v, slot) => slot && expandWord(v, slot, "backward"), { keywords: ["hippie", "complete word", "dabbrev"], }), text( "code.cyclicExpandWordBackward", "Cyclic Expand Word (Backward)", - (v, slot) => expandWord(v, slot, "forward"), + (v, slot) => slot && expandWord(v, slot, "forward"), { keywords: ["hippie", "complete word", "dabbrev"], }, @@ -956,7 +974,7 @@ export function registerEditorActions(): () => void { when: TEXT_WHEN, run: ({ arg }) => { if (typeof arg === "string") copyReference(Promise.resolve(arg)); - else withView((v, slot) => copyReference(resolveReference(v, slot)))(); + else withView((v, slot) => slot && copyReference(resolveReference(v, slot)))(); }, category: "Edit", keywords: ["fully qualified name", "fqn", "copy path"], @@ -983,8 +1001,13 @@ export function registerEditorActions(): () => void { icon: "soft-wrap", keywords: ["word wrap", "line wrap"], when: "textEditorActive || softWrapSurfaceFocus", - toggled: () => focusedSoftWrapSurface()?.enabled() ?? activeSlot()?.model.softWrapOn() ?? false, + // Cell editors wrap always; without the cell the setting is the active text tab's. + toggled: () => + focusedSoftWrapSurface()?.enabled() ?? + (focusedCellEditor() ? true : (activeSlot()?.model.softWrapOn() ?? false)), run: () => { + // Don't flip the last text tab's setting while a notebook cell has focus. + if (focusedCellEditor()) return; const surface = focusedSoftWrapSurface(); if (surface) surface.toggle(); else activeSlot()?.model.toggleSoftWrap(); @@ -996,8 +1019,12 @@ export function registerEditorActions(): () => void { category: "View", keywords: ["render documentation comments", "javadoc", "rendered doc", "comments"], when: "textEditorActive", - toggled: () => activeSlot()?.model.renderedDocsOn() ?? false, - run: () => activeSlot()?.model.toggleRenderedDocs(), + toggled: () => (focusedCellEditor() ? false : (activeSlot()?.model.renderedDocsOn() ?? false)), + run: () => { + // Notebook cells have no doc-comment rendering: leave it, don't toggle the last text tab's. + if (focusedCellEditor()) return; + activeSlot()?.model.toggleRenderedDocs(); + }, }, text("editor.toggleRenderedView", "Toggle Rendered View", (v) => toggleRenderedViewAtCaret(v), { category: "View", @@ -1005,11 +1032,11 @@ export function registerEditorActions(): () => void { }), text("code.foldAll", "Collapse All", (v) => collapseAll(v), { category: "Folding", icon: "collapse-all" }), text("code.unfoldAll", "Expand All", (v) => expandAll(v), { category: "Folding", icon: "expand-all" }), - text("code.expandDocComments", "Expand Doc Comments", (v, slot) => foldDocComments(v, slot, false), { + text("code.expandDocComments", "Expand Doc Comments", (v, slot) => slot && foldDocComments(v, slot, false), { category: "Folding", keywords: ["unfold", "documentation comments", "javadoc"], }), - text("code.collapseDocComments", "Collapse Doc Comments", (v, slot) => foldDocComments(v, slot, true), { + text("code.collapseDocComments", "Collapse Doc Comments", (v, slot) => slot && foldDocComments(v, slot, true), { category: "Folding", keywords: ["fold", "documentation comments", "javadoc"], }), @@ -1023,13 +1050,23 @@ export function registerEditorActions(): () => void { }), occurrence("code.addCaretNextOccurrence", "Add Selection for Next Occurrence", addNextOccurrence), occurrence("code.selectAllOccurrences", "Select All Occurrences", selectAllOccurrences), - text("code.completeStatement", "Complete Current Statement", (v, slot) => completeCurrentStatement(v, slot)), + text( + "code.completeStatement", + "Complete Current Statement", + (v, slot) => slot && completeCurrentStatement(v, slot), + ), edit("code.startNewLine", "Start New Line", (v) => startNewLine(v)), edit("code.startNewLineBefore", "Start New Line Before Current", (v) => startNewLineBefore(v)), edit("code.splitLine", "Split Line", (v) => splitLine(v)), caret("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }), caret("editor.scrollUp", "Scroll Up", (v) => scrollUp(v), { category: "Editor Actions" }), caret("editor.scrollDown", "Scroll Down", (v) => scrollDown(v), { category: "Editor Actions" }), + caret("editor.scrollUpAndMove", "Scroll Up and Move if Necessary", (v) => scrollUpAndMove(v), { + category: "Editor Actions", + }), + caret("editor.scrollDownAndMove", "Scroll Down and Move if Necessary", (v) => scrollDownAndMove(v), { + category: "Editor Actions", + }), caret("editor.scrollToTop", "Scroll to Top", (v) => scrollToTop(v), { category: "Editor Actions" }), caret("editor.scrollToBottom", "Scroll to Bottom", (v) => scrollToBottom(v), { category: "Editor Actions" }), caret("editor.moveToPageTop", "Move Caret to Page Top", (v) => cursorPageTop(v), { category: "Editor Actions" }), @@ -1083,6 +1120,30 @@ export function registerEditorActions(): () => void { (v) => selectParagraphBackward(v), { category: "Editor Actions" }, ), + caret( + "editor.nextWordInDifferentHumpsMode", + 'Move Caret to Next Word in Different "CamelHumps" Mode', + (v) => inDifferentHumpsMode("right", editorPrefs().smartKeys.camelHumps)(v), + { category: "Editor Actions" }, + ), + caret( + "editor.previousWordInDifferentHumpsMode", + 'Move Caret to Previous Word in Different "CamelHumps" Mode', + (v) => inDifferentHumpsMode("left", editorPrefs().smartKeys.camelHumps)(v), + { category: "Editor Actions" }, + ), + caret( + "editor.nextWordInDifferentHumpsModeWithSelection", + 'Move Caret to Next Word in Different "CamelHumps" Mode with Selection', + (v) => inDifferentHumpsMode("selectRight", editorPrefs().smartKeys.camelHumps)(v), + { category: "Editor Actions" }, + ), + caret( + "editor.previousWordInDifferentHumpsModeWithSelection", + 'Move Caret to Previous Word in Different "CamelHumps" Mode with Selection', + (v) => inDifferentHumpsMode("selectLeft", editorPrefs().smartKeys.camelHumps)(v), + { category: "Editor Actions" }, + ), text("editor.contextInfo", "Context Info", (v) => showContextInfo(v), { category: "View", keywords: ["enclosing method", "enclosing class", "where am I"], @@ -1135,7 +1196,7 @@ export function registerEditorActions(): () => void { category: "Editor Actions", keywords: ["overwrite mode", "overtype"], toggled: () => { - const view = activeSlot()?.view; + const view = focusedCellEditor() ?? activeSlot()?.view; return view ? isOverwrite(view.state) : false; }, }), @@ -1162,7 +1223,7 @@ export function registerEditorActions(): () => void { text( "code.fillParagraph", "Fill Paragraph", - (v, slot) => fillParagraph(v, hardWrapAt(slot.model.settings(), slot.model.info)), + (v, slot) => slot && fillParagraph(v, hardWrapAt(slot.model.settings(), slot.model.info)), { category: "Edit", keywords: ["wrap", "reflow", "rewrap comment"], @@ -1176,9 +1237,16 @@ export function registerEditorActions(): () => void { category: "Edit", keywords: ["spaces", "indentation"], }), - text("code.unwrap", "Unwrap/Remove…", (_v, slot) => void unwrapAtCaret(slot), { - keywords: ["unwrap", "remove if"], - }), + text( + "code.unwrap", + "Unwrap/Remove…", + (_v, slot) => { + if (slot) void unwrapAtCaret(slot); + }, + { + keywords: ["unwrap", "remove if"], + }, + ), text("code.foldSelection", "Fold Selection / Remove Region", (v) => foldSelection(v), { category: "Folding" }), { id: "editor.toggleColumnSelection", @@ -1187,7 +1255,7 @@ export function registerEditorActions(): () => void { keywords: ["block selection", "rectangular selection"], when: "textEditorActive", toggled: () => { - const view = activeSlot()?.view; + const view = focusedCellEditor() ?? activeSlot()?.view; return view ? isColumnMode(view.state) : false; }, run: withView((v) => toggleColumnMode(v)), @@ -1265,7 +1333,8 @@ export function registerEditorActions(): () => void { when: "textEditorActive", run: () => { const slot = activeSlot(); - if (slot) toggleReadOnly(slot.model); + // A notebook has no document model to toggle: leave it rather than the last text tab's file. + if (slot && !focusedCellEditor()) toggleReadOnly(slot.model); }, }, { @@ -1564,7 +1633,7 @@ export function registerEditorActions(): () => void { when: TEXT_WHEN, run: ({ arg }) => { if (typeof arg === "string") copyEditorPath(arg); - else withView((view, slot) => copyEditorPath(pathWithLines(view.state, slot.model.path)))(); + else withView((view, slot) => slot && copyEditorPath(pathWithLines(view.state, slot.model.path)))(); }, }, { @@ -1574,7 +1643,7 @@ export function registerEditorActions(): () => void { when: TEXT_WHEN, run: ({ arg }) => { if (typeof arg === "string") copyEditorPath(arg); - else withView((view, slot) => copyEditorPath(pathWithLines(view.state, slot.model.path, "absolute")))(); + else withView((view, slot) => slot && copyEditorPath(pathWithLines(view.state, slot.model.path, "absolute")))(); }, }, { diff --git a/src/editor/core/cm/caretCommands.test.ts b/src/editor/core/cm/caretCommands.test.ts index 506a098a1..d2507862b 100644 --- a/src/editor/core/cm/caretCommands.test.ts +++ b/src/editor/core/cm/caretCommands.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeAll, describe, expect, it } from "vitest"; import { EditorSelection, EditorState, StateEffect } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; -import { indentService, type LanguageSupport } from "@codemirror/language"; +import { codeFolding, foldEffect, indentService, type LanguageSupport } from "@codemirror/language"; import { languages } from "@codemirror/language-data"; import { addCursorAbove, insertBlankLine, selectLine, toggleTabFocusMode } from "@codemirror/commands"; import { @@ -14,9 +14,11 @@ import { nextParagraphBoundary, previousParagraphBoundary, scrollDown, + scrollDownAndMove, scrollToBottom, scrollToTop, scrollUp, + scrollUpAndMove, selectPageBottom, selectPageTop, selectParagraphForward, @@ -251,6 +253,104 @@ describe("Move Caret to Page Top / Bottom", () => { }); }); +describe("Scroll Up / Down and Move if Necessary", () => { + /** jsdom has no layout: a scroller `height` line heights tall, scrolled to `top` line heights. */ + function scroller(view: EditorView, top: number, height: number) { + const line = view.lineBlockAt(0).height; + let px = top * line; + Object.defineProperty(view.scrollDOM, "scrollTop", { + configurable: true, + get: () => px, + set: (v: number) => (px = Math.max(0, v)), + }); + Object.defineProperty(view, "documentTop", { configurable: true, get: () => -px }); + Object.defineProperty(view.scrollDOM, "clientHeight", { configurable: true, get: () => height * line }); + return () => px / line; + } + const lines = (marked: Record<number, string>) => + Array.from({ length: 10 }, (_, i) => marked[i] ?? `line ${i} text`).join("\n"); + const lineOf = (view: EditorView) => view.state.selection.ranges.map((r) => view.state.doc.lineAt(r.head).number - 1); + const columnOf = (view: EditorView) => + view.state.selection.ranges.map((r) => r.head - view.state.doc.lineAt(r.head).from); + + it("scrolls one line and keeps a caret that stays in view where it is", () => { + const view = make(lines({ 4: "line 4 te|xt" })); + const top = scroller(view, 2, 4); + const before = view.state.selection; + expect(scrollDownAndMove(view)).toBe(true); + expect(top()).toBe(3); + expect(view.state.selection.eq(before)).toBe(true); + expect(scrollUpAndMove(view)).toBe(true); + expect(top()).toBe(2); + expect(view.state.selection.eq(before)).toBe(true); + }); + + it("brings a caret that scrolls off the top down to the first line, keeping its column", () => { + const view = make(lines({ 2: "line 2 te|xt" })); + scroller(view, 2, 4); + scrollDownAndMove(view); + expect([lineOf(view), columnOf(view)]).toEqual([[3], [9]]); + }); + + it("brings a caret that scrolls off the bottom up to the last line, keeping its column", () => { + const view = make(lines({ 5: "li|ne 5 text" })); + scroller(view, 2, 4); + scrollUpAndMove(view); + expect([lineOf(view), columnOf(view)]).toEqual([[4], [2]]); + }); + + it("moves a caret already out of view to the nearest edge", () => { + const view = make(lines({ 9: "line 9 |text" })); + scroller(view, 0, 4); + scrollDownAndMove(view); + expect([lineOf(view), columnOf(view)]).toEqual([[4], [7]]); + }); + + it("drops the selection of a caret it moves and keeps the others", () => { + const view = make(lines({ 0: "|line 0 text" })); + const at = (line: number, col: number) => view.state.doc.line(line + 1).from + col; + view.dispatch({ + selection: EditorSelection.create( + [EditorSelection.range(at(2, 0), at(2, 4)), EditorSelection.range(at(4, 0), at(4, 4))], + 1, + ), + }); + scroller(view, 2, 4); + scrollDownAndMove(view); + expect(view.state.selection.ranges.map((r) => [r.anchor, r.head])).toEqual([ + [at(3, 4), at(3, 4)], + [at(4, 0), at(4, 4)], + ]); + expect(view.state.selection.mainIndex).toBe(1); + }); + + it("keeps a caret at the end of a folded block the view shows", () => { + const view = make(lines({ 7: "line 7 text|" })); + const { doc } = view.state; + view.dispatch({ + effects: [ + StateEffect.appendConfig.of(codeFolding()), + foldEffect.of({ from: doc.line(6).to, to: doc.line(8).to }), + ], + }); + expect(view.lineBlockAt(doc.line(8).to).from).toBe(doc.line(6).from); + const before = view.state.selection; + scroller(view, 1, 4); + scrollDownAndMove(view); + expect(view.state.selection.eq(before)).toBe(true); + }); + + it("only scrolls at the top of the file when the caret stays in view", () => { + const view = make(lines({ 1: "|line 1 text" })); + const top = scroller(view, 0, 4); + const before = view.state.selection; + scrollUpAndMove(view); + expect(top()).toBe(0); + expect(view.state.selection.eq(before)).toBe(true); + expect(view.state.doc.toString()).toBe(lines({})); + }); +}); + describe("code block navigation", () => { let js: LanguageSupport; beforeAll(async () => { diff --git a/src/editor/core/cm/caretCommands.ts b/src/editor/core/cm/caretCommands.ts index 8c16d10b0..9e3f92ca2 100644 --- a/src/editor/core/cm/caretCommands.ts +++ b/src/editor/core/cm/caretCommands.ts @@ -1,4 +1,4 @@ -/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down / Top / Bottom, Page Top / Bottom, code block, brace and paragraph navigation. */ +/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down / Top / Bottom, Scroll Up / Down and Move if Necessary, Page Top / Bottom, code block, brace and paragraph navigation. */ import { countColumn, EditorSelection, findColumn, type EditorState, type Transaction } from "@codemirror/state"; import { EditorView, type Command } from "@codemirror/view"; import { insertNewlineAndIndent } from "@codemirror/commands"; @@ -66,15 +66,21 @@ function pageEdgeLine(view: EditorView, edge: "top" | "bottom"): number { return block.top >= bottom || (block.bottom > bottom && previous.top >= top) ? previous.from : block.from; } +/** `head` moved to the line starting at `lineStart`, keeping its visual column. */ +function sameColumnOn(state: EditorState, head: number, lineStart: number): number { + const line = state.doc.lineAt(head); + const target = state.doc.lineAt(lineStart); + const column = countColumn(line.text, state.tabSize, head - line.from); + return target.from + findColumn(target.text, column, state.tabSize); +} + /** Move Caret to Page Top / Bottom (with Selection): every caret to that line, keeping its column. */ function moveToPageEdge(edge: "top" | "bottom", extend = false): Command { return (view) => { const { state } = view; - const target = state.doc.lineAt(pageEdgeLine(view, edge)); + const target = pageEdgeLine(view, edge); const ranges = state.selection.ranges.map((r) => { - const line = state.doc.lineAt(r.head); - const column = countColumn(line.text, state.tabSize, r.head - line.from); - const head = target.from + findColumn(target.text, column, state.tabSize); + const head = sameColumnOn(state, r.head, target); return extend ? EditorSelection.range(r.anchor, head) : EditorSelection.cursor(head); }); view.dispatch({ @@ -90,6 +96,35 @@ export const cursorPageBottom = moveToPageEdge("bottom"); export const selectPageTop = moveToPageEdge("top", true); export const selectPageBottom = moveToPageEdge("bottom", true); +/** + * Scroll Up / Down and Move if Necessary: move the viewport by one line, then bring + * a caret outside the lines the view shows whole to the first or last of them, + * keeping its column. Carets in view keep their place and selection. + */ +const scrollByLineAndMove = + (lines: number): Command => + (view) => { + scrollByLine(lines)(view); + const { state } = view; + const first = pageEdgeLine(view, "top"); + const last = view.lineBlockAt(pageEdgeLine(view, "bottom")); + let moved = false; + const ranges = state.selection.ranges.map((r) => { + if (r.head >= first && r.head <= last.to) return r; + moved = true; + return EditorSelection.cursor(sameColumnOn(state, r.head, r.head < first ? first : last.from)); + }); + if (moved) { + view.dispatch({ + selection: EditorSelection.create(ranges, state.selection.mainIndex), + userEvent: "select.navigate", + }); + } + return true; + }; +export const scrollUpAndMove = scrollByLineAndMove(-1); +export const scrollDownAndMove = scrollByLineAndMove(1); + const NOT_CODE = /String|Comment|Regexp|Char|Template/; /** `{` / `}` at `pos` when it is code (not inside a string or comment, as far as the syntax tree knows). */ diff --git a/src/editor/core/cm/editing.ts b/src/editor/core/cm/editing.ts index a560ee2c1..d01b663ff 100644 --- a/src/editor/core/cm/editing.ts +++ b/src/editor/core/cm/editing.ts @@ -24,10 +24,15 @@ import { } from "@codemirror/language"; import { copyLineDown, + cursorGroupLeft, + cursorGroupRight, + deleteGroupForward, deleteLine as deleteDocLine, insertNewlineAndIndent, moveLineDown, moveLineUp, + selectGroupLeft, + selectGroupRight, } from "@codemirror/commands"; import { SearchCursor } from "@codemirror/search"; import { humpLeft, humpRight, wordStartLeft } from "../model/camelHumps"; @@ -90,6 +95,21 @@ export const deleteHumpForward = deleteHump(true); /** ⌥⌫ / Ctrl+Backspace without CamelHumps: the whitespace before the caret and the word (or punctuation run) before it. */ export const deleteWordBackward = deleteHump(false, false); +/** The word moves and deletes the editor keys run in each mode (`caretExtension`): `[without CamelHumps, with CamelHumps]`. */ +const WORD_COMMANDS = { + left: [cursorGroupLeft, cursorHumpLeft], + right: [cursorGroupRight, cursorHumpRight], + selectLeft: [selectGroupLeft, selectHumpLeft], + selectRight: [selectGroupRight, selectHumpRight], + deleteToStart: [deleteWordBackward, deleteHumpBackward], + deleteToEnd: [deleteGroupForward, deleteHumpForward], +} satisfies Record<string, [Command, Command]>; + +/** IDEA's "… in Different "CamelHumps" Mode": the word command of the mode "Use CamelHumps words" is not set to. */ +export function inDifferentHumpsMode(op: keyof typeof WORD_COMMANDS, camelHumps: boolean): Command { + return WORD_COMMANDS[op][camelHumps ? 0 : 1]; +} + // --- lines / selections ------------------------------------------------------- /** diff --git a/src/editor/core/cm/ideaParity.test.ts b/src/editor/core/cm/ideaParity.test.ts index 719092626..aa53f783e 100644 --- a/src/editor/core/cm/ideaParity.test.ts +++ b/src/editor/core/cm/ideaParity.test.ts @@ -8,6 +8,7 @@ import { deleteWordBackward, duplicateEntireLines, duplicateLineOrSelection, + inDifferentHumpsMode, moveStatementDown, moveStatementUp, nextOccurrence, @@ -228,6 +229,57 @@ describe("Delete to Word Start", () => { }); }); +describe('in Different "CamelHumps" Mode', () => { + function run(text: string, op: Parameters<typeof inDifferentHumpsMode>[0], camelHumps: boolean, times = 1) { + const v = make(text); + for (let i = 0; i < times; i++) inDifferentHumpsMode(op, camelHumps)(v); + return show(v); + } + + it("moves by humps while the setting is off", () => { + expect(run("|parseHTMLDocument x", "right", false)).toBe("parse|HTMLDocument x"); + expect(run("|parseHTMLDocument x", "right", false, 2)).toBe("parseHTML|Document x"); + expect(run("x parseHTMLDocument|", "left", false)).toBe("x parseHTML|Document"); + expect(run("|snake_case_name", "right", false)).toBe("snake_|case_name"); + }); + + it("moves by whole words while the setting is on", () => { + expect(run("|parseHTMLDocument x", "right", true)).toBe("parseHTMLDocument| x"); + expect(run("x parseHTMLDocument|", "left", true)).toBe("x |parseHTMLDocument"); + }); + + it("extends the selection from its anchor in the with Selection variants", () => { + expect(run("|fooBarBaz", "selectRight", false, 2)).toBe("[fooBar]Baz"); + expect(run("fooBarBaz|", "selectLeft", false)).toBe("fooBar[Baz]"); + expect(run("|fooBar baz", "selectRight", true)).toBe("[fooBar] baz"); + }); + + it("moves every caret, and leaves a selection at its edge without extending", () => { + expect(run("|fooBar\n|bazQux", "right", false)).toBe("foo|Bar\nbaz|Qux"); + expect(run("[fooBar]Baz", "right", false)).toBe("fooBar|Baz"); + expect(run("foo[BarBaz]", "left", false)).toBe("foo|BarBaz"); + }); + + it("deletes to the word start or end of the other mode", () => { + expect(run("a.fooBar|", "deleteToStart", false)).toBe("a.foo|"); + expect(run("a.fooBar|", "deleteToStart", true)).toBe("a.|"); + expect(run("|fooBar.b", "deleteToEnd", false)).toBe("|Bar.b"); + expect(run("|fooBar.b", "deleteToEnd", true)).toBe("|.b"); + expect(run("foo [BarBaz] qux", "deleteToEnd", false)).toBe("foo | qux"); + expect(run("foo [BarBaz] qux", "deleteToEnd", true)).toBe("foo | qux"); + expect(run("aBc|\nxYz|", "deleteToStart", false)).toBe("a|\nx|"); + }); + + it("does not delete in a read-only editor", () => { + for (const camelHumps of [false, true]) { + const v = make("foo|Bar", EditorState.readOnly.of(true)); + expect(inDifferentHumpsMode("deleteToStart", camelHumps)(v)).toBe(false); + expect(inDifferentHumpsMode("deleteToEnd", camelHumps)(v)).toBe(false); + expect(show(v)).toBe("foo|Bar"); + } + }); +}); + describe("paste reformatting", () => { /** One unit deeper after a line ending in `{`. */ const braceIndent = indentService.of((cx, pos) => { diff --git a/src/editor/core/controller.test.ts b/src/editor/core/controller.test.ts index af99bb9bc..3e7c26a3f 100644 --- a/src/editor/core/controller.test.ts +++ b/src/editor/core/controller.test.ts @@ -24,6 +24,22 @@ import { installKeyboardDispatcher } from "@/platform/keymap"; import { TEXT_WHEN } from "./actions"; import { EDITOR_WHEN } from "@/editor/lsp/actions"; import { setShownLine } from "@/editor/api"; +import { registerProjectActions } from "@/features/project-tree/actions"; + +/** `isTauri` is a spy (File Color writes need it true); the settings commands stand in for the backend. */ +const ipc = vi.hoisted(() => ({ + isTauri: vi.fn(() => false), + settingsSet: vi.fn(async () => ({ status: "ok" as const, data: {} })), + settingsGet: vi.fn(async () => ({})), +})); +vi.mock("@/platform/ipc", async (orig) => { + const real = await orig<typeof import("@/platform/ipc")>(); + return { + ...real, + isTauri: ipc.isTauri, + commands: { ...real.commands, settingsSet: ipc.settingsSet, settingsGet: ipc.settingsGet }, + }; +}); let ctrl: EditorController | null = null; @@ -422,6 +438,46 @@ describe("EditorController", () => { expect(pane().tabs.map((t) => t.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]); }); + it("offers the project view's File Color submenu through actions", async () => { + useProject.setState({ + project: { name: "p", root: "/p", trusted: true, isGit: false, settings: {} } as never, + settings: {} as never, + }); + ipc.isTauri.mockReturnValue(true); + const disposeActions = registerProjectActions(); + try { + ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "", "/p/b.ts": "", "/elsewhere/c.ts": "" })); + ctrl.start(); + await ctrl.openFile("/p/a.ts", { focus: false }); + const pane = () => useTabs.getState().panes[useTabs.getState().activePane]!; + const raw = ctrl!.tabMenu(pane().id, pane().tabs[0]!); + const entry = raw.find((i) => "label" in i && i.label === "File Color"); + expect(entry).toBeDefined(); + const items = resolveMenuItems((entry as { submenu: typeof raw }).submenu); + expect(items.filter((i) => i.kind === "item").map((i) => i.label)).toEqual([ + "Blue", + "Green", + "Orange", + "Rose", + "Violet", + "Yellow", + "Gray", + "Edit File Colors…", + ]); + items.find((i) => i.label === "Blue")!.run!(); + await vi.waitFor(() => expect(ipc.settingsSet).toHaveBeenCalledTimes(2)); + expect(ipc.settingsSet).toHaveBeenNthCalledWith(1, "project", "scopes", expect.stringContaining('"file:a.ts"')); + expect(ipc.settingsSet).toHaveBeenNthCalledWith(2, "project", "fileColors", expect.stringContaining("blue")); + // A file outside the project has no File Color, as in the project view. + await ctrl.openFile("/elsewhere/c.ts", { focus: false }); + const outside = pane().tabs.find((t) => t.input.path === "/elsewhere/c.ts")!; + expect(ctrl.tabMenu(pane().id, outside).some((i) => "label" in i && i.label === "File Color")).toBe(false); + ipc.isTauri.mockReturnValue(false); + useProject.setState({ project: null, settings: null }); + } finally { + disposeActions(); + } + }); it("keeps editor tabs and unsaved documents through attach and detach", async () => { const settings = {}; useProject.setState({ @@ -908,3 +964,125 @@ describe("editor action when clauses", () => { expect(evaluateWhen(when, { ...editorBehind, toolWindowFocus: true })).toBe(false); }); }); + +describe("non-file tabs and split panes in Back / Forward", () => { + it("navigates back and forward across text files and non-path custom tabs while keeping Recent Locations text-only", async () => { + ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "one\ntwo\n", "/p/b.ts": "three\n" })); + ctrl.start(); + await ctrl.openFile("/p/a.ts", { focus: false }); + const chat = { kind: "agent-session", key: "agent:task-1", data: { task: "task-1" } }; + const cli = { kind: "cli", key: "cli:term-1", data: { name: "Local", command: "" } }; + await ctrl.openInput(chat, { focus: false }); + await ctrl.openInput(cli, { focus: false }); + await ctrl.openFile("/p/b.ts", { focus: false }); + + await ctrl.back(); + expect(ctrl.activeInput()?.key).toBe(cli.key); + await ctrl.back(); + expect(ctrl.activeInput()?.key).toBe(chat.key); + await ctrl.back(); + expect(ctrl.activeSlot?.model.path).toBe("/p/a.ts"); + + await ctrl.forward(); + expect(ctrl.activeInput()?.key).toBe(chat.key); + await ctrl.forward(); + expect(ctrl.activeInput()?.key).toBe(cli.key); + await ctrl.forward(); + expect(ctrl.activeSlot?.model.path).toBe("/p/b.ts"); + + expect(ctrl.nav.snapshot().entries.map((e) => e.path)).toEqual(["/p/a.ts", "/p/b.ts"]); + }); + + it("skips stale entries via canNavigate and collapses duplicates exposed by skipping them", async () => { + let taskExists = true; + const disposeTask = registerEditorKind({ + kind: "ephemeral-task", + title: () => "Task", + component: () => null, + canNavigate: (_input, open) => open || taskExists, + }); + const disposeCli = registerEditorKind({ + kind: "ephemeral-cli", + title: () => "Terminal", + component: () => null, + canNavigate: (_input, open) => open, + }); + try { + ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a\n", "/p/b.ts": "b\n" })); + ctrl.start(); + await ctrl.openFile("/p/a.ts", { focus: false }); + const task = { kind: "ephemeral-task", key: "ephemeral:task-1" }; + const cli = { kind: "ephemeral-cli", key: "ephemeral:cli-1" }; + await ctrl.openInput(task, { focus: false }); + await ctrl.openFile("/p/b.ts", { focus: false }); + await ctrl.openInput(cli, { focus: false }); + await ctrl.closeInput(cli.key); + await ctrl.closeInput(task.key); + taskExists = false; + + // Closing cli activated b.ts; Back skips both closed cli and deleted task and lands directly on a.ts. + expect(ctrl.activeSlot?.model.path).toBe("/p/b.ts"); + await ctrl.back(); + expect(ctrl.activeSlot?.model.path).toBe("/p/a.ts"); + await ctrl.forward(); + expect(ctrl.activeSlot?.model.path).toBe("/p/b.ts"); + } finally { + disposeTask(); + disposeCli(); + } + }); + + it("tracks split panes for both text and non-text tabs, and does not duplicate a moved tab", async () => { + ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "a\n", "/p/b.ts": "b\n" })); + ctrl.start(); + await ctrl.openFile("/p/a.ts", { focus: false }); + const p1 = useTabs.getState().activePane; + + // Splitting duplicates a.ts into p2; Back / Forward returns to the recorded pane. + ctrl.split(p1, "row"); + await vi.waitFor(() => expect(Object.keys(useTabs.getState().panes)).toHaveLength(2)); + const p2 = Object.keys(useTabs.getState().panes).find((id) => id !== p1)!; + const p2Tab = useTabs.getState().panes[p2]!.active!; + await ctrl.ensureSlot(p2Tab); + expect(useTabs.getState().activePane).toBe(p2); + + // Open a non-text tab in p2, then focus back into p1 via focusPane (simulating clicking the inactive pane). + const chat = { kind: "agent-session", key: "agent:task-1", data: { task: "task-1" } }; + await ctrl.openInput(chat, { pane: p2, focus: false }); + expect(useTabs.getState().activePane).toBe(p2); + + ctrl.focusPane(p1); + expect(useTabs.getState().activePane).toBe(p1); + ctrl.focusPane(p2); + expect(useTabs.getState().activePane).toBe(p2); + + await ctrl.back(); + expect(useTabs.getState().activePane).toBe(p1); + expect(ctrl.activeSlot?.model.path).toBe("/p/a.ts"); + + await ctrl.back(); + expect(useTabs.getState().activePane).toBe(p2); + expect(ctrl.activeInput()?.key).toBe(chat.key); + + await ctrl.back(); + expect(useTabs.getState().activePane).toBe(p2); + expect(ctrl.activeSlot?.model.path).toBe("/p/a.ts"); + + await ctrl.back(); + expect(useTabs.getState().activePane).toBe(p1); + expect(ctrl.activeSlot?.model.path).toBe("/p/a.ts"); + + // Moving a tab to the opposite pane keeps Back immediate and avoids duplicating the tab in its old pane. + await ctrl.openFile("/p/b.ts", { pane: p1, focus: false }); + const bTabId = useTabs.getState().panes[p1]!.active!; + ctrl.moveToOpposite(p1, bTabId); + expect(useTabs.getState().activePane).toBe(p2); + await ctrl.back(); + expect(useTabs.getState().activePane).toBe(p1); + expect(ctrl.activeSlot?.model.path).toBe("/p/a.ts"); + await ctrl.forward(); + expect(useTabs.getState().activePane).toBe(p2); + expect(ctrl.activeSlot?.model.path).toBe("/p/b.ts"); + expect(useTabs.getState().panes[p1]!.tabs.some((t) => t.input.path === "/p/b.ts")).toBe(false); + }); +}); diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index 956634366..ce0bbd173 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -12,7 +12,7 @@ import { create } from "zustand"; import { setContext } from "@/platform/context"; import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap"; import { isSameOrInside } from "@/platform/paths"; -import { basename, dirname, useProject } from "@/platform/project"; +import { basename, dirname, relativePath, useProject } from "@/platform/project"; import { editorPrefs } from "@/platform/editorSettings"; import { _emitEditorEvent, @@ -20,6 +20,7 @@ import { _provideNavigationHistory, _provideOpenEditorPaths, _setActiveEditor, + focusedCellEditor, shownLine, type NavigationLocation, } from "@/editor/api"; @@ -59,6 +60,7 @@ import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs"; import { isRemoteWindow, projectLocation } from "@/platform/remote"; import { auxiliaryWindow } from "@/platform/auxWindow"; import { fileIconName, showContextMenu, type MenuItem } from "@/ui"; +import { FILE_COLOR_NAMES, ownFileColor } from "@/platform/fileColors"; import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager"; import { activateTab, @@ -322,6 +324,7 @@ export class EditorController implements SlotHost { private openSequence = 0; private selectionRequests = new Map<string, number>(); private activationGeneration = 0; + private navGeneration = 0; private admitting = false; /** Tabs restored from a saved session: not a user's activation, so a pending open still activates its tab. */ private restoring = false; @@ -834,7 +837,10 @@ export class EditorController implements SlotHost { if (loc) { const s = useTabs.getState(); const next = activateTab(setActivePane(s, loc.paneId), loc.paneId, slot.tabId); - if (next !== s) useTabs.setState(next, true); + if (next !== s) { + this.recordLeaving(); + useTabs.setState(next, true); + } } if (this.activeSlot !== slot) this.setActiveSlot(slot); else _setActiveEditor(slot.handle); @@ -854,7 +860,8 @@ export class EditorController implements SlotHost { if (slot !== this.activeSlot) return; if (navigatedFrom && this.navSuppress === 0 && !slot.disposed) { // The place left behind is where the caret was right before the navigation. - this.nav.update({ path: slot.model.path, ...navigatedFrom }); + const paneId = this.locateTab(slot.tabId)?.paneId; + this.nav.update({ path: slot.model.path, ...navigatedFrom, ...(paneId ? { paneId } : {}) }); this.recordNav(slot, true); } // The status bar reflects the view state synchronously (programmatic and @@ -1012,6 +1019,7 @@ export class EditorController implements SlotHost { { kind: "action", action: "refactor.extractConstant" }, { kind: "action", action: "refactor.extractMethod" }, { kind: "action", action: "refactor.extractInterface" }, + { kind: "action", action: "refactor.extractTypeAlias" }, { kind: "action", action: "refactor.inline" }, { kind: "action", action: "refactor.pullMembersUp" }, { kind: "action", action: "refactor.pushMembersDown" }, @@ -1110,6 +1118,9 @@ export class EditorController implements SlotHost { const slot = this.activeSlot; const meta = slot?.model.getMeta(); const s = useTabs.getState(); + // A focused notebook cell editor stands in for the active text editor (the notebook + // publishes the editor context keys for it): republishing on tab churn keeps them on. + const cell = focusedCellEditor(); setContext("editorPath", slot?.model.path ?? null); setContext("editorLangId", meta?.language ?? null); setContext("editorReadOnly", !!meta?.readOnly); @@ -1119,66 +1130,145 @@ export class EditorController implements SlotHost { Object.values(s.panes).some((p) => p.tabs.length > 0), ); setContext("editorSplit", paneIds(s).length > 1); - setContext("editorTextFocus", !!slot?.view?.hasFocus); - setContext("textEditorActive", !!slot); + setContext("editorTextFocus", cell ? cell.hasFocus : !!slot?.view?.hasFocus); + setContext("textEditorActive", !!slot || !!cell); } // --- navigation history -------------------------------------------------------------- - /** `navigation`: the caret got here by a navigation (see NavigationHistory.update). */ - private recordNav(slot: EditorSlot, navigation = false) { - if (this.navSuppress > 0 || slot.disposed) return; + private slotLocation(slot: EditorSlot): Omit<NavigationLocation, "time"> { const c = slot.caret(); // A view standing in for the editor (Markdown Preview only) is where the reader is. const shown = shownLine(slot.model.path); const loc = shown === null || shown === c.line ? { line: c.line, col: c.col } : { line: shown, col: 0 }; - this.nav.update({ path: slot.model.path, ...loc }, navigation); + const paneId = this.locateTab(slot.tabId)?.paneId; + return { path: slot.model.path, ...loc, ...(paneId ? { paneId } : {}) }; + } + + /** `navigation`: the caret got here by a navigation (see NavigationHistory.update). */ + private recordNav(slot: EditorSlot, navigation = false) { + if (this.navSuppress > 0 || slot.disposed) return; + this.nav.update(this.slotLocation(slot), navigation); + } + + private recordInput(input: EditorInput, paneId: string | undefined, navigation = true) { + if (this.navSuppress > 0 || isTextInput(input)) return; + const kind = useContributions.getState().editorKinds.get(input.kind); + const place = kind?.navigationInput?.(input) ?? input; + this.nav.update( + { path: input.path ?? "", line: 0, col: 0, input: place, ...(paneId ? { paneId } : {}) }, + navigation, + ); + } + + private recordActiveEditor(navigation = true) { + if (this.navSuppress > 0) return; + if (this.activeSlot && !this.activeSlot.disposed) { + this.recordNav(this.activeSlot, navigation); + return; + } + const input = this.activeInput(); + if (!input || isTextInput(input)) return; + this.recordInput(input, useTabs.getState().activePane, navigation); } /** - * The place a navigation leaves: the text editor's caret, or a tab showing no text editor - * (a diff) as a whole, so Back returns to it as IDEA does. + * The place a navigation leaves: the text editor's caret, or a non-text editor tab + * (diff, agent chat, terminal tab…) as a whole, so Back returns to it as IDEA does. */ private recordLeaving() { if (this.navSuppress > 0) return; - if (this.activeSlot) return this.recordNav(this.activeSlot); + if (this.activeSlot && !this.activeSlot.disposed) { + this.recordNav(this.activeSlot); + return; + } const input = this.activeInput(); - if (!input?.path || isTextInput(input)) return; - const kind = useContributions.getState().editorKinds.get(input.kind); - const place = kind?.navigationInput?.(input) ?? input; - this.nav.update({ path: input.path, line: 0, col: 0, input: place }, true); + if (!input || isTextInput(input)) return; + this.recordInput(input, useTabs.getState().activePane, true); } - /** Whether the active tab is the current place (a tab place, as a text editor's records itself). */ + /** Whether the active editor tab and split pane already show `nav.current`. */ private showsCurrentPlace(): boolean { - const key = this.nav.current?.input?.key; - return !!key && this.activeInput()?.key === key; + const cur = this.nav.current; + if (!cur) return false; + const matchesTab = cur.input + ? this.activeInput()?.key === cur.input.key + : !!this.activeSlot && !this.activeSlot.disposed && this.activeSlot.model.path === cur.path; + if (!matchesTab) return false; + // If the recorded pane still holds this tab (a split copy), require that pane to be active; + // if the tab moved out of that pane, showing it in its new pane still counts as the current place. + const preferred = this.preferredPaneFor(cur); + return !preferred || useTabs.getState().activePane === preferred; + } + + private canNavigateTo(loc: NavigationLocation): boolean { + if (loc.input) { + const kind = useContributions.getState().editorKinds.get(loc.input.kind); + if (kind?.canNavigate) return kind.canNavigate(loc.input, !!findTab(useTabs.getState(), loc.input.key)); + } + return true; + } + + private preferredPaneFor(loc: NavigationLocation): string | undefined { + const id = loc.paneId; + if (!id) return undefined; + const s = useTabs.getState(); + const pane = s.panes[id]; + if (!pane) return undefined; + const matches = (t: Tab) => + loc.input ? t.input.key === loc.input.key : isTextInput(t.input) && t.input.path === loc.path; + if (pane.tabs.some(matches)) return id; + const openElsewhere = Object.values(s.panes).some((p) => p.tabs.some(matches)); + return openElsewhere ? undefined : id; } async navigateTo(loc: NavigationLocation | null) { if (!loc) return; + const gen = ++this.navGeneration; this.navSuppress++; try { + const pane = this.preferredPaneFor(loc); // At the place recorded on leaving it (a diff at its caret): a background tab shows afresh. - if (loc.input) await this.openInput(loc.input, { focus: true }); - else await this.openFile(loc.path, { selection: { line: loc.line, col: loc.col }, focus: true }); + if (loc.input) await this.openInput(loc.input, { ...(pane ? { pane } : {}), focus: true }); + else + await this.openFile(loc.path, { + ...(pane ? { pane } : {}), + selection: { line: loc.line, col: loc.col }, + focus: true, + }); } finally { this.navSuppress--; - if (this.activeSlot) this.recordNav(this.activeSlot); + if (gen === this.navGeneration && this.activeSlot) this.recordNav(this.activeSlot); } } + private refreshCurrentPlace() { + const cur = this.nav.current; + if (!cur) return; + if (this.activeSlot && !this.activeSlot.disposed) { + const loc = this.slotLocation(this.activeSlot); + if (!cur.input && loc.path === cur.path) + this.nav.update({ ...loc, ...(cur.paneId ? { paneId: cur.paneId } : {}) }); + return; + } + const input = this.activeInput(); + if (input && !isTextInput(input) && cur.input?.key === input.key) this.recordInput(input, cur.paneId, false); + } + back() { - const slot = this.activeSlot; - if (slot && !slot.disposed) this.recordNav(slot); // Nothing shows the current place (its last tab was closed, or another tab is active): // going back returns to it first, as in IDEA. - else if (!this.showsCurrentPlace()) return this.navigateTo(this.nav.current); - return this.navigateTo(this.nav.back()); + if (!this.showsCurrentPlace()) { + if (this.nav.current && this.canNavigateTo(this.nav.current)) return this.navigateTo(this.nav.current); + } else { + this.refreshCurrentPlace(); + } + return this.navigateTo(this.nav.back((loc) => this.canNavigateTo(loc))); } forward() { - return this.navigateTo(this.nav.forward()); + if (this.showsCurrentPlace()) this.refreshCurrentPlace(); + return this.navigateTo(this.nav.forward((loc) => this.canNavigateTo(loc))); } /** Navigate › Last Edit Location (⇧⌘⌫): repeated, walks back through older edits. */ @@ -1306,6 +1396,7 @@ export class EditorController implements SlotHost { async openInput(input: EditorInput, o: OpenOptions = {}) { if (input.path && isClassFile(input.path)) return this.openFile(input.path, o); + this.recordLeaving(); return this.admitInput(input, o, this.openingGeneration(o)); } @@ -1404,7 +1495,7 @@ export class EditorController implements SlotHost { const before = useTabs.getState(); let s = before; const activate = this.isCurrentOpening(generation); - if (activate) restoreMaximizedToolWindow(); + const restored = activate ? restoreMaximizedToolWindow() : false; const kinds = useContributions.getState().editorKinds; const lifecycle = documentLifecycle(input, kinds); const canPreview = !lifecycle || (lifecycle.allowPreview && !documentDirty({ input, lifecycle })); @@ -1538,12 +1629,16 @@ export class EditorController implements SlotHost { slot.reveal({ anchor: head, head: anchor, center: true }); } if (o.focus !== false && canFocus()) { - if (slot.view) slot.focus(); + if (restored) { + requestAnimationFrame(() => { + if (canFocus()) this.focus(); + }); + } else if (slot.view) slot.focus(); else slot.wantsFocus = true; } } finally { this.navSuppress--; - if (this.navSuppress === 0 && this.activeSlot) this.recordNav(this.activeSlot, true); + if (this.navSuppress === 0 && this.isCurrentOpening(generation)) this.recordActiveEditor(true); } } @@ -1582,10 +1677,23 @@ export class EditorController implements SlotHost { ).then((keys) => evict(new Set(keys.filter((key): key is string => key !== null)))); } + /** Switches `activePane` when focus enters an inactive split pane (e.g. a non-text tab). */ + focusPane(paneId: string) { + const s = useTabs.getState(); + if (!s.panes[paneId] || s.activePane === paneId) return; + this.recordLeaving(); + useTabs.setState(setActivePane(s, paneId), true); + const tab = this.activeTabOf(); + if (tab && !isTextTab(tab)) this.recordActiveEditor(true); + } + activate(paneId: string, tabId: string, focus = true) { const restored = restoreMaximizedToolWindow(); + this.recordLeaving(); ++this.activationGeneration; useTabs.setState((s) => activateTab(setActivePane(s, paneId), paneId, tabId), true); + const tab = this.activeTabOf(); + if (tab && !isTextTab(tab)) this.recordActiveEditor(true); if (focus) { if (restored) { requestAnimationFrame(() => this.focus()); @@ -1992,7 +2100,10 @@ export class EditorController implements SlotHost { this.focus(); } cycle(delta: number) { + this.recordLeaving(); this.apply((s) => cycleTab(s, delta)); + const tab = this.activeTabOf(); + if (tab && !isTextTab(tab)) this.recordActiveEditor(true); this.focus(); } async reopenClosed(): Promise<void> { @@ -2002,7 +2113,10 @@ export class EditorController implements SlotHost { if (generation !== this.projectGeneration || this.closeSession) return; const r = reopenClosed(useTabs.getState()); if (!r) return; + this.recordLeaving(); useTabs.setState(r.state, true); + const tab = this.activeTabOf(); + if (tab && !isTextTab(tab)) this.recordActiveEditor(true); void this.ensureSlot(r.tabId).then((slot) => slot && (slot.view ? slot.focus() : (slot.wantsFocus = true))); } @@ -2023,8 +2137,11 @@ export class EditorController implements SlotHost { return; } const srcSlot = srcPane?.active ? this.slots.get(srcPane.active) : undefined; + this.recordLeaving(); const r = splitPane(s, paneId, dir); useTabs.setState(r.state, true); + const tab = this.activeTabOf(); + if (tab && !isTextTab(tab)) this.recordActiveEditor(true); const newTab = r.state.panes[r.paneId]?.active; if (newTab) { void this.ensureSlot(newTab, { from: srcSlot }).then((slot) => { @@ -2147,8 +2264,11 @@ export class EditorController implements SlotHost { } return; } + this.recordLeaving(); const r = openTab(s, target, tab.input); useTabs.setState(r.state, true); + const activeTab = this.activeTabOf(); + if (activeTab && !isTextTab(activeTab)) this.recordActiveEditor(true); void this.ensureSlot(r.tabId, { from: this.slots.get(tabId) }).then((slot) => { if (slot?.view) slot.focus(); else if (slot) slot.wantsFocus = true; @@ -2221,7 +2341,9 @@ export class EditorController implements SlotHost { return; } const pane = document.querySelector<HTMLElement>(`[data-pane-id="${useTabs.getState().activePane}"]`); - pane?.querySelector<HTMLElement>("[data-editor-focus], .cm-content")?.focus({ preventScroll: true }); + (pane?.querySelector<HTMLElement>("[data-editor-focus]") ?? pane?.querySelector<HTMLElement>(".cm-content"))?.focus( + { preventScroll: true }, + ); } private stampActive(s: TabsState) { @@ -2429,6 +2551,9 @@ export class EditorController implements SlotHost { { kind: "separator" }, ...(path ? ([ + ...(inProject && path !== project!.root + ? ([{ label: "File Color", submenu: fileColorMenuItems(path) }, { kind: "separator" }] as MenuItem[]) + : []), { label: "Copy Path/Reference…", submenu: [ @@ -2517,6 +2642,26 @@ export class EditorController implements SlotHost { } } +/** + * File Color submenu of a file tab: the project view's File Color rows as action items carrying + * the path (features/project-tree owns the model and the titles), so both menus agree. + */ +function fileColorMenuItems(path: string): MenuItem[] { + const { project, settings } = useProject.getState(); + const current = project ? ownFileColor(relativePath(project.root, path), false, settings)?.toLowerCase() : null; + return [ + ...FILE_COLOR_NAMES.map((name): MenuItem => ({ + kind: "action", + action: `file.${name}`, + arg: path, + checked: current === name, + })), + { kind: "separator" }, + ...(current ? [{ kind: "action" as const, action: "file.clearColor", arg: path }] : []), + { kind: "action", action: "file.editColors" }, + ]; +} + /** Open In › for a file: Project View, Finder / Explorer / Files, associated app, Terminal. */ function openInMenu(path: string, lines?: { line: number; endLine?: number }): MenuItem { return { diff --git a/src/editor/core/copyPathChooser.ts b/src/editor/core/copyPathChooser.ts new file mode 100644 index 000000000..4ace325ea --- /dev/null +++ b/src/editor/core/copyPathChooser.ts @@ -0,0 +1,52 @@ +/** The Copy Path/Reference… chooser: each way to copy, with a preview of the text it copies. */ +import { tx } from "@/platform/i18n"; +import { shortcutLabel } from "@/platform/keymap"; +import { menuGroupItems, type MenuGroupContext } from "@/workbench/contributions"; +import { openPopup, type ListPopupItem, type LspPopup, type PopupPoint } from "@/editor/lsp/popupStore"; +import type { CopyPathRow } from "@/editor/api"; + +/** The chooser's popup: `rows`, then the rows contributed to the `copyPath` menu for `ctx`. */ +export function copyPathPopup( + anchor: PopupPoint | "center", + rows: readonly CopyPathRow[], + ctx: MenuGroupContext, + trailing: readonly ListPopupItem[] = [], +): Extract<LspPopup, { kind: "list" }> { + const contributed = menuGroupItems("copyPath", ctx).flatMap((item) => + (item.kind ?? "item") === "item" && "run" in item && item.id && item.run && item.preview + ? [ + { + id: item.id, + label: item.verbatim ? item.label : tx(item.label), + preview: item.preview, + shortcut: shortcutLabel(item.id), + run: item.run, + }, + ] + : [], + ); + return { + kind: "list", + title: tx("Copy Path/Reference…"), + layout: "copyPath", + anchor, + items: [ + ...rows.flatMap((row) => + row.preview === null + ? [] + : [{ id: row.id, label: tx(row.label), preview: row.preview, shortcut: shortcutLabel(row.id), run: row.run }], + ), + ...contributed, + ...trailing, + ], + }; +} + +/** Opens the chooser for files outside an editor (`openCopyPathChooser` of `@/editor/api`). */ +export function openCopyPathChooser( + anchor: PopupPoint | "center", + rows: readonly CopyPathRow[], + ctx: MenuGroupContext, +): void { + openPopup(copyPathPopup(anchor, rows, ctx)); +} diff --git a/src/editor/core/focusedCell.test.ts b/src/editor/core/focusedCell.test.ts new file mode 100644 index 000000000..d713dfbfe --- /dev/null +++ b/src/editor/core/focusedCell.test.ts @@ -0,0 +1,223 @@ +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { EditorView } from "@codemirror/view"; +import { executeAction, registerActions } from "@/platform/actions"; +import { evaluateWhen, getContext, useContextKeys } from "@/platform/context"; +import { installKeyboardDispatcher } from "@/platform/keymap"; +import { _setFocusedCellEditor } from "@/editor/api"; +import { TEXT_WHEN, registerEditorActions } from "./actions"; +import { editorController, useEditorStatus, useTabs } from "./controller"; +import { initialTabsState } from "./model/tabs"; +import { columnModeField, isColumnMode } from "./cm/columnMode"; + +const toggleReadOnlyMock = vi.hoisted(() => vi.fn()); +vi.mock("./fileAttributes", async (original) => ({ + ...(await original<typeof import("./fileAttributes")>()), + toggleReadOnly: toggleReadOnlyMock, +})); + +const ctrl = editorController(); +let disposeActions: () => void; +beforeAll(() => { + disposeActions = registerEditorActions(); + ctrl.start(); +}); +afterAll(() => { + ctrl.stop(); + disposeActions(); +}); +afterEach(() => { + useTabs.setState(initialTabsState(), true); + useEditorStatus.setState({ status: null }); + useContextKeys.setState({}, true); + _setFocusedCellEditor(null); + toggleReadOnlyMock.mockClear(); +}); + +/** A bare editor standing in for a focused notebook cell (the fact CellEditor publishes). */ +function focusedCell(doc = "x = 1\n"): { view: EditorView; clear: () => void } { + const host = document.createElement("div"); + document.body.appendChild(host); + // `columnModeField`: what a cell editor carries through its own extension list. + const view = new EditorView({ doc, parent: host, extensions: columnModeField }); + view.focus(); + if (!view.hasFocus) throw new Error("the jsdom view did not take focus"); + _setFocusedCellEditor(view); + return { view, clear: () => _setFocusedCellEditor(null) }; +} + +function disposeView(cell: { view: EditorView }): void { + cell.view.destroy(); + cell.view.dom.remove(); +} + +describe("editor context keys with a focused notebook cell", () => { + it("keeps the keys on while a cell editor has focus, with no text editor open", () => { + const cell = focusedCell(); + try { + ctrl.publishContext(); + expect(getContext().textEditorActive).toBe(true); + expect(getContext().editorTextFocus).toBe(true); + // Republishing (tab churn, pane focus) must not drop the keys. + ctrl.publishContext(); + expect(getContext().textEditorActive).toBe(true); + expect(getContext().editorTextFocus).toBe(true); + } finally { + cell.clear(); + disposeView(cell); + } + }); + + it("lets a focused cell editor win over the mounted but unfocused text editor", async () => { + await ctrl.openFile("/p/a.ts", { focus: false }); + const slot = ctrl.activeSlot!; + const host = document.createElement("div"); + document.body.appendChild(host); + try { + const textView = slot.mount(host); + ctrl.onMounted(slot); + const cell = focusedCell(); + ctrl.publishContext(); + expect(getContext().editorTextFocus).toBe(true); + expect(textView.hasFocus).toBe(false); + cell.clear(); + disposeView(cell); + } finally { + host.remove(); + } + }); + + it("drops the keys once no cell editor has focus", () => { + const cell = focusedCell(); + try { + ctrl.publishContext(); + expect(getContext().textEditorActive).toBe(true); + cell.clear(); + ctrl.publishContext(); + expect(getContext().textEditorActive).toBe(false); + expect(getContext().editorTextFocus).toBe(false); + } finally { + disposeView(cell); + } + }); + + it("keeps a text tab's own keys when no cell editor is focused", async () => { + await ctrl.openFile("/p/a.ts", { focus: false }); + const slot = ctrl.activeSlot!; + const host = document.createElement("div"); + document.body.appendChild(host); + try { + const view = slot.mount(host); + ctrl.onMounted(slot); + view.focus(); + ctrl.publishContext(); + expect(getContext().textEditorActive).toBe(true); + expect(getContext().editorTextFocus).toBe(true); + } finally { + host.remove(); + } + }); +}); + +describe("editor actions in a focused notebook cell", () => { + it("run in the focused cell editor, not the last text tab", async () => { + await ctrl.openFile("/p/a.ts", { focus: false }); + const slot = ctrl.activeSlot!; + const host = document.createElement("div"); + document.body.appendChild(host); + try { + const textView = slot.mount(host); + ctrl.onMounted(slot); + const cell = focusedCell(); + ctrl.publishContext(); + await executeAction("editor.toggleColumnSelection"); + expect(isColumnMode(cell.view.state)).toBe(true); + expect(isColumnMode(textView.state)).toBe(false); + cell.clear(); + disposeView(cell); + } finally { + host.remove(); + } + }); + + it("do not toggle the last text tab's read-only attribute", async () => { + await ctrl.openFile("/p/a.ts", { focus: false }); + const slot = ctrl.activeSlot!; + const host = document.createElement("div"); + document.body.appendChild(host); + try { + slot.mount(host); + ctrl.onMounted(slot); + const cell = focusedCell(); + await executeAction("file.toggleReadOnly"); + expect(toggleReadOnlyMock).not.toHaveBeenCalled(); + // Without a focused cell the text editor is toggled, as before. + cell.clear(); + ctrl.publishContext(); + await executeAction("file.toggleReadOnly"); + expect(toggleReadOnlyMock).toHaveBeenCalledOnce(); + } finally { + host.remove(); + } + }); + + it("give the keyboard to the cell: ⌥⌘L reaches an editor action there", () => { + const cell = focusedCell(); + ctrl.publishContext(); + const reformat = vi.fn(); + const disposeStub = registerActions([ + { id: "code.reformat", title: "Reformat Code", category: "Code", when: TEXT_WHEN, run: reformat }, + ]); + const uninstall = installKeyboardDispatcher(window); + try { + const event = new KeyboardEvent("keydown", { + key: "l", + code: "KeyL", + altKey: true, + metaKey: true, + bubbles: true, + cancelable: true, + }); + cell.view.contentDOM.dispatchEvent(event); + expect(reformat).toHaveBeenCalledOnce(); + expect(event.defaultPrevented).toBe(true); + } finally { + uninstall(); + disposeStub(); + cell.clear(); + disposeView(cell); + } + }); +}); + +describe("Copy Path with a notebook tab", () => { + it("resolves the notebook tab's path while a cell editor has focus", () => { + const paneId = useTabs.getState().activePane; + useTabs.setState((s) => ({ + ...s, + panes: { + ...s.panes, + [paneId]: { + ...s.panes[paneId]!, + tabs: [ + { + id: "nb-1", + input: { kind: "notebook", key: "notebook:/p/a.ipynb", path: "/p/a.ipynb" }, + preview: false, + pinned: false, + }, + ], + active: "nb-1", + mru: ["nb-1"], + }, + }, + })); + const cell = focusedCell(); + try { + ctrl.publishContext(); + expect(ctrl.activePath()).toBe("/p/a.ipynb"); + expect(evaluateWhen("textEditorActive", getContext())).toBe(true); + } finally { + cell.clear(); + } + }); +}); diff --git a/src/editor/core/index.ts b/src/editor/core/index.ts index 0e9508125..128a280e6 100644 --- a/src/editor/core/index.ts +++ b/src/editor/core/index.ts @@ -10,7 +10,8 @@ import { registerOverlay, registerStatusItem, } from "@/workbench/contributions"; -import { _provideCodePreview, _provideDocumentAttacher, editorsFor } from "@/editor/api"; +import { _provideCodePreview, _provideCopyPathChooser, _provideDocumentAttacher, editorsFor } from "@/editor/api"; +import { openCopyPathChooser } from "./copyPathChooser"; import { isUntitledUri } from "@/platform/virtualDocs"; import { formatDocument } from "@/editor/lsp/format"; import { chooserTitle, locationItems, pinToFind } from "@/editor/lsp/navigation"; @@ -82,6 +83,7 @@ export function activate(): void | (() => void) { }, }); _provideDocumentAttacher((path, options) => attachDocument(ctrl.manager, path, options)); + _provideCopyPathChooser(openCopyPathChooser); _provideCodePreview((path, editable) => previewExtensions(path, ctrl.manager.settings()?.editor, ctrl.manager.backend, editable), ); diff --git a/src/editor/core/model/model.test.ts b/src/editor/core/model/model.test.ts index 0041fbed1..51b6058b0 100644 --- a/src/editor/core/model/model.test.ts +++ b/src/editor/core/model/model.test.ts @@ -270,6 +270,51 @@ describe("navigation history", () => { expect(h.entries).toHaveLength(2); expect(h.index).toBe(0); }); + + it("tracks split panes and non-path inputs while keeping snapshots text-only", () => { + const h = new NavigationHistory(); + const agent = { kind: "agent-session", key: "agent:t1", data: { task: "t1" } }; + const cli = { kind: "cli", key: "cli:1", data: { name: "Local", command: "" } }; + h.update({ path: "/p/a.ts", line: 10, col: 0, paneId: "p1" }, true); + h.update({ path: "/p/a.ts", line: 10, col: 0, paneId: "p2" }, true); + h.update({ path: "", line: 0, col: 0, input: agent, paneId: "p1" }, true); + h.update({ path: "", line: 0, col: 0, input: cli, paneId: "p2" }, true); + h.update({ path: "", line: 0, col: 0, input: agent, paneId: "p1" }, true); + + expect(h.entries).toHaveLength(5); + expect(h.snapshot()).toMatchObject({ + index: 1, + entries: [ + { path: "/p/a.ts", paneId: "p1" }, + { path: "/p/a.ts", paneId: "p2" }, + ], + }); + + // Skipping a stale intermediate entry also skips the duplicate place it exposes. + expect(h.back((loc) => loc.input?.key !== cli.key)).toMatchObject({ + path: "/p/a.ts", + paneId: "p2", + }); + expect(h.back(() => false)).toBeNull(); + expect(h.current).toMatchObject({ path: "/p/a.ts", paneId: "p2" }); + expect(h.forward((loc) => loc.input?.key !== cli.key)).toMatchObject({ + input: agent, + paneId: "p1", + }); + }); + + it("removePath ignores empty paths and collapses newly adjacent duplicates", () => { + const h = new NavigationHistory(); + const agent = { kind: "agent-session", key: "agent:t1", data: { task: "t1" } }; + h.update({ path: "", line: 0, col: 0, input: agent, paneId: "p1" }, true); + h.update({ path: "/p/gone.ts", line: 5, col: 0, paneId: "p1" }, true); + h.update({ path: "", line: 0, col: 0, input: agent, paneId: "p1" }, true); + h.removePath(""); + expect(h.entries).toHaveLength(3); + h.removePath("/p/gone.ts"); + expect(h.entries).toHaveLength(1); + expect(h.current).toMatchObject({ input: agent, paneId: "p1" }); + }); }); describe("selection stack", () => { diff --git a/src/editor/core/model/navHistory.ts b/src/editor/core/model/navHistory.ts index 2bb19c3bb..549876d6f 100644 --- a/src/editor/core/model/navHistory.ts +++ b/src/editor/core/model/navHistory.ts @@ -24,10 +24,10 @@ export function isNavigation(tr: Transaction): boolean { const MAX_ENTRIES = 100; const sameTarget = (a: Omit<NavigationLocation, "time">, b: Omit<NavigationLocation, "time">) => - a.path === b.path && a.input?.key === b.input?.key; + a.path === b.path && a.input?.key === b.input?.key && a.paneId === b.paneId; const samePlace = (a: Omit<NavigationLocation, "time">, b: Omit<NavigationLocation, "time">) => - sameTarget(a, b) && Math.abs(a.line - b.line) < MERGE_LINES; + sameTarget(a, b) && (Boolean(a.input) || Math.abs(a.line - b.line) < MERGE_LINES); export class NavigationHistory { entries: NavigationLocation[] = []; @@ -49,8 +49,8 @@ export class NavigationHistory { } /** - * Records the caret position. `navigation`: the move came from a navigation - * command; a file switch always counts as one. + * Records the caret position or editor tab. `navigation`: the move came + * from a navigation command; a tab or split-pane switch always counts as one. */ update(loc: Omit<NavigationLocation, "time">, navigation = false) { const entry = { ...loc, time: this.now() }; @@ -76,28 +76,64 @@ export class NavigationHistory { this.emit(); } - /** Moves back; returns the location to navigate to. */ - back(): NavigationLocation | null { - if (!this.canGoBack()) return null; - this.index--; - this.emit(); - return this.current; + /** Moves back to the previous accepted entry; skips duplicates exposed by stale entries. */ + back(accept?: (loc: NavigationLocation) => boolean): NavigationLocation | null { + const cur = this.current; + let skipped = false; + for (let i = this.index - 1; i >= 0; i--) { + const candidate = this.entries[i]!; + if (accept && !accept(candidate)) { + skipped = true; + continue; + } + if (skipped && cur && samePlace(candidate, cur)) continue; + this.index = i; + this.emit(); + return candidate; + } + return null; } - forward(): NavigationLocation | null { - if (!this.canGoForward()) return null; - this.index++; - this.emit(); - return this.current; + /** Moves forward to the next accepted entry; skips duplicates exposed by stale entries. */ + forward(accept?: (loc: NavigationLocation) => boolean): NavigationLocation | null { + const cur = this.current; + let skipped = false; + for (let i = this.index + 1; i < this.entries.length; i++) { + const candidate = this.entries[i]!; + if (accept && !accept(candidate)) { + skipped = true; + continue; + } + if (skipped && cur && samePlace(candidate, cur)) continue; + this.index = i; + this.emit(); + return candidate; + } + return null; } - /** Drops entries of a deleted file. */ + /** Drops entries of a deleted file and collapses newly adjacent duplicates. */ removePath(path: string) { + if (!path) return; const before = this.entries.length; const cur = this.current; - this.entries = this.entries.filter((e) => e.path !== path); - if (this.entries.length === before) return; - this.index = cur && cur.path !== path ? this.entries.indexOf(cur) : this.entries.length - 1; + const kept: NavigationLocation[] = []; + let nextIndex = -1; + for (let i = 0; i < this.entries.length; i++) { + const entry = this.entries[i]!; + if (entry.path === path) continue; + const prev = kept[kept.length - 1]; + if (prev && samePlace(prev, entry)) { + kept[kept.length - 1] = entry; + if (entry === cur || i <= this.index) nextIndex = kept.length - 1; + } else { + kept.push(entry); + if (entry === cur || (nextIndex < 0 && i >= this.index)) nextIndex = kept.length - 1; + } + } + if (kept.length === before) return; + this.entries = kept; + this.index = cur && cur.path !== path ? Math.min(nextIndex, kept.length - 1) : kept.length - 1; this.emit(); } diff --git a/src/editor/core/view/EditorArea.tsx b/src/editor/core/view/EditorArea.tsx index b626a90cf..b598fd19e 100644 --- a/src/editor/core/view/EditorArea.tsx +++ b/src/editor/core/view/EditorArea.tsx @@ -360,7 +360,7 @@ function PaneView({ paneId }: { paneId: string }) { const onFocus = () => { setContext("editorFocus", true); - if (!isActivePane) useTabs.setState((s) => ({ ...s, activePane: paneId }), true); + if (!isActivePane) ctrl.focusPane(paneId); ctrl.publishContext(); }; const onBlur = (e: FocusEvent) => { diff --git a/src/editor/lsp/actions.test.ts b/src/editor/lsp/actions.test.ts new file mode 100644 index 000000000..19cc922ea --- /dev/null +++ b/src/editor/lsp/actions.test.ts @@ -0,0 +1,145 @@ +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { EditorView } from "@codemirror/view"; +import { executeAction } from "@/platform/actions"; +import { getContext, setContext, useContextKeys } from "@/platform/context"; +import { _setFocusedCellEditor } from "@/editor/api"; +import { registerLspActions } from "./actions"; +import { registerInlineCompletionActions } from "./inlineCompletion"; +import { editorController, useEditorStatus, useTabs } from "@/editor/core/controller"; +import { initialTabsState } from "@/editor/core/model/tabs"; + +const { formatDocument, showIntentions, refactorThis, requestInline, showHint } = vi.hoisted(() => ({ + formatDocument: vi.fn(), + showIntentions: vi.fn(), + refactorThis: vi.fn(), + requestInline: vi.fn(), + showHint: vi.fn(), +})); +vi.mock("./format", async (original) => ({ + ...(await original<typeof import("./format")>()), + formatDocument, +})); +vi.mock("./intentions", async (original) => ({ + ...(await original<typeof import("./intentions")>()), + showIntentions, +})); +vi.mock("@/editor/refactor", async (original) => ({ + ...(await original<typeof import("@/editor/refactor")>()), + refactorThis, +})); +vi.mock("./inlineCompletion", async (original) => ({ + ...(await original<typeof import("./inlineCompletion")>()), + requestInline, +})); +vi.mock("./hint", async (original) => ({ + ...(await original<typeof import("./hint")>()), + showHint, +})); + +const ctrl = editorController(); +let dispose: () => void; +beforeAll(() => { + const lsp = registerLspActions(); + const inline = registerInlineCompletionActions(); + dispose = () => { + inline(); + lsp(); + }; + ctrl.start(); +}); +afterAll(() => { + ctrl.stop(); + dispose(); +}); +afterEach(() => { + useTabs.setState(initialTabsState(), true); + useEditorStatus.setState({ status: null }); + useContextKeys.setState({}, true); + _setFocusedCellEditor(null); + vi.clearAllMocks(); +}); + +/** Mounts the text editor of an open tab (a background text tab, as in a split with a notebook). */ +async function mountTextEditor(path = "/p/a.ts"): Promise<EditorView> { + await ctrl.openFile(path, { focus: false }); + const slot = ctrl.activeSlot!; + const host = document.createElement("div"); + document.body.appendChild(host); + const view = slot.mount(host); + ctrl.onMounted(slot); + return view; +} + +/** A bare editor standing in for a focused notebook cell (the fact CellEditor publishes). */ +function focusedCell(): { view: EditorView; clear: () => void } { + const host = document.createElement("div"); + document.body.appendChild(host); + const view = new EditorView({ doc: "x = 1\nprint(x)\n", parent: host }); + view.focus(); + if (!view.hasFocus) throw new Error("the jsdom view did not take focus"); + _setFocusedCellEditor(view); + return { + view, + clear: () => { + _setFocusedCellEditor(null); + view.destroy(); + view.dom.remove(); + }, + }; +} + +describe("editor actions with a focused notebook cell", () => { + it("run in the focused cell, not the last text tab", async () => { + const textView = await mountTextEditor(); + const cell = focusedCell(); + setContext("projectOpen", true); + try { + ctrl.publishContext(); + expect(getContext().editorTextFocus).toBe(true); + await executeAction("code.reformat"); + await executeAction("code.showIntentions"); + await executeAction("refactor.thisMenu"); + expect(formatDocument).toHaveBeenCalledWith(cell.view, { explicit: true }); + expect(showIntentions).toHaveBeenCalledWith(cell.view); + expect(refactorThis).toHaveBeenCalledWith(cell.view, expect.any(Function)); + expect(showHint).not.toHaveBeenCalled(); + // The background text editor was not acted on (it is the view `activeEditor()` holds). + expect(formatDocument).not.toHaveBeenCalledWith(textView, { explicit: true }); + expect(showIntentions).toHaveBeenCalledOnce(); + } finally { + cell.clear(); + hostRemove(textView); + } + }); + + it("keep running in the focused text editor when no cell editor is focused", async () => { + const view = await mountTextEditor(); + setContext("projectOpen", true); + view.focus(); + await vi.waitFor(() => expect(getContext().editorTextFocus).toBe(true)); + await executeAction("code.reformat"); + expect(formatDocument).toHaveBeenCalledWith(view, { explicit: true }); + expect(formatDocument).toHaveBeenCalledOnce(); + }); + + it("target the focused cell for inline completion", async () => { + const textView = await mountTextEditor(); + const cell = focusedCell(); + try { + ctrl.publishContext(); + await executeAction("editor.inlineCompletion.trigger"); + await vi.waitFor(() => expect(showHint).toHaveBeenCalled()); + expect(showHint).toHaveBeenCalledWith(cell.view, expect.any(String)); + expect(showHint).not.toHaveBeenCalledWith(textView, expect.anything()); + } finally { + cell.clear(); + hostRemove(textView); + } + }); +}); + +function hostRemove(view: EditorView): void { + const host = view.dom.parentElement; + view.destroy(); + host?.remove(); +} diff --git a/src/editor/lsp/actions.ts b/src/editor/lsp/actions.ts index 04256a030..00c05de73 100644 --- a/src/editor/lsp/actions.ts +++ b/src/editor/lsp/actions.ts @@ -2,7 +2,14 @@ import { generateActionIcon, isGenerateAction } from "./generate"; import type { EditorView } from "@codemirror/view"; import { executeAction, registerActions, type Action } from "@/platform/actions"; -import { activeEditor, editorsFor, registerSaveParticipant, whenSynced, type TextEditorHandle } from "@/editor/api"; +import { + activeEditor, + editorsFor, + focusedCellEditor, + registerSaveParticipant, + whenSynced, + type TextEditorHandle, +} from "@/editor/api"; import { call, commands } from "@/platform/ipc"; import { maybeEditorService } from "@/workbench/contributions"; import { useProject } from "@/platform/project"; @@ -67,6 +74,13 @@ export const GENERATE_KEY_WHEN = GENERATE_LANGUAGES.map((id) => `editorLangId == function withEditor(run: (view: EditorView) => unknown): Action["run"] { return () => { + // While a notebook cell editor has focus it is the editor the action runs in + // (the notebook publishes the editor context keys for it), never the last text tab. + const cell = focusedCellEditor(); + if (cell) { + void run(cell); + return; + } const ed = activeEditor(); if (!ed) return; void run(ed.view); @@ -230,11 +244,15 @@ function editorAction( return { id, title, category, when: EDITOR_WHEN, run: withEditor(run), ...extra }; } -/** Whether saving a `language` file formats it: Format on save, or Run on save of an external formatter. */ +/** + * Whether saving a `language` file formats it: Format on save, or Run on save of an external + * formatter. dprint's covers any language its configuration does (the backend decides). + */ export function formatsOnSave(settings: Settings | null, language: string): boolean { - const { prettier, oxfmt, biome, ruff, black } = validateLanguages(settings?.languages); + const { prettier, oxfmt, biome, dprint, ruff, black } = validateLanguages(settings?.languages); return ( !!settings?.editor?.formatOnSave || + dprint.runOnSave || [prettier, oxfmt, biome, ruff, black].some( (formatter) => formatter.runOnSave && formatter.languages.includes(language), ) @@ -325,6 +343,13 @@ export function registerLspActions(): () => void { (v) => formatDocument(v, { explicit: true, tool: "biome" }), { keywords: ["format", "biome"] }, ), + editorAction( + "code.reformatWithDprint", + "Reformat with dprint", + "Code", + (v) => formatDocument(v, { explicit: true, tool: "dprint" }), + { keywords: ["format", "dprint"] }, + ), editorAction( "code.reformatWithRuff", "Reformat with Ruff", @@ -428,6 +453,9 @@ export function registerLspActions(): () => void { category: "Refactor", when: "projectOpen", run: ({ ctx }) => { + // A focused notebook cell is the editor here, like for Show Context Actions. + const cell = focusedCellEditor(); + if (cell && evaluateWhen(EDITOR_WHEN, ctx)) return refactorThis(cell, startRename); const ed = activeEditor(); if (ed && evaluateWhen(EDITOR_WHEN, ctx)) return refactorThis(ed.view, startRename); showNothingHere(); @@ -448,6 +476,9 @@ export function registerLspActions(): () => void { editorAction("refactor.extractInterface", "Extract Interface…", "Refactor", (v) => runRefactoring(v, "extractInterface"), ), + editorAction("refactor.extractTypeAlias", "Extract Type Alias…", "Refactor", (v) => + runRefactoring(v, "extractTypeAlias"), + ), editorAction("refactor.move", "Move…", "Refactor", (v) => runRefactoring(v, "move")), editorAction("refactor.changeSignature", "Change Signature…", "Refactor", (v) => runRefactoring(v, "changeSignature"), diff --git a/src/editor/lsp/completion.ts b/src/editor/lsp/completion.ts index ed33faae6..85a4e8ebb 100644 --- a/src/editor/lsp/completion.ts +++ b/src/editor/lsp/completion.ts @@ -62,6 +62,8 @@ import { iconNode } from "@/ui/iconNode"; import { parameterInfoOrLeave, triggerSignatureHelp } from "./signature"; import { featureBackoff } from "./availability"; import { pathCompletionSource, pathContext, pathLike } from "./fileReferences"; +import { cssVariablePrefix, cssVariableSource, STYLESHEETS, type VariableOption } from "./cssVariables"; +import { javaDeclarationAt, variableNameSource } from "./variableNames"; import { editorPrefs } from "@/platform/editorSettings"; import { tx } from "@/platform/i18n"; import { showHint } from "./hint"; @@ -619,8 +621,17 @@ function cancelInflight() { inflight = null; } +/** Inside a stylesheet's `var(`, where `cssVariableSource` lists the project's custom properties instead of the server or the document's words. */ +function inVarCall(ctx: CompletionContext): boolean { + const language = ctx.state.facet(lspDoc)?.language ?? ""; + if (!STYLESHEETS.has(language) || !isTauri()) return false; + const line = ctx.state.doc.lineAt(ctx.pos); + return cssVariablePrefix(line.text.slice(0, ctx.pos - line.from)) !== null; +} + /** Language-data completion sources (keywords etc.), used when no server answers. */ async function fallback(ctx: CompletionContext): Promise<CompletionResult | null> { + if (inVarCall(ctx)) return null; const sources = ctx.state.languageDataAt<CompletionSource | readonly (string | Completion)[]>( "autocomplete", ctx.pos, @@ -756,6 +767,7 @@ async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionRe ? list.items.filter((it) => matchesCase(it.filterText ?? it.label, typed, prefs.caseSensitivity)) : list.items, ); + if (inVarCall(ctx)) items = items.filter((it) => !it.label.startsWith("--")); // A server snippet named like a live template (jdtls `sout`, `fori`) would be listed twice; the template wins. if (items.some((it) => it.kind === "snippet")) { const own = await contributedSource(ctx); @@ -919,6 +931,9 @@ function gated(source: CompletionSource): CompletionSource { if (ctx.state.field(smartLookup, false) && source !== claimingLspSource) return null; const only = exclusiveSource(ctx); if (only) return source === contributedSource ? only(ctx) : null; + // At a Java declaration's name only names fit: IDEA lists no live templates there, and + // jdtls' own name proposals repeat the type (`orderBookOrderBook`). + if (source !== variableNameSource && javaDeclarationAt(ctx)) return null; if (!ctx.explicit && (!editorPrefs().completion.autoPopup || inplaceRenameActive(ctx.state))) return null; if (!editorPrefs().completion.sortAlphabetically) return source(ctx); return Promise.resolve(source(ctx)).then( @@ -1052,6 +1067,13 @@ export function explicitCompletion(view: EditorView): boolean { // Rendering function kindBadge(c: Completion): Node | null { + const swatch = (c as VariableOption).swatch; + if (swatch) { + const span = document.createElement("span"); + span.className = "cm-lsp-kind cm-lsp-swatch"; + span.style.setProperty("--swatch", swatch); + return span; + } if (!isLsp(c) && "icon" in c) { const icon = (c as RichCompletion).icon; if (icon) return iconNode(icon, 16, "cm-lsp-kind"); @@ -1185,7 +1207,13 @@ export function completionExtension() { smartLookup, endSmartLookup, autocompletion({ - override: [gated(claimingLspSource), gated(contributedSource), gated(pathFallbackSource)], + override: [ + gated(claimingLspSource), + gated(contributedSource), + gated(pathFallbackSource), + gated(cssVariableSource), + gated(variableNameSource), + ], icons: false, addToOptions: [ { render: kindBadge, position: 20 }, diff --git a/src/editor/lsp/cssVariables.test.ts b/src/editor/lsp/cssVariables.test.ts new file mode 100644 index 000000000..2ff1a5d6b --- /dev/null +++ b/src/editor/lsp/cssVariables.test.ts @@ -0,0 +1,73 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { CssVariable } from "@/platform/ipc"; +import { cssVariableAt, cssVariablePrefix, swatchColor, variableHoverMarkdown, variableOptions } from "./cssVariables"; + +const at = (path: string, line: number) => ({ + path, + range: { start: { line, col: 2 }, end: { line, col: 6 } }, + uri: null, +}); +const v = (name: string, value: string | null, path: string, line = 0): CssVariable => ({ + name, + value, + location: at(path, line), +}); + +describe("var() completion context", () => { + it("answers inside var( with the name typed so far", () => { + expect(cssVariablePrefix(".a { color: var(")).toBe(""); + expect(cssVariablePrefix(".a { color: var( --ac")).toBe("--ac"); + expect(cssVariablePrefix(" margin: calc(var(-")).toBe("-"); + expect(cssVariablePrefix(".a { color: var(--a) ")).toBeNull(); + expect(cssVariablePrefix(".a { color: avar(")).toBeNull(); + expect(cssVariablePrefix(".a { color: re")).toBeNull(); + }); + + it("finds the var(--name) under a column", () => { + const line = " border: 1px solid var(--line, red) var(--x);"; + expect(cssVariableAt(line, line.indexOf("--line") + 2)).toEqual({ name: "--line", from: 24, to: 30 }); + expect(cssVariableAt(line, line.indexOf("--x") + 3)?.name).toBe("--x"); + expect(cssVariableAt(line, 3)).toBeNull(); + expect(cssVariableAt(" --line: red;", 4)).toBeNull(); + }); +}); + +describe("custom property options", () => { + afterEach(() => vi.unstubAllGlobals()); + + it("lists each name once, the document's own declaration first and boosted", () => { + vi.stubGlobal("CSS", { supports: (_p: string, value: string) => /^#|^rgb/.test(value) }); + const options = variableOptions( + [ + v("--bg", "#fff", "/p/a.css"), + v("--bg", "#000", "/p/theme/dark.css"), + v("--gap", "4px 8px", "/p/theme/light.css"), + v("--ring", "var(--bg)", "/p/theme/light.css"), + ], + "/p/a.css", + ); + expect(options).toEqual([ + { label: "--bg", type: "variable", boost: 10, typeText: "#fff", swatch: "#fff" }, + { label: "--gap", type: "variable", boost: 0, typeText: "4px 8px" }, + { label: "--ring", type: "variable", boost: 0, typeText: "var(--bg)" }, + ]); + }); + + it("shows a swatch only for color values", () => { + vi.stubGlobal("CSS", { supports: () => true }); + expect(swatchColor("red !important")).toBe("red"); + expect(swatchColor("var(--bg)")).toBeNull(); + expect(swatchColor("inherit")).toBeNull(); + expect(swatchColor(null)).toBeNull(); + vi.stubGlobal("CSS", { supports: () => false }); + expect(swatchColor("4px")).toBeNull(); + }); + + it("hovers every declaration of the name with its file", () => { + const vars = [v("--bg", "#fff", "/p/theme/light.css", 1), v("--bg", "#000", "/p/theme/dark.css", 4)]; + expect(variableHoverMarkdown("--bg", vars)).toBe( + "```css\n--bg: #fff; /* light.css:2 */\n--bg: #000; /* dark.css:5 */\n```", + ); + expect(variableHoverMarkdown("--fg", vars)).toBeNull(); + }); +}); diff --git a/src/editor/lsp/cssVariables.ts b/src/editor/lsp/cssVariables.ts new file mode 100644 index 000000000..fe692719f --- /dev/null +++ b/src/editor/lsp/cssVariables.ts @@ -0,0 +1,101 @@ +/** + * CSS custom properties from the whole project: `var(--…)` completion (the document's own + * declarations first, values in the type column, a swatch for colors) and the hover over + * `var(--x)`. The language server only sees the open stylesheet; declarations come from + * the backend (`web_css_variables`: the document's text plus the project index). + */ +import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete"; +import type { EditorView } from "@codemirror/view"; +import { whenSynced } from "@/editor/api"; +import { call, commands, isTauri, type CssVariable, type Hover } from "@/platform/ipc"; +import { basename } from "@/platform/project"; +import { lspDoc } from "./lsp"; +import { offsetToPos } from "./positions"; + +export const STYLESHEETS = new Set(["css", "scss", "less"]); + +/** The custom property name typed so far inside `var(` at the end of `before`, or null outside one. */ +export function cssVariablePrefix(before: string): string | null { + const m = /\bvar\(\s*(-[\w-]*)?$/.exec(before); + return m ? (m[1] ?? "") : null; +} + +/** The `--name` of a `var(--name)` on `line` that covers column `col`. */ +export function cssVariableAt(line: string, col: number): { name: string; from: number; to: number } | null { + for (const m of line.matchAll(/\bvar\(\s*(--[\w-]+)/g)) { + const to = m.index + m[0].length; + const from = to - m[1]!.length; + if (col >= from && col <= to) return { name: m[1]!, from, to }; + } + return null; +} + +const NOT_SWATCH = /^(?:inherit|initial|unset|revert|revert-layer|currentcolor)$/i; + +/** The value as a CSS color, when the browser parses it as one (not `var(…)`: that is always "valid"). */ +export function swatchColor(value: string | null): string | null { + const color = value?.replace(/\s*!important$/i, ""); + if (!color || /var\(/i.test(color) || NOT_SWATCH.test(color)) return null; + return typeof CSS !== "undefined" && CSS.supports?.("color", color) ? color : null; +} + +/** An option with its value in the type column and, for a color, a swatch for its icon. */ +export type VariableOption = Completion & { typeText?: string; swatch?: string }; + +/** A completion option per name, the first declaration winning (the backend lists the document's own first). */ +export function variableOptions(vars: readonly CssVariable[], path: string): VariableOption[] { + const seen = new Set<string>(); + const options: VariableOption[] = []; + for (const v of vars) { + if (seen.has(v.name)) continue; + seen.add(v.name); + const swatch = swatchColor(v.value); + options.push({ + label: v.name, + type: "variable", + boost: v.location.path === path ? 10 : 0, + ...(v.value ? { typeText: v.value } : {}), + ...(swatch ? { swatch } : {}), + }); + } + return options; +} + +async function variablesOf(doc: number, view: EditorView | undefined): Promise<CssVariable[]> { + if (view) await whenSynced(view); + return call(commands.webCssVariables(doc)).catch(() => []); +} + +export async function cssVariableSource(ctx: CompletionContext): Promise<CompletionResult | null> { + const doc = ctx.state.facet(lspDoc); + if (!doc || doc.virtual || doc.readOnly || !STYLESHEETS.has(doc.language) || !isTauri()) return null; + const line = ctx.state.doc.lineAt(ctx.pos); + const prefix = cssVariablePrefix(line.text.slice(0, ctx.pos - line.from)); + if (prefix === null) return null; + const vars = await variablesOf(doc.doc, ctx.view); + if (ctx.aborted || !vars.length) return null; + return { from: ctx.pos - prefix.length, options: variableOptions(vars, doc.path), validFor: /^-[\w-]*$|^$/ }; +} + +/** Hover over `var(--x)`: each declaration with its value and file. */ +export function variableHoverMarkdown(name: string, vars: readonly CssVariable[]): string | null { + const lines = vars + .filter((v) => v.name === name) + .map((v) => `${name}: ${v.value ?? ""}; /* ${basename(v.location.path)}:${v.location.range.start.line + 1} */`); + return lines.length ? "```css\n" + lines.join("\n") + "\n```" : null; +} + +export async function cssVariableHover(view: EditorView, pos: number): Promise<Hover | null> { + const doc = view.state.facet(lspDoc); + if (!doc || doc.virtual || !STYLESHEETS.has(doc.language) || !isTauri()) return null; + const line = view.state.doc.lineAt(pos); + const at = cssVariableAt(line.text, pos - line.from); + if (!at) return null; + const value = variableHoverMarkdown(at.name, await variablesOf(doc.doc, view)); + if (!value) return null; + const range = { + start: offsetToPos(view.state.doc, line.from + at.from), + end: offsetToPos(view.state.doc, line.from + at.to), + }; + return { contents: { kind: "markdown", value }, range }; +} diff --git a/src/editor/lsp/format.test.ts b/src/editor/lsp/format.test.ts index c8a4af782..3729289d3 100644 --- a/src/editor/lsp/format.test.ts +++ b/src/editor/lsp/format.test.ts @@ -185,6 +185,8 @@ describe("format on save provider isolation", () => { expect(formatsOnSave(settings({ ruff: { runOnSave: true } }), "python")).toBe(true); expect(formatsOnSave(settings({ ruff: { runOnSave: true } }), "typescript")).toBe(false); expect(formatsOnSave(settings({}), "typescript")).toBe(false); + // dprint's configuration decides which files it formats. + expect(formatsOnSave(settings({ dprint: { runOnSave: true } }), "toml")).toBe(true); expect(formatsOnSave(settings({}, true), "rust")).toBe(true); expect(formatsOnSave(null, "typescript")).toBe(false); }); diff --git a/src/editor/lsp/format.ts b/src/editor/lsp/format.ts index 6b83aab76..bd5e1912d 100644 --- a/src/editor/lsp/format.ts +++ b/src/editor/lsp/format.ts @@ -96,7 +96,7 @@ interface FormatDocumentOptions { explicit: boolean; selectionOnly?: boolean; onSave?: boolean; - /** Runs this external formatter whatever the settings select (Reformat with Prettier/oxfmt/Biome). */ + /** Runs this external formatter whatever the settings select (Reformat with Prettier/oxfmt/Biome/dprint). */ tool?: ExternalFormatter; /** Formats only these ranges, e.g. the text changed since the last commit; an empty list formats nothing. */ ranges?: readonly OffsetRange[]; @@ -181,6 +181,7 @@ async function format(view: EditorView, opts: FormatDocumentOptions): Promise<Fo prettier: { failed: "Prettier formatting failed", timedOut: "Prettier formatting timed out" }, oxfmt: { failed: "oxfmt formatting failed", timedOut: "oxfmt formatting timed out" }, biome: { failed: "Biome formatting failed", timedOut: "Biome formatting timed out" }, + dprint: { failed: "dprint formatting failed", timedOut: "dprint formatting timed out" }, ruff: { failed: "Ruff formatting failed", timedOut: "Ruff formatting timed out" }, black: { failed: "Black formatting failed", timedOut: "Black formatting timed out" }, }[e.data.tool] diff --git a/src/editor/lsp/formatErrors.test.tsx b/src/editor/lsp/formatErrors.test.tsx index 1685e3fac..b906aa097 100644 --- a/src/editor/lsp/formatErrors.test.tsx +++ b/src/editor/lsp/formatErrors.test.tsx @@ -44,7 +44,7 @@ afterEach(() => { _resetI18nForTests(); }); -describe.each(["prettier", "oxfmt", "biome", "ruff"])("%s formatter errors", (name) => { +describe.each(["prettier", "oxfmt", "biome", "dprint", "ruff"])("%s formatter errors", (name) => { const tool = { type: "tool", tool: name, missing: false } as const; const display = ({ prettier: "Prettier", biome: "Biome", ruff: "Ruff" } as Record<string, string>)[name] ?? name; it("uses structured missing-tool information to request the shared install prompt", async () => { @@ -134,6 +134,7 @@ describe("Reformat with an external formatter", () => { ["code.reformatWithPrettier", "prettier"], ["code.reformatWithOxfmt", "oxfmt"], ["code.reformatWithBiome", "biome"], + ["code.reformatWithDprint", "dprint"], ["code.reformatWithRuff", "ruff"], ])("%s asks the backend for %s whatever the settings select", async (id, tool) => { vi.spyOn(lsp, "lspRequest").mockImplementation(async (request) => { diff --git a/src/editor/lsp/hover.ts b/src/editor/lsp/hover.ts index afeebb57a..5bb6725df 100644 --- a/src/editor/lsp/hover.ts +++ b/src/editor/lsp/hover.ts @@ -47,6 +47,7 @@ import { editorPrefs } from "@/platform/editorSettings"; import { CONTRIBUTED_HOVER, contributedAtAll, type ContributedHover } from "@/editor/api"; import { navigationModifierHeld, onNavigationModifier, pointerTarget } from "@/platform/navigationModifier"; import { languageSemantics } from "./semantic"; +import { cssVariableHover } from "./cssVariables"; import { tooltipBounds } from "@/editor/core/cm/setup"; let hoverRequest: RequestId | null = null; @@ -71,6 +72,9 @@ export async function requestHover(view: EditorView, pos: number): Promise<Hover contents: { kind: "markdown", value: construct.markdown }, range: { start: offsetToPos(view.state.doc, construct.from), end: offsetToPos(view.state.doc, construct.to) }, }; + // The server would describe the property the `var(--x)` is the value of, from this file only. + const variable = await cssVariableHover(view, pos); + if (variable) return variable; if (hoverRequest !== null && isTauri()) void commands.cancelRequest(hoverRequest); const id = (hoverRequest = nextRequestId()); try { diff --git a/src/editor/lsp/inlineCompletion.ts b/src/editor/lsp/inlineCompletion.ts index 54beafb13..0fe027bff 100644 --- a/src/editor/lsp/inlineCompletion.ts +++ b/src/editor/lsp/inlineCompletion.ts @@ -23,7 +23,7 @@ import { type RequestId, unavailableText, } from "@/platform/ipc"; -import { activeEditor } from "@/editor/api"; +import { activeEditor, focusedCellEditor } from "@/editor/api"; import { docOf, isUnavailable, lspRequest } from "./lsp"; import { offsetToPos, rangeToOffsets } from "./positions"; import { showHint } from "./hint"; @@ -288,7 +288,8 @@ const VISIBLE = `editorTextFocus && ${CONTEXT_KEY}`; function onView(run: (view: EditorView) => unknown): Action["run"] { return () => { - const view = activeEditor()?.view; + // A focused notebook cell editor is the editor (the notebook publishes the editor keys). + const view = focusedCellEditor() ?? activeEditor()?.view; if (view) void run(view); }; } diff --git a/src/editor/lsp/navigation.ts b/src/editor/lsp/navigation.ts index c4932ee3e..cddf0dd0e 100644 --- a/src/editor/lsp/navigation.ts +++ b/src/editor/lsp/navigation.ts @@ -95,6 +95,7 @@ import { dispatchMouseShortcut, shortcutLabel } from "@/platform/keymap"; import { isNavigationGesture, onNavigationModifier, navigationModifierHeld } from "@/platform/navigationModifier"; import { create } from "zustand"; import { tx } from "@/platform/i18n"; +import { cssVariableAt, STYLESHEETS } from "./cssVariables"; import { CONFIGURATION_NAVIGATION_MAX_AGE, configurationNavigationRevision, @@ -505,6 +506,12 @@ async function gotoResolved( return; } } + // `var(--x)`: the server only knows this stylesheet's declarations; list the project's. + if (declaration && STYLESHEETS.has(doc.language)) { + const line = view.state.doc.lineAt(offset); + if (cssVariableAt(line.text, offset - line.from) && (await gotoWebReference(view, doc, pos, offset, superseded))) + return; + } // Python: its servers have no type hierarchy and see one root, so the IDE's inheritance // graph answers implementations too (merged with the server's, not replacing them). const graphTargets = kind === "implementation" ? pythonImplementations(doc, pos) : null; diff --git a/src/editor/lsp/navigationCssVariable.test.ts b/src/editor/lsp/navigationCssVariable.test.ts new file mode 100644 index 000000000..36c83e90b --- /dev/null +++ b/src/editor/lsp/navigationCssVariable.test.ts @@ -0,0 +1,71 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import type { commands, Location } from "@/platform/ipc"; + +// `var(--x)`: the CSS server only knows the open stylesheet, so a name declared here and in a +// theme file would answer just the local one; the project index lists both. +const { lspGoto, webGoto, readManyFileLines } = vi.hoisted(() => ({ + lspGoto: vi.fn<typeof commands.lspGoto>(), + webGoto: vi.fn<typeof commands.webGoto>(), + readManyFileLines: vi.fn(async () => new Map<string, string[] | null>()), +})); +vi.mock("@/platform/ipc", async (orig) => { + const real = await orig<typeof import("@/platform/ipc")>(); + return { ...real, isTauri: () => true, commands: { ...real.commands, lspGoto, webGoto } }; +}); +vi.mock("./files", async (orig) => ({ ...(await orig<typeof import("./files")>()), readManyFileLines })); + +const { gotoTargets } = await import("./navigation"); +const { lspDoc } = await import("./lsp"); +const { closePopup, useLspPopup } = await import("./popupStore"); +const { provideEditorService } = await import("@/workbench/contributions"); +const openFile = vi.fn(async () => {}); +provideEditorService({ openFile } as never); + +const at = (path: string, line: number): Location => ({ + path, + range: { start: { line, col: 2 }, end: { line, col: 6 } }, + uri: null, +}); +const text = ":root { --bg: #fff; }\n.a { color: var(--bg); }\n"; + +let view: EditorView; +beforeEach(() => { + vi.clearAllMocks(); + lspGoto.mockResolvedValue({ status: "ok", data: [at("/p/a.css", 0)] }); + view = new EditorView({ + state: EditorState.create({ + doc: text, + extensions: [lspDoc.of({ doc: 1, path: "/p/a.css", language: "css", uiMode: "CSS", readOnly: false })], + }), + parent: document.body, + }); + view.dispatch({ selection: { anchor: text.lastIndexOf("--bg") + 2 } }); +}); +afterEach(() => { + closePopup(); + view.destroy(); + document.body.replaceChildren(); +}); + +describe("go to declaration on var(--x)", () => { + it("lists the declarations in every file, not only the server's local one", async () => { + const targets = [at("/p/a.css", 0), at("/p/theme/dark.css", 4)]; + webGoto.mockResolvedValue({ + status: "ok", + data: { reference: { kind: "cssVariable", name: "--bg", range: at("/p/a.css", 1).range }, targets }, + }); + await gotoTargets(view, "declaration"); + expect(webGoto).toHaveBeenCalledWith(1, { line: 1, col: 18 }); + expect(lspGoto).not.toHaveBeenCalled(); + const popup = useLspPopup.getState().popup; + expect(popup?.kind).toBe("list"); + expect(popup && "title" in popup ? popup.title : null).toBe("Choose Declaration of '--bg' (2 found)"); + expect(popup && "items" in popup ? popup.items.map((i) => i.target) : null).toEqual([ + expect.objectContaining({ path: expect.stringMatching(/a\.css:1$/) }), + expect.objectContaining({ path: expect.stringMatching(/dark\.css:5$/) }), + ]); + expect(openFile).not.toHaveBeenCalled(); + }); +}); diff --git a/src/editor/lsp/theme.ts b/src/editor/lsp/theme.ts index 1d50fb155..5e0e43c45 100644 --- a/src/editor/lsp/theme.ts +++ b/src/editor/lsp/theme.ts @@ -189,6 +189,16 @@ export const lspTheme = EditorView.theme({ alignItems: "center", justifyContent: "center", }, + // A color custom property's value (`var(--…)` completion), sized like the gutter's color swatch. + ".cm-lsp-completion .cm-lsp-swatch::before": { + content: '""', + width: "12px", + height: "12px", + boxSizing: "border-box", + border: "1px solid var(--border-strong)", + borderRadius: "var(--radius-small)", + background: "var(--swatch)", + }, ".cm-lsp-completion .cm-completionLabel": { flex: "none", maxWidth: diff --git a/src/editor/lsp/variableNames.test.ts b/src/editor/lsp/variableNames.test.ts new file mode 100644 index 000000000..91d122200 --- /dev/null +++ b/src/editor/lsp/variableNames.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "vitest"; +import { declarationAt, namesForType, pluralize } from "./variableNames"; + +const names = (before: string) => { + const found = declarationAt(before); + return found ? namesForType(found.type) : null; +}; + +describe("variable names by type (IDEA)", () => { + it("suggests the type's name and its shorter endings", () => { + expect(names(" private IMesCheckStandardService c")).toEqual([ + "iMesCheckStandardService", + "mesCheckStandardService", + "checkStandardService", + "standardService", + "service", + ]); + expect(names(" MesProductPlan p")).toEqual(["mesProductPlan", "productPlan", "plan"]); + expect(names(" UserServiceImpl ")).toEqual(["userService", "service"]); + expect(names(" HttpURLConnection c")).toEqual(["httpURLConnection", "urlConnection", "connection"]); + }); + + it("names collections, arrays, optionals and generic types by their contents", () => { + expect(names("List<MesProductCheck> l")).toEqual([ + "mesProductChecks", + "productChecks", + "checks", + "mesProductCheckList", + "productCheckList", + "checkList", + "list", + ]); + expect(names("Order[] ")).toEqual(["orders"]); + expect(names("Optional<User> ")).toEqual(["user", "optionalUser", "userOptional", "optional"]); + expect(names("Map<String, Order> ")).toEqual(["stringOrderMap", "orderMap", "map"]); + expect(pluralize("Category")).toBe("Categories"); + expect(pluralize("Box")).toBe("Boxes"); + }); + + it("gives locals and parameters IDEA's short names", () => { + expect(names(" String ")).toEqual(["s", "string"]); + expect(names(" private String ")).toEqual(["string"]); + expect(names(" int ")).toEqual(["i"]); + expect(names(" } catch (IOException ")).toEqual(["e", "ioException", "exception"]); + expect(names("void run(Order o")).toEqual(["order"]); + }); + + it("is quiet where no name is declared", () => { + expect(declarationAt(" return Foo")).toBeNull(); + expect(declarationAt(" return value ")).toBeNull(); + expect(declarationAt("class Foo ")).toBeNull(); + expect(declarationAt(" throw new Error ")).toBeNull(); + expect(declarationAt("@Autowired ")).toBeNull(); + expect(declarationAt(" private c")).toBeNull(); + expect(declarationAt(" var x")).toBeNull(); + expect(declarationAt(" foo.bar")).toBeNull(); + expect(declarationAt(" Foo f")).toEqual({ type: expect.objectContaining({ name: "Foo" }), typed: "f" }); + }); +}); diff --git a/src/editor/lsp/variableNames.ts b/src/editor/lsp/variableNames.ts new file mode 100644 index 000000000..3b1c7876b --- /dev/null +++ b/src/editor/lsp/variableNames.ts @@ -0,0 +1,211 @@ +/** + * Variable names by type, as IDEA's JavaCodeStyleManager suggests them: typing the name of a + * Java declaration (`private IUserService |`, `List<Order> |`, `catch (IOException |`) lists + * `userService`, `service`, `orders`, `e`… The language server offers nothing there. + */ +import type { Completion, CompletionContext, CompletionResult } from "@codemirror/autocomplete"; +import { syntaxTree } from "@codemirror/language"; +import { lspDoc } from "./lsp"; + +/** The declared type at a name being typed: `Map<String, Order>[]` → `Map`, `[String, Order]`, array. */ +export interface DeclaredType { + name: string; + args: string[]; + array: boolean; + kind: "field" | "parameter" | "local"; +} + +const PRIMITIVES = new Set(["int", "long", "short", "byte", "char", "boolean", "float", "double"]); + +/** Words before a type that make what follows something other than a declaration's name. */ +const NOT_A_DECLARATION = new Set([ + "new", + "class", + "interface", + "enum", + "record", + "extends", + "implements", + "permits", + "throws", + "import", + "package", + "return", + "throw", + "yield", + "assert", + "goto", + "var", + "this", + "super", +]); + +const FIELD_MODIFIERS = /\b(?:private|protected|public|static|volatile|transient)\b/; + +const DECLARATION = + /(^|[\s(,;{}])((?:[A-Za-z_$][\w$]*\.)*[A-Za-z_$][\w$]*)\s*(<[^;(){}=]*>)?((?:\s*\[\s*\])*)\s+([A-Za-z_$][\w$]*)?$/; + +/** + * The type whose variable's name ends `before` (the line up to the caret), with the name typed so + * far; null when the caret isn't at a declared name. + */ +export function declarationAt(before: string): { type: DeclaredType; typed: string } | null { + const m = DECLARATION.exec(before); + if (!m) return null; + const qualified = m[2]!; + const name = qualified.slice(qualified.lastIndexOf(".") + 1); + if (!PRIMITIVES.has(name) && !/^[A-Z]/.test(name)) return null; + const head = before.slice(0, m.index + m[1]!.length); + const previous = /([A-Za-z_@][\w]*)\s*$/.exec(head)?.[1]; + if (previous && (NOT_A_DECLARATION.has(previous) || previous.startsWith("@"))) return null; + if (/@\s*$/.test(head)) return null; + const params = /[(,]\s*$/.test(head) || /\(\s*(?:final\s+)?$/.test(head) || /\bcatch\s*\(\s*$/.test(head); + const kind = params ? "parameter" : FIELD_MODIFIERS.test(head) ? "field" : "local"; + return { + type: { name, args: typeArguments(m[3] ?? ""), array: !!m[4]?.trim(), kind }, + typed: m[5] ?? "", + }; +} + +/** The top-level type arguments' simple names (`<String, List<Order>>` → `String`, `List`); `?` and bounds skipped. */ +function typeArguments(generic: string): string[] { + const inner = generic.slice(1, -1); + const out: string[] = []; + let depth = 0; + let current = ""; + for (const ch of inner) { + if (ch === "<") depth++; + if (ch === ">") depth--; + if (ch === "," && depth === 0) { + out.push(current); + current = ""; + } else if (depth === 0 && ch !== ">") current += ch; + } + out.push(current); + return out + .map((a) => a.trim()) + .filter((a) => /^[A-Za-z_$][\w$.]*$/.test(a)) + .map((a) => a.slice(a.lastIndexOf(".") + 1)); +} + +/** IDEA's NameUtilCore.nameToWordList: `IUserURLService` → `I`, `User`, `URL`, `Service`. */ +function words(name: string): string[] { + return name.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z0-9]+|[A-Z]/g) ?? []; +} + +/** StringUtil.pluralize for the usual cases. */ +export function pluralize(word: string): string { + if (/(?:s|x|z|ch|sh)$/i.test(word)) return `${word}es`; + if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`; + return `${word}s`; +} + +/** `UserService` → `userService`, `service` (longest first); an all-caps first word goes lower case. */ +function suffixNames(name: string): string[] { + const ws = words(name); + const out: string[] = []; + for (let i = 0; i < ws.length; i++) { + const first = ws[i]!; + if (!/^[A-Za-z]/.test(first)) continue; + const head = first === first.toUpperCase() ? first.toLowerCase() : first[0]!.toLowerCase() + first.slice(1); + out.push(head + ws.slice(i + 1).join("")); + } + return out; +} + +const SHORT_NAMES: Record<string, string> = { + int: "i", + boolean: "b", + byte: "b", + char: "c", + long: "l", + short: "i", + double: "v", + float: "v", + Integer: "i", + Short: "i", + Long: "l", + Boolean: "b", + Byte: "b", + Character: "c", + Double: "v", + Float: "v", + Object: "o", + String: "s", +}; + +const ITERABLES = new Set([ + "Iterable", + "Collection", + "List", + "ArrayList", + "LinkedList", + "Set", + "HashSet", + "LinkedHashSet", + "TreeSet", + "SortedSet", + "NavigableSet", + "Queue", + "Deque", + "ArrayDeque", + "PriorityQueue", + "Stack", + "Vector", + "CopyOnWriteArrayList", +]); + +/** `UserServiceImpl` names a `userService`, as in IDEA. */ +const normalize = (name: string) => (name.length > 4 && name.endsWith("Impl") ? name.slice(0, -4) : name); + +const JAVA_KEYWORDS = new Set( + ( + "abstract assert boolean break byte case catch char class const continue default do double else enum extends " + + "final finally float for goto if implements import instanceof int interface long native new package private " + + "protected public return short static strictfp super switch synchronized this throw throws transient try void " + + "volatile while true false null var record yield" + ).split(" "), +); + +/** The names IDEA suggests for a variable of `type`, best first. */ +export function namesForType(type: DeclaredType): string[] { + const base: string[] = []; + const short = type.kind === "field" ? undefined : SHORT_NAMES[type.name]; + if (short) base.push(type.array ? pluralize(short) : short); + const name = normalize(type.name); + if (type.args.length === 1 && ITERABLES.has(type.name)) base.push(pluralize(normalize(type.args[0]!))); + if (type.args.length === 1 && type.name === "Optional") { + const content = normalize(type.args[0]!); + base.push(content, `optional${content}`); + } + if (type.args.length) base.push(type.args.map(normalize).join("") + name); + const own = type.array ? pluralize(name) : name; + if (type.kind === "parameter" && type.name.endsWith("Exception")) base.push("e"); + base.push(own); + if (own.length > "Entity".length && own.endsWith("Entity")) base.push(own.slice(0, -"Entity".length)); + const out: string[] = []; + for (const b of base) { + for (const n of PRIMITIVES.has(b) || b.length === 1 ? [b] : suffixNames(b)) { + if (!out.includes(n) && !JAVA_KEYWORDS.has(n) && /^[A-Za-z_$][\w$]*$/.test(n)) out.push(n); + } + } + return out; +} + +/** The declaration under the caret in a Java file (not in a comment or string), or null. */ +export function javaDeclarationAt(ctx: CompletionContext): { type: DeclaredType; typed: string } | null { + if (ctx.state.facet(lspDoc)?.language !== "java") return null; + const node = syntaxTree(ctx.state).resolveInner(ctx.pos, -1); + if (/Comment|String|TextBlock/.test(node.name)) return null; + const line = ctx.state.doc.lineAt(ctx.pos); + return declarationAt(line.text.slice(0, ctx.pos - line.from)); +} + +/** Completion source: the type's names at a Java declaration's name. */ +export function variableNameSource(ctx: CompletionContext): CompletionResult | null { + const found = javaDeclarationAt(ctx); + if (!found) return null; + const names = namesForType(found.type); + const options: Completion[] = names.map((label, i) => ({ label, type: "variable", boost: 50 - i })); + return options.length ? { from: ctx.pos - found.typed.length, options, validFor: /^[\w$]*$/ } : null; +} diff --git a/src/editor/refactor/catalog.ts b/src/editor/refactor/catalog.ts index f26633559..ed48b083c 100644 --- a/src/editor/refactor/catalog.ts +++ b/src/editor/refactor/catalog.ts @@ -2,8 +2,8 @@ * IDEA's refactorings and how language-server code actions map onto them: * `refactor.extract.*` → Extract Method / Introduce Variable…, `refactor.inline*` * → Inline, `refactor.move*` → Move, signature rewrites → Change Signature. - * Pull Members Up / Push Members Down come from the Java extension, Extract Interface from jdtls - * requests, not code actions. + * Pull Members Up / Push Members Down come from the Java extension, Java's Extract Interface from + * jdtls requests, not code actions; tsserver's "Extract to interface / type alias" are code actions. * Pure; used by Refactor This (⌃T) and the Refactor menu actions. */ import type { CodeAction } from "@/bindings"; @@ -19,6 +19,7 @@ export type RefactoringId = | "extractField" | "extractParameter" | "extractInterface" + | "extractTypeAlias" | "inline" | "pullMembersUp" | "pushMembersDown"; @@ -104,8 +105,17 @@ export const REFACTORINGS: readonly Refactoring[] = [ action: "refactor.extractInterface", label: "Extract Interface…", section: EXTRACT, - kind: null, - reason: () => "Caret should be inside a class", + // Java runs it through the dialog; TypeScript through tsserver's "Extract to interface". + kind: "refactor.extract", + reason: () => "Selected block should represent an object type", + }, + { + id: "extractTypeAlias", + action: "refactor.extractTypeAlias", + label: "Extract Type Alias…", + section: EXTRACT, + kind: "refactor.extract", + reason: () => "Selected block should represent a type", }, { id: "inline", @@ -169,6 +179,9 @@ export function classifyAction(action: Pick<CodeAction, "kind" | "title">): Refa if (kindIs(kind, "refactor.extract") || (generic && /^(extract|introduce)\b/i.test(title))) { const sub = kind.slice("refactor.extract".length); const is = (re: RegExp) => re.test(sub) || re.test(title); + // tsserver ("Extract to typedef" is its JSDoc form in JavaScript). + if (/^extract to (type alias|typedef)$/i.test(title)) return "extractTypeAlias"; + if (/^extract to interface$/i.test(title)) return "extractInterface"; if ( /^(extract|introduce)( (in)?to)?( an?)? (type\b|typedef|interface|struct|enum|trait|superclass|module)/i.test( title, diff --git a/src/editor/refactor/refactorThis.test.ts b/src/editor/refactor/refactorThis.test.ts index 0c68d19fb..576a93940 100644 --- a/src/editor/refactor/refactorThis.test.ts +++ b/src/editor/refactor/refactorThis.test.ts @@ -145,11 +145,15 @@ describe("catalog", () => { expect(c("Change signature", "refactor.changeSignature")).toBe("changeSignature"); expect(c("Convert parameters to destructured object", "refactor.rewrite.parameters.toDestructured")).toBeNull(); expect(c("Extract type alias", "refactor.extract.type")).toBeNull(); + expect(c("Extract to type alias", "refactor.extract.type")).toBe("extractTypeAlias"); + expect(c("Extract to typedef", "refactor.extract.typedef")).toBe("extractTypeAlias"); + expect(c("Extract to interface", "refactor.extract.interface")).toBe("extractInterface"); + expect(c("Extract to interface", "refactor")).toBe("extractInterface"); expect(c("Remove unused", "quickfix")).toBeNull(); // typescript-language-server reports plain `refactor` for everything. expect(c("Extract to inner function in function 'formatMoney'", "refactor")).toBe("extractMethod"); expect(c("Extract to constant in enclosing scope", "refactor")).toBe("extractVariable"); - expect(c("Extract to type alias", "refactor")).toBeNull(); + expect(c("Extract to type alias", "refactor")).toBe("extractTypeAlias"); expect(c("Extract type as type alias", "refactor.extract")).toBeNull(); expect(c("Extract struct from enum variant", "refactor.extract")).toBeNull(); expect(c("Move to a new file", "refactor")).toBe("move"); @@ -418,6 +422,67 @@ describe("Refactor menu actions", () => { expect(temporaryHighlights(v)).toHaveLength(2); }); + it("run tsserver's Extract to type alias / interface in TypeScript and rename the new type", async () => { + const text = "function f(p: { a: string }) {}"; + const literal = "{ a: string }"; + const v = editor(text, "typescript"); + v.dispatch({ selection: { anchor: text.indexOf(literal), head: text.indexOf(literal) + literal.length } }); + query = answer([ + action("Extract to interface", "refactor.extract.interface"), + action("Extract to type alias", "refactor.extract.type"), + ]); + onApply = () => + v.dispatch({ + changes: [ + { from: 0, insert: "type NewType = { a: string };\n\n" }, + { from: text.indexOf(literal), to: text.indexOf(literal) + literal.length, insert: "NewType" }, + ], + }); + await runRefactoring(v, "extractTypeAlias"); + expect(lspCodeActionQuery.mock.calls[0]![3]).toEqual(["refactor"]); + expect(lspResolveCodeAction.mock.calls[0]![1].title).toBe("Extract to type alias"); + await vi.waitFor(() => expect(inplaceSession(v.state)).not.toBeNull()); + expect(inplaceSession(v.state)!.oldName).toBe("NewType"); + + lspResolveCodeAction.mockClear(); + onApply = null; + const w = editor(text, "typescriptreact"); + w.dispatch({ selection: { anchor: text.indexOf(literal), head: text.indexOf(literal) + literal.length } }); + await runRefactoring(w, "extractInterface"); + expect(lspResolveCodeAction.mock.calls[0]![1].title).toBe("Extract to interface"); + expect(startExtractInterface).not.toHaveBeenCalled(); + }); + + it("say why when tsserver offers no type extraction, and keep Extract Interface on Java's dialog", async () => { + query = answer([action("Extract to constant in enclosing scope", "refactor.extract.constant")]); + const ts = editor("const x = 1;", "typescript"); + await runRefactoring(ts, "extractTypeAlias"); + expect(showHint).toHaveBeenLastCalledWith(ts, "Cannot perform refactoring. Selected block should represent a type"); + await runRefactoring(ts, "extractInterface"); + expect(showHint).toHaveBeenLastCalledWith( + ts, + "Cannot perform refactoring. Selected block should represent an object type", + ); + expect(lspExecuteCodeAction).not.toHaveBeenCalled(); + + const rs = editor(); + await runRefactoring(rs, "extractTypeAlias"); + expect(showHint).toHaveBeenLastCalledWith( + rs, + "Cannot perform refactoring. Extract Type Alias is not supported for Rust", + ); + await runRefactoring(rs, "extractInterface"); + expect(showHint).toHaveBeenLastCalledWith( + rs, + "Cannot perform refactoring. Extract Interface is not supported for Rust", + ); + + lspCodeActionQuery.mockClear(); + await runRefactoring(editor("class A {}", "java"), "extractInterface"); + expect(startExtractInterface).toHaveBeenCalledOnce(); + expect(lspCodeActionQuery).not.toHaveBeenCalled(); + }); + it("rename the introduced name in place after the server's edit", async () => { const text = "fn main() { let total = price * 2; }"; const v = editor(text); diff --git a/src/editor/refactor/refactorThis.ts b/src/editor/refactor/refactorThis.ts index 39de036fe..487521f26 100644 --- a/src/editor/refactor/refactorThis.ts +++ b/src/editor/refactor/refactorThis.ts @@ -59,6 +59,9 @@ const REFACTORING_SERVERS: Readonly<Record<string, { server: string; ids: Readon }, }; +/** Languages where tsserver offers "Extract to interface" and "Extract to type alias" (typedef in JavaScript). */ +const TYPE_EXTRACT_LANGUAGES = new Set(["typescript", "typescriptreact", "javascript", "javascriptreact"]); + /** Outcome of the server query: its answer, or why there is none. */ export type ServerAnswer = | { status: "ok"; query: CodeActionQuery } @@ -192,9 +195,20 @@ export async function runRefactoring(view: EditorView, id: RefactoringId): Promi await startChangeSignature(view); return; } - if (id === "extractInterface") { - if (EXTRACT_INTERFACE_LANGUAGES.has(ctx.language)) await startExtractInterface(view); - else showHint(view, cannotPerform(`Extract Interface is not supported for ${await languageName(ctx.language)}`)); + if (id === "extractInterface" && EXTRACT_INTERFACE_LANGUAGES.has(ctx.language)) { + await startExtractInterface(view); + return; + } + if ((id === "extractInterface" || id === "extractTypeAlias") && !TYPE_EXTRACT_LANGUAGES.has(ctx.language)) { + const lang = await languageName(ctx.language); + showHint( + view, + cannotPerform( + id === "extractInterface" + ? `Extract Interface is not supported for ${lang}` + : `Extract Type Alias is not supported for ${lang}`, + ), + ); return; } // IDEA picks the expression first (and the server then extracts exactly that one). diff --git a/src/editor/refactor/serverIntroduce.test.ts b/src/editor/refactor/serverIntroduce.test.ts index d2187cb72..1b1472a2e 100644 --- a/src/editor/refactor/serverIntroduce.test.ts +++ b/src/editor/refactor/serverIntroduce.test.ts @@ -45,6 +45,23 @@ describe("introducedName", () => { expect(introducedName(before, after)?.name).toBe("fun_name"); }); + it("finds tsserver's extracted type alias and interface", () => { + const before = "function f(p: { a: string; b: number }) {}\n"; + const alias = "type NewType = { a: string; b: number };\n\nfunction f(p: NewType) {}\n"; + expect(spansText(alias, introducedName(before, alias)!.spans)).toEqual(["NewType", "NewType"]); + const iface = "interface NewType {\n a: string;\n b: number;\n}\n\nfunction f(p: NewType) {}\n"; + expect(introducedName(before, iface)?.name).toBe("NewType"); + }); + + it("finds tsserver's unique NewType_1 when NewType is taken", () => { + // typescript's Extract to typedef output, verbatim: `typedef` is inserted twice too. + const before = + "/** @typedef {object} NewType */\n\n/** @param {{ a: number, b: number, c: number }} p */\nfunction f(p) {}\n"; + const after = + "/**\n* @typedef {{a: number;b: number;c: number;}} NewType_1\n*/\n\n/** @typedef {object} NewType */\n\n/** @param {NewType_1} p */\nfunction f(p) {}\n"; + expect(spansText(after, introducedName(before, after)!.spans)).toEqual(["NewType_1", "NewType_1"]); + }); + it("is null without a new name used twice", () => { expect(introducedName("a + b", "(a + b)")).toBeNull(); expect(introducedName("x", "x")).toBeNull(); diff --git a/src/editor/refactor/serverIntroduce.ts b/src/editor/refactor/serverIntroduce.ts index 74fb0ca5b..c01863329 100644 --- a/src/editor/refactor/serverIntroduce.ts +++ b/src/editor/refactor/serverIntroduce.ts @@ -40,7 +40,12 @@ export const EXPRESSION_REFACTORINGS: ReadonlySet<RefactoringId> = new Set([ ]); /** Refactorings whose result is a new name renamed in place afterwards. */ -const NAMING_REFACTORINGS: ReadonlySet<RefactoringId> = new Set([...EXPRESSION_REFACTORINGS, "extractMethod"]); +const NAMING_REFACTORINGS: ReadonlySet<RefactoringId> = new Set([ + ...EXPRESSION_REFACTORINGS, + "extractMethod", + "extractInterface", + "extractTypeAlias", +]); export function introducesName(id: RefactoringId | null): boolean { return !!id && NAMING_REFACTORINGS.has(id); @@ -184,7 +189,8 @@ function insertedTokens(before: Token[], after: Token[]): Token[] { } /** Names servers give new declarations before the user names them. */ -const SERVER_DEFAULT = /^(new[A-Z_]\w*|newLocal\w*|var_name\d*|fun_name\d*|extracted\w*|new_\w+|value\d*)$/; +const SERVER_DEFAULT = + /^(new[A-Z_]\w*|NewType(?:_\d+)?|newLocal\w*|var_name\d*|fun_name\d*|extracted\w*|new_\w+|value\d*)$/; /** * The name a refactoring introduced, and every place the edit wrote it, from diff --git a/src/features/agents/AgentList.tsx b/src/features/agents/AgentList.tsx index d6bb14cde..d5d2cc979 100644 --- a/src/features/agents/AgentList.tsx +++ b/src/features/agents/AgentList.tsx @@ -631,27 +631,34 @@ function Details({ /** Splits arguments on whitespace, honoring single and double quotes. */ function parseArgs(text: string): string[] { const out: string[] = []; - let current = ""; + let current: string | null = null; let quote: '"' | "'" | null = null; for (const ch of text.trim()) { if (quote) { if (ch === quote) quote = null; else current += ch; } else if (ch === '"' || ch === "'") { + current ??= ""; quote = ch; } else if (/\s/.test(ch)) { - if (current) { + if (current !== null) { out.push(current); - current = ""; + current = null; } } else { - current += ch; + current = (current ?? "") + ch; } } - if (current) out.push(current); + if (quote) throw new Error(tx("Close the quoted argument before applying.")); + if (current !== null) out.push(current); return out; } +/** Quotes one argv token at a time; `parseArgs` can read the result without shell expansion. */ +function formatArgs(args: readonly string[]): string { + return args.map((arg) => (/^[\w./:=@%+,-]+$/.test(arg) ? arg : `'${arg.replaceAll("'", `'"'"'`)}'`)).join(" "); +} + function CustomAgentModal({ backend, onClose, @@ -826,6 +833,14 @@ function ProviderSettings({ onChanged?.(); return command === agent.defaultProgram ? "" : (command ?? ""); }); + const argsBase = formatArgs(agent.additionalArgs ?? []); + const args = form.useExternal(`agents.${agent.id}.additionalArgs`, argsBase, async (draft) => { + const parsed = parseArgs(draft); + await backend.setAdditionalArgs(agent.id, parsed); + await refresh(); + onChanged?.(); + return formatArgs(parsed); + }); const accountBase = agent.env[COPILOT_GITHUB_ACCOUNT_ENV] ?? ""; const account = form.useExternal(`agents.${agent.id}.githubAccount`, accountBase, async (draft) => { const next = { ...agent.env }; @@ -851,9 +866,14 @@ function ProviderSettings({ // An edit can have been staged by a previous page instance. Its Apply callback // refreshes that instance; the mounted one follows the newly applied value too. useEffect(() => { - if (!saving && current !== base) void refresh().catch((e: unknown) => setError(errorText(e))); - }, [base, current, saving, refresh]); - const launch = [agent.defaultProgram, ...agent.defaultArgs].join(" "); + if (!saving && (current !== base || args.current !== argsBase)) { + void refresh().catch((e: unknown) => setError(errorText(e))); + } + }, [args.current, argsBase, base, current, saving, refresh]); + const launch = + agent.additionalArgs == null + ? [agent.defaultProgram, ...agent.defaultArgs].join(" ") + : formatArgs([agent.program, ...agent.args]); const envEditable = agent.commandReadOnlyReason !== "registry" && agent.commandReadOnlyReason !== "customAgent"; return ( <> @@ -941,6 +961,31 @@ function ProviderSettings({ )} </p> )} + {agent.additionalArgs != null && ( + <Row + label={<T>Additional arguments</T>} + htmlFor={`agent-args-${agent.id}`} + hint={<T>Appended to the launch command. Quote values containing spaces.</T>} + > + <div className={styles.field}> + <Input + id={`agent-args-${agent.id}`} + mono + value={args.value} + disabled={args.saving} + onChange={(e) => args.set(e.target.value)} + /> + {args.value && ( + <IconButton + icon="undo" + title="Reset additional arguments" + disabled={args.saving} + onClick={() => args.set("")} + /> + )} + </div> + </Row> + )} {envEditable && ( <Row label={<T>Environment variables</T>} diff --git a/src/features/agents/AgentsView.tsx b/src/features/agents/AgentsView.tsx index 786124c12..5ef61883d 100644 --- a/src/features/agents/AgentsView.tsx +++ b/src/features/agents/AgentsView.tsx @@ -42,6 +42,7 @@ import { } from "./organize"; import { externalKey, + forkExternalSession, importExternalSession, moveTasksToGroup, moveTasksToStatusGroup, @@ -718,6 +719,21 @@ export function AgentsView() { > <T>Import</T> </button> + <button + type="button" + className={styles.link} + disabled={importing.has(key)} + title={tx("Fork into a new task")} + onClick={() => + void forkExternalSession( + s.provider, + s.sessionId, + s.cwd ?? useProject.getState().project?.root ?? "", + ).catch(() => {}) + } + > + <T>Fork</T> + </button> </div> ); })} diff --git a/src/features/agents/Composer.tsx b/src/features/agents/Composer.tsx index 1a7dd8ef8..900d1b17f 100644 --- a/src/features/agents/Composer.tsx +++ b/src/features/agents/Composer.tsx @@ -24,7 +24,9 @@ import { registerKeyClaim } from "@/platform/keymap"; import { isVirtualUri } from "@/platform/virtualDocs"; import { copySourceOf } from "@/platform/clipboardSource"; import { + EDITOR_TAB_MIME, getAgentContextSources, + maybeEditorService, notifications, OWNS_FILE_DROP, type AgentContextSource, @@ -100,6 +102,18 @@ type Item = const isSection = (item: Item) => item.kind === "section"; +/** The file of an editor tab drag payload (`{paneId, tabId}`), null for virtual and non-file tabs. */ +const tabFilePath = (payload: string): string | null => { + try { + const p = JSON.parse(payload) as { paneId?: unknown; tabId?: unknown }; + if (typeof p.paneId !== "string" || typeof p.tabId !== "string") return null; + const input = maybeEditorService()?.tabInput?.(p.paneId, p.tabId); + return input?.kind === "file" && input.path && !isVirtualUri(input.path) ? input.path : null; + } catch { + return null; + } +}; + const SECTION_TITLES: Record<Section, string> = { command: "Commands", skill: "Skills", @@ -941,17 +955,21 @@ export function Composer(props: ComposerProps) { }; }, [addPaths, addImages]); - // Files and folders dragged from the Project view: the same `@` references. + // Files and folders dragged from the Project view, and file tabs dragged from the editor: + // the same `@` references. useEffect(() => { const el = boxRef.current; if (!el) return; return registerDropTarget(el, { - accepts: (type) => type === FILES_DRAG, + accepts: (type, data) => type === FILES_DRAG || (type === EDITOR_TAB_MIME && !!tabFilePath(data.payload)), over: () => setFileOver(true), leave: () => setFileOver(false), drop: (data) => { setFileOver(false); - addPaths(data.payload.split("\n").filter(Boolean)); + if (data.type === EDITOR_TAB_MIME) { + const path = tabFilePath(data.payload); + if (path) addPaths([path]); + } else addPaths(data.payload.split("\n").filter(Boolean)); }, }); }, [addPaths]); diff --git a/src/features/agents/HomeEditor.test.tsx b/src/features/agents/HomeEditor.test.tsx index afedae60c..d6aae830d 100644 --- a/src/features/agents/HomeEditor.test.tsx +++ b/src/features/agents/HomeEditor.test.tsx @@ -106,6 +106,67 @@ async function chooseEffort(effort: string) { fireEvent.click(within(list).getByRole("option", { name: effort })); } +function codexWithFast(current = "false") { + const fast = { ...option("service_tier", "model_config", ["false", "true"], current), name: "Fast" }; + const codex = { + ...backend.providers[0]!, + id: "codex", + name: "Codex", + config: [option("model", "model", ["big", "small", "plain"], "big"), fast], + thoughtLevels: { big: [fast], small: [{ ...fast, current: "false" }], plain: [] }, + }; + backend.providers = [codex]; + useAgents.setState({ providers: [codex], draft: savedDraft({ provider: "codex", config: {} }) }); +} + +it.each(["false", "true"])("leaves an untouched Codex Fast default (%s) to the runtime", async (current) => { + codexWithFast(current); + render(<HomeEditor />); + fireEvent.click(settingsButton()); + expect(screen.getByRole("switch", { name: "Fast" })).toHaveAttribute("aria-checked", current); + fireEvent.keyDown(document, { key: "Escape" }); + fireEvent.click(screen.getByRole("button", { name: "Start" })); + await waitFor(() => expect(backend.create).toHaveBeenCalled()); + expect(backend.create.mock.calls[0]![0].config).toEqual([{ id: "model", value: "big" }]); +}); + +it.each(["true", "false"])("sends an explicit Codex Fast selection (%s) before the first prompt", async (value) => { + codexWithFast(); + render(<HomeEditor />); + fireEvent.click(settingsButton()); + fireEvent.click(screen.getByRole("switch", { name: "Fast" })); + if (value === "false") fireEvent.click(screen.getByRole("switch", { name: "Fast" })); + expect(useAgents.getState().draft.thoughtLevels?.big?.service_tier).toBe(value); + fireEvent.keyDown(document, { key: "Escape" }); + fireEvent.click(screen.getByRole("button", { name: "Start" })); + await waitFor(() => expect(backend.create).toHaveBeenCalled()); + expect(backend.create.mock.calls[0]![0].config).toEqual([ + { id: "model", value: "big" }, + { id: "service_tier", value }, + ]); +}); + +it("keeps Codex Fast choices per model and omits them for models without Fast", async () => { + codexWithFast(); + render(<HomeEditor />); + fireEvent.click(settingsButton()); + fireEvent.click(screen.getByRole("switch", { name: "Fast" })); + fireEvent.keyDown(document, { key: "Escape" }); + await chooseModel("small"); + fireEvent.click(settingsButton()); + expect(screen.getByRole("switch", { name: "Fast" })).toHaveAttribute("aria-checked", "false"); + fireEvent.keyDown(document, { key: "Escape" }); + await chooseModel("big"); + fireEvent.click(settingsButton()); + expect(screen.getByRole("switch", { name: "Fast" })).toHaveAttribute("aria-checked", "true"); + fireEvent.keyDown(document, { key: "Escape" }); + await chooseModel("plain"); + expect(screen.queryByRole("button", { name: /^Model settings:/ })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Start" })); + await waitFor(() => expect(backend.create).toHaveBeenCalled()); + expect(backend.create.mock.calls[0]![0].config).toEqual([{ id: "model", value: "plain" }]); +}); + it("switches model-specific levels and restores each draft effort before starting", async () => { render(<HomeEditor />); expect(modelButton()).toHaveTextContent("big"); diff --git a/src/features/agents/ImportSessionsDialog.tsx b/src/features/agents/ImportSessionsDialog.tsx index 278c0f3d9..3ac0684df 100644 --- a/src/features/agents/ImportSessionsDialog.tsx +++ b/src/features/agents/ImportSessionsDialog.tsx @@ -6,7 +6,14 @@ import { hasPrimaryModifier } from "@/platform/keymap"; import { relativePath, useProject } from "@/platform/project"; import { useTx } from "@/platform/i18n"; import { age, providerIcon } from "./model"; -import { externalKey, hideImportSessions, importExternalSessions, refreshExternalSessions, useAgents } from "./store"; +import { + externalKey, + forkExternalSessions, + hideImportSessions, + importExternalSessions, + refreshExternalSessions, + useAgents, +} from "./store"; import styles from "./Agents.module.css"; /** The backend lists at most this many sessions, newest first. */ @@ -62,7 +69,7 @@ function ImportSessionsDialog() { const [query, setQuery] = useState(""); // By key, so a filter or rescan never moves the selection onto another session. const [sel, setSel] = useState<Selection>({ leadKey: null, anchorKey: null, keys: null }); - const [progress, setProgress] = useState<{ done: number; total: number } | null>(null); + const [progress, setProgress] = useState<{ done: number; total: number; fork?: boolean } | null>(null); // The batch's rows, listed while it imports (they leave `external` one by one). const [frozen, setFrozen] = useState<Row[] | null>(null); const abort = useRef<AbortController | null>(null); @@ -112,25 +119,36 @@ function ImportSessionsDialog() { keys: new Set(view.map((r) => r.key)), }); }; - const importChosen = () => { + const runChosen = (fork: boolean) => { if (busy || !shown || !chosen.length) return; - const batch = chosen.map((r) => ({ provider: r.provider, sessionId: r.sessionId, title: r.title })); setFrozen(chosen); setSel({ leadKey: chosen[0]!.key, anchorKey: chosen[0]!.key, keys: new Set(chosen.map((r) => r.key)) }); - setProgress({ done: 0, total: batch.length }); + const total = chosen.length; + setProgress({ done: 0, total, fork }); const controller = new AbortController(); abort.current = controller; - void importExternalSessions( - batch, - (done) => live.current && setProgress({ done, total: batch.length }), - controller.signal, - ).finally(() => live.current && hideImportSessions()); + const progress = (done: number) => live.current && setProgress({ done, total, fork }); + const finish = () => live.current && hideImportSessions(); + if (fork) { + const batch = chosen.map((r) => ({ + provider: r.provider, + sessionId: r.sessionId, + cwd: r.cwd ?? root ?? "", + title: r.title, + })); + void forkExternalSessions(batch, progress, controller.signal).finally(finish); + } else { + const batch = chosen.map((r) => ({ provider: r.provider, sessionId: r.sessionId, title: r.title })); + void importExternalSessions(batch, progress, controller.signal).finally(finish); + } }; + const importChosen = () => runChosen(false); // Cancel, Esc and the close button stop a running batch after the import in flight. const close = () => { abort.current?.abort(); hideImportSessions(); }; + const forkChosen = () => runChosen(true); const onFilterKey = (e: KeyboardEvent) => { if (e.key === "Enter") { e.preventDefault(); @@ -155,6 +173,7 @@ function ImportSessionsDialog() { }; const providerName = (id: string) => providers.find((p) => p.id === id)?.name ?? id; const importLabel = chosen.length > 1 ? tx`Import ${chosen.length}` : tx("Import"); + const forkLabel = chosen.length > 1 ? tx`Fork ${chosen.length}` : tx("Fork"); return ( <Dialog @@ -169,7 +188,9 @@ function ImportSessionsDialog() { </Button> {progress ? ( <span className={styles.chooserHint}> - {tx`Importing ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…`} + {progress.fork + ? tx`Forking ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…` + : tx`Importing ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…`} </span> ) : shown && external.length >= LISTED_MAX ? ( <span className={styles.chooserHint}> @@ -180,6 +201,7 @@ function ImportSessionsDialog() { } buttons={[ { label: "Cancel", role: "cancel" }, + { label: forkLabel, onClick: forkChosen, disabled: busy || !shown || !chosen.length }, { label: importLabel, role: "default", onClick: importChosen, disabled: busy || !shown || !chosen.length }, ]} > diff --git a/src/features/agents/agentRegistry.test.tsx b/src/features/agents/agentRegistry.test.tsx index 7fa07c314..eb65ced54 100644 --- a/src/features/agents/agentRegistry.test.tsx +++ b/src/features/agents/agentRegistry.test.tsx @@ -421,6 +421,7 @@ class FakeCommands implements CommandsBackend { providers = vi.fn(async () => this.list); chooseExecutable = vi.fn(async () => "/chosen/agent"); saveCustom = vi.fn(async () => {}); + setAdditionalArgs = vi.fn<CommandsBackend["setAdditionalArgs"]>(); removeCustom = vi.fn(async () => {}); importAcp = vi.fn(async (): Promise<AcpImportOutcome[]> => []); pickAcpJson = vi.fn(async (): Promise<string | null> => null); diff --git a/src/features/agents/commitMessage.test.ts b/src/features/agents/commitMessage.test.ts index 5650be353..bfa95a8ac 100644 --- a/src/features/agents/commitMessage.test.ts +++ b/src/features/agents/commitMessage.test.ts @@ -392,6 +392,8 @@ describe("generateCommitMessage", () => { provider: "claude", config: [{ id: "model", value: "smart" }], isolation: "local", + // The agent keeps no history of it. + ephemeral: true, }); expect(request.prompt.text).toContain(PATCH.trimEnd()); expect(request.prompt.text).toContain("- feat: earlier"); diff --git a/src/features/agents/commitMessage.ts b/src/features/agents/commitMessage.ts index 356d2dd70..3a64ef5ee 100644 --- a/src/features/agents/commitMessage.ts +++ b/src/features/agents/commitMessage.ts @@ -1,7 +1,8 @@ /** * Generate Commit Message with Agent: the coding agent the user works with reads the * changes about to be committed and writes their message. It runs as a short task that - * is deleted once the message is in the commit field. + * is deleted once the message is in the commit field, and asks the agent not to keep the + * session in its own history. */ import type { AgentConfigChoice, @@ -327,6 +328,7 @@ async function generate(): Promise<void> { config: agent.config, isolation: "local", base: null, + ephemeral: true, }), ); task = created; diff --git a/src/features/agents/composerFolders.test.tsx b/src/features/agents/composerFolders.test.tsx index 3c3633707..1cabe06a3 100644 --- a/src/features/agents/composerFolders.test.tsx +++ b/src/features/agents/composerFolders.test.tsx @@ -7,6 +7,7 @@ import userEvent from "@testing-library/user-event"; import { caretOf, setCaret, textOf, typeChars, typeIn } from "./composerTesting"; import chipStyles from "./ReferenceChip.module.css"; import { FILES_DRAG, dragSession } from "@/ui"; +import { EDITOR_TAB_MIME, provideEditorService, type EditorService } from "@/workbench/contributions"; import { useProject } from "@/platform/project"; const findFiles = vi.fn(); @@ -123,6 +124,32 @@ describe("Composer dropped paths", () => { expect(textOf(box)).toBe("@src/a.ts @src/dir/ "); }); + it("references the file of an editor tab dragged onto it and ignores other tabs", () => { + provideEditorService({ + tabInput: (_pane: string, tab: string) => + tab === "file" + ? { kind: "file", key: "/p/src/a.ts", path: "/p/src/a.ts" } + : { kind: "agentSession", key: "agent:one", data: { task: "one" } }, + } as unknown as EditorService); + const box = renderComposer(); + const restore = document.elementFromPoint; + document.elementFromPoint = () => box; + try { + act(() => { + const other = dragSession({ + type: EDITOR_TAB_MIME, + payload: JSON.stringify({ paneId: "p", tabId: "session" }), + }); + expect(other.drop(0, 0)).toBe(false); + const file = dragSession({ type: EDITOR_TAB_MIME, payload: JSON.stringify({ paneId: "p", tabId: "file" }) }); + expect(file.drop(0, 0)).toBe(true); + }); + } finally { + document.elementFromPoint = restore; + } + expect(textOf(box)).toBe("@src/a.ts "); + }); + it("deduplicates live references and allows a deleted reference to be dropped again", () => { const box = renderComposer(); drop(box, "/p/src/a.ts\n/p/src/a.ts\n/p/src/dir/"); diff --git a/src/features/agents/composerModel.ts b/src/features/agents/composerModel.ts index e793335c8..6197d925e 100644 --- a/src/features/agents/composerModel.ts +++ b/src/features/agents/composerModel.ts @@ -462,7 +462,8 @@ export const isPerModelOption = (o: AgentConfigOption) => o.category === "context_tier" || o.category === "model_config" || isFastOption(o.id) || - isContextOption(o.id); + isContextOption(o.id) || + o.id === "service_tier"; const matchesCategory = (o: AgentConfigOption, category: string) => o.category === category || diff --git a/src/features/agents/index.ts b/src/features/agents/index.ts index a548b26b1..ca5159ad2 100644 --- a/src/features/agents/index.ts +++ b/src/features/agents/index.ts @@ -164,6 +164,13 @@ export function activate(): () => void { trailing: (input) => createElement(TaskStatusMark, { task: (input.data as { task: string }).task }), // Tabs of tasks deleted meanwhile are closed when the tasks load (`connect`). restorable: true, + canNavigate: (input, open) => { + if (open) return true; + const task = (input.data as { task?: string } | undefined)?.task; + if (!task) return false; + const s = useAgents.getState(); + return !s.loaded || s.tasks.has(task); + }, onTabClose: (tabId) => clearAgentTabFontZoom(tabId), prepareWindowInput: prepareTaskWindowInput, onClose: (input) => { @@ -187,6 +194,13 @@ export function activate(): () => void { }, icon: () => "diff", restorable: true, + canNavigate: (input, open) => { + if (open) return true; + const task = (input.data as { task?: string } | undefined)?.task; + if (!task) return false; + const s = useAgents.getState(); + return !s.loaded || s.tasks.has(task); + }, onClose: (input) => releaseClosedTaskCache((input.data as { task: string }).task), }), registerEditorKind({ @@ -218,7 +232,7 @@ export function activate(): () => void { registerStatusItem({ id: "agents.status", align: "right", priority: 3, title: "Agents", component: AgentsStatus }), registerMenuGroup({ id: "agents.send", - menus: ["editor", "projectView"], + menus: ["editor", "editorTab", "projectView"], order: 80, items: (menu, { paths, dirs }) => paths.length && !paths.some(isVirtualUri) && agentsHere() @@ -226,7 +240,8 @@ export function activate(): () => void { { kind: "action", action: "agents.sendToAgent", - arg: menu === "projectView" ? paths.map((p, i) => (dirs?.[i] ? `${p}/` : p)) : undefined, + // The editor sends its selection; a tab or the Project view sends the files. + arg: menu === "editor" ? undefined : paths.map((p, i) => (dirs?.[i] ? `${p}/` : p)), }, ] : [], diff --git a/src/features/agents/registry.ts b/src/features/agents/registry.ts index 0f3fcf5d9..44346fbad 100644 --- a/src/features/agents/registry.ts +++ b/src/features/agents/registry.ts @@ -34,6 +34,7 @@ export interface CommandsBackend { providers(): Promise<AgentProvider[]>; refreshModels?(id: string, model: string | null): Promise<AgentModelCatalog>; set(id: string, command: string | null): Promise<void>; + setAdditionalArgs(id: string, args: string[]): Promise<void>; setEnv(id: string, env: Record<string, string>): Promise<void>; chooseExecutable(title: string, current?: string, location?: "desktop"): Promise<string | null>; saveCustom(input: CustomAgentInput): Promise<void>; @@ -69,6 +70,9 @@ export const tauriCommands: CommandsBackend = { set: async (id, command) => { await call(commands.agentSetCommand(id, command)); }, + setAdditionalArgs: async (id, args) => { + await call(commands.agentSetAdditionalArgs(id, args)); + }, setEnv: async (id, env) => { await call(commands.agentSetEnv(id, env)); }, diff --git a/src/features/agents/sessionState.test.tsx b/src/features/agents/sessionState.test.tsx index 752341092..ac1f3db59 100644 --- a/src/features/agents/sessionState.test.tsx +++ b/src/features/agents/sessionState.test.tsx @@ -15,6 +15,7 @@ import { ChangesTab } from "./session/ChangesTab"; import { acceptChanges, disconnect, + forkExternalSession, hideImportSessions, importExternalSessions, refreshChanges, @@ -56,6 +57,7 @@ const backend = vi.hoisted(() => ({ updatedMs: number; }>, imported: [] as Array<[string, string]>, + forked: [] as Array<[string, string, string]>, importError: null as string | null, importErrors: new Map<string, string>(), importWait: null as Promise<void> | null, @@ -157,6 +159,20 @@ vi.mock("@/platform/ipc", async (original) => ({ }, }; }, + agentForkSession: async (provider: string, sessionId: string, cwd: string) => { + backend.forked.push([provider, sessionId, cwd]); + const found = backend.external.find((e) => e.provider === provider && e.sessionId === sessionId); + if (!found) throw new Error("unknown session"); + return { + status: "ok", + data: { + ...task(`forked-${sessionId}`), + id: `forked-${sessionId}`, + title: found.title, + provider, + }, + }; + }, }, })); vi.mock("@tauri-apps/api/webview", () => ({ @@ -266,6 +282,7 @@ beforeEach(() => { // The flat list unless a test asks for the grouped view, so counts and selections stay as before. useChangesOptions.setState({ groupByCommit: false, scope: "task" }); backend.imported = []; + backend.forked = []; backend.importError = null; backend.importErrors = new Map(); backend.importWait = null; @@ -2614,6 +2631,19 @@ describe("batch import", () => { }); }); +describe("fork external session", () => { + it("forks a recorded session into a new task and opens it", async () => { + backend.external = [{ provider: "claude", sessionId: "a", title: "First", cwd: "/work/app", updatedMs: 0 }]; + useAgents.setState({ sessionLocation: "toolWindow", docked: null }); + await act(() => forkExternalSession("claude", "a", "/work/app")); + expect(backend.forked).toEqual([["claude", "a", "/work/app"]]); + expect(useAgents.getState().docked).toBe("forked-a"); + expect(useAgents.getState().tasks.has("forked-a")).toBe(true); + expect(useAgents.getState().external).toHaveLength(0); + expect(useAgents.getState().importing.size).toBe(0); + }); +}); + describe("import sessions dialog", () => { const sessions = [ { provider: "claude", sessionId: "abc", title: "Login fix", cwd: "/work/app", updatedMs: 0 }, diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index 8e2201c54..4f73f874f 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -1300,9 +1300,16 @@ export async function startTask( ) ) return; - const config = options.flatMap((o) => - o.current !== null && o.values.some((v) => v.value === o.current) ? [{ id: o.id, value: o.current }] : [], - ); + const model = options.find((o) => o.category === "model")?.current; + const defaults = providerDefaults(draft.provider); + const config = options.flatMap((o) => { + // An untouched Codex tier inherits the runtime's default; explicit Off must still be sent. + const value = + o.id === "service_tier" + ? ((model ? draft.thoughtLevels?.[model]?.[o.id] : undefined) ?? defaults[o.id] ?? null) + : o.current; + return value !== null && o.values.some((v) => v.value === value) ? [{ id: o.id, value }] : []; + }); try { const task = await call( commands.agentCreate({ @@ -1365,10 +1372,8 @@ function markImporting(keys: readonly string[], on: boolean) { }); } -async function importOne(provider: string, sessionId: string, open: boolean) { - const started = generation; - const task = await call(commands.agentImportSession(provider, sessionId)); - if (generation !== started) return task; +/** Records the task an external session became and opens it when asked; shared by import and fork. */ +function adoptSessionTask(provider: string, sessionId: string, task: AgentTask, open: boolean) { useAgents.setState((s) => ({ tasks: s.tasks.has(task.id) ? s.tasks : new Map(s.tasks).set(task.id, task), external: s.external.filter((e) => !(e.provider === provider && e.sessionId === sessionId)), @@ -1377,26 +1382,52 @@ async function importOne(provider: string, sessionId: string, open: boolean) { return task; } -/** Imports an external session as a task and opens it: its first turn loads it (#312). */ -export async function importExternalSession(provider: string, sessionId: string) { +async function importOne(provider: string, sessionId: string, open: boolean) { + const started = generation; + const task = await call(commands.agentImportSession(provider, sessionId)); + if (generation !== started) return task; + return adoptSessionTask(provider, sessionId, task, open); +} + +async function forkOne(provider: string, sessionId: string, cwd: string, open: boolean) { + const started = generation; + const task = await call(commands.agentForkSession(provider, sessionId, cwd)); + if (generation !== started) return task; + return adoptSessionTask(provider, sessionId, task, open); +} + +/** Guards a single external-session operation against a concurrent one on the same session. */ +async function runExternalOne(provider: string, sessionId: string, run: () => Promise<AgentTask>) { const key = externalKey(provider, sessionId); if (useAgents.getState().importing.has(key)) throw new Error(tx("Already importing")); markImporting([key], true); try { - return await importOne(provider, sessionId, true); + return await run(); } finally { markImporting([key], false); } } +/** Imports an external session as a task and opens it: its first turn loads it (#312). */ +export async function importExternalSession(provider: string, sessionId: string) { + return runExternalOne(provider, sessionId, () => importOne(provider, sessionId, true)); +} + +/** Forks a recorded session into a new task and opens it: its first turn continues the recording. */ +export async function forkExternalSession(provider: string, sessionId: string, cwd: string) { + return runExternalOne(provider, sessionId, () => forkOne(provider, sessionId, cwd, true)); +} + /** - * Imports sessions one after another, all marked pending from the start; only a single one opens. - * Sessions already being imported are skipped. Failures don't stop the rest and are reported - * together at the end. A project switch ends the batch; an abort ends it after the import in - * flight and frees the sessions it didn't reach. + * Runs external-session operations one after another, all marked pending from the start; only a + * single one opens. Sessions already pending are skipped. Failures don't stop the rest and are + * reported together at the end. A project switch ends the batch; an abort ends it after the + * operation in flight and frees the sessions it didn't reach. Shared by import and fork. */ -export async function importExternalSessions( - sessions: readonly { provider: string; sessionId: string; title: string }[], +async function runExternalBatch<T extends { provider: string; sessionId: string; title: string }>( + sessions: readonly T[], + runOne: (session: T, open: boolean) => Promise<unknown>, + failed: { one: string; many: string }, onProgress?: (done: number) => void, signal?: AbortSignal, ) { @@ -1414,8 +1445,8 @@ export async function importExternalSessions( break; } try { - // oxlint-disable-next-line no-await-in-loop -- imports are documented sequential: abort, generation and progress are checked between sessions - await importOne(s.provider, s.sessionId, batch.length === 1); + // oxlint-disable-next-line no-await-in-loop -- operations are documented sequential: abort, generation and progress are checked between sessions + await runOne(s, batch.length === 1); } catch (e) { failures.push(`${s.title}: ${e instanceof Error ? e.message : String(e)}`); } finally { @@ -1425,9 +1456,37 @@ export async function importExternalSessions( } if (generation !== started || !failures.length) return; // Not awaited, so the caller's dialog closes instead of waiting behind the message. - const title = - failures.length === 1 ? tx("A session could not be imported") : tx("Some sessions could not be imported"); - void showError(title, failures.join("\n")); + void showError(failures.length === 1 ? failed.one : failed.many, failures.join("\n")); +} + +/** Imports sessions one after another; the batch rules are {@link runExternalBatch}'s. */ +export async function importExternalSessions( + sessions: readonly { provider: string; sessionId: string; title: string }[], + onProgress?: (done: number) => void, + signal?: AbortSignal, +) { + await runExternalBatch( + sessions, + (s, open) => importOne(s.provider, s.sessionId, open), + { one: tx("A session could not be imported"), many: tx("Some sessions could not be imported") }, + onProgress, + signal, + ); +} + +/** Forks sessions one after another; the batch rules are {@link runExternalBatch}'s. */ +export async function forkExternalSessions( + sessions: readonly { provider: string; sessionId: string; cwd: string; title: string }[], + onProgress?: (done: number) => void, + signal?: AbortSignal, +) { + await runExternalBatch( + sessions, + (s, open) => forkOne(s.provider, s.sessionId, s.cwd, open), + { one: tx("A session could not be forked"), many: tx("Some sessions could not be forked") }, + onProgress, + signal, + ); } export function setIdeContext(on: boolean) { diff --git a/src/features/agents/unread.test.tsx b/src/features/agents/unread.test.tsx index 25ff28574..58e500d0c 100644 --- a/src/features/agents/unread.test.tsx +++ b/src/features/agents/unread.test.tsx @@ -3,6 +3,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react"; import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings"; import { dropOnEditor, + menuGroupItems, useContributions, useEditorTabTitles, type EditorInput, @@ -595,3 +596,20 @@ describe("the diff of an agent change", () => { expect(backend.openInput.mock.lastCall![0].data.chain).toBeUndefined(); }); }); + +describe("Send to Agent menus", () => { + it("sends the selection from the editor and the files from an editor tab or the Project view", () => { + const dispose = activate(); + try { + const send = (menu: "editor" | "editorTab" | "projectView", dirs?: boolean[]) => + menuGroupItems(menu, { paths: ["/p/a.ts", "/p/src"].slice(0, dirs ? 2 : 1), dirs }).find( + (i) => "action" in i && i.action === "agents.sendToAgent", + ); + expect(send("editor")).toMatchObject({ arg: undefined }); + expect(send("editorTab")).toMatchObject({ arg: ["/p/a.ts"] }); + expect(send("projectView", [false, true])).toMatchObject({ arg: ["/p/a.ts", "/p/src/"] }); + } finally { + dispose(); + } + }); +}); diff --git a/src/features/app/__tests__/menuBridge.test.ts b/src/features/app/__tests__/menuBridge.test.ts index dfe20dab1..bf8a01108 100644 --- a/src/features/app/__tests__/menuBridge.test.ts +++ b/src/features/app/__tests__/menuBridge.test.ts @@ -4,6 +4,7 @@ import { _resetI18nForTests, setLocale } from "@/platform/i18n"; import { useKeymap } from "@/platform/keymap"; import * as ipc from "@/platform/ipc"; import { resetDistractionFree, setDistractionFree } from "@/workbench/distractionFree"; +import { useFullscreen } from "@/workbench/zenMode"; import { registerStatusItem, registerToolWindow } from "@/workbench/contributions"; import { useProject } from "@/platform/project"; import { _reloadLayouts, saveLayout } from "@/workbench/toolwindows/layouts"; @@ -333,6 +334,19 @@ describe("window-scoped menu labels", () => { resetDistractionFree(); }); + it("flips Enter / Exit Zen Mode only while Distraction Free Mode and full screen are both on", () => { + const label = () => buildMenuConfig("macos").labels["menu.view.toggleZenMode"]; + expect(label()).toBe("Enter Zen Mode"); + setDistractionFree(true); + expect(label()).toBe("Enter Zen Mode"); + useFullscreen.setState({ on: true }); + expect(label()).toBe("Exit Zen Mode"); + setDistractionFree(false); + expect(label()).toBe("Enter Zen Mode"); + useFullscreen.setState({ on: false }); + resetDistractionFree(); + }); + it("formats Recompile with the active local Java filename across locales", async () => { try { expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile"); diff --git a/src/features/app/__tests__/windows.test.ts b/src/features/app/__tests__/windows.test.ts index 2908bdd05..34f0e9598 100644 --- a/src/features/app/__tests__/windows.test.ts +++ b/src/features/app/__tests__/windows.test.ts @@ -344,6 +344,14 @@ describe("loose files (LightEdit)", () => { expect(fsReadDir).toHaveBeenCalledWith("/x/a.txt"); expect(lightEditOpen).toHaveBeenCalledWith("/x/a.txt"); }); + + it("opens the folder of a dropped .uproject instead of the file", async () => { + windowOpenProject.mockResolvedValue(ok({ kind: "current" })); + await openPaths(["/work/Game/Game.uproject"], async () => false); + expect(windowOpenFiles).not.toHaveBeenCalled(); + expect(lightEditOpen).not.toHaveBeenCalled(); + expect(openProject).toHaveBeenCalledWith("/work/Game"); + }); }); describe("Open Containing Folder as Project", () => { diff --git a/src/features/app/menuBridge.ts b/src/features/app/menuBridge.ts index 32b8119be..9a20c60f9 100644 --- a/src/features/app/menuBridge.ts +++ b/src/features/app/menuBridge.ts @@ -23,6 +23,7 @@ import { useProject } from "@/platform/project"; import { syncRemoteRecentMenu } from "@/platform/remote"; import { useContributions, useMenuSlotItems, useStandaloneEditor } from "@/workbench/contributions"; import { useDistractionFree } from "@/workbench/distractionFree"; +import { useFullscreen } from "@/workbench/zenMode"; import { javaFileNameOf, menuLabelParams } from "@/workbench/menuLabels"; import { orderStatusItems } from "@/workbench/StatusBar"; import { statusWidgetRows } from "@/workbench/statusBarWidgets"; @@ -278,6 +279,10 @@ export function installMenuBridge(): () => void { useDistractionFree.subscribe((s, prev) => { if (s.active !== prev.active) push(); }), + // View › Appearance › Enter / Exit Zen Mode also follows full screen. + useFullscreen.subscribe((s, prev) => { + if (s.on !== prev.on && useDistractionFree.getState().active) push(); + }), // Window › Hide All Tool Windows reads "Restore Tool Windows" while it would restore them. useToolWindowLayout.subscribe((s, prev) => { if (toolWindowsRestorable(s) !== toolWindowsRestorable(prev)) push(); diff --git a/src/features/app/windows.ts b/src/features/app/windows.ts index 6bbe0b4e4..babc5fa48 100644 --- a/src/features/app/windows.ts +++ b/src/features/app/windows.ts @@ -128,14 +128,19 @@ export async function openFiles(files: readonly string[]): Promise<void> { const pathIsDir = (path: string) => call(commands.fsReadDir(path)).then(() => true); +/** A file that names the project around it: dropping it opens that folder, as a double-click would. */ +const projectMarker = /\.uproject$/i; + /** Opens dropped paths: files as loose files ({@link openFiles}), the first folder as a project. */ export async function openPaths( paths: readonly string[], isDir: (path: string) => Promise<boolean> = pathIsDir, ): Promise<void> { const kinds = await Promise.all(paths.map((p) => isDir(p).catch(() => false))); - const files = paths.filter((_, i) => !kinds[i]); - const dir = paths.find((_, i) => kinds[i]); + // An Unreal project is dragged in as its `.uproject`, which names the folder to open. + const marker = paths.find((p, i) => !kinds[i] && projectMarker.test(p)); + const files = paths.filter((p, i) => !kinds[i] && p !== marker); + const dir = paths.find((_, i) => kinds[i]) ?? (marker ? dirname(marker) : undefined); await openFiles(files); if (dir) await openProjectWithPolicy(dir); } diff --git a/src/features/code-insight/ProblemsView.tsx b/src/features/code-insight/ProblemsView.tsx index 5394b8313..fdf0f9714 100644 --- a/src/features/code-insight/ProblemsView.tsx +++ b/src/features/code-insight/ProblemsView.tsx @@ -5,6 +5,7 @@ import { useCallback, useMemo, useRef, useState, useSyncExternalStore, type Keyb import { create } from "zustand"; import clsx from "clsx"; import type { Diagnostic, Severity } from "@/bindings"; +import { call, commands } from "@/platform/ipc"; import { useEditorRegistry } from "@/editor/api"; import { previewColors } from "@/editor/lineTokens"; import { executeAction } from "@/platform/actions"; @@ -103,6 +104,8 @@ useProblemsOptions.subscribe((s) => { /** The Problems tool window's ⋮ menu entries. */ export function useProblemsHeaderMenu(): MenuItem[] { const o = useProblemsOptions(); + const tscWatch = useProject((s) => s.settings?.languages?.typescript?.watchProblems ?? false); + const hasProject = useProject((s) => s.project !== null); const toggle = (key: keyof ProblemsOptions) => () => useProblemsOptions.setState({ [key]: !o[key] }); return [ { kind: "header", label: "Sort By" }, @@ -111,9 +114,25 @@ export function useProblemsHeaderMenu(): MenuItem[] { { kind: "separator" }, { id: "preview", label: "Show Preview", checked: o.preview, run: toggle("preview") }, { id: "autoscroll", label: "Autoscroll to Source", checked: o.autoscroll, run: toggle("autoscroll") }, + { kind: "separator" }, + { + id: "tscWatch", + label: "TypeScript Project Errors (tsc --watch)", + checked: tscWatch, + disabled: !hasProject, + run: () => void setTscWatch(!tscWatch), + }, ]; } +/** Runs the project's own `tsc --watch` and lists its errors in Problems (project setting). */ +async function setTscWatch(on: boolean) { + const settings = await call( + commands.settingsSet("project", "languages.typescript.watchProblems", JSON.stringify(on)), + ); + useProject.setState({ settings }); +} + const group = (s: Severity): "error" | "warning" | "info" => (s === "hint" ? "info" : s); type FileNode = { kind: "file"; key: string; path: string; items: Diagnostic[]; error: boolean }; diff --git a/src/features/code-insight/problemsStore.test.ts b/src/features/code-insight/problemsStore.test.ts index 6d06a612e..8bd0440c5 100644 --- a/src/features/code-insight/problemsStore.test.ts +++ b/src/features/code-insight/problemsStore.test.ts @@ -64,6 +64,35 @@ describe("counts", () => { }); }); +describe("a problem two sources report", () => { + beforeEach(() => clearProblems()); + + it("is listed and counted once (Build's tsc step and the tsc watcher)", () => { + const counts = () => useProblems.getState().counts.error; + const listed = () => fileDiagnostics(useProblems.getState().map, "/p/b.ts").map((x) => x.source); + applyDiagnosticsEvent("/p/b.ts", "tsc", [d(1, "error", "tsc"), d(2, "error", "tsc")]); + applyDiagnosticsEvent("/p/b.ts", "build", [d(1, "error", "build")]); + expect(listed()).toEqual(["build", "tsc"]); + expect(counts()).toBe(2); + expect(projectCounts(useProblems.getState().map).error).toBe(2); + // Either source alone still shows it. + applyDiagnosticsEvent("/p/b.ts", "tsc", []); + expect(listed()).toEqual(["build"]); + expect(counts()).toBe(1); + applyDiagnosticsEvent("/p/b.ts", "build", []); + expect(listed()).toEqual([]); + expect(counts()).toBe(0); + }); + + it("keeps other sources as they are, and different problems on one line", () => { + let map = mergeDiagnostics(mergeDiagnostics(new Map(), "/a", "ra", [d(1)]), "/a", "eslint", [d(1)]); + expect(fileDiagnostics(map, "/a")).toHaveLength(2); + map = mergeDiagnostics(map, "/a", "build", [{ ...d(1), message: "another" }]); + map = mergeDiagnostics(map, "/a", "tsc", [d(1)]); + expect(fileDiagnostics(map, "/a")).toHaveLength(4); + }); +}); + describe("store + decorations", () => { beforeEach(() => clearProblems()); diff --git a/src/features/code-insight/problemsStore.ts b/src/features/code-insight/problemsStore.ts index be7c9f3f8..23c00e712 100644 --- a/src/features/code-insight/problemsStore.ts +++ b/src/features/code-insight/problemsStore.ts @@ -65,14 +65,26 @@ const SEVERITY_ORDER: Record<Severity, number> = { error: 0, warning: 1, info: 2 // A file's sources map is replaced whenever its diagnostics change, so it keys the merged list. const merged = new WeakMap<FileDiagnostics, readonly Diagnostic[]>(); -/** All diagnostics of a file across sources, ordered by position then severity. */ +const sameProblem = (d: Diagnostic) => + `${d.range.start.line}:${d.range.start.col}-${d.range.end.line}:${d.range.end.col} ${d.severity} ${d.message}`; + +/** + * All diagnostics of a file across sources, ordered by position then severity. An error both + * Build and the tsc watcher report is listed once. + */ export function fileDiagnostics(map: ProblemsMap, path: string): readonly Diagnostic[] { - const sources = map.get(path); + return mergedSources(map.get(path)); +} + +function mergedSources(sources: FileDiagnostics | undefined): readonly Diagnostic[] { if (!sources) return []; let items = merged.get(sources); if (!items) { - items = [...sources.values()] - .flat() + // Build's tsc step and the tsc watcher (Problems › TypeScript Project Errors) print the same errors. + const build = sources.get("build"); + const built = build && sources.has("tsc") ? new Set(build.map(sameProblem)) : null; + items = [...sources] + .flatMap(([source, list]) => (built && source === "tsc" ? list.filter((d) => !built.has(sameProblem(d))) : list)) .sort( (a, b) => a.range.start.line - b.range.start.line || @@ -153,7 +165,7 @@ export function countSeverities(diags: Iterable<Diagnostic>): SeverityCounts { export function projectCounts(map: ProblemsMap): SeverityCounts { const c: SeverityCounts = { error: 0, warning: 0, info: 0, hint: 0 }; - for (const sources of map.values()) for (const items of sources.values()) for (const d of items) c[d.severity]++; + for (const sources of map.values()) for (const d of mergedSources(sources)) c[d.severity]++; return c; } @@ -245,12 +257,13 @@ function applyTo(snapshot: ProblemsSnapshot, path: string, source: string, items export function applyDiagnosticsEvent(path: string, source: string, items: readonly Diagnostic[]) { useProblems.setState((s) => { - const before = s.map.get(path)?.get(source) ?? []; + // The file's sources map is replaced, not changed, so this is the list before the event. + const before = mergedSources(s.map.get(path)); const raw = applyTo(s.raw, path, source, items); if (!raw) return s; const map = applyTo(s.map, path, source, applyProfile(inspectionProfile(), source, items)); if (!map) return { raw }; - return { raw, map, counts: recount(s.counts, before, map.get(path)?.get(source) ?? []) }; + return { raw, map, counts: recount(s.counts, before, mergedSources(map.get(path))) }; }); } diff --git a/src/features/code-insight/problemsTscWatch.test.ts b/src/features/code-insight/problemsTscWatch.test.ts new file mode 100644 index 000000000..0db049a78 --- /dev/null +++ b/src/features/code-insight/problemsTscWatch.test.ts @@ -0,0 +1,41 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { renderHook } from "@testing-library/react"; +import type { Settings } from "@/bindings"; + +const settingsSet = vi.fn(async (_scope: string, _key: string, _value: string) => ({ + status: "ok" as const, + data: { languages: { typescript: { watchProblems: true } } } as Settings, +})); +vi.mock("@/platform/ipc", async (orig) => { + const actual = await orig<typeof import("@/platform/ipc")>(); + return { ...actual, commands: { ...actual.commands, settingsSet } }; +}); + +const { useProblemsHeaderMenu } = await import("./ProblemsView"); +const { useProject } = await import("@/platform/project"); + +afterEach(() => { + useProject.setState({ project: null, settings: null }); + vi.clearAllMocks(); +}); + +const tscWatchItem = () => + renderHook(() => useProblemsHeaderMenu()).result.current.find((i) => "id" in i && i.id === "tscWatch"); + +it("turns the project's tsc --watch on from the Problems menu", async () => { + useProject.setState({ + project: { root: "/p" } as never, + settings: { languages: { typescript: { watchProblems: false } } } as Settings, + }); + const item = tscWatchItem(); + expect(item).toMatchObject({ checked: false, disabled: false }); + if (item && "run" in item) item.run?.(); + await vi.waitFor(() => + expect(settingsSet).toHaveBeenCalledWith("project", "languages.typescript.watchProblems", "true"), + ); + await vi.waitFor(() => expect(useProject.getState().settings?.languages?.typescript?.watchProblems).toBe(true)); +}); + +it("is off and unavailable without a project", () => { + expect(tscWatchItem()).toMatchObject({ checked: false, disabled: true }); +}); diff --git a/src/features/database/DataView.tsx b/src/features/database/DataView.tsx index d413e9f57..05d3f890a 100644 --- a/src/features/database/DataView.tsx +++ b/src/features/database/DataView.tsx @@ -70,6 +70,70 @@ export function ExtractorSelect({ value, onChange }: { value: ExportFormat; onCh export const copyFormatOf = (extractor: ExportFormat): CopyFormat => extractor === "csv" ? "csv" : extractor === "onerow" ? "onerow" : "tsv"; +/** The toolbar's extractor; `table` is the whole table to export (`null`: nothing, already reported). */ +export interface ExtractorMenu { + value: ExportFormat; + onChange: (f: ExportFormat) => void; + table: () => ExportData | null | Promise<ExportData | null>; +} + +const PANEL_ENTRIES: ReadonlyArray<{ panel: DataPanel; label: string }> = [ + { panel: "record", label: "Show Record View" }, + { panel: "value", label: "Open in Value Editor" }, + { panel: "aggregates", label: "Show Aggregate View" }, +]; + +/** + * The view's entries of the grid's context menu (DataGrip's): the side panels, checked while + * shown, then the toolbar's extractor and Export Table to Clipboard when the view has them. + */ +export function viewMenu( + panel: DataPanel | null, + onPanelChange: (panel: DataPanel | null) => void, + extractor?: ExtractorMenu, +): MenuItem[] { + const items: MenuItem[] = PANEL_ENTRIES.map(({ panel: p, label }) => ({ + label, + checked: panel === p, + run: () => onPanelChange(panel === p ? null : p), + })); + if (!extractor) return items; + return [ + ...items, + { kind: "separator" }, + { + label: "Data Extractor", + submenu: EXPORT_FORMATS.map((f) => ({ + label: f.label, + checked: f.id === extractor.value, + run: () => extractor.onChange(f.id), + })), + }, + { + label: "Export Table to Clipboard", + icon: "copy", + run: () => + void Promise.resolve(extractor.table()).then( + (data) => data && writeClipboardText(exportData(extractor.value, data)), + ), + }, + ]; +} + +/** Copy as › SQL INSERT / UPDATE / DELETE of the whole selected rows, in the selected order. */ +function sqlCopies(rows: readonly number[], extractor: ExtractorMenu): MenuItem[] { + const copy = (format: ExportFormat) => () => + void Promise.resolve(extractor.table()).then((data) => { + const picked = data && rows.flatMap((r) => (data.rows[r] ? [data.rows[r]] : [])); + if (picked?.length) void writeClipboardText(exportData(format, { ...data!, rows: picked })); + }); + return [ + { label: "SQL INSERT", run: copy("sql") }, + { label: "SQL UPDATE", run: copy("sqlUpdates") }, + { label: "SQL DELETE", run: copy("sqlDeletes") }, + ]; +} + /** The Record / Value / Aggregates panel's toggle (IDEA's "Show Value Editor"). */ export function PanelToggle({ panel, onChange }: { panel: DataPanel | null; onChange: (p: DataPanel | null) => void }) { return ( @@ -117,6 +181,8 @@ export interface DataViewProps extends Pick< onPanelChange: (panel: DataPanel | null) => void; /** Plain ⌘C's copy format (the toolbar's extractor; TSV by default). */ copyFormat?: CopyFormat; + /** The toolbar's extractor, also offered in the grid's context menu with the whole table to copy. */ + extractor?: ExtractorMenu; /** The search bar is shown (the toolbar's search button, ⌘F in the grid). */ searchOpen?: boolean; onSearchOpenChange?: (open: boolean) => void; @@ -248,7 +314,12 @@ export function DataView(props: DataViewProps) { driver={props.driver} sort={sort} onSort={onSort} - rowMenu={props.rowMenu && ((rows) => props.rowMenu!(rows.map(at)))} + copyAs={props.extractor && ((rows) => sqlCopies(rows.map(at), props.extractor!))} + rowMenu={(rows) => { + const own = props.rowMenu?.(rows.map(at)) ?? []; + const view = viewMenu(panel, onPanelChange, props.extractor); + return own.length ? [...own, { kind: "separator" }, ...view] : view; + }} rowNumber={(r) => (props.firstRowNumber ?? 1) + at(r)} copyFormat={props.copyFormat} onSelectionChange={setRange} diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css index f60c84d26..c98408714 100644 --- a/src/features/database/Database.module.css +++ b/src/features/database/Database.module.css @@ -954,6 +954,23 @@ padding: 2px 4px; border-bottom: 1px solid var(--border); } +.modifyFilter { + flex: 1; + min-width: 0; +} +.modifyGroup { + display: flex; + align-items: center; + gap: var(--space-1); + height: 22px; + padding: 0 6px; + color: var(--fg-muted); + cursor: default; + white-space: nowrap; +} +.modifyGroup:hover { + color: var(--fg); +} .modifyList { flex: 1; overflow: auto; diff --git a/src/features/database/ExportDialog.tsx b/src/features/database/ExportDialog.tsx index d1f0167dc..840214cfa 100644 --- a/src/features/database/ExportDialog.tsx +++ b/src/features/database/ExportDialog.tsx @@ -10,6 +10,7 @@ import { notifications } from "@/workbench/contributions"; import { DEFAULT_EXPORT_OPTIONS, EXPORT_FORMATS, + SQL_FORMATS, exportData, type ExportData, type ExportFormat, @@ -169,7 +170,7 @@ export function ExportDialog({ <CodePreview className={styles.exportPreviewText} aria-label="Export preview" - sql={format === "sql"} + sql={SQL_FORMATS.has(format)} text={preview + (data.rows.length > PREVIEW_ROWS ? `\n… ${data.rows.length - PREVIEW_ROWS} more rows` : "")} /> </div> diff --git a/src/features/database/Grid.test.tsx b/src/features/database/Grid.test.tsx index 4d2aee989..bc925687f 100644 --- a/src/features/database/Grid.test.tsx +++ b/src/features/database/Grid.test.tsx @@ -1013,3 +1013,106 @@ describe("local filter (#6022)", () => { expect(cities()).toEqual(["Shanghai", "Beijing", "Shenzhen", "Hangzhou"]); }); }); + +describe("the data view's context menu (DataGrip)", () => { + const columns = [ + { name: "id", type: "int" }, + { name: "city", type: "text" }, + ]; + const data = [ + ["1", "Shanghai"], + ["2", "Beijing"], + ]; + const value = (r: number, c: number) => data[r]?.[c] ?? null; + + it("toggles the side panels, switches the extractor and exports the whole table to the clipboard", async () => { + const writeText = vi.fn(() => Promise.resolve()); + Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } }); + const onPanelChange = vi.fn(); + const onExtractor = vi.fn(); + const table = () => ({ columns, rows: data, table: "cities", driver: "postgres" as const }); + const { rerender } = render( + <> + <DataView + columns={columns} + rowCount={2} + value={value} + panel="value" + onPanelChange={onPanelChange} + extractor={{ value: "csv", onChange: onExtractor, table }} + /> + <ContextMenuHost /> + </>, + ); + const open = () => { + fireEvent.mouseDown(screen.getAllByRole("gridcell")[0]!, { button: 0 }); + fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 }); + }; + open(); + expect(screen.getByRole("menuitemcheckbox", { name: /Open in Value Editor/ })).toHaveAttribute( + "aria-checked", + "true", + ); + fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /Show Record View/ })); + expect(onPanelChange).toHaveBeenLastCalledWith("record"); + open(); + // The shown panel's entry hides it. + fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /Open in Value Editor/ })); + expect(onPanelChange).toHaveBeenLastCalledWith(null); + + open(); + await act(async () => void fireEvent.click(screen.getByRole("menuitem", { name: /Export Table to Clipboard/ }))); + expect(writeText).toHaveBeenCalledWith(exportData("csv", table())); + + open(); + fireEvent.click(screen.getByRole("menuitem", { name: /Data Extractor/ })); + expect(screen.getByRole("menuitemcheckbox", { name: /^CSV/ })).toHaveAttribute("aria-checked", "true"); + fireEvent.click(screen.getByRole("menuitemcheckbox", { name: /SQL Inserts/ })); + expect(onExtractor).toHaveBeenCalledWith("sql"); + + // Without an extractor (a view with no toolbar one) only the panels are offered. + rerender( + <> + <DataView columns={columns} rowCount={2} value={value} panel={null} onPanelChange={onPanelChange} /> + <ContextMenuHost /> + </>, + ); + open(); + expect(screen.queryByRole("menuitem", { name: /Export Table to Clipboard/ })).toBeNull(); + expect(screen.getByRole("menuitemcheckbox", { name: /Show Aggregate View/ })).toHaveAttribute( + "aria-checked", + "false", + ); + }); + + it("copies the selected whole rows as SQL INSERT / UPDATE / DELETE (#6143)", async () => { + const writeText = vi.fn((_text: string) => Promise.resolve()); + Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } }); + const keyed = [{ ...columns[0]!, primaryKey: true }, columns[1]!]; + const table = () => ({ columns: keyed, rows: data, table: "cities", driver: "postgres" as const }); + render( + <> + <DataView + columns={keyed} + rowCount={2} + value={value} + panel={null} + onPanelChange={() => {}} + extractor={{ value: "csv", onChange: () => {}, table }} + /> + <ContextMenuHost /> + </>, + ); + // Only the second row's city cell: the statements still cover its whole row. + fireEvent.mouseDown(screen.getAllByRole("gridcell")[3]!, { button: 0 }); + const copyAs = async (entry: string) => { + fireEvent.contextMenu(screen.getByRole("grid"), { clientX: 5, clientY: 5 }); + fireEvent.click(screen.getByRole("menuitem", { name: /^Copy as/ })); + await act(async () => void fireEvent.click(screen.getByRole("menuitem", { name: new RegExp(`^${entry}`) }))); + return writeText.mock.lastCall?.[0]; + }; + expect(await copyAs("SQL INSERT")).toBe("INSERT INTO cities (id, city) VALUES (2, 'Beijing');"); + expect(await copyAs("SQL UPDATE")).toBe("UPDATE cities SET city = 'Beijing' WHERE id = 2;"); + expect(await copyAs("SQL DELETE")).toBe("DELETE FROM cities WHERE id = 2;"); + }); +}); diff --git a/src/features/database/Grid.tsx b/src/features/database/Grid.tsx index 3d1a825f7..030fa9c8a 100644 --- a/src/features/database/Grid.tsx +++ b/src/features/database/Grid.tsx @@ -86,6 +86,8 @@ export interface GridProps { onSort?: (column: string, add: boolean) => void; /** Extra context menu items for the selected rows. */ rowMenu?: (rows: number[]) => MenuItem[]; + /** More Copy as entries for the selected rows (SQL statements of the whole rows). */ + copyAs?: (rows: number[]) => MenuItem[]; /** Row number shown for row 0 (paging). */ firstRowNumber?: number; /** Row number shown for a row (local sort / filter reorder them); `firstRowNumber + row` otherwise. */ @@ -629,6 +631,10 @@ export function Grid(props: GridProps) { { kind: "action", action: "db.copyAsTsv", label: "TSV", arg: cellActions.current }, { kind: "action", action: "db.copyAsCsv", label: "CSV", arg: cellActions.current }, { kind: "action", action: "db.copyAsOneRow", label: "One-Row", arg: cellActions.current }, + ...(() => { + const more = props.copyAs?.(selectedRows()) ?? []; + return more.length ? [{ kind: "separator" } as const, ...more] : []; + })(), ], }, { kind: "action", action: "db.copyWithHeader", arg: cellActions.current }, diff --git a/src/features/database/JdbcDriverProfiles.tsx b/src/features/database/JdbcDriverProfiles.tsx index 7982f45e3..5d418c6fc 100644 --- a/src/features/database/JdbcDriverProfiles.tsx +++ b/src/features/database/JdbcDriverProfiles.tsx @@ -5,7 +5,7 @@ import { useTx } from "@/platform/i18n"; import { Button, Dialog, IconButton, Input, Select, T } from "@/ui"; import { baseName } from "./dumpTools"; import { newSourceId } from "./model"; -import { VENDORS, vendorById } from "./vendors"; +import { DUCKDB_JDBC_CLASS, DUCKDB_JDBC_PREFIX, VENDORS, vendorById, vendorOf } from "./vendors"; import styles from "./Database.module.css"; export function useJdbcDrivers() { @@ -36,9 +36,14 @@ export function useJdbcDrivers() { const blankDriver = (): DbJdbcDriver => ({ id: newSourceId(), name: "", jars: [], className: "", urlTemplate: "" }); +export function jdbcProfileOption({ id, name, vendor }: DbJdbcDriver) { + const icon = vendorOf({ driver: "jdbc", vendor: vendor ?? undefined }).icon; + return { value: id, label: name, verbatim: true, icon }; +} + const DRIVER_TYPES = [ { value: "", label: "Custom JDBC only" }, - ...VENDORS.filter((v) => v.driver !== "jdbc").map((v) => ({ value: v.id, label: v.label, icon: v.icon })), + ...VENDORS.filter((v) => v.id !== "jdbc").map((v) => ({ value: v.id, label: v.label, icon: v.icon })), ]; export function JdbcDriverProfiles({ @@ -270,7 +275,7 @@ export function JdbcDriverProfiles({ <Select aria-label="JDBC driver profiles" value={current?.id ?? ""} - options={profiles.map((d) => ({ value: d.id, label: d.name, verbatim: true }))} + options={profiles.map(jdbcProfileOption)} placeholder="No JDBC driver profiles" disabled={!profiles.length} onChange={setSelection} @@ -279,7 +284,17 @@ export function JdbcDriverProfiles({ <div className={styles.formRow}> <Button icon="plus" - onClick={() => edit({ ...blankDriver(), ...(sourceVendor && { vendor: sourceVendor }) })} + onClick={() => + edit({ + ...blankDriver(), + ...(sourceVendor && { vendor: sourceVendor }), + ...(sourceVendor === "duckdb" && { + name: "DuckDB", + className: DUCKDB_JDBC_CLASS, + urlTemplate: `${DUCKDB_JDBC_PREFIX}{file}`, + }), + }) + } > <T>Add…</T> </Button> diff --git a/src/features/database/JdbcSourceDialog.test.tsx b/src/features/database/JdbcSourceDialog.test.tsx index 915bd59e2..bffa14007 100644 --- a/src/features/database/JdbcSourceDialog.test.tsx +++ b/src/features/database/JdbcSourceDialog.test.tsx @@ -1,14 +1,17 @@ -import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import type { DataSource, DbJdbcDriver, ProjectInfo } from "@/platform/ipc"; +import { registerHostPathChooser } from "@/platform/choosePath"; import { useProject } from "@/platform/project"; +import { useRemote } from "@/platform/remote"; import { SourceDialog } from "./SourceDialog"; +import { DatabaseDialogs } from "./Dialogs"; import { JdbcDriverProfiles } from "./JdbcDriverProfiles"; import { sourceIcon, sourceLabel } from "./model"; import { newMenu, nodeMenu } from "./treeMenu"; import { useDatabase } from "./store"; -const backend = vi.hoisted(() => ({ call: vi.fn(), saveSource: vi.fn(), pick: vi.fn() })); +const backend = vi.hoisted(() => ({ call: vi.fn(), saveSource: vi.fn(), pick: vi.fn(), pickNew: vi.fn() })); vi.mock("@/platform/ipc", async (importOriginal) => { const real = await importOriginal<typeof import("@/platform/ipc")>(); const request = @@ -21,6 +24,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => { commands: { ...real.commands, dbJdbcDrivers: request("list"), + clipboardText: request("clipboard"), dbJdbcDriverClasses: request("classes"), dbApproveJdbcSource: request("approve"), dbSaveJdbcDriver: request("save"), @@ -33,7 +37,7 @@ vi.mock("./store", async (importOriginal) => ({ ...(await importOriginal<typeof import("./store")>()), saveSource: backend.saveSource, })); -vi.mock("@/platform/dialog", () => ({ open: backend.pick })); +vi.mock("@/platform/dialog", () => ({ open: backend.pick, save: backend.pickNew })); const driver: DbJdbcDriver = { id: "example-driver", @@ -55,10 +59,316 @@ beforeEach(() => { ); backend.saveSource.mockResolvedValue(undefined); backend.pick.mockResolvedValue(driver.jars); + backend.pickNew.mockResolvedValue(null); useDatabase.setState({ sources: [], dialog: null, loaded: true }); useProject.setState({ project: null }); }); +describe("DuckDB data sources", () => { + const duckdb: DbJdbcDriver = { + id: "duckdb-driver", + vendor: "duckdb", + name: "DuckDB JDBC", + jars: ["/local/duckdb_jdbc.jar"], + className: "org.duckdb.DuckDBDriver", + urlTemplate: "jdbc:duckdb:{file}", + }; + const startDuckDb = () => { + const dialog = render(<SourceDialog initial={null} />); + select("Data source type", "DuckDB"); + return dialog; + }; + + it("offers DuckDB in the new data source menu", () => { + const dataSource = newMenu().find((item) => "label" in item && item.label === "Data Source"); + expect(dataSource && "submenu" in dataSource && dataSource.submenu).toEqual( + expect.arrayContaining([expect.objectContaining({ label: "DuckDB", icon: "db-duckdb" })]), + ); + }); + + function openFromMenu(label: string) { + const entry = newMenu().find((item) => "label" in item && item.label === label); + if (!entry || !("run" in entry) || !entry.run) throw new Error(`Missing menu entry: ${label}`); + act(entry.run); + } + + it.each([ + { file: "/tmp/warehouse.DUCKDB", type: "DuckDB" }, + { file: "/tmp/warehouse.db", type: "SQLite" }, + ])("opens $file as $type from the File action", async ({ file, type }) => { + backend.pick.mockResolvedValueOnce(file); + render(<DatabaseDialogs />); + openFromMenu("Data Source from File…"); + const picker = await screen.findByRole("button", { name: "Data source type" }); + expect(picker).toHaveTextContent(type); + expect(screen.getByLabelText("File:")).toHaveValue(file); + expect(backend.saveSource).not.toHaveBeenCalled(); + }); + + it.each(["Data Source from URL…", "Import from Clipboard"])( + "opens the named JDBC URL draft from %s without approving, saving or connecting", + async (action) => { + const url = "jdbc:duckdb:/tmp/quarter end.duckdb;threads=1"; + const unassigned = { ...duckdb, vendor: null }; + backend.call.mockImplementation(async ([op]) => (op === "list" ? [unassigned] : op === "clipboard" ? url : "OK")); + render(<DatabaseDialogs />); + openFromMenu(action); + if (action === "Data Source from URL…") { + const fromUrl = within(await screen.findByRole("dialog", { name: "Data Source from URL" })); + fireEvent.change(fromUrl.getByLabelText("URL:"), { target: { value: url } }); + fireEvent.click(fromUrl.getByRole("button", { name: "OK" })); + } + const dialog = within(await screen.findByRole("dialog", { name: "New Data Source" })); + expect(dialog.getByRole("button", { name: "Data source type" })).toHaveTextContent("DuckDB"); + expect(dialog.getByRole("button", { name: "JDBC URL", pressed: true })).toBeVisible(); + expect(dialog.getByLabelText("URL:")).toHaveValue(url); + await dialog.findByText(/Add the official DuckDB JDBC JAR/); + expect(dialog.getByRole("button", { name: "OK" })).toBeDisabled(); + expect(dialog.getByRole("button", { name: "Test Connection" })).toBeDisabled(); + expect(backend.call.mock.calls.map(([request]) => request[0])).not.toContain("approve"); + expect(backend.call.mock.calls.map(([request]) => request[0])).not.toContain("test"); + expect(backend.saveSource).not.toHaveBeenCalled(); + }, + ); + + it("guides missing JARs through the existing profile manager and trust prompt", async () => { + startDuckDb(); + await screen.findByText(/Add the official DuckDB JDBC JAR/); + expect(screen.getByRole("button", { name: "OK" })).toBeDisabled(); + fireEvent.click(screen.getByRole("button", { name: "Connection driver" })); + expect(within(screen.getByRole("listbox")).queryByText("Built-in")).toBeNull(); + fireEvent.keyDown(screen.getByRole("listbox"), { key: "Escape" }); + fireEvent.click(screen.getByRole("button", { name: "Manage Drivers…" })); + fireEvent.click(screen.getByRole("button", { name: "Add…" })); + expect(screen.getByLabelText("Driver class:")).toHaveValue(duckdb.className); + expect(screen.getByLabelText("URL template:")).toHaveValue(duckdb.urlTemplate); + backend.pick.mockResolvedValueOnce(duckdb.jars); + fireEvent.click(screen.getByRole("button", { name: "Add JARs…" })); + await screen.findByText("duckdb_jdbc.jar"); + fireEvent.click(screen.getByRole("button", { name: "Save" })); + fireEvent.click(await screen.findByRole("button", { name: "Trust and Save" })); + await waitFor(() => + expect(backend.call).toHaveBeenCalledWith([ + "save", + expect.objectContaining({ vendor: "duckdb", className: duckdb.className, jars: duckdb.jars }), + ]), + ); + }); + + it.each([ + { action: "Browse…", method: backend.pick, path: "/tmp/existing file.duckdb" }, + { action: "New File…", method: backend.pickNew, path: "/tmp/new.duckdb" }, + ])("saves and reopens a database file chosen with $action", async ({ action, method, path }) => { + backend.call.mockImplementation(async ([op]) => (op === "list" ? [driver, duckdb] : "OK")); + method.mockResolvedValueOnce(path); + const view = startDuckDb(); + await waitFor(() => + expect(screen.getByRole("button", { name: "Connection driver" })).toHaveTextContent(duckdb.name), + ); + fireEvent.click(screen.getByRole("button", { name: action })); + await waitFor(() => expect(screen.getByLabelText("File:")).toHaveValue(path)); + const url = `jdbc:duckdb:${path}`; + expect(screen.getByLabelText("URL:")).toHaveValue(url); + fireEvent.click(screen.getByRole("button", { name: "OK" })); + await waitFor(() => + expect(backend.saveSource).toHaveBeenCalledWith( + expect.objectContaining({ + driver: "jdbc", + vendor: "duckdb", + jdbcDriver: duckdb.id, + file: path, + url, + urlOnly: false, + }), + undefined, + undefined, + ), + ); + const [source] = backend.saveSource.mock.calls[0]!; + view.unmount(); + render(<SourceDialog initial={source} />); + expect(screen.getByRole("button", { name: "File", pressed: true })).toBeVisible(); + expect(screen.getByLabelText("File:")).toHaveValue(path); + }); + + it.each([ + { mode: "In memory", url: "jdbc:duckdb:", urlOnly: false }, + { mode: "JDBC URL", url: "jdbc:duckdb:/tmp/custom.duckdb", urlOnly: true }, + ])("saves and reopens a source in $mode mode", async ({ mode, url, urlOnly }) => { + const second = { ...duckdb, id: "second-driver", name: "DuckDB JDBC 2" }; + backend.call.mockImplementation(async ([op]) => (op === "list" ? [driver, duckdb, second] : "OK")); + const view = startDuckDb(); + await waitFor(() => expect(screen.getByRole("button", { name: "Manage Drivers…" })).toBeEnabled()); + select("Connection driver", second.name); + fireEvent.click(screen.getByRole("button", { name: mode })); + if (urlOnly) { + fireEvent.change(screen.getByLabelText("URL:"), { target: { value: "jdbc:other:local" } }); + expect(screen.getByRole("button", { name: "OK" })).toBeDisabled(); + fireEvent.change(screen.getByLabelText("URL:"), { target: { value: url } }); + } + expect(screen.queryByLabelText("File:")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "OK" })); + await waitFor(() => + expect(backend.saveSource).toHaveBeenCalledWith( + expect.objectContaining({ driver: "jdbc", vendor: "duckdb", jdbcDriver: second.id, file: null, url, urlOnly }), + undefined, + undefined, + ), + ); + const [source] = backend.saveSource.mock.calls[0]!; + view.unmount(); + render(<SourceDialog initial={source} />); + expect(screen.getByRole("button", { name: mode, pressed: true })).toBeVisible(); + expect(screen.getByLabelText("URL:")).toHaveValue(url); + }); + + it("starts the explicit JDBC URL draft from the file currently in the form", async () => { + backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "OK")); + render( + <SourceDialog + initial={{ + driver: "jdbc", + vendor: "duckdb", + jdbcDriver: duckdb.id, + file: "/tmp/previous.duckdb", + url: "jdbc:duckdb:/tmp/previous.duckdb", + }} + />, + ); + await waitFor(() => expect(screen.getByRole("button", { name: "Go to Driver" })).toBeEnabled()); + fireEvent.change(screen.getByLabelText("File:"), { target: { value: "/tmp/current.duckdb" } }); + fireEvent.click(screen.getByRole("button", { name: "JDBC URL" })); + expect(screen.getByLabelText("URL:")).toHaveValue("jdbc:duckdb:/tmp/current.duckdb"); + }); + + it.each([ + { draft: "generated", authoredUrl: null, expected: "jdbc:duckdb:/tmp/selected.duckdb" }, + { + draft: "user-authored", + authoredUrl: "jdbc:duckdb:/tmp/explicit.duckdb;threads=2", + expected: "jdbc:duckdb:/tmp/explicit.duckdb;threads=2", + }, + ])("handles a $draft JDBC URL draft after choosing a new file", async ({ authoredUrl, expected }) => { + backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "OK")); + backend.pick.mockResolvedValueOnce("/tmp/selected.duckdb"); + render( + <SourceDialog + initial={{ + driver: "jdbc", + vendor: "duckdb", + jdbcDriver: duckdb.id, + file: "/tmp/original.duckdb", + url: "jdbc:duckdb:/tmp/original.duckdb", + }} + />, + ); + await waitFor(() => expect(screen.getByRole("button", { name: "Go to Driver" })).toBeEnabled()); + const urlMode = screen.getByRole("button", { name: "JDBC URL" }); + const fileMode = screen.getByRole("button", { name: "File" }); + fireEvent.click(urlMode); + expect(screen.getByLabelText("URL:")).toHaveValue("jdbc:duckdb:/tmp/original.duckdb"); + if (authoredUrl) fireEvent.change(screen.getByLabelText("URL:"), { target: { value: authoredUrl } }); + + fireEvent.click(fileMode); + fireEvent.click(screen.getByRole("button", { name: "Browse…" })); + await waitFor(() => expect(screen.getByLabelText("File:")).toHaveValue("/tmp/selected.duckdb")); + fireEvent.click(urlMode); + expect(screen.getByLabelText("URL:")).toHaveValue(expected); + + fireEvent.click(screen.getByRole("button", { name: "In memory" })); + fireEvent.click(urlMode); + expect(screen.getByLabelText("URL:")).toHaveValue(authoredUrl ?? "jdbc:duckdb:"); + fireEvent.click(fileMode); + fireEvent.click(urlMode); + fireEvent.click(screen.getByRole("button", { name: "OK" })); + await waitFor(() => + expect(backend.saveSource).toHaveBeenCalledWith( + expect.objectContaining({ url: expected, urlOnly: true }), + undefined, + undefined, + ), + ); + }); + + it("rejects a database path the JDBC driver would parse as URL properties", async () => { + backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "OK")); + startDuckDb(); + await waitFor(() => + expect(screen.getByRole("button", { name: "Connection driver" })).toHaveTextContent(duckdb.name), + ); + fireEvent.change(screen.getByLabelText("File:"), { target: { value: "/tmp/actual.duckdb;different" } }); + expect(screen.getByText("DuckDB database paths cannot contain semicolons.")).toBeVisible(); + expect(screen.getByRole("button", { name: "Test Connection" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "OK" })).toBeDisabled(); + }); + + it("browses and selects a new destination on the project host in a remote window", async () => { + const choose = vi + .fn() + .mockResolvedValueOnce(["/srv/project/existing.duckdb"]) + .mockResolvedValueOnce(["/srv/project/new.duckdb"]); + const unregister = registerHostPathChooser(choose); + useRemote.setState({ session: { root: "/srv/project", os: "linux", commands: [] } as never }); + useProject.setState({ project: { root: "/srv/project" } as ProjectInfo }); + try { + backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "OK")); + startDuckDb(); + fireEvent.click(screen.getByRole("button", { name: "Browse…" })); + await waitFor(() => expect(screen.getByLabelText("File:")).toHaveValue("/srv/project/existing.duckdb")); + expect(choose).toHaveBeenCalledWith(expect.objectContaining({ defaultPath: "/srv/project" })); + fireEvent.click(screen.getByRole("button", { name: "New File…" })); + await waitFor(() => expect(screen.getByLabelText("File:")).toHaveValue("/srv/project/new.duckdb")); + expect(choose).toHaveBeenCalledWith(expect.objectContaining({ save: true })); + expect(backend.pick).not.toHaveBeenCalled(); + expect(backend.pickNew).not.toHaveBeenCalled(); + } finally { + unregister(); + useRemote.setState({ session: null }); + } + }); + + it("requires write access for in-memory databases", async () => { + backend.call.mockImplementation(async ([op]) => (op === "list" ? [duckdb] : "OK")); + render( + <SourceDialog + initial={{ + driver: "jdbc", + vendor: "duckdb", + jdbcDriver: duckdb.id, + url: "jdbc:duckdb::memory:;threads=1", + urlOnly: true, + readOnly: true, + }} + />, + ); + await screen.findByText("Turn off Read-only in Options to use an in-memory DuckDB database."); + expect(screen.getByRole("button", { name: "Test Connection" })).toBeDisabled(); + fireEvent.click(screen.getByRole("tab", { name: "Options" })); + const readOnly = screen.getByRole("checkbox", { name: "Read-only" }); + fireEvent.click(readOnly); + expect(readOnly).toBeDisabled(); + await waitFor(() => expect(screen.getByRole("button", { name: "Test Connection" })).toBeEnabled()); + }); + + it("keeps an existing generic DuckDB JDBC source generic", async () => { + const legacy = { ...duckdb, vendor: null }; + backend.call.mockImplementation(async ([op]) => (op === "list" ? [legacy] : "OK")); + render(<SourceDialog initial={{ driver: "jdbc", jdbcDriver: legacy.id, url: "jdbc:duckdb:" }} />); + const test = screen.getByRole("button", { name: "Test Connection" }); + await waitFor(() => expect(test).toBeEnabled()); + expect(screen.getByRole("button", { name: "Data source type" })).toHaveTextContent("Custom JDBC"); + fireEvent.click(test); + await waitFor(() => + expect(backend.call).toHaveBeenCalledWith([ + "test", + expect.objectContaining({ driver: "jdbc", vendor: "", jdbcDriver: legacy.id, url: "jdbc:duckdb:" }), + null, + null, + ]), + ); + }); +}); + describe("custom JDBC data sources", () => { it("expands the selected profile's URL template for testing and saving, and keeps a manual URL editable", async () => { const first = { ...driver, urlTemplate: "jdbc:example://{host}:{port}/{database}" }; diff --git a/src/features/database/ObjectDialogs.tsx b/src/features/database/ObjectDialogs.tsx index 8aab3ffac..3e5e3d8e5 100644 --- a/src/features/database/ObjectDialogs.tsx +++ b/src/features/database/ObjectDialogs.tsx @@ -4,7 +4,14 @@ * Preview of the SQL they run), Remove Data Source, Data Source from URL, and the Quick Documentation popup. */ import { useEffect, useMemo, useRef, useState } from "react"; -import { call, commands, type DbColumnInfo, type DbDriver, type DbTableGrant } from "@/platform/ipc"; +import { + call, + commands, + type DbColumnInfo, + type DbDriver, + type DbTableDetails, + type DbTableGrant, +} from "@/platform/ipc"; import { highlightInto } from "@/editor/lsp/markdown"; import { Button, @@ -14,6 +21,7 @@ import { Input, Popup, Icon, + SearchField, Select, T, Tabs, @@ -27,6 +35,8 @@ import { canAlterColumn, createDatabaseSql, createSchemaSql, + commentsSupported, + createTableCommentSql, createTableSql, draftOf, dropDatabaseSql, @@ -52,6 +62,7 @@ import { renameDatabase, loadDetails, loadGrants, + loadTables, openSourceDialog, readableDdl, refresh, @@ -538,6 +549,7 @@ function blankColumn(driver: DbDriver, n: number): ColumnDraft { notNull: false, default: "", primaryKey: false, + comment: "", dropped: false, }; } @@ -551,7 +563,8 @@ function ModifyTableDialog(props: ModifyProps) { if (table && !details) void loadDetails(id, schema, table); }, [details, id, schema, table]); if (!table) return <ModifyTableForm {...props} initial={null} />; - if (details?.status === "ok") return <ModifyTableForm {...props} initial={details.value.columns} />; + if (details?.status === "ok") + return <ModifyTableForm {...props} initial={details.value.columns} details={details.value} />; return ( <Dialog open @@ -565,6 +578,64 @@ function ModifyTableDialog(props: ModifyProps) { ); } +/** A read-only row of the Modify Table list (a key, foreign key, index or trigger). */ +interface ObjectRow { + key: string; + name: string; + detail: string; +} + +/** + * The groups after Columns, as DataGrip lists them: the primary key of the columns as edited, + * then the foreign keys, indexes and triggers the table has (shown, not edited here). + */ +function objectGroups( + columns: readonly ColumnDraft[], + details: DbTableDetails | null | undefined, +): Array<{ id: string; label: string; icon: string; rows: ObjectRow[] }> { + const pk = columns.filter((c) => c.primaryKey && !c.dropped).map((c) => c.name); + const list = (names: readonly string[]) => `(${names.join(", ")})`; + return [ + { + id: "keys", + label: "Keys", + icon: "db-key", + rows: pk.length ? [{ key: "primary", name: "PRIMARY KEY", detail: list(pk) }] : [], + }, + { + id: "foreignKeys", + label: "Foreign Keys", + icon: "db-foreign-key", + rows: (details?.foreignKeys ?? []).map((fk, i) => ({ + key: `fk-${i}`, + name: list(fk.columns), + detail: `→ ${fk.refTable} ${list(fk.refColumns)}`, + })), + }, + { + id: "indexes", + label: "Indexes", + icon: "db-index", + rows: (details?.indexes ?? []).map((ix) => ({ + key: `ix-${ix.name}`, + name: ix.name, + // `UNIQUE` is SQL, not UI text. + detail: ix.unique ? ["UNIQUE", list(ix.columns)].join(" ") : list(ix.columns), + })), + }, + { + id: "triggers", + label: "Triggers", + icon: "db-trigger", + rows: (details?.triggers ?? []).map((t) => ({ + key: `tr-${t.name}`, + name: t.name, + detail: `${t.timing} ${t.events}`.toUpperCase(), + })), + }, + ]; +} + function ModifyTableForm({ id, schema, @@ -572,7 +643,8 @@ function ModifyTableForm({ focusColumn, addColumn, initial, -}: ModifyProps & { initial: DbColumnInfo[] | null }) { + details, +}: ModifyProps & { initial: DbColumnInfo[] | null; details?: DbTableDetails }) { const driver = driverOf(id); const [name, setName] = useState(table ?? "table_name"); const [columns, setColumns] = useState<ColumnDraft[]>(() => { @@ -587,11 +659,19 @@ function ModifyTableForm({ return columns[Math.max(0, focus)]?.key ?? null; }); const { busy, runAndClose } = useRunner(); + const comments = commentsSupported(driver); + const [comment, setComment] = useState(details?.comment ?? ""); const statements = useMemo(() => { - if (!table) return [createTableSql(driver, schema, name.trim() || "table_name", columns)]; - return alterTableSql(driver, schema, table, name, columns); - }, [columns, driver, schema, table, name]); + if (!table) { + const created = name.trim() || "table_name"; + return [ + createTableSql(driver, schema, created, columns, comment), + ...createTableCommentSql(driver, schema, created, columns, comment), + ]; + } + return alterTableSql(driver, schema, table, name, columns, { original: details?.comment ?? "", value: comment }); + }, [columns, driver, schema, table, name, comment, details?.comment]); const current = columns.find((c) => c.key === selected) ?? null; const patch = (p: Partial<ColumnDraft>) => @@ -611,6 +691,28 @@ function ModifyTableForm({ } }; const locked = !!current && !canAlterColumn(driver, current); + // The list's filter (names and types) and its collapsed groups. + const [filter, setFilter] = useState(""); + const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set()); + const query = filter.trim().toLowerCase(); + const matches = (...texts: string[]) => !query || texts.some((t) => t.toLowerCase().includes(query)); + const shownColumns = columns.filter((c) => matches(c.name, c.dataType)); + const groups = objectGroups(columns, details) + .map((g) => ({ ...g, rows: g.rows.filter((r) => matches(r.name, r.detail)) })) + .filter((g) => g.rows.length); + const toggleGroup = (group: string) => + setCollapsed((c) => { + const next = new Set(c); + if (!next.delete(group)) next.add(group); + return next; + }); + const groupHeader = (group: string, label: string, count: number) => ( + <div className={styles.modifyGroup} onMouseDown={() => toggleGroup(group)}> + <Icon name={collapsed.has(group) ? "chevron-right" : "chevron-down"} size={12} /> + <span>{tx(label)}</span> + <span className={styles.treeType}>{count}</span> + </div> + ); const showGrants = !!table && grantsSupported(driver); const [tab, setTab] = useState<"columns" | "grants">("columns"); const title = table ? `Modify Table ${table}` : "Create Table"; @@ -628,7 +730,14 @@ function ModifyTableForm({ label: "OK", role: "default", disabled: busy || !statements.length || !name.trim(), - onClick: () => void runAndClose(id, statements), + onClick: () => + void runAndClose(id, statements).then((ok) => { + if (!ok) return; + // The tree and the next Modify Table show the table as it now is. + const final = name.trim(); + void loadDetails(id, schema, final); + if (final !== table) void loadTables(id, schema); + }), }, ]} > @@ -646,6 +755,19 @@ function ModifyTableForm({ /> <span className={styles.formHint}>{schema}</span> </div> + {comments && ( + <div className={styles.formRow}> + <label className={styles.formLabel} htmlFor="db-table-comment"> + <T>Comment:</T> + </label> + <Input + id="db-table-comment" + className={styles.fill} + value={comment} + onChange={(e) => setComment(e.target.value)} + /> + </div> + )} {showGrants && ( <Tabs variant="compact" @@ -672,21 +794,52 @@ function ModifyTableForm({ disabled={!current} onClick={remove} /> + <SearchField + variant="bare" + className={styles.modifyFilter} + value={filter} + onChange={setFilter} + placeholder="Filter by name or type" + aria-label="Filter columns" + /> </div> <div role="listbox" aria-label={tx("Columns")} className={styles.modifyList}> - {columns.map((c) => ( - <div - key={c.key} - role="option" - aria-selected={c.key === selected} - tabIndex={-1} - className={styles.modifyItem} - data-dropped={c.dropped || undefined} - onMouseDown={() => setSelected(c.key)} - > - <Icon name={c.primaryKey ? "db-column-key" : "db-column"} size={16} /> - <span className={styles.nodeLabel}>{c.name || "<unnamed>"}</span> - <span className={styles.treeType}>{c.dataType}</span> + <div role="group" aria-label={tx("Columns")}> + {groupHeader("columns", "Columns", shownColumns.length)} + {!collapsed.has("columns") && + shownColumns.map((c) => ( + <div + key={c.key} + role="option" + aria-selected={c.key === selected} + tabIndex={-1} + className={styles.modifyItem} + data-dropped={c.dropped || undefined} + onMouseDown={() => setSelected(c.key)} + > + <Icon name={c.primaryKey ? "db-column-key" : "db-column"} size={16} /> + <span className={styles.nodeLabel}>{c.name || "<unnamed>"}</span> + <span className={styles.treeType}>{c.dataType}</span> + </div> + ))} + </div> + {groups.map((g) => ( + <div key={g.id} role="group" aria-label={tx(g.label)}> + {groupHeader(g.id, g.label, g.rows.length)} + {!collapsed.has(g.id) && + g.rows.map((r) => ( + <div + key={r.key} + role="option" + aria-selected={false} + aria-disabled + className={styles.modifyItem} + > + <Icon name={g.icon} size={16} /> + <span className={styles.nodeLabel}>{r.name}</span> + <span className={styles.treeType}>{r.detail}</span> + </div> + ))} </div> ))} </div> @@ -746,6 +899,19 @@ function ModifyTableForm({ disabled={current.dropped || locked} onChange={(e) => patch({ default: e.target.value })} /> + {comments && ( + <> + <label className={styles.formLabel} htmlFor="db-col-comment"> + <T>Column comment</T> + </label> + <Input + id="db-col-comment" + value={current.comment} + disabled={current.dropped || locked} + onChange={(e) => patch({ comment: e.target.value })} + /> + </> + )} {locked && ( <> <span /> @@ -869,7 +1035,7 @@ function SourceUrlDialog() { if (!parsed) return; closeDialog(); const s = parsed.source; - const name = s.driver === "sqlite" ? s.name : `${s.database || s.user || "db"}@${s.host}`; + const name = s.name ?? (s.driver === "jdbc" ? undefined : `${s.database || s.user || "db"}@${s.host}`); openSourceDialog(null, { ...s, name }, parsed.password); }; return ( @@ -899,7 +1065,7 @@ function SourceUrlDialog() { <span className={styles.formHint}> {url.trim() && !parsed ? tx("Not a URL of PostgreSQL, MySQL, SQLite or a compatible database") - : "postgresql://, mysql://, mariadb://, redshift://, tidb://…, jdbc:…, sqlite:path"} + : "postgresql://, mysql://, mariadb://, redshift://, tidb://…, jdbc:…, sqlite:path, jdbc:duckdb:path"} </span> </div> </Dialog> diff --git a/src/features/database/ResultsView.tsx b/src/features/database/ResultsView.tsx index e352294f1..0218e5935 100644 --- a/src/features/database/ResultsView.tsx +++ b/src/features/database/ResultsView.tsx @@ -453,9 +453,9 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void } }; - const showExport = async (at: { x: number; y: number }) => { - if (!r) return; - // What is exported or copied is the whole values, not the starts the page carries. + /** The result to export or copy: the whole values, not the starts the page carries. */ + const exportSource = async (): Promise<ExportData | null> => { + if (!r) return null; if (hasCutCells(r)) { try { await loadPage(tab); @@ -466,17 +466,19 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void body: e instanceof Error ? e.message : String(e), key: "db-whole-value", }); - return; + return null; } } - showContextMenu( - at, - exportMenu( - { columns, rows: rowsOf(r), driver, table: queryTable(text, { driver }) }, - queryTable(text, { driver }), - extractor, - ), - ); + return { + columns: gridColumns.map((c) => ({ name: c.name, type: c.type, primaryKey: c.primaryKey })), + rows: rowsOf(r), + driver, + table: queryTable(text, { driver }), + }; + }; + const showExport = async (at: { x: number; y: number }) => { + const data = await exportSource(); + if (data) showContextMenu(at, exportMenu(data, queryTable(text, { driver }), extractor)); }; // Submit / Revert / Go to Column (⌘↩ / ⌥⌘Z / ⌘F12) reach the latest state through the handle, as in the table editor. @@ -635,6 +637,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void panel={panel} onPanelChange={setPanel} copyFormat={copyFormatOf(extractor)} + extractor={{ value: extractor, onChange: setExtractor, table: exportSource }} searchOpen={searchOpen} onSearchOpenChange={setSearchOpen} firstRowNumber={(tab.page ?? 0) * (tab.pageSize ?? 0) + 1} diff --git a/src/features/database/SourceDialog.tsx b/src/features/database/SourceDialog.tsx index 02f28c145..2cfcb038f 100644 --- a/src/features/database/SourceDialog.tsx +++ b/src/features/database/SourceDialog.tsx @@ -25,7 +25,7 @@ import { type RequestId, } from "@/platform/ipc"; import { executeAction } from "@/platform/actions"; -import { choosePath } from "@/platform/choosePath"; +import { choosePath, chooseSavePath } from "@/platform/choosePath"; import { tx, txPart, useTx, useTxTemplate } from "@/platform/i18n"; import { useProject } from "@/platform/project"; import { useRemote } from "@/platform/remote"; @@ -44,13 +44,20 @@ import { sshTunnelReady, } from "./model"; import { closeDialog, loadDatabases, loadSchemas, saveSource, useDatabase } from "./store"; -import { VENDORS, blankSnowflake, sourceUrl, vendorById, vendorOf } from "./vendors"; -import { JdbcDriverProfiles, useJdbcDrivers } from "./JdbcDriverProfiles"; +import { DUCKDB_JDBC_PREFIX, VENDORS, blankSnowflake, sourceUrl, vendorById, vendorOf } from "./vendors"; +import { JdbcDriverProfiles, jdbcProfileOption, useJdbcDrivers } from "./JdbcDriverProfiles"; import styles from "./Database.module.css"; import { isImeKey } from "@/platform/ime"; type Tab = "general" | "options" | "ssh" | "schemas" | "advanced"; type ConnectionMethod = "direct" | "ssh" | "external"; +type DuckDbMode = "file" | "memory" | "url"; + +const DUCKDB_MODES: Array<{ id: DuckDbMode; label: string }> = [ + { id: "file", label: "File" }, + { id: "memory", label: "In memory" }, + { id: "url", label: "JDBC URL" }, +]; const TYPES: SelectOption[] = VENDORS.map((v) => ({ value: v.id, label: v.label, icon: v.icon })); @@ -204,7 +211,7 @@ function absoluteDatabaseFile(path: string, root: string | undefined): boolean { : path.startsWith("/") || (!root && windowsAbsolutePath.test(path)); } -function sqliteJdbcFile(file: string | null | undefined, root: string | undefined): string | null { +function jdbcDatabaseFile(file: string | null | undefined, root: string | undefined): string | null { if (!file) return null; const windows = !!root && windowsAbsolutePath.test(root); const path = windows ? file.replace(/\\/g, "/") : file; @@ -507,8 +514,8 @@ export function SourceDialog({ }, []); useEffect(() => cancelExternalTest, [cancelExternalTest]); const [showComment, setShowComment] = useState(!!s.comment); - // The URL being typed in default mode (null: show the fields' URL). - const [urlDraft, setUrlDraft] = useState<string | null>(null); + // URL text being edited in native default mode or DuckDB's explicit URL mode. + const [urlDraft, setUrlDraft] = useState<string | null>(s.vendor === "duckdb" && s.urlOnly ? (s.url ?? "") : null); const [showJdbcProfiles, setShowJdbcProfiles] = useState(false); const [nativeDraft, setNativeDraft] = useState<{ source: DataSource; @@ -521,10 +528,17 @@ export function SourceDialog({ const jdbc = s.driver === "jdbc"; const vendor = vendorOf(s); const genericJdbc = vendor.id === "jdbc"; + const duckdb = vendor.id === "duckdb"; + const jdbcOnly = vendor.driver === "jdbc"; + const [duckDbMode, setDuckDbMode] = useState<DuckDbMode>(() => { + if (s.urlOnly) return "url"; + return !s.file && s.url === DUCKDB_JDBC_PREFIX ? "memory" : "file"; + }); const savedJdbcWithPreset = initial?.driver === "jdbc" && (!genericJdbc || vendorOf(initial).driver !== "jdbc"); const jdbcProfiles = useJdbcDrivers(); const availableProfiles = jdbcProfiles.drivers?.filter((d) => genericJdbc || d.vendor === vendor.id); - const jdbcProfile = availableProfiles?.find((d) => d.id === s.jdbcDriver); + const selectedProfileId = s.jdbcDriver || (duckdb && availableProfiles?.length === 1 ? availableProfiles[0]!.id : ""); + const jdbcProfile = availableProfiles?.find((d) => d.id === selectedProfileId); const installedJdbcProfile = jdbcProfiles.drivers?.find((d) => d.id === s.jdbcDriver); const projectRoot = useProject((st) => st.project?.root); const remote = useRemote((st) => st.session !== null); @@ -541,7 +555,7 @@ export function SourceDialog({ ((savedJdbcWithPreset && (initial.jdbcDriver !== s.jdbcDriver || nativeSource || - (s.url && s.url === jdbcProfile?.urlTemplate && s.url !== initial.url))) || + (!duckdb && s.url && s.url === jdbcProfile?.urlTemplate && s.url !== initial.url))) || (nativeSource && (!!initial || nativeSource.driver === "clickhouse" || @@ -609,9 +623,11 @@ export function SourceDialog({ s.name?.trim() || (genericJdbc ? (jdbcProfile?.name ?? tx("Custom JDBC")) - : vendor.driver === "sqlite" - ? fileSourceName(s.file ?? "") - : `${database || s.user || "db"}@${host || "localhost"}`); + : duckdb + ? (duckDbMode === "file" && fileSourceName(s.file ?? "")) || vendor.label + : vendor.driver === "sqlite" + ? fileSourceName(s.file ?? "") + : `${database || s.user || "db"}@${host || "localhost"}`); // Snowflake is reached over HTTPS, where a tunnel to another host name cannot pass certificate checks. const sshOn = !sqlite && !snowflake && !jdbc && !externalTunnel && !!ssh.enabled; const connectionMethod = externalTunnel ? "external" : sshOn ? "ssh" : "direct"; @@ -637,11 +653,38 @@ export function SourceDialog({ /\{(host|port|database|file)\}/g, (token, key: "host" | "port" | "database" | "file") => String(s[key] || token), ); - const fromTemplate = !!templateFields.length && (s.url === template || s.url === renderedUrl); - const jdbcUrl = fromTemplate ? renderedUrl : (s.url ?? ""); + const fromTemplate = !duckdb && !!templateFields.length && (s.url === template || s.url === renderedUrl); + const duckDbFile = duckdb && duckDbMode === "file" ? jdbcDatabaseFile(s.file, projectRoot) : null; + const duckDbFileError = + !duckDbFile || !s.file?.trim() || /[\r\n]/.test(duckDbFile) + ? tx("Enter an absolute database path or a path relative to the open project.") + : duckDbFile.includes(";") + ? tx("DuckDB database paths cannot contain semicolons.") + : null; + const jdbcUrl = + duckdb && duckDbMode === "file" + ? duckDbFileError + ? "" + : DUCKDB_JDBC_PREFIX + duckDbFile + : duckdb + ? duckDbMode === "memory" + ? DUCKDB_JDBC_PREFIX + : (urlDraft ?? s.url ?? "") + : fromTemplate + ? renderedUrl + : (s.url ?? ""); + const duckDbMemory = + duckdb && + (duckDbMode === "memory" || + (duckDbMode === "url" && + [DUCKDB_JDBC_PREFIX, `${DUCKDB_JDBC_PREFIX}:memory:`].includes(jdbcUrl.split(";", 1)[0]!))); const chooseProfile = (profile?: DbJdbcDriver, type = vendor) => { setTest(null); setConnectionSecurityConfirmed(false); + if (duckdb) { + set({ jdbcDriver: profile?.id ?? "" }); + return; + } if (jdbc) { const wasDefault = !s.url || (!savedJdbcWithPreset && (fromTemplate || s.url === jdbcProfile?.urlTemplate)); set({ jdbcDriver: profile?.id ?? "", url: wasDefault ? (profile?.urlTemplate ?? "") : s.url }); @@ -655,7 +698,7 @@ export function SourceDialog({ port: (parsed ? parsed.port : s.port) ?? (clickhouse && secure ? 8443 : vendor.port), database: parsed?.database ?? s.database, user: parsed?.user || s.user, - file: sqlite ? sqliteJdbcFile(file, projectRoot) : file, + file: sqlite ? jdbcDatabaseFile(file, projectRoot) : file, }; setNativeDraft({ source: s, password, endpoint }); const snowflakeOptions = { ...sf, ...parsed?.snowflake }; @@ -664,7 +707,7 @@ export function SourceDialog({ set({ ...endpoint, driver: "jdbc", - vendor: type.driver === "jdbc" ? "" : type.id, + vendor: type.id === "jdbc" ? "" : type.id, ...(snowflake ? { snowflake: snowflakeOptions } : {}), ...(needsJdbcPassword ? { savePassword: false } : {}), urlOnly: true, @@ -680,14 +723,22 @@ export function SourceDialog({ sslKeyFile: "", }); }; - const jdbcUrlValid = /^jdbc:[^\s:]+:[^\r\n]*$/.test(jdbcUrl) && !jdbcUrlPlaceholder.test(jdbcUrl); + const jdbcUrlValid = + duckdb && duckDbMode === "file" + ? duckDbFileError === null + : /^jdbc:[^\s:]+:[^\r\n]*$/.test(jdbcUrl) && + !jdbcUrlPlaceholder.test(jdbcUrl) && + (!duckdb || jdbcUrl.startsWith(DUCKDB_JDBC_PREFIX)); const valid = (!externalTunnel || (!externalError && !!externalTunnel.executable.trim() && externalTunnel.arguments.some((argument) => argument.includes("{localPort}")))) && (jdbc - ? !!jdbcProfile && jdbcUrlValid && (!reviewJdbcSecurity || connectionSecurityConfirmed) + ? !!jdbcProfile && + jdbcUrlValid && + !(duckDbMemory && s.readOnly) && + (!reviewJdbcSecurity || connectionSecurityConfirmed) : (!reviewBuiltinSecurity || connectionSecurityConfirmed) && (sqlite ? !!s.file?.trim() @@ -704,9 +755,10 @@ export function SourceDialog({ ...(externalTunnel ? { ssh: null } : {}), ...(jdbc ? { - jdbcDriver: s.jdbcDriver ?? "", + jdbcDriver: jdbcProfile?.id ?? "", url: jdbcUrl, - urlOnly: true, + urlOnly: !duckdb || duckDbMode === "url", + ...(duckdb && { file: duckDbFile }), ssh: null, options: { ...options, transaction: "auto" as const }, } @@ -719,8 +771,18 @@ export function SourceDialog({ setTest(null); setUrlDraft(null); setConnectionSecurityConfirmed(false); - if (v.driver === "jdbc") { - if (jdbc) set({ vendor: "" }); + if (v.id === "duckdb") { + const sameDriver = installedJdbcProfile?.vendor === v.id; + const existingDuckUrl = jdbc && jdbcUrl.startsWith(DUCKDB_JDBC_PREFIX); + if (!jdbc) chooseProfile(undefined, v); + setDuckDbMode(existingDuckUrl ? "url" : "file"); + setUrlDraft(existingDuckUrl ? jdbcUrl : null); + set({ vendor: v.id, file: null, url: "", jdbcDriver: sameDriver ? s.jdbcDriver : "" }); + return; + } + if (v.id === "jdbc") { + if (duckdb) set({ vendor: "", jdbcDriver: selectedProfileId, file: duckDbFile, url: jdbcUrl }); + else if (jdbc) set({ vendor: "" }); else chooseProfile(undefined, v); return; } @@ -913,7 +975,25 @@ export function SourceDialog({ { id: "advanced", label: "Advanced" }, ]; const current = tabs.some((t) => t.id === tab) ? tab : "general"; - const props = PROPERTIES[s.driver ?? "sqlite"]!; + const props = duckdb + ? { names: [], hint: "Passed to the DuckDB JDBC driver as connection properties." } + : PROPERTIES[s.driver ?? "sqlite"]!; + + const pickDuckDbFile = async (create: boolean) => { + const filters = [{ name: "DuckDB", extensions: ["duckdb", "db"] }]; + const defaultPath = duckDbFile ?? projectRoot; + const file = create + ? await chooseSavePath({ + title: tx("New DuckDB Database"), + filters, + defaultPath: jdbcDatabaseFile("database.duckdb", projectRoot) ?? "database.duckdb", + }) + : await choosePath({ directory: false, title: tx("Open DuckDB Database"), filters, defaultPath }); + if (file) { + set({ file }); + setTest(null); + } + }; const general = ( <> @@ -926,15 +1006,19 @@ export function SourceDialog({ <Select className={styles.fill} aria-label={genericJdbc ? "JDBC driver profile" : "Connection driver"} - value={jdbc ? (s.jdbcDriver ?? "") : ""} - disabled={genericJdbc && !jdbcProfiles.drivers} + value={jdbc ? selectedProfileId : ""} + disabled={jdbcOnly && !jdbcProfiles.drivers} onChange={(id) => { - if (!id && !genericJdbc) setType(vendor.id, true); + if (!id && !jdbcOnly) setType(vendor.id, true); else chooseProfile(availableProfiles?.find((d) => d.id === id)); }} options={[ - { value: "", label: genericJdbc ? "Choose a JDBC driver profile" : "Built-in" }, - ...(availableProfiles ?? []).map((d) => ({ value: d.id, label: d.name, verbatim: true })), + { + value: "", + label: jdbcOnly ? "Choose a JDBC driver profile" : "Built-in", + disabled: duckdb, + }, + ...(availableProfiles ?? []).map(jdbcProfileOption), ...(jdbc && s.jdbcDriver && !jdbcProfile ? [ { @@ -962,16 +1046,111 @@ export function SourceDialog({ <span className={styles.formFull} role="status"> <T>Loading JDBC driver profiles…</T> </span> + ) : duckdb && !jdbcProfile && !availableProfiles?.length ? ( + <span className={styles.formFull} role="status"> + <T>Add the official DuckDB JDBC JAR in Manage Drivers… to connect.</T> + </span> ) : jdbc && s.jdbcDriver && !jdbcProfile && jdbcProfiles.drivers ? ( <span className={`${styles.formFull} ${styles.bad}`} role="alert"> {tx( - installedJdbcProfile - ? "The JDBC driver profile is assigned to a different data source type. Select a matching profile or update its type in Custom JDBC." - : "The JDBC driver profile is missing. Select or add a profile before connecting.", + duckdb + ? "Select a DuckDB driver profile or add the official DuckDB JDBC JAR in Manage Drivers…" + : installedJdbcProfile + ? "The JDBC driver profile is assigned to a different data source type. Select a matching profile or update its type in Custom JDBC." + : "The JDBC driver profile is missing. Select or add a profile before connecting.", )} </span> ) : null} - {sqlite ? ( + {duckdb ? ( + <> + <span className={styles.formLabel}> + <T>Connection type:</T> + </span> + <div className={styles.segmented} role="group" aria-label={tx("Connection type")}> + {DUCKDB_MODES.map(({ id, label }) => ( + <button + type="button" + key={id} + aria-pressed={id === duckDbMode} + onClick={() => { + setDuckDbMode(id); + if (id === "url" && duckDbMode !== "url" && urlDraft === null) set({ url: jdbcUrl }); + setTest(null); + }} + > + <T>{label}</T> + </button> + ))} + </div> + {duckDbMode === "file" && ( + <> + <label className={styles.formLabel} htmlFor="db-duckdb-file"> + <T>File:</T> + </label> + <div className={styles.formRow}> + <Input + id="db-duckdb-file" + className={styles.fill} + value={s.file ?? ""} + invalid={!!s.file && !!duckDbFileError} + placeholder="path/to/database.duckdb" + onChange={(e) => { + set({ file: e.target.value }); + setTest(null); + }} + /> + <Button onClick={() => void pickDuckDbFile(false)}> + <T>Browse…</T> + </Button> + <Button disabled={!!s.readOnly} onClick={() => void pickDuckDbFile(true)}> + <T>New File…</T> + </Button> + </div> + <span /> + {s.file && duckDbFileError ? ( + <span className={styles.bad} role="alert"> + {duckDbFileError} + </span> + ) : ( + <span className={styles.formHint}> + {s.readOnly ? ( + <T>Read-only requires an existing database file.</T> + ) : ( + <T>Creates the database on first connection if the file does not exist.</T> + )} + </span> + )} + </> + )} + <label className={styles.formLabel} htmlFor="db-url"> + <T>URL:</T> + </label> + <Input + id="db-url" + mono + value={jdbcUrl} + readOnly={duckDbMode !== "url"} + invalid={duckDbMode === "url" && !!jdbcUrl && !jdbcUrlValid} + placeholder={DUCKDB_JDBC_PREFIX} + onChange={(e) => { + setUrlDraft(e.target.value); + setTest(null); + }} + /> + {duckDbMemory && ( + <> + <span /> + <span className={styles.formHint}> + {s.readOnly ? ( + <T>Turn off Read-only in Options to use an in-memory DuckDB database.</T> + ) : ( + <T>Data is discarded when the connection closes.</T> + )} + </span> + </> + )} + </> + ) : sqlite ? ( <FileField id="db-file" label="File:" @@ -1278,12 +1457,21 @@ export function SourceDialog({ <> <Section title="Connection" /> <span /> - <Checkbox checked={!!s.readOnly} onChange={(readOnly) => set({ readOnly })} label="Read-only" /> - {jdbc && ( + <Checkbox + checked={!!s.readOnly} + disabled={duckDbMemory && !s.readOnly} + onChange={(readOnly) => set({ readOnly })} + label="Read-only" + /> + {duckDbMemory ? ( + <span className={styles.formWide}> + <T>In-memory DuckDB databases require write access.</T> + </span> + ) : jdbc && !duckdb ? ( <span className={styles.formWide}> <T>For read-only access, use a database account with read-only privileges.</T> </span> - )} + ) : null} {!jdbc && ( <> <span className={styles.formLabel}> diff --git a/src/features/database/SqlScopesPage.tsx b/src/features/database/SqlScopesPage.tsx index dd5cc8d3b..630966bb2 100644 --- a/src/features/database/SqlScopesPage.tsx +++ b/src/features/database/SqlScopesPage.tsx @@ -9,6 +9,7 @@ import { tx } from "@/platform/i18n"; import { IconButton, Input, Select, T, type SelectOption } from "@/ui"; import { useSettingsForm } from "@/workbench/contributions"; import { scopePath, validateResolutionScopes, type SqlResolutionScope } from "./resolutionScopes"; +import { sourceIcon } from "./model"; import styles from "./SqlScopesPage.module.css"; const KEY = "database.resolutionScopes"; @@ -42,7 +43,7 @@ export function SqlScopesPage() { value: s.id ?? "", label: s.name ?? s.id ?? "", verbatim: true, - icon: "database", + icon: sourceIcon(s), })), ]; const sourceOptions = (current: string) => diff --git a/src/features/database/TableEditor.tsx b/src/features/database/TableEditor.tsx index 2189cc033..838a14bf4 100644 --- a/src/features/database/TableEditor.tsx +++ b/src/features/database/TableEditor.tsx @@ -440,6 +440,16 @@ export function TableEditor({ input }: { input: EditorInput }) { panel={panel} onPanelChange={setPanel} copyFormat={copyFormatOf(extractor)} + extractor={{ + value: extractor, + onChange: setExtractor, + table: () => ({ + columns: gridColumns, + rows: page.result.rows, + table: ref.table, + driver: sourceById(ref.id)?.driver ?? "sqlite", + }), + }} searchOpen={searchOpen} onSearchOpenChange={setSearchOpen} firstRowNumber={offset + 1} diff --git a/src/features/database/export.test.ts b/src/features/database/export.test.ts index 70303ce86..763ed9b2d 100644 --- a/src/features/database/export.test.ts +++ b/src/features/database/export.test.ts @@ -195,3 +195,60 @@ it.each<ExportFormat>(["csv", "tsv", "sql", "markdown", "onerow"])("%s retains e const value = "9223372036854775807"; expect(exportData(format, data(value))).toContain(value); }); + +describe("SQL statements of rows (#6143)", () => { + const rows: ExportData = { + columns: [ + { name: "id", type: "INTEGER", primaryKey: true }, + { name: "name", type: "TEXT" }, + { name: "note", type: "TEXT" }, + ], + rows: [ + ["2", "O'Hara", null], + ["1", "Ann", "x"], + ], + table: "people", + driver: "postgres", + }; + + it("writes one statement per row, in order, matching rows by the primary key", () => { + expect(exportData("sql", rows)).toBe( + [ + `INSERT INTO people (id, name, note) VALUES (2, 'O''Hara', NULL);`, + `INSERT INTO people (id, name, note) VALUES (1, 'Ann', 'x');`, + ].join("\n"), + ); + expect(exportData("sqlUpdates", rows)).toBe( + [ + `UPDATE people SET name = 'O''Hara', note = NULL WHERE id = 2;`, + `UPDATE people SET name = 'Ann', note = 'x' WHERE id = 1;`, + ].join("\n"), + ); + expect(exportData("sqlDeletes", rows)).toBe( + [`DELETE FROM people WHERE id = 2;`, `DELETE FROM people WHERE id = 1;`].join("\n"), + ); + expect(exportData("where", rows)).toBe(`WHERE (id = 2) OR (id = 1)`); + expect(exportData("where", { ...rows, rows: rows.rows.slice(1) })).toBe(`WHERE id = 1`); + }); + + it("matches on every column, saying so, when no key is known, and writes IS NULL for a null", () => { + const keyless = { ...rows, columns: rows.columns.map((c) => ({ ...c, primaryKey: false })), rows: [rows.rows[0]!] }; + expect(exportData("sqlDeletes", keyless)).toBe( + `-- No primary key is known: rows are matched on every column.\n` + + `DELETE FROM people WHERE id = 2 AND name = 'O''Hara' AND note IS NULL;`, + ); + // A null key value too. + const nullKey = { ...rows, rows: [[null, "x", "y"]] }; + expect(exportData("sqlDeletes", nullKey)).toBe(`DELETE FROM people WHERE id IS NULL;`); + }); + + it("escapes backslashes for drivers that read them, as SQL Inserts did", () => { + const d: ExportData = { + columns: [{ name: "p", type: "String" }], + rows: [["a\\b'"]], + table: "t", + driver: "clickhouse", + }; + expect(exportData("sql", d)).toBe(`INSERT INTO t (p) VALUES ('a\\\\b''');`); + }); +}); diff --git a/src/features/database/export.ts b/src/features/database/export.ts index 66706aa0f..f801dc91f 100644 --- a/src/features/database/export.ts +++ b/src/features/database/export.ts @@ -7,24 +7,40 @@ import type { DbDriver } from "@/platform/ipc"; import { jsonNumber } from "@/platform/losslessJson"; import { isNumericColumn } from "./Grid"; -import { toCsv, toOneRow, toTsv, type Cell } from "./model"; +import { sqlLiteral, toCsv, toOneRow, toTsv, type Cell } from "./model"; import { quoteIdent } from "./sql/complete"; -export type ExportFormat = "csv" | "tsv" | "json" | "sql" | "markdown" | "onerow"; +export type ExportFormat = + | "csv" + | "tsv" + | "json" + | "sql" + | "sqlUpdates" + | "sqlDeletes" + | "where" + | "markdown" + | "onerow"; + +/** The formats written as SQL (highlighted as SQL in the Export Data preview). */ +export const SQL_FORMATS: ReadonlySet<ExportFormat> = new Set(["sql", "sqlUpdates", "sqlDeletes", "where"]); export const EXPORT_FORMATS: ReadonlyArray<{ id: ExportFormat; label: string; extension: string }> = [ { id: "csv", label: "CSV", extension: "csv" }, { id: "tsv", label: "TSV", extension: "tsv" }, { id: "json", label: "JSON", extension: "json" }, { id: "sql", label: "SQL Inserts", extension: "sql" }, + { id: "sqlUpdates", label: "SQL Updates", extension: "sql" }, + { id: "sqlDeletes", label: "SQL Deletes", extension: "sql" }, + { id: "where", label: "Where Clause", extension: "sql" }, { id: "markdown", label: "Markdown", extension: "md" }, { id: "onerow", label: "One-Row", extension: "txt" }, ]; export interface ExportData { - columns: ReadonlyArray<{ name: string; type: string }>; + /** `primaryKey` columns identify a row in SQL Updates, SQL Deletes and Where Clause. */ + columns: ReadonlyArray<{ name: string; type: string; primaryKey?: boolean }>; rows: ReadonlyArray<readonly Cell[]>; - /** Target of SQL inserts (the query's table, when it reads one). */ + /** Target of SQL statements (the query's table, when it reads one). */ table: string; driver: DbDriver; } @@ -89,16 +105,11 @@ export function exportData( }); return rows.length ? `[\n${rows.join(",\n")}\n]` : "[]"; } - case "sql": { - const literal = (v: Cell, i: number) => - v === null - ? "NULL" - : numeric[i] && Number.isFinite(Number(v)) - ? v - : `'${(d.driver === "clickhouse" || d.driver === "snowflake" ? v.replace(/\\/g, "\\\\") : v).replace(/'/g, "''")}'`; - const head = `INSERT INTO ${quoteIdent(d.table, d.driver)} (${names.map((n) => quoteIdent(n, d.driver)).join(", ")}) VALUES`; - return d.rows.map((r) => `${head} (${r.map(literal).join(", ")});`).join("\n"); - } + case "sql": + case "sqlUpdates": + case "sqlDeletes": + case "where": + return sqlStatements(format, d, numeric); case "markdown": { const cell = (v: Cell) => (v ?? "").replace(/\|/g, "\\|").replace(/\r?\n/g, " "); const t = laidOut(d, options); @@ -115,3 +126,41 @@ export function exportData( return toOneRow(d.rows, (c) => numeric[c]!); } } + +/** + * SQL Inserts, Updates, Deletes and the Where Clause of the rows, one statement per row in + * their order. A row is identified by its primary key columns; with none known, by every + * column, which the text says first. + */ +function sqlStatements(format: ExportFormat, d: ExportData, numeric: readonly boolean[]): string { + const ident = (name: string) => quoteIdent(name, d.driver); + const names = d.columns.map((c) => ident(c.name)); + const literal = (v: Cell | undefined, i: number) => sqlLiteral(v ?? null, numeric[i]!, d.driver); + const table = ident(d.table); + if (format === "sql") + return d.rows + .map((r) => `INSERT INTO ${table} (${names.join(", ")}) VALUES (${r.map(literal).join(", ")});`) + .join("\n"); + const keys = d.columns.flatMap((c, i) => (c.primaryKey ? [i] : [])); + const match = keys.length ? keys : names.map((_, i) => i); + const where = (r: readonly Cell[]) => + match.map((i) => (r[i] == null ? `${names[i]} IS NULL` : `${names[i]} = ${literal(r[i], i)}`)).join(" AND "); + const note = keys.length || !d.rows.length ? "" : "-- No primary key is known: rows are matched on every column.\n"; + if (format === "where") { + if (!d.rows.length) return ""; + const body = d.rows.length === 1 ? where(d.rows[0]!) : d.rows.map((r) => `(${where(r)})`).join(" OR "); + return `${note}WHERE ${body}`; + } + if (format === "sqlDeletes") return note + d.rows.map((r) => `DELETE FROM ${table} WHERE ${where(r)};`).join("\n"); + // Updates set the other columns (every column when no key is known). + const set = keys.length ? names.flatMap((_, i) => (keys.includes(i) ? [] : [i])) : match; + return ( + note + + d.rows + .map( + (r) => + `UPDATE ${table} SET ${set.map((i) => `${names[i]} = ${literal(r[i], i)}`).join(", ")} WHERE ${where(r)};`, + ) + .join("\n") + ); +} diff --git a/src/features/database/model.ts b/src/features/database/model.ts index 21827dcaa..592be24f2 100644 --- a/src/features/database/model.ts +++ b/src/features/database/model.ts @@ -12,7 +12,7 @@ import type { DataSource, } from "@/platform/ipc"; import type { SshConfigValid } from "@/platform/remoteSettings"; -import { blankSnowflake, vendorOf, vendorOfScheme } from "./vendors"; +import { DUCKDB_JDBC_PREFIX, blankSnowflake, vendorOf, vendorOfScheme } from "./vendors"; export type Cell = string | null; @@ -30,9 +30,18 @@ export function toTsv(header: readonly string[] | null, rows: ReadonlyArray<read * single-quoted with `'` doubled. `numeric(c)` decides quoting per column. */ export function toOneRow(rows: ReadonlyArray<readonly Cell[]>, numeric: (col: number) => boolean): string { - const literal = (v: Cell, c: number) => - v === null ? "NULL" : numeric(c) && Number.isFinite(Number(v)) ? v : `'${v.replace(/'/g, "''")}'`; - return rows.flatMap((r) => r.map(literal)).join(", "); + return rows.flatMap((r) => r.map((v, c) => sqlLiteral(v, numeric(c)))).join(", "); +} + +/** + * A value as an SQL literal: NULL, a number unquoted in a numeric column, else single-quoted + * with `'` doubled (and `\\` doubled for drivers that read backslash escapes in strings). + */ +export function sqlLiteral(v: Cell, numeric: boolean, driver?: DbDriver): string { + if (v === null) return "NULL"; + if (numeric && Number.isFinite(Number(v))) return v; + const escaped = driver === "clickhouse" || driver === "snowflake" ? v.replace(/\\/g, "\\\\") : v; + return `'${escaped.replace(/'/g, "''")}'`; } /** RFC 4180 CSV; NULL is an empty field. */ @@ -410,11 +419,17 @@ function snowflakeParameter(source: Partial<DataSource>, name: string, value: st /** * Data Source from URL (and the General tab's URL field): `postgres://user:pass@host:5432/db`, * `mysql://…`, `mariadb://…`, wire-compatible products (`redshift://`, `tidb://`…), the - * `jdbc:` forms of those, `jdbc:sqlite:path` / `sqlite:path`. SSL parameters fill the - * SSL tab, other parameters become driver properties. Null when the URL names no supported driver. + * `jdbc:` forms of those, `jdbc:sqlite:path` / `sqlite:path` and `jdbc:duckdb:`. + * DuckDB keeps the explicit JDBC URL. For native drivers, SSL parameters fill + * the SSL tab and other parameters become driver properties. */ export function parseSourceUrl(raw: string): { source: Partial<DataSource>; password: string | null } | null { - const url = raw.trim().replace(/^jdbc:/i, ""); + const trimmed = raw.trim(); + if (trimmed.startsWith(DUCKDB_JDBC_PREFIX)) { + if (/[\r\n]/.test(trimmed)) return null; + return { source: { driver: "jdbc", vendor: "duckdb", url: trimmed, urlOnly: true }, password: null }; + } + const url = trimmed.replace(/^jdbc:/i, ""); const sqlite = /^sqlite3?:(?:\/\/)?(.+)$/i.exec(url); if (sqlite) { const file = sqlite[1]!.replace(/^\/([A-Za-z]:)/, "$1"); diff --git a/src/features/database/modifyTableGroups.test.tsx b/src/features/database/modifyTableGroups.test.tsx new file mode 100644 index 000000000..5dcef856e --- /dev/null +++ b/src/features/database/modifyTableGroups.test.tsx @@ -0,0 +1,112 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { fireEvent, render, screen, within } from "@testing-library/react"; +import { ObjectDialogs } from "./ObjectDialogs"; +import { detailsKey, openDialog, useDatabase } from "./store"; + +const column = (name: string, dataType: string, primaryKey = false) => ({ + name, + dataType, + nullable: !primaryKey, + default: null, + primaryKey, +}); + +function open() { + useDatabase.setState({ + details: { + [detailsKey("db", "main", "orders")]: { + status: "ok", + value: { + columns: [column("id", "integer", true), column("customer_id", "integer"), column("note", "text")], + indexes: [{ name: "orders_customer", unique: false, columns: ["customer_id"] }], + foreignKeys: [ + { + schema: "main", + table: "orders", + columns: ["customer_id"], + refSchema: "main", + refTable: "customers", + refColumns: ["id"], + }, + ], + triggers: [], + }, + }, + }, + } as never); + openDialog({ kind: "modifyTable", id: "db", schema: "main", table: "orders" }); + render(<ObjectDialogs />); +} + +const rows = (group: string) => + within(screen.getByRole("group", { name: group })) + .queryAllByRole("option") + .map((o) => o.textContent); + +afterEach(() => useDatabase.setState({ dialog: null, details: {}, sources: [] } as never)); + +describe("Modify Table's list (DataGrip)", () => { + it("groups the columns, keys, foreign keys and indexes, and filters them by name or type", () => { + open(); + expect(rows("Columns")).toEqual(["idinteger", "customer_idinteger", "notetext"]); + expect(rows("Keys")).toEqual(["PRIMARY KEY(id)"]); + expect(rows("Foreign Keys")).toEqual(["(customer_id)→ customers (id)"]); + expect(rows("Indexes")).toEqual(["orders_customer(customer_id)"]); + // No triggers: no group. + expect(screen.queryByRole("group", { name: "Triggers" })).toBeNull(); + + // A group collapses from its header. + fireEvent.mouseDown(within(screen.getByRole("group", { name: "Indexes" })).getByText("Indexes")); + expect(rows("Indexes")).toEqual([]); + + fireEvent.change(screen.getByRole("textbox", { name: "Filter columns" }), { target: { value: "TEXT" } }); + expect(rows("Columns")).toEqual(["notetext"]); + expect(screen.queryByRole("group", { name: "Foreign Keys" })).toBeNull(); + + fireEvent.change(screen.getByRole("textbox", { name: "Filter columns" }), { target: { value: "customer" } }); + expect(rows("Columns")).toEqual(["customer_idinteger"]); + expect(rows("Foreign Keys")).toEqual(["(customer_id)→ customers (id)"]); + }); + + it("keeps Keys on the primary key as edited in Create Table", () => { + openDialog({ kind: "modifyTable", id: "db", schema: "main", table: null }); + render(<ObjectDialogs />); + expect(rows("Keys")).toEqual(["PRIMARY KEY(id)"]); + fireEvent.click(screen.getByRole("button", { name: "Add Column" })); + fireEvent.click(screen.getByRole("checkbox", { name: "Primary key" })); + expect(rows("Keys")).toEqual(["PRIMARY KEY(id, column_2)"]); + }); + + it("reads and edits the table's and the columns' comments where the engine keeps them", () => { + useDatabase.setState({ + sources: [{ id: "pg", name: "pg", driver: "postgres" }], + details: { + [detailsKey("pg", "public", "orders")]: { + status: "ok", + value: { + comment: "Customer orders", + columns: [column("id", "integer", true), { ...column("note", "text"), comment: "Free text" }], + indexes: [], + foreignKeys: [], + triggers: [], + }, + }, + }, + } as never); + openDialog({ kind: "modifyTable", id: "pg", schema: "public", table: "orders", focusColumn: "note" }); + render(<ObjectDialogs />); + expect(screen.getByLabelText("Comment:")).toHaveProperty("value", "Customer orders"); + expect(screen.getByLabelText("Column comment")).toHaveProperty("value", "Free text"); + fireEvent.change(screen.getByLabelText("Column comment"), { target: { value: "" } }); + fireEvent.change(screen.getByLabelText("Comment:"), { target: { value: "Orders" } }); + const preview = document.body.textContent ?? ""; + expect(preview).toContain("comment on table public.orders is 'Orders';"); + expect(preview).toContain("comment on column public.orders.note is null;"); + }); + + it("has no comment fields on an engine without comments", () => { + open(); + expect(screen.queryByLabelText("Comment:")).toBeNull(); + expect(screen.queryByLabelText("Column comment")).toBeNull(); + }); +}); diff --git a/src/features/database/objects.test.ts b/src/features/database/objects.test.ts index 56664a9e2..103dab9e2 100644 --- a/src/features/database/objects.test.ts +++ b/src/features/database/objects.test.ts @@ -8,6 +8,8 @@ import { canModifyTable, createDatabaseSql, createSchemaSql, + commentsSupported, + createTableCommentSql, createTableSql, draftOf, dropDatabaseSql, @@ -188,6 +190,7 @@ describe("database object SQL", () => { notNull: false, default: "0", primaryKey: false, + comment: "", dropped: false, }); expect(alterTableSql("sqlite", "main", "users", "people", d)).toEqual([ @@ -209,6 +212,71 @@ describe("database object SQL", () => { }); }); +describe("table and column comments", () => { + const commented = [col("id", "INTEGER", { primaryKey: true }), col("note", "TEXT", { comment: "Free text" })]; + + it("sets, changes and clears comments per engine", () => { + const p = commented.map(draftOf); + p[0] = { ...p[0]!, comment: "Order's id" }; + p[1] = { ...p[1]!, comment: "" }; + const table = { original: "", value: "Orders" }; + expect(alterTableSql("postgres", "public", "t", "t", p, table)).toEqual([ + "comment on table public.t is 'Orders';", + "comment on column public.t.id is 'Order''s id';", + "comment on column public.t.note is null;", + ]); + expect(alterTableSql("oracle", "HR", "T", "T", p, { original: "Old", value: "" })).toEqual([ + "comment on table HR.T is '';", + "comment on column HR.T.\"id\" is 'Order''s id';", + "comment on column HR.T.\"note\" is '';", + ]); + expect(alterTableSql("snowflake", "HR", "T", "T", p, { original: "Old", value: "" })).toEqual([ + "alter table HR.T unset comment;", + "comment on column HR.T.\"id\" is 'Order''s id';", + 'alter table HR.T alter column "note" unset comment;', + ]); + // MySQL keeps a column's comment in its definition. + expect(alterTableSql("mysql", "app", "t", "t", p, { original: "", value: "a\\b" })).toEqual([ + "alter table app.t change column id id INTEGER comment 'Order''s id';", + "alter table app.t change column note note TEXT;", + "alter table app.t comment = 'a\\\\b';", + ]); + expect(alterTableSql("sqlite", "main", "t", "t", p, table)).toEqual([]); + }); + + it("keeps an unchanged comment, and comments a renamed column by its new name", () => { + const p = commented.map(draftOf); + expect(alterTableSql("postgres", "public", "t", "t", p, { original: "Orders", value: "Orders" })).toEqual([]); + // A MySQL change of type keeps the column's comment. + p[1] = { ...p[1]!, dataType: "varchar(40)" }; + expect(alterTableSql("mysql", "app", "t", "t", p)).toEqual([ + "alter table app.t change column note note varchar(40) comment 'Free text';", + ]); + p[1] = { ...commented.map(draftOf)[1]!, name: "body", comment: "Body" }; + expect(alterTableSql("postgres", "public", "t", "renamed", p)).toEqual([ + "alter table public.t rename column note to body;", + "comment on column public.t.body is 'Body';", + "alter table public.t rename to renamed;", + ]); + }); + + it("comments a new table", () => { + const d = commented.map((c) => ({ ...draftOf(c, 0), original: null })); + expect(createTableSql("mysql", "app", "t", d, "Orders")).toBe( + "create table app.t\n(\n id INTEGER,\n note TEXT comment 'Free text',\n primary key (id)\n)\ncomment = 'Orders';\n", + ); + expect(createTableCommentSql("mysql", "app", "t", d, "Orders")).toEqual([]); + expect(createTableCommentSql("postgres", "public", "t", d, "Orders")).toEqual([ + "comment on table public.t is 'Orders';", + "comment on column public.t.note is 'Free text';", + ]); + expect(createTableCommentSql("postgres", "public", "t", d, "")).toEqual([ + "comment on column public.t.note is 'Free text';", + ]); + expect(commentsSupported("sqlite")).toBe(false); + }); +}); + describe("oracle object SQL", () => { const emp = [col("ID", "NUMBER", { primaryKey: true, nullable: false }), col("NAME", "VARCHAR2(40)")]; const d = emp.map(draftOf); @@ -248,6 +316,7 @@ describe("oracle object SQL", () => { notNull: false, default: "SYSDATE", primaryKey: false, + comment: "", dropped: false, } satisfies ColumnDraft); expect(alterTableSql("oracle", "HR", "EMPLOYEES", "EMPLOYEES", p)).toEqual([ @@ -344,6 +413,7 @@ describe("snowflake object SQL", () => { notNull: false, default: "CURRENT_DATE", primaryKey: false, + comment: "", dropped: false, } satisfies ColumnDraft); expect(alterTableSql("snowflake", "HR", "EMP", "STAFF", p)).toEqual([ diff --git a/src/features/database/objects.ts b/src/features/database/objects.ts index 4ca5c1224..083ba03d0 100644 --- a/src/features/database/objects.ts +++ b/src/features/database/objects.ts @@ -305,6 +305,8 @@ export interface ColumnDraft { /** SQL expression; empty for none. */ default: string; primaryKey: boolean; + /** Empty for none. */ + comment: string; dropped: boolean; } @@ -317,6 +319,7 @@ export function draftOf(c: DbColumnInfo, key: number): ColumnDraft { notNull: !c.nullable, default: c.default ?? "", primaryKey: c.primaryKey, + comment: c.comment ?? "", dropped: false, }; } @@ -335,21 +338,95 @@ function columnDefinition(driver: DbDriver, c: ColumnDraft): string { let s = `${ident(driver, c.name)} ${c.dataType.trim() || fallback}`; if (c.default.trim()) s += ` default ${c.default.trim()}`; if (c.notNull && driver !== "clickhouse") s += " not null"; + // MySQL keeps a column's comment in its definition: `change column` without it drops the comment. + if (driver === "mysql" && c.comment) s += ` comment ${commentLiteral(driver, c.comment)}`; return s; } +/** Engines whose table and column comments the Modify Table dialog reads and edits. */ +export function commentsSupported(driver: DbDriver): boolean { + return driver === "postgres" || driver === "mysql" || driver === "oracle" || driver === "snowflake"; +} + +/** A comment as a string literal (MySQL and Snowflake read backslash escapes). */ +function commentLiteral(driver: DbDriver, text: string): string { + const escaped = driver === "mysql" || driver === "snowflake" ? text.replace(/\\/g, "\\\\") : text; + return `'${escaped.replace(/'/g, "''")}'`; +} + +/** A table comment as the dialog started (`original`) and as edited. */ +export interface CommentEdit { + original: string; + value: string; +} + +/** + * The statements setting the table's comment and its columns' (`comment on …` where the + * engine has it; MySQL's column comments are part of the definition, see `columnDefinition`). + * Columns are named as they end up; the table as it is (a rename comes after). + */ +function commentSql( + driver: DbDriver, + schema: string, + table: string, + columns: readonly ColumnDraft[], + comment: CommentEdit | undefined, +): string[] { + if (!commentsSupported(driver)) return []; + const q = qualifiedName(driver, schema, table); + const out: string[] = []; + if (comment && comment.value !== comment.original) { + const v = comment.value; + if (driver === "mysql") out.push(`alter table ${q} comment = ${commentLiteral(driver, v)};`); + else if (!v && driver === "snowflake") out.push(`alter table ${q} unset comment;`); + else out.push(`comment on table ${q} is ${v || driver !== "postgres" ? commentLiteral(driver, v) : "null"};`); + } + if (driver === "mysql") return out; + for (const c of columns) { + const name = c.name.trim() || c.original?.name; + if (c.dropped || !name || c.comment === (c.original?.comment ?? "")) continue; + const col = ident(driver, name); + if (!c.comment && driver === "snowflake") out.push(`alter table ${q} alter column ${col} unset comment;`); + else + out.push( + `comment on column ${q}.${col} is ${c.comment || driver !== "postgres" ? commentLiteral(driver, c.comment) : "null"};`, + ); + } + return out; +} + /** `create table` for New › Table. */ export function createTableSql( driver: DbDriver, schema: string, name: string, columns: readonly ColumnDraft[], + comment = "", ): string { const live = columns.filter((c) => !c.dropped && c.name.trim()); const keys = live.filter((c) => c.primaryKey).map((c) => ident(driver, c.name)); const items = live.map((c) => ` ${columnDefinition(driver, c)}`); if (keys.length && driver !== "clickhouse") items.push(` primary key (${keys.join(", ")})`); - return `create table ${qualifiedName(driver, schema, name)}\n(\n${items.join(",\n")}\n)${driver === "clickhouse" ? "\nengine = MergeTree\norder by tuple()" : ""};\n`; + const options = + driver === "clickhouse" + ? "\nengine = MergeTree\norder by tuple()" + : driver === "mysql" && comment + ? `\ncomment = ${commentLiteral(driver, comment)}` + : ""; + return `create table ${qualifiedName(driver, schema, name)}\n(\n${items.join(",\n")}\n)${options};\n`; +} + +/** The `comment on` statements following New › Table's `create table` (MySQL takes them inline). */ +export function createTableCommentSql( + driver: DbDriver, + schema: string, + name: string, + columns: readonly ColumnDraft[], + comment: string, +): string[] { + if (driver === "mysql") return []; + const live = columns.filter((c) => !c.dropped && c.name.trim()); + return commentSql(driver, schema, name, live, { original: "", value: comment }); } /** Whether `alterTableSql` can express changing column `c` (SQLite only renames, adds and drops). */ @@ -360,7 +437,7 @@ export function canAlterColumn(driver: DbDriver, c: ColumnDraft): boolean { /** * The statements turning the table `table` into `name` with `columns` * (Modify Table): renames, added / dropped columns, and — PostgreSQL / MySQL / - * Oracle / Snowflake — type, nullability and default changes. + * Oracle / Snowflake — type, nullability, default and comment changes, and the table's comment. */ export function alterTableSql( driver: DbDriver, @@ -368,6 +445,7 @@ export function alterTableSql( table: string, name: string, columns: readonly ColumnDraft[], + comment?: CommentEdit, ): string[] { if (!canModifyTable(driver)) return []; const out: string[] = []; @@ -391,7 +469,10 @@ export function alterTableSql( } const renamed = c.name.trim() && c.name !== o.name; const changed = - c.dataType.trim() !== o.dataType || c.notNull !== !o.nullable || c.default.trim() !== (o.default ?? "").trim(); + c.dataType.trim() !== o.dataType || + c.notNull !== !o.nullable || + c.default.trim() !== (o.default ?? "").trim() || + (driver === "mysql" && c.comment !== (o.comment ?? "")); if (driver === "mysql" && (renamed || changed)) { out.push(`alter table ${q()} change column ${ident(driver, o.name)} ${columnDefinition(driver, c)};`); continue; @@ -439,6 +520,7 @@ export function alterTableSql( `alter table ${q()} alter column ${col} ${c.default.trim() ? `set default ${c.default.trim()}` : "drop default"};`, ); } + out.push(...commentSql(driver, schema, table, columns, comment)); // Renamed last: the column statements above name the table as it was. if (name.trim() && name.trim() !== table) out.push(renameSql(driver, { kind: "table", schema, name: table }, name.trim())); diff --git a/src/features/database/treeMenu.ts b/src/features/database/treeMenu.ts index e5d27ee88..878e2a3aa 100644 --- a/src/features/database/treeMenu.ts +++ b/src/features/database/treeMenu.ts @@ -1,9 +1,10 @@ /** Menus of the Database tool window, laid out like IDEA's (New ▸, Copy/Paste ▸, SQL Scripts ▸ …). */ import { choosePath } from "@/platform/choosePath"; +import { tx } from "@/platform/i18n"; import type { MenuItem } from "@/ui"; import { notifications } from "@/workbench/contributions"; import { fileSourceName, parseSourceUrl } from "./model"; -import { VENDORS, vendorPreset } from "./vendors"; +import { VENDORS, vendorById, vendorPreset } from "./vendors"; import { nodeTarget, objectOf, tableOf, type DbNode } from "./nodes"; import { SCRIPT_LABELS, canDrop, canModifyTable, canRename, type ScriptKind } from "./objects"; import { @@ -32,12 +33,14 @@ const act = ( const sep: MenuItem = { kind: "separator" }; -async function sqliteFromFile() { - const file = await choosePath({ directory: false, title: "SQLite Database File" }); - if (typeof file === "string") openSourceDialog(null, { driver: "sqlite", file, name: fileSourceName(file) }); +async function sourceFromFile() { + const file = await choosePath({ directory: false, title: tx("Database File") }); + if (file === null) return; + const preset = /\.duckdb$/i.test(file) ? vendorPreset(vendorById("duckdb")!) : { driver: "sqlite" as const }; + openSourceDialog(null, { ...preset, file, name: fileSourceName(file) }); } -/** New ▸ Data Source ▸ — the drivers the backend speaks and wire-compatible products, A–Z like IDEA's. */ +/** New ▸ Data Source ▸ — built-in and JDBC presets, A–Z. */ function dataSourceItems(): MenuItem[] { return [ { @@ -49,7 +52,7 @@ function dataSourceItems(): MenuItem[] { run: () => openSourceDialog(null, vendorPreset(v)), })), }, - { label: "Data Source from File…", icon: "folder", run: () => void sqliteFromFile() }, + { label: "Data Source from File…", icon: "folder", run: () => void sourceFromFile() }, { label: "Data Source from URL…", icon: "external-link", run: () => openDialog({ kind: "sourceUrl" }) }, { label: "Import from Clipboard", icon: "paste", run: () => void sourceFromClipboard() }, ]; diff --git a/src/features/database/vendors.ts b/src/features/database/vendors.ts index 4ace9fe16..c2d0d7951 100644 --- a/src/features/database/vendors.ts +++ b/src/features/database/vendors.ts @@ -1,6 +1,6 @@ /** - * Data source types of New ▸ Data Source: the three drivers the backend speaks, - * and products that speak their wire protocol (a preset of port, icon and URL scheme). + * Data source types of New ▸ Data Source: built-in drivers, wire-compatible + * products, and JDBC presets. */ import type { DataSource, DbDriver, DbSnowflake, DbSslMode } from "@/platform/ipc"; @@ -17,6 +17,9 @@ export interface DbVendor { ssl?: DbSslMode; } +export const DUCKDB_JDBC_CLASS = "org.duckdb.DuckDBDriver"; +export const DUCKDB_JDBC_PREFIX = "jdbc:duckdb:"; + export const VENDORS: readonly DbVendor[] = [ { id: "aurora-mysql", label: "Amazon Aurora MySQL", driver: "mysql", port: 3306, icon: "db-aurora", scheme: "mysql" }, { @@ -45,6 +48,7 @@ export const VENDORS: readonly DbVendor[] = [ scheme: "postgresql", }, { id: "jdbc", label: "Custom JDBC", driver: "jdbc", port: null, icon: "database", scheme: "" }, + { id: "duckdb", label: "DuckDB", driver: "jdbc", port: null, icon: "db-duckdb", scheme: "duckdb" }, { id: "greenplum", label: "Greenplum", driver: "postgres", port: 5432, icon: "db-greenplum", scheme: "postgresql" }, { id: "mariadb", label: "MariaDB", driver: "mysql", port: 3306, icon: "db-mariadb", scheme: "mariadb" }, { diff --git a/src/features/debugger/__tests__/remote.test.ts b/src/features/debugger/__tests__/remote.test.ts index 83b89dc51..564a2eee6 100644 --- a/src/features/debugger/__tests__/remote.test.ts +++ b/src/features/debugger/__tests__/remote.test.ts @@ -177,6 +177,16 @@ describe("remote attach requests", () => { }); }); + it("Attach to Node.js reconnects automatically only when the option is on", () => { + const attach = (params: Record<string, string> = {}) => + JSON.parse(remoteAttachConfig(configOf(nodeRemoteType, params), "/p")!.extraJson!); + expect(attach()).not.toHaveProperty("restart"); + expect(attach({ restart: "true" })).toMatchObject({ restart: true, port: 9229 }); + expect(nodeRemoteType.fields.find((f) => f.key === "restart")!.control).toBe("checkbox"); + const hint = nodeRemoteType.fields.find((f) => f.key === "hint")!; + expect(hint.value!({ restart: "true", port: "9230" })).toBe("nodemon --inspect=0.0.0.0:9230 app.js"); + }); + it("PHP Remote Debug defaults to port 9003 and shows the xdebug command line", () => { expect(configOf(phpRemoteType).params).toEqual({ port: "9003" }); const field = phpRemoteType.fields.find((f) => f.key === "hint")!; @@ -215,6 +225,14 @@ describe("remote attach requests", () => { for (const t of REMOTE_TYPES.filter((x) => x !== phpRemoteType)) expect(remoteWaitingNote(configOf(t))).toBeNull(); }); + it("Attach to Node.js with Reconnect automatically says it waits once its process has ended", () => { + const rc = configOf(nodeRemoteType, { restart: "true", port: "9230" }); + expect(remoteWaitingNote(rc, true)).toBe("Waiting to reconnect to Node.js on localhost:9230"); + // The first attach (or one that never connects) isn't a reconnect. + expect(remoteWaitingNote(rc)).toBeNull(); + expect(remoteWaitingNote(configOf(nodeRemoteType), true)).toBeNull(); + }); + it("start-the-remote-side hints follow the port", () => { expect(remote.delveServerCommand({ port: "4000" })).toBe( "dlv debug --headless --listen=:4000 --api-version=2 --accept-multiclient", diff --git a/src/features/debugger/__tests__/sessionAdoption.test.ts b/src/features/debugger/__tests__/sessionAdoption.test.ts index aad838eaf..ce3069749 100644 --- a/src/features/debugger/__tests__/sessionAdoption.test.ts +++ b/src/features/debugger/__tests__/sessionAdoption.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { LaunchConfig } from "@/platform/ipc"; +import type { LaunchConfig, RunConfig } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { handleDebugEvent, resetSessions, startSession, useDebug } from "../state"; @@ -83,3 +83,36 @@ describe("sessions of a window whose backend changes", () => { expect(useDebug.getState().console).toEqual({}); }); }); + +describe("Attach to Node.js with Reconnect automatically", () => { + const attach = (restart: boolean) => + startSession( + { ...launch, name: "Attach", request: "attach" }, + { runConfig: { name: "Attach", kind: "node-remote", params: restart ? { restart: "true" } : {} } as RunConfig }, + ); + const ended = (id: number) => handleDebugEvent(id, { kind: "terminated" }); + + it("shows the restarted process in place of the finished one, with its output", async () => { + expect(await attach(true)).toBe(1); + child(2, 1, "Remote Process [100]"); + handleDebugEvent(2, { kind: "output", category: "stderr", output: "Error: boom\n" }); + ended(2); + // nodemon's next process has another pid. + child(3, 1, "Remote Process [200]"); + handleDebugEvent(3, { kind: "output", category: "stdout", output: "listening\n" }); + const { sessions } = useDebug.getState(); + expect(Object.keys(sessions).map(Number)).toEqual([1, 3]); + expect(sessions[1]?.status).toBe("running"); + await vi.waitFor(() => + expect(useDebug.getState().console[3]?.map((l) => l.text)).toEqual(["Error: boom\n", "listening\n"]), + ); + }); + + it("keeps finished processes of other sessions", async () => { + await attach(false); + child(2, 1, "Remote Process [0]"); + ended(2); + child(3, 1, "Remote Process [0]"); + expect(Object.keys(useDebug.getState().sessions).map(Number)).toEqual([1, 2, 3]); + }); +}); diff --git a/src/features/debugger/java.ts b/src/features/debugger/java.ts index a7127f5b6..ba04ea6ca 100644 --- a/src/features/debugger/java.ts +++ b/src/features/debugger/java.ts @@ -180,7 +180,11 @@ export async function javaLaunchConfig( const agentNote = await remoteJavaAgentNote(rc); if (agentNote) preparation?.report?.(agentNote); // The host adds JetBrains Runtime's flag for it, or says in the console why the session runs without. - const enhanced = rc.params?.enhancedClassRedefinition === "true" ? { enhancedClassRedefinition: true } : {}; + const enhanced = { + ...(rc.params?.enhancedClassRedefinition === "true" ? { enhancedClassRedefinition: true } : {}), + // A plugin executor's launch ("Debug with …"): the host adds that plugin's Java agent. + ...(rc.executor ? { executor: rc.executor } : {}), + }; if (kotlin) { return { name: rc.name, diff --git a/src/features/debugger/remote.ts b/src/features/debugger/remote.ts index 405c13452..addae965f 100644 --- a/src/features/debugger/remote.ts +++ b/src/features/debugger/remote.ts @@ -196,8 +196,9 @@ export const pythonRemoteType: RunConfigTypeContribution = { // --------------------------------------------------------------------------- // Attach to Node.js (inspector) +/** How to start the remote side; with Reconnect automatically, under nodemon, which restarts it on save. */ export function nodeInspectCommand(p: Params): string { - return `node --inspect=0.0.0.0:${portOf(p, 9229)} app.js`; + return `${p.restart === "true" ? "nodemon" : "node"} --inspect=0.0.0.0:${portOf(p, 9229)} app.js`; } export const nodeRemoteType: RunConfigTypeContribution = { @@ -218,6 +219,12 @@ export const nodeRemoteType: RunConfigTypeContribution = { mono: true, value: nodeInspectCommand, }, + { + key: "restart", + label: "Reconnect automatically", + control: "checkbox", + hint: "When the process restarts (nodemon, node --watch, tsx watch), attach to it again with the same breakpoints", + }, localRootField, remoteRootField("e.g. /usr/src/app"), ], @@ -407,6 +414,7 @@ export function remoteAttachConfig(rc: RunConfig, root: string): LaunchConfig | port: portOf(p, 9229), ...(map ? { localRoot: map.local, remoteRoot: map.remote } : {}), skipFiles: skip ? ["<node_internals>/**", "**/node_modules/**"] : [], + ...(p.restart === "true" ? { restart: true } : {}), }); case PHP_REMOTE: return requestBase(rc, "php-debug", root, "launch", { @@ -418,10 +426,23 @@ export function remoteAttachConfig(rc: RunConfig, root: string): LaunchConfig | } } -/** What a session of `rc` shows while nothing is suspended, when it waits for the debuggee to connect. */ -export function remoteWaitingNote(rc: Pick<RunConfig, "kind" | "params"> | undefined): string | null { +/** Attach to Node.js with Reconnect automatically: js-debug attaches each restarted process in a new child session. */ +export const reconnects = (rc: Pick<RunConfig, "kind" | "params"> | undefined) => + rc?.kind === NODE_REMOTE && rc.params?.restart === "true"; + +/** + * What a session of `rc` shows while nothing is suspended, when it waits for the debuggee to connect. + * `reconnecting`: the process it attached to has ended and none is attached yet. + */ +export function remoteWaitingNote( + rc: Pick<RunConfig, "kind" | "params"> | undefined, + reconnecting = false, +): string | null { + const p = rc?.params ?? {}; + if (reconnects(rc)) + return reconnecting ? tx`Waiting to reconnect to Node.js on ${serverAddress(hostOf(p), portOf(p, 9229))}` : null; if (rc?.kind !== PHP_REMOTE) return null; - return tx`Listening for Xdebug on port ${portOf(rc.params ?? {}, 9003)}`; + return tx`Listening for Xdebug on port ${portOf(p, 9003)}`; } /** What a Remote JVM Debug configuration attaches to (before the listen mode relay). */ diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 34d6efd3c..7ef33d4ba 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -58,6 +58,7 @@ import { missingAdapter } from "./missingAdapter"; import { startFailureMessage } from "./startFailure"; import { evaluateWithImports, forgetImports } from "./classImports"; import { JAVA_ADAPTER } from "./java"; +import { reconnects } from "./remote"; import { isTracing, markTraceStop } from "./streams/streamStore"; export type SessionStatus = "starting" | "running" | "paused" | "stopping" | "terminated"; @@ -360,8 +361,20 @@ function ownSession(id: DebugSessionId, event: DebugEvent): DebugSession | null // of a forgotten session, though its id may be one (another backend numbers from 1 again). if (owned.has(id) && event.kind !== "started") return null; if (event.kind === "started" && event.parent != null) { - if (!st.sessions[event.parent]) return null; - return adoptSession(id, { name: event.name, adapter: event.adapter, parent: event.parent }); + const parent = st.sessions[event.parent]; + if (!parent) return null; + const child = adoptSession(id, { name: event.name, adapter: event.adapter, parent: event.parent }); + // A process attached again after its restart takes the finished one's place (one tab, its output kept). + if (reconnects(rootOf(parent).runConfig)) + for (const s of Object.values(st.sessions)) { + if (s.parent !== event.parent || isLive(s)) continue; + flushConsoleOutput(); + useDebug.setState((cur) => ({ + console: { ...cur.console, [id]: [...(cur.console[s.id] ?? []), ...(cur.console[id] ?? [])] }, + })); + removeSession(s.id); + } + return child; } if (pendingStarts === 0) return null; provisional.add(id); diff --git a/src/features/debugger/ui/DebugToolWindow.tsx b/src/features/debugger/ui/DebugToolWindow.tsx index 1b1563f5e..7731ec7cf 100644 --- a/src/features/debugger/ui/DebugToolWindow.tsx +++ b/src/features/debugger/ui/DebugToolWindow.tsx @@ -440,6 +440,12 @@ function FramesPane({ session }: { session: DebugSession }) { if (list.current && selectedRow.current) revealVertically(list.current, selectedRow.current); }, [items]); const paused = session.status === "paused"; + const rootId = rootOf(session).id; + // js-debug attaches each process in a child session: an ended one and none live while it waits for a restart. + const reconnecting = useDebug((s) => { + const processes = Object.values(s.sessions).filter((c) => c.parent === rootId); + return processes.length > 0 && !processes.some(isLive); + }); const onKeyDown = (e: KeyboardEvent) => { if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return; const frames = items.flatMap((i) => (i.kind === "frame" ? [i.frame] : [])); @@ -475,7 +481,7 @@ function FramesPane({ session }: { session: DebugSession }) { <div className={styles.note}> {session.status === "terminated" ? tx("Finished") - : (remoteWaitingNote(rootOf(session).runConfig) ?? tx("Running…"))} + : (remoteWaitingNote(rootOf(session).runConfig, reconnecting) ?? tx("Running…"))} </div> )} {stopNote(session) && <div className={styles.note}>{stopNote(session)}</div>} diff --git a/src/features/notebook/CellEditor.test.tsx b/src/features/notebook/CellEditor.test.tsx index e4cc0c585..53a31dcb5 100644 --- a/src/features/notebook/CellEditor.test.tsx +++ b/src/features/notebook/CellEditor.test.tsx @@ -4,6 +4,8 @@ import type * as Ipc from "@/platform/ipc"; import { render } from "@testing-library/react"; import { EditorView } from "@codemirror/view"; import type { IdeEvent, NotebookSnapshot } from "@/bindings"; +import { focusedCellEditor } from "@/editor/api"; +import { getContext, useContextKeys } from "@/platform/context"; import { CellEditor } from "./CellEditor"; import { NotebookSession, notebookBackend } from "./session"; @@ -25,7 +27,10 @@ vi.mock("@tauri-apps/api/core", async (original) => ({ onmessage = (_event: unknown) => {}; }, })); -afterEach(() => kernelListeners.clear()); +afterEach(() => { + kernelListeners.clear(); + useContextKeys.setState({}, true); +}); function snapshot(): NotebookSnapshot { return { @@ -88,6 +93,37 @@ describe("cell editor focus", () => { }); }); +describe("cell editor context keys", () => { + it("publishes the editor keys and the focused view while the cell editor has focus", async () => { + useContextKeys.setState({}, true); + const session = makeSession(); + await session.load(); + const { container, unmount } = render( + <CellEditor session={session} id="cell-a" source="typed text" type="code" frozen={false} />, + ); + const view = EditorView.findFromDOM(container.querySelector(".cm-editor")!)!; + expect(focusedCellEditor()).toBeNull(); + expect(getContext().textEditorActive).toBeFalsy(); + view.contentDOM.focus(); + await vi.waitFor(() => { + expect(focusedCellEditor()).toBe(view); + expect(getContext().textEditorActive).toBe(true); + expect(getContext().editorTextFocus).toBe(true); + }); + view.contentDOM.blur(); + await vi.waitFor(() => { + expect(focusedCellEditor()).toBeNull(); + expect(getContext().textEditorActive).toBe(false); + expect(getContext().editorTextFocus).toBe(false); + }); + view.contentDOM.focus(); + await vi.waitFor(() => expect(focusedCellEditor()).toBe(view)); + unmount(); + expect(focusedCellEditor()).toBeNull(); + await session.close(); + }); +}); + describe("cell editor theme", () => { const cssRules = () => [...document.styleSheets].reduce((n, sheet) => n + sheet.cssRules.length, 0); diff --git a/src/features/notebook/CellEditor.tsx b/src/features/notebook/CellEditor.tsx index 7b2f2bde6..f84f8220c 100644 --- a/src/features/notebook/CellEditor.tsx +++ b/src/features/notebook/CellEditor.tsx @@ -12,14 +12,23 @@ import { import { defaultKeymap, indentWithTab } from "@codemirror/commands"; import { bracketMatching, indentOnInput, syntaxHighlighting } from "@codemirror/language"; import type { NotebookCellDoc } from "@/bindings"; -import { adjacentEditor, cellEditorExtensions, embeddedEditorExtensions, externalHistory } from "@/editor/api"; +import { + _setFocusedCellEditor, + adjacentEditor, + cellEditorExtensions, + embeddedEditorExtensions, + externalHistory, + focusedCellEditor, +} from "@/editor/api"; import { openideaTheme } from "@/editor/core/cm/theme"; import { openideaHighlightStyle } from "@/editor/core/cm/highlight"; import { selectionMarks } from "@/editor/core/cm/selectionMarks"; import { seamlessSelection } from "@/editor/core/cm/selectionLayer"; +import { multiCaretMouse } from "@/editor/core/cm/multiCaret"; import { findLanguageDescription, loadSupport } from "@/editor/core/cm/languages"; import { tooltipBounds } from "@/editor/core/cm/setup"; import { tx } from "@/platform/i18n"; +import { setContext } from "@/platform/context"; import type { CellReveal, NotebookSession } from "./session"; import styles from "./Notebook.module.css"; @@ -74,6 +83,7 @@ export function CellEditor({ drawSelection(), selectionMarks, seamlessSelection(), + multiCaretMouse, highlightActiveLine(), highlightSpecialChars(), bracketMatching(), @@ -123,8 +133,16 @@ export function CellEditor({ ), EditorView.updateListener.of((update) => { session.editors.set(id, update.state); - // The session puts the caret back here after a backend undo/redo (session.ts history). - if (update.focusChanged) session.focusedCell = update.view.hasFocus ? id : null; + if (update.focusChanged) { + // The session puts the caret back here after a backend undo/redo (session.ts history). + session.focusedCell = update.view.hasFocus ? id : null; + // While the cell editor has focus the notebook publishes the editor context keys a + // text tab does, and the cell's view is what editor actions resolve (@/editor/api, + // re-read by editor/core's publishContext and the action resolvers). + _setFocusedCellEditor(update.view.hasFocus ? update.view : null); + setContext("textEditorActive", update.view.hasFocus); + setContext("editorTextFocus", update.view.hasFocus); + } if (update.docChanged && update.transactions.some((tr) => !tr.annotation(external))) { session.edit({ type: "setSource", cell: id, source: update.state.doc.toString() }); } @@ -150,6 +168,7 @@ export function CellEditor({ alive = false; session.editors.set(id, editor.state); if (session.focusedCell === id) session.focusedCell = null; + if (focusedCellEditor() === editor) _setFocusedCellEditor(null); view.current = null; editor.destroy(); }; diff --git a/src/features/notebook/Notebook.module.css b/src/features/notebook/Notebook.module.css index 2dd536a70..72e8476bc 100644 --- a/src/features/notebook/Notebook.module.css +++ b/src/features/notebook/Notebook.module.css @@ -189,7 +189,7 @@ min-height: 80px; max-height: 600px; border: 1px solid var(--border); - background: white; + background: var(--bg-editor, var(--bg-app)); resize: vertical; box-sizing: border-box; } diff --git a/src/features/notebook/OutputView.tsx b/src/features/notebook/OutputView.tsx index 06ff326a8..df5fc6137 100644 --- a/src/features/notebook/OutputView.tsx +++ b/src/features/notebook/OutputView.tsx @@ -1,7 +1,8 @@ -import { useLayoutEffect, useMemo, useRef } from "react"; +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import Anser from "anser"; import { tx } from "@/platform/i18n"; import { openExternalUrl } from "@/platform/openUrl"; +import { subscribeTheme } from "@/platform/themeWatch"; import { editorService, notifications } from "@/workbench/contributions"; import { resolveLink } from "@/features/viewers/markdown/render"; import { @@ -10,6 +11,7 @@ import { markdownRoot, resolveMarkdownAttachments, staticOutputDocument, + type OutputPalette, } from "./security"; import { mimeText, object, own } from "./outputs"; import styles from "./Notebook.module.css"; @@ -43,8 +45,34 @@ function AnsiText({ text, error = false }: { text: string; error?: boolean }) { ); } +/** The output frame's colours: the notebook's own background and the theme's text and table colours. */ +function readPalette(): OutputPalette { + const root = document.documentElement; + const css = getComputedStyle(root); + const token = (name: string) => css.getPropertyValue(name).trim(); + return { + fg: token("--fg"), + bg: token("--bg-editor") || token("--bg-app"), + border: token("--border-strong"), + headerBg: token("--bg-elev"), + scheme: root.dataset.theme === "light" ? "light" : "dark", + }; +} + +/** Tracks the active theme so output frames follow it. */ +function useOutputPalette(): OutputPalette { + const [palette, setPalette] = useState(readPalette); + useEffect(() => { + const update = () => setPalette(readPalette()); + update(); + return subscribeTheme(update); + }, []); + return palette; +} + function StaticHtml({ html, title }: { html: string; title: string }) { - const srcDoc = useMemo(() => staticOutputDocument(html), [html]); + const palette = useOutputPalette(); + const srcDoc = useMemo(() => staticOutputDocument(html, palette), [html, palette]); return ( <iframe className={styles.outputFrame} sandbox="" referrerPolicy="no-referrer" srcDoc={srcDoc} title={title} /> ); diff --git a/src/features/notebook/security.test.ts b/src/features/notebook/security.test.ts index e8282a3ec..21ac9b467 100644 --- a/src/features/notebook/security.test.ts +++ b/src/features/notebook/security.test.ts @@ -40,6 +40,18 @@ describe("static notebook output sanitization", () => { expect(document.querySelector("body div")?.hasAttribute("style")).toBe(false); }); + it("themes the output frame from the supplied palette and ignores unsafe colour values", () => { + const palette = { fg: "#d1d3d9", bg: "#191a1c", border: "#40434a", headerBg: "#212326", scheme: "dark" as const }; + const html = staticOutputDocument("<table><tr><th>a</th></tr></table>", palette); + expect(html).toContain("background:#191a1c"); + expect(html).toContain("color-scheme:dark"); + expect(html).toContain("border:1px solid #40434a"); + const hostile = staticOutputDocument("<p>x</p>", { ...palette, bg: "red;}</style><script>alert(1)</script>" }); + expect(hostile).not.toContain("<script>"); + expect(hostile).toContain("background:white"); + expect(staticOutputDocument("<p>x</p>")).toContain("background:white"); + }); + it("retains safe SVG chart paint, local definitions and raster images but removes active/external SVG", () => { const url = sanitizedSvgUrl(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"> <script>alert(1)</script><foreignObject><div>host markup</div></foreignObject> diff --git a/src/features/notebook/security.ts b/src/features/notebook/security.ts index ace73bef8..e8c7522c8 100644 --- a/src/features/notebook/security.ts +++ b/src/features/notebook/security.ts @@ -217,9 +217,25 @@ function htmlRoot(html: string, markdown = false): HTMLElement { return root; } -export function staticOutputDocument(html: string): string { +export interface OutputPalette { + fg: string; + bg: string; + border: string; + headerBg: string; + scheme: "light" | "dark"; +} + +const CSS_COLOR = /^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%/]+\)|[a-z]+)$/i; + +export function staticOutputDocument(html: string, palette?: OutputPalette): string { const root = htmlRoot(html); - return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${OUTPUT_CSP}"><style>body{margin:8px;font:13px system-ui,sans-serif;color:#222;background:white;overflow-wrap:anywhere}table{border-collapse:collapse;max-width:100%}th,td{padding:4px 8px;border:1px solid #ddd;text-align:left}pre{white-space:pre-wrap}img{max-width:100%;height:auto}</style></head><body>${root.innerHTML}</body></html>`; + const safe = (c: string, fallback: string) => (CSS_COLOR.test(c.trim()) ? c.trim() : fallback); + const fg = safe(palette?.fg ?? "", "#222"); + const bg = safe(palette?.bg ?? "", "white"); + const border = safe(palette?.border ?? "", "#ddd"); + const headerBg = safe(palette?.headerBg ?? "", "transparent"); + const scheme = palette?.scheme ?? "light"; + return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${OUTPUT_CSP}"><style>body{margin:8px;font:13px system-ui,sans-serif;color:${fg};background:${bg};color-scheme:${scheme};overflow-wrap:anywhere}table{border-collapse:collapse;max-width:100%}th,td{padding:4px 8px;border:1px solid ${border};text-align:left}th{background:${headerBg}}pre{white-space:pre-wrap}img{max-width:100%;height:auto}</style></head><body>${root.innerHTML}</body></html>`; } const markdown = new Marked({ gfm: true }).use(mathExtension()); diff --git a/src/features/plugins/PluginsPage.tsx b/src/features/plugins/PluginsPage.tsx index ac67a1902..3b7893690 100644 --- a/src/features/plugins/PluginsPage.tsx +++ b/src/features/plugins/PluginsPage.tsx @@ -15,6 +15,7 @@ import type { MarketPlugin, PluginIcon as PluginIconData, PluginInfo, + PluginNetSetting, PluginStatus, } from "@/bindings"; import { @@ -56,6 +57,8 @@ import { setAllInstalledEnabled, setPluginCapability, revokePluginNetHost, + approvePluginNetSetting, + forgetPluginNetSetting, setPluginEnabled, uninstallPlugin, updateAllPlugins, @@ -567,7 +570,7 @@ function ProgramPermission({ plugin, cap, disabled }: { plugin: PluginInfo; cap: } function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean }) { - if (plugin.capabilities.length === 0 && plugin.netHosts.length === 0) { + if (plugin.capabilities.length === 0 && plugin.netHosts.length === 0 && plugin.netSettings.length === 0) { return ( <div className={styles.muted}> <T>No special permissions.</T> @@ -600,10 +603,73 @@ function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean }) {plugin.netHosts.map((host) => ( <NetHostRow key={host} plugin={plugin} host={host} disabled={busy || !confirmed} /> ))} + {plugin.netSettings.map((entry) => ( + <NetSettingRow + key={`${entry.setting}:${entry.http}`} + plugin={plugin} + entry={entry} + disabled={busy || !confirmed} + /> + ))} </ul> ); } +/** A host a `net:setting:<key>` grant approved in Settings, or the pending one to approve. */ +function NetSettingRow({ + plugin, + entry, + disabled, +}: { + plugin: PluginInfo; + entry: PluginNetSetting; + disabled: boolean; +}) { + const label = entry.http ? `net.http:setting:${entry.setting}` : `net:setting:${entry.setting}`; + const pending = entry.pending; + return ( + <li className={styles.capabilityItem}> + <div className={styles.capabilityHeader}> + <span className={styles.mono}>{label}</span> + <Badge tone={RISK_LABEL.medium.tone}>{RISK_LABEL.medium.label}</Badge> + </div> + {pending ? ( + <> + <p className={styles.capabilityDescription}> + {entry.http + ? tx`The “${entry.setting}” setting now holds ${entry.pending}. Approving connects over unencrypted HTTP.` + : tx`The “${entry.setting}” setting now holds ${entry.pending}. Approve it to let the plugin connect.`} + </p> + <div className={styles.programPermission}> + <Button + disabled={disabled} + onClick={() => void approvePluginNetSetting(plugin.id, entry.setting, entry.http, pending)} + > + {tx("Approve")} + </Button> + </div> + </> + ) : ( + entry.host && ( + <> + <p className={styles.capabilityDescription}> + {tx`The host set in the “${entry.setting}” setting, on any port. Remove it to leave it unapproved.`} + </p> + <div className={styles.programPermission}> + <Button + disabled={disabled} + onClick={() => void forgetPluginNetSetting(plugin.id, entry.setting, entry.http)} + > + {tx("Remove")} + </Button> + </div> + </> + ) + )} + </li> + ); +} + /** The agent a `java.agent` grant loads: jar, args, and any contributed JVM options. */ function JavaAgentDetail({ plugin, cap, disabled }: { plugin: PluginInfo; cap: CapabilityInfo; disabled: boolean }) { const agent = plugin.javaAgent; diff --git a/src/features/plugins/__tests__/plugins.test.tsx b/src/features/plugins/__tests__/plugins.test.tsx index bc155eb18..8a133a86f 100644 --- a/src/features/plugins/__tests__/plugins.test.tsx +++ b/src/features/plugins/__tests__/plugins.test.tsx @@ -80,6 +80,7 @@ function plugin(partial: Partial<PluginInfo> & Pick<PluginInfo, "id">): PluginIn hasCode: true, capabilities: [], netHosts: [], + netSettings: [], contributions: [], activation: [], warnings: [], @@ -1784,6 +1785,42 @@ describe("marketplace", () => { }, ); + it("lists the host of a net:setting grant with revoke and a pending one with approve", async () => { + const user = userEvent.setup(); + const base = createMemoryPluginsBackend([ + plugin({ + id: "p", + name: "GitLab bridge", + netSettings: [ + { setting: "server", http: false, host: "jira.corp.example", pending: null }, + { setting: "server", http: true, host: null, pending: "intra.example" }, + ], + capabilities: [ + { id: "net:setting:server", risk: "medium", description: "Connect", optional: true, granted: true }, + { id: "net.http:setting:server", risk: "medium", description: "Connect", optional: true, granted: true }, + ], + }), + ]); + const approveNetSetting = vi.fn((id: string, setting: string, http: boolean, host: string) => + base.approveNetSetting(id, setting, http, host), + ); + const forgetNetSetting = vi.fn((id: string, setting: string, http: boolean) => + base.forgetNetSetting(id, setting, http), + ); + setPluginsBackend({ ...base, approveNetSetting, forgetNetSetting }); + render(<PluginsPage initialTab="installed" />); + + await screen.findAllByText("net:setting:server"); + expect(screen.getByText(/The host set in the “server” setting, on any port\./)).toBeInTheDocument(); + expect(screen.getByText(/The “server” setting now holds intra\.example\./)).toBeInTheDocument(); + expect(screen.getByText(/Approving connects over unencrypted HTTP\./)).toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "Approve" })); + await waitFor(() => expect(approveNetSetting).toHaveBeenCalledWith("p", "server", true, "intra.example")); + // Both transports are approved now; the HTTPS row comes first. + await user.click((await screen.findAllByRole("button", { name: "Remove" }))[0]!); + await waitFor(() => expect(forgetNetSetting).toHaveBeenCalledWith("p", "server", false)); + }); + it("shows the Java agent next to the java.agent permission", async () => { setPluginsBackend( createMemoryPluginsBackend([ diff --git a/src/features/plugins/__tests__/serviceMenus.test.tsx b/src/features/plugins/__tests__/serviceMenus.test.tsx new file mode 100644 index 000000000..346d79bcd --- /dev/null +++ b/src/features/plugins/__tests__/serviceMenus.test.tsx @@ -0,0 +1,196 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { PluginInfo } from "@/bindings"; +import { registerAction } from "@/platform/actions"; +import type { RunConfig } from "@/platform/ipc"; +import { + provideNotificationService, + runExecutors, + type NotificationService, + type ServiceContext, +} from "@/workbench/contributions"; +import { executorLaunch, pluginExecutors, syncPluginExecutors } from "../executors"; +import { defineBuiltinUiPoints } from "../points"; +import { clearUiContributions, syncUiContributions } from "../projection"; +import { usePlugins } from "../store"; +import { pluginServiceActions, pluginServiceMenuItems } from "../uiPoints"; + +let undefinePoints: () => void = () => {}; + +beforeEach(() => { + undefinePoints = defineBuiltinUiPoints(); +}); + +afterEach(() => { + clearUiContributions(); + undefinePoints(); + usePlugins.setState({ plugins: [] }); +}); + +const plugin = (extra: Partial<PluginInfo> = {}) => + ({ id: "hot", name: "Hot Reload Tools", status: "active", enabled: true, icon: null, ...extra }) as PluginInfo; + +const spring: ServiceContext = { + provider: "runConfigurations", + id: "app", + kind: "spring-boot", + name: "App", + running: false, + runConfigurationId: "app", +}; +const container: ServiceContext = { provider: "docker", id: "c1", kind: "docker-container", name: "db", running: true }; + +const config = (extra: Partial<RunConfig> = {}): RunConfig => ({ + id: "app", + name: "App", + kind: "spring-boot", + command: "java", + args: [], + cwd: null, + env: {}, + detected: false, + isTest: false, + debugAdapter: "java-debug", + ...extra, +}); + +describe("plugin Services menus", () => { + it("offers entries whose when holds for every selected service, with the services as argument", async () => { + const run = vi.fn(); + const offs = [ + registerAction({ id: "plugin.hot.reload", title: "Reload", icon: "refresh", run: ({ arg }) => run(arg) }), + registerAction({ id: "plugin.hot.logs", title: "Logs", run: () => {} }), + ]; + syncUiContributions( + [ + { + pluginId: "hot", + point: "menus", + key: "services.context/reload", + decl: { + menu: "services.context", + command: "reload", + submenu: "Hot Reload", + when: "serviceKind == 'spring-boot' && !serviceRunning", + }, + }, + { + pluginId: "hot", + point: "menus", + key: "services.context/logs", + decl: { menu: "services.context", command: "logs", submenu: "Hot Reload", when: "serviceRunning" }, + }, + { + pluginId: "hot", + point: "menus", + key: "services.toolbar/reload", + decl: { menu: "services.toolbar", command: "reload", when: "serviceSelectionCount == 1" }, + }, + ], + [plugin()], + ); + + const json = (services: ServiceContext[]) => + JSON.stringify({ services: services.map((s) => ({ ...s, runConfigurationId: s.runConfigurationId ?? null })) }); + const arg = json([spring]); + expect(JSON.parse(arg)).toEqual({ + services: [ + { + provider: "runConfigurations", + id: "app", + kind: "spring-boot", + name: "App", + running: false, + runConfigurationId: "app", + }, + ], + }); + // One visible entry of the submenu: no nesting. + expect(pluginServiceMenuItems([spring])).toEqual([{ kind: "action", action: "plugin.hot.reload", arg }]); + expect(pluginServiceMenuItems([container])).toEqual([ + { kind: "action", action: "plugin.hot.logs", arg: json([container]) }, + ]); + // Mixed selection: an entry shows only when it holds for each service. + expect(pluginServiceMenuItems([spring, container])).toEqual([]); + const running = { ...spring, running: true }; + expect(pluginServiceMenuItems([running])).toEqual([ + { kind: "action", action: "plugin.hot.logs", arg: json([running]) }, + ]); + + const [button, ...rest] = pluginServiceActions([spring]); + expect(rest).toEqual([]); + expect(button).toMatchObject({ id: "plugin.hot.reload", title: "Reload", icon: "refresh" }); + button!.run(); + await vi.waitFor(() => expect(run).toHaveBeenCalledWith(arg)); + expect(pluginServiceActions([spring, { ...spring, id: "other" }])).toEqual([]); + offs.forEach((off) => off()); + }); + + it("drops entries whose command is not registered", () => { + syncUiContributions( + [ + { + pluginId: "hot", + point: "menus", + key: "services.context/gone", + decl: { menu: "services.context", command: "gone" }, + }, + ], + [plugin()], + ); + expect(pluginServiceMenuItems([spring])).toEqual([]); + }); +}); + +describe("plugin executors", () => { + const agent = (executor: string | null, approved = true) => ({ + fileName: "hot.jar", + args: null, + vmOptions: [], + jdk: null, + approved, + executor, + }); + + it("lists enabled plugins whose agent names an executor", () => { + expect( + pluginExecutors([ + plugin({ javaAgent: agent("Hot Reload") }), + plugin({ id: "plain", javaAgent: agent(null) }), + plugin({ id: "off", enabled: false, javaAgent: agent("Off") }), + ]), + ).toEqual([{ pluginId: "hot", pluginName: "Hot Reload Tools", title: "Hot Reload", approved: true }]); + }); + + it("registers Run and Debug with <title> for JVM configurations", async () => { + usePlugins.setState({ plugins: [plugin({ javaAgent: agent("Hot Reload") })] }); + const stop = syncPluginExecutors(); + const mine = runExecutors().filter((e) => e.id.startsWith("plugin:hot")); + expect(mine.map((e) => [e.id, e.label("App"), e.debug ?? false])).toEqual([ + ["plugin:hot", "Run 'App' with Hot Reload", false], + ["plugin:hot:debug", "Debug 'App' with Hot Reload", true], + ]); + const [run, debug] = mine; + expect(run!.supports(config())).toBe(true); + expect(run!.supports(config({ kind: "maven" }))).toBe(false); + expect(debug!.supports(config({ kind: "jar-application", debugAdapter: null }))).toBe(true); + expect(debug!.supports(config({ kind: "junit" }))).toBe(false); + const plan = await run!.prepare(config()); + expect(plan?.launch).toMatchObject({ id: "app", executor: "hot" }); + + // Disabled: gone. + usePlugins.setState({ plugins: [plugin({ enabled: false, javaAgent: agent("Hot Reload") })] }); + expect(runExecutors().some((e) => e.id.startsWith("plugin:hot"))).toBe(false); + stop(); + }); + + it("asks for the permission, and refuses run targets, instead of launching without the agent", () => { + const notify = vi.fn(); + provideNotificationService({ notify } as unknown as NotificationService); + const e = { pluginId: "hot", pluginName: "Hot Reload Tools", title: "Hot Reload", approved: false }; + expect(executorLaunch(e, config())).toBeNull(); + expect(notify.mock.calls[0]![0]).toMatchObject({ title: "Hot Reload needs the Java agent of Hot Reload Tools" }); + expect(executorLaunch({ ...e, approved: true }, config({ target: "ssh-1" }))).toBeNull(); + expect(notify.mock.calls[1]![0]).toMatchObject({ title: "Cannot run 'App' with Hot Reload" }); + expect(executorLaunch({ ...e, approved: true }, config())).toMatchObject({ executor: "hot" }); + }); +}); diff --git a/src/features/plugins/__tests__/settings.test.tsx b/src/features/plugins/__tests__/settings.test.tsx index 1ec351f05..9909b3725 100644 --- a/src/features/plugins/__tests__/settings.test.tsx +++ b/src/features/plugins/__tests__/settings.test.tsx @@ -1,9 +1,12 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import type { ComponentType } from "react"; +import { MessagesHost } from "@/workbench/messages"; import { SettingsFormContext, useSettingsPages } from "@/workbench/contributions"; import { useSettingsFormFor } from "@/features/settings/components/context"; import { + applySettings, closeSettings, openSettings, resetPage, @@ -64,6 +67,11 @@ const declaration: SettingsDecl = { { key: "name", title: "Name", type: "string", default: "" }, ], }, + { + id: "server", + title: "Server", + properties: [{ key: "server", title: "Server", type: "string", default: "" }], + }, ], }; let dispose: () => void; @@ -174,6 +182,151 @@ it("does not run a command when applying settings fails", async () => { expect(run).not.toHaveBeenCalled(); }); +it("refuses a host value that is not a host when it is staged", async () => { + const { usePlugins } = await import("../store"); + act(() => { + usePlugins.setState({ + plugins: [ + { + id: "example.helper", + name: "Helper", + capabilities: [ + { id: "net:setting:server", risk: "medium", description: "Connect", optional: true, granted: true }, + ], + } as never, + ], + }); + }); + render(<Harness page="server" />); + const field = screen.getByRole("textbox", { name: "Server" }); + fireEvent.change(field, { target: { value: "not a host!" } }); + await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent(/Enter a host/)); + expect(stagedValue(useSettingsDialog.getState(), "global", "plugins")).toEqual({}); + fireEvent.change(field, { target: { value: "jira.corp.example" } }); + await waitFor(() => expect(screen.queryByRole("alert")).toBeNull()); + expect(stagedValue(useSettingsDialog.getState(), "global", "plugins")).toMatchObject({ + "example.helper": { server: "jira.corp.example" }, + }); +}); + +it("asks about the host when a net:setting value is applied; deny leaves it unapproved", async () => { + const user = userEvent.setup(); + const approveNetSetting = vi.fn(async () => ({}) as never); + setPluginsBackend({ ...createMemoryPluginsBackend([]), approveNetSetting }); + const { usePlugins } = await import("../store"); + const plugin = { + id: "example.helper", + name: "Helper", + version: "1.0.0", + description: "", + authors: [], + homepage: null, + changeNotes: null, + icon: null, + javaAgent: null, + source: "installed", + path: "/plugins/helper", + enabled: true, + status: "active", + error: null, + hasCode: true, + capabilities: [{ id: "net:setting:server", risk: "medium", description: "Connect", optional: true, granted: true }], + netHosts: [], + netSettings: [], + contributions: [], + activation: [], + warnings: [], + stats: { + activations: 0, + activationMs: 0, + calls: 0, + errors: 0, + maxCallMs: 0, + p95CallMs: 0, + slowCalls: 0, + crashes: 0, + reclaims: 0, + }, + publisher: null, + previousVersion: null, + depends: [], + dependents: [], + extensionPoints: [], + }; + act(() => { + usePlugins.setState({ plugins: [plugin as never] }); + }); + render( + <> + <MessagesHost /> + <Harness page="server" /> + </>, + ); + fireEvent.change(screen.getByRole("textbox", { name: "Server" }), { + target: { value: "https://jira.corp.example/" }, + }); + await waitFor(() => + expect(stagedValue(useSettingsDialog.getState(), "global", "plugins")).toMatchObject({ + "example.helper": { server: "https://jira.corp.example/" }, + }), + ); + // Applying asks; the answer resolves the apply. + const applying = applySettings(); + await user.click(await screen.findByRole("button", { name: "Deny" })); + await act(() => applying); + await waitFor(() => expect(approveNetSetting).not.toHaveBeenCalled()); + // The value itself was saved; only the approval was withheld. + expect(useProject.getState().settings).toMatchObject({ + plugins: { "example.helper": { server: "https://jira.corp.example/" } }, + }); +}); + +it("records the approval when the applied host is allowed, and forgets it when cleared", async () => { + const user = userEvent.setup(); + const approveNetSetting = vi.fn(async () => ({}) as never); + const forgetNetSetting = vi.fn(async () => ({}) as never); + setPluginsBackend({ ...createMemoryPluginsBackend([]), approveNetSetting, forgetNetSetting }); + const { usePlugins } = await import("../store"); + const plugin = { + id: "example.helper", + name: "Helper", + netSettings: [], + capabilities: [{ id: "net:setting:server", risk: "medium", description: "Connect", optional: true, granted: true }], + }; + act(() => { + usePlugins.setState({ plugins: [plugin as never] }); + }); + render( + <> + <MessagesHost /> + <Harness page="server" /> + </>, + ); + fireEvent.change(screen.getByRole("textbox", { name: "Server" }), { target: { value: "jira.corp.example" } }); + await waitFor(() => + expect(stagedValue(useSettingsDialog.getState(), "global", "plugins")).toMatchObject({ + "example.helper": { server: "jira.corp.example" }, + }), + ); + const applying = applySettings(); + await user.click(await screen.findByRole("button", { name: "Allow" })); + await act(() => applying); + await waitFor(() => + expect(approveNetSetting).toHaveBeenCalledWith("example.helper", "server", false, "jira.corp.example"), + ); + + // Clearing the value forgets the approval without a dialog. + fireEvent.change(screen.getByRole("textbox", { name: "Server" }), { target: { value: "" } }); + await waitFor(() => + expect(stagedValue(useSettingsDialog.getState(), "global", "plugins")).toMatchObject({ + "example.helper": { server: "" }, + }), + ); + await act(() => applySettings()); + await waitFor(() => expect(forgetNetSetting).toHaveBeenCalledWith("example.helper", "server", false)); + expect(screen.queryByText(/Allow Helper to connect/)).toBeNull(); +}); + it("lists the plugin's declared secrets on its settings page", async () => { setPluginsBackend({ ...createMemoryPluginsBackend([]), diff --git a/src/features/plugins/__tests__/webviewKeys.test.tsx b/src/features/plugins/__tests__/webviewKeys.test.tsx index c88901000..99289b988 100644 --- a/src/features/plugins/__tests__/webviewKeys.test.tsx +++ b/src/features/plugins/__tests__/webviewKeys.test.tsx @@ -3,6 +3,8 @@ import { render, waitFor } from "@testing-library/react"; import type { PluginInfo } from "@/bindings"; import { registerAction } from "@/platform/actions"; import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap"; +import { installFocusScopeTracking } from "@/ui/focusScope"; +import { installFocusTracking } from "@/workbench/focus"; import { createMemoryPluginsBackend, setPluginsBackend } from "../backend"; import { usePlugins } from "../store"; import { FRAME_TAG } from "../views/frame"; @@ -141,4 +143,55 @@ describe("keys a plugin web view passes on", () => { await flush(); expect(run).not.toHaveBeenCalled(); }); + + it("reports iframe focus to the host only while the frame actually holds window focus", async () => { + const hasFocus = vi.spyOn(document, "hasFocus").mockReturnValue(true); + setPluginsBackend({ ...createMemoryPluginsBackend([]), webPageUrl: async () => "about:blank" }); + usePlugins.setState({ + plugins: [{ id: "k8s.view", hasCode: false, enabled: true, capabilities: [] } as unknown as PluginInfo], + }); + const calls: Array<[string | null, boolean]> = []; + const disposeScope = installFocusScopeTracking(); + const disposeFocus = installFocusTracking((id, editor) => calls.push([id, editor])); + try { + const view = render( + <section data-toolwindow="plugin.k8s.view" data-focus-scope=""> + <WebView pluginId="k8s.view" view="v" label="Kubernetes" /> + </section>, + ); + const frame = await waitFor(() => { + const found = view.container.querySelector("iframe"); + expect(found).not.toBeNull(); + return found!; + }); + const scope = view.container.querySelector('[data-toolwindow="plugin.k8s.view"]')!; + + // Spoofed focus message while another element has focus is ignored. + window.dispatchEvent( + new MessageEvent("message", { data: { tag: FRAME_TAG, focus: true }, source: frame.contentWindow }), + ); + expect(calls).toEqual([]); + expect(scope).not.toHaveAttribute("data-focus-active"); + + // Ignored when the window itself does not have focus. + frame.focus(); + calls.length = 0; + hasFocus.mockReturnValue(false); + window.dispatchEvent( + new MessageEvent("message", { data: { tag: FRAME_TAG, focus: true }, source: frame.contentWindow }), + ); + expect(calls).toEqual([]); + + // Accepted once the frame is activeElement and the window has focus. + hasFocus.mockReturnValue(true); + window.dispatchEvent( + new MessageEvent("message", { data: { tag: FRAME_TAG, focus: true }, source: frame.contentWindow }), + ); + expect(calls).toEqual([["plugin.k8s.view", false]]); + expect(scope).toHaveAttribute("data-focus-active", ""); + } finally { + disposeFocus(); + disposeScope(); + } + }); }); diff --git a/src/features/plugins/backend.ts b/src/features/plugins/backend.ts index 8c3d523d0..0d2c71f8c 100644 --- a/src/features/plugins/backend.ts +++ b/src/features/plugins/backend.ts @@ -65,6 +65,12 @@ export interface PluginsBackend { pickProgram(): Promise<string | null>; setCapability(id: string, capability: string, granted: boolean): Promise<PluginInfo>; revokeNetHost(id: string, host: string): Promise<PluginInfo>; + /** The host a `net:setting:` grant derives from `value` (a bare host or a URL); an error refuses it. */ + netSettingHost(id: string, setting: string, value: string): Promise<string>; + /** Approves `host` for a `net:setting:` grant; refused when the setting no longer holds it. */ + approveNetSetting(id: string, setting: string, http: boolean, host: string): Promise<PluginInfo>; + /** Drops the approved host of a `net:setting:` grant (revoked, or the setting cleared). */ + forgetNetSetting(id: string, setting: string, http: boolean): Promise<PluginInfo>; /** Validated assets (icon theme mapping and SVGs) whose id starts with `prefix`. */ assets(pluginId: string, prefix: string): Promise<[string, string][]>; /** `language` / `file` / `view` activation events. */ @@ -232,6 +238,9 @@ export const tauriPluginsBackend: PluginsBackend = { pickProgram: () => choosePath({ directory: false, title: tx("Choose plugin executable") }), setCapability: (id, capability, granted) => call(commands.pluginSetCapability(id, capability, granted)), revokeNetHost: (id, host) => call(commands.pluginRevokeNetHost(id, host)), + netSettingHost: (id, setting, value) => call(commands.pluginNetSettingHost(id, setting, value)), + approveNetSetting: (id, setting, http, host) => call(commands.pluginApproveNetSetting(id, setting, http, host)), + forgetNetSetting: (id, setting, http) => call(commands.pluginForgetNetSetting(id, setting, http)), assets: (pluginId, prefix) => call(commands.pluginAssets(pluginId, prefix)), activationEvent: async (kind, value) => { await call(commands.pluginActivationEvent(kind, value)); @@ -481,6 +490,7 @@ function samplePlugins(): PluginInfo[] { error: null, capabilities: [], netHosts: [], + netSettings: [], contributions: [], activation: [], warnings: [], @@ -663,6 +673,38 @@ export function createMemoryPluginsBackend( emit({ type: "commandsChanged" }); return { ...p }; }, + netSettingHost: async (_id, _setting, value) => { + let host = value.trim(); + if (host.includes("://")) + host = host + .replace(/^[a-z][a-z0-9+.-]*:\/\//i, "") + .replace(/[/?#].*$/, "") + .replace(/.*@/, ""); + host = host.replace(/:\d+$/, "").replace(/\.$/, "").toLowerCase(); + if ( + !host || + host.includes("*") || + !/^[a-z0-9.-]+$/.test(host) || + host.split(".").some((l) => !l || /[^a-z0-9-]/.test(l)) + ) + throw new IpcError({ kind: "invalidInput", message: `${value}: not a host (example.com) or a URL` }); + return host; + }, + approveNetSetting: async (id, setting, http, host) => { + const p = find(id); + p.netSettings = [ + ...p.netSettings.filter((n) => n.setting !== setting || n.http !== http), + { setting, http, host, pending: null }, + ]; + emit({ type: "commandsChanged" }); + return { ...p }; + }, + forgetNetSetting: async (id, setting, http) => { + const p = find(id); + p.netSettings = p.netSettings.filter((n) => n.setting !== setting || n.http !== http); + emit({ type: "commandsChanged" }); + return { ...p }; + }, assets: async () => [], activationEvent: async () => {}, catalog: async () => catalog.map((c) => ({ ...c })), diff --git a/src/features/plugins/executors.ts b/src/features/plugins/executors.ts new file mode 100644 index 000000000..fc583f98e --- /dev/null +++ b/src/features/plugins/executors.ts @@ -0,0 +1,139 @@ +/** + * Plugin executors (`executor = "<title>"` on `[[contributes.javaAgents]]`, API 1.18): + * "Run '<config>' with <title>" and "Debug '<config>' with <title>" beside Run and Debug + * for the JVM configurations the agent loads into (the run widget's ⋮ menu, the gutter, + * the context menus' More Run/Debug and the Services tree). The launch carries the + * plugin's id; the host adds that plugin's agent to it, and to no other launch. + */ +import type { PluginInfo } from "@/bindings"; +import { executeAction, registerActions } from "@/platform/actions"; +import { tx } from "@/platform/i18n"; +import type { RunConfig } from "@/platform/ipc"; +import { isRemoteWindow } from "@/platform/remote"; +import { + notifications, + registerRunExecutor, + type ExecutorLaunch, + type RunExecutorContribution, +} from "@/workbench/contributions"; +import { usePlugins } from "./store"; + +/** Configuration kinds whose JVM gets plugin agents (`ide_run::java_agent::KINDS`). */ +const KINDS = ["application", "spring-boot", "jar-application"]; + +export const pluginExecutorId = (pluginId: string, debug: boolean) => `plugin:${pluginId}${debug ? ":debug" : ""}`; + +const actionId = (pluginId: string, debug: boolean) => `pluginExecutor.${pluginId}.${debug ? "debug" : "run"}`; + +export interface PluginExecutor { + pluginId: string; + pluginName: string; + title: string; + /** The agent jar is approved (`java.agent` granted, jar unchanged). */ + approved: boolean; +} + +/** Executors of the enabled plugins that declare one. */ +export function pluginExecutors(plugins: readonly PluginInfo[]): PluginExecutor[] { + return plugins.flatMap((p) => + p.enabled && p.javaAgent?.executor + ? [{ pluginId: p.id, pluginName: p.name, title: p.javaAgent.executor, approved: p.javaAgent.approved }] + : [], + ); +} + +/** What "Run/Debug with <title>" launches: the configuration marked with the plugin's id. */ +export function executorLaunch(e: PluginExecutor, config: RunConfig): RunConfig | null { + if (!e.approved) { + notifications().notify({ + group: "run", + level: "warning", + key: `plugin-executor-${e.pluginId}`, + title: tx`${e.title} needs the Java agent of ${e.pluginName}`, + body: tx`Allow the java.agent permission of ${e.pluginName} in Settings › Plugins, then try again.`, + userInitiated: true, + actions: [{ label: "Plugins…", run: () => void executeAction("plugins.settings") }], + }); + return null; + } + if (config.target) { + notifications().notify({ + group: "run", + level: "warning", + key: `plugin-executor-${e.pluginId}`, + title: tx`Cannot run '${config.name}' with ${e.title}`, + body: tx`Plugin Java agents load only into JVMs started on this machine. Choose “Local machine” under “Run on”.`, + userInitiated: true, + actions: [{ label: "Edit Configuration…", run: () => void executeAction("run.editConfigs", config.id) }], + }); + return null; + } + return { ...config, executor: e.pluginId }; +} + +function executor(e: PluginExecutor, debug: boolean): RunExecutorContribution { + return { + id: pluginExecutorId(e.pluginId, debug), + label: (name) => (debug ? tx`Debug '${name}' with ${e.title}` : tx`Run '${name}' with ${e.title}`), + icon: debug ? "debug" : "run", + action: actionId(e.pluginId, debug), + order: debug ? 101 : 100, + debug, + checksTarget: true, + // All three debug: Application / Spring Boot through the Java debugger, JAR Application through JDWP. + supports: (config) => KINDS.includes(config.kind) && !isRemoteWindow(), + prepare: async (config): Promise<ExecutorLaunch | null> => { + const launch = executorLaunch(e, config); + return launch ? { launch, finished: () => {} } : null; + }, + }; +} + +function register(e: PluginExecutor): () => void { + const disposers = [false, true].flatMap((debug) => [ + registerRunExecutor(executor(e, debug)), + registerActions([ + { + id: actionId(e.pluginId, debug), + title: debug ? tx`Debug with ${e.title}` : tx`Run with ${e.title}`, + description: tx`Launches the selected configuration with the Java agent of ${e.pluginName}`, + category: "Run", + icon: debug ? "debug" : "run", + when: "projectOpen", + run: ({ arg }) => + executeAction("run.withExecutor", { + executor: pluginExecutorId(e.pluginId, debug), + ...(arg && typeof arg === "object" ? arg : {}), + }).then(() => undefined), + }, + ]), + ]); + return () => disposers.forEach((d) => d()); +} + +/** Keeps the executors in line with the installed plugins. */ +export function syncPluginExecutors(): () => void { + const live = new Map<string, { sig: string; dispose: () => void }>(); + const sync = (plugins: readonly PluginInfo[]) => { + const next = new Map(pluginExecutors(plugins).map((e) => [e.pluginId, e])); + for (const [id, entry] of live) { + const e = next.get(id); + if (!e || JSON.stringify(e) !== entry.sig) { + entry.dispose(); + live.delete(id); + } + } + for (const [id, e] of next) { + if (!live.has(id)) live.set(id, { sig: JSON.stringify(e), dispose: register(e) }); + } + }; + sync(usePlugins.getState().plugins); + const unsubscribe = usePlugins.subscribe((s, prev) => { + if (s.plugins !== prev.plugins) sync(s.plugins); + }); + return () => { + unsubscribe(); + for (const entry of live.values()) entry.dispose(); + live.clear(); + }; +} diff --git a/src/features/plugins/index.ts b/src/features/plugins/index.ts index 49eb687f4..210645349 100644 --- a/src/features/plugins/index.ts +++ b/src/features/plugins/index.ts @@ -23,6 +23,7 @@ import { providePluginThemePreviews, startPluginBridge } from "./bridge"; import { ConsentDialogHost, provideConsentDialog } from "./consent"; import { pluginLineMarkerGutter } from "./lineMarkerGutter"; import { startViewUi } from "./uiPoints"; +import { syncPluginExecutors } from "./executors"; import { showInstalledIntellijThemes } from "./intellijThemesDialogStore"; import { startWorkspaceContains } from "./workspaceContains"; import { startPluginDecorations } from "./decorations"; @@ -119,6 +120,8 @@ export function activate(): () => void { startPluginConsoleRules(), // Plugin custom editors (tab kind) and context menu entries. startViewUi((input) => void editorService().openInput(input)), + // "Run/Debug with <title>" of plugins whose Java agent is bound to an executor. + syncPluginExecutors(), startWorkspaceContains(), // Gutter icons from plugins' `line-markers` providers (next to the LSP ones). registerEditorContribution({ id: "plugins.languageFeatures", order: 58, extensions: pluginLanguageVisuals }), diff --git a/src/features/plugins/settings.tsx b/src/features/plugins/settings.tsx index 0facfbe02..a102e1bd8 100644 --- a/src/features/plugins/settings.tsx +++ b/src/features/plugins/settings.tsx @@ -1,6 +1,7 @@ /** IDE-rendered plugin settings; every control edits the dialog's staged form. */ import { useMemo, useRef, useState } from "react"; import { tx, VerbatimTextContext } from "@/platform/i18n"; +import { ask } from "@/workbench/messages"; import { Button, Checkbox, IconButton, Input, Select, T } from "@/ui"; import { registerSettingsPages, useSettingsForm } from "@/workbench/contributions"; import { pluginsBackend } from "./backend"; @@ -236,10 +237,19 @@ function accepts(s: SettingSchema, value: unknown): boolean { function SettingControl({ pluginId, s }: { pluginId: string; s: SettingSchema }) { const [invalid, setInvalid] = useState(false); + const [hostInvalid, setHostInvalid] = useState(false); const form = useSettingsForm(); const all = form.useValue("plugins") as PluginSettings | undefined; const stored = all?.[pluginId]?.[s.key]; const value = accepts(s, stored) ? stored : s.default; + // A `net:setting:<key>` grant takes its host from this setting: the value is + // checked when it is staged, and its host is asked about when it is applied + // (#3809). Only granted transports are asked about. + const transports = netSettingTransports(pluginId, s.key); + const [initialRaw] = useState(() => (typeof stored === "string" ? stored : "")); + const applied = form.useExternal(`net-setting:${s.key}`, initialRaw, (raw) => + applyNetSettingValue(pluginId, s.key, transports, raw), + ); const control = ( <ValueControl s={s} @@ -249,7 +259,28 @@ function SettingControl({ pluginId, s }: { pluginId: string; s: SettingSchema }) setInvalid(!valid); // Keep the chosen value even when it equals the default: false and "" // are real plugin settings, not "remove the override". - if (valid) form.setMapEntry("plugins", [pluginId, s.key], v); + if (!valid) return; + if (!transports.length || typeof v !== "string") { + setHostInvalid(false); + form.setMapEntry("plugins", [pluginId, s.key], v); + if (transports.length && v === null) applied.set(""); // cleared: forget on apply + return; + } + if (v.trim() === "") { + setHostInvalid(false); + form.setMapEntry("plugins", [pluginId, s.key], v); + applied.set(v); // cleared: forget on apply + return; + } + // A host value is refused before it is staged. + void pluginsBackend() + .netSettingHost(pluginId, s.key, v.trim()) + .then(() => { + setHostInvalid(false); + form.setMapEntry("plugins", [pluginId, s.key], v); + applied.set(v); + }) + .catch(() => setHostInvalid(true)); }} /> ); @@ -276,10 +307,76 @@ function SettingControl({ pluginId, s }: { pluginId: string; s: SettingSchema }) <T>The value exceeds this setting’s limits.</T> </p> )} + {hostInvalid && ( + <p role="alert" className={styles.error}> + <T>Enter a host (example.com) or a URL (https://example.com/).</T> + </p> + )} </div> ); } +/** The transports (`false`: HTTPS/loopback, `true`: plain HTTP) of the + * plugin's granted `net:setting:<key>` grants for this settings key. */ +function netSettingTransports(pluginId: string, key: string): boolean[] { + const plugin = usePlugins.getState().plugins.find((p) => p.id === pluginId); + const transports: boolean[] = []; + for (const cap of plugin?.capabilities ?? []) { + const match = /^(net(?:\.http)?):setting:(.+)$/.exec(cap.id); + if (match?.[2] === key && cap.granted) transports.push(match[1] === "net.http"); + } + return transports; +} + +/** + * The value was applied in Settings: the host it names is approved here or + * never — Deny is the default, and a value that arrives any other way stays + * pending in the plugin's permissions. Clearing the setting forgets the + * approval (#3809). + */ +async function applyNetSettingValue( + pluginId: string, + key: string, + transports: boolean[], + raw: unknown, +): Promise<string> { + const value = typeof raw === "string" ? raw.trim() : ""; + const backend = pluginsBackend(); + if (!value || !transports.length) { + for (const http of transports) await backend.forgetNetSetting(pluginId, key, http); + return value; + } + const host = await backend.netSettingHost(pluginId, key, value); + const name = usePlugins.getState().plugins.find((p) => p.id === pluginId)?.name ?? pluginId; + for (const http of transports) { + const entry = usePlugins + .getState() + .plugins.find((p) => p.id === pluginId) + ?.netSettings.find((n) => n.setting === key && n.http === http); + if (entry?.host === host) continue; // the host is already the approved one + const answer = await ask({ + title: tx`Allow ${name} to connect to ${host}?`, + body: [ + tx`This host comes from the plugin's “${key}” setting.`, + " ", + http + ? tx("The connection is unencrypted HTTP: anyone on the network can read it.") + : tx("This allows this exact host on any port; subdomains need separate permission."), + " ", + tx("Deny leaves the host unapproved; you can approve it any time in the plugin's permissions."), + ], + buttons: [ + { id: "allow", label: http ? tx("Allow unencrypted HTTP") : tx("Allow") }, + { id: "deny", label: tx("Deny"), primary: true }, + ], + cancel: false, + icon: "question", + }); + if (answer.button === "allow") await backend.approveNetSetting(pluginId, key, http, host); + } + return value; +} + function PageAction({ pluginId, action }: { pluginId: string; action: SettingsAction }) { const form = useSettingsForm(); const lock = useRef(false); diff --git a/src/features/plugins/store.ts b/src/features/plugins/store.ts index 64d7a585f..06cdd15a5 100644 --- a/src/features/plugins/store.ts +++ b/src/features/plugins/store.ts @@ -211,6 +211,20 @@ export function revokePluginNetHost(id: string, host: string): Promise<boolean> return withBusy(id, tx`Could not revoke ${host} for ${name}`, () => pluginsBackend().revokeNetHost(id, host)); } +export function approvePluginNetSetting(id: string, setting: string, http: boolean, host: string): Promise<boolean> { + const name = nameOf(id); + return withBusy(id, tx`Could not approve the host of the ${setting} setting for ${name}`, () => + pluginsBackend().approveNetSetting(id, setting, http, host), + ); +} + +export function forgetPluginNetSetting(id: string, setting: string, http: boolean): Promise<boolean> { + const name = nameOf(id); + return withBusy(id, tx`Could not revoke the host of the ${setting} setting for ${name}`, () => + pluginsBackend().forgetNetSetting(id, setting, http), + ); +} + export async function refreshCatalog(): Promise<void> { try { usePlugins.setState({ catalog: await pluginsBackend().catalog(), catalogError: null }); diff --git a/src/features/plugins/uiPoints.tsx b/src/features/plugins/uiPoints.tsx index 73d37fdaf..585ecf1f9 100644 --- a/src/features/plugins/uiPoints.tsx +++ b/src/features/plugins/uiPoints.tsx @@ -2,8 +2,8 @@ * Client side of the plugin UI points: declarations the * backend validated, projected onto the workbench's own registries. * - * - `menus`: editor / project view / editor tab context menus, Tools in the main menu, and the - * toolbar above the commit message; + * - `menus`: editor / project view / editor tab context menus, Tools in the main menu, the + * toolbar above the commit message, and the Services tree's context menu and toolbar; * - `keymaps`: default shortcuts below the IDE's (a taken keystroke is dropped); * - `statusBar`: items shown before the code runs (its `set-status-item` with the same id updates them); * - `settings`: a page under Settings › Plugins generated from the schema; @@ -19,7 +19,7 @@ */ import type { PluginInfo } from "@/bindings"; import { registerEditorContribution } from "@/editor/api"; -import { getAction } from "@/platform/actions"; +import { executeAction, getAction } from "@/platform/actions"; import { evaluateWhen, getContext, useContextKeys } from "@/platform/context"; import { tx } from "@/platform/i18n"; import { isMacHost, registerExtensionBindings } from "@/platform/keymap"; @@ -34,9 +34,12 @@ import { registerMenuGroup, registerMenuSlotItem, registerServiceProvider, + registerServiceSelectionItems, registerTextEditorWrapper, type ContextMenuId, type ContributedCommitProblem, + type ServiceContext, + type ServiceItemAction, type ToolWindowAnchor, } from "@/workbench/contributions"; import { pluginsBackend } from "./backend"; @@ -90,7 +93,9 @@ interface MenuDecl { | "editorTab.context" | "viewItem.context" | "tools" - | "commit.message"; + | "commit.message" + | "services.context" + | "services.toolbar"; view?: string | null; command: string; when?: string | null; @@ -180,6 +185,66 @@ export function pluginViewItemMenuItems(pluginId: string, view: string, key: str return flattenSingleGroups(out); } +/** The when keys of one selected service. */ +export function serviceWhenContext(service: ServiceContext, count: number) { + return { + ...getContext(), + serviceProvider: service.provider, + serviceKind: service.kind, + serviceId: service.id, + serviceName: service.name, + serviceRunning: service.running, + runConfigurationId: service.runConfigurationId ?? "", + serviceSelectionCount: count, + }; +} + +/** The command's argument (JSON text, as a plugin command's argument is a string): the selected services. */ +export const servicesArg = (services: readonly ServiceContext[]) => + JSON.stringify({ + services: services.map((s) => ({ + provider: s.provider, + id: s.id, + kind: s.kind, + name: s.name, + running: s.running, + runConfigurationId: s.runConfigurationId ?? null, + })), + }); + +/** Plugin entries of `services.context` / `services.toolbar` whose `when` holds for every selected service. */ +function serviceEntries(menu: "services.context" | "services.toolbar", services: readonly ServiceContext[]) { + return [...contextItems.values()].flatMap(({ pluginId, decl }) => { + if (decl.menu !== menu) return []; + if (!services.every((s) => evaluateWhen(decl.when ?? undefined, serviceWhenContext(s, services.length)))) return []; + const action = pluginActionId(pluginId, decl.command); + return getAction(action) ? [{ pluginId, decl, action }] : []; + }); +} + +export function pluginServiceMenuItems(services: readonly ServiceContext[]): MenuItem[] { + const out: MenuItem[] = []; + const groups = new Map<string, MenuItem[]>(); + const arg = servicesArg(services); + for (const { pluginId, decl, action } of serviceEntries("services.context", services)) + addGrouped(out, groups, pluginId, decl.submenu, { kind: "action", action, arg }); + return flattenSingleGroups(out); +} + +export function pluginServiceActions(services: readonly ServiceContext[]): ServiceItemAction[] { + const arg = servicesArg(services); + return serviceEntries("services.toolbar", services).map(({ pluginId, action }) => { + const a = getAction(action)!; + const plugin = usePlugins.getState().plugins.find((p) => p.id === pluginId); + return { + id: action, + title: a.title, + icon: a.icon ?? pluginIconName(pluginId, plugin?.icon ?? null), + run: () => void executeAction(action, arg), + }; + }); +} + function projectMenu(pluginId: string, decl: MenuDecl, plugin: PluginInfo): () => void { if (decl.menu === "tools") { const action = pluginActionId(pluginId, decl.command); @@ -609,6 +674,7 @@ export function startViewUi(openInput: (input: ReturnType<typeof customEditorInp icon: pluginContentEditorIcon, document: pluginContentEditorDocument, }), + registerServiceSelectionItems({ id: "plugins", menu: pluginServiceMenuItems, actions: pluginServiceActions }), registerMenuGroup({ id: "plugins", menus: ["editor", "projectView", "editorTab", "problems", "searchResults"], diff --git a/src/features/plugins/views/WebView.tsx b/src/features/plugins/views/WebView.tsx index c4b83722e..fd0cfdad7 100644 --- a/src/features/plugins/views/WebView.tsx +++ b/src/features/plugins/views/WebView.tsx @@ -23,6 +23,7 @@ import { useProject } from "@/platform/project"; import { subscribeTheme, themeKey } from "@/platform/themeWatch"; import { EmptyState, Spinner } from "@/ui"; import { editorService, registerFontZoomSurface } from "@/workbench/contributions"; +import { notifyFocusElement } from "@/workbench/focus"; import { ToolWindowCornerActions, useOwnToolWindowHeader } from "@/workbench/toolwindows/ToolWindows"; import { pluginsBackend, type FileFilter } from "../backend"; import { errorText, usePlugins } from "../store"; @@ -548,9 +549,13 @@ export function WebView({ op?: unknown; args?: unknown; key?: unknown; + focus?: unknown; } | null; if (m?.tag !== FRAME_TAG) return; - if (m.key && typeof m.key === "object") { + if (m.focus === true) { + const host = frame.current.ownerDocument; + if (host.activeElement === frame.current && host.hasFocus()) notifyFocusElement(frame.current); + } else if (m.key && typeof m.key === "object") { // A shortcut the page didn't handle: as if pressed on the frame, for the IDE's keymap. The // page can post one at any time and can take the focus, but it cannot fake the user's own // input, so it counts only right after the user pressed a key or clicked in the frame. diff --git a/src/features/plugins/views/frame-bridge.js b/src/features/plugins/views/frame-bridge.js index 346d911c2..345953e63 100644 --- a/src/features/plugins/views/frame-bridge.js +++ b/src/features/plugins/views/frame-bridge.js @@ -88,6 +88,12 @@ root.style.zoom = next === 100 ? "" : (next / 100).toFixed(2); }; + // Report frame activation to the host so focus tracking and focus-scope highlighting + // stay in sync even when switching directly into or between sandboxed plugin frames. + const notifyFocus = () => window.parent.postMessage({ tag: TAG, focus: true }, "*"); + window.addEventListener("focus", notifyFocus); + window.addEventListener("pointerdown", notifyFocus, true); + // IDE shortcuts (Save, Close, Find Action…) pressed while the page has focus: // the ones the page left alone go to the workbench. Editing keys stay here. const EDITING_KEYS = new Set(["a", "c", "v", "x", "z", "y"]); diff --git a/src/features/profiler/ProfilerView.tsx b/src/features/profiler/ProfilerView.tsx index e6d4d2483..678f83c01 100644 --- a/src/features/profiler/ProfilerView.tsx +++ b/src/features/profiler/ProfilerView.tsx @@ -6,8 +6,9 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react"; import clsx from "clsx"; import type { Profile } from "@/platform/ipc"; -import { EmptyState, Icon, IconButton, Input, Tabs, Tree, T } from "@/ui"; +import { Button, EmptyState, Icon, IconButton, Input, Tabs, Tree, T } from "@/ui"; import { editorService } from "@/workbench/contributions"; +import { executeAction } from "@/platform/actions"; import { colorSlot, flameLayout, flameStep, formatWeight, frameLocation, matchingFrames, share } from "./model"; import { activeSnapshot, closeSnapshot, useProfiler, type ProfilerTab } from "./store"; import styles from "./Profiler.module.css"; @@ -56,6 +57,10 @@ function openFrame(profile: Profile, frame: number) { ); } +export function ProfilerHeaderActions() { + return <IconButton icon="open" action="profiler.openSnapshot" size="small" />; +} + export function ProfilerTabs() { const snapshots = useProfiler((s) => s.snapshots); const activeId = useProfiler((s) => s.activeId); @@ -294,7 +299,14 @@ export function ProfilerView() { const query = useProfiler((s) => s.query); if (!snapshot) { return ( - <EmptyState title="No profiler snapshots"> + <EmptyState + title="No profiler snapshots" + actions={ + <Button size="small" onClick={() => void executeAction("profiler.openSnapshot")}> + <T>Open Snapshot…</T> + </Button> + } + > <span> <T>Profile a run configuration to see where it spends its time.</T> </span> diff --git a/src/features/profiler/cpuProfiles.test.ts b/src/features/profiler/cpuProfiles.test.ts index d502b2cd0..888d1531c 100644 --- a/src/features/profiler/cpuProfiles.test.ts +++ b/src/features/profiler/cpuProfiles.test.ts @@ -2,7 +2,14 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { Profile, ProfileSpec } from "@/platform/ipc"; const collected: ProfileSpec[] = []; -let fails = false; +let fails: boolean | ((spec: ProfileSpec) => boolean) = false; +let picked: string[] = []; +const notified: Array<{ title: string; body?: string }> = []; +vi.mock("@/workbench/contributions", () => ({ + notifications: () => ({ notify: (n: { title: string; body?: string }) => notified.push(n) }), + toolWindowService: () => ({ show: () => undefined }), +})); +vi.mock("@/platform/choosePath", () => ({ choosePaths: () => Promise.resolve(picked) })); const profile = { profiler: "v8", unit: "samples", mode: "cpu", total: 3, frames: [] } as unknown as Profile; vi.mock("@/platform/ipc", async (orig) => { const real = await orig<typeof import("@/platform/ipc")>(); @@ -13,7 +20,7 @@ vi.mock("@/platform/ipc", async (orig) => { profilerCollect: (spec: ProfileSpec) => { collected.push(spec); return Promise.resolve( - fails + (typeof fails === "function" ? fails(spec) : fails) ? { status: "error", error: { kind: "invalidInput", message: "no samples" } } : { status: "ok", data: profile }, ); @@ -22,12 +29,14 @@ vi.mock("@/platform/ipc", async (orig) => { }; }); -const { showCpuProfiles } = await import("./cpuProfiles"); +const { isCpuProfilePath, openCpuProfileFiles, showCpuProfiles } = await import("./cpuProfiles"); const { resetProfiler, useProfiler } = await import("./store"); beforeEach(() => { collected.length = 0; fails = false; + picked = []; + notified.length = 0; resetProfiler(); }); @@ -53,3 +62,59 @@ describe("CPU profiles recorded elsewhere", () => { expect(useProfiler.getState().snapshots).toEqual([]); }); }); + +describe("Open Snapshot", () => { + const names = () => useProfiler.getState().snapshots.map((s) => s.name); + + it("opens each .cpuprofile file as its own snapshot", async () => { + await openCpuProfileFiles(["/work/app/CPU.1.cpuprofile", "C:\\ci\\run.cpuprofile"]); + expect(collected).toEqual([ + { kind: "cpuProfileFile", path: "/work/app/CPU.1.cpuprofile" }, + { kind: "cpuProfileFile", path: "C:\\ci\\run.cpuprofile" }, + ]); + expect(names()).toEqual(["run.cpuprofile", "CPU.1.cpuprofile"]); + }); + + it("asks for the files when the action has none, and opens nothing when cancelled", async () => { + await openCpuProfileFiles(undefined); + expect(collected).toEqual([]); + picked = ["/tmp/a.cpuprofile"]; + await openCpuProfileFiles(undefined); + expect(names()).toEqual(["a.cpuprofile"]); + }); + + it("skips a file that is not a CPU profile and still opens the others", async () => { + fails = (spec) => spec.kind === "cpuProfileFile" && spec.path.endsWith("bad.cpuprofile"); + await expect(openCpuProfileFiles(["/tmp/bad.cpuprofile", "/tmp/good.cpuprofile"])).resolves.toBeUndefined(); + expect(names()).toEqual(["good.cpuprofile"]); + }); + + it("replaces the snapshot of a file opened again", async () => { + await openCpuProfileFiles(["/tmp/a.cpuprofile", "/tmp/b.cpuprofile"]); + const first = useProfiler.getState().snapshots.find((s) => s.name === "a.cpuprofile")!.id; + await openCpuProfileFiles("/tmp/a.cpuprofile"); + const state = useProfiler.getState(); + expect(names()).toEqual(["a.cpuprofile", "b.cpuprofile"]); + expect(state.activeId).toBe(first); + }); + + it("says which snapshots it closed to stay within the limit, recordings included", async () => { + await showCpuProfiles({ name: "localhost:5173", dir: "/tmp/p", root: "/work/shop" }); + await openCpuProfileFiles([1, 2, 3, 4, 5].map((n) => `/tmp/${n}.cpuprofile`)); + expect(names()).toEqual(["5.cpuprofile", "4.cpuprofile", "3.cpuprofile", "2.cpuprofile", "1.cpuprofile"]); + expect(notified).toEqual([ + { + group: "run", + level: "info", + title: "Closed older profiler snapshots", + body: "The Profiler keeps the last 5 snapshots open; closed localhost:5173.", + }, + ]); + }); + + it("recognises .cpuprofile files by extension", () => { + expect(isCpuProfilePath("/a/CPU.20261126.cpuprofile")).toBe(true); + expect(isCpuProfilePath("/a/X.CPUPROFILE")).toBe(true); + expect(isCpuProfilePath("/a/cpuprofile.json")).toBe(false); + }); +}); diff --git a/src/features/profiler/cpuProfiles.ts b/src/features/profiler/cpuProfiles.ts index 9ad14c136..233af1567 100644 --- a/src/features/profiler/cpuProfiles.ts +++ b/src/features/profiler/cpuProfiles.ts @@ -1,3 +1,5 @@ +import { choosePaths } from "@/platform/choosePath"; +import { tx } from "@/platform/i18n"; import { call, commands } from "@/platform/ipc"; import { notifications, toolWindowService } from "@/workbench/contributions"; import { addSnapshot } from "./store"; @@ -38,9 +40,47 @@ export async function showCpuProfiles(arg: unknown): Promise<void> { }); return; } + showProfiler(); +} + +function showProfiler() { try { toolWindowService().show("profiler", true); } catch { // No workbench (tests). } } + +export const isCpuProfilePath = (path: string) => path.toLowerCase().endsWith(".cpuprofile"); + +/** The paths to open: the action's arg (a path or paths), else the ones picked in a file dialog. */ +async function snapshotPaths(arg: unknown): Promise<string[]> { + if (typeof arg === "string") return [arg]; + if (Array.isArray(arg)) return arg.filter((p): p is string => typeof p === "string"); + return choosePaths({ + directory: false, + title: tx("Open Snapshot"), + filters: [{ name: tx("V8 CPU profile"), extensions: ["cpuprofile"] }], + }); +} + +/** Opens `.cpuprofile` files (`node --cpu-prof`, Chrome DevTools), each as its own snapshot. */ +export async function openCpuProfileFiles(arg: unknown): Promise<void> { + let opened = false; + for (const path of await snapshotPaths(arg)) { + try { + // oxlint-disable-next-line no-await-in-loop -- one snapshot per file, in the order picked + const profile = await call(commands.profilerCollect({ kind: "cpuProfileFile", path })); + addSnapshot(path.split(/[/\\]/).pop() ?? path, profile, null, path); + opened = true; + } catch (e) { + notifications().notify({ + group: "run", + level: "error", + title: "Cannot open the CPU profile", + body: e instanceof Error ? e.message : String(e), + }); + } + } + if (opened) showProfiler(); +} diff --git a/src/features/profiler/index.ts b/src/features/profiler/index.ts index ab7b7e8f7..c53bae0fc 100644 --- a/src/features/profiler/index.ts +++ b/src/features/profiler/index.ts @@ -4,12 +4,27 @@ */ import { executeAction, registerActions } from "@/platform/actions"; import { useProject } from "@/platform/project"; -import { registerRunExecutor, registerToolWindow } from "@/workbench/contributions"; -import { showCpuProfiles } from "./cpuProfiles"; +import { + registerEditorBanner, + registerMenuGroup, + registerRunExecutor, + registerToolWindow, + type EditorBanner, +} from "@/workbench/contributions"; +import { isCpuProfilePath, openCpuProfileFiles, showCpuProfiles } from "./cpuProfiles"; import { profilerExecutor } from "./executor"; -import { ProfilerTabs, ProfilerView } from "./ProfilerView"; +import { ProfilerHeaderActions, ProfilerTabs, ProfilerView } from "./ProfilerView"; import { resetProfiler } from "./store"; +function useCpuProfileBanner(path: string): EditorBanner | null { + if (!isCpuProfilePath(path)) return null; + return { + text: "This file is a V8 CPU profile", + icon: "profile", + actions: [{ label: "Open in Profiler", run: () => void openCpuProfileFiles(path) }], + }; +} + export function activate(): () => void { const disposers: Array<() => void> = [ registerRunExecutor(profilerExecutor("cpu")), @@ -24,6 +39,17 @@ export function activate(): () => void { order: 25, component: ProfilerView, headerContent: ProfilerTabs, + headerActions: ProfilerHeaderActions, + }), + registerEditorBanner({ id: "profiler.cpuProfile", order: 30, useBanner: useCpuProfileBanner }), + registerMenuGroup({ + id: "profiler.openInProfiler", + menus: ["projectView", "editor", "editorTab"], + order: 45, + items: (_menu, { paths, dirs }) => + paths.length && paths.every((p, i) => !dirs?.[i] && isCpuProfilePath(p)) + ? [{ kind: "action", action: "profiler.openInProfiler", arg: paths }] + : [], }), registerActions([ { @@ -46,6 +72,26 @@ export function activate(): () => void { hidden: true, run: ({ arg }) => showCpuProfiles(arg), }, + { + id: "profiler.openSnapshot", + title: "Open Snapshot…", + description: "Open V8 .cpuprofile files saved by node --cpu-prof or Chrome DevTools in the Profiler", + category: "Profiler", + icon: "profile", + when: "projectOpen", + keywords: ["cpuprofile", "profiler", "snapshot", "flame graph"], + run: () => openCpuProfileFiles(undefined), + }, + { + id: "profiler.openInProfiler", + title: "Open in Profiler", + description: "Open the selected .cpuprofile files as Profiler snapshots", + category: "Profiler", + icon: "profile", + hidden: true, + when: "projectOpen", + run: ({ arg }) => (arg === undefined ? undefined : openCpuProfileFiles(arg)), + }, { id: "run.profileAllocations", title: "Profile Allocations", diff --git a/src/features/profiler/store.ts b/src/features/profiler/store.ts index 9f015a415..2c8e3591a 100644 --- a/src/features/profiler/store.ts +++ b/src/features/profiler/store.ts @@ -1,6 +1,8 @@ /** Profiler snapshots of this project window (the last few stay open as tabs). */ import { create } from "zustand"; +import { tx } from "@/platform/i18n"; import type { Profile } from "@/platform/ipc"; +import { notifications } from "@/workbench/contributions"; export const MAX_SNAPSHOTS = 5; @@ -12,6 +14,8 @@ export interface Snapshot { profile: Profile; /** Why the numbers may mislead; shown above the views. */ notice: string | null; + /** The `.cpuprofile` it was opened from; opening the file again replaces it. */ + path?: string; } export type ProfilerTab = "flame" | "tree" | "methods"; @@ -28,12 +32,31 @@ export const useProfiler = create<ProfilerState>(() => ({ snapshots: [], activeI let seq = 0; -export function addSnapshot(name: string, profile: Profile, notice: string | null = null): Snapshot { - const snapshot: Snapshot = { id: `profile${++seq}`, name, createdAt: Date.now(), profile, notice }; - useProfiler.setState((s) => ({ - snapshots: [snapshot, ...s.snapshots].slice(0, MAX_SNAPSHOTS), - activeId: snapshot.id, - })); +/** Adds a snapshot in front; the oldest beyond {@link MAX_SNAPSHOTS} close, with a notification. */ +export function addSnapshot(name: string, profile: Profile, notice: string | null = null, path?: string): Snapshot { + const prev = useProfiler.getState().snapshots; + const same = path === undefined ? undefined : prev.find((x) => x.path === path); + const snapshot: Snapshot = { + id: same?.id ?? `profile${++seq}`, + name, + createdAt: Date.now(), + profile, + notice, + ...(path !== undefined && { path }), + }; + const rest = prev.filter((x) => x !== same); + const dropped = rest.slice(MAX_SNAPSHOTS - 1); + useProfiler.setState({ snapshots: [snapshot, ...rest.slice(0, MAX_SNAPSHOTS - 1)], activeId: snapshot.id }); + if (dropped.length) { + const max = MAX_SNAPSHOTS; + const names = dropped.map((x) => x.name).join(", "); + notifications().notify({ + group: "run", + level: "info", + title: "Closed older profiler snapshots", + body: tx`The Profiler keeps the last ${max} snapshots open; closed ${names}.`, + }); + } return snapshot; } diff --git a/src/features/project-tree/HeaderActions.tsx b/src/features/project-tree/HeaderActions.tsx index 0d54ed692..a72a26e3e 100644 --- a/src/features/project-tree/HeaderActions.tsx +++ b/src/features/project-tree/HeaderActions.tsx @@ -21,9 +21,12 @@ export function useProjectTitleMenu(): { label: string; items: MenuItem[] } { const mode = useProjectTree((s) => s.mode); const scope = useProjectTree((s) => s.scope); const unity = useProjectTree((s) => s.unity); + const unreal = useProjectTree((s) => s.unreal); + // The engine panes only exist in a project of that engine. + const available = (id: string) => (id !== "unity" || Boolean(unity)) && (id !== "unreal" || Boolean(unreal)); // User scopes (Settings › Scopes) follow the built-in panes, as in IDEA. const scopes = userScopes(useProject((s) => (s.settings as { scopes?: unknown } | null)?.scopes)); - const items: MenuItem[] = VIEW_MODES.filter(([id]) => id !== "unity" || unity).map(([id, label]) => ({ + const items: MenuItem[] = VIEW_MODES.filter(([id]) => available(id)).map(([id, label]) => ({ id, label, checked: id === mode, diff --git a/src/features/project-tree/ProjectView.tsx b/src/features/project-tree/ProjectView.tsx index 2e783e31a..936dcbf85 100644 --- a/src/features/project-tree/ProjectView.tsx +++ b/src/features/project-tree/ProjectView.tsx @@ -605,7 +605,7 @@ export function ProjectView() { const rootNode = m.roots[0]; if (!rootNode) return; setSelection(new Set([rootNode.key]), rootNode.key); - showContextMenu(e, contextMenuItems([rootNode])); + showContextMenu(e, contextMenuItems([rootNode], { x: e.clientX, y: e.clientY })); return; } const nodes = [...sel].map((k) => m.byKey.get(k)).filter((n): n is ProjectNode => !!n && !n.placeholder); @@ -614,7 +614,7 @@ export function ProjectView() { // Contributed groups may read the file first (bounded wait). const at = { x: e.clientX, y: e.clientY }; void prepareMenuGroups("projectView", menuGroupContext(target)).then(() => - showContextMenu(at, contextMenuItems(target)), + showContextMenu(at, contextMenuItems(target, at)), ); }, []); diff --git a/src/features/project-tree/actions.ts b/src/features/project-tree/actions.ts index f13804fc1..3a6fb08fe 100644 --- a/src/features/project-tree/actions.ts +++ b/src/features/project-tree/actions.ts @@ -1,13 +1,15 @@ /** Actions of the project view (Find Action, keymap, other features via `executeAction`). */ import { activeEditor } from "@/editor/api"; -import { getAction, registerActions, type Action } from "@/platform/actions"; +import { executeAction, getAction, registerActions, type Action } from "@/platform/actions"; import { getContext } from "@/platform/context"; +import { FILE_COLOR_NAMES } from "@/platform/fileColors"; import { canRevealInFileManager, revealInFileManagerLabel } from "@/platform/fileManager"; import { dirname, useProject } from "@/platform/project"; import { showContextMenu, type MenuItem } from "@/ui"; import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions"; import { OPTION_LABELS, SORT_LABELS, flipToggle, isToggled } from "./HeaderActions"; import { compareTarget, newMenuItems, revealLabel } from "./contextMenu"; +import { LABELS, setFileColor } from "./fileColor"; import { openNewPopup } from "./newPopupModel"; import type { ProjectNode } from "./model"; import { @@ -587,5 +589,28 @@ export function registerProjectActions(): () => void { ...toggles, ...modes, ...sorts, + // File Color of a single path (the project view's submenu; the editor tab menu references + // these ids with a path argument instead of importing this feature). + ...FILE_COLOR_NAMES.map((name): Action => ({ + id: `file.${name}`, + title: LABELS[name], + category: "Project View", + hidden: true, + run: ({ arg }) => void setFileColor(String(arg), false, name), + })), + { + id: "file.clearColor", + title: "Clear File Color", + category: "Project View", + hidden: true, + run: ({ arg }) => void setFileColor(String(arg), false, null), + }, + { + id: "file.editColors", + title: "Edit File Colors…", + category: "Project View", + hidden: true, + run: () => void executeAction("file.settings", "fileColors"), + }, ]); } diff --git a/src/features/project-tree/contextMenu.test.ts b/src/features/project-tree/contextMenu.test.ts index 5fa418e92..2cf0c7bd0 100644 --- a/src/features/project-tree/contextMenu.test.ts +++ b/src/features/project-tree/contextMenu.test.ts @@ -8,6 +8,11 @@ import { registerMenuGroup } from "@/workbench/contributions"; import { contextMenuItems, keyLabel, revealLabel } from "./contextMenu"; import type { ProjectNode } from "./model"; import { useProjectTree } from "./store"; +import { closePopup, useLspPopup } from "@/editor/lsp/popupStore"; +import { _provideCopyPathChooser } from "@/editor/api"; +import { openCopyPathChooser } from "@/editor/core/copyPathChooser"; + +_provideCopyPathChooser(openCopyPathChooser); vi.mock("@/platform/ipc", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/platform/ipc")>()), @@ -79,6 +84,7 @@ beforeEach(() => { }); afterEach(() => { + closePopup(); disposers.forEach((d) => d()); useProject.setState({ project: null, settings: null }); useProjectTree.setState({ root: null }); @@ -147,38 +153,56 @@ describe("project view context menu", () => { } }); - it("lists contributed links in Copy Path/Reference…", () => { + /** Runs Copy Path/Reference… and returns the chooser's rows as `label: preview`. */ + const chooser = (items: MenuItem[]) => { + const item = resolveMenuItems(items).find((r) => r.label === "Copy Path/Reference…"); + expect(item?.submenu).toBeUndefined(); + item!.run!(); + const popup = useLspPopup.getState().popup; + return popup?.kind === "list" ? popup.items.map((i) => `${i.label}: ${i.preview}`) : undefined; + }; + + it("previews each way Copy Path/Reference… copies the selection, contributed links included", () => { disposers.push( registerMenuGroup({ id: "test.link", menus: ["copyPath"], items: (_menu, ctx) => [ - { label: `Link ${ctx.paths.join()} ${ctx.dirs?.join()}`, verbatim: true, run: () => undefined }, + { + id: "test.link", + label: "Link", + verbatim: true, + preview: `${ctx.paths.join()} ${ctx.dirs?.join()}`, + run: () => undefined, + }, + // Without a preview a contribution has nothing to show in the chooser. + { id: "test.bare", label: "Bare", run: () => undefined }, ], }), ); - expect(sub(contextMenuItems([node("/p/src", true)]), "Copy Path/Reference…")).toEqual([ - "Absolute Path", - "File Name", - "Path From Content Root", - "-", - "Link /p/src true", + expect(chooser(contextMenuItems([node("/p/src", true), node("/p/src/a.ts")], { x: 10, y: 20 }))).toEqual([ + "Absolute Path: /p/src\n/p/src/a.ts", + "File Name: src\na.ts", + "Path From Content Root: src\nsrc/a.ts", + "Link: /p/src,/p/src/a.ts true,false", ]); + expect(useLspPopup.getState().popup).toMatchObject({ layout: "copyPath", anchor: { x: 10, y: 20 } }); }); - it("lists contributed links in Copy Path/Reference… of library files too", () => { + it("offers no content root paths for library files in Copy Path/Reference…", () => { disposers.push( registerMenuGroup({ id: "test.link", menus: ["copyPath"], - items: (_menu, ctx) => [{ label: `Link ${ctx.paths.join()}`, verbatim: true, run: () => undefined }], + items: (_menu, ctx) => [ + { id: "test.link", label: "Link", verbatim: true, preview: ctx.paths.join(), run: () => undefined }, + ], }), ); - expect(sub(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]), "Copy Path/Reference…")).toEqual([ - "Absolute Path", - "File Name", - "-", - "Link /root/.m2/lib.jar", + expect(chooser(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]))).toEqual([ + "Absolute Path: /root/.m2/lib.jar", + "File Name: lib.jar", + "Link: /root/.m2/lib.jar", ]); }); diff --git a/src/features/project-tree/contextMenu.ts b/src/features/project-tree/contextMenu.ts index 9cf5ffe95..509908a0f 100644 --- a/src/features/project-tree/contextMenu.ts +++ b/src/features/project-tree/contextMenu.ts @@ -1,5 +1,7 @@ /** Context menu and "New" popup of the project view. */ +import { openCopyPathChooser } from "@/editor/api"; import { executeAction, getAction } from "@/platform/actions"; +import type { PathKind } from "@/platform/copyPath"; import { getContext } from "@/platform/context"; import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager"; import { formatBinding, hostBinding, isMacHost, shortcutLabel } from "@/platform/keymap"; @@ -18,6 +20,7 @@ import { canPaste, copyPaths, copySelection, + pathsFor, delegate, deleteSelection, findFileUsages, @@ -151,6 +154,8 @@ function delegated( } type Entry = MenuItem | null | false | undefined; +/** Where a menu opens; popups its items open appear there. */ +type MenuPoint = { x: number; y: number } | "center"; /** A submenu of the present entries, or nothing when none is left (never an empty submenu). */ function submenu(id: string, label: string, entries: Entry[], icon?: string): MenuItem | null { @@ -160,8 +165,13 @@ function submenu(id: string, label: string, entries: Entry[], icon?: string): Me } /** Project view actions available for the selected files and directories. */ -export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] { - if (nodes.some((n) => n.readOnly)) return libraryMenuItems(nodes.filter((n) => !n.group)); +/** `at`: where the menu opens, for the popups its items open (Copy Path/Reference…). */ +export function contextMenuItems(nodes: ProjectNode[], at: MenuPoint = "center"): MenuItem[] { + if (nodes.some((n) => n.readOnly)) + return libraryMenuItems( + nodes.filter((n) => !n.group), + at, + ); const lead = nodes[0] ?? null; const single = nodes.length === 1 ? lead : null; const nonRoot = nodes.filter((n) => !n.root); @@ -217,22 +227,7 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] { disabled: !nonRoot.length, run: () => copySelection(false), }, - { - id: "copyPath", - label: "Copy Path/Reference…", - submenu: [ - { - id: "abs", - label: "Absolute Path", - shortcut: keyLabel("project.copyAbsolutePath"), - run: () => void copyPaths("absolute", nodes), - }, - { id: "name", label: "File Name", run: () => void copyPaths("name", nodes) }, - { id: "rel", label: "Path From Content Root", run: () => void copyPaths("relative", nodes) }, - { kind: "separator" }, - ...menuGroupItems("copyPath", menuGroupContext(nodes)), - ], - }, + copyPathItem(nodes, at, false), { id: "paste", label: "Paste", @@ -464,27 +459,13 @@ function openInRightSplitItem(files: ProjectNode[]): MenuItem { } /** Library sources (External Libraries) are read-only: copy, find and reveal only. */ -function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] { +function libraryMenuItems(nodes: ProjectNode[], at: MenuPoint): MenuItem[] { if (!nodes.length) return []; const single = nodes.length === 1 ? nodes[0]! : null; const folder = single?.dir ? single.path : null; const items: Entry[] = [ { id: "copy", label: "Copy", icon: "copy", shortcut: keyLabel("project.copy"), run: () => copySelection(false) }, - { - id: "copyPath", - label: "Copy Path/Reference…", - submenu: [ - { - id: "abs", - label: "Absolute Path", - shortcut: keyLabel("project.copyAbsolutePath"), - run: () => void copyPaths("absolute", nodes), - }, - { id: "name", label: "File Name", run: () => void copyPaths("name", nodes) }, - { kind: "separator" }, - ...menuGroupItems("copyPath", menuGroupContext(nodes)), - ], - }, + copyPathItem(nodes, at, true), { kind: "separator" }, !!folder && delegated("find.inPath", { directory: folder }, "Find in Files…", { icon: "search" }), !!folder && { kind: "separator" }, @@ -518,6 +499,43 @@ export function revealLabel() { return fileManagerName(); } +/** + * Copy Path/Reference…: a chooser previewing what each way copies for the selection (several + * paths one per line), contributed links and references included. Library files have no + * content or source root. + */ +function copyPathItem(nodes: ProjectNode[], at: MenuPoint, library: boolean): Entry { + const row = (kind: PathKind, id: string, label: string) => { + const paths = pathsFor(kind, nodes); + return { + id, + label, + // A selection only partly under a source root has no source-root path. + preview: paths.length && paths.length === nodes.length ? paths.join("\n") : null, + run: () => void copyPaths(kind, nodes), + }; + }; + return { + id: "copyPath", + label: "Copy Path/Reference…", + run: () => + openCopyPathChooser( + at, + [ + row("absolute", "project.copyAbsolutePath", "Absolute Path"), + row("name", "project.copyFileName", "File Name"), + ...(library + ? [] + : [ + row("relative", "project.copyRelativePath", "Path From Content Root"), + row("source", "project.copySourceRootPath", "Path From Source Root"), + ]), + ], + menuGroupContext(nodes), + ), + }; +} + /** What contributed menu groups see: the selected (non-placeholder) paths. */ export function menuGroupContext(nodes: ProjectNode[]): MenuGroupContext { const real = nodes.filter((n) => !n.placeholder); diff --git a/src/features/project-tree/fileColor.ts b/src/features/project-tree/fileColor.ts index df262f6c3..cc8878097 100644 --- a/src/features/project-tree/fileColor.ts +++ b/src/features/project-tree/fileColor.ts @@ -8,7 +8,8 @@ import { call, commands, isTauri } from "@/platform/ipc"; import { loadSettings, relativePath, useProject } from "@/platform/project"; import type { MenuItem } from "@/ui"; -const LABELS: Record<(typeof FILE_COLOR_NAMES)[number], string> = { +/** English title per colour, also the title of its `file.<colour>` action (the editor tab menu). */ +export const LABELS: Record<(typeof FILE_COLOR_NAMES)[number], string> = { blue: "Blue", green: "Green", orange: "Orange", diff --git a/src/features/project-tree/index.ts b/src/features/project-tree/index.ts index fee0e5770..610f77921 100644 --- a/src/features/project-tree/index.ts +++ b/src/features/project-tree/index.ts @@ -62,11 +62,19 @@ export function activate(): () => void { const p = useProject.getState().project; const s = useProjectTree.getState(); if ((p?.root ?? null) !== s.root || p?.workspace?.projects !== (s.members ?? undefined)) - initProjectTree(p?.root ?? null, p?.name ?? "", p?.workspace?.projects ?? null, p?.unity ?? null); + initProjectTree( + p?.root ?? null, + p?.name ?? "", + p?.workspace?.projects ?? null, + p?.unity ?? null, + p?.unreal ?? null, + ); else if (p) { - useProjectTree.setState({ name: p.name, unity: p.unity ?? null }); + useProjectTree.setState({ name: p.name, unity: p.unity ?? null, unreal: p.unreal ?? null }); if (p.unity && !s.unity && s.mode === "project") setViewMode("unity"); if (!p.unity && s.mode === "unity") setViewMode("project"); + if (p.unreal && !s.unreal && s.mode === "project") setViewMode("unreal"); + if (!p.unreal && s.mode === "unreal") setViewMode("project"); } }; sync(); diff --git a/src/features/project-tree/model.ts b/src/features/project-tree/model.ts index 76bf89ee6..b2adb1ab0 100644 --- a/src/features/project-tree/model.ts +++ b/src/features/project-tree/model.ts @@ -10,7 +10,10 @@ import { ancestorsWithin, insideAnyOf, isInside, isSameOrInside, nameOf, parentO export interface TreeOptions { /** Applied only by the Unity pane, never persisted as a user preference. */ unityRoot?: string; + /** Applied only by the Unreal pane, never persisted as a user preference. */ + unrealRoot?: string; showUnityMeta: boolean; + /** Generated build output, shared by the engine panes (Unity's Library, Unreal's Binaries/Intermediate). */ showUnityGenerated: boolean; /** Show ignored names (`files.ignoredNames`: `.git`, `.DS_Store`, …). Dotfiles are always shown. */ showHidden: boolean; @@ -90,8 +93,21 @@ export function unityPathVisible(path: string, opts: TreeOptions): boolean { return true; } +/** The Unreal pane hides what UBT writes: build output, and the project files it generates. */ +export function unrealPathVisible(path: string, opts: TreeOptions): boolean { + if (opts.unrealRoot && path.startsWith(opts.unrealRoot + "/")) { + const relative = path.slice(opts.unrealRoot.length + 1); + if (!opts.showUnityGenerated) { + if (/^(Binaries|Intermediate|Saved|DerivedDataCache|\.vs)(\/|$)/.test(relative)) return false; + if (!relative.includes("/") && /\.(sln|slnx|suo|user|vcxproj|pidb)$/i.test(relative)) return false; + } + } + return true; +} + export function isVisible(entry: FileEntry, opts: TreeOptions): boolean { if (!unityPathVisible(entry.path, opts)) return false; + if (!unrealPathVisible(entry.path, opts)) return false; // Ignored names are also excluded on the backend; only "Show Hidden" brings them back. if (isIgnoredName(entry.name)) return opts.showHidden; if (!opts.showExcluded && entry.ignored) return false; diff --git a/src/features/project-tree/store.ts b/src/features/project-tree/store.ts index 105e71583..8848cc311 100644 --- a/src/features/project-tree/store.ts +++ b/src/features/project-tree/store.ts @@ -4,7 +4,7 @@ * Kept outside React so actions (keyboard, Find Action, context menu) share it. */ import { create } from "zustand"; -import type { UnityProjectInfo } from "@/bindings"; +import type { UnrealProjectInfo, UnityProjectInfo } from "@/bindings"; import { call } from "@/platform/ipc"; import { commands, type FileEntry, type OutlineItem } from "@/bindings"; import { withDocument } from "@/editor/lsp/files"; @@ -37,6 +37,7 @@ import { visibleEntries, visibleInfo, unityPathVisible, + unrealPathVisible, type Placeholder, type ProjectNode, type TreeModel, @@ -89,10 +90,19 @@ function storedOptions(): ViewOptions { } /** IDEA's Project view panes ("Project ▾" in the tool window header). */ -export type ViewMode = "unity" | "project" | "projectFiles" | "openFiles" | "changedFiles" | "scratches" | "scope"; +export type ViewMode = + | "unity" + | "unreal" + | "project" + | "projectFiles" + | "openFiles" + | "changedFiles" + | "scratches" + | "scope"; export const VIEW_MODES: ReadonlyArray<[ViewMode, string]> = [ ["unity", "Unity"], + ["unreal", "Unreal"], ["project", "Project"], ["projectFiles", "Project Files"], ["openFiles", "Open Files"], @@ -118,6 +128,7 @@ export interface Clipboard { interface ProjectTreeState { unity: UnityProjectInfo | null; + unreal: UnrealProjectInfo | null; root: string | null; name: string; members: readonly string[] | null; @@ -172,6 +183,7 @@ function writeJson(key: string, value: unknown) { export const useProjectTree = create<ProjectTreeState>(() => ({ unity: null, + unreal: null, root: null, name: "", members: null, @@ -207,6 +219,7 @@ const set = (patch: Partial<ProjectTreeState>) => useProjectTree.setState(patch) let memo: { unity: UnityProjectInfo | null; + unreal: UnrealProjectInfo | null; root: string | null; name: string; members: readonly string[] | null; @@ -232,7 +245,9 @@ const filesOf = (s: ProjectTreeState) => : null; function treeOptions(s: ProjectTreeState): TreeOptions { - return s.mode === "unity" && s.unity && s.root ? { ...s.options, compact: false, unityRoot: s.root } : s.options; + if (s.mode === "unity" && s.unity && s.root) return { ...s.options, compact: false, unityRoot: s.root }; + if (s.mode === "unreal" && s.unreal && s.root) return { ...s.options, compact: false, unrealRoot: s.root }; + return s.options; } export function selectModel(s: ProjectTreeState): TreeModel { @@ -240,6 +255,7 @@ export function selectModel(s: ProjectTreeState): TreeModel { if ( memo && memo.unity === s.unity && + memo.unreal === s.unreal && memo.root === s.root && memo.name === s.name && memo.members === s.members && @@ -300,6 +316,8 @@ export function selectModel(s: ProjectTreeState): TreeModel { else model = withExtraRoots(project(), contributed, s.listings, options, placeholder); if (s.unity && s.mode === "unity" && model.roots[0]) model.roots[0].detail = s.unity.editorVersion ? `Unity ${s.unity.editorVersion}` : "Unity"; + if (s.unreal && s.mode === "unreal" && model.roots[0]) + model.roots[0].detail = s.unreal.engine ? `Unreal ${s.unreal.engine.id}` : "Unreal · engine not found"; const libraries = extraFolders(contributed).flatMap((r) => r.readOnly && r.path !== undefined && isSameOrInside(r.path, s.root!) ? [r.path] : [], ); @@ -307,6 +325,7 @@ export function selectModel(s: ProjectTreeState): TreeModel { } memo = { unity: s.unity, + unreal: s.unreal, root: s.root, name: s.name, members: s.members, @@ -350,6 +369,7 @@ export function initProjectTree( name = "", members: readonly string[] | null = null, unity: UnityProjectInfo | null = null, + unreal: UnrealProjectInfo | null = null, ) { cancelExpansion(); generation++; @@ -363,8 +383,13 @@ export function initProjectTree( autoExpanded.clear(); const previous = get(); const previousMode = previous.mode; + const engineMode: ViewMode | null = unreal ? "unreal" : unity ? "unity" : null; const mode = - unity && previousMode === "project" ? "unity" : !unity && previousMode === "unity" ? "project" : previousMode; + engineMode && previousMode === "project" + ? engineMode + : !engineMode && (previousMode === "unity" || previousMode === "unreal") + ? "project" + : previousMode; // Keep the remaining members' types visible while the workspace is rescanned. const projectTypes = new Map<string, ProjectType>(); if (root === previous.root && members) { @@ -375,6 +400,7 @@ export function initProjectTree( } set({ unity, + unreal, mode, root, name, @@ -411,7 +437,7 @@ function initialExpanded(root: string | null, mode: ViewMode, members = get().me // Keys of nodes that no longer exist are inert. Only a first open expands the roots. const scope = projectLocation(root) ?? root; const persisted = - mode === "project" || mode === "unity" + mode === "project" || mode === "unity" || mode === "unreal" ? (readJson<string[]>(expandedKey(scope)) ?? (scope !== root ? readJson<string[]>(expandedKey(root)) : null)) : null; if (persisted) return new Set(persisted); @@ -419,11 +445,11 @@ function initialExpanded(root: string | null, mode: ViewMode, members = get().me } function persistExpanded() { - if (get().mode !== "project" && get().mode !== "unity") return; + if (get().mode !== "project" && get().mode !== "unity" && get().mode !== "unreal") return; clearTimeout(persistTimer); persistTimer = setTimeout(() => { const { root, expanded, mode } = get(); - if (root && (mode === "project" || mode === "unity")) + if (root && (mode === "project" || mode === "unity" || mode === "unreal")) writeJson(expandedKey(projectLocation(root) ?? root), [...expanded].slice(0, MAX_PERSISTED)); }, 300); } @@ -432,6 +458,7 @@ function persistExpanded() { export function setViewMode(mode: ViewMode) { const s = get(); if (mode === "unity" && !s.unity) return; + if (mode === "unreal" && !s.unreal) return; if (s.mode === mode) return; cancelExpansion(); modeExpanded.set(s.mode, s.expanded); @@ -901,6 +928,8 @@ export function modeShows(path: string, mode = get().mode): boolean { switch (mode) { case "unity": return !!state.unity && unityPathVisible(path, treeOptions({ ...state, mode })); + case "unreal": + return !!state.unreal && unrealPathVisible(path, treeOptions({ ...state, mode })); case "project": return true; case "projectFiles": diff --git a/src/features/run/ConfigForm.tsx b/src/features/run/ConfigForm.tsx index 1c6606e52..65e4ff759 100644 --- a/src/features/run/ConfigForm.tsx +++ b/src/features/run/ConfigForm.tsx @@ -61,6 +61,7 @@ import { PluginArgsInput } from "./PluginArgsInput"; import { pluginOwnedConfig } from "./pluginArgsCompletion"; import { useBuildModel } from "@/platform/buildModel"; import { COMPOUND, formParams, terminalApplies, withParams } from "./types"; +import { frameworkFor } from "./testing"; import { TomcatSettings } from "./TomcatSettings"; import { toolWindowTitle } from "@/workbench/toolwindows/title"; import styles from "./Run.module.css"; @@ -109,6 +110,7 @@ export type OptionId = | "openToolWindow" | "focusToolWindow" | "isTest" + | "watch" | "emulateTerminal"; const VALUE_OPTIONS: ReadonlySet<OptionId> = new Set([ @@ -131,13 +133,14 @@ const OPTION_LABELS: Record<OptionId, string> = { openToolWindow: "Open run/debug tool window when started", focusToolWindow: "Focus run/debug tool window when started", isTest: "Show results in the test runner", + watch: "Watch for changes", emulateTerminal: "Emulate terminal in output console", }; const OPTION_GROUPS: ReadonlyArray<{ label: string; options: OptionId[]; process: boolean }> = [ { label: "Operating System", options: ["allowParallel", "stdinFile", "envFiles", "emulateTerminal"], process: true }, { label: "Logs", options: ["outputFile", "showOnStdout", "showOnStderr"], process: true }, - { label: "Test", options: ["isTest"], process: true }, + { label: "Test", options: ["isTest", "watch"], process: true }, { label: "Before Launch", options: ["buildPolicy", "beforeLaunch", "openToolWindow", "focusToolWindow"], @@ -170,6 +173,8 @@ export function optionSet(config: RunConfig, id: OptionId, openByDefault: boolea return !!config.focusToolWindow; case "isTest": return config.isTest; + case "watch": + return !!config.watch; case "emulateTerminal": return !!config.emulateTerminal; } @@ -200,6 +205,8 @@ export function optionPatch(id: OptionId, on: boolean): Partial<RunConfig> { return { focusToolWindow: on }; case "isTest": return on ? { isTest: true, emulateTerminal: false } : { isTest: false }; + case "watch": + return { watch: on }; case "emulateTerminal": return { emulateTerminal: on }; } @@ -398,6 +405,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi }; const terminal = terminalApplies(config, type); + const watchApplies = config.isTest && frameworkFor(config) === "js"; // A terminal has no separate input file: the two options exclude each other. const blocked = (id: OptionId) => (id === "emulateTerminal" && isShown("stdinFile")) || (id === "stdinFile" && !!config.emulateTerminal); @@ -408,7 +416,8 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi (id) => (!compound || id === "beforeLaunch") && (id !== "emulateTerminal" || terminal || !!config.emulateTerminal) && - (id !== "buildPolicy" || buildPolicyApplies(config)), + (id !== "buildPolicy" || buildPolicyApplies(config)) && + (id !== "watch" || watchApplies), ) .map((id): MenuItem => ({ label: OPTION_LABELS[id], @@ -498,6 +507,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi "openToolWindow", "focusToolWindow", "isTest", + "watch", ] as const ).filter( (id) => (!noProcess || id === "openToolWindow" || id === "focusToolWindow") && optionSet(config, id, openByDefault), @@ -911,6 +921,12 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi </div> )} + {config.watch && watchApplies && !noProcess && ( + <div className={styles.notice}> + <T>Debug runs the tests once, without watching.</T> + </div> + )} + {!noProcess && !template && ( <div className={styles.editPreview}> <span className={styles.chooserMuted}> diff --git a/src/features/run/ConsoleView.tsx b/src/features/run/ConsoleView.tsx index e3609e75c..dd0aa1efa 100644 --- a/src/features/run/ConsoleView.tsx +++ b/src/features/run/ConsoleView.tsx @@ -128,6 +128,11 @@ export interface FileLink extends LinkPosition { } /** The file links on the `shown` lines (a collapsed fold hides its links), in output order. */ +/** A copy of a line the model may still append to (the open last line). */ +function copyLine(line: ConsoleLine): ConsoleLine { + return { ...line, spans: line.spans.map((span) => ({ ...span })) }; +} + export function fileLinks(lines: readonly ConsoleLine[], shown: (index: number) => boolean): FileLink[] { const links: FileLink[] = []; lines.forEach((line, i) => { @@ -257,7 +262,12 @@ export function ConsoleView({ }: ConsoleViewProps) { const scrollRef = useRef<HTMLDivElement>(null); const innerRef = useRef<HTMLDivElement>(null); - const lines = model.lines; + // Pause Output: the output so far stays on screen while the process keeps + // writing; resuming shows everything that arrived meanwhile. + const [paused, setPaused] = useState<readonly ConsoleLine[] | null>(null); + const lines = paused ?? model.lines; + const togglePaused = () => + setPaused((p) => (p ? null : model.lines.map((l, i, all) => (i === all.length - 1 ? copyLine(l) : l)))); const patterns = useWorkflowSettings((s) => s.console.foldPatterns); const logColors = useWorkflowSettings((s) => s.console.logColors); const consoleRules = compileConsoleRules(useConsoleRules((s) => s.providers)); @@ -539,7 +549,16 @@ export function ConsoleView({ // Opens Settings › Console with the text added to the fold patterns, for OK / Cancel there. run: () => void executeAction("file.settings", `build.console#${foldText}`), }, - { label: "Clear All", icon: "trash", disabled: !onClear, run: () => onClear?.() }, + { label: "Pause Output", icon: "pause", checked: !!paused, run: togglePaused }, + { + label: "Clear All", + icon: "trash", + disabled: !onClear, + run: () => { + setPaused(null); + onClear?.(); + }, + }, ...(input ? [{ kind: "separator" } as const, { label: "Send EOF", shortcut: "⌃D", run: () => input.onEof() }] : []), diff --git a/src/features/run/RunView.test.tsx b/src/features/run/RunView.test.tsx index e76307b9c..a58ec4389 100644 --- a/src/features/run/RunView.test.tsx +++ b/src/features/run/RunView.test.tsx @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { RunConfig } from "@/platform/ipc"; import { debugSession, resetRuns, useRun, type RunSession } from "./store"; -import { sessionIcon } from "./RunView"; +import { sessionIcon, testsRun } from "./RunView"; const actions = vi.hoisted(() => ({ executeAction: vi.fn() })); vi.mock("@/platform/actions", async (orig) => ({ ...(await orig<object>()), executeAction: actions.executeAction })); @@ -80,3 +80,13 @@ describe("debugSession", () => { expect(actions.executeAction).not.toHaveBeenCalled(); }); }); + +describe("testsRun", () => { + const live = { status: "running" } as RunSession; + it("ends a watch run's tests with each cycle", () => { + expect(testsRun({ ...live, watching: true }, { finished: false })).toBe("running"); + expect(testsRun({ ...live, watching: true }, { finished: true })).toBe("done"); + expect(testsRun(live, { finished: true })).toBe("running"); + expect(testsRun({ ...live, status: "finished" }, { finished: false })).toBe("done"); + }); +}); diff --git a/src/features/run/RunView.tsx b/src/features/run/RunView.tsx index c1e729ffd..58190ea02 100644 --- a/src/features/run/RunView.tsx +++ b/src/features/run/RunView.tsx @@ -38,6 +38,7 @@ import { rerunSession, resizeTerminal, runSelectedTests, + toggleRerunAutomatically, runtime, sendStdin, setPendingInput, @@ -50,7 +51,7 @@ import { pinSession, } from "./store"; import { rerunFailedConfigs } from "./testing/rerun"; -import { formatDuration, nodeOutput } from "./testing"; +import { formatDuration, frameworkFor, nodeOutput } from "./testing"; import { TestStatusBar, TestTreeView } from "./TestTreeView"; import { StackTracePanel, useStackTraces, type StackTraceTab } from "./stackTrace"; import { ThreadDumpPanel } from "./threadDump/ThreadDumpPanel"; @@ -143,6 +144,7 @@ export function SessionPanel({ if (hasTests) testSplit.current?.setLayout(testLayouts.current[testOrientation]); }, [hasTests, testOrientation]); const running = isLive(session); + const testsRunning = testsRun(session, rt?.tests) === "running"; const cwd = runDirectory(session.config.cwd); const baseConfig = useRun(() => baseConfigOf(session)); // Test results mutate in place; their version refreshes the selection. @@ -211,7 +213,7 @@ export function SessionPanel({ const consoleColumn = ( <div className={styles.consoleColumn}> - {rt.tests && <TestStatusBar results={rt.tests} version={version} running={running} />} + {rt.tests && <TestStatusBar results={rt.tests} version={version} running={testsRunning} />} {rt.console.dropped > 0 && !testModel && ( <div className={styles.notice}>{tx`${rt.console.dropped.toLocaleString()} earlier lines were discarded`}</div> )} @@ -411,7 +413,7 @@ export function SessionPanel({ results={rt.tests} version={version} cwd={cwd} - running={running} + running={testsRunning} name={session.config.name} selected={selectedTest} onSelect={setSelectedTest} @@ -419,6 +421,11 @@ export function SessionPanel({ onUpdateSnapshots={(ids) => void updateSnapshots(session.id, ids)} canRunTests={(ids) => canRunSelectedTests(session.id, ids)} onRunTests={(ids, debug) => void runSelectedTests(session.id, ids, debug)} + rerunAutomatically={ + frameworkFor(session.config) === "js" + ? { on: !!session.watching && running, toggle: () => toggleRerunAutomatically(session.id) } + : undefined + } /> </SplitPanel> <SplitHandle /> @@ -434,6 +441,14 @@ export function SessionPanel({ ); } +/** + * Whether a session's tests still run: a watch run's are done at the end of each cycle, like a + * finished run (status, Sort by Duration, Select First Failed). + */ +export function testsRun(session: RunSession, tests: { finished: boolean } | null | undefined): "running" | "done" { + return isLive(session) && !(session.watching && tests?.finished) ? "running" : "done"; +} + function sessionItems(sessions: readonly RunSession[], targets: readonly RunTargetValid[]): TabItem[] { return sessions.map((s) => { const label = remoteLabel(s.config, targets); diff --git a/src/features/run/TestTreeView.test.tsx b/src/features/run/TestTreeView.test.tsx index 66e3f5015..a891a6eb7 100644 --- a/src/features/run/TestTreeView.test.tsx +++ b/src/features/run/TestTreeView.test.tsx @@ -168,6 +168,28 @@ describe("TestTreeView", () => { ); }); +it("shows Rerun Automatically only where watch mode applies", () => { + const { unmount } = render(<Host />); + expect(screen.queryByRole("button", { name: "Rerun Automatically" })).toBeNull(); + unmount(); + const toggle = vi.fn(); + render( + <TestTreeView + results={results()} + version={1} + cwd="/p" + selected={null} + onSelect={() => {}} + running + rerunAutomatically={{ on: true, toggle }} + />, + ); + const button = screen.getByRole("button", { name: "Rerun Automatically" }); + expect(button.getAttribute("aria-pressed")).toBe("true"); + fireEvent.click(button); + expect(toggle).toHaveBeenCalledOnce(); +}); + describe("Previous / Next Failed Test", () => { const navigate = vi.fn(); beforeEach(() => { diff --git a/src/features/run/TestTreeView.tsx b/src/features/run/TestTreeView.tsx index e00446199..fcd420ef3 100644 --- a/src/features/run/TestTreeView.tsx +++ b/src/features/run/TestTreeView.tsx @@ -194,6 +194,8 @@ export interface TestTreeViewProps { /** Run / Debug the selected tests (context menu); absent when the configuration can't be narrowed. */ onRunTests?: (ids: string[], debug: boolean) => void; canRunTests?: (ids: string[]) => boolean | Promise<boolean>; + /** Jest / Vitest runs: the "Rerun Automatically" (watch mode) toggle. */ + rerunAutomatically?: { on: boolean; toggle: () => void }; } export function TestTreeView({ @@ -208,6 +210,7 @@ export function TestTreeView({ canUpdateSnapshots, onRunTests, canRunTests, + rerunAutomatically, }: TestTreeViewProps) { const [filters, setFilters] = useState(loadTestFilters); const { showPassed, showIgnored, showDurations, selectFirstFailed, sortAlphabetically, sortByDuration } = filters; @@ -385,6 +388,16 @@ export function TestTreeView({ return ( <div className={styles.testPane}> <Toolbar className={styles.testToolbar} aria-label="Test results"> + {rerunAutomatically && ( + <IconButton + icon="rerun-automatically" + size="small" + iconSize={16} + title="Rerun Automatically" + pressed={rerunAutomatically.on} + onClick={rerunAutomatically.toggle} + /> + )} <div className={styles.testFilters}> <IconButton icon="test-show-passed" diff --git a/src/features/run/configs.ts b/src/features/run/configs.ts index 4d03c121b..8b767d955 100644 --- a/src/features/run/configs.ts +++ b/src/features/run/configs.ts @@ -69,6 +69,7 @@ export const KIND_CATEGORIES: Record<string, string> = { node: "JavaScript", bun: "JavaScript", deno: "JavaScript", + cypress: "JavaScript", python: "Python", pytest: "Python", cargo: "Rust", diff --git a/src/features/run/consolePauseOutput.test.tsx b/src/features/run/consolePauseOutput.test.tsx new file mode 100644 index 000000000..b5739f595 --- /dev/null +++ b/src/features/run/consolePauseOutput.test.tsx @@ -0,0 +1,52 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { act, fireEvent, render, within } from "@testing-library/react"; +import { useProject } from "@/platform/project"; +import { hideContextMenu, useContextMenuStore } from "@/ui"; +import { ConsoleModel } from "./console"; +import { ConsoleView } from "./ConsoleView"; + +vi.mock("@tanstack/react-virtual", () => ({ + useVirtualizer: ({ count }: { count: number }) => ({ + getTotalSize: () => count * 20, + getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 20, key: index })), + scrollToIndex: () => {}, + measureElement: () => {}, + measure: () => {}, + }), +})); + +beforeEach(() => useProject.setState({ settings: null })); +afterEach(() => act(hideContextMenu)); + +function pauseItem(log: Element) { + fireEvent.contextMenu(log); + const items = useContextMenuStore.getState().menu?.items ?? []; + return items.find((i) => "label" in i && i.label === "Pause Output") as + | { checked?: boolean; run?: () => void } + | undefined; +} + +it("Pause Output keeps the output on screen until it is resumed, then shows what arrived meanwhile", () => { + const model = new ConsoleModel(); + model.append({ kind: "stdout", text: "first\nsecond " }); + const view = (version: number) => ( + <ConsoleView model={model} version={version} softWrap={false} follow={false} onFollowChange={() => {}} cwd="/" /> + ); + const { container, rerender } = render(view(1)); + const log = within(container).getByRole("log"); + expect(pauseItem(log)?.checked).toBe(false); + act(() => pauseItem(log)!.run!()); + + // The open line and new lines keep arriving while paused, but are not shown. + model.append({ kind: "stdout", text: "half\nthird\n" }); + rerender(view(2)); + expect(log.textContent).toContain("first"); + expect(log.textContent).toContain("second"); + expect(log.textContent).not.toContain("half"); + expect(log.textContent).not.toContain("third"); + expect(pauseItem(log)?.checked).toBe(true); + + act(() => pauseItem(log)!.run!()); + expect(log.textContent).toContain("second half"); + expect(log.textContent).toContain("third"); +}); diff --git a/src/features/run/context.ts b/src/features/run/context.ts index 775dea353..87cdc9811 100644 --- a/src/features/run/context.ts +++ b/src/features/run/context.ts @@ -8,6 +8,7 @@ import { jvmModuleDir } from "@/platform/javaLaunch"; import { djangoLabel, djangoTestsOf, hasDjangoTests } from "./djangoTypes"; import { inGradleModule } from "./gradleModuleTests"; import { systemPython } from "./pythonTypes"; +import { cypressSelection, isCypressComponentSpec } from "./testing/cypress"; import { phpunitArgs } from "./testing/phpunit"; import { frameworkFor } from "./testing"; import { goTestParts } from "./goArguments"; @@ -55,7 +56,7 @@ const stem = (p: string) => (p.split("/").pop() ?? p).replace(/\.[^.]+$/, ""); /** Kinds whose test configs can run a file of this extension. */ function testKinds(relPath: string): string[] { if (/\.cs$/i.test(relPath)) return ["dotnet-test"]; - if (/\.[cm]?[jt]sx?$/.test(relPath)) return ["npm", "deno", "bun", "node"]; + if (/\.[cm]?[jt]sx?$/.test(relPath)) return ["npm", "deno", "bun", "node", "cypress"]; if (/\.py$/.test(relPath)) return ["pytest", "python", "django-test"]; if (/\.php$/.test(relPath)) return ["phpunit"]; if (/_spec\.rb$/.test(relPath)) return ["rspec", "rake", "ruby"]; @@ -211,6 +212,16 @@ function byRunner(bases: RunConfig[], content: string): RunConfig[] { return isPlaywrightSpec(content) ? playwright : bases.filter((c) => !playwright.includes(c)); } +/** + * Cypress specs (`*.cy.*`, files in `cypress/`) run on the project's Cypress configurations, however far, when it + * has any; other files never do, so they keep their runner (Vitest at the workspace root…) as before. + */ +function byCypress(candidates: RunConfig[], relPath: string): RunConfig[] { + const cypress = candidates.filter((c) => frameworkFor(c) === "cypress"); + const spec = /\.cy\.[cm]?[jt]sx?$|(^|\/)cypress\//.test(relPath); + return spec && cypress.length ? cypress : candidates.filter((c) => !cypress.includes(c)); +} + /** * Test configurations that can run `relPath` equally well (same, closest working * directory: `npm run test` and `npm run test:unit`…); the default one first. @@ -224,7 +235,7 @@ export function testBasesFor(relPath: string, configs: RunConfig[], content?: st // `node` configurations run a file of their own; only Playwright's (`npx playwright test`) take a test file. .filter((c) => c.kind !== "node" || frameworkFor(c) === "playwright") .sort((a, b) => kinds.indexOf(a.kind) - kinds.indexOf(b.kind)); - const best = allClosest(candidates, relPath); + const best = allClosest(byCypress(candidates, relPath), relPath); if (best.length) return content === undefined ? best : byRunner(best, content); const fallback = implicitPytest(relPath, configs); return fallback ? [fallback] : []; @@ -243,6 +254,13 @@ export function testConfigFor( base ??= testBasesFor(relPath, configs, content)[0]; if (!base) return null; const file = relToCwd(relPath, base); + if (frameworkFor(base) === "cypress") { + return derived( + base, + relPath, + cypressSelection(base, [file], { component: isCypressComponentSpec(relPath, content) }), + ); + } switch (base.kind) { case "dotnet-test": { const methods = csharpTargets(content ?? "") diff --git a/src/features/run/contextRun.test.ts b/src/features/run/contextRun.test.ts index acf6f1583..610204727 100644 --- a/src/features/run/contextRun.test.ts +++ b/src/features/run/contextRun.test.ts @@ -400,6 +400,38 @@ describe("Debug entry", () => { }); }); +describe("Go tests in the project view", () => { + const goTest: RunConfig = { + ...npmTest, + id: "go:test", + name: "go test ./...", + kind: "go", + command: "go", + args: ["test", "./..."], + debugAdapter: "delve", + }; + const view = (path: string, dir: boolean) => + labels(contextMenuItems("projectView", { paths: [path], dirs: [dir] })).filter((l) => !l.startsWith("run.modify")); + + beforeEach(() => { + useProject.setState({ project: { name: "app", root: ROOT, trusted: true, isGit: false, settings: {} } as never }); + useRun.setState({ configs: [goTest], loaded: true }); + }); + afterEach(() => { + useProject.setState({ project: null }); + useRun.setState({ configs: [], loaded: false }); + }); + + it("a package directory and the module root: Run / Debug 'go test <package>/...'", () => { + expect(view(`${ROOT}/cart`, true)).toEqual([ + "run.runContext|Run 'go test cart/...'|run", + "run.debugContext|Debug 'go test cart/...'|debug", + ]); + expect(view(ROOT, true)[0]).toBe("run.runContext|Run 'go test ./...'|run"); + expect(view(`${ROOT}/cart/testdata`, true)).toEqual([]); + }); +}); + describe("Run with Fuzzing", () => { const goTest: RunConfig = { ...npmTest, diff --git a/src/features/run/cypressType.ts b/src/features/run/cypressType.ts new file mode 100644 index 000000000..26fd69668 --- /dev/null +++ b/src/features/run/cypressType.ts @@ -0,0 +1,153 @@ +/** + * Cypress tests (WebStorm's "Cypress" configuration): `npx cypress run` in the project's directory, with + * the testing type (end-to-end or component), the browser, the specs and further options. + */ +import { call, commands, type RunConfig } from "@/platform/ipc"; +import { notifications, type RunConfigTypeContribution } from "@/workbench/contributions"; +import { formatArgs, parseArgs } from "./configs"; +import { joinPath } from "./links"; +import { runDirectory } from "./navigate"; +import { appendScriptArgs } from "./scriptArgs"; +import { CYPRESS_GREP } from "./testing/cypress"; + +const BROWSERS = ["chrome", "chromium", "edge", "electron", "firefox"]; + +/** Plugins that select tests by the titles in `grep` (`@cypress/grep` and its predecessors). */ +const GREP_PLUGINS = ["@cypress/grep", "cypress-grep", "@bahmutov/cy-grep"]; + +/** The run directory and the project folders above it (workspaces keep dependencies at the root). */ +function searchDirs(cwd: string | null | undefined): string[] { + const root = runDirectory(null); + const dirs: string[] = []; + for (let dir = runDirectory(cwd); dir.startsWith(root); dir = dir.slice(0, dir.lastIndexOf("/"))) { + dirs.push(dir); + if (dir === root) break; + } + return dirs; +} + +async function readJson(path: string): Promise<Record<string, unknown> | null> { + try { + return JSON.parse(await call(commands.fsReadText(path))) as Record<string, unknown>; + } catch { + return null; + } +} + +/** The installed Cypress's `[major, minor]`. */ +async function versionIn(dir: string): Promise<[number, number] | null> { + const pkg = await readJson(joinPath(dir, "node_modules/cypress/package.json")); + const m = /^(\d+)\.(\d+)/.exec(String(pkg?.version)); + return m ? [Number(m[1]), Number(m[2])] : null; +} + +/** Whether `dir/package.json` depends on a grep plugin. */ +async function dependsOnGrep(dir: string): Promise<boolean> { + const pkg = await readJson(joinPath(dir, "package.json")); + const deps = [pkg?.dependencies, pkg?.devDependencies].flatMap((d) => Object.keys(d ?? {})); + return deps.some((d) => GREP_PLUGINS.includes(d)); +} + +/** + * A run selecting tests by title (`CYPRESS_grep`): with a grep plugin, also as `--expose grep=…`, where + * `@cypress/grep` 7 reads it (Cypress 15.10 added `--expose`, which older versions reject). Without one, + * the whole spec runs: a notification says so, so the run doesn't pass for the selected tests alone. + */ +export async function prepareCypressLaunch<T extends RunConfig>(config: T): Promise<T> { + const grep = config.env[CYPRESS_GREP]; + if (!grep) return config; + const dirs = searchDirs(config.cwd); + const [plugins, versions] = await Promise.all([ + Promise.all(dirs.map(dependsOnGrep)), + Promise.all(dirs.map(versionIn)), + ]); + if (!plugins.includes(true)) { + notifications().notify({ + group: "run", + level: "info", + key: "cypress-grep", + title: "Cypress ran the whole spec file", + body: "Cypress can select tests by name only through a grep plugin such as @cypress/grep, which this project doesn't depend on: every test of the spec ran.", + }); + return config; + } + const version = versions.find((v) => v !== null); + if (config.args.some((a) => a === "--expose" || a.startsWith("--expose="))) return config; + if (!version || version[0] < 15 || (version[0] === 15 && version[1] < 10)) return config; + return { + ...config, + args: appendScriptArgs(config.command, config.args, ["--expose", JSON.stringify({ grep, grepOmitFiltered: true })]), + }; +} + +export const cypressType: RunConfigTypeContribution = { + id: "cypress", + label: "Cypress", + icon: "file-js", + description: "Run Cypress tests", + defaults: { testingType: "e2e" }, + ownsWorkingDirectory: true, + terminal: false, + prepareLaunch: prepareCypressLaunch, + fields: [ + { + key: "packageDir", + label: "Cypress project directory", + mono: true, + browse: "directory", + placeholder: "Project root", + }, + { + key: "testingType", + label: "Testing type", + control: "select", + options: [ + { value: "e2e", label: "End-to-end" }, + { value: "component", label: "Component" }, + ], + }, + { + key: "browser", + label: "Browser", + mono: true, + placeholder: "Electron", + hint: "Passed as --browser: a browser name or the path to its executable", + suggestions: () => BROWSERS, + }, + { + key: "spec", + label: "Specs", + mono: true, + placeholder: "e.g. cypress/e2e/**/*.cy.ts", + hint: "Passed as --spec: files or globs, comma separated; empty runs every spec", + }, + { key: "options", label: "Cypress options", mono: true, placeholder: "e.g. --headed --config video=true" }, + ], + commandLine(p) { + const args = ["cypress", "run"]; + if (p.testingType === "component") args.push("--component"); + if (p.browser?.trim()) args.push("--browser", p.browser.trim()); + if (p.spec?.trim()) args.push("--spec", p.spec.trim()); + args.push(...parseArgs(p.options ?? "")); + return { command: "npx", args, cwd: p.packageDir?.trim() || null }; + }, + paramsFrom(c) { + if (c.command !== "npx" || c.args[0] !== "cypress" || c.args[1] !== "run") return null; + const args = c.args.slice(2); + const take = (...flags: string[]): string => { + const at = args.findIndex((a) => flags.includes(a)); + if (at < 0 || at + 1 >= args.length) return ""; + return args.splice(at, 2)[1]!; + }; + const component = args.includes("--component"); + const browser = take("--browser", "-b"); + const spec = take("--spec", "-s"); + return { + packageDir: c.cwd ?? "", + testingType: component ? "component" : "e2e", + browser, + spec, + options: formatArgs(args.filter((a) => a !== "--component" && a !== "--e2e")), + }; + }, +}; diff --git a/src/features/run/executors.ts b/src/features/run/executors.ts index 656651106..b9b94600f 100644 --- a/src/features/run/executors.ts +++ b/src/features/run/executors.ts @@ -4,6 +4,7 @@ * any other, and the executor hears when the process exits. */ import type { RunConfig } from "@/platform/ipc"; +import { executeAction } from "@/platform/actions"; import { notifications, useRunExecutors, type ExecutorLaunch } from "@/workbench/contributions"; import { containerExecutorBlocked } from "./remote"; import { prepareLaunch, startRun } from "./store"; @@ -11,8 +12,9 @@ import { prepareLaunch, startRun } from "./store"; export async function runWithExecutor(config: RunConfig, executorId: string): Promise<void> { const executor = useRunExecutors.getState().executors.get(executorId); if (!executor) return; - if (containerExecutorBlocked(config)) return; - if (!(await prepareLaunch(config))) return; + if (!executor.checksTarget && containerExecutorBlocked(config)) return; + // Debug runs the before-launch tasks itself. + if (!executor.debug && !(await prepareLaunch(config))) return; let plan: ExecutorLaunch | null; try { plan = await executor.prepare(config); @@ -28,6 +30,10 @@ export async function runWithExecutor(config: RunConfig, executorId: string): Pr } if (!plan) return; const { launch, finished, beforeStop } = plan; + if (executor.debug) { + await executeAction("run.debugConfig", launch); + return; + } await startRun(config, undefined, undefined, { launch, onExit: (exitCode, stopped) => finished({ exitCode, stopped }), diff --git a/src/features/run/links.ts b/src/features/run/links.ts index 646062baf..0464b1169 100644 --- a/src/features/run/links.ts +++ b/src/features/run/links.ts @@ -19,6 +19,8 @@ export interface FileTarget { resolve: "path" | "name" | "rubyTest"; /** JVM frames: the class's binary name (`com.acme.OrderController$Inner`). */ className?: string; + /** No line: the describe chain and name of a JS test, found in the file (Cypress prints no line). */ + test?: string[]; } /** diff --git a/src/features/run/navigate.test.ts b/src/features/run/navigate.test.ts index 32bc39dac..a32aaaa48 100644 --- a/src/features/run/navigate.test.ts +++ b/src/features/run/navigate.test.ts @@ -6,6 +6,8 @@ const files: Record<string, string> = { "/p/src/main/java/com/acme/Util.java": "package com.acme;\nclass Util {}", "/p/other/Util.java": "package org.other;\nclass Util {}", "/p/src/main/kotlin/Orders.kt": "package com.acme.orders\nfun main() {}", + "/p/cypress/e2e/cart.cy.ts": + 'describe("cart", () => {\n it("adds", () => {});\n context("totals", () => {\n it("adds", () => {});\n });\n});', }; const symbols = vi.hoisted(() => ({ list: [] as unknown[] })); @@ -27,7 +29,16 @@ vi.mock("@/platform/ipc", () => ({ }, })); -const { resolveTarget } = await import("./navigate"); +const { declarationLine, resolveTarget } = await import("./navigate"); + +describe("JS tests without a line", () => { + it("are found in their file by describe chain and name", async () => { + expect(await declarationLine("/p/cypress/e2e/cart.cy.ts", ["cart", "totals", "adds"])).toBe(4); + expect(await declarationLine("/p/cypress/e2e/cart.cy.ts", ["cart", "adds"])).toBe(2); + expect(await declarationLine("/p/cypress/e2e/cart.cy.ts", ["cart", "gone"])).toBeUndefined(); + // The first call loads the run targets' parsers. + }, 60_000); +}); describe("JVM stack frame resolution", () => { afterEach(() => { diff --git a/src/features/run/navigate.ts b/src/features/run/navigate.ts index d3f7f1367..bae41f798 100644 --- a/src/features/run/navigate.ts +++ b/src/features/run/navigate.ts @@ -120,6 +120,18 @@ async function searchRuby(pattern: string, files?: string[]) { return out.sort((a, b) => a.relPath.localeCompare(b.relPath)); } +/** 1-based line declaring the JS test (or suite) with this describe chain and name. */ +export async function declarationLine(path: string, test: string[]): Promise<number | undefined> { + try { + const { detectRunTargets } = await import("./targets"); + const text = await call(commands.fsReadText(path)); + const found = detectRunTargets(text, path).find((t) => t.path.join("\u0000") === test.join("\u0000")); + return found ? found.line + 1 : undefined; + } catch { + return undefined; + } +} + export async function openTarget(target: FileTarget, cwd: string, focus = true): Promise<void> { if (!isTauri()) return; if (target.resolve === "rubyTest") { @@ -161,7 +173,8 @@ export async function openTarget(target: FileTarget, cwd: string, focus = true): }); return; } - const selection = target.line ? { line: target.line - 1, col: Math.max(0, (target.col ?? 1) - 1) } : undefined; + const line = target.line ?? (target.test ? await declarationLine(path, target.test) : undefined); + const selection = line ? { line: line - 1, col: Math.max(0, (target.col ?? 1) - 1) } : undefined; await editorService().openFile(path, { selection, focus }); } diff --git a/src/features/run/producers.test.ts b/src/features/run/producers.test.ts index 8fd4fff02..2e03ba0fd 100644 --- a/src/features/run/producers.test.ts +++ b/src/features/run/producers.test.ts @@ -1311,6 +1311,88 @@ describe("Go test names (GoLand)", () => { expect(dir.config!.name).toBe(dir.name); }); + describe("any package directory, like GoLand: 'go test <import path>/...'", () => { + const dirAt = (rel: string, configs = GO) => + produceDirectory({ path: rel ? `${ROOT}/${rel}` : ROOT, root: ROOT, configs, goModule: modules }); + + it("a package and a folder of packages", () => { + const cart = dirAt("cart")!; + expect(cart.name).toBe("go test example.com/fixture/cart/..."); + expect(cart.config).toMatchObject({ args: ["test", "./cart/..."], isTest: true, debugAdapter: "delve" }); + expect(dirAt("internal/pricing")!.config!.args).toEqual(["test", "./internal/pricing/..."]); + }); + + it("the module root: the whole module", () => { + const all = dirAt("")!; + expect(all.name).toBe("go test example.com/fixture/..."); + expect(all.config!.args).toEqual(["test", "./..."]); + }); + + it("a nested module's folder runs from that module", () => { + const nested = [ + cfg({ id: "go:test:api", kind: "go", command: "go", args: ["test", "./..."], cwd: "api", isTest: true }), + ]; + expect(dirAt("api", nested)!.config).toMatchObject({ args: ["test", "./..."], cwd: "api" }); + expect(dirAt("api/cart", nested)!.config!.args).toEqual(["test", "./cart/..."]); + // Outside the only Go module. + expect(dirAt("web", nested)).toBeNull(); + }); + + it("keeps the configuration's flags and program arguments, not its packages", () => { + const own = [ + cfg({ + id: "go:own", + kind: "go", + command: "go", + args: ["test", "-race", "./cart", "-args", "-v"], + isTest: true, + }), + ]; + expect(dirAt("pricing", own)!.config!.args).toEqual(["test", "-race", "./pricing/...", "-args", "-v"]); + }); + + it("a Go Test form configuration gets the directory as its target", () => { + const form = [ + cfg({ + id: "go:form", + kind: "go", + command: "go", + args: ["test", "./..."], + isTest: true, + params: { goKind: "test", scope: "package", target: "./...", useTags: "true" }, + }), + ]; + expect(dirAt("cart", form)!.config!.params).toMatchObject({ scope: "directory", target: "./cart/..." }); + }); + + it("folders go test skips, and folders of a closer non-Go test configuration, get nothing", () => { + for (const rel of ["testdata", "cart/testdata", ".github", "_tools", "vendor/example.com/lib"]) + expect(dirAt(rel), rel).toBeNull(); + const web = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"], cwd: "web", isTest: true }); + expect(dirAt("web/src", [...GO, web])).toBeNull(); + // Without a Go test configuration, a plain folder still gets nothing. + expect(dirAt("cart", [GO[0]!])).toBeNull(); + }); + + it("folders as close to other tests, and folders outside the project, get nothing", () => { + const npm = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"], isTest: true }); + const pytest = cfg({ id: "pytest", kind: "pytest", command: "pytest", isTest: true }); + expect(dirAt("src", [...GO, npm])).toBeNull(); + expect(dirAt("scripts", [...GO, pytest])).toBeNull(); + const attached = { root: ROOT, configs: GO, goModule: modules, contentRoots: ["/work/web"] }; + expect(produceDirectory({ ...attached, path: "/work/web" })).toBeNull(); + expect(produceDirectory({ ...attached, path: "/work/web/src" })).toBeNull(); + }); + + it("skipped names count inside the module only", () => { + const tools = [ + cfg({ id: "go:test:tools", kind: "go", command: "go", args: ["test", "./..."], cwd: "_tools", isTest: true }), + ]; + expect(dirAt("_tools/lint", tools)!.config).toMatchObject({ args: ["test", "./lint/..."], cwd: "_tools" }); + expect(dirAt("_tools/testdata", tools)).toBeNull(); + }); + }); + it("without go.mod read yet: the package clause", () => { expect(at(5).name).toBe("TestAdd in calc"); expect(at(undefined).name).toBe("go test calc"); diff --git a/src/features/run/producers.ts b/src/features/run/producers.ts index 4fae57c8a..abce3affb 100644 --- a/src/features/run/producers.ts +++ b/src/features/run/producers.ts @@ -38,6 +38,7 @@ import { goFuzzConfig, targetConfig, targetLanguage, + specsInSpecDirectory, testsInTestDirectory, zigTargets, type RunTarget, @@ -1153,7 +1154,13 @@ export function fileTargets( (t) => t.kind === "main" && (!t.className || /\.(java|kt)$/.test(input.path)), ); } - const targets = detectRunTargets(content, s.rel, hasDjangoTests(input.configs), testsInTestDirectory(input.configs)); + const targets = detectRunTargets( + content, + s.rel, + hasDjangoTests(input.configs), + testsInTestDirectory(input.configs), + specsInSpecDirectory(input.configs), + ); return /\.java$/.test(input.path) ? [...targets, ...inheritedRunTargets(input.path, content)] : targets; } @@ -1266,6 +1273,8 @@ function cmakeTargets(input: ContextInput): RunConfig[] { // Directories (project view): "Run 'Tests in 'dir''", "Run 'All Tests'" const TEST_DIR = /(^|\/)(tests?|__tests__|specs?|test_?\w*)$/; +/** Folders `go test ./...` never builds packages from: `testdata`, `vendor`, names starting with `.` or `_`. */ +const GO_SKIPPED_DIR = /(^|\/)(testdata|vendor|[._][^/]*)(\/|$)/; /** * The tests of a Ruby folder: RSpec on the folder, `rake test` with `TEST=<glob>`, or the @@ -1298,14 +1307,13 @@ function rubyDirectory( export function produceDirectory(input: ContextInput): Produced | null { input = scopedInput(input); const { root } = input; - if (!root || !isProjectPath(input) || input.path === root) return null; - const rel = relTo(input.path, root); + if (!root || !isProjectPath(input)) return null; + const rel = input.path === root ? "" : relTo(input.path, root); const name = baseName(rel); const jvmRoot = /^(?:(.*)\/)?src\/test(?:\/(java|kotlin|scala|groovy))?$/.exec(rel); const jvmPackage = /^(?:(.*)\/)?src\/test\/(?:java|kotlin|scala|groovy)\/(.+)$/.exec(rel); const marked = isTestPath(currentRoots(), rel); const tests = input.configs.filter((c) => c.isTest); - if (!TEST_DIR.test(rel) && !jvmRoot && !jvmPackage && !marked && !/(^|\/)src\/test(\/|$)/.test(rel)) return null; const closest = (kinds: string[]) => allClosest( tests.filter((c) => kinds.includes(c.kind)), @@ -1325,6 +1333,25 @@ export function produceDirectory(input: ContextInput): Produced | null { }, }); const testsIn = `Tests in '${name}'`; + const goTests = (base: RunConfig | undefined): Produced | null => { + if (base?.args[0] !== "test") return null; + const dir = relToCwd(base); + // Outside the module (an attached project's folder), or a folder `go test` skips. + if (/^(\/|[A-Za-z]:\/)/.test(dir) || GO_SKIPPED_DIR.test(dir)) return null; + const target = dir ? `./${dir}/...` : "./..."; + const parts = goTestParts(base.args); + const p = make(base, testsIn, ["test", ...parts.flags, target, ...parts.program]); + const config = goTestNamed( + base.params?.goKind ? { ...p.config!, params: { ...base.params, scope: "directory", target } } : p.config!, + input, + ); + return { ...p, name: config.name, config }; + }; + if (!rel || (!TEST_DIR.test(rel) && !jvmRoot && !jvmPackage && !marked && !/(^|\/)src\/test(\/|$)/.test(rel))) { + // Like GoLand, any folder of a Go module runs the packages under it, unless it belongs as closely to other tests. + const owners = allClosest(tests, rel); + return owners.every((c) => c.kind === "go") ? goTests(owners[0]) : null; + } if (jvmRoot || jvmPackage || /(^|\/)src\/test(\/|$)/.test(rel)) { const base = closest(["gradle", "maven"]); @@ -1361,17 +1388,7 @@ export function produceDirectory(input: ContextInput): Produced | null { if (js.kind === "deno") return make(js, testsIn, [...js.args, dir]); return make(js, testsIn, js.args.includes("--") ? [...js.args, dir] : [...js.args, "--", dir]); } - if (go) { - const dir = relToCwd(go); - const p = make( - go, - testsIn, - go.args.map((a) => (a === "./..." ? `./${dir}/...` : a)), - ); - const config = goTestNamed(p.config!, input); - return { ...p, name: config.name, config }; - } - return null; + return goTests(go); } /** All tools a production for this input may ask about (looked up before launching). */ diff --git a/src/features/run/services.test.ts b/src/features/run/services.test.ts index 8fc3d345c..7ad81f60a 100644 --- a/src/features/run/services.test.ts +++ b/src/features/run/services.test.ts @@ -27,7 +27,12 @@ import { } from "./services"; import { KIND_OPTIONS, categoryOf } from "./configs"; import { startedPort } from "@/platform/serverPort"; -import { registerRunConfigType, useDebugRunSessions, type DebugServiceSession } from "@/workbench/contributions"; +import { + registerRunConfigType, + registerRunExecutor, + useDebugRunSessions, + type DebugServiceSession, +} from "@/workbench/contributions"; import { useRun, type RunSession } from "./store"; const { startRun, stopServiceSessions, openUrl, showContextMenu } = vi.hoisted(() => ({ @@ -427,6 +432,33 @@ describe("running service count (the Services badge)", () => { expect(runningServiceCount()).toBe(2); }); + it("describes a configuration node to other features and offers its executors", () => { + useRun.setState({ configs: [dev], sessions: [session("s1", dev, "running", 1)] }); + const node = { key: "run:config:dev", label: "dev", icon: "" }; + expect(runServiceProvider.context!(node)).toEqual({ + provider: "runConfigurations", + id: "dev", + kind: dev.kind, + name: "dev", + running: true, + runConfigurationId: "dev", + }); + expect(runServiceProvider.context!({ key: `run:type:${dev.kind}`, label: "", icon: "" })).toBeNull(); + const off = registerRunExecutor({ + id: "probe", + label: (name) => `Probe '${name}'`, + icon: "run", + action: "probe.run", + supports: (c) => c.id === "dev", + prepare: async () => null, + }); + const labels = runServiceProvider.menu!(node).flatMap((e) => + e.kind === "separator" || e.kind === "header" || e.kind === "action" ? [] : [e.label], + ); + expect(labels).toContain("Probe 'dev'"); + off(); + }); + it("does not count a configuration removed from the window while it runs", () => { useRun.setState({ configs: [dev], sessions: [session("s1", dev, "running", 1)] }); const node = { key: "run:config:dev", label: "dev", icon: "" }; diff --git a/src/features/run/services.tsx b/src/features/run/services.tsx index b8321e2c6..34fdb3319 100644 --- a/src/features/run/services.tsx +++ b/src/features/run/services.tsx @@ -18,6 +18,7 @@ import type { MenuItem } from "@/ui"; import { toolWindowService, notifications, + runExecutors, useRunConfigTypes, useDebugRunSessions, useServicesRunningCount, @@ -27,6 +28,7 @@ import { type ServiceTreeItem, } from "@/workbench/contributions"; import { pickServices } from "./serviceImport"; +import { runWithExecutor } from "./executors"; import { CATEGORY_ORDER, categoryOf, commandLine, configIcon, KIND_OPTIONS, kindLabel } from "./configs"; import { openUrl } from "./navigate"; import { showApplicationUpdate } from "./applicationUpdate"; @@ -742,6 +744,18 @@ function menu(item: ServiceTreeItem): MenuItem[] { const config = r.config; const session = r.session?.run; const debuggerSession = serviceDebugger(r.session) ?? r.session?.debug.at(-1); + // IDEA: the configuration's other executors (Run with Coverage, Profile, plugins' executors). + const executors = runExecutors().filter((e) => e.supports(config)); + if (executors.length) + items.push( + { kind: "separator" }, + ...executors.map((e): MenuItem => ({ + id: `executor:${e.id}`, + label: e.label(config.name), + icon: e.icon, + run: () => void runWithExecutor(config, e.id), + })), + ); items.push( { kind: "separator" }, { @@ -925,6 +939,18 @@ export const runServiceProvider: ServiceProviderContribution = { useRoots, actions, menu, + context: (item) => { + const { config, session } = resolve(item); + if (!config) return null; + return { + provider: RUN_PROVIDER, + id: config.id, + kind: config.kind, + name: config.name, + running: !!session && liveServiceSession(session), + runConfigurationId: config.id, + }; + }, activate: (item) => { const r = resolve(item); if (r.config && !(r.session && liveServiceSession(r.session)) && !isDebugOnly(r.config)) run(r); diff --git a/src/features/run/store.ts b/src/features/run/store.ts index d0bfa37dc..170969aca 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -57,6 +57,7 @@ import { TeamcityOutput } from "./testing/teamcity"; import type { TestStdout } from "./testing/types"; import { flutterMachineOutput, isFlutterMachineRun } from "./flutterMachine"; import { recordTestStates } from "./testing/states"; +import { packageScript, watchLaunch } from "./testing/watch"; import { failedTestPaths, leafTestPaths, rerunFailedConfigs, testsConfigs } from "./testing/rerun"; import { testsBySubproject } from "./testing/gradleSubprojects"; import { @@ -113,6 +114,8 @@ export interface RunSession { pinned?: boolean; /** Commit checks own these tabs so their output stays available for review. */ backgroundCheck?: boolean; + /** Jest / Vitest watch mode: the process reruns the tests after each edit. */ + watching?: boolean; } interface SessionRuntime { @@ -792,20 +795,25 @@ function newRuntime(config: RunConfig): SessionRuntime { }) : null; const parser = pluginTests ? null : builtIn; + // A watch cycle's end records the test states like a finished run (gutter icons). + const applyTests = (events: TestEvent[]) => { + tests!.apply(events); + if (events.some((e) => e.type === "end")) recordTestStates(tests!); + }; const feed = (line: string) => { - if (tests && parser) tests.apply(parser.feed(line)); + if (tests && parser) applyTests(parser.feed(line)); }; const framework = tests && parser ? frameworkFor(config) : null; // PHPUnit `--teamcity` and Gradle's test init script report through service messages, Minitest, - // node:test and Mocha through the IDE's own reporters (RSpec has none: its progress dots must show as they come). + // node:test, Mocha and Jasmine through the IDE's own reporters (RSpec has none: its progress dots must show as they come). const stdout = framework === "go" ? new GoTestOutput(feed) - : framework === "phpunit" || framework === "jvm" - ? new TeamcityOutput(feed, framework === "jvm") + : framework === "phpunit" || framework === "jvm" || framework === "cypress" // Cypress: its `teamcity` reporter + ? new TeamcityOutput(feed, framework !== "phpunit") : framework === "ruby" && config.kind !== "rspec" ? new RubyTestOutput(feed) - : framework === "node-test" || framework === "mocha" + : framework === "node-test" || framework === "mocha" || framework === "jasmine" ? new RecordsOutput(feed) : null; const runtime: SessionRuntime = { @@ -817,7 +825,7 @@ function newRuntime(config: RunConfig): SessionRuntime { maxChars: consoleCharLimit(), onLine: (text, kind) => { if (pluginTests && kind !== "system") pluginTests.feed(text); - if (parser && tests && kind !== "system" && !(kind === "stdout" && stdout)) tests.apply(parser.feed(text)); + if (parser && tests && kind !== "system" && !(kind === "stdout" && stdout)) applyTests(parser.feed(text)); if (kind !== "system") for (const l of runtime.lineListeners) l(text); if (kind !== "system") runtime.dotnetReports?.feed(text); }, @@ -1044,6 +1052,7 @@ async function startRunIn( stopped: false, httpPort: undefined, backgroundCheck: undefined, + watching: undefined, }; const updated = session; useRun.setState((s) => ({ @@ -1120,6 +1129,20 @@ async function startRunIn( }; try { let launch = options.launch ?? config; + // Jest / Vitest "Watch for changes". Debug and derived runs (Rerun Failed, selected tests, + // Update Snapshot) run the tests once. + if (!options.launch && !baseConfig && launch.watch && launch.isTest && frameworkFor(launch) === "js") { + const watched = watchLaunch(launch, await packageScript(launch)); + if (runtimes.get(sessionId)?.generation !== generation) return getSession(sessionId) ?? null; + if (watched) { + launch = watched; + patchSession(sessionId, { watching: true }); + } else + enqueue(sessionId, { + kind: "system", + text: tx`Watch mode needs a command or script that ends with Jest or Vitest: the tests run once.\n`, + }); + } // A Maven/Gradle configuration's own command is its build; Rebuild adds clean. if (!options.launch) launch = applyBuildPolicyToCommand(launch); // "Build and run using: Gradle": the module's Gradle build compiles and launches it. @@ -1138,7 +1161,10 @@ async function startRunIn( } launch = resolved; } - const prepare = typeFor(launch.kind)?.prepareLaunch; + // `npm run` scripts running Cypress pass the test selection the way the installed Cypress takes it, too. + const prepare = + typeFor(launch.kind)?.prepareLaunch ?? + (frameworkFor(launch) === "cypress" ? typeFor("cypress")?.prepareLaunch : undefined); if (prepare) { launch = await prepare(launch); if (!check && launch.kind === "tomcat") useRun.setState({ activeSession: sessionId }); @@ -1652,6 +1678,14 @@ export function configRemoved(id: string): boolean { return listedConfigIds.has(id) && !useRun.getState().configs.some((c) => c.id === id); } +/** "Rerun Automatically": a Jest / Vitest run in watch mode in the same tab; off stops the watcher. */ +export function toggleRerunAutomatically(sessionId: string) { + const session = getSession(sessionId); + if (!session) return; + if (session.watching && isLive(session)) void stopSession(sessionId); + else void startRun({ ...baseConfigOf(session), watch: true }, sessionId); +} + export function rerunSession(sessionId: string) { const session = getSession(sessionId); if (session) void startRun(rerunConfig(session), sessionId, session.baseConfig && baseConfigOf(session)); diff --git a/src/features/run/targets.ts b/src/features/run/targets.ts index 6e1b61b19..3feda9c8b 100644 --- a/src/features/run/targets.ts +++ b/src/features/run/targets.ts @@ -19,6 +19,7 @@ import { escapeRegExp } from "./testing/rerun"; import { pestFilter, phpunitArgs, phpunitFilter } from "./testing/phpunit"; import { frameworkFor } from "./testing"; import { withNodeTestNamePattern } from "./testing/nodeTest"; +import { cypressSelection, cypressSpecs } from "./testing/cypress"; export type TargetKind = "main" | "test" | "suite" | "generate"; @@ -134,9 +135,12 @@ function rustTargets(lines: string[], relPath: string): RunTarget[] { ); } -/** Jest / Vitest `describe` / `test` / `it` (Mocha's `specify` too), and Playwright's `test.describe` and modifiers. */ +/** + * Jest / Vitest `describe` / `test` / `it` (Mocha's `specify` and Jasmine's `fdescribe` / `fit` / + * `xdescribe` / `xit` too), and Playwright's `test.describe` and modifiers. + */ const JS_RE = - /^(\s*)(test\.describe|describe|suite|context|test|it|specify)\b(?:\.(?:only|skip|todo|concurrent|failing|sequential|fixme|fail|serial|parallel))*(\.each\s*(?:\(.*?\)|`[^`]*`))?\s*\(\s*(['"`])((?:\\.|(?!\4).)*)\4/; + /^(\s*)(test\.describe|[fx]?describe|suite|context|test|[fx]?it|specify)\b(?:\.(?:only|skip|todo|concurrent|failing|sequential|fixme|fail|serial|parallel))*(\.each\s*(?:\(.*?\)|`[^`]*`))?\s*\(\s*(['"`])((?:\\.|(?!\4).)*)\4/; function jsTargets(lines: string[]): RunTarget[] { const out: RunTarget[] = []; @@ -149,7 +153,7 @@ function jsTargets(lines: string[]): RunTarget[] { const name = m[5]!.replace(/\\(.)/g, "$1"); const parameterized = !!m[3] || (m[4] === "`" && name.includes("${")) || /%[sdifjo#%p]|\$\w+/.test(name); const path = [...stack.map((s) => s.name), name]; - const isSuite = m[2] === "test.describe" || m[2] === "describe" || m[2] === "suite" || m[2] === "context"; + const isSuite = m[2]!.endsWith("describe") || m[2] === "suite" || m[2] === "context"; out.push({ line: i, kind: isSuite ? "suite" : "test", name: path.join(" > "), path, parameterized }); if (isSuite) stack.push({ indent, name }); } @@ -373,21 +377,34 @@ export function testsInTestDirectory(configs: readonly RunConfig[]): boolean { return configs.some((c) => c.isTest && ["mocha", "node-test"].includes(frameworkFor(c))); } +/** Whether the project tests with Jasmine, which looks in `spec/` by default (`fooSpec.js` and the like). */ +export function specsInSpecDirectory(configs: readonly RunConfig[]): boolean { + return configs.some((c) => c.isTest && frameworkFor(c) === "jasmine"); +} + /** * Run targets of a file (relative path picks the language). `django`: a Django project, where * `tests.py` (Django's default test module) holds tests too. `testDirectory`: JS files in `test/` - * hold tests whatever their name (`testsInTestDirectory`). + * hold tests whatever their name (`testsInTestDirectory`); `specDirectory`: the same for `spec/` + * (`specsInSpecDirectory`). */ -export function detectRunTargets(text: string, relPath: string, django = false, testDirectory = false): RunTarget[] { +export function detectRunTargets( + text: string, + relPath: string, + django = false, + testDirectory = false, + specDirectory = false, +): RunTarget[] { if (text.length > MAX_SCAN) return []; const lines = text.split("\n"); + if (specDirectory && /(^|\/)spec\//.test(relPath) && targetLanguage(relPath) === "js") return jsTargets(lines); switch (targetLanguage(relPath)) { case "csharp": return csharpTargets(text); case "rust": return rustTargets(lines, relPath); case "js": - return /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)__tests__\//.test(relPath) || + return /\.(test|spec|cy)\.[cm]?[jt]sx?$|(^|\/)__tests__\//.test(relPath) || (testDirectory && /(^|\/)test\//.test(relPath)) ? jsTargets(lines) : []; @@ -481,12 +498,16 @@ export function targetConfig( env: { ...file.env }, detected: true, }); + // Cypress has no name filter of its own: `@cypress/grep` reads the full title (see `testing/cypress.ts`). + if (frameworkFor(file) === "cypress") + return { ...named([]), ...cypressSelection(file, cypressSpecs(file.args), { grep: [target.path.join(" ")] }) }; // Playwright selects by declaration line (`file:line`), which also covers a describe block. if (frameworkFor(file) === "playwright") return named(withLast(file.args, (f) => `${f}:${target.line + 1}`)); // node:test selects by full name, through NODE_OPTIONS (see `nodeTest.ts`). if (frameworkFor(file) === "node-test") return { ...named(file.args), env: withNodeTestNamePattern(file.env, jsNamePattern(target)) }; if (frameworkFor(file) === "mocha") return named([...file.args, "--grep", jsNamePattern(target)]); + if (frameworkFor(file) === "jasmine") return named([...file.args, `--filter=${jsNamePattern(target)}`]); switch (file.kind) { case "dotnet-test": { const methods = diff --git a/src/features/run/testing/cypress.test.ts b/src/features/run/testing/cypress.test.ts new file mode 100644 index 000000000..ec5ceab9c --- /dev/null +++ b/src/features/run/testing/cypress.test.ts @@ -0,0 +1,365 @@ +import { describe, expect, it, vi } from "vitest"; +import type { ProjectInfo, RunConfig } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { testBasesFor, testConfigFor } from "../context"; +import { provideNotificationService, type NotificationService } from "@/workbench/contributions"; +import { cypressType, prepareCypressLaunch } from "../cypressType"; +import { detectRunTargets, targetConfig } from "../targets"; +import { formParams } from "../types"; +import { cypressSpecs } from "./cypress"; +import { + createTestParser, + frameworkFor, + nodeOutput, + parseAll, + TestResults, + withTestReporting, + type TestNode, +} from "./index"; +import { failedTestPaths, rerunFailedConfigs } from "./rerun"; + +const installed = vi.hoisted(() => ({ files: {} as Record<string, string> })); +vi.mock("@/platform/ipc", async (original) => ({ + ...(await original<typeof import("@/platform/ipc")>()), + call: async (v: unknown) => v, + commands: { + fsReadText: async (path: string) => { + if (path in installed.files) return installed.files[path]; + throw new Error("not found"); + }, + }, +})); + +const cfg = (over: Partial<RunConfig> & { id: string; kind: string }): RunConfig => ({ + name: over.id, + command: over.kind, + args: [], + cwd: null, + env: {}, + detected: true, + isTest: true, + debugAdapter: null, + ...over, +}); + +/** The configuration detected for a package with Cypress that no script runs. */ +const npx = cfg({ id: "cypress", kind: "cypress", command: "npx", args: ["cypress", "run"] }); +/** `npm run cy:run` whose script is `cypress run` (detection records the runner). */ +const script = cfg({ id: "npm:cy:run", kind: "npm", command: "npm", args: ["run", "cy:run"], testRunner: "cypress" }); + +function results(text: string, config: RunConfig = npx) { + const r = new TestResults(); + r.apply(parseAll(createTestParser(config), text)); + return r; +} + +const key = (...path: string[]) => path.join("\u0000"); + +// `npx cypress run --browser chrome --reporter teamcity` with Cypress 16.4, as printed (tables shortened). +const RUN = ` +================================================================================ + + (Run Starting) + + │ Specs: 2 found (cart.cy.ts, nested/login.cy.js) │ + │ Searched: cypress/e2e/**/*.cy.{js,jsx,ts,tsx} │ + +──────────────────────────────────────────────────────────────────────────────────────────────────── + + Running: cart.cy.ts (1 of 2) +##teamcity[testSuiteStarted name='cart' flowId='43775'] +##teamcity[testStarted name='adds an item' captureStandardOutput='true' flowId='43775'] +##teamcity[testFinished name='adds an item' duration='117' flowId='43775'] +##teamcity[testIgnored name='is skipped' message='is skipped' flowId='43775'] +##teamcity[testStarted name='is skipped' captureStandardOutput='true' flowId='43775'] +##teamcity[testSuiteStarted name='totals, with tax' flowId='43775'] +##teamcity[testStarted name='sums |'quoted|' prices' captureStandardOutput='true' flowId='43775'] +##teamcity[testFinished name='sums |'quoted|' prices' duration='25' flowId='43775'] +##teamcity[testStarted name='fails on purpose' captureStandardOutput='true' flowId='43775'] +##teamcity[testFailed name='fails on purpose' message='Timed out retrying after 4000ms: expected 3 to equal 4' details='AssertionError: Timed out retrying after 4000ms: expected 3 to equal 4|n at Context.eval (webpack://cy/./cypress/e2e/cart.cy.ts:10:17)' captureStandardOutput='true' flowId='43775'] +##teamcity[testFinished name='fails on purpose' duration='4201' flowId='43775'] +##teamcity[testSuiteFinished name='totals, with tax' duration='4237' flowId='43775'] +##teamcity[testSuiteFinished name='cart' duration='4410' flowId='43775'] + + (Results) + + │ Tests: 4 │ + +──────────────────────────────────────────────────────────────────────────────────────────────────── + + Running: nested/login.cy.js (2 of 2) +##teamcity[testStarted name='top-level test' captureStandardOutput='true' flowId='43775'] +##teamcity[testFinished name='top-level test' duration='45' flowId='43775'] + + (Results) +`; + +describe("Cypress teamcity reporter", () => { + it("builds the tree from the spec, suites and tests, with statuses, durations and failures", () => { + const r = results(RUN); + expect(r.roots.map((n) => n.name)).toEqual(["cart.cy.ts", "nested/login.cy.js"]); + const node = (...path: string[]) => r.get(key(...path))!; + expect(node("cart.cy.ts", "cart", "adds an item")).toMatchObject({ own: "passed", durationMs: 117 }); + expect(node("cart.cy.ts", "cart", "is skipped").own).toBe("skipped"); + expect(node("cart.cy.ts", "cart", "totals, with tax", "sums 'quoted' prices").own).toBe("passed"); + const failed = node("cart.cy.ts", "cart", "totals, with tax", "fails on purpose"); + expect(failed).toMatchObject({ own: "failed", durationMs: 4201 }); + expect(nodeOutput(failed)).toEqual([ + "AssertionError: Timed out retrying after 4000ms: expected 3 to equal 4", + " at Context.eval (webpack://cy/./cypress/e2e/cart.cy.ts:10:17)", + ]); + expect(node("nested/login.cy.js", "top-level test").own).toBe("passed"); + // Cypress prints no line: the test is found in its spec by its titles. + expect(failed.location).toEqual({ + path: "cart.cy.ts", + resolve: "path", + test: ["cart", "totals, with tax", "fails on purpose"], + }); + }); + + it("names specs by the --spec paths they were run as, and joins wrapped names", () => { + const run = cfg({ ...npx, args: ["cypress", "run", "--spec", "cypress/e2e/cart.cy.ts,**/nested/login.cy.js"] }); + expect(cypressSpecs(run.args)).toEqual(["cypress/e2e/cart.cy.ts", "**/nested/login.cy.js"]); + expect(results(RUN, run).roots.map((n) => n.name)).toEqual(["cypress/e2e/cart.cy.ts", "nested/login.cy.js"]); + const wrapped = results( + [ + " Running: some/very/long/folder/structure/for/checking/wrapping/an-extremely-l (2 of 2)", + " ong-spec-file-name-for-wrapping.cy.js ", + "##teamcity[testStarted name='deep' captureStandardOutput='true' flowId='41517']", + "##teamcity[testFinished name='deep' duration='24' flowId='41517']", + ].join("\n"), + ); + expect(wrapped.roots.map((n) => n.name)).toEqual([ + "some/very/long/folder/structure/for/checking/wrapping/an-extremely-long-spec-file-name-for-wrapping.cy.js", + ]); + }); +}); + +// Failing hooks (\`beforeEach\`, \`before\`, \`afterEach\`, \`after\`) with Cypress 16.4, as printed. +const HOOKS = ` + Running: hooks.cy.js (1 of 1) +##teamcity[testSuiteStarted name='each' flowId='14448'] +##teamcity[testStarted name='outside' captureStandardOutput='true' flowId='14448'] +##teamcity[testFinished name='outside' duration='25' flowId='14448'] +##teamcity[testSuiteStarted name='inner' flowId='14448'] +##teamcity[testStarted name='first' captureStandardOutput='true' flowId='14448'] +##teamcity[testFailed name='"before each" hook for "first"' message='expected 1 to equal 2|n|nBecause this error occurred during a \`before each\` hook we are skipping the remaining tests in the current suite: \`inner\`' details='AssertionError: expected 1 to equal 2|n|nBecause this error occurred during a \`before each\` hook we are skipping the remaining tests in the current suite: \`inner\`|n at Context.eval (webpack://hk/./cypress/e2e/hooks.cy.js:3:36)' captureStandardOutput='true' flowId='14448'] +##teamcity[testFinished name='first' duration='9' flowId='14448'] +##teamcity[testSuiteFinished name='inner' duration='50' flowId='14448'] +##teamcity[testSuiteFinished name='each' duration='79' flowId='14448'] +##teamcity[testSuiteStarted name='all' flowId='14448'] +##teamcity[testFailed name='"before all" hook for "one"' message='expected 1 to equal 3|n|nBecause this error occurred during a \`before all\` hook we are skipping the remaining tests in the current suite: \`all\`' details='AssertionError: expected 1 to equal 3|n|nBecause this error occurred during a \`before all\` hook we are skipping the remaining tests in the current suite: \`all\`|n at Context.eval (webpack://hk/./cypress/e2e/hooks.cy.js:10:30)' captureStandardOutput='true' flowId='14448'] +##teamcity[testFinished name='one' duration='7' flowId='14448'] +##teamcity[testSuiteFinished name='all' duration='15' flowId='14448'] +##teamcity[testSuiteStarted name='after' flowId='14448'] +##teamcity[testStarted name='runs' captureStandardOutput='true' flowId='14448'] +##teamcity[testFailed name='"after each" hook for "runs"' message='expected 1 to equal 4|n|nBecause this error occurred during a \`after each\` hook we are skipping the remaining tests in the current suite: \`after\`' details='AssertionError: expected 1 to equal 4|n|nBecause this error occurred during a \`after each\` hook we are skipping the remaining tests in the current suite: \`after\`|n at Context.eval (webpack://hk/./cypress/e2e/hooks.cy.js:15:33)' captureStandardOutput='true' flowId='14448'] +##teamcity[testFinished name='runs' duration='1' flowId='14448'] +##teamcity[testSuiteFinished name='after' duration='25' flowId='14448'] +##teamcity[testSuiteStarted name='afterAll' flowId='14448'] +##teamcity[testStarted name='only' captureStandardOutput='true' flowId='14448'] +##teamcity[testFailed name='"after all" hook for "only"' message='expected 1 to equal 5|n|nBecause this error occurred during a \`after all\` hook we are skipping the remaining tests in the current suite: \`afterAll\`' details='AssertionError: expected 1 to equal 5|n|nBecause this error occurred during a \`after all\` hook we are skipping the remaining tests in the current suite: \`afterAll\`|n at Context.eval (webpack://hk/./cypress/e2e/hooks.cy.js:20:29)' captureStandardOutput='true' flowId='14448'] +##teamcity[testFinished name='only' duration='1' flowId='14448'] +##teamcity[testSuiteFinished name='afterAll' duration='7' flowId='14448'] +`; + +describe("Cypress hook failures", () => { + it("fail the test an each hook ran for, and the suite of an all hook", () => { + const r = results(HOOKS); + const own = (...path: string[]) => r.get(key("hooks.cy.js", ...path))?.own; + expect(own("each", "outside")).toBe("passed"); + expect(own("each", "inner", "first")).toBe("failed"); + expect(nodeOutput(r.get(key("hooks.cy.js", "each", "inner", "first"))!)[0]).toBe( + "AssertionError: expected 1 to equal 2", + ); + expect(own("all")).toBe("failed"); + expect(own("after", "runs")).toBe("failed"); + expect(own("afterAll")).toBe("failed"); + // No node carries a hook's title. + const names: string[] = []; + const visit = (n: TestNode) => { + names.push(n.name); + n.children.forEach(visit); + }; + r.roots.forEach(visit); + expect(names.filter((n) => /" hook/.test(n))).toEqual([]); + }); + + it("rerun the test or the suite, whose titles @cypress/grep matches", async () => { + const paths = failedTestPaths(results(HOOKS)); + expect(paths.map((p) => p.join(" › "))).toEqual([ + "hooks.cy.js › each › inner › first", + "hooks.cy.js › all", + "hooks.cy.js › after › runs", + "hooks.cy.js › afterAll", + ]); + const [rerun] = await rerunFailedConfigs(npx, paths); + expect(rerun!.env.CYPRESS_grep).toBe("each inner first; all; after runs; afterAll"); + }); +}); + +describe("Cypress configurations", () => { + it("are recognised by their type, the recorded runner or the command line", () => { + expect(frameworkFor(npx)).toBe("cypress"); + expect(frameworkFor(script)).toBe("cypress"); + expect(frameworkFor(cfg({ id: "x", kind: "shell", command: "npx", args: ["cypress", "run"] }))).toBe("cypress"); + expect(frameworkFor(cfg({ id: "open", kind: "npm", command: "npm", args: ["run", "cy:open"] }))).toBe("js"); + }); + + it("report through the teamcity reporter unless the configuration chose one", () => { + expect(withTestReporting(npx).args).toEqual(["cypress", "run", "--reporter", "teamcity"]); + expect(withTestReporting(script).args).toEqual(["run", "cy:run", "--", "--reporter", "teamcity"]); + const own = { ...npx, args: ["cypress", "run", "-r", "junit"] }; + expect(withTestReporting(own).args).toEqual(own.args); + }); + + it("choose the browser and the testing type in their form", () => { + const params = { packageDir: "web", testingType: "component", browser: "firefox", spec: "src/**/*.cy.tsx" }; + const line = cypressType.commandLine({ ...params, options: "--headed" })!; + expect(line).toEqual({ + command: "npx", + args: ["cypress", "run", "--component", "--browser", "firefox", "--spec", "src/**/*.cy.tsx", "--headed"], + cwd: "web", + }); + expect(cypressType.paramsFrom!({ ...npx, ...line })).toEqual({ ...params, options: "--headed" }); + // The detected configuration opens in the form as it is. + expect(formParams(npx, cypressType)).toEqual({ + packageDir: "", + testingType: "e2e", + browser: "", + spec: "", + options: "", + }); + }); +}); + +describe("Cypress gutter targets", () => { + const spec = [ + 'describe("cart", () => {', // 0 + ' it("adds an item", () => {});', // 1 + ' context("totals, with tax", () => {', // 2 + " specify(\"sums 'quoted' prices\", () => {});", // 3 + ' it.only("fails on purpose", () => {});', // 4 + " });", + "});", + ].join("\n"); + + it("find describe / context blocks and it / specify tests in *.cy.* files", () => { + expect(detectRunTargets(spec, "cypress/e2e/cart.cy.ts").map((t) => [t.line, t.kind, t.path.join("/")])).toEqual([ + [0, "suite", "cart"], + [1, "test", "cart/adds an item"], + [2, "suite", "cart/totals, with tax"], + [3, "test", "cart/totals, with tax/sums 'quoted' prices"], + [4, "test", "cart/totals, with tax/fails on purpose"], + ]); + }); + + it("run a spec with --spec, and a test or suite by its full title", () => { + const [cart, , , , fails] = detectRunTargets(spec, "cypress/e2e/cart.cy.ts"); + expect(testConfigFor("cypress/e2e/cart.cy.ts", [script], undefined, spec)?.args).toEqual([ + "run", + "cy:run", + "--", + "--spec", + "cypress/e2e/cart.cy.ts", + ]); + const test = targetConfig(fails!, "cypress/e2e/cart.cy.ts", [npx], spec)!; + expect(test.args).toEqual(["cypress", "run", "--spec", "cypress/e2e/cart.cy.ts"]); + expect(test.env).toEqual({ + CYPRESS_grep: "cart totals, with tax fails on purpose", + CYPRESS_grepOmitFiltered: "true", + }); + expect(test.params?.spec).toBe("cypress/e2e/cart.cy.ts"); + const web = { ...npx, cwd: "web", module: "web" }; + const suite = targetConfig(cart!, "web/cypress/e2e/cart.cy.ts", [web], spec)!; + expect(suite.args).toEqual(["cypress", "run", "--spec", "cypress/e2e/cart.cy.ts"]); + expect(suite.env.CYPRESS_grep).toBe("cart"); + }); + + it("run component specs as component tests, end-to-end specs end to end", () => { + const mount = 'it("renders", () => { cy.mount(<Button />); });'; + expect(testConfigFor("src/Button.cy.tsx", [npx], undefined, mount)?.args).toEqual([ + "cypress", + "run", + "--component", + "--spec", + "src/Button.cy.tsx", + ]); + const component = { ...npx, args: ["cypress", "run", "--component", "--browser", "chrome"] }; + expect(testConfigFor("cypress/e2e/cart.cy.ts", [component], undefined, spec)?.args).toEqual([ + "cypress", + "run", + "--browser", + "chrome", + "--spec", + "cypress/e2e/cart.cy.ts", + ]); + }); + + it("never send other tests to Cypress, even when its configuration is the closest one", () => { + // Vitest at the workspace root; `apps/web` depends on Cypress and has no test script. + const vitest = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"] }); + const web = { ...npx, id: "cypress:apps/web", cwd: "apps/web", module: "apps/web" }; + const ids = (relPath: string, content: string) => testBasesFor(relPath, [vitest, web], content).map((c) => c.id); + expect(ids("apps/web/src/util.test.ts", "test('adds', () => {});")).toEqual(["npm:test"]); + expect( + testConfigFor("apps/web/src/util.test.ts", [vitest, web], undefined, "test('adds', () => {});")?.args, + ).toEqual(["run", "test", "--", "apps/web/src/util.test.ts"]); + expect(ids("apps/web/cypress/e2e/cart.cy.ts", spec)).toEqual(["cypress:apps/web"]); + // And the other way round: a spec runs on Cypress at the root, not on a closer Vitest. + const app = { ...vitest, id: "npm:apps/web:test", cwd: "apps/web", module: "apps/web" }; + expect(ids("apps/web/src/Button.cy.tsx", spec)).toEqual(["cypress:apps/web"]); + expect(testBasesFor("apps/web/src/Button.cy.tsx", [app, npx], spec).map((c) => c.id)).toEqual(["cypress"]); + expect(testBasesFor("apps/web/src/util.test.ts", [app, npx], spec).map((c) => c.id)).toEqual(["npm:apps/web:test"]); + }); + + it("send specs to Cypress and other tests to the project's other runner", () => { + const vitest = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"] }); + const configs = [vitest, npx]; + expect(testBasesFor("cypress/e2e/cart.cy.ts", configs, spec).map((c) => c.id)).toEqual(["cypress"]); + expect(testBasesFor("src/cart.test.ts", configs, "test('adds', () => {});").map((c) => c.id)).toEqual(["npm:test"]); + }); +}); + +describe("Cypress Rerun Failed Tests", () => { + it("runs the failed tests' specs, selecting them by full title", async () => { + const r = results(RUN); + const [rerun] = await rerunFailedConfigs({ ...npx, env: { FOO: "1" } }, failedTestPaths(r)); + expect(rerun!.args).toEqual(["cypress", "run", "--spec", "**/cart.cy.ts"]); + expect(rerun!.env).toEqual({ + FOO: "1", + CYPRESS_grep: "cart totals, with tax fails on purpose", + CYPRESS_grepOmitFiltered: "true", + }); + // The rerun's tree keeps the names of the first run. + expect(results(RUN, rerun).roots[0]!.name).toBe("cart.cy.ts"); + }); + + it("pass the selection as --expose to Cypress 15.10 and later, where @cypress/grep 7 reads it", async () => { + useProject.setState({ + project: { root: "/p", name: "p", trusted: true, isGit: false, settings: {} as ProjectInfo["settings"] }, + }); + const notify = vi.fn(); + provideNotificationService({ notify } as unknown as NotificationService); + const selected = { ...script, args: ["run", "cy:run", "--", "--spec", "a.cy.ts"], env: { CYPRESS_grep: "a b" } }; + // No grep plugin: the whole spec runs, and a notification says so. + installed.files["/p/node_modules/cypress/package.json"] = '{"version":"16.4.0"}'; + installed.files["/p/package.json"] = '{"devDependencies":{"cypress":"^16.0.0"}}'; + expect(await prepareCypressLaunch(selected)).toEqual(selected); + expect(notify).toHaveBeenCalledTimes(1); + expect(notify.mock.calls[0]![0]).toMatchObject({ key: "cypress-grep", title: "Cypress ran the whole spec file" }); + notify.mockClear(); + // A workspace member: the plugin and Cypress are found in the folders above it. + installed.files["/p/package.json"] = '{"devDependencies":{"cypress":"^16.0.0","@cypress/grep":"^7.0.0"}}'; + expect((await prepareCypressLaunch({ ...selected, cwd: "web" })).args).toEqual([ + ...selected.args, + "--expose", + '{"grep":"a b","grepOmitFiltered":true}', + ]); + installed.files["/p/node_modules/cypress/package.json"] = '{"version":"15.9.1"}'; + expect(await prepareCypressLaunch(selected)).toEqual(selected); + // Whole specs need no selection. + expect(await prepareCypressLaunch({ ...selected, env: {} })).toEqual({ ...selected, env: {} }); + expect(notify).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/run/testing/cypress.ts b/src/features/run/testing/cypress.ts new file mode 100644 index 000000000..251f4d611 --- /dev/null +++ b/src/features/run/testing/cypress.ts @@ -0,0 +1,159 @@ +/** + * Cypress through its built-in `teamcity` reporter (the run adds `--reporter teamcity`): service + * messages for each suite and test, with durations and failure details. They name no file: Cypress + * prints `Running: cart.cy.ts (1 of 2)` before each spec, relative to the specs' common folder, + * which the `--spec` paths of the run, when it names them, turn back into the path they were given as. + * + * `cypress run` has no option selecting tests by name: a test or suite runs its spec with its full + * title in `CYPRESS_grep` (`Cypress.env("grep")`), which the official `@cypress/grep` plugin reads; its + * version 7 reads `--expose grep=…` instead, added at launch for Cypress 15.10+ (`cypressType.ts`). + */ +import type { RunConfig } from "@/platform/ipc"; +import { stripAnsi } from "@/ui/ansi"; +import { cypressType } from "../cypressType"; +import { appendScriptArgs } from "../scriptArgs"; +import { serviceMessage } from "./teamcity"; +import type { TestEvent, TestOutputParser } from "./types"; + +const RUNNING_RE = /^\s*Running:\s+(.+?)\s+\(\d+ of \d+\)$/; +/** Mocha's title of a failing hook: `"before each" hook for "test"`, `"after all" hook: name for "test"`. */ +const HOOK_RE = /^"(?:before|after) (each|all)" hook(?:: .*?)?(?: for "(.*)")?$/; +/** A long spec path wraps onto lines of its own, under where it starts. */ +const WRAPPED_RE = /^ {12}(\S.*?)\s*$/; + +/** Values of `--spec` / `-s`: comma-separated paths or globs. */ +export function cypressSpecs(args: readonly string[]): string[] { + const out: string[] = []; + args.forEach((a, i) => { + const value = a === "--spec" || a === "-s" ? args[i + 1] : a.startsWith("--spec=") ? a.slice(7) : undefined; + if (value) out.push(...value.split(",").map((s) => s.trim().replace(/\\/g, "/").replace(/^\.\//, ""))); + }); + return out.filter(Boolean); +} + +/** The file a `Running:` name stands for: the `--spec` path it ends with, else the name itself. */ +function specFile(name: string, specs: readonly string[]): string { + const clean = name.replace(/\\/g, "/"); + const given = specs.map((s) => s.replace(/^\*\*\//, "")).find((s) => s === clean || s.endsWith(`/${clean}`)); + return given ?? clean; +} + +export function cypressParser(specs: readonly string[] = []): TestOutputParser { + let file = ""; + /** The `Running:` name while it may continue on the next line. */ + let wrapping: string | null = null; + const suites: string[] = []; + const open = new Map<string, { path: string[]; failed: boolean }>(); + /** `it.skip`: reported ignored, then started and never finished. */ + const ignored = new Set<string>(); + const pathOf = (name: string) => [file, ...suites, name]; + return { + feed(raw) { + const line = stripAnsi(raw); + const wrapped = WRAPPED_RE.exec(line); + if (wrapping !== null && wrapped && !line.includes("##teamcity[")) { + wrapping += wrapped[1]!; + file = specFile(wrapping, specs); + return []; + } + wrapping = null; + const running = RUNNING_RE.exec(line); + if (running) { + wrapping = running[1]!; + file = specFile(running[1]!, specs); + suites.length = 0; + open.clear(); + ignored.clear(); + return []; + } + const message = serviceMessage(line); + if (!message || !file) return []; + const { kind, attrs: a } = message; + const name = a.name ?? ""; + const events: TestEvent[] = []; + const path = pathOf(name); + const key = path.join("\u0000"); + switch (kind) { + case "testSuiteStarted": + suites.push(name); + break; + case "testSuiteFinished": + if (suites[suites.length - 1] === name) suites.pop(); + break; + case "testStarted": + if (ignored.has(key)) break; + open.set(key, { path, failed: false }); + events.push({ type: "start", path }); + events.push({ type: "location", path, location: { path: file, resolve: "path", test: path.slice(1) } }); + break; + case "testIgnored": + ignored.add(key); + events.push({ type: "location", path, location: { path: file, resolve: "path", test: path.slice(1) } }); + events.push({ type: "result", path, status: "skipped" }); + break; + case "testFailed": { + // A failing hook is reported under its own title (`"before each" hook for "adds"`): an `each` hook + // fails the test it ran for, an `all` hook its suite (whose remaining tests Cypress skips). + const hook = HOOK_RE.exec(name); + const failed = !hook ? path : hook[1] === "each" ? pathOf(hook[2] ?? name) : [file, ...suites]; + const test = open.get(failed.join("\u0000")); + if (test) test.failed = true; + const text = a.details || a.message || ""; + for (const l of text.replace(/\n$/, "").split("\n")) events.push({ type: "output", path: failed, line: l }); + events.push({ type: "result", path: failed, status: "failed" }); + break; + } + case "testFinished": { + const test = open.get(key); + if (!test) break; + open.delete(key); + const durationMs = a.duration ? Number(a.duration) : undefined; + events.push({ type: "result", path, status: test.failed ? "failed" : "passed", durationMs }); + break; + } + } + return events; + }, + }; +} + +/** A component spec: it mounts components, or sits in `cypress/component/` (others are end-to-end specs). */ +export function isCypressComponentSpec(relPath: string, content?: string): boolean { + return /(^|\/)cypress\/component\//.test(relPath) || /\bcy\.mount\s*\(/.test(content ?? ""); +} + +/** The environment variable carrying the titles to run: `@cypress/grep` before version 7 reads it as `Cypress.env("grep")`. */ +export const CYPRESS_GREP = "CYPRESS_grep"; +const CYPRESS_GREP_OMIT = "CYPRESS_grepOmitFiltered"; + +/** + * Arguments, environment (and a Cypress configuration's form) running `specs` (paths or globs relative to + * the project) on `config`, in place of its own `--spec`. `grep`: full titles (describe chain and name) for + * `@cypress/grep`, `; ` separated; none runs the specs whole. `component`: the testing type the specs need, + * switched on a Cypress configuration's own arguments. + */ +export function cypressSelection( + config: RunConfig, + specs: string[], + { grep = [], component }: { grep?: string[]; component?: boolean } = {}, +): Pick<RunConfig, "args" | "params" | "env"> { + const args: string[] = []; + for (let i = 0; i < config.args.length; i++) { + const a = config.args[i]!; + if (a === "--spec" || a === "-s") i++; + else if (!a.startsWith("--spec=")) args.push(a); + } + const own = + config.kind === "cypress" && component !== undefined + ? args.filter((a) => a !== "--component" && a !== "--e2e") + : args; + const mode = component && !own.includes("--component") ? ["--component"] : []; + const selected = appendScriptArgs(config.command, own, [...mode, "--spec", specs.join(",")]); + const { [CYPRESS_GREP]: _grep, [CYPRESS_GREP_OMIT]: _omit, ...env } = config.env; + // Tests left out are not reported at all (else as skipped). + if (grep.length) Object.assign(env, { [CYPRESS_GREP]: grep.join("; "), [CYPRESS_GREP_OMIT]: "true" }); + // A Cypress configuration's form shows what runs: the specs, the testing type. + const params = + config.kind === "cypress" ? (cypressType.paramsFrom!({ ...config, args: selected }) ?? undefined) : config.params; + return { args: selected, params, env }; +} diff --git a/src/features/run/testing/index.ts b/src/features/run/testing/index.ts index 52f5064ac..1b1dc745f 100644 --- a/src/features/run/testing/index.ts +++ b/src/features/run/testing/index.ts @@ -2,8 +2,10 @@ import type { RunConfig } from "@/platform/ipc"; import { isJunitRunner } from "../application"; import { cargoParser } from "./cargo"; +import { cypressParser, cypressSpecs } from "./cypress"; import { goParser } from "./go"; import { jsParser } from "./js"; +import { withJasmineHook } from "./jasmine"; import { jvmParser } from "./jvm"; import { withMochaHook } from "./mocha"; import { withNodeTestReporter } from "./nodeTest"; @@ -46,8 +48,10 @@ export type Framework = | "cargo" | "js" | "playwright" + | "cypress" | "node-test" | "mocha" + | "jasmine" | "pytest" | "unittest" | "phpunit" @@ -58,15 +62,18 @@ export type Framework = | "zig" | "auto"; -type FrameworkConfig = Pick<RunConfig, "kind" | "command" | "args"> & Partial<Pick<RunConfig, "testRunner" | "env">>; +type FrameworkConfig = Pick<RunConfig, "kind" | "command" | "args"> & + Partial<Pick<RunConfig, "testRunner" | "env" | "watch">>; export function frameworkFor(config: FrameworkConfig): Framework { const cmd = [config.command, ...config.args].join(" "); // A `package.json` script names its runner only in package.json: detection records it. if (config.testRunner === "playwright" || /\bplaywright\s+test\b/.test(cmd)) return "playwright"; + if (config.kind === "cypress" || config.testRunner === "cypress" || /\bcypress\s+run\b/.test(cmd)) return "cypress"; if (config.testRunner === "node-test" || /(^|[\s/\\])(node|tsx)(\.exe)?(\s+-\S*)*\s+--test(\s|$)/.test(cmd)) return "node-test"; if (config.testRunner === "mocha" || /(^|[\s/\\])_?mocha(\.cmd|\.js)?(\s|$)/.test(cmd)) return "mocha"; + if (config.testRunner === "jasmine" || /(^|[\s/\\])jasmine(\.cmd|\.js)?(\s|$)/.test(cmd)) return "jasmine"; if (isJunitRunner(config)) return "jvm"; switch (config.kind) { case "dotnet-test": @@ -133,11 +140,19 @@ function rubyVerbose<T extends Pick<RunConfig, "kind" | "command" | "args">>(con export function withTestReporting<T extends FrameworkConfig>(config: T): T { if (frameworkFor(config) === "node-test") return { ...config, env: withNodeTestReporter(config.env ?? {}) }; if (frameworkFor(config) === "mocha") return { ...config, env: withMochaHook(config.env ?? {}) }; + if (frameworkFor(config) === "jasmine") return { ...config, env: withJasmineHook(config.env ?? {}) }; if (frameworkFor(config) === "playwright") { // The list reporter prints a line per test; a project's own (`html`, `dot` on CI) may print none. const chosen = config.args.some((a) => a === "--reporter" || a.startsWith("--reporter=")); return chosen ? config : { ...config, args: appendScriptArgs(config.command, config.args, ["--reporter=list"]) }; } + if (frameworkFor(config) === "cypress") { + // Service messages per test; the project's own reporter (`spec`, `mochawesome`…) prints none the tree can read. + const chosen = config.args.some((a) => a === "--reporter" || a === "-r" || a.startsWith("--reporter=")); + return chosen + ? config + : { ...config, args: appendScriptArgs(config.command, config.args, ["--reporter", "teamcity"]) }; + } if (frameworkFor(config) === "go" && config.args[0] === "test") { const boundary = config.args.findIndex((a) => a === "-args" || a === "--"); const tool = boundary < 0 ? config.args : config.args.slice(0, boundary); @@ -172,11 +187,14 @@ export function createTestParser(config: FrameworkConfig): TestOutputParser { case "cargo": return cargoParser(); case "js": - return jsParser(); + return jsParser(!!config.watch); case "playwright": return playwrightParser(); + case "cypress": + return cypressParser(cypressSpecs(config.args)); case "node-test": case "mocha": + case "jasmine": return recordsParser(); case "pytest": return pytestParser(); diff --git a/src/features/run/testing/jasmine.test.ts b/src/features/run/testing/jasmine.test.ts new file mode 100644 index 000000000..5c7f19e75 --- /dev/null +++ b/src/features/run/testing/jasmine.test.ts @@ -0,0 +1,146 @@ +import { describe, expect, it } from "vitest"; +import type { RunConfig } from "@/platform/ipc"; +import { detectRunTargets, specsInSpecDirectory, targetConfig } from "../targets"; +import { createTestParser, frameworkFor, nodeOutput, parseAll, TestResults, withTestReporting } from "./index"; +import { failedTestPaths, rerunFailedConfigs } from "./rerun"; + +const cfg = (over: Partial<RunConfig> & { id: string; kind: string }): RunConfig => ({ + name: over.id, + command: over.kind, + args: [], + cwd: null, + env: {}, + detected: true, + isTest: true, + debugAdapter: "js-debug", + ...over, +}); + +/** `npm run test` whose script is `jasmine` (detection records the runner). */ +const script = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"], testRunner: "jasmine" }); + +// `jasmine` (5.13, default reporter) with the IDE's hook, as printed (`fixtures/jasmine-app`, OPENIDEA_FAIL=1). +const OUTPUT = String.raw`Started +.@@openidea:test@@{"path":["spec/cartSpec.js","cart","total","is zero for an empty cart"],"status":"passed","ms":1,"line":5,"col":5} +F@@openidea:test@@{"path":["spec/cartSpec.js","cart","intentionally fails (set OPENIDEA_FAIL=1)"],"status":"failed","ms":1,"line":24,"col":3,"error":"Expected 6 to be 7.\n at <Jasmine>\n at UserContext.<anonymous> (file:///work/shop/spec/cartSpec.js:26:48)\n at <Jasmine>"} +*@@openidea:test@@{"path":["spec/cartSpec.js","cart","later"],"status":"skipped","ms":0,"line":29,"col":3} + + +Failures: +1) cart intentionally fails (set OPENIDEA_FAIL=1) + Message: + Expected 6 to be 7. + +3 specs, 1 failure, 1 pending spec +Finished in 0.006 seconds +`; + +function results(text: string) { + const r = new TestResults(); + r.apply(parseAll(createTestParser(script), text)); + return r; +} + +describe("Jasmine runs", () => { + it("are recognised by the recorded runner or the command line", () => { + expect(frameworkFor(script)).toBe("jasmine"); + expect(frameworkFor(cfg({ id: "x", kind: "node", command: "npx", args: ["jasmine", "spec/cartSpec.js"] }))).toBe( + "jasmine", + ); + expect( + frameworkFor(cfg({ id: "x", kind: "node", command: "node", args: ["node_modules/jasmine/bin/jasmine.js"] })), + ).toBe("jasmine"); + expect(frameworkFor(cfg({ id: "x", kind: "node", command: "npx", args: ["jasmine-browser-runner"] }))).not.toBe( + "jasmine", + ); + }); + + it("load the IDE's hook through NODE_OPTIONS, once", () => { + const launched = withTestReporting({ ...script, env: { NODE_OPTIONS: "--enable-source-maps" } }); + const [own, hook] = launched.env.NODE_OPTIONS!.split(" "); + expect(own).toBe("--enable-source-maps"); + expect(hook).toMatch(/^--import=data:text\/javascript;base64,/); + expect(withTestReporting(launched).env).toEqual(launched.env); + expect(launched.args).toEqual(script.args); + }); + + it("build the tree from the hook's records, with declaration lines and failures", () => { + const r = results(OUTPUT); + expect(r.counts()).toMatchObject({ passed: 1, failed: 1, skipped: 1 }); + const zero = r.get(["spec/cartSpec.js", "cart", "total", "is zero for an empty cart"].join("\u0000"))!; + expect(zero.location).toEqual({ path: "spec/cartSpec.js", line: 5, col: 5, resolve: "path" }); + expect(nodeOutput(r.firstFailure()!).join("\n")).toContain("Expected 6 to be 7."); + }); + + it("rerun failed specs by file and full name with --filter=", async () => { + const [rerun] = await rerunFailedConfigs( + { ...script, args: ["run", "test", "--", "--filter=old"] }, + failedTestPaths(results(OUTPUT)), + ); + expect(rerun!.args).toEqual([ + "run", + "test", + "--", + "spec/cartSpec.js", + "--filter=^(?:cart intentionally fails \\(set OPENIDEA_FAIL=1\\))(?: |$)", + ]); + }); + + it("rerun a suite whose afterAll failed by its specs", async () => { + // The hook's record for an `afterAll` failure, after the suite's specs passed. + const afterAll = String.raw`@@openidea:test@@{"path":["spec/cartSpec.js","cart","total","sums"],"status":"passed","ms":0,"line":3,"col":5} +@@openidea:test@@{"path":["spec/cartSpec.js","cart"],"status":"failed","ms":1,"error":"Error: afterAll broke"}`; + const paths = failedTestPaths(results(afterAll)); + expect(paths).toEqual([["spec/cartSpec.js", "cart"]]); + const [rerun] = await rerunFailedConfigs(script, paths); + const filter = new RegExp(rerun!.args.at(-1)!.slice("--filter=".length)); + expect(filter.test("cart total sums")).toBe(true); + expect(filter.test("cartography maps")).toBe(false); + }); +}); + +describe("Jasmine gutter targets", () => { + const src = [ + "describe('cart', () => {", // 0 + " fit('adds', () => {});", // 1 + " xdescribe('later', () => {", // 2 + " xit('removes', () => {});", // 3 + " });", + " fdescribe('total', () => {", // 5 + " it('sums', () => {});", // 6 + " });", + "});", + ].join("\n"); + + it("are found in spec/ whatever the file's name in Jasmine projects, focused and excluded ones included", () => { + expect(specsInSpecDirectory([script])).toBe(true); + expect( + detectRunTargets(src, "spec/cartSpec.js", false, false, true).map((t) => [t.line, t.kind, t.path.join("/")]), + ).toEqual([ + [0, "suite", "cart"], + [1, "test", "cart/adds"], + [2, "suite", "cart/later"], + [3, "test", "cart/later/removes"], + [5, "suite", "cart/total"], + [6, "test", "cart/total/sums"], + ]); + expect(detectRunTargets(src, "lib/cartSpec.js", false, false, true)).toEqual([]); + }); + + it("are not looked for in spec/ of a Jest or Vitest project", () => { + const vitest = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"] }); + expect(specsInSpecDirectory([vitest])).toBe(false); + expect(detectRunTargets(src, "spec/cartSpec.js")).toEqual([]); + }); + + it("run by file and full name", () => { + const targets = detectRunTargets(src, "spec/cartSpec.js", false, false, true); + expect(targetConfig(targets[5]!, "spec/cartSpec.js", [script], src)?.args).toEqual([ + "run", + "test", + "--", + "spec/cartSpec.js", + "--filter=^cart total sums$", + ]); + }); +}); diff --git a/src/features/run/testing/jasmine.ts b/src/features/run/testing/jasmine.ts new file mode 100644 index 000000000..b612ab35e --- /dev/null +++ b/src/features/run/testing/jasmine.ts @@ -0,0 +1,15 @@ +/** + * Jasmine: the IDE's hook (`jasmineHook.js`), imported through `NODE_OPTIONS`, prints a record per + * finished spec (`records.ts`) next to the run's own reporter. Specs are selected with Jasmine's + * own `--filter=`. + */ +import HOOK_SOURCE from "./jasmineHook.js?raw"; + +const HOOK = `--import=data:text/javascript;base64,${btoa(HOOK_SOURCE)}`; + +/** `NODE_OPTIONS` with the IDE's hook added (once). */ +export function withJasmineHook(env: Record<string, string>): Record<string, string> { + const options = env.NODE_OPTIONS ?? ""; + if (options.includes(HOOK)) return env; + return { ...env, NODE_OPTIONS: [options, HOOK].filter(Boolean).join(" ") }; +} diff --git a/src/features/run/testing/jasmineHook.js b/src/features/run/testing/jasmineHook.js new file mode 100644 index 000000000..f6c934a71 --- /dev/null +++ b/src/features/run/testing/jasmineHook.js @@ -0,0 +1,117 @@ +// The IDE's Jasmine hook (`--import`, passed as a data: URL through NODE_OPTIONS): once +// `jasmine-core` is booted, every spec a run reports also prints a record (`records.ts`) next to +// the run's own reporter, with the line the spec is declared on (Jasmine reports none). Runs in the +// user's Node (20+), so plain ESM without dependencies; reporting must never break a test run. +import Module from "node:module"; +import { relative, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const MARK = "@@openidea:test@@"; +const FRAME = /(?:\(|\s)((?:file:\/\/\/?)?(?:[A-Za-z]:)?[^:()]+):(\d+):(\d+)\)?$/; + +// Jasmine reports ES modules' files as URLs (`file:/...`). +const pathOf = (file) => resolve(file.startsWith("file:") ? fileURLToPath(file) : file); +const fileOf = (file) => relative(process.cwd(), pathOf(file)).split("\\").join("/"); + +/** The first frame of `stack` in the user's code: where a spec is declared while Jasmine loads its file. */ +function declaration(stack) { + for (const frame of stack.split("\n")) { + const m = FRAME.exec(frame); + if (!m || m[1].startsWith("node:") || /[\\/]node_modules[\\/]/.test(m[1])) continue; + return { file: pathOf(m[1]), line: Number(m[2]), col: Number(m[3]) }; + } + return null; +} + +function watch(env) { + /** Spec id to where it is declared. */ + const declared = new Map(); + // The globals are replaced, not wrapped: Jasmine finds a spec's file at a fixed depth in the stack + // below `env.it`, which a wrapper would shift. + for (const name of ["it", "fit", "xit"]) { + if (typeof globalThis[name] !== "function" || typeof env[name] !== "function") continue; + globalThis[name] = function () { + const spec = env[name].apply(env, arguments); + try { + // Below the first two lines (the message, this function): the caller. + const at = declaration((new Error().stack ?? "").split("\n").slice(2).join("\n")); + if (spec && spec.id !== undefined && at) declared.set(spec.id, at); + } catch { + // No declaration line. + } + return spec; + }; + } + + const suites = []; + const report = (result, names, status) => { + try { + const at = declared.get(result.id); + const file = result.filename ?? at?.file; + if (!file) return; + // An expectation's stack leaves out its message. + const errors = (result.failedExpectations ?? []).map((e) => + e.stack?.includes(e.message) ? e.stack : [e.message, e.stack].filter(Boolean).join("\n"), + ); + const record = { + path: [fileOf(file), ...names], + status, + ms: result.duration ?? undefined, + line: at?.line, + col: at?.col, + error: errors.length ? errors.join("\n") : undefined, + }; + process.stdout.write(`${MARK}${JSON.stringify(record)}\n`); + } catch { + // A result without its usual shape: no record. + } + }; + env.addReporter({ + suiteStarted: (result) => suites.push(result.description), + suiteDone: (result) => { + // An error in `beforeAll` / `afterAll` (or the describe body) fails the suite itself. + if (result.failedExpectations?.length) report(result, [...suites], "failed"); + suites.pop(); + }, + specDone: (result) => { + // `excluded`: left out by `fit` / `fdescribe` or `--filter`; not part of this run. + const status = { passed: "passed", failed: "failed", pending: "skipped" }[result.status]; + if (status) report(result, [...suites, result.description], status); + }, + }); +} + +const load = Module._load; +const watched = new WeakSet(); +let patched = false; +Module._load = function (...args) { + const exports = load.apply(this, args); + // `jasmine-core`, which the runner (and each `--parallel` worker) boots to get its environment. + if (!patched && typeof exports?.boot === "function" && typeof exports.version === "function") { + patched = true; + const boot = exports.boot; + exports.boot = function (...bootArgs) { + const jasmine = boot.apply(this, bootArgs); + try { + // The runner creates the environment with its own options: watch it once it does. + const getEnv = jasmine.getEnv; + jasmine.getEnv = function (...envArgs) { + const env = getEnv.apply(this, envArgs); + try { + if (!watched.has(env)) { + watched.add(env); + watch(env); + } + } catch { + // Another Jasmine than expected: the run goes on without records. + } + return env; + }; + } catch { + // No environment to watch. + } + return jasmine; + }; + } + return exports; +}; diff --git a/src/features/run/testing/js.ts b/src/features/run/testing/js.ts index b08bd5ae5..0424e395a 100644 --- a/src/features/run/testing/js.ts +++ b/src/features/run/testing/js.ts @@ -37,7 +37,29 @@ function counts(text: string) { return out; } -export function jsParser(): TestOutputParser { +/** `watch`: after a run's summary, the next output starts a new cycle (`reset`). */ +export function jsParser(watch = false): TestOutputParser { + const parser = runParser(); + if (!watch) return parser; + let ended = false; + return { + feed(line) { + const events = parser.feed(line); + if (ended && events.some((e) => e.type !== "summary")) { + ended = false; + events.unshift({ type: "reset" }); + } + // The counts line (`Tests: …`) ends the cycle; `Time:` / `Duration` follow it. + if (!ended && events.some((e) => e.type === "summary" && e.durationMs === undefined)) { + ended = true; + events.push({ type: "end" }); + } + return events; + }, + }; +} + +function runParser(): TestOutputParser { let file: string | null = null; /** Jest verbose describe blocks: indentation → name. */ let describes: Array<{ indent: number; name: string }> = []; diff --git a/src/features/run/testing/rerun.ts b/src/features/run/testing/rerun.ts index 4768d9b63..5c580c0f2 100644 --- a/src/features/run/testing/rerun.ts +++ b/src/features/run/testing/rerun.ts @@ -14,6 +14,7 @@ import { goTestParts, withoutGoSelection } from "../goArguments"; import { withMavenTests } from "../mavenTests"; import { frameworkFor } from "./index"; import { dotnetFilter } from "./dotnet"; +import { cypressSelection } from "./cypress"; import { playwrightProject, playwrightTitles } from "./playwright"; import { withNodeTestNamePattern } from "./nodeTest"; import { nodeStatus, type TestNode, type TestResults } from "./results"; @@ -269,6 +270,13 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string): case "playwright": args = playwrightArgs(config, paths); break; + case "cypress": { + // Tree files may be relative to the specs' common folder (see `cypress.ts`): `**/` finds them from the project. + const files = unique(paths.map((p) => p[0]!).filter(Boolean)).map((f) => (f.startsWith("**/") ? f : `**/${f}`)); + const names = unique(paths.filter((p) => p.length > 1).map((p) => p.slice(1).join(" "))); + if (!files.length) return null; + return { ...config, ...cypressSelection(config, files, { grep: names }), name, detected: true }; + } case "node-test": { // The files narrow a script's run when it gives `node --test` no patterns of its own; the names always do. const files = unique(paths.map((p) => p[0]!).filter(Boolean)); @@ -291,6 +299,16 @@ function builtinTestsConfig(config: RunConfig, paths: string[][], name: string): args = appendScriptArgs(config.command, base, [...files, ...grep]); break; } + case "jasmine": { + // Jasmine's `--filter=` matches a spec's full name: its describe chain and name, space separated. + // A failed suite (`afterAll`) has no spec of that name: its name followed by a space matches its specs. + const files = unique(paths.map((p) => p[0]!).filter(Boolean)); + const names = unique(paths.filter((p) => p.length > 1).map((p) => p.slice(1).join(" "))); + if (!files.length) return null; + const filter = names.length ? [`--filter=^(?:${names.map(escapeRegExp).join("|")})(?: |$)`] : []; + args = appendScriptArgs(config.command, dropFlag(config.args, ["--filter"]), [...files, ...filter]); + break; + } case "pytest": args = pytestArgs(config.args, paths); break; diff --git a/src/features/run/testing/results.ts b/src/features/run/testing/results.ts index 872aa57bd..d6e6a67b4 100644 --- a/src/features/run/testing/results.ts +++ b/src/features/run/testing/results.ts @@ -168,6 +168,15 @@ export class TestResults { case "summary": this.summary = { ...this.summary, ...stripUndefined(e) }; break; + case "reset": + this.roots.length = 0; + this.byId.clear(); + this.summary = {}; + this.finished = false; + break; + case "end": + this.finished = true; + break; } } } diff --git a/src/features/run/testing/types.ts b/src/features/run/testing/types.ts index f770bc180..6291f3fd2 100644 --- a/src/features/run/testing/types.ts +++ b/src/features/run/testing/types.ts @@ -14,6 +14,8 @@ export interface TestLocation { resolve: "path" | "name" | "rubyTest"; /** JVM frames: the class's binary name; `path` is then the file under its package directory. */ className?: string; + /** No line: the describe chain and name of a JS test to find in the file (Cypress reports none). */ + test?: string[]; } export type TestEvent = @@ -21,7 +23,11 @@ export type TestEvent = | { type: "result"; path: string[]; status: Exclude<TestStatus, "running">; durationMs?: number } | { type: "location"; path: string[]; location: TestLocation } | { type: "output"; path: string[]; line: string } - | { type: "summary"; passed?: number; failed?: number; skipped?: number; durationMs?: number }; + | { type: "summary"; passed?: number; failed?: number; skipped?: number; durationMs?: number } + /** A watch mode cycle begins: its results replace the previous ones. */ + | { type: "reset" } + /** A watch mode cycle has reported all its results. */ + | { type: "end" }; export interface TestOutputParser { feed(line: string): TestEvent[]; diff --git a/src/features/run/testing/watch.test.ts b/src/features/run/testing/watch.test.ts new file mode 100644 index 000000000..3ad463e08 --- /dev/null +++ b/src/features/run/testing/watch.test.ts @@ -0,0 +1,152 @@ +import { describe, expect, it } from "vitest"; +import type { RunConfig } from "@/platform/ipc"; +import { jsParser, parseAll, TestResults } from "./index"; +import { watchLaunch } from "./watch"; + +const cfg = (over: Partial<RunConfig>): RunConfig => + ({ + id: "t", + name: "t", + kind: "npm", + command: "npm", + args: ["run", "test"], + env: {}, + isTest: true, + ...over, + }) as RunConfig; + +const JEST_CYCLES = `PASS src/sum.test.js + sum + ✓ adds (3 ms) + ✓ zero (1 ms) + +Test Suites: 1 passed, 1 total +Tests: 2 passed, 2 total +Snapshots: 0 total +Time: 0.861 s +Ran all test suites. + +FAIL src/sum.test.js + sum + ✕ adds (4 ms) + ✓ zero (1 ms) + + ● sum › adds + + expect(received).toBe(expected) + +Test Suites: 1 failed, 1 total +Tests: 1 failed, 1 passed, 2 total +Time: 0.5 s +Ran all test suites.`; + +const VITEST_CYCLES = ` DEV v2.1.9 /p + + ✓ tests/cart.test.ts (5 tests | 1 skipped) 96ms + + Test Files 1 passed (1) + Tests 4 passed | 1 skipped (5) + Duration 1.11s + + PASS Waiting for file changes... + RERUN src/money.ts x2 + + ✓ tests/cart.test.ts (5 tests | 1 skipped) 38ms + + Test Files 1 passed (1) + Tests 4 passed | 1 skipped (5) + Duration 133ms + + PASS Waiting for file changes...`; + +describe("watch mode cycles", () => { + it("replaces the tree with each Jest cycle", () => { + const tests = new TestResults(); + tests.apply(parseAll(jsParser(true), JEST_CYCLES)); + expect(tests.roots.map((r) => r.name)).toEqual(["src/sum.test.js"]); + expect(tests.roots[0]!.children[0]!.children.map((c) => [c.name, c.own])).toEqual([ + ["adds", "failed"], + ["zero", "passed"], + ]); + expect(tests.counts()).toMatchObject({ passed: 1, failed: 1, total: 2 }); + expect(tests.finished).toBe(true); + }); + + it("ends each cycle once and starts the next one unfinished", () => { + const parser = jsParser(true); + const tests = new TestResults(); + const lines = JEST_CYCLES.split("\n"); + const firstEnd = lines.findIndex((l) => l.startsWith("Tests:")); + for (const l of lines.slice(0, firstEnd + 3)) tests.apply(parser.feed(l)); + expect(tests.finished).toBe(true); + tests.apply(parser.feed("FAIL src/sum.test.js")); + expect(tests.finished).toBe(false); + expect(parseAll(jsParser(true), JEST_CYCLES).filter((e) => e.type === "end")).toHaveLength(2); + }); + + it("replaces the tree with each Vitest cycle", () => { + const events = parseAll(jsParser(true), VITEST_CYCLES); + expect(events.filter((e) => e.type === "reset")).toHaveLength(1); + const tests = new TestResults(); + tests.apply(events); + expect(tests.roots).toHaveLength(1); + expect(tests.summary).toMatchObject({ passed: 4, skipped: 1, durationMs: 133 }); + }); + + it("keeps a single run's results without watch", () => { + expect(parseAll(jsParser(), JEST_CYCLES).some((e) => e.type === "reset")).toBe(false); + }); +}); + +const script = (text: string, pre = false) => ({ text, pre }); + +describe("watchLaunch", () => { + it("appends the watch flag to a package.json script", () => { + expect(watchLaunch(cfg({}), script("tsc && jest", true))?.args).toEqual(["run", "test", "--", "--watchAll"]); + expect(watchLaunch(cfg({ command: "pnpm" }), script("vitest --config v.ts"))?.args).toEqual([ + "run", + "test", + "--watch", + ]); + }); + + it("starts `vitest watch` through the package manager for a script running `vitest run`", () => { + const watched = watchLaunch( + cfg({ args: ["run", "test", "--", "tests/a.test.ts"] }), + script("CI=1 vitest run --dir src"), + ); + expect(watched).toMatchObject({ + command: "npm", + args: ["exec", "--", "vitest", "watch", "--dir", "src", "tests/a.test.ts"], + env: { CI: "1" }, + }); + expect(watchLaunch(cfg({ command: "yarn" }), script("vitest run"))?.args).toEqual(["vitest", "watch"]); + expect(watchLaunch(cfg({ command: "pnpm" }), script("vitest run"))?.args).toEqual(["exec", "vitest", "watch"]); + }); + + it("runs once when the watch flag would reach another tool or steps would be skipped", () => { + expect(watchLaunch(cfg({}), script("jest && eslint ."))).toBeNull(); + expect(watchLaunch(cfg({}), script("tsc && vitest run"))).toBeNull(); + expect(watchLaunch(cfg({}), script("vitest run", true))).toBeNull(); + expect(watchLaunch(cfg({}), script("cross-env CI=1 vitest run"))).toBeNull(); + }); + + it("changes the runner's own command line", () => { + expect( + watchLaunch(cfg({ kind: "node", command: "npx", args: ["vitest", "run", "a.test.ts"] }), null)?.args, + ).toEqual(["vitest", "watch", "a.test.ts"]); + expect(watchLaunch(cfg({ kind: "node", command: "npx", args: ["jest", "-t", "^x$"] }), null)?.args).toEqual([ + "jest", + "-t", + "^x$", + "--watchAll", + ]); + }); + + it("is null without Jest or Vitest", () => { + expect(watchLaunch(cfg({}), script("mocha"))).toBeNull(); + expect(watchLaunch(cfg({}), null)).toBeNull(); + // `bun test` is Bun's own runner, not the `test` script. + expect(watchLaunch(cfg({ kind: "bun", command: "bun", args: ["test"] }), script("vitest"))).toBeNull(); + }); +}); diff --git a/src/features/run/testing/watch.ts b/src/features/run/testing/watch.ts new file mode 100644 index 000000000..0bb0f63f0 --- /dev/null +++ b/src/features/run/testing/watch.ts @@ -0,0 +1,91 @@ +/** + * Jest / Vitest "Watch for changes": the launch that keeps the runner watching, so each + * edit reruns the tests in the same tab (`jsParser` starts a new cycle after each summary). + */ +import { call, commands, type RunConfig } from "@/platform/ipc"; +import { commandName } from "../commandName"; +import { parseArgs } from "../configs"; +import { runDirectory } from "../navigate"; +import { appendScriptArgs } from "../scriptArgs"; + +type Runner = "jest" | "vitest"; + +/** Jest's `--watch` needs git or hg; `--watchAll` works everywhere. */ +const WATCH_FLAG: Record<Runner, string> = { jest: "--watchAll", vitest: "--watch" }; +const PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"]; +const CHAIN = new Set(["&&", "||", ";", "|"]); + +function runnerOf(token: string): Runner | null { + const name = commandName(token).replace(/\.[cm]?js$/, ""); + return name === "jest" || name === "vitest" ? name : null; +} + +/** `npm run test` / `pnpm test`: the package.json script it runs (`bun test` is Bun's own runner). */ +function scriptName(config: RunConfig): string | null { + const pm = commandName(config.command); + if (!["npm", "bun"].includes(config.kind) || !PACKAGE_MANAGERS.includes(pm)) return null; + if (config.args[0] === "run") return config.args[1] ?? null; + return pm === "bun" ? null : (config.args[0] ?? null); +} + +/** The package.json script a configuration runs: its text, and whether a `pre` script runs before it. */ +export interface PackageScript { + text: string; + pre: boolean; +} + +export async function packageScript(config: RunConfig): Promise<PackageScript | null> { + const name = scriptName(config); + if (!name) return null; + try { + const pkg = JSON.parse(await call(commands.fsReadText(`${runDirectory(config.cwd)}/package.json`))) as { + scripts?: Record<string, unknown>; + }; + const text = pkg.scripts?.[name]; + return typeof text === "string" ? { text, pre: typeof pkg.scripts?.[`pre${name}`] === "string" } : null; + } catch { + return null; + } +} + +/** The package manager's way to start a package's binary (Yarn PnP included). */ +const EXEC: Record<string, string[]> = { npm: ["exec", "--"], pnpm: ["exec"], yarn: [], bun: ["x"] }; +const ASSIGNMENT = /^\w+=/; + +/** + * `config` launched in watch mode; null when that can't be done and the tests run once: no Jest + * or Vitest, or a script that runs more after it (`jest && eslint .`). `script`: see {@link packageScript}. + */ +export function watchLaunch(config: RunConfig, script: PackageScript | null): RunConfig | null { + const name = scriptName(config); + if (!name) { + const cmd = [config.command, ...config.args]; + const at = cmd.findIndex((t) => runnerOf(t)); + if (at < 0) return null; + const runner = runnerOf(cmd[at]!)!; + // `vitest run` never watches, whatever the flags: `vitest watch` does. + if (runner === "vitest" && cmd[at + 1] === "run") cmd[at + 1] = "watch"; + else cmd.push(WATCH_FLAG[runner]); + return { ...config, command: cmd[0]!, args: cmd.slice(1) }; + } + if (script === null) return null; + const words = parseArgs(script.text); + const at = words.findIndex((w) => runnerOf(w)); + if (at < 0) return null; + const runner = runnerOf(words[at]!)!; + const rest = words.slice(at + 1); + // The package manager adds arguments at the end of the script: the runner must be its last command. + if (rest.some((w) => CHAIN.has(w))) return null; + if (runner === "jest" || rest[0] !== "run") + return { ...config, args: appendScriptArgs(config.command, config.args, [WATCH_FLAG[runner]]) }; + // `vitest run` ignores `--watch`: the package manager starts `vitest watch` with the script's + // variables and options, unless the script does more (a `pre` script, `tsc && …`, `cross-env …`). + const before = words.slice(0, at); + if (script.pre || !before.every((w) => ASSIGNMENT.test(w))) return null; + const env = { ...config.env }; + for (const w of before) env[w.slice(0, w.indexOf("="))] = w.slice(w.indexOf("=") + 1); + const passed = config.args.slice(config.args[0] === "run" ? 2 : 1); + if (passed[0] === "--") passed.shift(); + const exec = EXEC[commandName(config.command)] ?? []; + return { ...config, args: [...exec, "vitest", "watch", ...rest.slice(1), ...passed], env }; +} diff --git a/src/features/run/types.ts b/src/features/run/types.ts index c4fd03649..761f225b2 100644 --- a/src/features/run/types.ts +++ b/src/features/run/types.ts @@ -31,6 +31,7 @@ import { rakeType, rspecType, rubyScriptType } from "./rubyTypes"; import { djangoTestType } from "./djangoTypes"; import { pythonType } from "./pythonTypes"; import { phpunitType } from "./phpunitTypes"; +import { cypressType } from "./cypressType"; import { UNITY_CONFIG_KIND } from "./unity"; export const COMPOUND = "compound"; @@ -204,6 +205,47 @@ const godot: RunConfigTypeContribution = { }, }; +const isUProject = (a: string) => !a.startsWith("-") && /\.uproject$/i.test(a); + +/** + * Unreal Engine: `<editor> <project>.uproject [-game|-server]`. The editor comes from the + * detected configuration (the engine is registered per version); the mode stays in the + * arguments, so the editor, a game and a server are the same type. + */ +const unreal: RunConfigTypeContribution = { + id: "unreal", + label: "Unreal Engine", + icon: "file-cpp", + group: "Unreal", + description: "Open an Unreal Engine project in the editor, or in game mode", + debugAdapter: "lldb-dap", + fields: [ + { + key: "project", + label: "Project", + mono: true, + browse: "file", + required: true, + placeholder: "…/Game.uproject", + }, + { key: "arguments", label: "Arguments", mono: true, placeholder: "e.g. -game" }, + ], + commandLine: (p) => ({ + command: p.executable || "UnrealEditor.exe", + args: [p.project ?? "", ...parseArgs(p.arguments ?? "")], + cwd: null, + }), + paramsFrom(c) { + const project = c.args.find(isUProject); + if (!project) return null; + return { + project, + arguments: formatArgs(c.args.filter((a) => a !== project)), + ...(c.command !== "UnrealEditor.exe" ? { executable: c.command } : {}), + }; + }, +}; + const PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"]; const NPM_COMMANDS = ["run", "test", "start", "install", "ci", "publish", "pack"]; @@ -570,10 +612,12 @@ export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [ npm, node, bun, + cypressType, gradle, maven, godot, flutterType, + unreal, pythonType, pytest, rubyScriptType, @@ -637,7 +681,8 @@ export function withParams(config: RunConfig, params: Record<string, string>, ty ...(config.kind === "dotnet" && config.beforeLaunch === undefined ? { beforeLaunch: [{ kind: "dotnetBuild", target: "" }] } : {}), - ...(config.kind === "dotnet-test" || + ...(config.kind === "cypress" || + config.kind === "dotnet-test" || config.kind === "django-test" || config.kind === "phpunit" || config.kind === "junit" || diff --git a/src/features/run/watchRun.test.ts b/src/features/run/watchRun.test.ts new file mode 100644 index 000000000..845ce61b6 --- /dev/null +++ b/src/features/run/watchRun.test.ts @@ -0,0 +1,88 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import type { RunConfig } from "@/platform/ipc"; + +const ipc = vi.hoisted(() => ({ + runStart: vi.fn(async (_config: RunConfig) => ({ status: "ok", data: { id: 7, pty: false } })), + runStop: vi.fn(async () => ({ status: "ok", data: null })), + fsReadText: vi.fn(async () => ({ status: "ok", data: JSON.stringify({ scripts: { test: ipc.script } }) })), + script: "vitest run", +})); +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal<typeof import("@/platform/ipc")>(); + return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } }; +}); +vi.mock("@tauri-apps/api/core", async (importOriginal) => ({ + ...(await importOriginal<typeof import("@tauri-apps/api/core")>()), + Channel: class { + onmessage: ((m: unknown) => void) | null = null; + }, +})); + +import { useProject } from "@/platform/project"; +import { + provideNotificationService, + provideToolWindowService, + type ToolWindowService, +} from "@/workbench/contributions"; +import { resetRuns, runtime, startRun, toggleRerunAutomatically, useRun } from "./store"; + +const config = (over: Partial<RunConfig> = {}): RunConfig => + ({ + id: "npm:test", + name: "npm run test", + kind: "npm", + command: "npm", + args: ["run", "test"], + cwd: null, + env: {}, + isTest: true, + ...over, + }) as RunConfig; +const launched = () => ipc.runStart.mock.calls.map(([c]) => [c.command, ...c.args].join(" ")); + +beforeEach(() => { + vi.clearAllMocks(); + ipc.script = "vitest run"; + useProject.setState({ settings: null, project: { root: "/p" } as never }); + provideNotificationService({ notify: vi.fn() }); + provideToolWindowService({ show: vi.fn(), hide: vi.fn() } as unknown as ToolWindowService); +}); +afterEach(() => resetRuns()); + +it("runs as configured without Watch for changes", async () => { + await startRun(config(), undefined, undefined, { prepared: true }); + expect(launched()).toEqual(["npm run test"]); + expect(ipc.fsReadText).not.toHaveBeenCalled(); +}); + +it("launches the watcher, and Rerun Automatically stops it", async () => { + const session = await startRun(config({ watch: true }), undefined, undefined, { prepared: true }); + expect(ipc.fsReadText).toHaveBeenCalledWith("/p/package.json"); + expect(launched()).toEqual(["npm exec -- vitest watch"]); + expect(useRun.getState().sessions[0]).toMatchObject({ status: "running", watching: true }); + toggleRerunAutomatically(session!.id); + await vi.waitFor(() => expect(ipc.runStop).toHaveBeenCalledWith(7)); +}); + +it("Rerun Automatically restarts a finished tab in watch mode", async () => { + const session = await startRun(config(), undefined, undefined, { prepared: true }); + useRun.setState((s) => ({ sessions: s.sessions.map((x) => ({ ...x, status: "finished" as const })) })); + toggleRerunAutomatically(session!.id); + await vi.waitFor(() => expect(launched()).toEqual(["npm run test", "npm exec -- vitest watch"])); + expect(useRun.getState().sessions).toHaveLength(1); + expect(useRun.getState().sessions[0]!.config.watch).toBe(true); +}); + +it("runs derived runs (Rerun Failed, selected tests, Update Snapshot) once", async () => { + const session = await startRun(config({ watch: true }), undefined, config({ watch: true }), { prepared: true }); + expect(launched()).toEqual(["npm run test"]); + expect(session?.watching).toBeUndefined(); +}); + +it("runs once, and says so, when the script runs more than the tests", async () => { + ipc.script = "jest && eslint ."; + const session = await startRun(config({ watch: true }), undefined, undefined, { prepared: true }); + expect(launched()).toEqual(["npm run test"]); + expect(useRun.getState().sessions[0]!.watching).toBeUndefined(); + await vi.waitFor(() => expect(runtime(session!.id)!.console.text()).toContain("the tests run once")); +}); diff --git a/src/features/search/__tests__/bookmarks.test.ts b/src/features/search/__tests__/bookmarks.test.ts index 5a2063fe3..4bd7fc08c 100644 --- a/src/features/search/__tests__/bookmarks.test.ts +++ b/src/features/search/__tests__/bookmarks.test.ts @@ -1,4 +1,7 @@ import { beforeEach, describe, expect, it } from "vitest"; +import { EditorView } from "@codemirror/view"; +import { _setActiveEditor, _setFocusedCellEditor, type TextEditorHandle } from "@/editor/api"; +import { caretLine } from "../index"; import { assignMnemonic, bookmarkByMnemonic, @@ -102,3 +105,26 @@ describe("mnemonic bookmarks", () => { expect(bookmarkLabel(list[0]!)).toBe("let x = 1;"); }); }); + +describe("bookmarks in a notebook", () => { + it("read no caret line from a focused notebook cell", () => { + const host = document.createElement("div"); + document.body.appendChild(host); + const view = new EditorView({ doc: "a\nb\n", parent: host }); + const handle = { view, ctx: { doc: 1, path: "/p/a.ts", language: "", uiMode: null, readOnly: false } }; + _setActiveEditor(handle as TextEditorHandle); + try { + expect(caretLine()?.path).toBe("/p/a.ts"); + const cell = new EditorView({ doc: "x = 1\n", parent: host }); + cell.focus(); + _setFocusedCellEditor(cell); + expect(caretLine()).toBeNull(); + _setFocusedCellEditor(null); + expect(caretLine()?.path).toBe("/p/a.ts"); + } finally { + _setActiveEditor(null); + view.destroy(); + view.dom.remove(); + } + }); +}); diff --git a/src/features/search/__tests__/everywhereModel.test.ts b/src/features/search/__tests__/everywhereModel.test.ts index 59f0874b7..be116b345 100644 --- a/src/features/search/__tests__/everywhereModel.test.ts +++ b/src/features/search/__tests__/everywhereModel.test.ts @@ -5,6 +5,7 @@ import { buildRows, fileItem, matchActions, + matchOutsideFiles, mergeSymbols, splitSymbolQuery, parseCommand, @@ -183,6 +184,18 @@ describe("matchActions", () => { }); describe("items and rows", () => { + it("matchOutsideFiles takes - and _ for each other, the exact spelling scoring higher", () => { + const files = [ + { path: "/s/bit-matcher.txt", relPath: "bit-matcher.txt" }, + { path: "/s/bit_matcher.txt", relPath: "bit_matcher.txt" }, + ]; + const hits = matchOutsideFiles(files, "bit_matcher"); + expect(hits.map((h) => h.relPath)).toEqual(["bit-matcher.txt", "bit_matcher.txt"]); + expect(hits[1]!.score).toBeGreaterThan(hits[0]!.score); + expect(hits[0]!.indices).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + expect(matchOutsideFiles(files, "bit.matcher")).toEqual([]); + }); + it("fileItem splits name and directory highlights", () => { const f = fileItem( { path: "/p/src/orders/OrderController.kt", relPath: "src/orders/OrderController.kt", indices: [4, 11, 12, 16] }, diff --git a/src/features/search/everywhere/model.ts b/src/features/search/everywhere/model.ts index 46fe68b15..58c363cce 100644 --- a/src/features/search/everywhere/model.ts +++ b/src/features/search/everywhere/model.ts @@ -220,11 +220,14 @@ export function matchOutsideFiles(files: readonly OutsideFile[], query: string): .toLowerCase(); if (!q) return []; const byPath = q.includes("/"); + // `-` and `_` match each other, as in the index's file matching; the boost keeps the exact spelling first. + const fold = (s: string) => s.replaceAll("_", "-"); + const folded = fold(q); const out: FileMatch[] = []; for (const f of files) { const name = basename(f.relPath); const nameStart = f.relPath.length - name.length; - const m = byPath ? wordMatch(f.relPath, q) : wordMatch(name, q); + const m = byPath ? wordMatch(fold(f.relPath), folded) : wordMatch(fold(name), folded); if (!m) continue; const boost = nameBoost(name, byPath ? q.slice(q.lastIndexOf("/") + 1) : q); out.push({ diff --git a/src/features/search/index.ts b/src/features/search/index.ts index 16c62c219..4d615d234 100644 --- a/src/features/search/index.ts +++ b/src/features/search/index.ts @@ -4,7 +4,7 @@ * window, the Structure tool window + File Structure popup, and bookmarks. */ import { lazyComponent, lazyWhen } from "@/ui"; -import { activeEditor, registerEditorContribution } from "@/editor/api"; +import { activeEditor, focusedCellEditor, registerEditorContribution } from "@/editor/api"; import { executeAction, registerActions } from "@/platform/actions"; import { onFilesMoved, pendingFileMoves } from "@/platform/fileOps"; import { call, commands, IpcError, isTauri, onIdeEvent } from "@/platform/ipc"; @@ -92,7 +92,10 @@ function editorSelectionText(): string | null { } /** The active editor's caret line (and where to show a popup for it). */ -function caretLine(): { path: string; line: number; text: string; at?: { x: number; y: number } } | null { +export function caretLine(): { path: string; line: number; text: string; at?: { x: number; y: number } } | null { + // A notebook cell editor has no line in a bookmarkable file yet: no bookmark rather + // than the last text tab's caret (the notebook's own lines are a later step). + if (focusedCellEditor()) return null; const handle = activeEditor(); if (!handle) return null; const head = handle.view.state.selection.main.head; diff --git a/src/features/services/ServicesTree.test.tsx b/src/features/services/ServicesTree.test.tsx index b11af1350..1519bd4aa 100644 --- a/src/features/services/ServicesTree.test.tsx +++ b/src/features/services/ServicesTree.test.tsx @@ -1,7 +1,13 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { fireEvent, render, screen, within } from "@testing-library/react"; import { usePlatform } from "@/platform/platformInfo"; -import { ToolWindowShownProvider, useServiceProviders, type ServiceTreeItem } from "@/workbench/contributions"; +import { + ToolWindowShownProvider, + registerServiceSelectionItems, + useServiceProviders, + type ServiceContext, + type ServiceTreeItem, +} from "@/workbench/contributions"; import { ServicesTreeView } from "./ServicesTree"; import { useServicesTree } from "./tree"; import { selectedServices, selectionActions, selectionMenu } from "./selection"; @@ -190,6 +196,30 @@ it("ignores removed rows and avoids invoking a selected group's descendants twic expect(stop.mock.calls).toEqual([["group"]]); }); +it("adds other features' entries for selected services, never for a group", () => { + const context = (item: ServiceTreeItem): ServiceContext | null => + item.children ? null : { provider: "a", id: item.key, kind: "app", name: item.label, running: false }; + const provider = { id: "a", useRoots: () => [], menu: () => [{ label: "Own", run }], context }; + const seen: string[][] = []; + const off = registerServiceSelectionItems({ + id: "extra", + menu: (services) => { + seen.push(services.map((s) => s.id)); + return [{ label: "Extra", run }]; + }, + actions: () => [{ id: "extra", title: "Extra", icon: "run", run }], + }); + const at = (item: ServiceTreeItem) => ({ provider: "a", item, parent: null }); + expect( + selectionMenu([at(roots[0]!), at(roots[1]!)], [provider]).map((i) => ("label" in i ? i.label : i.kind)), + ).toEqual(["Own", "separator", "Extra"]); + expect(seen).toEqual([["one", "two"]]); + expect(selectionActions([at(roots[0]!)], [provider]).map((a) => a.id)).toEqual(["extra"]); + const group = { key: "g", label: "g", icon: "run", children: [roots[0]!] }; + expect(selectionMenu([at(group)], [provider]).map((i) => ("label" in i ? i.label : i.kind))).toEqual(["Own"]); + off(); +}); + it("disables actions when no selected row can run them", () => { const { row, toolbar } = setup(); fireEvent.mouseDown(row("three")); diff --git a/src/features/services/docker.tsx b/src/features/services/docker.tsx index 0735e768e..df98cdc1f 100644 --- a/src/features/services/docker.tsx +++ b/src/features/services/docker.tsx @@ -583,6 +583,18 @@ export const dockerProvider: ServiceProviderContribution = { watch, actions, menu, + context: (item) => { + const t = resolveTarget(item.key); + if (t?.node.kind !== "container") return null; + const c = t.node.container; + return { + provider: DOCKER_PROVIDER, + id: c.id, + kind: "docker-container", + name: c.name, + running: c.state === "running", + }; + }, activate: (item) => { const t = resolveTarget(item.key); if (t?.node.kind === "container") useServices.setState({ detailTab: "log" }); diff --git a/src/features/services/selection.ts b/src/features/services/selection.ts index c7938050b..d00855405 100644 --- a/src/features/services/selection.ts +++ b/src/features/services/selection.ts @@ -1,6 +1,11 @@ import { executeAction, getAction, isActionEnabled } from "@/platform/actions"; import type { MenuItem } from "@/ui"; -import type { ServiceItemAction, ServiceProviderContribution } from "@/workbench/contributions"; +import { + serviceSelectionContributions, + type ServiceContext, + type ServiceItemAction, + type ServiceProviderContribution, +} from "@/workbench/contributions"; import type { Located } from "./tree"; /** A selected group already targets its descendants; don't invoke those twice. */ @@ -24,15 +29,42 @@ function batch<T extends { disabled?: boolean; run?: () => void }>(items: T[]): return { ...items[0]!, disabled: !enabled.length, run: () => enabled.forEach((item) => item.run?.()) }; } +/** The selected services as other features see them; null when a selected node is no service (a group). */ +export function selectionContexts( + selection: Located[], + providers: readonly ServiceProviderContribution[], +): ServiceContext[] | null { + const contexts = selection.map(({ item, provider }) => providers.find((p) => p.id === provider)?.context?.(item)); + return contexts.length && contexts.every((c) => !!c) ? (contexts as ServiceContext[]) : null; +} + +function contributed<T>( + selection: Located[], + providers: readonly ServiceProviderContribution[], + pick: (c: ReturnType<typeof serviceSelectionContributions>[number], services: ServiceContext[]) => T[] | undefined, +): T[] { + const services = selectionContexts(selection, providers); + if (!services) return []; + return serviceSelectionContributions().flatMap((c) => { + try { + return pick(c, services) ?? []; + } catch (e) { + console.error(`services contribution ${c.id} failed`, e); + return []; + } + }); +} + export function selectionActions( selection: Located[], providers: readonly ServiceProviderContribution[], ): ServiceItemAction[] { const groups = selection.map(({ item, provider }) => providers.find((p) => p.id === provider)?.actions?.(item) ?? []); - return (groups[0] ?? []).flatMap((action) => { + const own = (groups[0] ?? []).flatMap((action) => { const matches = groups.flatMap((group) => group.filter((a) => a.id === action.id)); return matches.length === groups.length ? [batch(matches)] : []; }); + return [...own, ...contributed(selection, providers, (c, services) => c.actions?.(services))]; } function menuKey(item: MenuItem): string | undefined { @@ -70,5 +102,7 @@ function commonMenu(groups: MenuItem[][]): MenuItem[] { export function selectionMenu(selection: Located[], providers: readonly ServiceProviderContribution[]): MenuItem[] { const groups = selection.map(({ item, provider }) => providers.find((p) => p.id === provider)?.menu?.(item) ?? []); - return groups.length === 1 ? groups[0]! : commonMenu(groups); + const own = groups.length === 1 ? groups[0]! : commonMenu(groups); + const extra = contributed(selection, providers, (c, services) => c.menu?.(services)); + return extra.length ? [...own, ...(own.length ? [{ kind: "separator" } as const] : []), ...extra] : own; } diff --git a/src/features/settings/__tests__/intelliSort.test.tsx b/src/features/settings/__tests__/intelliSort.test.tsx new file mode 100644 index 000000000..cd30299c3 --- /dev/null +++ b/src/features/settings/__tests__/intelliSort.test.tsx @@ -0,0 +1,66 @@ +import { useMemo, type ComponentType } from "react"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { useProject } from "@/platform/project"; +import { PageContext } from "../components/context"; +import { DEFAULT_SETTINGS } from "../model/schema"; +import { openSettings, stagedValue, useSettingsDialog } from "../model/staging"; +import { codeStyleLanguagePages } from "../pages/editor/codeStyle"; + +const mocks = vi.hoisted(() => ({ languages: vi.fn() })); +vi.mock("@/platform/ipc", async (original) => { + const actual = await original<typeof import("@/platform/ipc")>(); + return { + ...actual, + isTauri: () => true, + commands: { + ...actual.commands, + languages: mocks.languages, + }, + }; +}); + +beforeEach(() => { + mocks.languages.mockResolvedValue([ + { id: "java", name: "Java", indent: { tabSize: 4, insertSpaces: true } }, + { id: "rust", name: "Rust" }, + ]); + useProject.setState({ settings: structuredClone(DEFAULT_SETTINGS), project: null }); + openSettings("editor.codeStyle.java"); +}); +afterEach(cleanup); + +function CodeStylePage({ id, Page }: { id: string; Page: ComponentType }) { + const value = useMemo(() => ({ pageId: id, scope: "global" as const }), [id]); + return ( + <PageContext.Provider value={value}> + <Page /> + </PageContext.Provider> + ); +} + +async function page(language: string) { + const pages = await codeStyleLanguagePages(); + const spec = pages.find((p) => p.id === `editor.codeStyle.${language}`)!; + render(<CodeStylePage id={spec.id} Page={spec.component!} />); +} +const value = () => stagedValue(useSettingsDialog.getState(), "global", "editor.codeStyle.languages"); + +describe("Java Imports (IntelliSort)", () => { + it("stages the class-count and static-count options on the Java code style", async () => { + await page("java"); + fireEvent.click(screen.getByRole("tab", { name: "Imports" })); + fireEvent.change(screen.getByLabelText("Class count to use import with *"), { target: { value: "7" } }); + fireEvent.change(screen.getByLabelText("Names count to use static import with *"), { target: { value: "2" } }); + expect(value()).toEqual({ + java: { classCountToUseImportWithStar: 7, namesCountToUseStaticImportWithStar: 2 }, + }); + fireEvent.click(screen.getByRole("button", { name: "Reset to Language Defaults" })); + expect(value()).toEqual({}); + }); + + it("keeps the Imports tab specific to Java", async () => { + await page("rust"); + expect(screen.queryByRole("tab", { name: "Imports" })).toBeNull(); + }); +}); diff --git a/src/features/settings/__tests__/languages.test.ts b/src/features/settings/__tests__/languages.test.ts index 195ed304e..ae0ff52d2 100644 --- a/src/features/settings/__tests__/languages.test.ts +++ b/src/features/settings/__tests__/languages.test.ts @@ -201,6 +201,12 @@ describe("languages settings", () => { expect(v.prettier).toMatchObject({ prefer: false, runOnSave: false }); }); + it("gives dprint opt-in settings without a language list", () => { + expect(validateLanguages({}).dprint).toEqual({ ...DEFAULT_LANGUAGES.prettier, languages: [] }); + const v = validateLanguages({ dprint: { path: " ./bin/dprint ", prefer: true, runOnSave: true } }); + expect(v.dprint).toMatchObject({ path: "./bin/dprint", languages: [], prefer: true, runOnSave: true }); + }); + it("enables Ruff for Python by default and keeps its settings separate", () => { expect(validateLanguages({}).ruff).toMatchObject({ path: "", @@ -389,6 +395,7 @@ describe("language pages", () => { "Prettier", "oxfmt", "Biome", + "dprint", "Ruby", "Rust", "TypeScript", diff --git a/src/features/settings/__tests__/tsCodeStyle.test.tsx b/src/features/settings/__tests__/tsCodeStyle.test.tsx new file mode 100644 index 000000000..fa903cd57 --- /dev/null +++ b/src/features/settings/__tests__/tsCodeStyle.test.tsx @@ -0,0 +1,82 @@ +import { useMemo, type ComponentType } from "react"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { useProject } from "@/platform/project"; +import { PageContext } from "../components/context"; +import { DEFAULT_SETTINGS } from "../model/schema"; +import { openSettings, stagedValue, useSettingsDialog } from "../model/staging"; +import { codeStyleLanguagePages } from "../pages/editor/codeStyle"; + +vi.mock("@/platform/ipc", async (original) => { + const actual = await original<typeof import("@/platform/ipc")>(); + return { + ...actual, + isTauri: () => true, + commands: { + ...actual.commands, + languages: async () => [ + { id: "typescript", name: "TypeScript", lineComment: "//" }, + { id: "javascript", name: "JavaScript", lineComment: "//" }, + { id: "typescriptreact", name: "TypeScript JSX", lineComment: "//" }, + ], + }, + }; +}); + +beforeEach(() => { + useProject.setState({ settings: structuredClone(DEFAULT_SETTINGS), project: null }); + openSettings("editor.codeStyle.typescript"); +}); +afterEach(cleanup); + +function CodeStylePage({ id, Page }: { id: string; Page: ComponentType }) { + const value = useMemo(() => ({ pageId: id, scope: "global" as const }), [id]); + return ( + <PageContext.Provider value={value}> + <Page /> + </PageContext.Provider> + ); +} + +async function page(language: string) { + const pages = await codeStyleLanguagePages(); + const spec = pages.find((p) => p.id === `editor.codeStyle.${language}`)!; + render(<CodeStylePage id={spec.id} Page={spec.component!} />); + return spec; +} +const value = () => stagedValue(useSettingsDialog.getState(), "global", "editor.codeStyle.languages"); + +describe("JavaScript / TypeScript code style", () => { + it("stages semicolons, quotes and spaces for the language of the page", async () => { + const spec = await page("typescript"); + expect(spec.keywords).toEqual(expect.arrayContaining(["Spaces", "Punctuation", "Semicolons", "Quotes"])); + fireEvent.click(screen.getByRole("tab", { name: "Punctuation" })); + expect(screen.getByRole("button", { name: "Semicolons" }).textContent).toContain("Keep as is"); + expect(screen.getByRole("button", { name: "Quotes" }).textContent).toContain("As in the file"); + fireEvent.click(screen.getByRole("button", { name: "Semicolons" })); + fireEvent.click(screen.getByRole("option", { name: "Don't use semicolons" })); + fireEvent.click(screen.getByRole("button", { name: "Quotes" })); + fireEvent.click(screen.getByRole("option", { name: "Single quotes" })); + expect(value()).toEqual({ typescript: { semicolons: "remove", quotes: "single" } }); + + fireEvent.click(screen.getByRole("tab", { name: "Spaces" })); + const braces = screen.getByRole("checkbox", { name: "Within braces" }) as HTMLInputElement; + expect(braces.checked).toBe(true); + fireEvent.click(braces); + expect(value()).toEqual({ + typescript: { + semicolons: "remove", + quotes: "single", + spaces: { insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: false }, + }, + }); + }); + + it("is on the JavaScript and TypeScript pages only", async () => { + await page("javascript"); + expect(screen.getByRole("tab", { name: "Punctuation" })).toBeTruthy(); + cleanup(); + await page("typescriptreact"); + expect(screen.queryByRole("tab", { name: "Punctuation" })).toBeNull(); + }); +}); diff --git a/src/features/settings/languages/FormatterPage.tsx b/src/features/settings/languages/FormatterPage.tsx index 613d25ddf..af624fb8e 100644 --- a/src/features/settings/languages/FormatterPage.tsx +++ b/src/features/settings/languages/FormatterPage.tsx @@ -71,18 +71,20 @@ function FormatterPage({ </Row> <Toggle label="Run on save" checked={save} onChange={setSave} hint={saveHint} /> </Section> - <Section title="Enabled languages"> - {DEFAULT_LANGUAGES[tool].languages.map((language) => ( - <Toggle - key={language} - label={names[language]!} - checked={languages.includes(language)} - onChange={(checked) => - setLanguages(checked ? [...languages, language] : languages.filter((l) => l !== language)) - } - /> - ))} - </Section> + {DEFAULT_LANGUAGES[tool].languages.length > 0 && ( + <Section title="Enabled languages"> + {DEFAULT_LANGUAGES[tool].languages.map((language) => ( + <Toggle + key={language} + label={names[language]!} + checked={languages.includes(language)} + onChange={(checked) => + setLanguages(checked ? [...languages, language] : languages.filter((l) => l !== language)) + } + /> + ))} + </Section> + )} </> ); } @@ -159,6 +161,19 @@ export function BiomePage() { ); } +export function DprintPage() { + return ( + <FormatterPage + tool="dprint" + name="dprint" + pathLabel="dprint path" + autoLabel="Automatic (projects with dprint)" + providerHint="dprint formats every file its plugins cover, before the other formatters, below a dprint configuration file (dprint.json, .dprint.json, dprint.jsonc) or installation, or when it is the selected provider. Other files keep their usual formatter." + saveHint="Run dprint on save for the files it formats. Format on save also runs it." + /> + ); +} + export function RuffPage() { return ( <FormatterPage diff --git a/src/features/settings/model/schema.ts b/src/features/settings/model/schema.ts index 4e17039e6..cf6bb0f92 100644 --- a/src/features/settings/model/schema.ts +++ b/src/features/settings/model/schema.ts @@ -118,7 +118,7 @@ export interface ValidSettings extends WorkflowSettings { proxy: ProxySettingsValid; remoteDevelopment: { idleTimeoutMinutes: number }; /** Tools › Download sources: a mirror prefix for the installer's release downloads. */ - toolDownloads: { githubMirror: string }; + toolDownloads: { githubMirror: string; configuredRegistriesOnly: boolean }; languages: LanguagesValid; cmake: ReturnType<typeof validateCMake>; projectStructure: ProjectStructureValid; @@ -227,7 +227,7 @@ export const DEFAULT_SETTINGS: ValidSettings = { notifications: DEFAULT_NOTIFICATIONS, proxy: DEFAULT_PROXY, remoteDevelopment: { idleTimeoutMinutes: DEFAULT_REMOTE_IDLE_MINUTES }, - toolDownloads: { githubMirror: "" }, + toolDownloads: { githubMirror: "", configuredRegistriesOnly: false }, languages: DEFAULT_LANGUAGES, cmake: {}, projectStructure: DEFAULT_PROJECT_STRUCTURE, @@ -435,6 +435,7 @@ export function validateSettings(raw: Settings | unknown): ValidSettings { typeof obj(root.toolDownloads).githubMirror === "string" ? String(obj(root.toolDownloads).githubMirror).trim() : "", + configuredRegistriesOnly: obj(root.toolDownloads).configuredRegistriesOnly === true, }, languages: validateLanguages(root.languages), cmake: validateCMake(root.cmake), diff --git a/src/features/settings/pages/editor/codeStyle.tsx b/src/features/settings/pages/editor/codeStyle.tsx index 77a73afc6..83fff0093 100644 --- a/src/features/settings/pages/editor/codeStyle.tsx +++ b/src/features/settings/pages/editor/codeStyle.tsx @@ -157,6 +157,55 @@ const COMMENTS = { keywords: ["Line comment at first column", "Add a space at line comment start"], }; const CASE = { id: "case", label: "Case", keywords: ["Keywords", "Identifiers", "To upper", "To lower"] }; +const IMPORTS = { + id: "imports", + label: "Imports", + keywords: ["imports", "static imports", "wildcard", "class count", "import with *"], +}; + +const SPACES = { id: "spaces", label: "Spaces", keywords: ["Space", "Around binary operators", "Within braces"] }; +const PUNCTUATION = { id: "punctuation", label: "Punctuation", keywords: ["Semicolons", "Quotes"] }; + +/** The TypeScript server's code style: JavaScript (and JSX) and TypeScript (and TSX). */ +const TS_STYLE_LANGUAGES = new Set(["javascript", "typescript"]); + +/** tsserver's space options and their defaults (vtsls'). */ +const TS_SPACES = [ + { key: "insertSpaceAfterCommaDelimiter", label: "After comma", on: true }, + { key: "insertSpaceAfterSemicolonInForStatements", label: "After semicolon in for statements", on: true }, + { key: "insertSpaceBeforeAndAfterBinaryOperators", label: "Around binary operators", on: true }, + { key: "insertSpaceAfterKeywordsInControlFlowStatements", label: "After control flow keywords", on: true }, + { + key: "insertSpaceAfterFunctionKeywordForAnonymousFunctions", + label: "After function keyword in anonymous functions", + on: true, + }, + { key: "insertSpaceBeforeFunctionParenthesis", label: "Before function declaration parentheses", on: false }, + { key: "insertSpaceAfterConstructor", label: "After constructor keyword", on: false }, + { key: "insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis", label: "Within parentheses", on: false }, + { key: "insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets", label: "Within brackets", on: false }, + { key: "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", label: "Within braces", on: true }, + { key: "insertSpaceAfterOpeningAndBeforeClosingEmptyBraces", label: "Within empty braces", on: true }, + { + key: "insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces", + label: "Within template string interpolations", + on: false, + }, + { key: "insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces", label: "Within JSX expressions", on: false }, + { key: "insertSpaceAfterTypeAssertion", label: "After type assertion", on: false }, +]; + +const SEMICOLONS: SelectOption<NonNullable<LanguageCodeStyle["semicolons"]>>[] = [ + { value: "ignore", label: "Keep as is" }, + { value: "insert", label: "Use semicolons" }, + { value: "remove", label: "Don't use semicolons" }, +]; + +const QUOTES: SelectOption<NonNullable<LanguageCodeStyle["quotes"]>>[] = [ + { value: "auto", label: "As in the file" }, + { value: "single", label: "Single quotes" }, + { value: "double", label: "Double quotes" }, +]; const WORD_CASES: SelectOption<SqlWordCase>[] = [ { value: "upper", label: "To upper" }, @@ -254,6 +303,83 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) { ), }); } + if (lang.id === "java") { + tabs.push({ + ...IMPORTS, + content: ( + <FormGroup> + <Row + label="Class count to use import with '*'" + hint="Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports)." + > + <NumberInput + value={own.classCountToUseImportWithStar ?? 5} + onChange={(n) => set({ classCountToUseImportWithStar: n })} + min={1} + max={999} + integer + aria-label="Class count to use import with *" + /> + </Row> + <Row + label="Names count to use static import with '*'" + hint="Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports)." + > + <NumberInput + value={own.namesCountToUseStaticImportWithStar ?? 3} + onChange={(n) => set({ namesCountToUseStaticImportWithStar: n })} + min={1} + max={999} + integer + aria-label="Names count to use static import with *" + /> + </Row> + </FormGroup> + ), + }); + } + if (TS_STYLE_LANGUAGES.has(lang.id)) { + tabs.push( + { + ...SPACES, + content: ( + <> + {TS_SPACES.map(({ key, label, on }) => ( + <Toggle + key={key} + checked={own.spaces?.[key] ?? on} + onChange={(v) => set({ spaces: { ...own.spaces, [key]: v } })} + label={label} + /> + ))} + </> + ), + }, + { + ...PUNCTUATION, + content: ( + <FormGroup> + <Row label="Semicolons"> + <Select + value={own.semicolons ?? "ignore"} + options={SEMICOLONS} + onChange={(semicolons) => set({ semicolons })} + aria-label="Semicolons" + /> + </Row> + <Row label="Quotes" hint="For the strings and imports the TypeScript server adds."> + <Select + value={own.quotes ?? "auto"} + options={QUOTES} + onChange={(quotes) => set({ quotes })} + aria-label="Quotes" + /> + </Row> + </FormGroup> + ), + }, + ); + } if (lang.id === "sql") { const wordCase = sqlCaseOf(own); tabs.push({ @@ -292,6 +418,13 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) { )} </div> )} + {TS_STYLE_LANGUAGES.has(lang.id) && ( + <div className={styles.note}> + {tx( + "The TypeScript server applies Spaces and Punctuation to Reformat Code and to the code it adds: quick fixes, imports, refactorings and organize imports. Files below a Prettier, Biome or oxfmt configuration are formatted by that tool. A .editorconfig's quote_type and ij_* properties come first. TSX files use the TypeScript settings, JSX files the JavaScript ones.", + )} + </div> + )} {lang.id === "php" && ( <section aria-label={tx("Alignment")}> <div className={styles.previewTitle}> @@ -408,10 +541,20 @@ export async function codeStyleLanguagePages(): Promise<PageSpec[]> { ...keywords, ]), ...(lang.id === "java" - ? ["Formatting profile", "IntelliJ IDEA", "Custom Eclipse formatter XML", "Eclipse formatter XML"] + ? [ + "Formatting profile", + "IntelliJ IDEA", + "Custom Eclipse formatter XML", + "Eclipse formatter XML", + IMPORTS.label, + ...IMPORTS.keywords, + ] : []), ...(lang.id === "php" ? ["Alignment", "Align key-value pairs", "Align consecutive assignments"] : []), ...(lang.id === "sql" ? [CASE.label, ...CASE.keywords, "Do not change"] : []), + ...(TS_STYLE_LANGUAGES.has(lang.id) + ? [SPACES, PUNCTUATION].flatMap(({ label, keywords }) => [label, ...keywords]) + : []), ], component: () => <LanguageStyle lang={lang} />, })); diff --git a/src/features/settings/pages/languages.tsx b/src/features/settings/pages/languages.tsx index 32e71cf2b..2e3c39031 100644 --- a/src/features/settings/pages/languages.tsx +++ b/src/features/settings/pages/languages.tsx @@ -25,6 +25,7 @@ const PrettierPage = lazyPage("languages.prettier", () => ); const OxfmtPage = lazyPage("languages.oxfmt", () => import("../languages/FormatterPage").then((m) => m.OxfmtPage)); const BiomePage = lazyPage("languages.biome", () => import("../languages/FormatterPage").then((m) => m.BiomePage)); +const DprintPage = lazyPage("languages.dprint", () => import("../languages/FormatterPage").then((m) => m.DprintPage)); const DocstringsPage = lazyPage("python.docstrings", () => import("../languages/DocstringsPage").then((m) => m.DocstringsPage), ); @@ -226,6 +227,16 @@ export const LANGUAGE_PAGES: PageSpec[] = [ keywords: ["formatter", "linter", "biome", "biome.json", "format on save", "node_modules"], component: BiomePage, }, + { + id: "languages.dprint", + projectScope: true, + defaultScope: "project", + title: "dprint", + group: LANGUAGES_GROUP, + order: 403.8, + keywords: ["formatter", "dprint", "dprint.json", "format on save", "node_modules"], + component: DprintPage, + }, { id: "python.docstrings", title: "Docstrings", diff --git a/src/features/settings/pages/tools.tsx b/src/features/settings/pages/tools.tsx index 16f87edf1..5ccd34693 100644 --- a/src/features/settings/pages/tools.tsx +++ b/src/features/settings/pages/tools.tsx @@ -892,7 +892,20 @@ export const TOOLS_PAGES: PageSpec[] = [ title: "Download Mirrors", group: TOOLS_GROUP, order: 590, - keywords: ["mirror", "download", "github", "proxy", "slow", "language server", "accelerate"], + keywords: [ + "mirror", + "download", + "github", + "proxy", + "slow", + "language server", + "accelerate", + "registry", + "npm", + "maven central", + "nexus", + "artifactory", + ], sections: [ { title: "GitHub", @@ -905,6 +918,17 @@ export const TOOLS_PAGES: PageSpec[] = [ }, ], }, + { + title: "Package Registries", + options: [ + { + kind: "toggle", + key: "toolDownloads.configuredRegistriesOnly", + label: "Use only the configured package registries", + hint: "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).", + }, + ], + }, ], }, ]; diff --git a/src/features/terminal/index.ts b/src/features/terminal/index.ts index fe2423e1b..70e6998ce 100644 --- a/src/features/terminal/index.ts +++ b/src/features/terminal/index.ts @@ -32,6 +32,7 @@ import { moveTerminalToEditor, openNewTerminalInEditor, splitCliTab, + useClis, } from "./cli"; import { installTerminalKeys } from "./keys"; import { loadTerminalRuntime, terminalRuntime } from "./loader"; @@ -170,6 +171,7 @@ export function activate(): () => void { keepAlive: true, singleton: true, splitInput: splitCliTab, + canNavigate: (input, open) => open || !!useClis.getState().sessions[input.key], onClose: (input) => terminalRuntime()?.disposeCli(input.key), isBusy: (input) => terminalRuntime()?.cliBusy(input.key) ?? false, }), diff --git a/src/features/vcs/BranchFilterPopup.tsx b/src/features/vcs/BranchFilterPopup.tsx index 2e4ca58b2..5827242ba 100644 --- a/src/features/vcs/BranchFilterPopup.tsx +++ b/src/features/vcs/BranchFilterPopup.tsx @@ -1,5 +1,5 @@ import clsx from "clsx"; -import { useEffect, useMemo, useState, type KeyboardEvent } from "react"; +import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react"; import type { Branch } from "@/bindings"; import { HighlightedText, Icon, List, Popup, SearchField, T, firstSelectable, fuzzyMatch, listNavigate } from "@/ui"; import { useRowHeight } from "@/ui/density"; @@ -25,7 +25,10 @@ type Row = }; const ROW_HEIGHT = 24; +/** The list's height limit when the window has no more room below the popup. */ const MAX_LIST_HEIGHT = 320; +/** Popup's gap to its anchor and its margin to the window edge. */ +const POPUP_MARGINS = 4 + 6; /** * IDEA's branch filter: HEAD, the favorite branches (★), then Local and Remote collapsed like its @@ -129,7 +132,19 @@ export function BranchFilterPopup({ setActive(next); } }; - const height = Math.min(MAX_LIST_HEIGHT, Math.max(rowHeight * 3, rows.length * rowHeight)); + const listRef = useRef<HTMLDivElement>(null); + const [maxListHeight, setMaxListHeight] = useState(MAX_LIST_HEIGHT); + // Opened groups grow the list down to the window's bottom edge, so the popup stays where it opened. + // With less room than that below the anchor, the list keeps its usual limit. + useLayoutEffect(() => { + const list = listRef.current; + const popup = list?.parentElement; + if (!list || !popup) return; + const room = window.innerHeight - anchor.getBoundingClientRect().bottom - POPUP_MARGINS; + const others = popup.offsetHeight - parseFloat(list.style.height); + setMaxListHeight(Math.max(MAX_LIST_HEIGHT, Math.floor(room - others))); + }, [anchor]); + const height = Math.min(maxListHeight, Math.max(rowHeight * 3, rows.length * rowHeight)); return ( <Popup open @@ -152,7 +167,7 @@ export function BranchFilterPopup({ aria-label="Search branches" /> </div> - <div className={styles.branchFilterList} style={{ height }}> + <div ref={listRef} className={styles.branchFilterList} style={{ height }}> <List items={rows} getKey={(r) => r.key} diff --git a/src/features/vcs/BranchWidget.tsx b/src/features/vcs/BranchWidget.tsx index 91b208ae5..fda848f7b 100644 --- a/src/features/vcs/BranchWidget.tsx +++ b/src/features/vcs/BranchWidget.tsx @@ -25,6 +25,7 @@ import { } from "@/ui"; import { useRowHeight } from "@/ui/density"; import type { PopupAnchor } from "@/ui/Popup"; +import { isSubmenuAim, type MenuPointer } from "@/ui/menuAim"; import { useActiveRepository, useWidgetBranch } from "./activeRepository"; import { buildBranchRows, @@ -737,6 +738,14 @@ function MultiRepoPanel({ const { menuFor, setMenuFor, openTagMenu } = useBranchSubmenu(); const [repoMenu, setRepoMenu] = useState<{ root: string; el: HTMLElement; focus: boolean } | null>(null); const listRef = useRef<HTMLDivElement>(null); + const aim = useRef<{ + previous: MenuPointer | null; + pointer: MenuPointer | null; + moved: boolean; + pending: number | null; + timer?: ReturnType<typeof setTimeout>; + }>({ previous: null, pointer: null, moved: false, pending: null }); + const repoMenuLabel = repoMenu ? tx`Branches of ${repoName(repoMenu.root)}` : ""; const searchRef = useRef<HTMLInputElement>(null); /** Back from a repository's submenu to the search field. */ const closeRepoMenu = () => { @@ -867,11 +876,52 @@ function MultiRepoPanel({ } }; // The pointer on a repository opens its branches right away; elsewhere it closes them. - const hover = (i: number) => { + const applyHover = (i: number) => { + clearTimeout(aim.current.timer); + aim.current.pending = null; setActive(i); if (rows[i]?.type === "repo") openSub(i, false); else setRepoMenu(null); }; + /** While the pointer heads for the open branch list, the rows it crosses wait (like submenus of a menu). */ + const aiming = () => { + const { previous, pointer } = aim.current; + const popup = repoMenu && document.querySelector(`[data-popup][aria-label="${CSS.escape(repoMenuLabel)}"]`); + return !!popup && !!pointer && isSubmenuAim(previous, pointer, popup.getBoundingClientRect()); + }; + const deferHover = (i: number) => { + clearTimeout(aim.current.timer); + aim.current.pending = i; + aim.current.timer = setTimeout(() => applyHover(i), 300); + }; + const hover = (i: number) => { + const fromPointer = aim.current.moved; + aim.current.moved = false; + const row = rows[i]; + const openRepo = row?.type === "repo" && row.repo.root === repoMenu?.root; + if (fromPointer && repoMenu && !openRepo && aiming()) deferHover(i); + else applyHover(i); + }; + // Pointer positions for the aim check, recorded before the rows see the move (capture phase). + useEffect(() => { + if (!repoMenu) return; + const onMove = (e: PointerEvent) => { + const a = aim.current; + if (a.pointer?.x === e.clientX && a.pointer.y === e.clientY) return; + a.previous = a.pointer; + a.pointer = { x: e.clientX, y: e.clientY }; + a.moved = true; + if (a.pending === null) return; + const popup = document.querySelector(`[data-popup][aria-label="${CSS.escape(repoMenuLabel)}"]`); + if (popup?.contains(e.target as Node)) { + clearTimeout(a.timer); + a.pending = null; + } else if (!aiming()) applyHover(a.pending); + }; + document.addEventListener("pointermove", onMove, true); + return () => document.removeEventListener("pointermove", onMove, true); + }); + useEffect(() => () => clearTimeout(aim.current.timer), []); const onKeyDown = (e: KeyboardEvent) => { if (isNewBranchStroke(strokeOf(e))) { @@ -984,7 +1034,7 @@ function MultiRepoPanel({ placement="right-start" offset={2} autoFocus={repoMenu.focus} - aria-label={tx`Branches of ${repoName(repoMenu.root)}`} + aria-label={repoMenuLabel} onClose={closeRepoMenu} className={styles.popup} > diff --git a/src/features/vcs/DiffEditor.tsx b/src/features/vcs/DiffEditor.tsx index ab8b2d066..71ceedcf1 100644 --- a/src/features/vcs/DiffEditor.tsx +++ b/src/features/vcs/DiffEditor.tsx @@ -1,6 +1,8 @@ /** Diff viewer editor tab (side-by-side / unified) built on @codemirror/merge. */ import { focusedDiffNavigator, setFocusedDiffNavigator, type DiffNavigator } from "./diffNavigator"; import { StagingDiff } from "./StagingDiff"; +import { ImageDiffHost } from "./ImageDiffHost"; +import { imageDiffKind } from "./imageDiffInput"; import { useCallback, useEffect, @@ -404,19 +406,66 @@ export function DiffEditor(props: DiffEditorProps) { } export function ResolvedDiffEditor({ - diff: { data, entries, loading }, + diff: { data, entries, loading, versions }, ...props }: DiffEditorProps & { diff: ReturnType<typeof useGitDiffEntries> }) { const input = data === props.input.data ? props.input : { ...props.input, data }; - if (data.middle) return <StagingDiff key={input.key} {...props} input={input} metadataLoading={loading} />; - return ( + const [source, setSource] = useState<{ key: string; visible: boolean }>(); + const imageData = useMemo(() => (versions ? { ...data, ...versions } : data), [data, versions]); + const regularFiles = !entries?.some((entry) => entry && !entry.mode.startsWith("100")); + const kind = regularFiles && !hasGitlink(data) ? imageDiffKind(imageData) : null; + const openedSource = kind === "svg" && source?.key === input.key; + const showSource = openedSource && source.visible; + if (kind && loading && !openedSource) return <Spinner size={14} />; + const image = kind && !showSource && ( + <ImageDiffHost + key={input.key} + {...props} + data={imageData} + onSource={kind === "svg" ? () => setSource({ key: input.key, visible: true }) : undefined} + /> + ); + if (image && !openedSource) return image; + + const preview = openedSource && ( + <Button size="small" onClick={() => setSource({ key: input.key, visible: false })}> + <T>Image preview</T> + </Button> + ); + const toolbarActions = openedSource ? ( + <> + {preview} + {props.toolbarActions} + </> + ) : ( + props.toolbarActions + ); + const text = data.middle ? ( + <StagingDiff key={input.key} {...props} input={input} toolbarActions={toolbarActions} metadataLoading={loading} /> + ) : ( <TwoPaneDiff {...props} input={input} + toolbarActions={toolbarActions} metadataLoading={loading} gitModes={entries ? [entries[0]?.mode ?? null, entries[2]?.mode ?? null] : undefined} /> ); + if (!openedSource) return text; + // Unmounting an editable staged diff can save its draft. Switching views must preserve it. + return ( + <> + {image} + <div + hidden={!showSource} + inert={!showSource} + className={showSource ? clsx(styles.root, props.fit && styles.fit) : undefined} + > + {props.fit && !data.middle && preview} + {text} + </div> + </> + ); } function TwoPaneDiff({ diff --git a/src/features/vcs/ImageDiff.module.css b/src/features/vcs/ImageDiff.module.css new file mode 100644 index 000000000..2cb870785 --- /dev/null +++ b/src/features/vcs/ImageDiff.module.css @@ -0,0 +1,96 @@ +.root { + display: flex; + flex: 1; + flex-direction: column; + height: 100%; + min-height: 180px; + min-width: 0; + background: var(--bg-editor); +} +.toolbar { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: var(--space-1); + padding: var(--space-1) var(--space-2); + border-bottom: 1px solid var(--border); +} +.toolbar > button[aria-pressed="true"] { + background: var(--bg-toolbar-selected, var(--bg-tree-selected)); + color: var(--fg-strong); +} +.separator { + height: 16px; + border-inline-start: 1px solid var(--border-strong); +} +.actions { + display: flex; + margin-inline-start: auto; +} +.panes { + display: flex; + flex: 1; + min-height: 0; +} +.pane { + display: flex; + flex-direction: column; + flex: 1 1 0; + min-width: 0; +} +.pane + .pane { + border-inline-start: 1px solid var(--border); +} +.heading { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: var(--space-1); + padding: var(--space-1-5) var(--space-3); + border-bottom: 1px solid var(--border); + color: var(--fg-secondary); + font-size: var(--fs-small); + font-variant-numeric: tabular-nums; +} +.heading strong { + overflow: hidden; + color: var(--fg-strong); + font-weight: 500; + text-overflow: ellipsis; + white-space: nowrap; +} +.surface { + container-type: size; + display: flex; + flex: 1; + min-height: 0; + overflow: auto; + padding: var(--space-2); +} +.plane { + position: relative; + flex: none; + width: var(--plane-width); + aspect-ratio: var(--plane-ratio); + margin: auto; +} +.panes[data-fit] .plane { + width: min(var(--plane-width), 100cqw, calc(100cqh * var(--plane-ratio))); +} +.art { + position: absolute; + inset: 0 auto auto 0; + max-width: none; + box-shadow: 0 0 0 1px var(--border-strong); + background-color: var(--bg-elev); + background-image: conic-gradient(var(--bg-hover) 25%, transparent 0 50%, var(--bg-hover) 0 75%, transparent 0); + background-size: 16px 16px; +} +.message { + margin: auto; + text-align: center; + overflow-wrap: anywhere; + color: var(--fg-muted); + font-size: var(--fs-small); +} diff --git a/src/features/vcs/ImageDiff.tsx b/src/features/vcs/ImageDiff.tsx new file mode 100644 index 000000000..9e1bb0ebb --- /dev/null +++ b/src/features/vcs/ImageDiff.tsx @@ -0,0 +1,260 @@ +import { useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react"; +import { useStore } from "zustand"; +import { onEditorEvent } from "@/editor/api"; +import { isSvgPath } from "@/features/viewers/fileKinds"; +import { useForwardFocus } from "@/features/viewers/forwardFocus"; +import { useT, useTx } from "@/platform/i18n"; +import { Button, IconButton, Select, T } from "@/ui"; +import { useEditorDocuments } from "@/workbench/contributions"; +import { emptyStagedStatus, stagedDiffPath, stagedDocumentAtPath } from "./stagedDocument"; +import { sideFile, sideLabel, type DiffData } from "./diffInput"; +import { loadImageFrames, type ImageFrame } from "./imageDiffFrames"; +import { canComparePixels, imageBounds, paintPixelDifference, type ImageSize } from "./imagePixels"; +import { useVcs } from "./store"; +import styles from "./ImageDiff.module.css"; + +function frameSize(frame: ImageFrame) { + return frame.kind === "ready" ? [frame.size] : []; +} + +function Pane({ label, detail, children }: { label: string; detail?: ReactNode; children: ReactNode }) { + return ( + <section className={styles.pane} aria-label={label}> + <div className={styles.heading}> + <strong title={label}>{label}</strong> + {detail && <span>{detail}</span>} + </div> + <div className={styles.surface} data-wheel-scroll> + {children} + </div> + </section> + ); +} + +function imageStyle(size: ImageSize, bounds: ImageSize): CSSProperties { + return { width: (100 * size.width) / bounds.width + "%", height: (100 * size.height) / bounds.height + "%" }; +} + +function PixelDifference({ before, after, bounds }: { before: ImageFrame; after: ImageFrame; bounds: ImageSize }) { + const tx = useTx(); + const t = useT(); + const canvas = useRef<HTMLCanvasElement>(null); + const [result, setResult] = useState<number | "error" | null>(null); + const extent = imageBounds([...frameSize(before), ...frameSize(after)]); + const empty = before.kind === "absent" && after.kind === "absent"; + const comparable = before.kind !== "error" && after.kind !== "error" && canComparePixels(extent); + useEffect(() => { + const mask = canvas.current; + if (!mask || !comparable) return; + try { + mask.width = extent.width; + mask.height = extent.height; + const ctx = mask.getContext("2d", { willReadFrequently: true }); + if (!ctx) throw new Error("Canvas unavailable"); + const pixels = (frame: ImageFrame) => { + if (frame.kind !== "ready") return null; + const { width, height } = frame.size; + ctx.clearRect(0, 0, width, height); + ctx.drawImage(frame.image, 0, 0); + return ctx.getImageData(0, 0, width, height); + }; + const left = pixels(before); + const right = pixels(after); + const out = ctx.createImageData(extent.width, extent.height); + const count = paintPixelDifference(left, right, out); + ctx.putImageData(out, 0, 0); + setResult(count); + } catch { + setResult("error"); + } + return () => { + mask.width = mask.height = 0; + }; + }, [before, after, comparable, extent.width, extent.height]); + const message = + before.kind === "error" || after.kind === "error" || result === "error" + ? tx("Pixel differences unavailable") + : empty + ? tx("No images to compare") + : !comparable + ? tx("Image dimensions exceed the pixel comparison limit") + : null; + const count = empty ? 0 : result; + return ( + <Pane + label={tx("Changed pixels")} + detail={<span role="status">{typeof count === "number" && t("vcs.imageDiff.changedPixels", { count })}</span>} + > + {message ? ( + <span className={styles.message}>{message}</span> + ) : ( + <div className={styles.plane}> + <canvas + ref={canvas} + role="img" + aria-label={tx("Pixel difference mask")} + className={styles.art} + style={imageStyle(extent, bounds)} + /> + </div> + )} + </Pane> + ); +} + +export function ImageDiff({ + data, + onSource, + toolbarActions, + forwardFocus = false, +}: { + data: DiffData; + onSource?: () => void; + toolbarActions?: ReactNode; + forwardFocus?: boolean; +}) { + const root = useRef<HTMLDivElement>(null); + useForwardFocus(root); + const tx = useTx(); + const { left, middle, right, path } = data; + const sides = useMemo(() => (middle ? [left, middle, right] : [left, right]), [left, middle, right]); + const immutable = sides.every( + (side) => side.type === "text" || (side.type === "rev" && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(side.rev)), + ); + const version = useVcs((s) => (immutable ? 0 : s.version)); + const stagedPath = stagedDiffPath(data); + const indexDoc = useEditorDocuments(() => + stagedPath && isSvgPath(stagedPath) ? stagedDocumentAtPath(stagedPath) : undefined, + ); + const stagedDraft = useStore(indexDoc?.status ?? emptyStagedStatus, (s) => + s.base && s.text !== s.base.text ? s.text : null, + ); + const [documentVersion, setDocumentVersion] = useState(0); + useEffect(() => { + const files = sides.map((side) => sideFile(side, path)); + if (!files.some(Boolean)) return; + return onEditorEvent((e) => { + if ((e.type === "docSaved" || (e.type === "docChanged" && isSvgPath(e.path))) && files.includes(e.path)) + setDocumentVersion((n) => n + 1); + }); + }, [path, sides]); + + const request = useMemo( + () => ({ path, sides, version, documentVersion, stagedDraft }), + [path, sides, version, documentVersion, stagedDraft], + ); + const [loaded, setLoaded] = useState<{ request: typeof request; frames: ImageFrame[] }>(); + useEffect(() => { + let cancelled = false; + void loadImageFrames(request.path, request.sides, () => cancelled).then((frames) => { + if (!cancelled) setLoaded({ request, frames }); + }); + return () => { + cancelled = true; + }; + }, [request]); + const frames = loaded?.request === request ? loaded.frames : undefined; + const labels = sides.map((side) => tx(sideLabel(side))); + const [highlight, setHighlight] = useState(false); + const [fit, setFit] = useState(true); + const [pair, setPair] = useState("0-1"); + const pairs: readonly (readonly [number, number])[] = middle + ? [ + [0, 1], + [1, 2], + [0, 2], + ] + : [[0, 1]]; + const selected = pairs.find((p) => p.join("-") === pair) ?? pairs[0]!; + const visible = highlight ? selected : sides.map((_, i) => i); + const bounds = imageBounds(visible.flatMap((i) => (frames?.[i] ? frameSize(frames[i]!) : []))); + const hasImage = frames?.some((frame) => frame.kind === "ready"); + + return ( + <div ref={forwardFocus ? root : undefined} tabIndex={-1} className={styles.root}> + <div role="toolbar" aria-label={tx("Image diff")} className={styles.toolbar}> + <Button + size="small" + variant="ghost" + aria-pressed={highlight} + disabled={!hasImage && !highlight} + onClick={() => { + setHighlight(!highlight); + if (!highlight) setFit(false); + }} + > + Highlight changed pixels + </Button> + {highlight && middle && ( + <Select + value={pair} + options={pairs.map(([a, b]) => ({ + value: [a, b].join("-"), + label: labels[a] + " ↔ " + labels[b], + verbatim: true, + }))} + aria-label="Compare revisions" + onChange={setPair} + /> + )} + <span className={styles.separator} /> + <IconButton icon="actual-size" size="small" title="Actual Size" pressed={!fit} onClick={() => setFit(false)} /> + <IconButton icon="maximize" size="small" title="Fit to Window" pressed={fit} onClick={() => setFit(true)} /> + {onSource && ( + <Button size="small" variant="ghost" onClick={onSource}> + View source diff + </Button> + )} + <div className={styles.actions}>{toolbarActions}</div> + </div> + <div + className={styles.panes} + data-fit={fit || undefined} + style={ + { + "--plane-width": (bounds.width || 1) + "px", + "--plane-ratio": (bounds.width || 1) / (bounds.height || 1), + } as CSSProperties + } + > + {visible.map((i) => { + const frame = frames?.[i]; + const dimensions = frame?.kind === "ready" && frame.intrinsic.width + " × " + frame.intrinsic.height; + return ( + <Pane key={i} label={labels[i]!} detail={dimensions}> + {frame?.kind === "ready" ? ( + <div className={styles.plane}> + <img + src={frame.image.src} + alt={labels[i]!} + draggable={false} + className={styles.art} + style={imageStyle(frame.size, bounds)} + /> + </div> + ) : ( + <span className={styles.message}> + {!frame ? ( + <T>Loading…</T> + ) : frame.kind === "absent" ? ( + <T>No image on this side</T> + ) : ( + tx`Cannot show the image: ${frame.error}` + )} + </span> + )} + </Pane> + ); + })} + {highlight && frames && hasImage && ( + <PixelDifference + key={selected.join("-")} + before={frames[selected[0]]!} + after={frames[selected[1]]!} + bounds={bounds} + /> + )} + </div> + </div> + ); +} diff --git a/src/features/vcs/ImageDiffHost.tsx b/src/features/vcs/ImageDiffHost.tsx new file mode 100644 index 000000000..842d57ed1 --- /dev/null +++ b/src/features/vcs/ImageDiffHost.tsx @@ -0,0 +1,133 @@ +import { useCallback, useEffect, useMemo, useRef } from "react"; +import clsx from "clsx"; +import { setContext } from "@/platform/context"; +import { shortcutLabel } from "@/platform/keymap"; +import { IconButton, isPopupOpen } from "@/ui"; +import { editorService } from "@/workbench/contributions"; +import type { DiffEditorProps } from "./DiffEditor"; +import { chainNeighbour, openDiff, sideFile, type DiffData } from "./diffInput"; +import { changedChainNeighbour } from "./diffNavigation"; +import { focusedDiffNavigator, setFocusedDiffNavigator, type DiffNavigator } from "./diffNavigator"; +import { loadDiffOptions } from "./diffOptions"; +import { ImageDiff } from "./ImageDiff"; +import styles from "./DiffEditor.module.css"; + +export function ImageDiffHost({ + data, + onSource, + onNeighbour, + skipUnchangedFiles = true, + onJumpToSource, + onClose, + toolbarActions, + fit, +}: Pick< + DiffEditorProps, + "onNeighbour" | "skipUnchangedFiles" | "onJumpToSource" | "onClose" | "toolbarActions" | "fit" +> & { + data: DiffData; + onSource?: () => void; +}) { + const request = useRef<object | null>(null); + const navigator = useMemo<DiffNavigator>(() => { + const file = async (dir: 1 | -1) => { + const id = {}; + request.current = id; + const next = skipUnchangedFiles + ? await changedChainNeighbour(data, dir, loadDiffOptions().ignore) + : chainNeighbour(data, dir); + if (!next || id !== request.current) return; + if (onNeighbour) onNeighbour(next); + else await openDiff(next, { preview: true }); + }; + return { + file, + next: () => void file(1), + prev: () => void file(-1), + close: () => { + onClose?.(); + return !!onClose; + }, + jumpToSource: () => { + const path = sideFile(data.right, data.path) ?? sideFile(data.left, data.path); + if (path) { + onJumpToSource?.(); + void editorService().openFile(path, { focus: true }); + } + }, + applyChange: () => false, + showSettings: () => {}, + focusOpposite: () => false, + swapSides: () => false, + showInExternalTool: () => false, + }; + }, [data, onClose, onJumpToSource, onNeighbour, skipUnchangedFiles]); + const blur = useCallback(() => { + if (focusedDiffNavigator() !== navigator) return; + setFocusedDiffNavigator(null); + setContext("diffEditorFocus", false); + }, [navigator]); + const root = useRef<HTMLDivElement>(null); + useEffect(() => { + if (root.current?.contains(document.activeElement)) { + setFocusedDiffNavigator(navigator); + setContext("diffEditorFocus", true); + } + return () => { + request.current = null; + blur(); + }; + }, [navigator, blur]); + return ( + <div + ref={root} + className={clsx(styles.root, fit && styles.fit)} + onFocusCapture={() => { + setFocusedDiffNavigator(navigator); + setContext("diffEditorFocus", true); + }} + onBlurCapture={(e) => { + if (!e.currentTarget.contains(e.relatedTarget as Node | null)) blur(); + }} + onKeyDown={(e) => { + if ( + e.key === "Escape" && + !e.defaultPrevented && + !e.altKey && + !e.ctrlKey && + !e.metaKey && + !e.shiftKey && + !e.nativeEvent.isComposing && + !isPopupOpen() && + navigator.close() + ) { + e.preventDefault(); + e.stopPropagation(); + } + }} + > + <ImageDiff + data={data} + forwardFocus={!fit && !data.embedded} + onSource={onSource} + toolbarActions={ + <> + {data.chain && + ([-1, 1] as const).map((dir) => ( + <IconButton + key={dir} + icon={dir === 1 ? "arrow-right" : "arrow-left"} + size="small" + title={dir === 1 ? "Compare Next File" : "Compare Previous File"} + shortcut={shortcutLabel(dir === 1 ? "diff.nextFile" : "diff.prevFile")} + disabled={!chainNeighbour(data, dir)} + onClick={() => navigator.file(dir)} + /> + ))} + {toolbarActions} + </> + } + /> + </div> + ); +} diff --git a/src/features/vcs/__tests__/ImageDiff.test.tsx b/src/features/vcs/__tests__/ImageDiff.test.tsx new file mode 100644 index 000000000..838bdf37a --- /dev/null +++ b/src/features/vcs/__tests__/ImageDiff.test.tsx @@ -0,0 +1,110 @@ +import { act, cleanup, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { _emitEditorEvent } from "@/editor/api"; +import { useProject } from "@/platform/project"; +import { commands } from "@/platform/ipc"; +import { stagedDocument, stagedDocumentLifecycle } from "../stagedDocument"; +import { ImageDiff } from "../ImageDiff"; +import type { DiffData } from "../diffInput"; +import { loadImageFrames, type ImageFrame } from "../imageDiffFrames"; +import { useVcs } from "../store"; + +vi.mock("../imageDiffFrames", () => ({ loadImageFrames: vi.fn() })); + +const data: DiffData = { path: "/x.svg", left: { type: "rev", rev: "HEAD" }, right: { type: "worktree" } }; +afterEach(() => { + cleanup(); + vi.resetAllMocks(); +}); + +it("discards a late read after a diff switch and refreshes on a matching save or repository change", async () => { + let finish!: (frames: ImageFrame[]) => void; + const loader = vi.mocked(loadImageFrames); + loader.mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + loader.mockResolvedValue([{ kind: "absent" }, { kind: "error", error: "current failure" }]); + const { rerender } = render(<ImageDiff data={data} />); + const updated = { ...data, path: "/y.svg" }; + rerender(<ImageDiff data={updated} />); + expect(await screen.findByText("No image on this side")).toBeVisible(); + expect(screen.getByText(/current failure/)).toBeVisible(); + await act(async () => finish([{ kind: "error", error: "old failure" }, { kind: "absent" }])); + expect(screen.queryByText(/old failure/)).toBeNull(); + expect(loader.mock.calls[0]![2]()).toBe(true); + + act(() => _emitEditorEvent({ type: "docSaved", doc: 7, path: "/x.svg" })); + expect(loader).toHaveBeenCalledTimes(2); + act(() => _emitEditorEvent({ type: "docSaved", doc: 8, path: "/y.svg" })); + await waitFor(() => expect(loader).toHaveBeenCalledTimes(3)); + act(() => useVcs.setState((s) => ({ version: s.version + 1 }))); + await waitFor(() => expect(loader).toHaveBeenCalledTimes(4)); +}); + +it("keeps immutable historical images loaded when the repository refreshes", async () => { + const loader = vi.mocked(loadImageFrames).mockResolvedValue([{ kind: "absent" }, { kind: "absent" }]); + render( + <ImageDiff + data={{ + ...data, + left: { type: "rev", rev: "a".repeat(40) }, + right: { type: "rev", rev: "b".repeat(64) }, + }} + />, + ); + expect(await screen.findAllByText("No image on this side")).toHaveLength(2); + act(() => useVcs.setState((s) => ({ version: s.version + 1 }))); + expect(loader).toHaveBeenCalledTimes(1); +}); + +it("hands the editor host's focus to the image viewer for file navigation", async () => { + vi.mocked(loadImageFrames).mockResolvedValue([{ kind: "absent" }, { kind: "absent" }]); + const { container } = render( + <div data-editor-focus tabIndex={-1}> + <ImageDiff data={data} forwardFocus /> + </div>, + ); + const host = container.firstElementChild as HTMLElement; + host.focus(); + expect(host.firstElementChild).toHaveFocus(); + await screen.findAllByText("No image on this side"); +}); + +it("refreshes when the working SVG has unsaved edits", async () => { + const loader = vi.mocked(loadImageFrames).mockResolvedValue([{ kind: "absent" }, { kind: "absent" }]); + render(<ImageDiff data={data} />); + await screen.findAllByText("No image on this side"); + act(() => _emitEditorEvent({ type: "docChanged", doc: 1, path: data.path, baseVersion: 1, version: 2, changes: [] })); + await waitFor(() => expect(loader).toHaveBeenCalledTimes(2)); +}); + +it("refreshes for successive edits in an SVG staging editor opened after the image diff", async () => { + const loader = vi.mocked(loadImageFrames).mockResolvedValue([{ kind: "absent" }, { kind: "absent" }]); + const project = useProject.getState().project; + useProject.setState({ project: { root: "/r" } as never }); + const path = "/r/staged.svg"; + render(<ImageDiff data={{ path, left: data.left, right: { type: "rev", rev: ":0" } }} />); + await screen.findAllByText("No image on this side"); + const snapshot = vi + .spyOn(commands, "vcsStagedText") + .mockResolvedValue({ status: "ok", data: { text: "clean", version: "v1" } }); + const doc = stagedDocument(path, "image-test")!; + try { + await act(async () => { + await doc.reload(); + doc.edit({ from: 0, to: 5, insert: "draft" }); + }); + await waitFor(() => expect(loader).toHaveBeenCalledTimes(2)); + act(() => doc.edit({ from: 5, insert: " again" })); + await waitFor(() => expect(loader).toHaveBeenCalledTimes(3)); + } finally { + cleanup(); + doc.discard(); + snapshot.mockRestore(); + await stagedDocumentLifecycle().close({ key: "image-test", kind: "diff" }); + useProject.setState({ project }); + } +}); diff --git a/src/features/vcs/__tests__/blame.test.tsx b/src/features/vcs/__tests__/blame.test.tsx index 38a6f801d..85c00f01f 100644 --- a/src/features/vcs/__tests__/blame.test.tsx +++ b/src/features/vcs/__tests__/blame.test.tsx @@ -276,6 +276,27 @@ describe("annotate Options", () => { const hidden = (v: EditorView) => ["date", "author", "revision"].filter((c) => v.dom.classList.contains(`cm-vcs-blame-hide-${c}`)); + it("prints Today/Yesterday in the date cell when pretty formatting is on", async () => { + const today = Date.now(); + const yesterday = today - 86_400_000; + const recentLines: BlameLine[] = [ + { commit: sha, author: "Aleks Zlateski", timeMs: today, summary: "today" }, + { commit: otherSha, author: "Dan Crankshaw", timeMs: yesterday, summary: "yesterday" }, + ]; + mocks.blame.mockResolvedValue({ status: "ok", data: recentLines }); + useProject.setState({ settings: { general: { dateFormat: { pretty: true } } } }); + const created = new EditorView({ + parent: document.body, + state: EditorState.create({ doc: "first\nsecond\nthird", extensions: [blameSlot()] }), + }); + view = created; + await toggleAnnotations(created, "/repo/src/main.py"); + const cell = (commit: string) => + created.dom.querySelector<HTMLElement>(`.cm-vcs-blame [data-commit="${commit}"] .cm-vcs-blame-date`)?.textContent; + expect(cell(sha)).toBe("Today"); + expect(cell(otherSha)).toBe("Yesterday"); + }); + it("shows date and author by default and adds the revision from Options", async () => { view = await annotated(); expect( diff --git a/src/features/vcs/__tests__/branchFilterPopup.test.tsx b/src/features/vcs/__tests__/branchFilterPopup.test.tsx index 31d852d0e..d239f1938 100644 --- a/src/features/vcs/__tests__/branchFilterPopup.test.tsx +++ b/src/features/vcs/__tests__/branchFilterPopup.test.tsx @@ -1,4 +1,4 @@ -import { fireEvent, render, screen } from "@testing-library/react"; +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { Branch } from "@/bindings"; import { BranchFilterPopup } from "../BranchFilterPopup"; @@ -33,6 +33,8 @@ const rowTexts = () => screen.getAllByRole("option").map((o) => o.textContent); afterEach(() => { localStorage.clear(); useFavoriteBranches.setState({ key: "", names: null }); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); }); describe("branch filter popup", () => { @@ -93,4 +95,37 @@ describe("branch filter popup", () => { fireEvent.change(input, { target: { value: "missing" } }); expect(screen.getByText("No matching branches")).toBeTruthy(); }); + + it("grows an opened group down to the window's bottom edge, keeping the usual limit with less room", () => { + const many = [branch("main", { current: true }), ...Array.from({ length: 40 }, (_, i) => branch(`feature-${i}`))]; + const list = () => screen.getByRole("listbox", { name: "Branches" }).parentElement!; + // No layout in jsdom: a 1000 px window, and a popup 80 px taller than its list. + vi.stubGlobal("innerHeight", 1000); + vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockImplementation(function (this: HTMLElement) { + return this.hasAttribute("data-popup") ? 80 + parseFloat(list().style.height) : 0; + }); + const open = (anchorBottom: number) => { + const anchor = document.createElement("button"); + anchor.getBoundingClientRect = () => ({ bottom: anchorBottom }) as DOMRect; + const view = render( + <BranchFilterPopup + anchor={anchor} + branches={many} + selected={[]} + onSelect={vi.fn()} + onSelectMany={vi.fn()} + onClose={vi.fn()} + />, + ); + fireEvent.click(screen.getByText("Local")); + return view; + }; + + // 1000 - 100 (anchor) - 10 (popup margins) - 80 (search, padding, Select…) leaves 810 px. + open(100); + expect(list().style.height).toBe("810px"); + cleanup(); + open(700); + expect(list().style.height).toBe("320px"); + }); }); diff --git a/src/features/vcs/__tests__/diffNavigation.test.ts b/src/features/vcs/__tests__/diffNavigation.test.ts index ca220ef9a..cefa5cd25 100644 --- a/src/features/vcs/__tests__/diffNavigation.test.ts +++ b/src/features/vcs/__tests__/diffNavigation.test.ts @@ -69,3 +69,15 @@ it("normalizes line endings like the viewer when skipping unchanged files", asyn const data = withChain([diff("a"), crlf, diff("z")], 0); expect(await changedChainNeighbour(data, 1, "none")).toMatchObject({ path: "/repo/z" }); }); + +it("stops at a changed Git image before trying to decode its bytes as text", async () => { + const image: DiffData = { + path: "/repo/badge.PNG", + left: { type: "rev", rev: "HEAD" }, + right: { type: "worktree" }, + }; + probe.mockResolvedValue({ status: "ok", data: { binary: true, tooLarge: false } }); + const chain = withChain([diff("a"), image, diff("z")], 0); + expect(await changedChainNeighbour(chain, 1, "none")).toMatchObject({ path: image.path }); + expect(probe).not.toHaveBeenCalled(); +}); diff --git a/src/features/vcs/__tests__/imageDiffFrames.test.ts b/src/features/vcs/__tests__/imageDiffFrames.test.ts new file mode 100644 index 000000000..c3d6c211a --- /dev/null +++ b/src/features/vcs/__tests__/imageDiffFrames.test.ts @@ -0,0 +1,50 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { loadImageFrames, svgAtViewport, svgIntrinsicSize } from "../imageDiffFrames"; +import { readImageSide } from "../imageDiffInput"; +import { imageBounds } from "../imagePixels"; + +vi.mock("../imageDiffInput", () => ({ readImageSide: vi.fn() })); +afterEach(() => vi.resetAllMocks()); + +function svg(attrs: string) { + const doc = new DOMParser().parseFromString( + '<svg xmlns="http://www.w3.org/2000/svg" ' + attrs + '><rect width="1" height="2"/></svg>', + "image/svg+xml", + ); + return doc.documentElement as unknown as SVGSVGElement; +} + +describe("SVG diff viewport", () => { + it("resolves absolute units and preserves the viewBox ratio if one side is implicit", () => { + expect(svgIntrinsicSize(svg('width="1in" viewBox="10 8 12 6"'))).toEqual({ width: 96, height: 48 }); + expect(svgIntrinsicSize(svg('viewBox="10 8 12 6"'))).toEqual({ width: 12, height: 6 }); + expect(svgIntrinsicSize(svg('width="100%" height="100%"'))).toEqual({ width: 300, height: 150 }); + }); + + it("sets both layout viewports before rendering and leaves each drawing's own coordinates intact", () => { + const a = svg('width="12" height="8" viewBox="0 0 6 4" preserveAspectRatio="none"'); + const b = svg('style="width: 16px; height: 3px" viewBox="0 0 6 4" preserveAspectRatio="none"'); + const viewport = imageBounds([svgIntrinsicSize(a), svgIntrinsicSize(b)]); + for (const revision of [a, b]) { + const url = svgAtViewport(revision, viewport); + const rendered = new DOMParser().parseFromString( + decodeURIComponent(url.split(",")[1]!), + "image/svg+xml", + ).documentElement; + expect(rendered.getAttribute("width")).toBe("16"); + expect(rendered.getAttribute("height")).toBe("8"); + expect(rendered.getAttribute("viewBox")).toBe("0 0 6 4"); + expect(rendered.getAttribute("preserveAspectRatio")).toBe("none"); + expect(rendered.firstElementChild?.getAttribute("width")).toBe("1"); + } + }); + + it("distinguishes missing and invalid images, and discards reads from a superseded comparison", async () => { + vi.mocked(readImageSide).mockResolvedValueOnce(null).mockResolvedValueOnce("data:image/svg+xml,%3Cbroken"); + const sides = [{ type: "worktree" }, { type: "rev", rev: "HEAD" }] as const; + const loaded = await loadImageFrames("x.svg", [...sides], () => false); + expect(loaded.map((s) => s.kind)).toEqual(["absent", "error"]); + vi.mocked(readImageSide).mockResolvedValue("data:image/svg+xml,%3Cbroken"); + expect(await loadImageFrames("x.svg", [...sides], () => true)).toEqual([]); + }); +}); diff --git a/src/features/vcs/__tests__/imageDiffHost.test.tsx b/src/features/vcs/__tests__/imageDiffHost.test.tsx new file mode 100644 index 000000000..cb87bbea1 --- /dev/null +++ b/src/features/vcs/__tests__/imageDiffHost.test.tsx @@ -0,0 +1,28 @@ +import { act, cleanup, render, waitFor } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { getContext } from "@/platform/context"; +import { withChain, type DiffData } from "../diffInput"; +import { focusedDiffNavigator } from "../diffNavigator"; +import { ImageDiffHost } from "../ImageDiffHost"; + +vi.mock("../imageDiffFrames", () => ({ loadImageFrames: async () => [{ kind: "absent" }, { kind: "absent" }] })); +afterEach(cleanup); + +it("navigates from the focused image past an unchanged text file and drops the navigator on close", async () => { + const image: DiffData = { path: "badge.png", left: { type: "rev", rev: "HEAD" }, right: { type: "worktree" } }; + const text = (path: string, after: string): DiffData => ({ + path, + left: { type: "text", label: "Before", text: "a" }, + right: { type: "text", label: "After", text: after }, + }); + const data = withChain([image, text("readme", "a"), text("license", "b")], 0); + const onNeighbour = vi.fn(); + const viewer = render(<ImageDiffHost data={data} onNeighbour={onNeighbour} />); + act(() => viewer.getByRole("button", { name: "Compare Next File" }).focus()); + expect(getContext().diffEditorFocus).toBe(true); + act(() => focusedDiffNavigator()!.file(1)); + await waitFor(() => expect(onNeighbour).toHaveBeenCalledWith(expect.objectContaining({ path: "license" }))); + viewer.unmount(); + expect(focusedDiffNavigator()).toBeNull(); + expect(getContext().diffEditorFocus).toBe(false); +}); diff --git a/src/features/vcs/__tests__/imageDiffInput.test.ts b/src/features/vcs/__tests__/imageDiffInput.test.ts new file mode 100644 index 000000000..c81a9444c --- /dev/null +++ b/src/features/vcs/__tests__/imageDiffInput.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it, vi } from "vitest"; +import { _provideDocumentAttacher } from "@/editor/api"; +import { createMemoryBackend } from "@/editor/core/backend"; +import { attachDocument } from "@/editor/core/model/attachment"; +import { DocumentManager } from "@/editor/core/model/document"; +import { useProject } from "@/platform/project"; +import { stagedDocument, stagedDocumentLifecycle } from "../stagedDocument"; +import type { DiffData } from "../diffInput"; +import { imageDiffKind, readImageSide } from "../imageDiffInput"; + +const { vcsImageAt, fsReadImage } = vi.hoisted(() => ({ + vcsImageAt: vi.fn(async () => ({ status: "ok", data: "revision" })), + fsReadImage: vi.fn(async () => ({ status: "ok", data: "working tree" })), +})); +vi.mock("@/platform/ipc", async (original) => ({ + ...(await original<typeof import("@/platform/ipc")>()), + commands: { + vcsImageAt, + fsReadImage, + vcsStagedText: async () => ({ status: "ok", data: { text: "clean", version: "v1" } }), + }, +})); + +const change = (path: string): DiffData => ({ path, left: { type: "rev", rev: "HEAD" }, right: { type: "worktree" } }); + +describe("Git image diff input", () => { + it.each(["png", "JPG", "jpeg", "WeBp", "svg"])("supports .%s", (extension) => { + expect(imageDiffKind(change("icon." + extension))).toBe(extension === "svg" ? "svg" : "raster"); + }); + + it("keeps other binary files, line ranges and inline text diffs in the original viewer", () => { + expect(imageDiffKind(change("movie.mp4"))).toBeNull(); + expect(imageDiffKind({ ...change("icon.svg"), line: 12 })).toBeNull(); + expect(imageDiffKind({ ...change("icon.png"), left: { type: "text", label: "patch", text: "patch" } })).toBeNull(); + }); + + it("labels a mixed image-format rename as raster and ignores an absent side's extension", () => { + const data = change("new.svg"); + expect(imageDiffKind({ ...data, left: { type: "rev", rev: "HEAD", path: "old.png" } })).toBe("raster"); + expect(imageDiffKind({ ...data, left: { type: "text", label: "missing", text: "", absent: true } })).toBe("svg"); + }); + + it("loads the renamed revision and index by their individual paths, and reads the working file from disk", async () => { + const path = "/r/new.png"; + expect(await readImageSide(path, { type: "rev", rev: "HEAD", path: "/r/old.png" })).toBe("revision"); + expect(vcsImageAt).toHaveBeenCalledWith("/r/old.png", "HEAD"); + await readImageSide(path, { type: "rev", rev: ":0" }); + expect(vcsImageAt).toHaveBeenCalledWith(path, ":0"); + expect(await readImageSide(path, { type: "worktree" })).toBe("working tree"); + expect(fsReadImage).toHaveBeenCalledWith(path); + expect(await readImageSide(path, { type: "text", text: "", label: "missing", absent: true })).toBeNull(); + }); + + it("reads an unsaved SVG even after its text editor unmounts", async () => { + const path = "/r/inactive.svg"; + const backend = createMemoryBackend({ [path]: "<svg/>" }); + const manager = new DocumentManager(backend, { settings: () => ({ files: { autoSave: false } }), notify: vi.fn() }); + manager.start(); + _provideDocumentAttacher((file) => attachDocument(manager, file)); + try { + const source = await attachDocument(manager, path); + source.edit({ from: 4, insert: ' id="draft"' }); + await source.synced(); + source.release(); + const url = await readImageSide(path, { type: "worktree" }); + expect(decodeURIComponent(url!)).toContain('<svg id="draft"/>'); + expect(backend.files.get(path)).toBe("<svg/>"); + } finally { + _provideDocumentAttacher(null); + manager.releaseProjectDocuments(); + manager.stop(); + } + }); + + it("uses a dirty SVG index draft only on its matching index side", async () => { + const path = "/r/new.svg"; + const old = "/r/old.svg"; + const project = useProject.getState().project; + useProject.setState({ project: { root: "/r" } as never }); + const doc = stagedDocument(old, "image-test")!; + try { + await doc.reload(); + doc.edit({ from: 0, to: 5, insert: "<svg/>" }); + expect(decodeURIComponent((await readImageSide(path, { type: "rev", rev: ":0", path: old }))!)).toContain( + "<svg/>", + ); + expect(await readImageSide(path, { type: "rev", rev: "HEAD", path: old })).toBe("revision"); + expect(await readImageSide(path, { type: "rev", rev: ":0" })).toBe("revision"); + } finally { + doc.discard(); + await stagedDocumentLifecycle().close({ key: "image-test", kind: "diff" }); + useProject.setState({ project }); + } + }); +}); diff --git a/src/features/vcs/__tests__/imagePixels.test.ts b/src/features/vcs/__tests__/imagePixels.test.ts new file mode 100644 index 000000000..d0853af88 --- /dev/null +++ b/src/features/vcs/__tests__/imagePixels.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from "vitest"; +import { canComparePixels, imageBounds, paintPixelDifference, type PixelImage } from "../imagePixels"; + +function pixels(width: number, height: number, rgba?: number[]): PixelImage { + const data = new Uint8ClampedArray(width * height * 4); + if (rgba) data.set(rgba); + return { width, height, data }; +} + +describe("image pixel differences", () => { + it("compares decoded RGBA, including a one-step opacity change", () => { + const before = pixels(2, 1, [10, 40, 80, 255, 13, 13, 13, 250]); + const after = pixels(2, 1, [...before.data]); + const mask = pixels(2, 1); + expect(paintPixelDifference(before, after, mask)).toBe(0); + expect(mask.data[0]).toBe(mask.data[1]); + expect(mask.data[1]).toBe(mask.data[2]); + expect(mask.data[3]).toBe(255); + expect(mask.data[7]).toBe(250); + after.data[7] = 249; + expect(paintPixelDifference(before, after, mask)).toBe(1); + expect(mask.data[7]).toBe(255); + after.data[0] = 11; + expect(paintPixelDifference(before, after, mask)).toBe(2); + }); + + it("keeps a crop at its original coordinates and counts transparent edge pixels", () => { + const before = pixels(3, 2); + const after = pixels(2, 2); + const mask = pixels(3, 2); + expect(paintPixelDifference(before, after, mask)).toBe(2); + expect([...mask.data].filter((_, i) => i % 4 === 3)).toEqual([0, 0, 255, 0, 0, 255]); + }); + + it("excludes the corner outside both images and handles an absent side", () => { + const wide = pixels(3, 1); + const tall = pixels(1, 2); + const mask = pixels(3, 2); + expect(paintPixelDifference(wide, tall, mask)).toBe(3); + expect([...mask.data].filter((_, i) => i % 4 === 3)).toEqual([0, 255, 255, 255, 0, 0]); + expect(paintPixelDifference(null, wide, pixels(3, 1))).toBe(3); + expect(paintPixelDifference(tall, null, pixels(1, 2))).toBe(2); + }); + + it("uses one enclosing viewport regardless of revision order and bounds allocations", () => { + const a = { width: 8000, height: 20 }; + const b = { width: 13, height: 7000 }; + expect(imageBounds([a, b])).toEqual({ width: 8000, height: 7000 }); + expect(imageBounds([a, b])).toEqual(imageBounds([b, a])); + expect(canComparePixels(a)).toBe(true); + expect(canComparePixels(imageBounds([a, b]))).toBe(false); + expect(canComparePixels({ width: 16385, height: 1 })).toBe(false); + expect(canComparePixels(imageBounds([]))).toBe(false); + }); +}); diff --git a/src/features/vcs/__tests__/imageSourceToggle.test.tsx b/src/features/vcs/__tests__/imageSourceToggle.test.tsx new file mode 100644 index 000000000..61db82515 --- /dev/null +++ b/src/features/vcs/__tests__/imageSourceToggle.test.tsx @@ -0,0 +1,38 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import type { ReactNode } from "react"; +import { ResolvedDiffEditor } from "../DiffEditor"; +import { diffInput, type DiffData } from "../diffInput"; + +vi.mock("../ImageDiffHost", () => ({ + ImageDiffHost: ({ onSource }: { onSource: () => void }) => <button onClick={onSource}>View source diff</button>, +})); +vi.mock("../StagingDiff", () => ({ + StagingDiff: ({ toolbarActions }: { toolbarActions: ReactNode }) => ( + <> + {toolbarActions} + <textarea aria-label="index" /> + </> + ), +})); +afterEach(cleanup); + +it("keeps the SVG source editor and its pending index edits alive while previewing the image", () => { + const data: DiffData = { + path: "/repo/icon.svg", + left: { type: "rev", rev: "HEAD" }, + middle: { type: "rev", rev: ":0" }, + right: { type: "worktree" }, + }; + render( + <ResolvedDiffEditor input={diffInput(data)} diff={{ data, entries: null, versions: undefined, loading: false }} />, + ); + fireEvent.click(screen.getByRole("button", { name: "View source diff" })); + const index = screen.getByRole("textbox", { name: "index" }); + fireEvent.change(index, { target: { value: "<svg/>" } }); + fireEvent.click(screen.getByRole("button", { name: "Image preview" })); + expect(index).toBeInTheDocument(); + expect(index).not.toBeVisible(); + fireEvent.click(screen.getByRole("button", { name: "View source diff" })); + expect(screen.getByRole("textbox", { name: "index" })).toHaveValue("<svg/>"); +}); diff --git a/src/features/vcs/__tests__/logBranches.test.tsx b/src/features/vcs/__tests__/logBranches.test.tsx index 7d4cb5a80..32f9daafc 100644 --- a/src/features/vcs/__tests__/logBranches.test.tsx +++ b/src/features/vcs/__tests__/logBranches.test.tsx @@ -1,8 +1,12 @@ -import type { Branch, BranchInfo } from "@/bindings"; +import type { Branch, BranchInfo, LogQuery } from "@/bindings"; import { isMacHost } from "@/platform/keymap"; import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +const vcsLog = vi.hoisted(() => + vi.fn((_repo: string | null, _query: LogQuery) => Promise.resolve({ status: "ok" as const, data: [] })), +); + const repoData = vi.hoisted(() => ({ branches: {} as Record<string, unknown[]>, tags: {} as Record<string, string[]>, @@ -15,7 +19,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => { ...real.commands, vcsBranches: (root: string) => Promise.resolve({ status: "ok", data: repoData.branches[root] ?? [] }), vcsTags: (root: string) => Promise.resolve({ status: "ok", data: repoData.tags[root] ?? [] }), - vcsLog: () => Promise.resolve({ status: "ok", data: [] }), + vcsLog, vcsConfigGet: () => Promise.resolve({ status: "ok", data: null }), }, }; @@ -30,6 +34,7 @@ vi.mock("@/platform/actions", async (importOriginal) => ({ import { ContextMenuHost } from "@/ui"; import syncStyles from "../BranchSync.module.css"; import { BranchesPanel } from "../log/BranchesPanel"; +import { FilterBar } from "../log/FilterBar"; import { useBranchesPane } from "../logPaneActions"; import { emptyFilters, useGitLog } from "../logStore"; import { useVcs } from "../store"; @@ -63,6 +68,7 @@ const cmd = () => (isMacHost() ? { metaKey: true } : { ctrlKey: true }); beforeEach(() => { writeText.mockClear(); + vcsLog.mockClear(); Object.defineProperty(navigator, "clipboard", { value: { writeText }, configurable: true }); useVcs.setState({ root: "/p", repo: "/p", branches, branchesLoaded: true, branch: head }); useGitLog.setState({ filters: emptyFilters() }); @@ -328,6 +334,78 @@ describe("Git Log branches pane with several repositories", () => { expect(screen.getAllByText("dev")).toHaveLength(2); }); + it("shows commits only from the repository of the activated branch when both have it", async () => { + render(<BranchesPanel />); + await screen.findByText("solo"); + fireEvent.click(screen.getByRole("button", { name: "Group by Repository" })); + const [mainInA] = screen.getAllByText("main"); + fireEvent.doubleClick(mainInA!); + + await waitFor(() => expect(vcsLog).toHaveBeenCalled()); + expect(vcsLog.mock.calls.map(([repo, query]) => [repo, query.branches])).toEqual([["/p/a", ["main"]]]); + expect(screen.getByText("other")).toBeInTheDocument(); + }); + + it("restores both repositories when the scoped branch filter is cleared", async () => { + render( + <> + <FilterBar /> + <BranchesPanel /> + </>, + ); + await screen.findByText("solo"); + fireEvent.click(screen.getByRole("button", { name: "Group by Repository" })); + fireEvent.doubleClick(screen.getAllByText("main")[0]!); + await waitFor(() => expect(vcsLog).toHaveBeenCalled()); + vcsLog.mockClear(); + + fireEvent.click(screen.getByRole("button", { name: "Clear Branch filter" })); + + await waitFor(() => expect(vcsLog).toHaveBeenCalledTimes(2)); + expect(vcsLog.mock.calls.map(([repo, query]) => [repo, query.branches])).toEqual([ + ["/p/a", []], + ["/p/b", []], + ]); + }); + + it("keeps the Paths filter when activating and clearing a repository branch", async () => { + useGitLog.setState({ filters: { ...emptyFilters(), paths: ["/p/a/src", "/p/b/test"] } }); + render( + <> + <FilterBar /> + <BranchesPanel /> + </>, + ); + await screen.findByText("solo"); + fireEvent.click(screen.getByRole("button", { name: "Group by Repository" })); + fireEvent.doubleClick(screen.getAllByText("main")[0]!); + + await waitFor(() => expect(vcsLog).toHaveBeenCalled()); + expect(vcsLog.mock.calls.map(([repo, query]) => [repo, query.paths])).toEqual([["/p/a", ["/p/a/src"]]]); + vcsLog.mockClear(); + fireEvent.click(screen.getByRole("button", { name: "Clear Branch filter" })); + await waitFor(() => expect(vcsLog).toHaveBeenCalledTimes(2)); + expect(vcsLog.mock.calls.map(([repo, query]) => [repo, query.paths])).toEqual([ + ["/p/a", ["/p/a/src"]], + ["/p/b", ["/p/b/test"]], + ]); + }); + + it("queries only the selected branch in each repository when several are selected", async () => { + render(<BranchesPanel />); + await screen.findByText("solo"); + fireEvent.click(screen.getByRole("button", { name: "Group by Repository" })); + fireEvent.mouseDown(screen.getAllByText("main")[0]!); + fireEvent.mouseDown(screen.getAllByText("dev")[1]!, cmd()); + fireEvent.keyDown(screen.getByRole("tree", { name: "Branches" }), { key: "Enter" }); + + await waitFor(() => expect(vcsLog).toHaveBeenCalledTimes(2)); + expect(vcsLog.mock.calls.map(([repo, query]) => [repo, query.branches])).toEqual([ + ["/p/a", ["main"]], + ["/p/b", ["dev"]], + ]); + }); + it("keeps a repository filter chosen elsewhere when a branch is double-clicked", async () => { act(() => useGitLog.setState({ filters: { ...emptyFilters(), repositories: ["/p/b"] } })); render(<BranchesPanel />); diff --git a/src/features/vcs/__tests__/repoBranches.test.ts b/src/features/vcs/__tests__/repoBranches.test.ts index 3c3ff37a9..96ab4e9f5 100644 --- a/src/features/vcs/__tests__/repoBranches.test.ts +++ b/src/features/vcs/__tests__/repoBranches.test.ts @@ -160,6 +160,15 @@ describe("buildMultiRepoRows", () => { ]); }); + it("lists the current repository first, keeping the others' order and colours", () => { + const rows = summary(buildMultiRepoRows({ ...input, current: "/p/ology-gateway", query: "" })); + expect(rows.filter((r) => r.startsWith("repo"))).toEqual([ + "repo ology-gateway [dev] c3", + "repo ology-collect [dev] c1", + "repo ology-dependencies [dev] c2", + ]); + }); + it("groups common remote branches by remote when expanded", () => { const expanded = new Map([ ["common:local", false], diff --git a/src/features/vcs/__tests__/updateBranches.test.ts b/src/features/vcs/__tests__/updateBranches.test.ts index 489e295f9..9c59093c9 100644 --- a/src/features/vcs/__tests__/updateBranches.test.ts +++ b/src/features/vcs/__tests__/updateBranches.test.ts @@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({ update: vi.fn(), updateCurrent: vi.fn(), head: vi.fn(), + checkout: vi.fn(), notify: vi.fn(), openWorktree: vi.fn(), })); @@ -22,7 +23,7 @@ vi.mock("../ops", async (original) => ({ vi.mock("../openWorktree", () => ({ openWorktree: mocks.openWorktree })); vi.mock("@/platform/ipc", async (original) => { const real = await original<typeof import("@/platform/ipc")>(); - return { ...real, commands: { ...real.commands, vcsBranchInfo: mocks.head } }; + return { ...real, commands: { ...real.commands, vcsBranchInfo: mocks.head, vcsCheckout: mocks.checkout } }; }); vi.mock("@/workbench/contributions", async (original) => ({ ...(await original<typeof import("@/workbench/contributions")>()), @@ -30,7 +31,7 @@ vi.mock("@/workbench/contributions", async (original) => ({ })); import { branchMenu, commonBranchMenu } from "../branchMenu"; -import { branchUpdateSummary, updateBranches } from "../branchOps"; +import { branchUpdateSummary, checkoutAndUpdate, updateBranches } from "../branchOps"; import { getAction } from "@/platform/actions"; import { useProject } from "@/platform/project"; import type { Settings } from "@/bindings"; @@ -209,3 +210,38 @@ describe("branch common to several repositories", () => { ]); }); }); + +describe("Checkout and Update", () => { + const item = (items: ReturnType<typeof branchMenu>) => + items.find((i) => "label" in i && i.label === "Checkout and Update") as { disabled?: boolean } | undefined; + + it("is offered for a local branch that is not checked out, and needs a tracked branch", () => { + expect(item(branchMenu(branch("topic"), "main"))?.disabled).toBe(false); + expect(item(branchMenu(branch("topic", { upstream: null }), "main"))?.disabled).toBe(true); + expect(item(branchMenu(branch("origin/topic", { remote: true, upstream: null }), "main"))).toBeUndefined(); + expect(item(branchMenu(branch("main", { current: true }), "main"))).toBeUndefined(); + const common = { name: "feature", remote: false, current: false, favorite: false, upstream: true }; + expect(item(commonBranchMenu(common, ["/p", "/p/lib"], null))?.disabled).toBe(false); + }); + + it("checks the branch out, then pulls it with the configured method", async () => { + let head = "main"; + mocks.checkout.mockImplementation(async () => { + head = "topic"; + return { status: "ok", data: { kind: "done" } }; + }); + mocks.head.mockImplementation(async () => ({ status: "ok", data: { head, upstream: `origin/${head}` } })); + await checkoutAndUpdate(branch("topic")); + expect(mocks.checkout).toHaveBeenCalledTimes(1); + expect(mocks.updateCurrent).toHaveBeenCalledWith([ + { repo: "/p", op: { op: "pull", expectedBranch: "topic", rebase: false } }, + ]); + }); + + it("updates nothing when the checkout did not happen", async () => { + mocks.checkout.mockResolvedValue({ status: "error", error: { kind: "failed", message: "nope" } }); + await checkoutAndUpdate(branch("topic")); + expect(mocks.updateCurrent).not.toHaveBeenCalled(); + expect(mocks.update).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/vcs/blame.ts b/src/features/vcs/blame.ts index 0599d4066..696c47f09 100644 --- a/src/features/vcs/blame.ts +++ b/src/features/vcs/blame.ts @@ -11,7 +11,7 @@ import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowS import { showContextMenu, type MenuItem } from "@/ui"; import { notifications } from "@/workbench/contributions"; import { closeBlamePopup, scheduleCloseBlamePopup, scheduleOpenBlamePopup } from "./BlamePopup"; -import { formatDate } from "./model"; +import { formatPrettyDay } from "@/platform/dateFormat"; import { saveVcsSetting } from "./settingsUi"; import { useVcs } from "./store"; @@ -318,7 +318,7 @@ function build(lines: BlameLine[], doc: Text): BlameState { let label = labels.get(line.commit); if (!label && !isUncommitted(line)) { label = { - date: formatDate(line.timeMs), + date: line.timeMs ? formatPrettyDay(line.timeMs) : "", author: shortAuthorName(line.author, names), revision: line.commit.slice(0, 8), }; diff --git a/src/features/vcs/branchMenu.ts b/src/features/vcs/branchMenu.ts index 9b0b07fed..3723ec3ca 100644 --- a/src/features/vcs/branchMenu.ts +++ b/src/features/vcs/branchMenu.ts @@ -5,6 +5,7 @@ import { showContextMenu, useContextMenuStore, type MenuItem } from "@/ui"; import { isFavoriteBranch } from "./branches"; import { branchRef, + checkoutAndUpdate, checkoutBranch, checkoutDetached, checkoutInRepos, @@ -158,6 +159,15 @@ export function branchMenu( } const items: MenuItem[] = [ { label: "Checkout", run: run(() => checkoutBranch(b)) }, + ...(b.remote + ? [] + : [ + { + label: "Checkout and Update", + disabled: !b.upstream || updating || !!existingWorktree, + run: run(() => checkoutAndUpdate(b)), + }, + ]), ...(existingWorktree && !b.remote ? [{ label: "Open Existing Worktree", icon: "folder", run: run(() => openWorktree(existingWorktree, true)) }] : []), @@ -327,6 +337,15 @@ export function commonBranchMenu( const base = bases[0]; const items: MenuItem[] = [ { label: "Checkout", run: run(() => checkoutInRepos(b, roots)) }, + ...(b.remote + ? [] + : [ + { + label: "Checkout and Update", + disabled: !b.upstream || !!useVcs.getState().remoteBusy || checkedOutInWorktree, + run: run(() => checkoutAndUpdate(b, roots)), + }, + ]), newFrom, worktree, ...(bases.every(Boolean) diff --git a/src/features/vcs/branchOps.ts b/src/features/vcs/branchOps.ts index 6c08df715..61a57e1f2 100644 --- a/src/features/vcs/branchOps.ts +++ b/src/features/vcs/branchOps.ts @@ -1376,6 +1376,27 @@ export async function checkoutAndRebase({ branch, repos }: CheckoutRebaseTarget) }); } +/** + * Checkout and Update on a local branch: checks it out (in `roots`, or the + * current repository), then updates it like Update does, in each repository + * where the checkout took place. + */ +export async function checkoutAndUpdate(branch: NamedBranch, roots?: readonly string[]) { + const project = useProject.getState().project; + if (roots) await checkoutInRepos(branch, roots); + else await checkoutBranch(branch); + if (useProject.getState().project !== project) return; + const repos: readonly (string | null)[] = roots ?? [currentRepo()]; + const heads = await Promise.all( + repos.map(async (repo) => [repo, await call(commands.vcsBranchInfo(repo)).catch(() => null)] as const), + ); + if (useProject.getState().project !== project) return; + const targets = heads + .filter(([, info]) => info?.head === branch.name) + .map(([repo]) => ({ repo: repo ?? undefined, branch })); + if (targets.length) await updateBranches(targets); +} + export type BranchUpdateTarget = { repo?: string; branch?: Pick<Branch, "name" | "remote"> }; /** Update the named branches. Checked-out branches follow the configured update method. */ diff --git a/src/features/vcs/diffNavigation.ts b/src/features/vcs/diffNavigation.ts index 9d2ceecf1..e687d3865 100644 --- a/src/features/vcs/diffNavigation.ts +++ b/src/features/vcs/diffNavigation.ts @@ -3,8 +3,9 @@ import { call, commands } from "@/platform/ipc"; import { ideaChunks, type IgnorePolicy } from "./diffOptions"; import { chainNeighbour, loadSide, sideFile, type DiffData } from "./diffInput"; import { gitlinkDiffSides } from "./gitDiffEntries"; +import { imageDiffKind } from "./imageDiffInput"; -/** Find a textual change without opening binary, unreadable or unchanged siblings. */ +/** Find the next image or textual change in the chain. */ export async function changedChainNeighbour( data: DiffData, dir: 1 | -1, @@ -14,6 +15,7 @@ export async function changedChainNeighbour( try { // oxlint-disable-next-line no-await-in-loop -- walk the chain one neighbour at a time; an unusable link is skipped, a textual change returns const [left, right] = await gitlinkDiffSides(next); + if (imageDiffKind({ ...next, left, right })) return next; const paths = [sideFile(left, next.path), sideFile(right, next.path)].filter((p): p is string => !!p); // oxlint-disable-next-line no-await-in-loop -- probes for this neighbour must finish before deciding to skip it const probes = await Promise.all(paths.map((path) => call(commands.fsProbe(path)))); diff --git a/src/features/vcs/gitDiffEntries.ts b/src/features/vcs/gitDiffEntries.ts index 2cd64998b..b3173af36 100644 --- a/src/features/vcs/gitDiffEntries.ts +++ b/src/features/vcs/gitDiffEntries.ts @@ -88,5 +88,5 @@ export function useGitDiffEntries(data: DiffData, cache?: DiffEntriesCache) { right: resolveSide(right, entries[2]), }; }, [data, entries, left, middle, right]); - return { data: resolved, entries, loading: !!query && !hit && loaded?.query !== query }; + return { data: resolved, entries, versions, loading: !!query && !hit && loaded?.query !== query }; } diff --git a/src/features/vcs/imageDiffFrames.ts b/src/features/vcs/imageDiffFrames.ts new file mode 100644 index 000000000..c626bb44c --- /dev/null +++ b/src/features/vcs/imageDiffFrames.ts @@ -0,0 +1,81 @@ +import { parseLengthPx, parseViewBoxSize } from "@/ui/svgSize"; +import type { DiffSide } from "./diffInput"; +import { readImageSide } from "./imageDiffInput"; +import { imageBounds, type ImageSize } from "./imagePixels"; + +type Unavailable = { kind: "absent" } | { kind: "error"; error: string }; +type Source = { kind: "raster"; url: string } | { kind: "svg"; svg: SVGSVGElement; intrinsic: ImageSize } | Unavailable; +export type ImageFrame = + | { kind: "ready"; image: HTMLImageElement; intrinsic: ImageSize; size: ImageSize } + | Unavailable; + +export function svgIntrinsicSize(svg: SVGSVGElement): ImageSize { + const box = parseViewBoxSize(svg.getAttribute("viewBox")); + const w = parseLengthPx(svg.style.width || svg.getAttribute("width")); + const h = parseLengthPx(svg.style.height || svg.getAttribute("height")); + return { + width: Math.max(1, Math.round(w ?? (h && box ? (h * box.w) / box.h : (box?.w ?? 300)))), + height: Math.max(1, Math.round(h ?? (w && box ? (w * box.h) / box.w : (box?.h ?? 150)))), + }; +} + +function readSvg(url: string): SVGSVGElement { + const comma = url.indexOf(","); + const data = url.slice(comma + 1); + const xml = /;base64/i.test(url.slice(0, comma)) + ? new TextDecoder().decode(Uint8Array.from(atob(data), (c) => c.charCodeAt(0))) + : decodeURIComponent(data); + const svg = new DOMParser().parseFromString(xml, "image/svg+xml").documentElement; + if (svg.localName !== "svg" || svg.namespaceURI !== "http://www.w3.org/2000/svg") throw new Error("Invalid SVG"); + return svg as unknown as SVGSVGElement; +} + +/** Set the SVG layout viewport before rasterizing so intrinsic sizes don't stretch one revision's pixels. */ +export function svgAtViewport(svg: SVGSVGElement, { width, height }: ImageSize): string { + svg.setAttribute("width", String(width)); + svg.setAttribute("height", String(height)); + svg.style.setProperty("width", width + "px", "important"); + svg.style.setProperty("height", height + "px", "important"); + return "data:image/svg+xml;charset=utf-8," + encodeURIComponent(new XMLSerializer().serializeToString(svg)); +} + +function failed(e: unknown): Unavailable { + return { kind: "error", error: e instanceof Error ? e.message : String(e) }; +} + +export async function loadImageFrames( + path: string, + sides: DiffSide[], + cancelled: () => boolean, +): Promise<ImageFrame[]> { + const sources = await Promise.all( + sides.map(async (side): Promise<Source> => { + try { + const url = await readImageSide(path, side); + if (cancelled() || url === null) return { kind: "absent" }; + if (!/^data:image\/svg\+xml\b/i.test(url)) return { kind: "raster", url }; + const svg = readSvg(url); + return { kind: "svg", svg, intrinsic: svgIntrinsicSize(svg) }; + } catch (e) { + return failed(e); + } + }), + ); + if (cancelled()) return []; + const viewport = imageBounds(sources.flatMap((s) => (s.kind === "svg" ? [s.intrinsic] : []))); + return Promise.all( + sources.map(async (source): Promise<ImageFrame> => { + if (source.kind === "absent" || source.kind === "error") return source; + try { + const image = new Image(); + // Even for XML we only render in an image context, where scripts and external resources are disabled. + image.src = source.kind === "svg" ? svgAtViewport(source.svg, viewport) : source.url; + await image.decode(); + const size = { width: image.naturalWidth, height: image.naturalHeight }; + return { kind: "ready", image, size, intrinsic: source.kind === "svg" ? source.intrinsic : size }; + } catch (e) { + return failed(e); + } + }), + ); +} diff --git a/src/features/vcs/imageDiffInput.ts b/src/features/vcs/imageDiffInput.ts new file mode 100644 index 000000000..bb260836b --- /dev/null +++ b/src/features/vcs/imageDiffInput.ts @@ -0,0 +1,44 @@ +import { attachDocument } from "@/editor/api"; +import { call, commands } from "@/platform/ipc"; +import { isSvgPath } from "@/features/viewers/fileKinds"; +import { maybeEditorService } from "@/workbench/contributions"; +import { stagedDocumentAtPath } from "./stagedDocument"; +import { isIndex, type DiffData, type DiffSide } from "./diffInput"; + +export function imageDiffKind(data: DiffData): "svg" | "raster" | null { + if (data.stagingRange || data.line !== undefined || data.context || data.annotations?.length || data.annotateLeft) + return null; + const paths: string[] = []; + for (const side of [data.left, data.middle, data.right]) { + if (!side || (side.type === "text" && side.absent && !side.gitlinkSource)) continue; + if (side.type !== "rev" && side.type !== "worktree" && side.type !== "file") return null; + const path = (side.type !== "worktree" && side.path) || data.path; + if (!/\.(png|jpe?g|webp|svg)$/i.test(path)) return null; + paths.push(path); + } + if (!paths.length) return null; + return paths.every(isSvgPath) ? "svg" : "raster"; +} + +const svgDataUrl = (text: string) => "data:image/svg+xml;charset=utf-8," + encodeURIComponent(text); + +export async function readImageSide(path: string, side: DiffSide): Promise<string | null> { + if (side.type === "rev") { + const file = side.path ?? path; + const draft = isIndex(side) && isSvgPath(file) && stagedDocumentAtPath(file); + if (draft && draft.dirty) return svgDataUrl(draft.status.getState().text); + return call(commands.vcsImageAt(file, side.rev)); + } + if (side.type !== "worktree" && side.type !== "file") return null; + const file = side.type === "file" ? side.path : path; + if (isSvgPath(file) && maybeEditorService()?.dirtyDocumentIds?.().length !== 0) { + // The shared document keeps unsaved text even when its editor tab is unmounted. + const doc = await attachDocument(file).catch(() => null); + try { + if (doc?.dirty()) return svgDataUrl(doc.text()); + } finally { + doc?.release(); + } + } + return call(commands.fsReadImage(file)); +} diff --git a/src/features/vcs/imagePixels.ts b/src/features/vcs/imagePixels.ts new file mode 100644 index 000000000..fc4ce1349 --- /dev/null +++ b/src/features/vcs/imagePixels.ts @@ -0,0 +1,57 @@ +export interface ImageSize { + width: number; + height: number; +} + +export interface PixelImage extends ImageSize { + data: Uint8ClampedArray; +} + +export function imageBounds(sizes: readonly ImageSize[]): ImageSize { + return { + width: Math.max(0, ...sizes.map((size) => size.width)), + height: Math.max(0, ...sizes.map((size) => size.height)), + }; +} + +export function canComparePixels({ width, height }: ImageSize): boolean { + return width > 0 && height > 0 && width <= 16384 && height <= 16384 && width * height <= 8_388_608; +} + +function rgbaWords(frame: PixelImage | null) { + const data = frame?.data; + return data && new Uint32Array(data.buffer, data.byteOffset, data.length / 4); +} + +/** The mask has the enclosing dimensions. Coordinates are anchored at the top left of each revision. */ +export function paintPixelDifference(before: PixelImage | null, after: PixelImage | null, mask: PixelImage): number { + let changed = 0; + const a = rgbaWords(before); + const b = rgbaWords(after); + const out = mask.data; + for (let y = 0; y < mask.height; y++) { + for (let x = 0; x < mask.width; x++) { + const i = 4 * (y * mask.width + x); + const left = before && x < before.width && y < before.height ? y * before.width + x : -1; + const right = after && x < after.width && y < after.height ? y * after.width + x : -1; + if (left < 0 && right < 0) continue; + if (after && a?.[left] === b?.[right]) { + const offset = 4 * right; + const rgba = after.data; + const luminance = (rgba[offset]! + 2 * rgba[offset + 1]! + rgba[offset + 2]!) / 4; + const gray = 90 + luminance * 0.4; + out[i] = gray; + out[i + 1] = gray; + out[i + 2] = gray; + out[i + 3] = rgba[offset + 3]!; + } else { + changed++; + out[i] = 240; + out[i + 1] = 48; + out[i + 2] = 141; + out[i + 3] = 255; + } + } + } + return changed; +} diff --git a/src/features/vcs/log/BranchesPanel.tsx b/src/features/vcs/log/BranchesPanel.tsx index a70523c7e..eee60a0c8 100644 --- a/src/features/vcs/log/BranchesPanel.tsx +++ b/src/features/vcs/log/BranchesPanel.tsx @@ -140,7 +140,7 @@ export function BranchesPanel() { const remoteBusy = useVcs((s) => s.remoteBusy); const current = useVcs((s) => s.branch?.head ?? null); const favorites = useFavoriteBranches((s) => s.names); - const filterBranches = filters.branches; + const { branches: filterBranches, branchTargets } = filters; const [query, setQuery] = useState(""); const [tags, setTags] = useState<string[]>([]); useEffect(() => loadFavoriteBranches(), [root]); @@ -205,9 +205,15 @@ export function BranchesPanel() { filterBranches.flatMap((b) => { if (b === "HEAD") return ["head"]; if (repositories.length < 2 || merged) return [`b:${b}`]; - return repositories.map((r) => `${r}:b:${b}`); + return repositories + .filter( + (repo) => + !branchTargets || + branchTargets.some((target) => target.ref === b && (!target.repo || target.repo === repo)), + ) + .map((repo) => `${repo}:b:${b}`); }), - [filterBranches, repositories, merged], + [filterBranches, branchTargets, repositories, merged], ); const filterKey = filterKeys.join("\n"); const [shownKey, setShownKey] = useState(filterKey); @@ -369,13 +375,13 @@ export function BranchesPanel() { selected={selected} onSelectionChange={(sel) => setSelected(sel)} onActivate={(n) => { - // Double click (or Enter) filters the log to that branch, or to every selected one - // in a multi-selection; checking out stays in the context menu. Only the branch filter - // changes: repositories without the branch contribute no commits, and leaving the - // repository filter alone keeps every repository listed here, so clearing the branch - // filter restores the whole log. if (!n.ref) return; - setLogFilters({ branches: selected.has(n.key) ? [...new Set(targets.map((r) => r.ref))] : [n.ref] }); + const activated = selected.has(n.key) ? targets : expand(n, scopedRepo); + const branchTargets = activated.map(({ ref, repo }) => ({ ref, repo })); + setLogFilters({ + branches: [...new Set(branchTargets.map(({ ref }) => ref))], + branchTargets: branchTargets.some(({ repo }) => repo) ? branchTargets : undefined, + }); }} onContextMenu={(n, _sel, e) => { if (readOnly) { diff --git a/src/features/vcs/logStore.ts b/src/features/vcs/logStore.ts index 677ac4453..2240a6e37 100644 --- a/src/features/vcs/logStore.ts +++ b/src/features/vcs/logStore.ts @@ -29,9 +29,16 @@ export interface LogDateFilter { /** User filter entry standing for the current Git user (`user.name` / `user.email`). */ export const ME = "me"; +interface LogBranchTarget { + ref: string; + repo?: string; +} + export interface LogFilters { /** Branches / revisions to show; empty = all. */ branches: string[]; + /** Refs activated in the Branches pane; a missing repo targets all repositories. */ + branchTargets?: LogBranchTarget[]; repositories?: string[]; /** Author names or emails (any matches); `ME` = the current user. */ authors: string[]; @@ -269,7 +276,7 @@ export function initLogBranchFilter(): boolean { .branches.filter((b) => !b.name.endsWith("/HEAD")) .map((b) => b.name); const next = resolveLogBranches(rememberedLogBranches(repo), names); - useGitLog.setState({ filters: { ...s.filters, branches: next }, branchScope: repo }); + useGitLog.setState({ filters: { ...s.filters, branches: next, branchTargets: undefined }, branchScope: repo }); return true; } @@ -286,6 +293,7 @@ export function setLogBranches(branches: readonly string[]) { filters: { ...s.filters, branches: branches.filter((b) => !b.includes("..")), + branchTargets: undefined, range: ranges.length ? ranges.join("\n") : null, }, ...(repo ? { branchScope: repo } : {}), @@ -430,7 +438,9 @@ export function ensureEditorLog(id: string, label: string, config?: Pick<LogTab, function comparisonFilters(filters: LogFilters, tab: LogTab | undefined): LogFilters { const range = tab?.comparison; - return range ? { ...filters, branches: [], range: `${range.from}..${range.to}`, repoRanges: undefined } : filters; + return range + ? { ...filters, branches: [], branchTargets: undefined, range: `${range.from}..${range.to}`, repoRanges: undefined } + : filters; } /** Selects a content tab of the Git tool window; a log tab brings its own filters and commits. */ @@ -619,9 +629,22 @@ function parseFilters(value: unknown): LogFilters { const raw = value as Record<string, unknown>; const strings = (v: unknown): string[] => Array.isArray(v) ? v.filter((s): s is string => typeof s === "string") : []; + const branches = strings(raw.branches); + const branchTargets = Array.isArray(raw.branchTargets) + ? raw.branchTargets.filter( + (target: unknown): target is LogBranchTarget => + !!target && + typeof target === "object" && + "ref" in target && + typeof target.ref === "string" && + branches.includes(target.ref) && + (!("repo" in target) || typeof target.repo === "string"), + ) + : []; const filters = { ...emptyFilters(), - branches: strings(raw.branches), + branches, + ...(branchTargets.length ? { branchTargets } : {}), authors: strings(raw.authors), repositories: strings(raw.repositories), paths: strings(raw.paths), @@ -808,6 +831,7 @@ export function recentLogFilters(): LogFilters[] { function rememberRecentFilters(before: LogFilters) { for (const name of Object.keys(before) as Array<keyof LogFilters>) { + if (name === "branchTargets") continue; const value = before[name]; if (value == null || value === "" || (Array.isArray(value) && !value.length)) continue; try { @@ -842,7 +866,7 @@ export function setLogFilters(patch: Partial<LogFilters>) { rememberRecentFilters(useGitLog.getState().filters); useGitLog.setState((s) => ({ filters: comparisonFilters( - { ...s.filters, ...("branches" in patch ? { range: null } : {}), ...patch }, + { ...s.filters, ...("branches" in patch ? { range: null, branchTargets: undefined } : {}), ...patch }, s.logTabs.find((tab) => tab.id === s.shownLog), ), })); @@ -865,7 +889,14 @@ function logRepositoryScope(state: LogState) { : registeredRoots.length ? registeredRoots : [f.path || f.paths?.length ? projectRepo : currentRepo()]; - return { repositories: scopedLogRepositories(candidates, f, ownerRoots), ownerRoots }; + const repositories = scopedLogRepositories(candidates, f, ownerRoots); + const { branchTargets } = f; + return { + repositories: branchTargets?.length + ? repositories.filter((repo) => branchTargets.some((target) => !target.repo || target.repo === repo)) + : repositories, + ownerRoots, + }; } /** The source can already be specified by one branch or a single revision range. */ @@ -1021,9 +1052,13 @@ function loadPage(replace: boolean, id: string, before = false): Promise<void> { let joined = false; const results = await Promise.allSettled( roots.map(async (repo) => { - const branches = f.branches.filter( - (ref) => !knownRefs.has(ref) || (repo && refs[repo]?.some((b) => b.name === ref)), - ); + const branches = f.branchTargets?.length + ? [ + ...new Set( + f.branchTargets.filter((target) => !target.repo || target.repo === repo).map((target) => target.ref), + ), + ] + : f.branches.filter((ref) => !knownRefs.has(ref) || (repo && refs[repo]?.some((b) => b.name === ref))); if (f.branches.length && !branches.length) return []; const config = (key: string) => call(commands.vcsConfigGet(repo, key)).catch(() => null); const [userEmail, userName] = await Promise.all([config("user.email"), config("user.name")]); diff --git a/src/features/vcs/repoBranches.ts b/src/features/vcs/repoBranches.ts index 8f7dd57e9..4865d35e1 100644 --- a/src/features/vcs/repoBranches.ts +++ b/src/features/vcs/repoBranches.ts @@ -215,6 +215,9 @@ export function buildMultiRepoRows({ if (m !== false) repoRows.push({ type: "repo", key: `repo:${repo.root}`, repo, color: repoColorIndex(i), matches: m }); }); + // The repository this window works on comes first; the others keep their order (and colours). + const currentRow = repoRows.findIndex((r) => r.type === "repo" && r.repo.root === current); + if (currentRow > 0) repoRows.unshift(...repoRows.splice(currentRow, 1)); blocks.push(repoRows); /** A group row followed (when expanded) by its children; nothing when it has none. */ diff --git a/src/features/vcs/selectionHistoryKind.ts b/src/features/vcs/selectionHistoryKind.ts index 56b56972b..3757ee176 100644 --- a/src/features/vcs/selectionHistoryKind.ts +++ b/src/features/vcs/selectionHistoryKind.ts @@ -1,5 +1,5 @@ /** History for Selection tab input; kept apart from `SelectionHistory` so opening one does not load it. */ -import { activeEditor } from "@/editor/api"; +import { activeEditor, focusedCellEditor } from "@/editor/api"; import { isVirtualUri } from "@/platform/virtualDocs"; import { editorService, notifications, type EditorInput } from "@/workbench/contributions"; @@ -35,6 +35,12 @@ export function selectedLines( /** Git › Show History for Selection: the active editor's selected lines. */ export function showSelectionHistory() { + // A notebook cell has no line range in its file yet: ask for a file rather than + // showing the last text tab's selection (the notebook's own lines are a later step). + if (focusedCellEditor()) { + notifications().notify({ group: "vcs", level: "info", title: "Open a file to show the history of its selection" }); + return; + } const editor = activeEditor(); if (!editor || isVirtualUri(editor.ctx.path)) { notifications().notify({ group: "vcs", level: "info", title: "Open a file to show the history of its selection" }); diff --git a/src/platform/dateFormat.test.ts b/src/platform/dateFormat.test.ts index 32e9b9dfa..095e3662b 100644 --- a/src/platform/dateFormat.test.ts +++ b/src/platform/dateFormat.test.ts @@ -5,6 +5,7 @@ import { formatDateTime, formatDay, formatPattern, + formatPrettyDay, formatTimestamp, } from "./dateFormat"; @@ -33,6 +34,19 @@ describe("dateFormat", () => { expect(formatTimestamp(d.getTime(), now, custom)).toBe("05.11.2026 09:07"); }); + it("shows Today/Yesterday without a clock time for blame, older dates keep the short date", () => { + const now = new Date(2026, 10, 13, 12, 0).getTime(); + const pretty = { ...system, pretty: true }; + const older = new Date(2026, 10, 5, 9, 7); + const short = { year: "2-digit", month: "2-digit", day: "2-digit" } as const; + expect(formatPrettyDay(new Date(2026, 10, 13, 9, 7).getTime(), now, pretty)).toBe("Today"); + expect(formatPrettyDay(new Date(2026, 10, 12, 23, 30).getTime(), now, pretty)).toBe("Yesterday"); + expect(formatPrettyDay(older.getTime(), now, pretty)).toBe(older.toLocaleDateString(undefined, short)); + expect(formatPrettyDay(new Date(2026, 10, 13, 9, 7).getTime(), now, { ...system, pretty: false })).toBe( + new Date(2026, 10, 13, 9, 7).toLocaleDateString(undefined, short), + ); + }); + it("formats another date with the same cached formatter", () => { const e = new Date(2025, 0, 31); formatDay(d, system); diff --git a/src/platform/dateFormat.ts b/src/platform/dateFormat.ts index 75d5f7cb1..02cbc0b32 100644 --- a/src/platform/dateFormat.ts +++ b/src/platform/dateFormat.ts @@ -99,3 +99,16 @@ export function formatTimestamp(ms: number, now = Date.now(), o: DateFormatOptio } return formatDateTime(d, o); } + +/** + * Day without clock time (blame gutter): "Today" / "Yesterday" when pretty + * formatting is on, as IDEA's annotate shows; older dates keep the short date. + */ +export function formatPrettyDay(ms: number, now = Date.now(), o: DateFormatOptions = dateFormatOptions()): string { + const d = new Date(ms); + if (o.pretty) { + if (d.toDateString() === new Date(now).toDateString()) return tx("Today"); + if (d.toDateString() === new Date(now - 86_400_000).toDateString()) return tx("Yesterday"); + } + return formatDay(d, o, true); +} diff --git a/src/platform/editorSettings.ts b/src/platform/editorSettings.ts index f61abfb94..6daf74299 100644 --- a/src/platform/editorSettings.ts +++ b/src/platform/editorSettings.ts @@ -47,6 +47,15 @@ export interface LanguageCodeStyle { /** SQL › Case: Reformat Code's case for keywords and unquoted identifiers. */ keywordCase?: SqlWordCase; identifierCase?: SqlWordCase; + /** Java: organize imports switches to a wildcard import once this many classes of one package are used (jdtls passthrough). */ + classCountToUseImportWithStar?: number; + /** Java: organize imports switches to a wildcard static import once this many names are used (jdtls passthrough). */ + namesCountToUseStaticImportWithStar?: number; + /** JavaScript / TypeScript › Punctuation (unset: tsserver's default, `ignore` / `auto`). */ + semicolons?: "ignore" | "insert" | "remove"; + quotes?: "auto" | "single" | "double"; + /** JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`). */ + spaces?: Record<string, boolean>; } /** IDEA's SQL word case: To upper / To lower / Do not change. */ diff --git a/src/platform/i18n.test.ts b/src/platform/i18n.test.ts index 1b583b55b..b2cd1e23f 100644 --- a/src/platform/i18n.test.ts +++ b/src/platform/i18n.test.ts @@ -352,6 +352,13 @@ describe("catalogs", () => { "Deno", "Node.js", "bun-dap (Bun)", + // DuckDB data source: the product name, the JDBC URL field and its path placeholder. + "DuckDB", + "JDBC URL", + "path/to/database.duckdb", + // Unreal Engine projects: the product name and the .uproject path placeholder. + "Unreal Engine", + "…/Game.uproject", ]); const translated = SUPPORTED_LOCALES.filter((locale) => locale !== "en").sort(); diff --git a/src/platform/ideaActions.ts b/src/platform/ideaActions.ts index 3e69926fa..4b9bec14e 100644 --- a/src/platform/ideaActions.ts +++ b/src/platform/ideaActions.ts @@ -117,8 +117,11 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = { MoveTabDown: "editor.splitAndMoveDown", Unsplit: "editor.unsplit", ToggleDistractionFreeMode: "editor.toggleZen", + ToggleZenMode: "view.toggleZenMode", EditorScrollUp: "editor.scrollUp", EditorScrollDown: "editor.scrollDown", + EditorScrollUpAndMove: "editor.scrollUpAndMove", + EditorScrollDownAndMove: "editor.scrollDownAndMove", EditorScrollTop: "editor.scrollToTop", EditorScrollBottom: "editor.scrollToBottom", EditorMoveToPageTop: "editor.moveToPageTop", @@ -129,6 +132,12 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = { EditorBackwardParagraph: "editor.paragraphBackward", EditorForwardParagraphWithSelection: "editor.paragraphForwardWithSelection", EditorBackwardParagraphWithSelection: "editor.paragraphBackwardWithSelection", + EditorNextWordInDifferentHumpsMode: "editor.nextWordInDifferentHumpsMode", + EditorPreviousWordInDifferentHumpsMode: "editor.previousWordInDifferentHumpsMode", + EditorNextWordInDifferentHumpsModeWithSelection: "editor.nextWordInDifferentHumpsModeWithSelection", + EditorPreviousWordInDifferentHumpsModeWithSelection: "editor.previousWordInDifferentHumpsModeWithSelection", + EditorDeleteToWordStartInDifferentHumpsMode: "code.deleteToWordStartInDifferentHumpsMode", + EditorDeleteToWordEndInDifferentHumpsMode: "code.deleteToWordEndInDifferentHumpsMode", EditorGutterToggleGlobalLineNumbers: "editor.toggleLineNumbers", EditorGutterToggleGlobalIndentLines: "editor.toggleIndentGuides", EditorGutterToggleGlobalStickyLines: "editor.toggleStickyLines", diff --git a/src/platform/ideaKeymap.test.ts b/src/platform/ideaKeymap.test.ts index 5dcee130a..a67f94271 100644 --- a/src/platform/ideaKeymap.test.ts +++ b/src/platform/ideaKeymap.test.ts @@ -92,6 +92,15 @@ describe("IntelliJ IDEA keymap import", () => { expect(k.unknownActions).toEqual([]); }); + it("maps Scroll Up / Scroll Down and Move if Necessary", () => { + const k = parseIdeaKeymap( + `<keymap name="E" parent="$default"><action id="EditorScrollUpAndMove"><keyboard-shortcut first-keystroke="alt UP"/></action><action id="EditorScrollDownAndMove"><keyboard-shortcut first-keystroke="alt DOWN"/></action></keymap>`, + ); + expect(k.overrides["editor.scrollUpAndMove"]).toEqual([normalizeBinding("Alt+Up")]); + expect(k.overrides["editor.scrollDownAndMove"]).toEqual([normalizeBinding("Alt+Down")]); + expect(k.unknownActions).toEqual([]); + }); + it("maps Scroll to Top / Scroll to Bottom", () => { const k = parseIdeaKeymap( `<keymap name="X" parent="Mac OS X 10.5+"><action id="EditorScrollTop"><keyboard-shortcut first-keystroke="HOME"/></action><action id="EditorScrollBottom"><keyboard-shortcut first-keystroke="END"/></action></keymap>`, @@ -101,6 +110,14 @@ describe("IntelliJ IDEA keymap import", () => { expect(k.unknownActions).toEqual([]); }); + it("maps Toggle Zen Mode", () => { + const k = parseIdeaKeymap( + `<keymap name="E" parent="Mac OS X 10.5+"><action id="ToggleZenMode"><keyboard-shortcut first-keystroke="control meta Z"/></action></keymap>`, + ); + expect(k.overrides["view.toggleZenMode"]).toEqual([normalizeBinding("Ctrl+Meta+Z")]); + expect(k.unknownActions).toEqual([]); + }); + it("maps Copy as Plain Text / Copy as Rich Text", () => { const k = parseIdeaKeymap( `<keymap name="E" parent="Mac OS X 10.5+"><action id="CopyAsPlainText"><keyboard-shortcut first-keystroke="control alt C"/></action><action id="CopyAsRichText"><keyboard-shortcut first-keystroke="control alt shift C"/></action></keymap>`, @@ -145,6 +162,18 @@ describe("IntelliJ IDEA keymap import", () => { expect(k.unknownActions).toEqual([]); }); + it('maps the word moves and deletes in Different "CamelHumps" Mode', () => { + const k = parseIdeaKeymap( + `<keymap name="H" parent="$default"><action id="EditorNextWordInDifferentHumpsMode"><keyboard-shortcut first-keystroke="control alt RIGHT"/></action><action id="EditorPreviousWordInDifferentHumpsModeWithSelection"><keyboard-shortcut first-keystroke="control alt shift LEFT"/></action><action id="EditorDeleteToWordStartInDifferentHumpsMode"><keyboard-shortcut first-keystroke="control alt BACK_SPACE"/></action></keymap>`, + ); + expect(k.overrides["editor.nextWordInDifferentHumpsMode"]).toEqual([normalizeBinding("Ctrl+Alt+Right")]); + expect(k.overrides["editor.previousWordInDifferentHumpsModeWithSelection"]).toEqual([ + normalizeBinding("Ctrl+Alt+Shift+Left"), + ]); + expect(k.overrides["code.deleteToWordStartInDifferentHumpsMode"]).toEqual([normalizeBinding("Ctrl+Alt+Backspace")]); + expect(k.unknownActions).toEqual([]); + }); + it("maps Swap Selection Boundaries", () => { const k = parseIdeaKeymap( `<keymap name="S" parent="$default"><action id="EditorSwapSelectionBoundaries"><keyboard-shortcut first-keystroke="control X" second-keystroke="control X"/></action></keymap>`, diff --git a/src/platform/keymaps/ideaParity.test.ts b/src/platform/keymaps/ideaParity.test.ts index 15a574a87..6b6977445 100644 --- a/src/platform/keymaps/ideaParity.test.ts +++ b/src/platform/keymaps/ideaParity.test.ts @@ -64,6 +64,8 @@ describe("IDEA keymap parity", () => { // `Mac OS X 10.5+` removes the ⌘↑ / ⌘↓ it would inherit from `Mac OS X`. ["editor.scrollUp", [], ["Ctrl+Up"]], ["editor.scrollDown", [], ["Ctrl+Down"]], + ["editor.scrollUpAndMove", [], []], + ["editor.scrollDownAndMove", [], []], // Only IDEA's Xcode keymap binds these (Home / End). ["editor.scrollToTop", [], []], ["editor.scrollToBottom", [], []], @@ -86,6 +88,8 @@ describe("IDEA keymap parity", () => { // CopyAsPlainText / CopyAsRichText have no shortcut. ["code.copyAsPlainText", [], []], ["code.copyAsRichText", [], []], + // ToggleZenMode has no shortcut. + ["view.toggleZenMode", [], []], ["navigate.nextOccurrence", ["Meta+Alt+Down"], ["Ctrl+Alt+Down"]], ["navigate.prevOccurrence", ["Meta+Alt+Up"], ["Ctrl+Alt+Up"]], // Rerun in the Find / Find Usages tool windows uses the Rerun shortcut. @@ -103,6 +107,13 @@ describe("IDEA keymap parity", () => { ["editor.paragraphBackward", [], []], ["editor.paragraphForwardWithSelection", [], []], ["editor.paragraphBackwardWithSelection", [], []], + // The "in Different "CamelHumps" Mode" word moves and deletes have no shortcut. + ["editor.nextWordInDifferentHumpsMode", [], []], + ["editor.previousWordInDifferentHumpsMode", [], []], + ["editor.nextWordInDifferentHumpsModeWithSelection", [], []], + ["editor.previousWordInDifferentHumpsModeWithSelection", [], []], + ["code.deleteToWordStartInDifferentHumpsMode", [], []], + ["code.deleteToWordEndInDifferentHumpsMode", [], []], ["code.collapseBlock", ["Meta+Shift+."], ["Ctrl+Shift+."]], ["code.autoIndentLines", ["Ctrl+Alt+I"], ["Ctrl+Alt+I"]], ["code.showErrorDescription", ["Meta+F1"], ["Ctrl+F1"]], diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts index 0bb18c4e8..4c8a1b29b 100644 --- a/src/platform/keymaps/intellij-macos.ts +++ b/src/platform/keymaps/intellij-macos.ts @@ -138,6 +138,8 @@ export const intellijMacos: Record<string, string[]> = { "editor.scrollToCenter": ["Ctrl+L"], "editor.scrollUp": [], "editor.scrollDown": [], + "editor.scrollUpAndMove": [], + "editor.scrollDownAndMove": [], "editor.scrollToTop": [], "editor.scrollToBottom": [], "editor.moveToPageTop": ["Meta+PageUp"], @@ -152,6 +154,12 @@ export const intellijMacos: Record<string, string[]> = { "editor.paragraphBackward": [], "editor.paragraphForwardWithSelection": [], "editor.paragraphBackwardWithSelection": [], + "editor.nextWordInDifferentHumpsMode": [], + "editor.previousWordInDifferentHumpsMode": [], + "editor.nextWordInDifferentHumpsModeWithSelection": [], + "editor.previousWordInDifferentHumpsModeWithSelection": [], + "code.deleteToWordStartInDifferentHumpsMode": [], + "code.deleteToWordEndInDifferentHumpsMode": [], "editor.contextInfo": ["Ctrl+Shift+Q"], "navigate.customRegion": ["Meta+Alt+."], "code.expandToLevel1": ["Meta+* 1"], @@ -204,6 +212,7 @@ export const intellijMacos: Record<string, string[]> = { "refactor.move": ["F6"], "refactor.safeDelete": ["Meta+Delete"], "refactor.extractInterface": [], + "refactor.extractTypeAlias": [], "refactor.pullMembersUp": [], "refactor.pushMembersDown": [], @@ -291,6 +300,8 @@ export const intellijMacos: Record<string, string[]> = { // (ToggleDistractionFreeMode has no default). ⌃⌘D is macOS's system-wide // "Look Up in Dictionary" hotkey, which never reaches the webview. "editor.toggleZen": [], + // ToggleZenMode has no default. + "view.toggleZenMode": [], "editor.toggleLineNumbers": [], "editor.toggleIndentGuides": [], "editor.toggleStickyLines": [], diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts index 7120fe71c..96f682f46 100644 --- a/src/platform/keymaps/intellij-windows.ts +++ b/src/platform/keymaps/intellij-windows.ts @@ -139,6 +139,8 @@ export const intellijWindows: Record<string, string[]> = { "editor.scrollToCenter": ["Ctrl+M"], "editor.scrollUp": ["Ctrl+Up"], "editor.scrollDown": ["Ctrl+Down"], + "editor.scrollUpAndMove": [], + "editor.scrollDownAndMove": [], "editor.scrollToTop": [], "editor.scrollToBottom": [], "editor.moveToPageTop": ["Ctrl+PageUp"], @@ -153,6 +155,12 @@ export const intellijWindows: Record<string, string[]> = { "editor.paragraphBackward": [], "editor.paragraphForwardWithSelection": [], "editor.paragraphBackwardWithSelection": [], + "editor.nextWordInDifferentHumpsMode": [], + "editor.previousWordInDifferentHumpsMode": [], + "editor.nextWordInDifferentHumpsModeWithSelection": [], + "editor.previousWordInDifferentHumpsModeWithSelection": [], + "code.deleteToWordStartInDifferentHumpsMode": [], + "code.deleteToWordEndInDifferentHumpsMode": [], "editor.contextInfo": ["Alt+Q"], "navigate.customRegion": ["Ctrl+Alt+."], "code.expandToLevel1": ["Ctrl+* 1"], @@ -205,6 +213,7 @@ export const intellijWindows: Record<string, string[]> = { "refactor.move": ["F6"], "refactor.safeDelete": ["Alt+Delete"], "refactor.extractInterface": [], + "refactor.extractTypeAlias": [], "refactor.pullMembersUp": [], "refactor.pushMembersDown": [], @@ -285,6 +294,8 @@ export const intellijWindows: Record<string, string[]> = { "toolwindow.hideSide": [], "toolwindow.focusEditor": ["Escape"], "editor.toggleZen": [], + // ToggleZenMode has no default. + "view.toggleZenMode": [], "editor.toggleLineNumbers": [], "editor.toggleIndentGuides": [], "editor.toggleStickyLines": [], diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts index 64a9b6635..2a3683460 100644 --- a/src/platform/keymaps/vscode-macos.ts +++ b/src/platform/keymaps/vscode-macos.ts @@ -209,6 +209,7 @@ export const vscodeMacos: Record<string, string[]> = { "refactor.move": [], "refactor.safeDelete": [], "refactor.extractInterface": [], + "refactor.extractTypeAlias": [], "refactor.pullMembersUp": [], "refactor.pushMembersDown": [], @@ -235,6 +236,7 @@ export const vscodeMacos: Record<string, string[]> = { "editor.splitAndMoveRight": [], "editor.splitAndMoveDown": [], "editor.toggleZen": ["Meta+K Z"], + "view.toggleZenMode": [], "editor.toggleLineNumbers": [], "editor.toggleIndentGuides": [], "editor.toggleStickyLines": [], @@ -252,6 +254,8 @@ export const vscodeMacos: Record<string, string[]> = { "editor.scrollToCenter": [], "editor.scrollUp": [], "editor.scrollDown": [], + "editor.scrollUpAndMove": [], + "editor.scrollDownAndMove": [], "editor.scrollToTop": [], "editor.scrollToBottom": [], "editor.moveToPageTop": [], @@ -264,6 +268,12 @@ export const vscodeMacos: Record<string, string[]> = { "editor.paragraphBackward": [], "editor.paragraphForwardWithSelection": [], "editor.paragraphBackwardWithSelection": [], + "editor.nextWordInDifferentHumpsMode": [], + "editor.previousWordInDifferentHumpsMode": [], + "editor.nextWordInDifferentHumpsModeWithSelection": [], + "editor.previousWordInDifferentHumpsModeWithSelection": [], + "code.deleteToWordStartInDifferentHumpsMode": [], + "code.deleteToWordEndInDifferentHumpsMode": [], "editor.cloneCaretAbove": ["Meta+Alt+Up"], "editor.cloneCaretBelow": ["Meta+Alt+Down"], "editor.matchBrace": ["Meta+Shift+\\"], diff --git a/src/platform/languageSettings.ts b/src/platform/languageSettings.ts index bf8a926c2..3e5998569 100644 --- a/src/platform/languageSettings.ts +++ b/src/platform/languageSettings.ts @@ -26,7 +26,7 @@ const DEFAULT_GO_BUILD_TAGS: GoBuildTags = { experiments: "", }; -/** An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats. */ +/** An external formatter (Prettier, oxfmt, Biome, dprint, Ruff, Black) and the languages it formats. */ interface ExternalFormatterValid { path: string; configurationDirectory: string; @@ -64,6 +64,9 @@ const DEFAULT_BIOME_FORMATTER: ExternalFormatterValid = { languages: ["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"], }; +/** dprint formats what its configuration covers: no language list. */ +const DEFAULT_DPRINT_FORMATTER: ExternalFormatterValid = { ...DEFAULT_FORMATTER, languages: [] }; + const DEFAULT_PYTHON_FORMATTER: ExternalFormatterValid = { ...DEFAULT_FORMATTER, languages: ["python"], @@ -212,6 +215,7 @@ export interface LanguagesValid { prettier: ExternalFormatterValid; oxfmt: ExternalFormatterValid; biome: ExternalFormatterValid; + dprint: ExternalFormatterValid; ruff: ExternalFormatterValid; black: ExternalFormatterValid; java: { @@ -329,6 +333,7 @@ export const DEFAULT_LANGUAGES: LanguagesValid = { prettier: DEFAULT_FORMATTER, oxfmt: DEFAULT_FORMATTER, biome: DEFAULT_BIOME_FORMATTER, + dprint: DEFAULT_DPRINT_FORMATTER, ruff: DEFAULT_PYTHON_FORMATTER, black: DEFAULT_PYTHON_FORMATTER, java: { @@ -511,6 +516,7 @@ export function validateLanguages(raw: unknown): LanguagesValid { prettier: validateFormatter(l.prettier), oxfmt: validateFormatter(l.oxfmt), biome: validateFormatter(l.biome, DEFAULT_BIOME_FORMATTER), + dprint: validateFormatter(l.dprint, DEFAULT_DPRINT_FORMATTER), ruff: validateFormatter(l.ruff, DEFAULT_PYTHON_FORMATTER), black: validateFormatter(l.black, DEFAULT_PYTHON_FORMATTER), java: { diff --git a/src/platform/locales/en.json b/src/platform/locales/en.json index 5f0650214..ec63a61ef 100644 --- a/src/platform/locales/en.json +++ b/src/platform/locales/en.json @@ -1,4 +1,5 @@ { + "vcs.imageDiff.changedPixels": "{count, plural, one {# changed pixel} other {# changed pixels}}", "app.about.build": "Build", "app.about.configDir": "Configuration", "app.about.copyInfo": "Copy Info", @@ -190,6 +191,7 @@ "menu.editor.splitDown": "Split Down", "menu.editor.splitRight": "Split Right", "menu.editor.toggleZen": "{distractionFree, select, on {Exit Distraction Free Mode} other {Enter Distraction Free Mode}}", + "menu.view.toggleZenMode": "{zenMode, select, on {Exit Zen Mode} other {Enter Zen Mode}}", "menu.editor.unsplit": "Unsplit", "menu.file": "File", "menu.fileProperties": "File Properties", @@ -304,6 +306,7 @@ "menu.refactor.extractConstant": "Introduce Constant…", "menu.refactor.extractField": "Introduce Field…", "menu.refactor.extractInterface": "Extract Interface…", + "menu.refactor.extractTypeAlias": "Extract Type Alias…", "menu.refactor.extractMethod": "Extract Method…", "menu.refactor.extractParameter": "Introduce Parameter…", "menu.refactor.extractVariable": "Introduce Variable…", @@ -319,6 +322,7 @@ "menu.run.debug": "Debug", "menu.run.debugContext": "Debug Context Configuration", "menu.run.coverage": "Run with Coverage", + "menu.profiler.openSnapshot": "Open Profiler Snapshot…", "menu.run.profile": "Profile", "menu.coverage.hide": "Hide Coverage", "menu.debuggingActions": "Debugging Actions", diff --git a/src/platform/locales/es.json b/src/platform/locales/es.json index be1214fb5..dc294cbe4 100644 --- a/src/platform/locales/es.json +++ b/src/platform/locales/es.json @@ -157,6 +157,7 @@ "menu.editor.splitDown": "Dividir hacia abajo", "menu.editor.splitRight": "Dividir a la derecha", "menu.editor.toggleZen": "{distractionFree, select, on {Salir del modo sin distracciones} other {Entrar al modo sin distracciones}}", + "menu.view.toggleZenMode": "{zenMode, select, on {Salir del modo Zen} other {Entrar al modo Zen}}", "menu.editor.unsplit": "Quitar división", "menu.file": "Archivo", "menu.fileProperties": "Propiedades del archivo", diff --git a/src/platform/locales/fr.json b/src/platform/locales/fr.json index 0df85625b..6859aefef 100644 --- a/src/platform/locales/fr.json +++ b/src/platform/locales/fr.json @@ -156,6 +156,7 @@ "menu.editor.splitDown": "Scinder vers le bas", "menu.editor.splitRight": "Scinder vers la droite", "menu.editor.toggleZen": "{distractionFree, select, on {Quitter le mode sans distraction} other {Passer en mode sans distraction}}", + "menu.view.toggleZenMode": "{zenMode, select, on {Quitter le mode Zen} other {Passer en mode Zen}}", "menu.editor.unsplit": "Annuler la scission", "menu.file": "Fichier", "menu.fileProperties": "Propriétés du fichier", diff --git a/src/platform/locales/ko.json b/src/platform/locales/ko.json index 01be7dbb4..ede98d010 100644 --- a/src/platform/locales/ko.json +++ b/src/platform/locales/ko.json @@ -163,6 +163,7 @@ "menu.editor.splitDown": "아래로 분할", "menu.editor.splitRight": "오른쪽으로 분할", "menu.editor.toggleZen": "{distractionFree, select, on {집중력 분산 방지 모드 종료} other {집중력 분산 방지 모드 시작}}", + "menu.view.toggleZenMode": "{zenMode, select, on {Zen 모드 종료} other {Zen 모드 시작}}", "menu.editor.unsplit": "분할 해제", "menu.file": "파일", "menu.fileProperties": "파일 속성", diff --git a/src/platform/locales/pl.json b/src/platform/locales/pl.json index 089f6b153..e3e1f1e93 100644 --- a/src/platform/locales/pl.json +++ b/src/platform/locales/pl.json @@ -157,6 +157,7 @@ "menu.editor.splitDown": "Podziel w dół", "menu.editor.splitRight": "Podziel w prawo", "menu.editor.toggleZen": "{distractionFree, select, on {Wyjdź z trybu bez rozpraszaczy} other {Włącz tryb bez rozpraszaczy}}", + "menu.view.toggleZenMode": "{zenMode, select, on {Wyjdź z trybu Zen} other {Włącz tryb Zen}}", "menu.editor.unsplit": "Usuń podział", "menu.file": "Plik", "menu.fileProperties": "Właściwości pliku", diff --git a/src/platform/locales/pt.json b/src/platform/locales/pt.json index 8e5630b0f..68e10aa75 100644 --- a/src/platform/locales/pt.json +++ b/src/platform/locales/pt.json @@ -157,6 +157,7 @@ "menu.editor.splitDown": "Dividir para baixo", "menu.editor.splitRight": "Dividir à direita", "menu.editor.toggleZen": "{distractionFree, select, on {Sair do modo sem distrações} other {Entrar no modo sem distrações}}", + "menu.view.toggleZenMode": "{zenMode, select, on {Sair do modo Zen} other {Entrar no modo Zen}}", "menu.editor.unsplit": "Remover divisão", "menu.file": "Arquivo", "menu.fileProperties": "Propriedades do arquivo", diff --git a/src/platform/locales/ru.json b/src/platform/locales/ru.json index d80b64ac2..a7a953d74 100644 --- a/src/platform/locales/ru.json +++ b/src/platform/locales/ru.json @@ -190,6 +190,7 @@ "menu.editor.splitDown": "Разделить вниз", "menu.editor.splitRight": "Разделить вправо", "menu.editor.toggleZen": "{distractionFree, select, on {Выйти из режима без отвлекающих факторов} other {Войти в режим без отвлекающих факторов}}", + "menu.view.toggleZenMode": "{zenMode, select, on {Выйти из режима Zen} other {Войти в режим Zen}}", "menu.editor.unsplit": "Убрать разделение", "menu.file": "Файл", "menu.fileProperties": "Свойства файла", @@ -304,6 +305,7 @@ "menu.refactor.extractConstant": "Ввести константу…", "menu.refactor.extractField": "Ввести поле…", "menu.refactor.extractInterface": "Извлечь интерфейс…", + "menu.refactor.extractTypeAlias": "Извлечь псевдоним типа…", "menu.refactor.extractMethod": "Извлечь метод…", "menu.refactor.extractParameter": "Ввести параметр…", "menu.refactor.extractVariable": "Ввести переменную…", diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index c713ba529..4da81606d 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1,4 +1,21 @@ { + "No images to compare": "No images to compare", + "Image diff": "Image diff", + "Highlight changed pixels": "Highlight changed pixels", + "Changed pixels": "Changed pixels", + "Pixel difference mask": "Pixel difference mask", + "Pixel differences unavailable": "Pixel differences unavailable", + "Image dimensions exceed the pixel comparison limit": "Image dimensions exceed the pixel comparison limit", + "Compare revisions": "Compare revisions", + "Actual Size": "Actual Size", + "Fit to Window": "Fit to Window", + "View source diff": "View source diff", + "Image preview": "Image preview", + "No image on this side": "No image on this side", + "Additional arguments": "Additional arguments", + "Appended to the launch command. Quote values containing spaces.": "Appended to the launch command. Quote values containing spaces.", + "Reset additional arguments": "Reset additional arguments", + "Close the quoted argument before applying.": "Close the quoted argument before applying.", "Short Go error guards and case clauses": "Short Go error guards and case clauses", "Create function '{name}'": "Create function '{name}'", "Create class '{name}'": "Create class '{name}'", @@ -565,6 +582,8 @@ "Pinned": "Pinned", "Models": "Models", "Effort Level": "Effort Level", + "Fast": "Fast", + "Standard": "Standard", "Model settings": "Model settings", "Model settings: {summary}": "Model settings: {summary}", "Context Size": "Context Size", @@ -592,6 +611,11 @@ "Filter sessions": "Filter sessions", "Import {count}": "Import {count}", "Importing {done} of {total}…": "Importing {done} of {total}…", + "Fork {count}": "Fork {count}", + "Forking {done} of {total}…": "Forking {done} of {total}…", + "A session could not be forked": "A session could not be forked", + "Some sessions could not be forked": "Some sessions could not be forked", + "Fork into a new task": "Fork into a new task", "Only the 50 most recent sessions are shown.": "Only the 50 most recent sessions are shown.", "Some sessions could not be imported": "Some sessions could not be imported", "A session could not be imported": "A session could not be imported", @@ -1175,6 +1199,9 @@ "For web requests: the XDEBUG_SESSION cookie or query parameter; point xdebug.client_host at this machine when PHP runs in a container": "For web requests: the XDEBUG_SESSION cookie or query parameter; point xdebug.client_host at this machine when PHP runs in a container", "e.g. /var/www/html": "e.g. /var/www/html", "Listening for Xdebug on port {port}": "Listening for Xdebug on port {port}", + "Reconnect automatically": "Reconnect automatically", + "When the process restarts (nodemon, node --watch, tsx watch), attach to it again with the same breakpoints": "When the process restarts (nodemon, node --watch, tsx watch), attach to it again with the same breakpoints", + "Waiting to reconnect to Node.js on {address}": "Waiting to reconnect to Node.js on {address}", "Port {port} is already in use: another IDE or debug session may be listening on it. Stop it or choose another port.": "Port {port} is already in use: another IDE or debug session may be listening on it. Stop it or choose another port.", "Unable to load image: {path}": "Unable to load image: {path}", "Load image from {host}": "Load image from {host}", @@ -1832,6 +1859,16 @@ "Allowed when the plugin asked at first use. Remove it to be asked again.": "Allowed when the plugin asked at first use. Remove it to be asked again.", "Ask to connect to a host that is not on the list the first time it tries; you allow or refuse each host, and can revoke the allowed ones": "Ask to connect to a host that is not on the list the first time it tries; you allow or refuse each host, and can revoke the allowed ones", "This allows this exact host on any port; subdomains need separate permission.": "This allows this exact host on any port; subdomains need separate permission.", + "Enter a host (example.com) or a URL (https://example.com/).": "Enter a host (example.com) or a URL (https://example.com/).", + "This host comes from the plugin's “{key}” setting.": "This host comes from the plugin's “{key}” setting.", + "The connection is unencrypted HTTP: anyone on the network can read it.": "The connection is unencrypted HTTP: anyone on the network can read it.", + "Deny leaves the host unapproved; you can approve it any time in the plugin's permissions.": "Deny leaves the host unapproved; you can approve it any time in the plugin's permissions.", + "Allow unencrypted HTTP": "Allow unencrypted HTTP", + "The “{setting}” setting now holds {host}. Approve it to let the plugin connect.": "The “{setting}” setting now holds {host}. Approve it to let the plugin connect.", + "The “{setting}” setting now holds {host}. Approving connects over unencrypted HTTP.": "The “{setting}” setting now holds {host}. Approving connects over unencrypted HTTP.", + "The host set in the “{setting}” setting, on any port. Remove it to leave it unapproved.": "The host set in the “{setting}” setting, on any port. Remove it to leave it unapproved.", + "Could not approve the host of the {setting} setting for {name}": "Could not approve the host of the {setting} setting for {name}", + "Could not revoke the host of the {setting} setting for {name}": "Could not revoke the host of the {setting} setting for {name}", "Could not revoke {host} for {name}": "Could not revoke {host} for {name}", "host is not remembered for this plugin": "host is not remembered for this plugin", "URL must name one exact host": "URL must name one exact host", @@ -2649,6 +2686,17 @@ "Stop recording the page and open the profile": "Stop recording the page and open the profile", "Cannot record a CPU profile": "Cannot record a CPU profile", "No CPU profile to show": "No CPU profile to show", + "Open Snapshot…": "Open Snapshot…", + "Open Snapshot": "Open Snapshot", + "Open V8 .cpuprofile files saved by node --cpu-prof or Chrome DevTools in the Profiler": "Open V8 .cpuprofile files saved by node --cpu-prof or Chrome DevTools in the Profiler", + "Open in Profiler": "Open in Profiler", + "Open the selected .cpuprofile files as Profiler snapshots": "Open the selected .cpuprofile files as Profiler snapshots", + "This file is a V8 CPU profile": "This file is a V8 CPU profile", + "V8 CPU profile": "V8 CPU profile", + "Cannot open the CPU profile": "Cannot open the CPU profile", + "Closed older profiler snapshots": "Closed older profiler snapshots", + "The Profiler keeps the last {max} snapshots open; closed {names}.": "The Profiler keeps the last {max} snapshots open; closed {names}.", + "Profiler": "Profiler", "Opens the V8 .cpuprofile files of a directory as a snapshot (arg: { name, dir, root, profiler? }).": "Opens the V8 .cpuprofile files of a directory as a snapshot (arg: { name, dir, root, profiler? }).", "Show Only Matches": "Show Only Matches", "Docker Compose service {service}": "Docker Compose service {service}", @@ -2966,10 +3014,13 @@ "Interface name should differ from the class name": "Interface name should differ from the class name", "Select the members to form the interface": "Select the members to form the interface", "The class has no members to form an interface": "The class has no members to form an interface", - "Caret should be inside a class": "Caret should be inside a class", "Extract Interface from '{name}'": "Extract Interface from '{name}'", "The interface could not be extracted": "The interface could not be extracted", "Extract Interface is not supported for {name}": "Extract Interface is not supported for {name}", + "Extract Type Alias…": "Extract Type Alias…", + "Extract Type Alias is not supported for {name}": "Extract Type Alias is not supported for {name}", + "Selected block should represent a type": "Selected block should represent a type", + "Selected block should represent an object type": "Selected block should represent an object type", "Package for new interface": "Package for new interface", "Untitled files were not saved": "Untitled files were not saved", "Missing blank line between subject and body": "Missing blank line between subject and body", @@ -3594,6 +3645,7 @@ "Shelve Silently": "Shelve Silently", "Unshelve Silently": "Unshelve Silently", "Fold Lines Like This": "Fold Lines Like This", + "Pause Output": "Pause Output", "Remove All Watches": "Remove All Watches", "Not Cherry-Picked Commits": "Not Cherry-Picked Commits", "Show Branch Diff": "Show Branch Diff", @@ -3607,6 +3659,7 @@ "Stopped highlighting unpicked commits from '{source}' after the branch filter changed": "Stopped highlighting unpicked commits from '{source}' after the branch filter changed", "Checkout and Rebase": "Checkout and Rebase", "Checkout and Rebase onto Current": "Checkout and Rebase onto Current", + "Checkout and Update": "Checkout and Update", "Checkout and Rebase failed": "Checkout and Rebase failed", "Checkout and Rebase requires an existing commit": "Checkout and Rebase requires an existing commit", "Checked out and rebased '{branchName}'": "Checked out and rebased '{branchName}'", @@ -3815,6 +3868,13 @@ "Run Biome on save for enabled languages when it is the selected formatting provider.": "Run Biome on save for enabled languages when it is the selected formatting provider.", "Biome formatting failed": "Biome formatting failed", "Biome formatting timed out": "Biome formatting timed out", + "Reformat with dprint": "Reformat with dprint", + "dprint path": "dprint path", + "Automatic (projects with dprint)": "Automatic (projects with dprint)", + "dprint formats every file its plugins cover, before the other formatters, below a dprint configuration file (dprint.json, .dprint.json, dprint.jsonc) or installation, or when it is the selected provider. Other files keep their usual formatter.": "dprint formats every file its plugins cover, before the other formatters, below a dprint configuration file (dprint.json, .dprint.json, dprint.jsonc) or installation, or when it is the selected provider. Other files keep their usual formatter.", + "Run dprint on save for the files it formats. Format on save also runs it.": "Run dprint on save for the files it formats. Format on save also runs it.", + "dprint formatting failed": "dprint formatting failed", + "dprint formatting timed out": "dprint formatting timed out", "Loading preview…": "Loading preview…", "Left": "Left", "Result": "Result", @@ -4057,5 +4117,61 @@ "Dependencies changed since the last install": "Dependencies changed since the last install", "Run '{command}' in '{rel}' to install them.": "Run '{command}' in '{rel}' to install them.", "Run '{command}' to install them.": "Run '{command}' to install them.", - "Install Node.js Dependencies": "Install Node.js Dependencies" + "Install Node.js Dependencies": "Install Node.js Dependencies", + "Imports": "Imports", + "Class count to use import with '*'": "Class count to use import with '*'", + "Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports).": "Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports).", + "Class count to use import with *": "Class count to use import with *", + "Names count to use static import with '*'": "Names count to use static import with '*'", + "Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports).": "Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports).", + "Names count to use static import with *": "Names count to use static import with *", + "Watch for changes": "Watch for changes", + "Rerun Automatically": "Rerun Automatically", + "Debug runs the tests once, without watching.": "Debug runs the tests once, without watching.", + "Watch mode needs a command or script that ends with Jest or Vitest: the tests run once.\n": "Watch mode needs a command or script that ends with Jest or Vitest: the tests run once.\n", + "TypeScript Project Errors (tsc --watch)": "TypeScript Project Errors (tsc --watch)", + "Spaces": "Spaces", + "Punctuation": "Punctuation", + "After comma": "After comma", + "After semicolon in for statements": "After semicolon in for statements", + "Around binary operators": "Around binary operators", + "After control flow keywords": "After control flow keywords", + "After function keyword in anonymous functions": "After function keyword in anonymous functions", + "Before function declaration parentheses": "Before function declaration parentheses", + "After constructor keyword": "After constructor keyword", + "Within parentheses": "Within parentheses", + "Within brackets": "Within brackets", + "Within braces": "Within braces", + "Within empty braces": "Within empty braces", + "Within template string interpolations": "Within template string interpolations", + "Within JSX expressions": "Within JSX expressions", + "After type assertion": "After type assertion", + "Keep as is": "Keep as is", + "Use semicolons": "Use semicolons", + "Don't use semicolons": "Don't use semicolons", + "As in the file": "As in the file", + "Single quotes": "Single quotes", + "Double quotes": "Double quotes", + "Semicolons": "Semicolons", + "Quotes": "Quotes", + "For the strings and imports the TypeScript server adds.": "For the strings and imports the TypeScript server adds.", + "The TypeScript server applies Spaces and Punctuation to Reformat Code and to the code it adds: quick fixes, imports, refactorings and organize imports. Files below a Prettier, Biome or oxfmt configuration are formatted by that tool. A .editorconfig's quote_type and ij_* properties come first. TSX files use the TypeScript settings, JSX files the JavaScript ones.": "The TypeScript server applies Spaces and Punctuation to Reformat Code and to the code it adds: quick fixes, imports, refactorings and organize imports. Files below a Prettier, Biome or oxfmt configuration are formatted by that tool. A .editorconfig's quote_type and ij_* properties come first. TSX files use the TypeScript settings, JSX files the JavaScript ones.", + "Show Record View": "Show Record View", + "Open in Value Editor": "Open in Value Editor", + "Show Aggregate View": "Show Aggregate View", + "Data Extractor": "Data Extractor", + "Export Table to Clipboard": "Export Table to Clipboard", + "Keys": "Keys", + "Triggers": "Triggers", + "Filter by name or type": "Filter by name or type", + "Filter columns": "Filter columns", + "Package Registries": "Package Registries", + "Use only the configured package registries": "Use only the configured package registries", + "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).", + "SQL Updates": "SQL Updates", + "SQL Deletes": "SQL Deletes", + "Where Clause": "Where Clause", + "SQL INSERT": "SQL INSERT", + "SQL UPDATE": "SQL UPDATE", + "SQL DELETE": "SQL DELETE" } diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 8660cace4..80c772af3 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -110,6 +110,12 @@ "Move Caret Backward a Paragraph": "Mover el cursor un párrafo hacia atrás", "Move Caret Forward a Paragraph with Selection": "Mover el cursor un párrafo hacia adelante con selección", "Move Caret Backward a Paragraph with Selection": "Mover el cursor un párrafo hacia atrás con selección", + "Move Caret to Next Word in Different \"CamelHumps\" Mode": "Mover el cursor a la palabra siguiente en el otro modo \"CamelHumps\"", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode": "Mover el cursor a la palabra anterior en el otro modo \"CamelHumps\"", + "Move Caret to Next Word in Different \"CamelHumps\" Mode with Selection": "Mover el cursor a la palabra siguiente en el otro modo \"CamelHumps\" con selección", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode with Selection": "Mover el cursor a la palabra anterior en el otro modo \"CamelHumps\" con selección", + "Delete to Word Start in Different \"CamelHumps\" Mode": "Eliminar hasta el inicio de la palabra en el otro modo \"CamelHumps\"", + "Delete to Word End in Different \"CamelHumps\" Mode": "Eliminar hasta el final de la palabra en el otro modo \"CamelHumps\"", "Move Caret to Code Block End": "Mover cursor al final del bloque de código", "Clone Caret Above": "Clonar cursor arriba", "Clone Caret Below": "Clonar cursor abajo", @@ -3885,6 +3891,8 @@ "Process comments": "Procesar comentarios", "Distraction Free Mode": "Modo sin distracciones", "Exit Distraction Free Mode": "Salir del modo sin distracciones", + "Enter Zen Mode": "Entrar al modo Zen", + "Exit Zen Mode": "Salir del modo Zen", "Show Hidden Files": "Mostrar archivos ocultos", "Show Members": "Mostrar miembros", "Show Excluded Files": "Mostrar archivos excluidos", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index 2851bd8d3..331f5340e 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -66,6 +66,12 @@ "Move Caret Backward a Paragraph": "Déplacer le curseur d'un paragraphe vers l'arrière", "Move Caret Forward a Paragraph with Selection": "Déplacer le curseur d'un paragraphe vers l'avant avec sélection", "Move Caret Backward a Paragraph with Selection": "Déplacer le curseur d'un paragraphe vers l'arrière avec sélection", + "Move Caret to Next Word in Different \"CamelHumps\" Mode": "Déplacer le curseur au mot suivant dans l'autre mode « CamelHumps »", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode": "Déplacer le curseur au mot précédent dans l'autre mode « CamelHumps »", + "Move Caret to Next Word in Different \"CamelHumps\" Mode with Selection": "Déplacer le curseur au mot suivant dans l'autre mode « CamelHumps » avec sélection", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode with Selection": "Déplacer le curseur au mot précédent dans l'autre mode « CamelHumps » avec sélection", + "Delete to Word Start in Different \"CamelHumps\" Mode": "Supprimer jusqu'au début du mot dans l'autre mode « CamelHumps »", + "Delete to Word End in Different \"CamelHumps\" Mode": "Supprimer jusqu'à la fin du mot dans l'autre mode « CamelHumps »", "Move Caret to Code Block End": "Déplacer le curseur à la fin du bloc de code", "Clone Caret Above": "Dupliquer le curseur au-dessus", "Clone Caret Below": "Dupliquer le curseur en dessous", @@ -3759,6 +3765,8 @@ "Process comments": "Traiter les commentaires", "Distraction Free Mode": "Mode sans distraction", "Exit Distraction Free Mode": "Quitter le mode sans distraction", + "Enter Zen Mode": "Passer en mode Zen", + "Exit Zen Mode": "Quitter le mode Zen", "Show Hidden Files": "Afficher les fichiers masqués", "Show Members": "Afficher les membres", "Show Excluded Files": "Afficher les fichiers exclus", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index dd4f50e2d..d9da6430d 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -141,6 +141,12 @@ "Move Caret Backward a Paragraph": "캐럿을 이전 단락으로 이동", "Move Caret Forward a Paragraph with Selection": "선택 영역과 함께 캐럿을 다음 단락으로 이동", "Move Caret Backward a Paragraph with Selection": "선택 영역과 함께 캐럿을 이전 단락으로 이동", + "Move Caret to Next Word in Different \"CamelHumps\" Mode": "다른 \"CamelHumps\" 모드로 캐럿을 다음 단어로 이동", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode": "다른 \"CamelHumps\" 모드로 캐럿을 이전 단어로 이동", + "Move Caret to Next Word in Different \"CamelHumps\" Mode with Selection": "선택 영역과 함께 다른 \"CamelHumps\" 모드로 캐럿을 다음 단어로 이동", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode with Selection": "선택 영역과 함께 다른 \"CamelHumps\" 모드로 캐럿을 이전 단어로 이동", + "Delete to Word Start in Different \"CamelHumps\" Mode": "다른 \"CamelHumps\" 모드로 단어 시작까지 삭제", + "Delete to Word End in Different \"CamelHumps\" Mode": "다른 \"CamelHumps\" 모드로 단어 끝까지 삭제", "Move Caret to Code Block End": "캐럿을 코드 블록 끝부분으로 이동", "Clone Caret Above": "캐럿을 위에 복제", "Clone Caret Below": "캐럿을 아래에 복제", @@ -3945,6 +3951,8 @@ "Process comments": "주석 처리", "Distraction Free Mode": "집중력 분산 방지 모드", "Exit Distraction Free Mode": "집중력 분산 방지 모드 종료", + "Enter Zen Mode": "Zen 모드 시작", + "Exit Zen Mode": "Zen 모드 종료", "Show Hidden Files": "숨겨진 파일 표시", "Show Members": "멤버 표시", "Show Excluded Files": "제외된 파일 표시", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 6392674f2..b83b2d382 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -102,6 +102,12 @@ "Move Caret Backward a Paragraph": "Przesuń kursor o akapit do tyłu", "Move Caret Forward a Paragraph with Selection": "Przesuń kursor o akapit do przodu z zaznaczeniem", "Move Caret Backward a Paragraph with Selection": "Przesuń kursor o akapit do tyłu z zaznaczeniem", + "Move Caret to Next Word in Different \"CamelHumps\" Mode": "Przesuń kursor do następnego słowa w innym trybie \"CamelHumps\"", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode": "Przesuń kursor do poprzedniego słowa w innym trybie \"CamelHumps\"", + "Move Caret to Next Word in Different \"CamelHumps\" Mode with Selection": "Przesuń kursor do następnego słowa w innym trybie \"CamelHumps\" z zaznaczeniem", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode with Selection": "Przesuń kursor do poprzedniego słowa w innym trybie \"CamelHumps\" z zaznaczeniem", + "Delete to Word Start in Different \"CamelHumps\" Mode": "Usuń do początku słowa w innym trybie \"CamelHumps\"", + "Delete to Word End in Different \"CamelHumps\" Mode": "Usuń do końca słowa w innym trybie \"CamelHumps\"", "Move Caret to Code Block End": "Przesuń kursor na koniec bloku kodu", "Clone Caret Above": "Klonuj kursor powyżej", "Clone Caret Below": "Klonuj kursor poniżej", @@ -3852,6 +3858,8 @@ "Process comments": "Przetwarzaj komentarze", "Distraction Free Mode": "Tryb bez rozpraszania uwagi", "Exit Distraction Free Mode": "Wyjdź z trybu bez rozpraszania uwagi", + "Enter Zen Mode": "Włącz tryb Zen", + "Exit Zen Mode": "Wyjdź z trybu Zen", "Show Hidden Files": "Pokaż ukryte pliki", "Show Members": "Pokaż składowe", "Show Excluded Files": "Pokaż wykluczone pliki", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 1f3417820..26a1d9472 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -102,6 +102,12 @@ "Move Caret Backward a Paragraph": "Mover cursor um parágrafo para trás", "Move Caret Forward a Paragraph with Selection": "Mover cursor um parágrafo para a frente com seleção", "Move Caret Backward a Paragraph with Selection": "Mover cursor um parágrafo para trás com seleção", + "Move Caret to Next Word in Different \"CamelHumps\" Mode": "Mover cursor para a próxima palavra no outro modo \"CamelHumps\"", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode": "Mover cursor para a palavra anterior no outro modo \"CamelHumps\"", + "Move Caret to Next Word in Different \"CamelHumps\" Mode with Selection": "Mover cursor para a próxima palavra no outro modo \"CamelHumps\" com seleção", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode with Selection": "Mover cursor para a palavra anterior no outro modo \"CamelHumps\" com seleção", + "Delete to Word Start in Different \"CamelHumps\" Mode": "Excluir até o início da palavra no outro modo \"CamelHumps\"", + "Delete to Word End in Different \"CamelHumps\" Mode": "Excluir até o fim da palavra no outro modo \"CamelHumps\"", "Move Caret to Code Block End": "Mover cursor para o fim do bloco de código", "Clone Caret Above": "Clonar cursor acima", "Clone Caret Below": "Clonar cursor abaixo", @@ -3858,6 +3864,8 @@ "Process comments": "Processar comentários", "Distraction Free Mode": "Modo sem distrações", "Exit Distraction Free Mode": "Sair do modo sem distrações", + "Enter Zen Mode": "Entrar no modo Zen", + "Exit Zen Mode": "Sair do modo Zen", "Show Hidden Files": "Exibir arquivos ocultos", "Show Members": "Exibir membros", "Show Excluded Files": "Exibir arquivos excluídos", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index 39bf42b9f..8392637f0 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -1005,6 +1005,12 @@ "Move Caret Backward a Paragraph": "Переместить каретку на абзац назад", "Move Caret Forward a Paragraph with Selection": "Переместить каретку на абзац вперёд с выделением", "Move Caret Backward a Paragraph with Selection": "Переместить каретку на абзац назад с выделением", + "Move Caret to Next Word in Different \"CamelHumps\" Mode": "Переместить каретку к следующему слову в другом режиме \"CamelHumps\"", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode": "Переместить каретку к предыдущему слову в другом режиме \"CamelHumps\"", + "Move Caret to Next Word in Different \"CamelHumps\" Mode with Selection": "Переместить каретку к следующему слову в другом режиме \"CamelHumps\" с выделением", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode with Selection": "Переместить каретку к предыдущему слову в другом режиме \"CamelHumps\" с выделением", + "Delete to Word Start in Different \"CamelHumps\" Mode": "Удалить до начала слова в другом режиме \"CamelHumps\"", + "Delete to Word End in Different \"CamelHumps\" Mode": "Удалить до конца слова в другом режиме \"CamelHumps\"", "Move Caret to Code Block End": "Переместить каретку к концу блока кода", "Clone Caret Above": "Клонировать каретку выше", "Clone Caret Below": "Клонировать каретку ниже", @@ -3899,6 +3905,7 @@ "Hold Shift to Run, F4 to edit, Delete to remove": "Удерживайте Shift для запуска, F4 — для редактирования, Delete — для удаления", "Send EOF": "Отправить EOF", "Fold Lines Like This": "Свернуть похожие строки", + "Pause Output": "Приостановить вывод", "Collapse folded lines": "Сворачивать свернутые строки", "Close Tool Window Tab": "Закрыть вкладку окна инструментов", "No open files": "Нет открытых файлов", @@ -5288,6 +5295,8 @@ "Process comments": "Обрабатывать комментарии", "Distraction Free Mode": "Режим без отвлечения", "Exit Distraction Free Mode": "Выйти из режима без отвлечения", + "Enter Zen Mode": "Войти в режим Zen", + "Exit Zen Mode": "Выйти из режима Zen", "Show Hidden Files": "Показывать скрытые файлы", "Show Members": "Показывать члены", "Show Excluded Files": "Показывать исключённые файлы", @@ -5607,6 +5616,7 @@ "Stopped highlighting unpicked commits from '{source}' after the branch filter changed": "Подсветка неперенесённых коммитов из '{source}' остановлена после изменения фильтра веток", "Checkout and Rebase": "Переключиться и перебазировать", "Checkout and Rebase onto Current": "Переключиться и перебазировать на текущую", + "Checkout and Update": "Переключиться и обновить", "Checkout and Rebase failed": "Не удалось переключиться и перебазировать", "Checkout and Rebase requires an existing commit": "Для переключения и перебазирования требуется существующий коммит", "Checked out and rebased '{branchName}'": "Выполнено переключение и перебазирование '{branchName}'", @@ -9262,10 +9272,13 @@ "Interface name should differ from the class name": "Имя интерфейса должно отличаться от имени класса", "Select the members to form the interface": "Выберите члены для формирования интерфейса", "The class has no members to form an interface": "В классе нет членов для формирования интерфейса", - "Caret should be inside a class": "Каретка должна находиться внутри класса", "Extract Interface from '{name}'": "Извлечь интерфейс из '{name}'", "The interface could not be extracted": "Не удалось извлечь интерфейс", "Extract Interface is not supported for {name}": "Извлечение интерфейса не поддерживается для {name}", + "Extract Type Alias…": "Извлечь псевдоним типа…", + "Extract Type Alias is not supported for {name}": "Извлечение псевдонима типа не поддерживается для {name}", + "Selected block should represent a type": "Выбранный блок должен представлять тип", + "Selected block should represent an object type": "Выбранный блок должен представлять объектный тип", "Package for new interface": "Пакет для нового интерфейса", "Untitled files were not saved": "Безымянные файлы не были сохранены", "Missing blank line between subject and body": "Отсутствует пустая строка между заголовком и телом сообщения", @@ -10150,5 +10163,24 @@ "Allowed command pattern": "Шаблон разрешённой команды", "Blocked command pattern": "Шаблон заблокированной команды", "Mode applies to": "Режим действует для", - "Allow all optional permissions": "Разрешить все необязательные разрешения" + "Allow all optional permissions": "Разрешить все необязательные разрешения", + "Show Record View": "Показать представление записи", + "Open in Value Editor": "Открыть в редакторе значений", + "Show Aggregate View": "Показать агрегаты", + "Data Extractor": "Экстрактор данных", + "Export Table to Clipboard": "Экспортировать таблицу в буфер обмена", + "Keys": "Ключи", + "Triggers": "Триггеры", + "Filter by name or type": "Фильтр по имени или типу", + "Filter columns": "Фильтр столбцов", + "Package Registries": "Реестры пакетов", + "Use only the configured package registries": "Использовать только настроенные реестры пакетов", + "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "Для корпоративного реестра, например Nexus или Artifactory: при установке инструментов и агентов не выполняется повторная попытка через публичный реестр npm, если настроенный реестр отклонил пакет или не нашёл его, а сама IDE ничего не загружает из Maven Central, npm, PyPI или crates.io (JUnit Launcher, автодополнение версий зависимостей).", + "SQL Updates": "SQL-обновления", + "SQL Deletes": "SQL-удаления", + "Where Clause": "Условие WHERE", + "SQL INSERT": "SQL INSERT", + "SQL UPDATE": "SQL UPDATE", + "SQL DELETE": "SQL DELETE", + "Column comment": "Комментарий к столбцу" } diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 202045a3a..fdddd2daf 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -2272,10 +2272,13 @@ "Interface name should differ from the class name": "Arayüz adı sınıf adından farklı olmalıdır", "Select the members to form the interface": "Arayüzü oluşturacak üyeleri seçin", "The class has no members to form an interface": "Sınıfta arayüz oluşturacak üye bulunmuyor", - "Caret should be inside a class": "İmleç bir sınıfın içinde olmalıdır", "Extract Interface from '{name}'": "'{name}' Sınıfından Arayüz Çıkar", "The interface could not be extracted": "Arayüz çıkarılamadı", "Extract Interface is not supported for {name}": "{name} için Arayüz Çıkar desteklenmiyor", + "Extract Type Alias…": "Tür Takma Adı Çıkar…", + "Extract Type Alias is not supported for {name}": "{name} için Tür Takma Adı Çıkar desteklenmiyor", + "Selected block should represent a type": "Seçili blok bir türü temsil etmelidir", + "Selected block should represent an object type": "Seçili blok bir nesne türünü temsil etmelidir", "Package for new interface": "Yeni arayüzün paketi", "Untitled files were not saved": "Adsız dosyalar kaydedilmedi", "Missing blank line between subject and body": "Konu ile gövde arasında boş satır eksik", @@ -2754,6 +2757,7 @@ "Shelve Silently": "Bildirim Vermeden Rafa Al", "Unshelve Silently": "Bildirim Vermeden Raftan Çıkar", "Fold Lines Like This": "Buna Benzer Satırları Daralt", + "Pause Output": "Çıktıyı Duraklat", "Remove All Watches": "İzlenen Tüm İfadeleri Kaldır", "GitHub account": "GitHub hesabı", "Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "Etkin GitHub CLI hesabını kullanmak için boş bırakın. OpenIDEA tokeni başlatma sırasında çözümler ve saklamaz.", @@ -2907,6 +2911,12 @@ "Move Caret Backward a Paragraph": "İmleci Önceki Paragrafa Taşı", "Move Caret Forward a Paragraph with Selection": "Seçimle Sonraki Paragrafa Taşı", "Move Caret Backward a Paragraph with Selection": "Seçimle Önceki Paragrafa Taşı", + "Move Caret to Next Word in Different \"CamelHumps\" Mode": "Diğer “CamelHumps” Modunda Sonraki Sözcüğe Taşı", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode": "Diğer “CamelHumps” Modunda Önceki Sözcüğe Taşı", + "Move Caret to Next Word in Different \"CamelHumps\" Mode with Selection": "Diğer “CamelHumps” Modunda Seçimle Sonraki Sözcüğe Taşı", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode with Selection": "Diğer “CamelHumps” Modunda Seçimle Önceki Sözcüğe Taşı", + "Delete to Word Start in Different \"CamelHumps\" Mode": "Diğer “CamelHumps” Modunda Sözcük Başına Kadar Sil", + "Delete to Word End in Different \"CamelHumps\" Mode": "Diğer “CamelHumps” Modunda Sözcük Sonuna Kadar Sil", "Move Caret to Code Block End": "İmleci Kod Bloğunun Sonuna Taşı", "Clone Caret Above": "İmleci Üste Çoğalt", "Clone Caret Below": "İmleci Alta Çoğalt", @@ -6548,6 +6558,8 @@ "Process comments": "Yorumları işle", "Distraction Free Mode": "Dikkat Dağıtmayan Mod", "Exit Distraction Free Mode": "Dikkat Dağıtmayan Moddan Çık", + "Enter Zen Mode": "Zen Moduna Geç", + "Exit Zen Mode": "Zen Modundan Çık", "Show Hidden Files": "Gizli Dosyaları Göster", "Show Members": "Üyeleri Göster", "Show Excluded Files": "Hariç Tutulan Dosyaları Göster", @@ -8812,5 +8824,24 @@ "Allowed command pattern": "İzin verilen komut kalıbı", "Blocked command pattern": "Engellenen komut kalıbı", "Mode applies to": "Modun uygulandığı yer", - "Allow all optional permissions": "Tüm isteğe bağlı izinlere izin ver" + "Allow all optional permissions": "Tüm isteğe bağlı izinlere izin ver", + "Show Record View": "Kayıt Görünümünü Göster", + "Open in Value Editor": "Değer Düzenleyicide Aç", + "Show Aggregate View": "Toplam Görünümünü Göster", + "Data Extractor": "Veri Çıkarıcı", + "Export Table to Clipboard": "Tabloyu Panoya Aktar", + "Keys": "Anahtarlar", + "Triggers": "Tetikleyiciler", + "Filter by name or type": "Ada veya türe göre filtrele", + "Filter columns": "Sütunları filtrele", + "Package Registries": "Paket Kayıt Defterleri", + "Use only the configured package registries": "Yalnızca yapılandırılmış paket kayıt defterlerini kullan", + "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "Nexus veya Artifactory gibi bir şirket kayıt defteri için: araçlar ve ajanlar yüklenirken yapılandırılmış kayıt defteri bir paketi reddederse ya da bulamazsa genel npm kayıt defterinde yeniden denenmez ve IDE kendisi Maven Central, npm, PyPI veya crates.io'dan hiçbir şey indirmez (JUnit başlatıcısı, bağımlılık sürümü tamamlama).", + "SQL Updates": "SQL Güncelleme İfadeleri", + "SQL Deletes": "SQL Silme İfadeleri", + "Where Clause": "WHERE Koşulu", + "SQL INSERT": "SQL INSERT", + "SQL UPDATE": "SQL UPDATE", + "SQL DELETE": "SQL DELETE", + "Column comment": "Sütun yorumu" } diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index a41f21375..054ab9fa3 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -693,6 +693,8 @@ "Scroll to Center": "捲動到中央", "Scroll Up": "向上捲動", "Scroll Down": "向下捲動", + "Scroll Up and Move if Necessary": "向上捲動並在必要時移動游標", + "Scroll Down and Move if Necessary": "向下捲動並在必要時移動游標", "Scroll to Top": "捲動到頂部", "Scroll to Bottom": "捲動到底部", "Move Caret to Page Top": "將游標移至頁面頂部", @@ -704,6 +706,12 @@ "Move Caret Backward a Paragraph": "將游標移至上一段落", "Move Caret Forward a Paragraph with Selection": "將游標移至下一段落並選擇", "Move Caret Backward a Paragraph with Selection": "將游標移至上一段落並選擇", + "Move Caret to Next Word in Different \"CamelHumps\" Mode": "以另一種「駝峰」模式將游標移至下一個單字", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode": "以另一種「駝峰」模式將游標移至上一個單字", + "Move Caret to Next Word in Different \"CamelHumps\" Mode with Selection": "以另一種「駝峰」模式將游標移至下一個單字並選擇", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode with Selection": "以另一種「駝峰」模式將游標移至上一個單字並選擇", + "Delete to Word Start in Different \"CamelHumps\" Mode": "以另一種「駝峰」模式刪除至單字開頭", + "Delete to Word End in Different \"CamelHumps\" Mode": "以另一種「駝峰」模式刪除至單字結尾", "Move Caret to Code Block End": "將游標移至程式碼塊末尾", "Clone Caret Above": "在上方新增游標", "Clone Caret Below": "在下方新增游標", @@ -3468,6 +3476,7 @@ "Hold Shift to Run, F4 to edit, Delete to remove": "按住 Shift 執行,F4 編輯,Delete 刪除", "Send EOF": "傳送 EOF", "Fold Lines Like This": "摺疊與此類似的行", + "Pause Output": "暫停輸出", "Collapse folded lines": "摺疊行", "Close Tool Window Tab": "關閉工具視窗分頁", "No open files": "沒有開啟的檔案", @@ -4841,6 +4850,8 @@ "Process comments": "處理註解", "Distraction Free Mode": "無干擾模式", "Exit Distraction Free Mode": "結束無干擾模式", + "Enter Zen Mode": "進入 Zen 模式", + "Exit Zen Mode": "結束 Zen 模式", "Show Hidden Files": "顯示隱藏檔案", "Show Members": "顯示成員", "Show Excluded Files": "顯示已排除的檔案", @@ -8725,10 +8736,13 @@ "Interface name should differ from the class name": "介面名稱應與類別名稱不同", "Select the members to form the interface": "選擇形成介面的成員", "The class has no members to form an interface": "該類別沒有可形成介面的成員", - "Caret should be inside a class": "游標應位於類別中", "Extract Interface from '{name}'": "從 '{name}' 提取介面", "The interface could not be extracted": "無法提取介面", "Extract Interface is not supported for {name}": "{name} 不支援提取介面", + "Extract Type Alias…": "提取型別別名…", + "Extract Type Alias is not supported for {name}": "{name} 不支援提取型別別名", + "Selected block should represent a type": "所選程式碼區塊應為一個型別", + "Selected block should represent an object type": "所選程式碼區塊應為一個物件型別", "Package for new interface": "新介面的軟體包", "Untitled files were not saved": "未命名檔案未儲存", "Missing blank line between subject and body": "主題和正文之間缺少空行", @@ -9350,5 +9364,24 @@ "Allowed command pattern": "允許的命令模式", "Blocked command pattern": "封鎖的命令模式", "Mode applies to": "模式作用範圍", - "Allow all optional permissions": "允許全部可選權限" + "Allow all optional permissions": "允許全部可選權限", + "Show Record View": "顯示記錄檢視", + "Open in Value Editor": "在值編輯器中開啟", + "Show Aggregate View": "顯示彙總檢視", + "Data Extractor": "資料擷取器", + "Export Table to Clipboard": "將表格匯出到剪貼簿", + "Keys": "鍵", + "Triggers": "觸發器", + "Filter by name or type": "依名稱或類型篩選", + "Filter columns": "篩選欄", + "Package Registries": "套件倉庫", + "Use only the configured package registries": "僅使用已設定的套件倉庫", + "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "適用於 Nexus、Artifactory 等公司倉庫:安裝工具和 agent 時,若已設定的倉庫拒絕或找不到某個套件,不再改從公開 npm 倉庫重試;IDE 本身也不會從 Maven Central、npm、PyPI 或 crates.io 取得任何內容(JUnit 啟動器、相依版本補全)。", + "SQL Updates": "SQL Update 陳述式", + "SQL Deletes": "SQL Delete 陳述式", + "Where Clause": "Where 子句", + "SQL INSERT": "SQL INSERT 陳述式", + "SQL UPDATE": "SQL UPDATE 陳述式", + "SQL DELETE": "SQL DELETE 陳述式", + "Column comment": "欄位註解" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index e8798cc0b..9c33706b1 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1,4 +1,16 @@ { + "No images to compare": "没有可比较的图像", + "Image diff": "图像差异", + "Highlight changed pixels": "高亮显示更改的像素", + "Changed pixels": "已更改的像素", + "Pixel difference mask": "像素差异掩码", + "Pixel differences unavailable": "无法显示像素差异", + "Image dimensions exceed the pixel comparison limit": "图像尺寸超出像素比较限制", + "Compare revisions": "比较修订版本", + "Fit to Window": "适应窗口", + "View source diff": "查看源代码差异", + "Image preview": "图像预览", + "No image on this side": "此侧无图像", "Short Go error guards and case clauses": "简短的 Go 错误检查和 case 分支", "Create function '{name}'": "创建函数 '{name}'", "Create class '{name}'": "创建类 '{name}'", @@ -256,6 +268,24 @@ "Use Driver": "使用驱动程序", "Custom JDBC": "自定义 JDBC", "Data source type:": "数据源类型:", + "DuckDB": "DuckDB", + "In memory": "内存", + "JDBC URL": "JDBC URL", + "Passed to the DuckDB JDBC driver as connection properties.": "这些连接属性将传递给 DuckDB JDBC 驱动。", + "Database File": "数据库文件", + "New DuckDB Database": "新建 DuckDB 数据库", + "Open DuckDB Database": "打开 DuckDB 数据库", + "Add the official DuckDB JDBC JAR in Manage Drivers… to connect.": "请在“管理驱动…”中添加官方 DuckDB JDBC JAR 文件以连接数据库。", + "Select a DuckDB driver profile or add the official DuckDB JDBC JAR in Manage Drivers…": "请选择 DuckDB 驱动配置,或在“管理驱动…”中添加官方 DuckDB JDBC JAR 文件。", + "path/to/database.duckdb": "path/to/database.duckdb", + "New File…": "新建文件…", + "Read-only requires an existing database file.": "只读连接需要现有的数据库文件。", + "Creates the database on first connection if the file does not exist.": "如果文件不存在,首次连接时会创建数据库。", + "Turn off Read-only in Options to use an in-memory DuckDB database.": "请在“选项”中关闭“只读”以使用内存 DuckDB 数据库。", + "In-memory DuckDB databases require write access.": "内存 DuckDB 数据库需要写入权限。", + "Enter an absolute database path or a path relative to the open project.": "请输入数据库的绝对路径,或相对于当前项目的路径。", + "DuckDB database paths cannot contain semicolons.": "DuckDB 数据库路径不能包含分号。", + "Data is discarded when the connection closes.": "连接关闭时将丢弃数据。", "Connection driver": "连接驱动", "Built-in": "内置", "Custom JDBC only": "仅用于自定义 JDBC", @@ -466,6 +496,8 @@ "Unpin model": "取消置顶模型", "Models": "模型", "Effort Level": "思考强度", + "Fast": "快速", + "Standard": "标准", "Model settings": "模型设置", "Model settings: {summary}": "模型设置:{summary}", "Context Size": "上下文大小", @@ -1022,6 +1054,8 @@ "Scroll to Center": "滚动到中央", "Scroll Up": "向上滚动", "Scroll Down": "向下滚动", + "Scroll Up and Move if Necessary": "向上滚动并在必要时移动光标", + "Scroll Down and Move if Necessary": "向下滚动并在必要时移动光标", "Scroll to Top": "滚动到顶部", "Scroll to Bottom": "滚动到底部", "Move Caret to Page Top": "将光标移至页面顶部", @@ -1033,6 +1067,12 @@ "Move Caret Backward a Paragraph": "将光标移至上一段落", "Move Caret Forward a Paragraph with Selection": "将光标移至下一段落并选择", "Move Caret Backward a Paragraph with Selection": "将光标移至上一段落并选择", + "Move Caret to Next Word in Different \"CamelHumps\" Mode": "以另一种“驼峰”模式将光标移至下一个单词", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode": "以另一种“驼峰”模式将光标移至上一个单词", + "Move Caret to Next Word in Different \"CamelHumps\" Mode with Selection": "以另一种“驼峰”模式将光标移至下一个单词并选择", + "Move Caret to Previous Word in Different \"CamelHumps\" Mode with Selection": "以另一种“驼峰”模式将光标移至上一个单词并选择", + "Delete to Word Start in Different \"CamelHumps\" Mode": "以另一种“驼峰”模式删除到单词开头", + "Delete to Word End in Different \"CamelHumps\" Mode": "以另一种“驼峰”模式删除到单词结尾", "Move Caret to Code Block End": "将光标移至代码块末尾", "Clone Caret Above": "在上方添加光标", "Clone Caret Below": "在下方添加光标", @@ -3339,6 +3379,11 @@ "Filter sessions": "过滤会话", "Import {count}": "导入 {count} 个", "Importing {done} of {total}…": "正在导入 {done}/{total}…", + "Fork {count}": "Fork {count} 个", + "Forking {done} of {total}…": "正在 Fork {done}/{total}…", + "A session could not be forked": "一个会话无法 Fork", + "Some sessions could not be forked": "部分会话无法 Fork", + "Fork into a new task": "Fork 为新任务", "Only the 50 most recent sessions are shown.": "仅显示最近的 50 个会话。", "Some sessions could not be imported": "部分会话无法导入", "A session could not be imported": "有一个会话无法导入", @@ -3996,6 +4041,7 @@ "Hold Shift to Run, F4 to edit, Delete to remove": "按住 Shift 运行,F4 编辑,Delete 删除", "Send EOF": "发送 EOF", "Fold Lines Like This": "折叠与此类似的行", + "Pause Output": "暂停输出", "Collapse folded lines": "折叠行", "Close Tool Window Tab": "关闭工具窗口标签页", "No open files": "没有打开的文件", @@ -5055,6 +5101,9 @@ "For web requests: the XDEBUG_SESSION cookie or query parameter; point xdebug.client_host at this machine when PHP runs in a container": "对于 Web 请求:设置 XDEBUG_SESSION cookie 或查询参数;当 PHP 运行在容器中时,将 xdebug.client_host 指向本机", "e.g. /var/www/html": "例如 /var/www/html", "Listening for Xdebug on port {port}": "正在端口 {port} 上监听 Xdebug", + "Reconnect automatically": "自动重新连接", + "When the process restarts (nodemon, node --watch, tsx watch), attach to it again with the same breakpoints": "进程重启时(nodemon、node --watch、tsx watch)以相同的断点重新附加", + "Waiting to reconnect to Node.js on {address}": "正在等待重新连接到 {address} 上的 Node.js", "Port {port} is already in use: another IDE or debug session may be listening on it. Stop it or choose another port.": "端口 {port} 已被占用:可能有其他 IDE 或调试会话正在监听。请停止它或选择其他端口。", "Copied": "已复制", "'{name}' can only be debugged": "'{name}' 只能调试", @@ -5258,6 +5307,12 @@ "Scene": "场景", "Main scene": "主场景", "Godot command line options, e.g. --debug-collisions": "Godot 命令行选项,例如 --debug-collisions", + "Unreal Engine": "Unreal Engine", + "Unreal": "Unreal 项目", + "Unreal · engine not found": "Unreal · 未找到引擎", + "Open an Unreal Engine project in the editor, or in game mode": "用编辑器打开 Unreal Engine 项目,或以游戏模式运行", + "…/Game.uproject": "…/Game.uproject", + "e.g. -game": "例如 -game", "Bookmark description": "书签描述", "Cannot open {path}": "无法打开 {path}", "Search context": "搜索上下文", @@ -5386,6 +5441,8 @@ "Process comments": "处理注释", "Distraction Free Mode": "无干扰模式", "Exit Distraction Free Mode": "退出无干扰模式", + "Enter Zen Mode": "进入 Zen 模式", + "Exit Zen Mode": "退出 Zen 模式", "Show Hidden Files": "显示隐藏文件", "Show Members": "显示成员", "Show Excluded Files": "显示已排除的文件", @@ -5705,6 +5762,7 @@ "Stopped highlighting unpicked commits from '{source}' after the branch filter changed": "分支筛选已更改,停止高亮 '{source}' 中未拣选的提交", "Checkout and Rebase": "签出并变基", "Checkout and Rebase onto Current": "签出并变基到当前分支", + "Checkout and Update": "签出并更新", "Checkout and Rebase failed": "签出并变基失败", "Checkout and Rebase requires an existing commit": "签出并变基需要已有提交", "Checked out and rebased '{branchName}'": "已签出并变基 '{branchName}'", @@ -7235,6 +7293,19 @@ "Passed as --filter: a test name or a regular expression": "作为 --filter 传入:测试名称或正则表达式", "PHPUnit options": "PHPUnit 选项", "e.g. --stop-on-failure --testsuite unit": "例如 --stop-on-failure --testsuite unit", + "Run Cypress tests": "运行 Cypress 测试", + "Cypress project directory": "Cypress 项目目录", + "Testing type": "测试类型", + "End-to-end": "端到端", + "Component": "组件", + "Passed as --browser: a browser name or the path to its executable": "作为 --browser 传入:浏览器名称或其可执行文件路径", + "Specs": "Spec 文件", + "e.g. cypress/e2e/**/*.cy.ts": "例如 cypress/e2e/**/*.cy.ts", + "Passed as --spec: files or globs, comma separated; empty runs every spec": "作为 --spec 传入:文件或 glob,以逗号分隔;留空则运行全部 spec", + "Cypress options": "Cypress 选项", + "e.g. --headed --config video=true": "例如 --headed --config video=true", + "Cypress ran the whole spec file": "Cypress 运行了整个 spec 文件", + "Cypress can select tests by name only through a grep plugin such as @cypress/grep, which this project doesn't depend on: every test of the spec ran.": "Cypress 只能通过 @cypress/grep 等 grep 插件按名称选择测试,而本项目没有依赖这类插件:spec 中的所有测试都运行了。", "CLI Interpreter": "CLI 解释器", "PHP interpreter": "PHP 解释器", "Runs PHP scripts, PHPUnit, Composer and artisan, and the PHP-based language servers (phpactor). Its folder is put first on PATH, so vendor/bin/phpunit and other #!/usr/bin/env php scripts use it too.": "运行 PHP 脚本、PHPUnit、Composer 和 artisan,以及基于 PHP 的语言服务器(phpactor)。其所在文件夹会被置于 PATH 最前,因此 vendor/bin/phpunit 等 #!/usr/bin/env php 脚本也会使用它。", @@ -8375,6 +8446,16 @@ "Allowed when the plugin asked at first use. Remove it to be asked again.": "在插件首次使用询问时允许。移除后下次会再次询问。", "Ask to connect to a host that is not on the list the first time it tries; you allow or refuse each host, and can revoke the allowed ones": "首次连接清单之外的主机时询问;你可以逐个允许或拒绝,并可撤销已允许的主机", "This allows this exact host on any port; subdomains need separate permission.": "允许此确切主机的任意端口;子域名需要单独授权。", + "Enter a host (example.com) or a URL (https://example.com/).": "请输入主机名(example.com)或 URL(https://example.com/)。", + "This host comes from the plugin's “{key}” setting.": "此主机来自插件的「{key}」设置。", + "The connection is unencrypted HTTP: anyone on the network can read it.": "连接是未加密的 HTTP:网络上的任何人都可能读取它。", + "Deny leaves the host unapproved; you can approve it any time in the plugin's permissions.": "拒绝后主机保持未批准;你可以随时在插件权限中批准。", + "Allow unencrypted HTTP": "允许未加密 HTTP", + "The “{setting}” setting now holds {host}. Approve it to let the plugin connect.": "「{setting}」设置现在为 {host}。批准后插件才能连接。", + "The “{setting}” setting now holds {host}. Approving connects over unencrypted HTTP.": "「{setting}」设置现在为 {host}。批准后将以未加密 HTTP 连接。", + "The host set in the “{setting}” setting, on any port. Remove it to leave it unapproved.": "「{setting}」设置中的主机,任意端口。移除后保持未批准。", + "Could not approve the host of the {setting} setting for {name}": "无法为 {name} 批准 {setting} 设置的主机", + "Could not revoke the host of the {setting} setting for {name}": "无法为 {name} 撤销 {setting} 设置的主机", "Could not revoke {host} for {name}": "无法撤销 {name} 对 {host} 的授权", "host is not remembered for this plugin": "此插件没有记住该主机的授权", "URL must name one exact host": "URL 必须指定一个确切主机", @@ -8583,6 +8664,9 @@ "Letters, digits, dashes and underscores only; names the agent file.": "仅限字母、数字、短横线和下划线;用作 Agent 文件名。", "my-agent": "my-agent", "Separate arguments with spaces; quote ones containing spaces.": "用空格分隔参数;含空格的参数请加引号。", + "Appended to the launch command. Quote values containing spaces.": "附加到启动命令末尾;含空格的参数请加引号。", + "Reset additional arguments": "重置附加参数", + "Close the quoted argument before applying.": "请在应用前补全参数的引号。", "Select acp.json": "选择 acp.json", "ACP config": "ACP 配置", "An Angular app from the Angular CLI.": "用 Angular CLI 创建的 Angular 应用。", @@ -9091,6 +9175,16 @@ "Stop recording the page and open the profile": "停止记录页面并打开性能分析结果", "Cannot record a CPU profile": "无法记录 CPU 性能分析", "No CPU profile to show": "没有可显示的 CPU 性能分析", + "Open Snapshot…": "打开快照…", + "Open Snapshot": "打开快照", + "Open V8 .cpuprofile files saved by node --cpu-prof or Chrome DevTools in the Profiler": "在性能分析器中打开由 node --cpu-prof 或 Chrome DevTools 保存的 V8 .cpuprofile 文件", + "Open in Profiler": "在性能分析器中打开", + "Open the selected .cpuprofile files as Profiler snapshots": "将选中的 .cpuprofile 文件作为性能分析快照打开", + "This file is a V8 CPU profile": "此文件是 V8 CPU 性能分析文件", + "V8 CPU profile": "V8 CPU 性能分析文件", + "Cannot open the CPU profile": "无法打开 CPU 性能分析文件", + "Closed older profiler snapshots": "已关闭较早的性能分析快照", + "The Profiler keeps the last {max} snapshots open; closed {names}.": "性能分析器只保留最近 {max} 个快照;已关闭 {names}。", "Opens the V8 .cpuprofile files of a directory as a snapshot (arg: { name, dir, root, profiler? }).": "将目录中的 V8 .cpuprofile 文件作为快照打开(参数:{ name, dir, root, profiler? })。", "Show Only Matches": "仅显示匹配项", "Docker Compose service {service}": "Docker Compose 服务 {service}", @@ -9394,10 +9488,13 @@ "Interface name should differ from the class name": "接口名称应与类名不同", "Select the members to form the interface": "选择形成接口的成员", "The class has no members to form an interface": "该类没有可形成接口的成员", - "Caret should be inside a class": "光标应位于类中", "Extract Interface from '{name}'": "从 '{name}' 提取接口", "The interface could not be extracted": "无法提取接口", "Extract Interface is not supported for {name}": "{name} 不支持提取接口", + "Extract Type Alias…": "提取类型别名…", + "Extract Type Alias is not supported for {name}": "{name} 不支持提取类型别名", + "Selected block should represent a type": "所选代码块应为一个类型", + "Selected block should represent an object type": "所选代码块应为一个对象类型", "Package for new interface": "新接口的软件包", "Untitled files were not saved": "未命名文件未保存", "Missing blank line between subject and body": "主题和正文之间缺少空行", @@ -10130,6 +10227,13 @@ "Run Biome on save for enabled languages when it is the selected formatting provider.": "对已启用的语言,在选择 Biome 作为格式化工具时于保存时运行。", "Biome formatting failed": "Biome 格式化失败", "Biome formatting timed out": "Biome 格式化超时", + "Reformat with dprint": "使用 dprint 重新格式化", + "dprint path": "dprint 路径", + "Automatic (projects with dprint)": "自动(使用 dprint 的项目)", + "dprint formats every file its plugins cover, before the other formatters, below a dprint configuration file (dprint.json, .dprint.json, dprint.jsonc) or installation, or when it is the selected provider. Other files keep their usual formatter.": "在 dprint 配置文件(dprint.json、.dprint.json、dprint.jsonc)或安装所在目录之下,或选择 dprint 作为格式化工具时,dprint 先于其他格式化工具格式化其插件覆盖的所有文件。其他文件仍使用原来的格式化工具。", + "Run dprint on save for the files it formats. Format on save also runs it.": "保存时对 dprint 格式化的文件运行 dprint。「保存时格式化」也会运行它。", + "dprint formatting failed": "dprint 格式化失败", + "dprint formatting timed out": "dprint 格式化超时", "Loading preview…": "正在加载预览…", "16 unchanged lines": "16 行未变更", "Create exception breakpoint on {name}": "在 {name} 上创建异常断点", @@ -10450,5 +10554,70 @@ "Dependencies changed since the last install": "依赖在上次安装后有变化", "Run '{command}' in '{rel}' to install them.": "在 '{rel}' 中运行 '{command}' 安装依赖。", "Run '{command}' to install them.": "运行 '{command}' 安装依赖。", - "Install Node.js Dependencies": "安装 Node.js 依赖" + "Install Node.js Dependencies": "安装 Node.js 依赖", + "{title} needs the Java agent of {pluginName}": "{title} 需要 {pluginName} 的 Java 代理", + "Allow the java.agent permission of {pluginName} in Settings › Plugins, then try again.": "请在 设置 › 插件 中允许 {pluginName} 的 java.agent 权限,然后重试。", + "Cannot run '{name}' with {title}": "无法使用 {title} 运行 '{name}'", + "Plugin Java agents load only into JVMs started on this machine. Choose “Local machine” under “Run on”.": "插件的 Java 代理只加载到本机启动的 JVM 中。请在“运行于”中选择“本地计算机”。", + "Run '{name}' with {title}": "使用 {title} 运行 '{name}'", + "Debug '{name}' with {title}": "使用 {title} 调试 '{name}'", + "Run with {title}": "使用 {title} 运行", + "Debug with {title}": "使用 {title} 调试", + "Launches the selected configuration with the Java agent of {pluginName}": "使用 {pluginName} 的 Java 代理启动所选配置", + "Class count to use import with '*'": "使用通配符导入的类数", + "Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports).": "当同一个包使用达到该数量的类时使用通配符导入;默认为 5,999 表示始终保留单类导入。", + "Class count to use import with *": "使用通配符导入的类数", + "Names count to use static import with '*'": "使用通配符静态导入的名称数", + "Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports).": "静态导入的名称达到该数量时使用通配符静态导入;默认为 3,999 表示始终保留单条导入。", + "Names count to use static import with *": "使用通配符静态导入的名称数", + "Watch for changes": "监视更改", + "Rerun Automatically": "自动重新运行", + "Debug runs the tests once, without watching.": "调试时测试只运行一次,不监视更改。", + "Watch mode needs a command or script that ends with Jest or Vitest: the tests run once.\n": "监视模式要求命令或脚本以 Jest 或 Vitest 结尾:测试只运行一次。\n", + "TypeScript Project Errors (tsc --watch)": "TypeScript 项目错误(tsc --watch)", + "Spaces": "空格", + "Punctuation": "标点", + "After comma": "逗号后", + "After semicolon in for statements": "for 语句中的分号后", + "Around binary operators": "二元运算符两侧", + "After control flow keywords": "控制流关键字后", + "After function keyword in anonymous functions": "匿名函数的 function 关键字后", + "Before function declaration parentheses": "函数声明括号前", + "After constructor keyword": "constructor 关键字后", + "Within parentheses": "圆括号内", + "Within brackets": "方括号内", + "Within braces": "花括号内", + "Within empty braces": "空花括号内", + "Within template string interpolations": "模板字符串插值内", + "Within JSX expressions": "JSX 表达式内", + "After type assertion": "类型断言后", + "Keep as is": "保持原样", + "Use semicolons": "使用分号", + "Don't use semicolons": "不使用分号", + "As in the file": "与文件一致", + "Single quotes": "单引号", + "Double quotes": "双引号", + "Semicolons": "分号", + "Quotes": "引号", + "For the strings and imports the TypeScript server adds.": "用于 TypeScript 服务器添加的字符串和导入。", + "The TypeScript server applies Spaces and Punctuation to Reformat Code and to the code it adds: quick fixes, imports, refactorings and organize imports. Files below a Prettier, Biome or oxfmt configuration are formatted by that tool. A .editorconfig's quote_type and ij_* properties come first. TSX files use the TypeScript settings, JSX files the JavaScript ones.": "TypeScript 服务器将空格和标点设置用于重新格式化代码,以及它添加的代码:快速修复、导入、重构和优化导入。位于 Prettier、Biome 或 oxfmt 配置之下的文件由该工具格式化。.editorconfig 的 quote_type 和 ij_* 属性优先。TSX 文件使用 TypeScript 设置,JSX 文件使用 JavaScript 设置。", + "Show Record View": "显示记录视图", + "Open in Value Editor": "在值编辑器中打开", + "Show Aggregate View": "显示聚合视图", + "Data Extractor": "数据提取器", + "Export Table to Clipboard": "将表导出到剪贴板", + "Keys": "键", + "Triggers": "触发器", + "Filter by name or type": "按名称或类型过滤", + "Filter columns": "过滤列", + "Package Registries": "包仓库", + "Use only the configured package registries": "仅使用已配置的包仓库", + "For a company registry such as Nexus or Artifactory: installing tools and agents never retries against the public npm registry when the configured one refuses or misses a package, and the IDE fetches nothing from Maven Central, npm, PyPI or crates.io itself (the JUnit launcher, dependency version completion).": "适用于 Nexus、Artifactory 等公司仓库:安装工具和 agent 时,若已配置的仓库拒绝或找不到某个包,不再改从公共 npm 仓库重试;IDE 自身也不会从 Maven Central、npm、PyPI 或 crates.io 获取任何内容(JUnit 启动器、依赖版本补全)。", + "SQL Updates": "SQL Update 语句", + "SQL Deletes": "SQL Delete 语句", + "Where Clause": "Where 子句", + "SQL INSERT": "SQL INSERT 语句", + "SQL UPDATE": "SQL UPDATE 语句", + "SQL DELETE": "SQL DELETE 语句", + "Column comment": "列注释" } diff --git a/src/platform/locales/textCatalog.test.ts b/src/platform/locales/textCatalog.test.ts index 1065619a8..680c14ecf 100644 --- a/src/platform/locales/textCatalog.test.ts +++ b/src/platform/locales/textCatalog.test.ts @@ -97,7 +97,9 @@ const UNTRANSLATED = new Set<string>([ "Prettier", "oxfmt", "Biome", + "dprint", "Ruff", + "Cypress", "IntelliJ IDEA", "GitHub", "PHPStan", @@ -111,6 +113,7 @@ const UNTRANSLATED = new Set<string>([ "Edge", "Safari", "Firefox", + "Electron", "JaCoCo", // Docker run target placeholder values "compose.yaml", diff --git a/src/platform/locales/tr.json b/src/platform/locales/tr.json index dca0ab663..9f7822414 100644 --- a/src/platform/locales/tr.json +++ b/src/platform/locales/tr.json @@ -188,6 +188,7 @@ "menu.editor.splitDown": "Aşağı Böl", "menu.editor.splitRight": "Sağa Böl", "menu.editor.toggleZen": "{distractionFree, select, on {Dikkat Dağıtmayan Moddan Çık} other {Dikkat Dağıtmayan Moda Geç}}", + "menu.view.toggleZenMode": "{zenMode, select, on {Zen Modundan Çık} other {Zen Moduna Geç}}", "menu.editor.unsplit": "Bölmeyi Kaldır", "menu.file": "Dosya", "menu.fileProperties": "Dosya Özellikleri", @@ -301,6 +302,7 @@ "menu.refactor.extractConstant": "Sabit Tanımla…", "menu.refactor.extractField": "Alan Tanımla…", "menu.refactor.extractInterface": "Arayüz Çıkar…", + "menu.refactor.extractTypeAlias": "Tür Takma Adı Çıkar…", "menu.refactor.extractMethod": "Metot Çıkar…", "menu.refactor.extractParameter": "Parametre Tanımla…", "menu.refactor.extractVariable": "Değişken Tanımla…", diff --git a/src/platform/locales/zh-TW.json b/src/platform/locales/zh-TW.json index b480d73cf..204fccd04 100644 --- a/src/platform/locales/zh-TW.json +++ b/src/platform/locales/zh-TW.json @@ -188,6 +188,7 @@ "menu.editor.splitDown": "向下拆分", "menu.editor.splitRight": "向右拆分", "menu.editor.toggleZen": "{distractionFree, select, on {結束無干擾模式} other {進入無干擾模式}}", + "menu.view.toggleZenMode": "{zenMode, select, on {結束 Zen 模式} other {進入 Zen 模式}}", "menu.editor.unsplit": "取消拆分", "menu.file": "檔案", "menu.fileProperties": "檔案屬性", @@ -301,6 +302,7 @@ "menu.refactor.extractConstant": "引入常量…", "menu.refactor.extractField": "引入欄位…", "menu.refactor.extractInterface": "提取介面…", + "menu.refactor.extractTypeAlias": "提取型別別名…", "menu.refactor.extractMethod": "提取方法…", "menu.refactor.extractParameter": "引入參數…", "menu.refactor.extractVariable": "引入變數…", diff --git a/src/platform/locales/zh.json b/src/platform/locales/zh.json index 6598c4fa0..d94d624b1 100644 --- a/src/platform/locales/zh.json +++ b/src/platform/locales/zh.json @@ -1,4 +1,5 @@ { + "vcs.imageDiff.changedPixels": "{count} 个像素发生更改", "app.about.build": "构建", "app.about.configDir": "配置目录", "app.about.copyInfo": "复制信息", @@ -190,6 +191,7 @@ "menu.editor.splitDown": "向下拆分", "menu.editor.splitRight": "向右拆分", "menu.editor.toggleZen": "{distractionFree, select, on {退出无干扰模式} other {进入无干扰模式}}", + "menu.view.toggleZenMode": "{zenMode, select, on {退出 Zen 模式} other {进入 Zen 模式}}", "menu.editor.unsplit": "取消拆分", "menu.file": "文件", "menu.fileProperties": "文件属性", @@ -304,6 +306,7 @@ "menu.refactor.extractConstant": "引入常量…", "menu.refactor.extractField": "引入字段…", "menu.refactor.extractInterface": "提取接口…", + "menu.refactor.extractTypeAlias": "提取类型别名…", "menu.refactor.extractMethod": "提取方法…", "menu.refactor.extractParameter": "引入参数…", "menu.refactor.extractVariable": "引入变量…", @@ -319,6 +322,7 @@ "menu.run.debug": "调试", "menu.run.debugContext": "调试上下文配置", "menu.run.coverage": "使用覆盖率运行", + "menu.profiler.openSnapshot": "打开性能分析快照…", "menu.run.profile": "性能分析", "menu.coverage.hide": "隐藏覆盖率", "menu.debuggingActions": "调试操作", diff --git a/src/ui/List.test.tsx b/src/ui/List.test.tsx index fca715eac..c06e9932e 100644 --- a/src/ui/List.test.tsx +++ b/src/ui/List.test.tsx @@ -103,6 +103,25 @@ describe("List", () => { expect(options()[0]).toHaveAttribute("aria-selected", "true"); }); + it("keeps a visible hovered row in place and still scrolls to keyboard selections", () => { + const rows = Array.from({ length: 40 }, (_, i) => `Item ${i}`); + render(<List items={rows} getKey={(r) => r} renderItem={(r) => r} rowHeight={20} hoverSelects />); + const list = screen.getByRole("listbox"); + Object.defineProperty(list, "clientHeight", { value: 200 }); + Object.defineProperty(list, "scrollHeight", { value: 800 }); + list.scrollTop = 20; + fireEvent.scroll(list); + // A browser can move the viewport before delivering the corresponding scroll event. + list.scrollTop = 0; + const scroll = vi.spyOn(list, "scrollTo"); + const hovered = screen.getByRole("option", { name: "Item 4" }); + fireEvent.pointerMove(hovered); + expect(hovered).toHaveAttribute("aria-selected", "true"); + expect(scroll).not.toHaveBeenCalled(); + fireEvent.keyDown(list, { key: "End" }); + expect(scroll).toHaveBeenCalledOnce(); + }); + it("highlights matched characters in rows", () => { renderList(); const first = screen.getAllByRole("option")[0]!; diff --git a/src/ui/List.tsx b/src/ui/List.tsx index dc46d24af..e582d98a1 100644 --- a/src/ui/List.tsx +++ b/src/ui/List.tsx @@ -169,7 +169,13 @@ export function List<T>({ const viewportHeight = virtualizer.scrollRect?.height; useEffect(() => { - if (active >= 0 && active < items.length) virtualizer.scrollToIndex(active, { align: "auto" }); + if (active < 0 || active >= items.length) return; + const viewport = scrollRef.current; + const row = virtualizer.getVirtualItems().find((item) => item.index === active); + // The browser can scroll before the virtualizer receives the new offset. + if (viewport && row && row.start >= viewport.scrollTop && row.end <= viewport.scrollTop + viewport.clientHeight) + return; + virtualizer.scrollToIndex(active, { align: "auto" }); }, [active, items.length, viewportHeight, virtualizer]); // Options are virtualised: expose position / count of selectable rows (or the table row index) diff --git a/src/ui/expui/actions/rerunAutomatically.svg b/src/ui/expui/actions/rerunAutomatically.svg new file mode 100644 index 000000000..c14a2fa50 --- /dev/null +++ b/src/ui/expui/actions/rerunAutomatically.svg @@ -0,0 +1,7 @@ +<!-- Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. --> +<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path fill-rule="evenodd" clip-rule="evenodd" d="M9 9.50215C9 8.32441 10.2951 7.60608 11.2942 8.22967L15.2962 10.7275C16.2372 11.3149 16.2372 12.6851 15.2962 13.2725L11.2942 15.7703C10.2951 16.3939 9 15.6756 9 14.4978V9.50215ZM10.7647 9.07799C10.4317 8.87013 10 9.10957 10 9.50215V14.4978C10 14.8904 10.4317 15.1298 10.7647 14.922L14.7667 12.4241C15.0804 12.2284 15.0804 11.7716 14.7667 11.5758L10.7647 9.07799Z" fill="#208A3C"/> +<path d="M10 9.50226C10 9.10968 10.4317 8.87024 10.7647 9.0781L14.7667 11.5759C15.0804 11.7717 15.0804 12.2285 14.7667 12.4243L10.7647 14.9221C10.4317 15.13 10 14.8905 10 14.4979V9.50226Z" fill="#F2FCF3"/> +<path d="M10.5 2C10.2239 2 10 2.22386 10 2.5V3.08902C9.99986 3.09587 9.99986 3.10271 10 3.10954V5.5C10 5.77614 10.2239 6 10.5 6C10.7761 6 11 5.77614 11 5.5V3.99951C12.215 4.91216 13 6.36471 13 7.99998C13 8.03829 12.9996 8.07651 12.9987 8.11462L13.958 8.71338C13.9857 8.47944 14 8.24138 14 7.99998C14 5.91232 12.9337 4.0744 11.3177 3H13.5C13.7761 3 14 2.77614 14 2.5C14 2.22386 13.7761 2 13.5 2H10.5Z" fill="#6C707E"/> +<path d="M6 10.5C6 10.2239 5.77614 10 5.5 10C5.22386 10 5 10.2239 5 10.5V12.0004C3.78495 11.0878 3 9.63525 3 7.99998C3 5.54954 4.76326 3.50989 7.09033 3.08244C7.36193 3.03255 7.54166 2.77193 7.49177 2.50033C7.44188 2.22873 7.18127 2.049 6.90967 2.09889C4.1165 2.61195 2 5.05827 2 7.99998C2 10.0877 3.06633 11.9256 4.68238 13H2.5C2.22386 13 2 13.2239 2 13.5C2 13.7761 2.22386 14 2.5 14H5.5C5.77614 14 6 13.7761 6 13.5V12.911C6.00014 12.9041 6.00014 12.8972 6 12.8904V10.5Z" fill="#6C707E"/> +</svg> diff --git a/src/ui/expui/actions/rerunAutomatically_dark.svg b/src/ui/expui/actions/rerunAutomatically_dark.svg new file mode 100644 index 000000000..519ac9f65 --- /dev/null +++ b/src/ui/expui/actions/rerunAutomatically_dark.svg @@ -0,0 +1,7 @@ +<!-- Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. --> +<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> +<path fill-rule="evenodd" clip-rule="evenodd" d="M9 9.50215C9 8.32441 10.2951 7.60608 11.2942 8.22967L15.2962 10.7275C16.2372 11.3149 16.2372 12.6851 15.2962 13.2725L11.2942 15.7703C10.2951 16.3939 9 15.6756 9 14.4978V9.50215ZM10.7647 9.07799C10.4317 8.87013 10 9.10957 10 9.50215V14.4978C10 14.8904 10.4317 15.1298 10.7647 14.922L14.7667 12.4241C15.0804 12.2284 15.0804 11.7716 14.7667 11.5758L10.7647 9.07799Z" fill="#57965C"/> +<path d="M10 9.50226C10 9.10968 10.4317 8.87024 10.7647 9.0781L14.7667 11.5759C15.0804 11.7717 15.0804 12.2285 14.7667 12.4243L10.7647 14.9221C10.4317 15.13 10 14.8905 10 14.4979V9.50226Z" fill="#253627"/> +<path d="M10.5 2C10.2239 2 10 2.22386 10 2.5V3.08902C9.99986 3.09587 9.99986 3.10271 10 3.10954V5.5C10 5.77614 10.2239 6 10.5 6C10.7761 6 11 5.77614 11 5.5V3.99951C12.215 4.91216 13 6.36471 13 7.99998C13 8.03829 12.9996 8.07651 12.9987 8.11462L13.958 8.71338C13.9857 8.47944 14 8.24138 14 7.99998C14 5.91232 12.9337 4.0744 11.3177 3H13.5C13.7761 3 14 2.77614 14 2.5C14 2.22386 13.7761 2 13.5 2H10.5Z" fill="#CED0D6"/> +<path d="M6 10.5C6 10.2239 5.77614 10 5.5 10C5.22386 10 5 10.2239 5 10.5V12.0004C3.78495 11.0878 3 9.63525 3 7.99998C3 5.54954 4.76326 3.50989 7.09033 3.08244C7.36193 3.03255 7.54166 2.77193 7.49177 2.50033C7.44188 2.22873 7.18127 2.049 6.90967 2.09889C4.1165 2.61195 2 5.05827 2 7.99998C2 10.0877 3.06633 11.9256 4.68238 13H2.5C2.22386 13 2 13.2239 2 13.5C2 13.7761 2.22386 14 2.5 14H5.5C5.77614 14 6 13.7761 6 13.5V12.911C6.00014 12.9041 6.00014 12.8972 6 12.8904V10.5Z" fill="#CED0D6"/> +</svg> diff --git a/src/ui/focusScope.ts b/src/ui/focusScope.ts index f67a111d6..c0a3ae0b6 100644 --- a/src/ui/focusScope.ts +++ b/src/ui/focusScope.ts @@ -10,6 +10,13 @@ const FOCUS_SCOPE_ATTR = "data-focus-scope"; export const FOCUS_ACTIVE_ATTR = "data-focus-active"; +let markCurrent: ((target: Element | null) => void) | null = null; + +/** Updates the active focus scope marks for `target` (e.g. a focused plugin iframe). */ +export function syncFocusScope(target: Element | null) { + markCurrent?.(target); +} + /** Marks the scopes holding focus. Returns an uninstaller that clears the marks. */ export function installFocusScopeTracking(): () => void { let active: Element[] = []; @@ -22,11 +29,23 @@ export function installFocusScopeTracking(): () => void { for (const el of chain) el.setAttribute(FOCUS_ACTIVE_ATTR, ""); active = chain; }; + markCurrent = mark; const onFocusIn = (e: FocusEvent) => mark(e.target instanceof Element ? e.target : null); + const checkIframe = () => { + const el = document.activeElement; + if (el instanceof HTMLIFrameElement && document.hasFocus()) mark(el); + }; + const onWindowBlur = () => { + checkIframe(); + queueMicrotask(checkIframe); + }; document.addEventListener("focusin", onFocusIn); + window.addEventListener("blur", onWindowBlur); mark(document.activeElement); return () => { + if (markCurrent === mark) markCurrent = null; document.removeEventListener("focusin", onFocusIn); + window.removeEventListener("blur", onWindowBlur); for (const el of active) el.removeAttribute(FOCUS_ACTIVE_ATTR); active = []; }; diff --git a/src/ui/icons.test.tsx b/src/ui/icons.test.tsx index da9cca521..ff9556e0e 100644 --- a/src/ui/icons.test.tsx +++ b/src/ui/icons.test.tsx @@ -196,6 +196,13 @@ describe("fileIconName", () => { ["schema.graphql", "file-graphql"], ["api.proto", "file-proto"], ["main.go", "file-go"], + ["cart_test.go", "file-go-test"], + // Only what `go test` builds as a test file: case-sensitive, not a file it ignores (`_…`, `.…`). + ["Cart_TEST.go", "file-go"], + ["_test.go", "file-go"], + [".cart_test.go", "file-go"], + ["test.go", "file-go"], + ["cart_test.go.tmpl", "file-go"], ["page.gotmpl", "file-go"], ["message.tmpl", "file-go"], ["docker-stack.yaml.go.tmpl", "file-go"], diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index 009ea9776..5898f8634 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -170,6 +170,7 @@ const ICONS = { "file-fsharp": "openidea/fileTypes/fsharp", "file-swift": "fileTypes/swiftLang", "file-go": "openidea/fileTypes/go", + "file-go-test": "openidea/fileTypes/goTest", "file-gomod": "openidea/fileTypes/goMod", "file-gowork": "openidea/fileTypes/goWork", "file-rust": "fileTypes/rust", @@ -438,6 +439,7 @@ const ICONS = { "db-sqlite": "openidea/database/sqlite", "db-postgres": "openidea/database/postgres", "db-clickhouse": "openidea/database/clickhouse", + "db-duckdb": "openidea/database/duckdb", "db-mysql": "openidea/database/mysql", "db-sqlserver": "openidea/database/sqlserver", "db-oracle": "openidea/database/oracle", @@ -511,6 +513,7 @@ const ICONS = { "gutter-javadoc-edit": "gutter/javadocEdit", stop: "run/stop", rerun: "run/rerun", + "rerun-automatically": "actions/rerunAutomatically", "hot-reload": "openidea/general/hotReload", "rerun-filled": "run/rerun_stroke", "restart-debug": "run/restartDebug", @@ -1173,7 +1176,8 @@ const EXT_ICONS = table({ "file-jsp": "jsp jspx jspf jsph tag tagf tagx", "file-freemarker": "ftl ftlh ftlx", "file-astro": "astro", - "file-json": "json jsonc json5 jsonl ndjson geojson topojson webmanifest har avsc code-workspace code-snippets map", + "file-json": + "json jsonc json5 jsonl ndjson geojson topojson webmanifest har avsc code-workspace code-snippets map uproject uplugin", "file-md": "md mdx markdown mdown mkd mkdn mdwn ronn workbook", "file-word": "doc docx rtf odt", "file-pdf": "pdf", @@ -1319,6 +1323,8 @@ export function fileIconName(fileName: string, path: string | null = null): Icon } const themed = fileIconTheme?.file(fileName, path); if (themed) return themed as IconName; + // A file `go test` builds as a test: the name is case-sensitive, and `_…` / `.…` files are ignored. + if (/^[^._].*_test\.go$/.test(fileName)) return "file-go-test"; const lower = fileName.toLowerCase(); const named = FILE_NAMES[lower] ?? NAME_PATTERNS.find(([re]) => re.test(lower))?.[1]; if (named) return named; diff --git a/src/ui/openidea/database/duckdb.svg b/src/ui/openidea/database/duckdb.svg new file mode 100644 index 000000000..85dd6cda7 --- /dev/null +++ b/src/ui/openidea/database/duckdb.svg @@ -0,0 +1,5 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500" fill="none"> + <path fill="#1a1a1a" d="M249.9996737,500C111.9320267,500,0,388.068425,0,250.0000251,0,111.9318259,111.3637372,0,249.9996737,0,388.6367145,0,500,111.9318259,500,250.0000251c0,138.0683999-111.9317506,249.9999749-250.0003263,249.9999749Z"/> + <path fill="#fff100" d="M190.0545045,146.5907724c-56.8184727,0-103.4089829,46.5908427-103.4089829,103.4092276,0,57.3868501,46.5905102,103.4092401,103.4089829,103.4092401,56.8183974,0,103.4091523-46.5908552,103.4091523-103.4092401s-46.5907549-103.4092401-103.4091523-103.4092276Z"/> + <path fill="#fff100" d="M376.1380597,212.7835876h-49.1467777v74.432875h49.1467777c20.5540155,0,37.2164375-16.6623467,37.2164375-37.2164375v-.0000753c0-20.5540155-16.662422-37.2163622-37.2164375-37.2163622Z"/> +</svg> diff --git a/src/ui/openidea/database/duckdb_dark.svg b/src/ui/openidea/database/duckdb_dark.svg new file mode 100644 index 000000000..c0154a04a --- /dev/null +++ b/src/ui/openidea/database/duckdb_dark.svg @@ -0,0 +1,5 @@ +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 500" fill="none"> + <path fill="#fff100" d="M249.9996737,500C111.9320267,500,0,388.068425,0,250.0000251,0,111.9318259,111.3637372,0,249.9996737,0,388.6367145,0,500,111.9318259,500,250.0000251c0,138.0683999-111.9317506,249.9999749-250.0003263,249.9999749Z"/> + <path fill="#1d1d1b" d="M190.0545045,146.5907724c-56.8184727,0-103.4089829,46.5908427-103.4089829,103.4092276,0,57.3868501,46.5905102,103.4092401,103.4089829,103.4092401,56.8183974,0,103.4091523-46.5908552,103.4091523-103.4092401s-46.5907549-103.4092401-103.4091523-103.4092276Z"/> + <path fill="#1d1d1b" d="M376.1380597,212.7835876h-49.1467777v74.432875h49.1467777c20.5540155,0,37.2164375-16.6623467,37.2164375-37.2164375v-.0000753c0-20.5540155-16.662422-37.2163622-37.2164375-37.2163622Z"/> +</svg> diff --git a/src/ui/openidea/fileTypes/goTest.svg b/src/ui/openidea/fileTypes/goTest.svg new file mode 100644 index 000000000..71ff2bf7c --- /dev/null +++ b/src/ui/openidea/fileTypes/goTest.svg @@ -0,0 +1,7 @@ +<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> +<ellipse cx="3.1" cy="8.6" rx="1" ry="0.8" fill="#C8946A"/><ellipse cx="12.9" cy="8.6" rx="1" ry="0.8" fill="#C8946A"/><ellipse cx="5.4" cy="14.3" rx="1.1" ry="0.7" fill="#C8946A"/><ellipse cx="10.6" cy="14.3" rx="1.1" ry="0.7" fill="#C8946A"/> +<path d="M3.6 3.4L3.7 1.1L5.5 2.2C6.2 1.8 7.1 1.6 8 1.6C8.9 1.6 9.8 1.8 10.5 2.2L12.3 1.1L12.4 3.4C12.8 4.1 13 4.9 13 5.8V11.2C13 13.2 10.9 14.6 8 14.6C5.1 14.6 3 13.2 3 11.2V5.8C3 4.9 3.2 4.1 3.6 3.4Z" fill="#3C7FE6"/> +<circle cx="6" cy="5.4" r="1.7" fill="white"/><circle cx="10" cy="5.4" r="1.7" fill="white"/><circle cx="6" cy="5.5" r="0.7" fill="#1E1F22"/><circle cx="10" cy="5.5" r="0.7" fill="#1E1F22"/> +<ellipse cx="8" cy="7.5" rx="0.9" ry="0.6" fill="#1E1F22"/><path d="M7.3 8H8.7V8.9C8.7 9.1 8.5 9.2 8.4 9.2H7.6C7.4 9.2 7.3 9.1 7.3 8.9V8Z" fill="white"/> +<g transform="translate(7.5 7.5) scale(0.5625)"><circle cx="8" cy="8" r="7" fill="#FFF7F7" stroke="#DB3B4B" stroke-width="1.78"/><path d="M8.46217 11.5H9.46061V10.5943H8.59311C8.26575 10.5943 8.02023 10.3488 8.02023 10.0214V6.81878H9.46061L9.46606 5.91309H8.02023V4.5H7.07635V5.44934C7.07635 5.72214 6.88539 5.91309 6.6126 5.91309H5.90878L5.90332 6.81878H6.9836L6.98906 10.1142C6.98906 10.9108 7.61104 11.5 8.46217 11.5Z" fill="#DB3B4B"/></g> +</svg> diff --git a/src/ui/openidea/fileTypes/goTest_dark.svg b/src/ui/openidea/fileTypes/goTest_dark.svg new file mode 100644 index 000000000..c97cd3fff --- /dev/null +++ b/src/ui/openidea/fileTypes/goTest_dark.svg @@ -0,0 +1,7 @@ +<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> +<ellipse cx="3.1" cy="8.6" rx="1" ry="0.8" fill="#D6A67E"/><ellipse cx="12.9" cy="8.6" rx="1" ry="0.8" fill="#D6A67E"/><ellipse cx="5.4" cy="14.3" rx="1.1" ry="0.7" fill="#D6A67E"/><ellipse cx="10.6" cy="14.3" rx="1.1" ry="0.7" fill="#D6A67E"/> +<path d="M3.6 3.4L3.7 1.1L5.5 2.2C6.2 1.8 7.1 1.6 8 1.6C8.9 1.6 9.8 1.8 10.5 2.2L12.3 1.1L12.4 3.4C12.8 4.1 13 4.9 13 5.8V11.2C13 13.2 10.9 14.6 8 14.6C5.1 14.6 3 13.2 3 11.2V5.8C3 4.9 3.2 4.1 3.6 3.4Z" fill="#5D95F0"/> +<circle cx="6" cy="5.4" r="1.7" fill="white"/><circle cx="10" cy="5.4" r="1.7" fill="white"/><circle cx="6" cy="5.5" r="0.7" fill="#1E1F22"/><circle cx="10" cy="5.5" r="0.7" fill="#1E1F22"/> +<ellipse cx="8" cy="7.5" rx="0.9" ry="0.6" fill="#1E1F22"/><path d="M7.3 8H8.7V8.9C8.7 9.1 8.5 9.2 8.4 9.2H7.6C7.4 9.2 7.3 9.1 7.3 8.9V8Z" fill="white"/> +<g transform="translate(7.5 7.5) scale(0.5625)"><circle cx="8" cy="8" r="7" fill="#402929" stroke="#DB5C5C" stroke-width="1.78"/><path d="M8.46217 11.5H9.46061V10.5943H8.59311C8.26575 10.5943 8.02023 10.3488 8.02023 10.0214V6.81878H9.46061L9.46606 5.91309H8.02023V4.5H7.07635V5.44934C7.07635 5.72214 6.88539 5.91309 6.6126 5.91309H5.90878L5.90332 6.81878H6.9836L6.98906 10.1142C6.98906 10.9108 7.61104 11.5 8.46217 11.5Z" fill="#DB5C5C"/></g> +</svg> diff --git a/src/ui/projectType.ts b/src/ui/projectType.ts index 081decf8d..37b03d8b7 100644 --- a/src/ui/projectType.ts +++ b/src/ui/projectType.ts @@ -36,6 +36,8 @@ export const PROJECT_TYPES = { godot: { name: "Godot", icon: "file-godot", markers: ["project.godot"] }, cmake: { name: "CMake", icon: "file-cmake", markers: ["CMakeLists.txt"] }, make: { name: "Make", icon: "file-makefile", markers: ["Makefile", "makefile", "GNUmakefile"] }, + // Before .NET: the `.sln` a UE project generates belongs to the project, not to C#. + unreal: { name: "Unreal Engine", icon: "file-cpp", markers: [/^[^/]+\.uproject$/i] }, dotnet: { name: ".NET", icon: "file-csharp", markers: [/^[^/]+\.(?:[cf]sproj|slnx?)$/i] }, } as const satisfies Record<string, ProjectTypeDefinition>; diff --git a/src/workbench/TitleBar.test.tsx b/src/workbench/TitleBar.test.tsx index c33f9f5b9..3dbc1d699 100644 --- a/src/workbench/TitleBar.test.tsx +++ b/src/workbench/TitleBar.test.tsx @@ -44,7 +44,11 @@ describe("title bar gear menu", () => { expect(keymap.map((i) => i.label)).toContain("Mine"); expect(keymap.filter((i) => i.checked).map((i) => i.label)).toEqual(["macOS"]); // View Mode only switches the existing modes. - expect((items[7] as Sub).submenu.map((i) => i.action)).toEqual(["editor.toggleZen", "window.toggleFullScreen"]); + expect((items[7] as Sub).submenu.map((i) => i.action)).toEqual([ + "editor.toggleZen", + "view.toggleZenMode", + "window.toggleFullScreen", + ]); }); it("lists every widget with a checkbox in Customize Main Toolbar", () => { diff --git a/src/workbench/activate.ts b/src/workbench/activate.ts index 46f1fc5e8..dcd374ba3 100644 --- a/src/workbench/activate.ts +++ b/src/workbench/activate.ts @@ -16,6 +16,7 @@ import { } from "./contributions"; import { installBrowserGuards } from "./browserGuards"; import { installDistractionFree } from "./distractionFree"; +import { installZenMode } from "./zenMode"; import { installNarrowWindow } from "./narrowWindow"; import { installFileDrop } from "./fileDrop"; import { installFocusTracking } from "./focus"; @@ -78,6 +79,7 @@ export function activateWorkbench(): () => void { installToolWindowActions(), installToolWindowLayoutSync(), installDistractionFree(), + installZenMode(), installNarrowWindow(), installFocusTracking(setFocusedToolWindow), installFocusScopeTracking(), diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index 364b2cc2d..c815d5b1f 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -170,6 +170,11 @@ export interface EditorKindContribution { onClose?(input: EditorInput): void; /** The input that shows this tab where it is now when Back returns to it, e.g. a diff at its caret. */ navigationInput?(input: EditorInput): EditorInput; + /** + * Whether Back/Forward can still navigate to this input (`open`: a tab with its key is open). + * Defaults to true; return false to skip deleted tasks or closed ephemeral sessions. + */ + canNavigate?(input: EditorInput, open: boolean): boolean; /** * "Open in New Window" on its tabs: moves the tab to a lightweight window of this project * (`EditorService.openInWindow`) with whatever state it carries. False when it stayed here. @@ -305,6 +310,8 @@ export interface ServiceProviderContribution { /** Toolbar buttons for a selected node of this provider. */ actions?(item: ServiceTreeItem): ServiceItemAction[]; menu?(item: ServiceTreeItem): MenuItem[]; + /** The service a node stands for, as other contributors see it (plugins' Services menus); null for groups. */ + context?(item: ServiceTreeItem): ServiceContext | null; /** Double click / Enter. */ activate?(item: ServiceTreeItem): void; /** Jump to Source (F4 / ⌘↓); a provider without it activates the node instead. */ @@ -323,6 +330,43 @@ export interface ServiceProviderContribution { reorder?: TreeReorder<ServiceTreeItem>; } +/** A selected Services node as contributors outside its provider see it. */ +export interface ServiceContext { + /** The provider's id: `run`, `docker`. */ + provider: string; + /** Stable within the provider: a run configuration's id, a container's id. */ + id: string; + /** `spring-boot`, `application`, … (a run configuration's kind), `docker-container`. */ + kind: string; + name: string; + running: boolean; + /** When a run configuration backs the service. */ + runConfigurationId?: string; +} + +/** + * Entries other features add to the Services tree's context menu and toolbar for the + * selected services (all of which have a {@link ServiceContext}). + */ +export interface ServiceSelectionContribution { + id: string; + menu?(services: ServiceContext[]): MenuItem[]; + actions?(services: ServiceContext[]): ServiceItemAction[]; +} + +const serviceSelectionItems = new Map<string, ServiceSelectionContribution>(); + +export function registerServiceSelectionItems(c: ServiceSelectionContribution): () => void { + serviceSelectionItems.set(c.id, c); + return () => { + if (serviceSelectionItems.get(c.id) === c) serviceSelectionItems.delete(c.id); + }; +} + +export function serviceSelectionContributions(): ServiceSelectionContribution[] { + return [...serviceSelectionItems.values()].sort((a, b) => a.id.localeCompare(b.id)); +} + export const useServiceProviders = create<{ providers: Map<string, ServiceProviderContribution> }>(() => ({ providers: new Map(), })); @@ -1743,6 +1787,13 @@ export interface RunExecutorContribution { supports(config: RunConfig): boolean; /** Plans the launch; null when it can't run (the executor has said why). */ prepare(config: RunConfig): Promise<ExecutorLaunch | null>; + /** + * The launch starts under the debugger (a plugin's "Debug with …"): no Run before-launch + * pass of its own, and `finished` / `beforeStop` are not called. + */ + debug?: boolean; + /** `prepare` handles a configuration on a run target itself (no container check before it). */ + checksTarget?: boolean; } export const useRunExecutors = create<{ executors: Map<string, RunExecutorContribution> }>(() => ({ diff --git a/src/workbench/focus.test.ts b/src/workbench/focus.test.ts index 7b69d0c58..86a767562 100644 --- a/src/workbench/focus.test.ts +++ b/src/workbench/focus.test.ts @@ -1,6 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { setContext } from "@/platform/context"; -import { EDITOR_AREA_SELECTOR, focusEditor, installFocusTracking } from "./focus"; +import { installFocusScopeTracking } from "@/ui/focusScope"; +import { EDITOR_AREA_SELECTOR, focusEditor, installFocusTracking, notifyFocusElement } from "./focus"; describe("focus after popups", () => { afterEach(() => { @@ -122,4 +123,45 @@ describe("focus tracking", () => { ]); dispose(); }); + + it("tracks focus entering sandboxed plugin iframes and updates focus-scope highlighting", () => { + vi.spyOn(document, "hasFocus").mockReturnValue(true); + document.body.innerHTML = ` + <div data-editor-area> + <section data-pane-id="p1" data-focus-scope=""><iframe id="ed-frame" tabindex="0"></iframe></section> + </div> + <section data-toolwindow="plugin.k8s.view" data-focus-scope=""> + <iframe id="tw-frame" tabindex="0"></iframe> + </section>`; + const calls: Array<[string | null, boolean]> = []; + const disposeScope = installFocusScopeTracking(); + const dispose = installFocusTracking((id, editor) => calls.push([id, editor])); + + const twFrame = document.getElementById("tw-frame") as HTMLIFrameElement; + const edFrame = document.getElementById("ed-frame") as HTMLIFrameElement; + let active: Element | null = twFrame; + Object.defineProperty(document, "activeElement", { configurable: true, get: () => active }); + + // Window blur when activeElement is an iframe inside a tool window tracks it and marks its focus scope. + window.dispatchEvent(new Event("blur")); + // Repeated bridge notification for the same iframe is deduplicated. + notifyFocusElement(twFrame); + expect(calls).toEqual([["plugin.k8s.view", false]]); + expect(document.querySelector('[data-toolwindow="plugin.k8s.view"]')).toHaveAttribute("data-focus-active", ""); + + // Switching to an iframe inside an editor pane updates both tracking and focus-scope highlight. + active = edFrame; + notifyFocusElement(edFrame); + expect(calls).toEqual([ + ["plugin.k8s.view", false], + [null, true], + ]); + expect(document.querySelector('[data-pane-id="p1"]')).toHaveAttribute("data-focus-active", ""); + expect(document.querySelector('[data-toolwindow="plugin.k8s.view"]')).not.toHaveAttribute("data-focus-active"); + + Reflect.deleteProperty(document, "activeElement"); + dispose(); + disposeScope(); + vi.restoreAllMocks(); + }); }); diff --git a/src/workbench/focus.ts b/src/workbench/focus.ts index 322275515..28e47410f 100644 --- a/src/workbench/focus.ts +++ b/src/workbench/focus.ts @@ -1,9 +1,18 @@ /** Focus routing between tool windows and the editor area. */ import { setContext, useContextKeys } from "@/platform/context"; +import { syncFocusScope } from "@/ui/focusScope"; import { maybeEditorService } from "./contributions"; export const EDITOR_AREA_SELECTOR = "[data-editor-area]"; +let activeTracker: ((el: Element | null) => void) | null = null; + +/** Reports that focus entered `el` (e.g. a sandboxed plugin iframe that does not bubble `focusin`). */ +export function notifyFocusElement(el: Element | null) { + syncFocusScope(el); + activeTracker?.(el); +} + /** Moves focus to the active editor (or the editor area when none is open). */ export function focusEditor() { if (typeof document !== "undefined" && document.querySelector(EDITOR_AREA_SELECTOR)?.closest("[hidden]")) { @@ -51,25 +60,44 @@ function dropEditorCaret(e: FocusEvent) { * `activeToolWindow` and `editorAreaFocus`. Returns an uninstaller. */ export function installFocusTracking(onToolWindowFocus: (id: string | null, editor: boolean) => void): () => void { - const onFocusIn = (e: FocusEvent) => { - const el = e.target as Element | null; + let lastEl: Element | null = null; + const handleFocus = (el: Element | null) => { + if (el && el === lastEl && el instanceof HTMLIFrameElement) return; + lastEl = el; const tw = el?.closest?.("[data-toolwindow]"); const editor = !!el?.closest?.(EDITOR_AREA_SELECTOR); onToolWindowFocus(tw?.getAttribute("data-toolwindow") ?? null, editor); setContext("editorAreaFocus", editor); }; + activeTracker = handleFocus; + const onFocusIn = (e: FocusEvent) => handleFocus(e.target as Element | null); + const checkIframeFocus = () => { + const active = document.activeElement; + if (active instanceof HTMLIFrameElement && document.hasFocus()) handleFocus(active); + }; + const onWindowBlur = () => { + checkIframeFocus(); + queueMicrotask(checkIframeFocus); + }; const onFocusOut = (e: FocusEvent) => { dropEditorCaret(e); if (e.relatedTarget) return; - // Focus left to nowhere (window blur keeps document.activeElement). + // Focus left to nowhere (window blur keeps document.activeElement) or into an iframe. queueMicrotask(() => { - if (document.activeElement && document.activeElement !== document.body) return; + const active = document.activeElement; + if (active instanceof HTMLIFrameElement && document.hasFocus()) { + handleFocus(active); + return; + } + if (active && active !== document.body) return; + lastEl = null; onToolWindowFocus(null, false); setContext("editorAreaFocus", false); }); }; document.addEventListener("focusin", onFocusIn); document.addEventListener("focusout", onFocusOut); + window.addEventListener("blur", onWindowBlur); // IDEA: closing the last popup / menu / dialog never leaves focus nowhere. let popupOpen = !!useContextKeys.getState().popupOpen; let refocus: ReturnType<typeof setTimeout> | undefined; @@ -84,9 +112,11 @@ export function installFocusTracking(onToolWindowFocus: (id: string | null, edit }); }); return () => { + if (activeTracker === handleFocus) activeTracker = null; clearTimeout(refocus); unsubPopups(); document.removeEventListener("focusin", onFocusIn); document.removeEventListener("focusout", onFocusOut); + window.removeEventListener("blur", onWindowBlur); }; } diff --git a/src/workbench/menuLabels.ts b/src/workbench/menuLabels.ts index 7437d7d86..23323351a 100644 --- a/src/workbench/menuLabels.ts +++ b/src/workbench/menuLabels.ts @@ -5,6 +5,7 @@ import { isVirtualUri } from "@/platform/virtualDocs"; import { maybeEditorService } from "./contributions"; import { isDistractionFree } from "./distractionFree"; import { toolWindowsRestorable } from "./toolwindows/store"; +import { isZenMode } from "./zenMode"; export function javaFileNameOf(path: unknown): string | null { if (typeof path !== "string" || !path || isVirtualUri(path) || !/\.java$/i.test(path)) return null; @@ -16,6 +17,7 @@ export function menuLabelParams(os: string) { return { os, distractionFree: isDistractionFree() ? "on" : "off", + zenMode: isZenMode() ? "on" : "off", toolWindows: toolWindowsRestorable() ? "hidden" : "shown", compileFile: compileFileName ? "yes" : "no", compileFileName: compileFileName ?? "", diff --git a/src/workbench/quickSwitch.ts b/src/workbench/quickSwitch.ts index c86989de1..02042d970 100644 --- a/src/workbench/quickSwitch.ts +++ b/src/workbench/quickSwitch.ts @@ -105,9 +105,10 @@ export function colorSchemeItems(current: string | undefined): MenuItem[] { ]; } -/** The existing view modes: Distraction Free Mode and Full Screen. */ +/** The existing view modes: Distraction Free Mode, Zen Mode and Full Screen. */ export const VIEW_MODE_ITEMS: MenuItem[] = [ { kind: "action", action: "editor.toggleZen" }, + { kind: "action", action: "view.toggleZenMode" }, { kind: "action", action: "window.toggleFullScreen" }, ]; diff --git a/src/workbench/toolwindows/ToolWindows.tsx b/src/workbench/toolwindows/ToolWindows.tsx index 642cddd17..5616e8678 100644 --- a/src/workbench/toolwindows/ToolWindows.tsx +++ b/src/workbench/toolwindows/ToolWindows.tsx @@ -831,18 +831,29 @@ function ToolWindowView({ tw, hidden }: { tw: ToolWindowContribution; hidden: bo const root = ref.current; if (!root) return; const body = root.querySelector<HTMLElement>("[data-toolwindow-body]"); - // Like IDEA, activation focuses the content (a field, list or tree), never a button or - // link: a scripted focus on one draws its focus ring (an empty view's "New…" link). + // Like IDEA, activation focuses visible content (a field, list or tree), never a button, + // link, or hidden / inert target: a scripted focus on a button draws its focus ring, and + // focusing a hidden element (e.g. a file input or inactive tab panel) is a silent no-op + // that leaves focus stranded in the previous window. + const isVisibleTarget = (el: HTMLElement) => { + if (el.matches('input[type="hidden"]') || el.closest("[hidden], [inert]")) return false; + for (let cur: HTMLElement | null = el; cur && cur !== body; cur = cur.parentElement) { + const style = getComputedStyle(cur); + if (style.display === "none" || style.visibility === "hidden") return false; + } + return true; + }; const contentTarget = () => - body?.querySelector<HTMLElement>("[data-autofocus]") ?? + [...(body?.querySelectorAll<HTMLElement>("[data-autofocus]") ?? [])].find(isVisibleTarget) ?? [...(body?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? [])].find( - (el) => !el.matches('button, a[href], [role="button"], [role="link"]'), + (el) => !el.matches('button, a[href], [role="button"], [role="link"]') && isVisibleTarget(el), ); const target = contentTarget(); if (target || !body) { (target ?? root).focus({ preventScroll: true }); - return; + if (root.contains(document.activeElement)) return; } + if (!body) return; if (!body.hasAttribute("tabindex")) body.tabIndex = -1; body.focus({ preventScroll: true }); // Lazily loaded views (the Terminal) render their field after this: focus it when it diff --git a/src/workbench/toolwindows/header.test.tsx b/src/workbench/toolwindows/header.test.tsx index b1b5102c1..afd97eaf4 100644 --- a/src/workbench/toolwindows/header.test.tsx +++ b/src/workbench/toolwindows/header.test.tsx @@ -134,3 +134,68 @@ it("shows the header title in a language chosen while the window is open", () => act(() => useI18n.setState({ texts: before })); } }); + +it("skips hidden and inert focus targets when activating a tool window", () => { + vi.useFakeTimers(); + const dispose = registerToolWindow({ + id: "hidden-inputs", + title: "Hidden Inputs", + icon: "file", + anchor: "right", + requiresProject: false, + component: () => ( + <div> + <input type="file" aria-label="Hidden file" style={{ display: "none" }} /> + <input type="hidden" value="secret" /> + <div hidden> + <input aria-label="In hidden panel" data-autofocus="" /> + </div> + <div inert> + <input aria-label="In inert container" /> + </div> + <div style={{ display: "none" }}> + <input aria-label="In display-none wrapper" /> + </div> + <textarea aria-label="Visible composer" /> + </div> + ), + }); + try { + render(<ToolWindowLayout editor={<input aria-label="Editor" />} />); + screen.getByRole("textbox", { name: "Editor" }).focus(); + act(() => showToolWindow("hidden-inputs", true)); + act(() => vi.runAllTimers()); + expect(document.activeElement).toBe(screen.getByRole("textbox", { name: "Visible composer" })); + } finally { + dispose(); + vi.useRealTimers(); + } +}); + +it("falls back to the tool window body when only hidden focus targets exist", () => { + vi.useFakeTimers(); + const dispose = registerToolWindow({ + id: "only-hidden", + title: "Only Hidden", + icon: "file", + anchor: "right", + requiresProject: false, + component: () => ( + <div> + <input type="file" aria-label="Hidden file" style={{ display: "none" }} /> + <button type="button">Action</button> + </div> + ), + }); + try { + render(<ToolWindowLayout editor={<input aria-label="Editor" />} />); + screen.getByRole("textbox", { name: "Editor" }).focus(); + act(() => showToolWindow("only-hidden", true)); + act(() => vi.runAllTimers()); + const body = document.querySelector<HTMLElement>('[data-toolwindow="only-hidden"] [data-toolwindow-body]')!; + expect(document.activeElement).toBe(body); + } finally { + dispose(); + vi.useRealTimers(); + } +}); diff --git a/src/workbench/zenMode.test.ts b/src/workbench/zenMode.test.ts new file mode 100644 index 000000000..9d33c7be9 --- /dev/null +++ b/src/workbench/zenMode.test.ts @@ -0,0 +1,123 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { executeAction, getAction } from "@/platform/actions"; +import { isDistractionFree, resetDistractionFree, setDistractionFree } from "./distractionFree"; +import { usePlatform } from "@/platform/platformInfo"; +import { ZEN_MODE_ACTION, installZenMode, isZenMode, toggleZenMode, useFullscreen } from "./zenMode"; + +const win = vi.hoisted(() => ({ fullscreen: false, onChange: null as null | (() => void) })); + +const { windowIsFullscreen, windowToggleFullscreen } = vi.hoisted(() => ({ + windowIsFullscreen: vi.fn(async () => win.fullscreen), + windowToggleFullscreen: vi.fn(async () => { + win.fullscreen = !win.fullscreen; + win.onChange?.(); + return { status: "ok", data: win.fullscreen }; + }), +})); + +vi.mock("@/platform/ipc", async (orig) => { + const actual = await orig<typeof import("@/platform/ipc")>(); + return { + ...actual, + isTauri: () => true, + commands: { ...actual.commands, windowIsFullscreen, windowToggleFullscreen }, + onIdeEvent: (type: string, handler: () => void) => { + if (type !== "windowFullscreenChanged") return () => {}; + win.onChange = handler; + return () => (win.onChange = null); + }, + }; +}); + +let dispose: () => void = () => {}; +const os = usePlatform.getState().os; +const settle = () => new Promise((r) => setTimeout(r, 0)); +const title = () => getAction(ZEN_MODE_ACTION)?.title; + +beforeEach(async () => { + localStorage.clear(); + resetDistractionFree(); + win.fullscreen = false; + useFullscreen.setState({ on: false }); + windowToggleFullscreen.mockClear(); + dispose = installZenMode(); + await settle(); +}); + +afterEach(() => { + dispose(); + usePlatform.setState({ os }); + resetDistractionFree(); +}); + +describe("zen mode", () => { + it("turns on Distraction Free Mode and full screen together, and both off again", async () => { + expect(title()).toBe("Enter Zen Mode"); + await executeAction(ZEN_MODE_ACTION); + expect(isDistractionFree()).toBe(true); + expect(win.fullscreen).toBe(true); + expect(isZenMode()).toBe(true); + expect(title()).toBe("Exit Zen Mode"); + await executeAction(ZEN_MODE_ACTION); + expect(isDistractionFree()).toBe(false); + expect(win.fullscreen).toBe(false); + expect(title()).toBe("Enter Zen Mode"); + expect(windowToggleFullscreen).toHaveBeenCalledTimes(2); + }); + + it("enters from full screen alone without leaving full screen", async () => { + win.fullscreen = true; + await executeAction(ZEN_MODE_ACTION); + expect(windowToggleFullscreen).not.toHaveBeenCalled(); + expect(win.fullscreen).toBe(true); + expect(isDistractionFree()).toBe(true); + expect(title()).toBe("Exit Zen Mode"); + }); + + it("enters from Distraction Free Mode alone by adding full screen", async () => { + setDistractionFree(true); + expect(title()).toBe("Enter Zen Mode"); + await executeAction(ZEN_MODE_ACTION); + expect(isDistractionFree()).toBe(true); + expect(win.fullscreen).toBe(true); + expect(title()).toBe("Exit Zen Mode"); + }); + + it("is off once full screen is left another way, and the action enters it again", async () => { + await executeAction(ZEN_MODE_ACTION); + // View › Appearance › Toggle Full Screen or the window's green button. + win.fullscreen = false; + win.onChange?.(); + await settle(); + expect(isZenMode()).toBe(false); + expect(title()).toBe("Enter Zen Mode"); + await executeAction(ZEN_MODE_ACTION); + expect(isDistractionFree()).toBe(true); + expect(win.fullscreen).toBe(true); + }); + + it("enters once when run again before full screen has switched", async () => { + await Promise.all([toggleZenMode(), toggleZenMode()]); + expect(windowToggleFullscreen).toHaveBeenCalledTimes(1); + expect(isDistractionFree()).toBe(true); + expect(win.fullscreen).toBe(true); + }); + + it("notices full screen left without an event once the window resizes (Windows, Linux)", async () => { + dispose(); + usePlatform.setState({ os: "windows" }); + dispose = installZenMode(); + await executeAction(ZEN_MODE_ACTION); + win.fullscreen = false; + window.dispatchEvent(new Event("resize")); + await settle(); + expect(title()).toBe("Enter Zen Mode"); + }); + + it("is off once Distraction Free Mode is left, and leaves full screen alone then", async () => { + await executeAction(ZEN_MODE_ACTION); + setDistractionFree(false); + expect(title()).toBe("Enter Zen Mode"); + expect(win.fullscreen).toBe(true); + }); +}); diff --git a/src/workbench/zenMode.ts b/src/workbench/zenMode.ts new file mode 100644 index 000000000..bf06c9927 --- /dev/null +++ b/src/workbench/zenMode.ts @@ -0,0 +1,93 @@ +/** + * Zen Mode (View › Appearance), IDEA's ToggleZenMode: Distraction Free Mode and + * full screen together. The mode is on while both are on; the action turns both + * on, or both off when it is on, leaving either alone if it is already right. + */ +import { create } from "zustand"; +import { registerAction, type Action } from "@/platform/actions"; +import { commands, isTauri, onIdeEvent } from "@/platform/ipc"; +import { usePlatform } from "@/platform/platformInfo"; +import { setDistractionFree, useDistractionFree } from "./distractionFree"; + +export const ZEN_MODE_ACTION = "view.toggleZenMode"; + +/** This window's full-screen state, kept current by `installZenMode`. */ +export const useFullscreen = create<{ on: boolean }>(() => ({ on: false })); + +export function isZenMode(): boolean { + return useDistractionFree.getState().active && useFullscreen.getState().on; +} + +function zenModeTitle(active: boolean): string { + return active ? "Exit Zen Mode" : "Enter Zen Mode"; +} + +async function readFullscreen(): Promise<boolean> { + return isTauri() ? commands.windowIsFullscreen() : document.fullscreenElement === document.documentElement; +} + +async function syncFullscreen() { + const on = await readFullscreen().catch(() => useFullscreen.getState().on); + if (on !== useFullscreen.getState().on) useFullscreen.setState({ on }); +} + +async function setFullscreen(on: boolean) { + if ((await readFullscreen()) === on) return; + if (isTauri()) await commands.windowToggleFullscreen(); + else if (on) await document.documentElement.requestFullscreen?.(); + else await document.exitFullscreen(); + await syncFullscreen(); +} + +/** The toggle in progress: full screen only flips, so a second run must not read the state before it lands. */ +let pending: Promise<void> | null = null; + +export function toggleZenMode(): Promise<void> { + pending ??= (async () => { + await syncFullscreen(); + const on = !isZenMode(); + setDistractionFree(on); + await setFullscreen(on); + })().finally(() => (pending = null)); + return pending; +} + +function action(active: boolean): Action { + return { + id: ZEN_MODE_ACTION, + title: zenModeTitle(active), + category: "View", + keywords: ["zen", "distraction free", "full screen", "toggle zen mode"], + run: toggleZenMode, + }; +} + +/** Registers the action; its title follows the mode, like IDEA's Enter / Exit Zen Mode. */ +export function installZenMode(): () => void { + let active = isZenMode(); + let dispose = registerAction(action(active)); + const update = () => { + if (isZenMode() === active) return; + active = !active; + const previous = dispose; + dispose = registerAction(action(active)); + previous(); + }; + const unsubs = [useDistractionFree.subscribe(update), useFullscreen.subscribe(update)]; + const onFullscreen = () => void syncFullscreen(); + if (isTauri()) unsubs.push(onIdeEvent("windowFullscreenChanged", onFullscreen)); + else { + document.addEventListener("fullscreenchange", onFullscreen); + unsubs.push(() => document.removeEventListener("fullscreenchange", onFullscreen)); + } + // Only macOS reports full-screen changes; elsewhere (F11 on Windows) the window resizes. + if (isTauri() && usePlatform.getState().os !== "macos") { + window.addEventListener("resize", onFullscreen); + unsubs.push(() => window.removeEventListener("resize", onFullscreen)); + } + void syncFullscreen(); + return () => { + unsubs.forEach((u) => u()); + dispose(); + }; +} diff --git a/wit/agents.wit b/wit/agents.wit new file mode 100644 index 000000000..b833f3b91 --- /dev/null +++ b/wit/agents.wit @@ -0,0 +1,14 @@ +package openidea:plugin@1.18.0; + +/// Forking recorded native agent sessions into new tasks (API 1.18). Requires +/// the `agents` capability. The session must belong to the invoking window's +/// project and have been recorded in `cwd`; the host builds the fork invocation +/// and names the fork's id for claude (codex assigns its own). +interface agents { + use types.{error}; + /// Fork the recorded session `session-id` of `agent` (a native provider, + /// `claude` or `codex`) into a new task in the open project, returning the + /// new task id. `cwd` must be where the session was recorded. The first + /// turn continues the recording as the agent's own fork. + fork-session: func(agent: string, session-id: string, cwd: string) -> result<string, error>; +} \ No newline at end of file diff --git a/wit/plugin.wit b/wit/plugin.wit index 8cc725b88..ec2debc26 100644 --- a/wit/plugin.wit +++ b/wit/plugin.wit @@ -40,6 +40,7 @@ world plugin { import mcp; import settings; import extensions; + import agents; export lifecycle; export commands;