дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 09:11:10 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
e6e2bdb80d | ||
|
|
6e5f91f7fd | ||
|
|
e38599b82b | ||
|
|
437008c517 | ||
|
|
5947204022 | ||
|
|
d4a2a84c36 | ||
|
|
1c94aeb476 | ||
|
|
b9014f34cf | ||
|
|
0920f189d6 | ||
|
|
a3c7591624 | ||
|
|
1ba9ace7e2 | ||
|
|
d8e58296be | ||
|
|
196057019f | ||
|
|
272a183442 | ||
|
|
cd57b7f053 | ||
|
|
45dd96cdeb | ||
|
|
22db3ab9c3 | ||
|
|
343dd51082 | ||
|
|
75c57e2691 | ||
|
|
856fc3009e | ||
|
|
3f7a072fa1 | ||
|
|
c9a2b6200e | ||
|
|
c1d552e578 | ||
|
|
02d22fe658 | ||
|
|
7f9a618cac | ||
|
|
1877d8c1a1 | ||
|
|
839da450f7 | ||
|
|
ba42061885 | ||
|
|
2b359f9a98 | ||
|
|
b83c1a60c2 | ||
|
|
f213999338 | ||
|
|
920e321109 | ||
|
|
ede0705bd5 | ||
|
|
a75c332905 | ||
|
|
954180beb0 | ||
|
|
eb6483030c | ||
|
|
6c9c02417e | ||
|
|
9e7f842caf | ||
|
|
0bda7b194b | ||
|
|
9ab90941ef | ||
|
|
1dc1c67095 | ||
|
|
6f7c8e246f | ||
|
|
5638f8d04e | ||
|
|
f156baa976 | ||
|
|
d41bccc50c | ||
|
|
9087fa61d9 | ||
|
|
6404c30718 | ||
|
|
66a765664c | ||
|
|
fe1b5eacf8 | ||
|
|
21c4b08a5d | ||
|
|
f8e0ad57ff | ||
|
|
72e1d6afc1 | ||
|
|
8ffd6c9e2c | ||
|
|
dbfec0c433 | ||
|
|
1bdd5b4094 | ||
|
|
88eba9f3bd | ||
|
|
8044948178 | ||
|
|
0425004ecd | ||
|
|
c1b45b037d | ||
|
|
f5732dd706 | ||
|
|
e86e28ae63 | ||
|
|
82fdd97588 | ||
|
|
1757d26e78 | ||
|
|
766e1edc0c | ||
|
|
fc52975be0 | ||
|
|
c3726daed6 | ||
|
|
69c9521e85 | ||
|
|
fc60719d4b | ||
|
|
e35ba7d805 | ||
|
|
fa0783ab03 | ||
|
|
5338a34008 | ||
|
|
1d3547a953 | ||
|
|
14ed7aa647 | ||
|
|
27164e8919 | ||
|
|
62bac6ec8c | ||
|
|
17a32e0c1f | ||
|
|
e0ed6a0a3b | ||
|
|
db0cdccd66 | ||
|
|
4237117f2c | ||
|
|
26edc6d826 | ||
|
|
92c71837cb | ||
|
|
0791e73974 | ||
|
|
a8773a196c | ||
|
|
5f50469d7e | ||
|
|
9e4fbe863d | ||
|
|
7fdd39a628 | ||
|
|
9d8fdab75e | ||
|
|
f09d51bd49 | ||
|
|
00aef16862 | ||
|
|
87b659b3ac | ||
|
|
709cde907e | ||
|
|
6a69707220 | ||
|
|
e30651473d | ||
|
|
8397e5e2a3 | ||
|
|
890fade636 | ||
|
|
dfe4784874 | ||
|
|
43c9053624 | ||
|
|
05c64c2475 | ||
|
|
3334d1016b | ||
|
|
637e227efa | ||
|
|
5432d7f288 | ||
|
|
2fdc024358 | ||
|
|
84267f44ed | ||
|
|
e08e455fe5 | ||
|
|
ceb020857a | ||
|
|
e8f5f6d6ba | ||
|
|
b0f5c9aed0 | ||
|
|
f40550e0cf | ||
|
|
43d668dc75 | ||
|
|
81a746b8e2 | ||
|
|
0aaa586cec | ||
|
|
159f10ba82 | ||
|
|
355d6005aa | ||
|
|
98a6de6ff0 | ||
|
|
2f3f08efde | ||
|
|
797904c308 | ||
|
|
c8f9f9cc37 | ||
|
|
db57c0961e | ||
|
|
70f6316a69 | ||
|
|
ac68fbe39e | ||
|
|
41f4e22b29 | ||
|
|
af2e515d0f | ||
|
|
a1ed7af5cf | ||
|
|
43dac21ac3 | ||
|
|
0d3b001191 | ||
|
|
0f328854a2 | ||
|
|
5ae211ecd6 | ||
|
|
55274d2dd1 | ||
|
|
72f7b59e3b | ||
|
|
581672eebc | ||
|
|
eace2fc741 | ||
|
|
f39b728947 | ||
|
|
f307355369 | ||
|
|
611f40c6ce | ||
|
|
391b91539f | ||
|
|
5633d76da1 | ||
|
|
310cbaad66 | ||
|
|
bc63e8e029 | ||
|
|
a579d81694 | ||
|
|
6eb1f0713d | ||
|
|
95d4a41b62 | ||
|
|
18ac414b52 | ||
|
|
10e399cbec | ||
|
|
ce4b2f9655 | ||
|
|
65686e246e | ||
|
|
3078674a86 | ||
|
|
82d8a6ea19 | ||
|
|
3785b75582 | ||
|
|
15b55c66ca | ||
|
|
d6d6fd0909 | ||
|
|
7bfad25bb5 | ||
|
|
5c31ccfe70 | ||
|
|
304674d0fe | ||
|
|
aa003541a3 | ||
|
|
d2699c430e | ||
|
|
f404a33e7a | ||
|
|
05e7db4be6 | ||
|
|
8ad3fc4faf | ||
|
|
3f7b83e8fd | ||
|
|
7fa280e9e0 | ||
|
|
3c8acf8ee3 | ||
|
|
0d94a8973e | ||
|
|
18f28cd804 | ||
|
|
37f2dd3ced | ||
|
|
ba5eb92c70 | ||
|
|
bbbcf23c77 | ||
|
|
ac9f745dcf | ||
|
|
86cfabfbe4 | ||
|
|
6b038245fd | ||
|
|
e985322f3a | ||
|
|
1f329cbc87 | ||
|
|
0f0cdd4672 | ||
|
|
875b17938e | ||
|
|
6820d27af5 | ||
|
|
02aa916a26 | ||
|
|
a7b9529109 | ||
|
|
0303a513cd | ||
|
|
a2bf7fb0c4 | ||
|
|
17dd723a3d | ||
|
|
f1097831d7 | ||
|
|
ad0a755f07 | ||
|
|
099bb57abd | ||
|
|
1ba2ce55bb | ||
|
|
24588b0975 | ||
|
|
8dc1fecc0e | ||
|
|
cb7668d4f0 | ||
|
|
90377204aa | ||
|
|
1d3de3c366 | ||
|
|
4466a059b3 | ||
|
|
b7bacc8ff5 | ||
|
|
50508b0af0 | ||
|
|
ef4458c04c | ||
|
|
0666f9ea5a | ||
|
|
3fe4e12252 | ||
|
|
9ecb664036 | ||
|
|
e6c8d6d9ac | ||
|
|
a68ebc1293 | ||
|
|
8b267c6307 | ||
|
|
67460f1275 | ||
|
|
4a620287c8 | ||
|
|
607812d8fa | ||
|
|
90f9d4ffd0 | ||
|
|
0f359ddf3b | ||
|
|
51a6b40314 | ||
|
|
bd5af356f4 | ||
|
|
d3cb8513be | ||
|
|
29d1a52d91 | ||
|
|
5b24b61b49 | ||
|
|
1dd8ea9b3b | ||
|
|
2221afad01 | ||
|
|
471bce2bb1 | ||
|
|
b630dfad55 | ||
|
|
74b50f7592 | ||
|
|
95bc3622ab | ||
|
|
b911366115 | ||
|
|
b2a9d105e2 | ||
|
|
b83c2cf11a | ||
|
|
6648f502f1 | ||
|
|
115003f0b6 | ||
|
|
02d912d72a | ||
|
|
70fe0e6653 | ||
|
|
950bf986d6 | ||
|
|
310d923480 | ||
|
|
0c506fa479 | ||
|
|
bc86836492 | ||
|
|
dead55af21 | ||
|
|
c7a4201ce9 | ||
|
|
91cf66e72e | ||
|
|
4a87022e58 | ||
|
|
c92bd0999b | ||
|
|
880835f0ac | ||
|
|
ce938df81b | ||
|
|
9abe3d7e3c | ||
|
|
4e5ae49aa9 | ||
|
|
9443517d1c | ||
|
|
29f6131f9d | ||
|
|
4027b8341f | ||
|
|
ddc483fd2a | ||
|
|
23d81a2b3d | ||
|
|
74f61a3540 | ||
|
|
c287ce0ee3 | ||
|
|
607e4e095d | ||
|
|
e7da5e0937 | ||
|
|
ae4a90b23a | ||
|
|
04006f2ea7 | ||
|
|
7f20fc0c54 | ||
|
|
a8db175c25 | ||
|
|
8aacedf5ad | ||
|
|
1425bfe8ae | ||
|
|
75ec6c51a3 | ||
|
|
b20e7c0817 | ||
|
|
adf5701e16 | ||
|
|
5debc5297b | ||
|
|
5db70297cb | ||
|
|
0f78b845e6 | ||
|
|
c319656529 | ||
|
|
4ebc769042 | ||
|
|
300424658a | ||
|
|
44ccaaef26 | ||
|
|
befb4792ce | ||
|
|
34741f56c4 | ||
|
|
2907832e37 | ||
|
|
ff4e916561 | ||
|
|
2f799aede9 | ||
|
|
f853ccf544 | ||
|
|
8b4de98664 | ||
|
|
a36516d463 | ||
|
|
b7c2d4eacb | ||
|
|
abc5b2b2c6 | ||
|
|
cb10ba7207 | ||
|
|
0fe39535d6 | ||
|
|
0c9ffe1e41 | ||
|
|
cda99d5495 | ||
|
|
d979e102f9 | ||
|
|
67d68f7f4e | ||
|
|
2b73ef73f1 | ||
|
|
de41651a5e | ||
|
|
6bd2d5f843 | ||
|
|
93c15547ef | ||
|
|
90d98f3edd | ||
|
|
b7ef68df71 | ||
|
|
fdc4df4752 | ||
|
|
54ce048ec9 | ||
|
|
a372385788 | ||
|
|
7ff8d472f7 | ||
|
|
4de01a91c5 | ||
|
|
657d49e30a | ||
|
|
2a7975a077 | ||
|
|
71d88d0b55 | ||
|
|
c6faf280db | ||
|
|
fba7705acf | ||
|
|
f87fb35be5 | ||
|
|
f4236a0ea1 | ||
|
|
1eece0ae51 | ||
|
|
7361707b63 | ||
|
|
8e56d3b73e | ||
|
|
e5453a8a97 | ||
|
|
27689f09d3 | ||
|
|
9b468b0873 | ||
|
|
cb887dad80 | ||
|
|
3cfbf80e26 | ||
|
|
97add1f448 | ||
|
|
35a6bec1c2 | ||
|
|
f8ba067e1d | ||
|
|
85cbc6bacd | ||
|
|
3f490684d6 | ||
|
|
8f6200c3fa | ||
|
|
0aa64c2c6e | ||
|
|
8d4e016cb0 | ||
|
|
a1ef8ca749 | ||
|
|
669462c4de | ||
|
|
90eb6bac1b | ||
|
|
674e925c9a | ||
|
|
ddd27a6e50 | ||
|
|
d4791ea0c2 | ||
|
|
baea2733f8 | ||
|
|
0d2401705e | ||
|
|
6c96b79538 | ||
|
|
878e86e10c | ||
|
|
6c36723a7d | ||
|
|
ed58f1aba0 | ||
|
|
adda2cbb93 | ||
|
|
132259242a | ||
|
|
1a400d3405 | ||
|
|
aa1711194c | ||
|
|
83dcdc8eca | ||
|
|
783daaa041 | ||
|
|
dc74595bca | ||
|
|
aa596f1125 | ||
|
|
6927b787b2 | ||
|
|
e1e9ede2d6 | ||
|
|
839292fb30 | ||
|
|
2a4bf1f848 | ||
|
|
3e41c93a95 | ||
|
|
b85027dc47 | ||
|
|
63c2ced086 | ||
|
|
d73b8d8ec1 | ||
|
|
74b90a114a | ||
|
|
e70b516ca0 | ||
|
|
7d15681313 | ||
|
|
2ecaefe859 | ||
|
|
895e5bd56e | ||
|
|
2dc577614b | ||
|
|
a9e92d0665 | ||
|
|
fa0be07436 | ||
|
|
fea27f5608 | ||
|
|
a4d172ac83 | ||
|
|
c40d06c702 | ||
|
|
619ae7f727 | ||
|
|
c725b1629d | ||
|
|
b0033a869d | ||
|
|
4ed4ced5b1 | ||
|
|
7668e4a5ba | ||
|
|
4a6e0dfac1 | ||
|
|
11e8f8a101 | ||
|
|
7a27f285e6 | ||
|
|
f21ae03bdd | ||
|
|
5dacbcd0cd | ||
|
|
281c2ff1e5 | ||
|
|
4276250056 | ||
|
|
ba04491ace | ||
|
|
660a311f21 | ||
|
|
92bf9354fe | ||
|
|
54da9c2c12 | ||
|
|
9ba3150998 | ||
|
|
190e5639f1 | ||
|
|
5f782e9c5d | ||
|
|
10fe5d21af | ||
|
|
16c30e819c | ||
|
|
43c8699beb | ||
|
|
071fbf7639 | ||
|
|
bde1e5f7a0 | ||
|
|
c1e8864138 | ||
|
|
5966d193c4 | ||
|
|
6d38521498 | ||
|
|
52e6a0f84b | ||
|
|
72873981aa | ||
|
|
d44a104ff8 | ||
|
|
23ea9cf07d | ||
|
|
cea3f4ac9c | ||
|
|
aee715f797 | ||
|
|
711349c6c1 | ||
|
|
9b2d783322 | ||
|
|
72ae354d29 | ||
|
|
dd8de05013 | ||
|
|
a547c8cdee | ||
|
|
a74d5b5dbb | ||
|
|
b895093f6b | ||
|
|
cbb9079577 | ||
|
|
44418411b8 | ||
|
|
5e23076766 | ||
|
|
689d3fd877 | ||
|
|
608ab44fca | ||
|
|
41545d38e5 | ||
|
|
4f86211dd6 | ||
|
|
203e4fbcb2 | ||
|
|
869e52f837 | ||
|
|
02e4c9c7a2 | ||
|
|
61be657209 | ||
|
|
52294c51c2 | ||
|
|
222d0b5ee3 | ||
|
|
cd8f29ea63 | ||
|
|
ba94abcb8b | ||
|
|
937eb0c3a0 | ||
|
|
b2d03ac5f0 | ||
|
|
4e735eadcb | ||
|
|
50ba6b5c56 | ||
|
|
36910712d1 | ||
|
|
5b99b8b5ab | ||
|
|
f3874b9b2e | ||
|
|
18b87b066b | ||
|
|
41a76ca0d7 | ||
|
|
1bf29ab3d7 | ||
|
|
49b52a8bfa | ||
|
|
77342b8e71 | ||
|
|
369ff7cec8 | ||
|
|
4016c410db | ||
|
|
3c3d02d7be | ||
|
|
2f66eb0503 | ||
|
|
63db10a688 | ||
|
|
1dd3d64781 | ||
|
|
8ac194cf50 | ||
|
|
3b488a7824 | ||
|
|
b5e89aace0 | ||
|
|
81c95b2ab7 | ||
|
|
f7b5cc388c | ||
|
|
277d0e9d1e | ||
|
|
d6adb7aa40 | ||
|
|
6e5e482410 | ||
|
|
cc02c2fe40 | ||
|
|
74a3f6470a | ||
|
|
4c8c078666 | ||
|
|
e672b14d52 | ||
|
|
c0300f8959 | ||
|
|
11cf9864a1 | ||
|
|
04a4d98d68 | ||
|
|
9a984f64a3 | ||
|
|
e35a607556 | ||
|
|
3fa990fce2 | ||
|
|
11e520dedb | ||
|
|
a0c0b69b4a | ||
|
|
b89128649f | ||
|
|
9973cad74c | ||
|
|
8cb7a2fe06 | ||
|
|
5d867d7d2d | ||
|
|
70f6678271 | ||
|
|
530388a79d | ||
|
|
98cb85003a | ||
|
|
dfae46868c | ||
|
|
635da15486 | ||
|
|
249d0526f0 | ||
|
|
181bbdfdc2 | ||
|
|
c7172184ad | ||
|
|
8380732e60 | ||
|
|
42fcbb336a | ||
|
|
93a450aa8c | ||
|
|
8e0a36fb1c | ||
|
|
11da3ecce7 | ||
|
|
53d295d785 | ||
|
|
9f1380cf04 | ||
|
|
338e1a5b02 | ||
|
|
092cde1319 | ||
|
|
fc1e1838ca | ||
|
|
9a9a536525 | ||
|
|
2d7928374e | ||
|
|
58eb5ae667 | ||
|
|
0698ebb9b0 | ||
|
|
647e564127 | ||
|
|
edd2e90b9b | ||
|
|
5bfefff5e1 | ||
|
|
49097bf5c0 | ||
|
|
09a44bebbe | ||
|
|
7237a37104 | ||
|
|
c864cec32f | ||
|
|
f7f2efaace |
No files matched your search
@@ -0,0 +1,129 @@
|
||||
---
|
||||
name: pr
|
||||
description: Prepare and open an OpenIDEA pull request that a maintainer can accept from its description — scope check, the checks CI runs, evidence chosen by the kind of change, UX consistency review, and a filled-in template. Use before opening or updating a PR ("提 pr", "open a PR", "写 PR 描述", "准备验收证据").
|
||||
---
|
||||
|
||||
# Open a pull request with evidence
|
||||
|
||||
A reviewer should be able to accept the PR from its description: what changed, why, and proof
|
||||
that it works and didn't break its neighbours. Evidence is the part people skip; it is required.
|
||||
|
||||
## 1. Scope
|
||||
|
||||
- One problem per PR. If the description needs more than 2–4 sentences, split it.
|
||||
- `Closes #<n>` when it resolves an issue. Read the issue's comments first: a maintainer may
|
||||
already have decided how it should behave.
|
||||
- The diff contains only what the problem needs: no drive-by refactors, formatting of untouched
|
||||
files, generated files you didn't need to regenerate, or local IDE state (`.openidea/`).
|
||||
- A product decision you can't make (layout or navigation restructure, a changed default, an
|
||||
unclear expected behaviour) → ask in the issue, label `needs-decision`, stop.
|
||||
- Title in Conventional Commits, written as the commit you want on `main`:
|
||||
`fix(editor): keep the caret visible after folding`. It describes the change, not the
|
||||
process; no references to screenshots, other products or "parity".
|
||||
|
||||
## 2. Checks
|
||||
|
||||
Run what CI runs for the parts you touched (`AGENTS.md` § Before opening a PR). Run long checks
|
||||
one at a time. Paste the command and its result line (`test result: ok. 412 passed`,
|
||||
`Tests 87 passed`), not "tests pass".
|
||||
|
||||
Easy to miss:
|
||||
|
||||
| You touched | Also run |
|
||||
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
||||
| Any `.ts`/`.tsx`, including tests | `pnpm typecheck` |
|
||||
| A feature's UI | every spec under `e2e/` whose name contains the feature |
|
||||
| New regex in frontend code | `pnpm vitest run src/platform/webkitCompatibility.test.ts` |
|
||||
| Text catalog keys | `pnpm vitest run src/platform/locales/textCatalog.test.ts src/platform/i18n.test.ts` |
|
||||
| `tokens.css` | `pnpm gen:theme-docs`, then the full `pnpm test` |
|
||||
| Moved or removed exports | `pnpm knip` |
|
||||
| A `pub fn` signature | `cargo test -p <crate>` (all targets), or workspace clippy |
|
||||
| A new crate dependency, or imports in files the smoke runs load | `pnpm vitest run scripts/smoke-paths.test.ts` |
|
||||
| IPC types | `pnpm gen:bindings`, commit `src/bindings.ts` |
|
||||
| `wit/` or the plugin SDK | `plugins/build.sh`, commit the rebuilt `dist/` |
|
||||
|
||||
## 3. Evidence
|
||||
|
||||
Pick every row that applies. Evidence must come from the final commit of the branch; re-take it
|
||||
after review changes that affect it.
|
||||
|
||||
| Change | Evidence |
|
||||
| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Bug fix | A test that fails on `main` and passes on the branch (name it), or exact steps from a fresh start with the before/after result |
|
||||
| Visible UI | `before.png` / `after.png` at the same state and window size. Every theme the change touches (at least Islands Light and Islands Dark when colours, borders or icons change). The narrow case when width matters |
|
||||
| Interaction: multi-step, drag and drop, keyboard, focus, animation | A short recording (GIF/MP4), or numbered screenshots of each step |
|
||||
| Keyboard shortcut or action | Where it appears (Find Action, menu, keymap settings) and that it doesn't clash in the default keymaps |
|
||||
| Code intelligence / language support | Which `fixtures/` project, `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` output; for Java, `pnpm eval --only <id>` numbers before/after |
|
||||
| Run / debug | `pnpm smoke smoke/run.test.ts -t <language>` or `smoke/debug.test.ts`, plus a screenshot of the Run/Debug tool window |
|
||||
| Performance | Before/after numbers on the same machine and build type (`pnpm perf`, `pnpm perf:rust`, or the exact measurement), and evidence the results are identical: a fast path must return the same results or fall back |
|
||||
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine. Say plainly if you couldn't run it on that platform |
|
||||
| Backend / IPC | Test output; logs for behaviour tests can't reach |
|
||||
| Remote development / containers / WSL | The flow against a real `openidea-server` host or container, with a screenshot or log |
|
||||
| Plugin API / `wit/` | A sample plugin exercising the change, and the rebuilt `dist/` |
|
||||
| Settings / persisted data / migrations | Start from data written by the previous release and show it still loads and behaves the same |
|
||||
| Security fix | A test for the attack case. Describe the class of problem only; follow `SECURITY.md` for anything not yet public |
|
||||
| Copy, docs, pure refactor | The commands run, and "No visible change" / "no behaviour change" stated |
|
||||
|
||||
Also state what else the change could affect (other languages, platforms, entry points such as
|
||||
menu / context menu / shortcut, other themes) and how you checked each.
|
||||
|
||||
How to capture:
|
||||
|
||||
- Use the `verify` skill to drive the app and take screenshots. Before: on `main` (or with the
|
||||
fix reverted). After: on the branch, same state and window size.
|
||||
- Crop to the relevant area when the window is large, but keep enough context to locate it.
|
||||
- Drag screenshots and recordings into the PR description on GitHub. Never commit them.
|
||||
- No real credentials, tokens, private repository names or personal paths in screenshots or logs.
|
||||
|
||||
## 4. UX consistency
|
||||
|
||||
For any change users can see, review it against `DESIGN.md`, `PRODUCT.md` and
|
||||
`docs/en/contribute/guidelines/ui.mdx` before taking the "after" screenshots:
|
||||
|
||||
- Tokens only; spacing on the `--space-*` scale; icons from `src/ui/icons.tsx`; no emoji.
|
||||
- Built from `src/ui/` primitives and workbench contributions; it looks like its neighbours
|
||||
(same row height, font size, padding, hover/selection, empty state) rather than new.
|
||||
- Same action, same name, place and shortcut as elsewhere in the IDE.
|
||||
- Keyboard reachable, visible focus, focus returns sensibly; `aria-label` on icon buttons.
|
||||
- Every new string in `en.json` and `zh.json`; long translations don't break the layout.
|
||||
- Light and dark, default and narrow widths all look right.
|
||||
- The Impeccable design skills can help critique and polish; they read `DESIGN.md`,
|
||||
`PRODUCT.md` and `.impeccable/`.
|
||||
|
||||
A layout or navigation restructure needs a maintainer decision first (§ 1).
|
||||
|
||||
## 5. Description
|
||||
|
||||
Fill in `.github/pull_request_template.md`; keep it short and plain:
|
||||
|
||||
```markdown
|
||||
Closes #123
|
||||
|
||||
## What and why
|
||||
|
||||
<The change a user notices, and the root cause. 2–4 sentences.>
|
||||
|
||||
## How it was verified
|
||||
|
||||
- [x] Bug fix: `pnpm vitest run src/features/editor/folding.test.ts` — the new
|
||||
`keeps caret visible after fold` fails on main, passes here (12 passed)
|
||||
- [x] Visible UI: before / after (Islands Light, Islands Dark)
|
||||
<screenshots>
|
||||
- `pnpm typecheck`, `pnpm lint`, `pnpm e2e e2e/editor-folding.spec.ts` — all pass
|
||||
- Also affected: folding from the gutter and from ⌘- — both checked in the app
|
||||
|
||||
## Review focus
|
||||
|
||||
<Optional.>
|
||||
```
|
||||
|
||||
The `PR check` workflow labels the PR `needs-info` when **How it was verified** is empty, or when
|
||||
the PR changes UI files and the section has no screenshot or recording and doesn't say
|
||||
"No visible change".
|
||||
|
||||
## 6. Before you push
|
||||
|
||||
- Re-read the diff as the reviewer: anything unrelated, debug output, commented-out code,
|
||||
leftover TODOs?
|
||||
- Rebased on current `main`; checks re-run if the rebase changed anything they cover.
|
||||
- Open as draft while evidence is missing; mark ready once it's in.
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
name: verify
|
||||
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
|
||||
---
|
||||
|
||||
# Verify OpenIDEA in the running app
|
||||
|
||||
## Launch
|
||||
|
||||
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
|
||||
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
|
||||
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
|
||||
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
|
||||
session already running for this worktree, reuse that one.
|
||||
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
|
||||
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
|
||||
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
|
||||
`location.href` before acting if anything looks off.
|
||||
- Make sure the binary contains the change: a session already running for this worktree may be an
|
||||
older build. Restart it after Rust changes; frontend changes reload through Vite.
|
||||
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
|
||||
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
|
||||
reload shows an empty `#root`. Stop that app and start the session again.
|
||||
- Stop everything you started when done and nothing else; never use process-name kills.
|
||||
|
||||
## Driving
|
||||
|
||||
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
|
||||
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
|
||||
screenshots come back black.
|
||||
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
|
||||
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
|
||||
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
|
||||
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
|
||||
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
|
||||
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
|
||||
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
|
||||
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
|
||||
|
||||
## Evidence
|
||||
|
||||
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
|
||||
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
|
||||
flows: a numbered series (`after-1.png`, `after-2.png`, ...). When colours, borders or icons
|
||||
change, take each in Islands Light and Islands Dark. The `pr` skill lists what evidence each
|
||||
kind of change needs.
|
||||
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
|
||||
acceptance entry. Never commit screenshots to the feature branch.
|
||||
|
||||
## Fixture
|
||||
|
||||
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
|
||||
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
|
||||
|
||||
## Flows worth driving
|
||||
|
||||
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
|
||||
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
|
||||
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
|
||||
Symlink
@@ -0,0 +1 @@
|
||||
../../.agents/skills/pr
|
||||
Symlink
@@ -0,0 +1 @@
|
||||
../../.agents/skills/verify
|
||||
@@ -11,3 +11,10 @@ package(=ide-clipboard) & (
|
||||
)
|
||||
'''
|
||||
test-group = "windows-clipboard"
|
||||
|
||||
# The Subversion tests run svn against throwaway servers: none should take minutes. A test
|
||||
# that hangs (a server left stopped) is ended after 5 minutes instead of waiting for svn's own
|
||||
# timeout.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(=ide-svn) | (package(=ide-host) & (binary(=svn) | binary(=ij_svn_roots)))'
|
||||
slow-timeout = { period = "60s", terminate-after = 5 }
|
||||
Бінарний файл не відображається.
|
До Ширина: | Висота: | Розмір: 169 KiB |
Бінарний файл не відображається.
|
Після Ширина: | Висота: | Розмір: 179 KiB |
@@ -7,11 +7,20 @@
|
||||
|
||||
## How it was verified
|
||||
|
||||
<!-- Required. Commands you actually ran and their results; what else this could
|
||||
affect and how you checked it still works.
|
||||
Visible UI changes: before/after screenshots (not for removed UI or copy-only
|
||||
changes). Multi-step interactions: a recording.
|
||||
Backend changes: logs or command output. -->
|
||||
<!-- Required, from the final version of this branch. Commands you actually ran and
|
||||
their results; what else this could affect and how you checked it still works.
|
||||
Then the evidence for each kind of change this PR makes (AGENTS.md § Issues & PRs):
|
||||
|
||||
- Bug fix: a test that fails on main and passes here, or exact repro steps
|
||||
- Visible UI: before/after screenshots, same state and size; each theme touched
|
||||
- Interaction (multi-step, drag, keyboard, focus): a recording
|
||||
- Code intelligence / run / debug: language_smoke or smoke output on a fixture
|
||||
- Performance: before/after numbers on the same machine, and the results unchanged
|
||||
- Windows/Linux only: CI job plus a screenshot or log from a real machine
|
||||
- Settings / persisted data: starting from the previous version's data
|
||||
- Copy, docs, refactor, no UI change: write "No visible change"
|
||||
|
||||
Drag screenshots and recordings in here; don't commit them. -->
|
||||
|
||||
## Review focus
|
||||
|
||||
|
||||
@@ -106,8 +106,9 @@ jobs:
|
||||
if: needs.changes.outputs.rust == 'true'
|
||||
permissions:
|
||||
contents: read
|
||||
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run.
|
||||
timeout-minutes: ${{ matrix.os == 'windows-latest' && 75 || 60 }}
|
||||
# A Windows build that misses the Rust cache spends ~50 minutes compiling before the tests run;
|
||||
# on macOS clippy plus the test build alone take ~45 minutes.
|
||||
timeout-minutes: ${{ matrix.os == 'ubuntu-latest' && 60 || 75 }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -150,8 +151,18 @@ jobs:
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf subversion sqlite3)
|
||||
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
|
||||
# The Subversion tests run the real svn, svnadmin and svnserve (and sqlite3, to write a
|
||||
# working copy's database); with CI set they fail instead of skipping when these are
|
||||
# missing. Linux gets them with the deps above; macOS has sqlite3. Windows runners skip them.
|
||||
- name: Subversion (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
run: command -v svnadmin >/dev/null || brew install subversion
|
||||
- name: Subversion version
|
||||
if: runner.os != 'Windows'
|
||||
shell: bash
|
||||
run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version
|
||||
# tauri-build checks that frontendDist exists.
|
||||
- run: pnpm install --frozen-lockfile && mkdir -p dist
|
||||
shell: bash
|
||||
@@ -360,6 +371,12 @@ jobs:
|
||||
node-version: 22
|
||||
cache: ${{ runner.environment != 'self-hosted' && 'pnpm' || '' }}
|
||||
package-manager-cache: ${{ runner.environment != 'self-hosted' }}
|
||||
# src/features/dotnet/edit.test.ts and *.cli.test.ts run the real `dotnet` CLI; with CI set they fail, not skip, when it is missing.
|
||||
- uses: actions/setup-dotnet@v5
|
||||
with:
|
||||
dotnet-version: |
|
||||
10.0.x
|
||||
11.0.x
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm lint
|
||||
|
||||
@@ -34,7 +34,9 @@ on:
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/core/cm/inlineBg.ts"
|
||||
- "src/editor/core/cm/localAppearance.ts"
|
||||
- "src/editor/core/cm/lineNumberOptions.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
- "src/editor/lsp/files.ts"
|
||||
@@ -45,7 +47,7 @@ on:
|
||||
- "src/bindings.ts"
|
||||
- "src/styles/tokens.css"
|
||||
- "src/test/setup.ts"
|
||||
- "src-tauri/icons/128x128.png"
|
||||
- "src/assets/openidea-logo.png"
|
||||
- "smoke/**"
|
||||
- "vite.config.ts"
|
||||
- "tsconfig.json"
|
||||
@@ -109,7 +111,7 @@ jobs:
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|lineNumberOptions|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src/assets/openidea-logo\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
name: PR check
|
||||
on:
|
||||
# pull_request_target so the check can label PRs from forks. It never checks out
|
||||
# or runs PR code: it only reads the PR title and description.
|
||||
# or runs PR code: it only reads the PR title, description and changed file names.
|
||||
pull_request_target:
|
||||
types: [opened, edited, reopened, ready_for_review]
|
||||
types: [opened, edited, reopened, ready_for_review, synchronize]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
@@ -34,6 +34,24 @@ jobs:
|
||||
|
||||
const { owner, repo } = context.repo;
|
||||
const issue_number = pr.number;
|
||||
|
||||
if (verified && verified[1].trim()) {
|
||||
const section = verified[1];
|
||||
const hasMedia =
|
||||
/!\[[^\]]*\]\(|<img\b|<video\b|github\.com\/user-attachments\/|https?:\/\/\S+\.(png|jpe?g|gif|webp|mp4|mov|webm)\b/i.test(section);
|
||||
const optedOut = /no visible change/i.test(section);
|
||||
if (!hasMedia && !optedOut) {
|
||||
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: issue_number, per_page: 100 });
|
||||
const ui = files
|
||||
.filter(f => f.status !== 'removed')
|
||||
.map(f => f.filename)
|
||||
.filter(name => /^src\/.*\.(tsx|css)$/.test(name) && !/\.(test|spec)\.tsx$/.test(name));
|
||||
if (ui.length) {
|
||||
const shown = ui.slice(0, 3).map(n => `\`${n}\``).join(', ') + (ui.length > 3 ? ', …' : '');
|
||||
problems.push(`This PR changes UI files (${shown}). Add before/after screenshots, or a recording for interactions, to **How it was verified**; if nothing users see changed, write "No visible change" and say what you checked.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
|
||||
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes(MARKER));
|
||||
const labeled = pr.labels.some(l => l.name === LABEL);
|
||||
|
||||
@@ -284,6 +284,8 @@ jobs:
|
||||
return;
|
||||
}
|
||||
// Bundle suffix → updater platform keys, as tauri-action names them.
|
||||
// Nightly builds skip RPM because RPM rejects `-` in SemVer prerelease versions.
|
||||
const nightly = tag.includes("-nightly.");
|
||||
const windows = (arch, msi, nsis) => [
|
||||
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
|
||||
[nsis, [`windows-${arch}-nsis`]],
|
||||
@@ -291,10 +293,10 @@ jobs:
|
||||
const kinds = [
|
||||
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
|
||||
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
|
||||
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
|
||||
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
|
||||
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
|
||||
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
|
||||
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
|
||||
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
|
||||
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
|
||||
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
|
||||
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
|
||||
|
||||
+6
-5
@@ -33,12 +33,13 @@ target/
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
# Local AI agent files
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
|
||||
CLAUDE.local.md
|
||||
.agents/
|
||||
.claude/
|
||||
.claude/*
|
||||
!.claude/skills/
|
||||
.claude/skills/*
|
||||
!.claude/skills/pr
|
||||
!.claude/skills/verify
|
||||
|
||||
# Local reference screenshots
|
||||
pycharm-screenshots/
|
||||
@@ -15,10 +15,12 @@
|
||||
"src/editor/core/cm/jsp/parser*.ts",
|
||||
"src/editor/core/cm/astro/parser*.ts",
|
||||
"src/editor/core/cm/django/parser*.ts",
|
||||
"src/editor/core/cm/freemarker/parser*.ts",
|
||||
"plugins/themes.md",
|
||||
"pnpm-lock.yaml",
|
||||
"**/*.toml",
|
||||
"fixtures",
|
||||
"vendor",
|
||||
"plugins/*/web",
|
||||
"plugins/official/*/web",
|
||||
"crates/**/tests/fixtures"
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"src/editor/core/cm/angular/parser*.ts",
|
||||
"src/editor/core/cm/astro/parser*.ts",
|
||||
"fixtures",
|
||||
"vendor",
|
||||
"plugins",
|
||||
"test-results",
|
||||
"playwright-report",
|
||||
@@ -152,7 +153,10 @@
|
||||
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
|
||||
"excludeFiles": ["e2e/**"],
|
||||
"rules": {
|
||||
"no-await-in-loop": "error"
|
||||
"no-await-in-loop": "error",
|
||||
"react/no-array-index-key": "error",
|
||||
"react/jsx-no-constructed-context-values": "error",
|
||||
"react/no-object-type-as-default-prop": "error"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
# OpenIDEA — contributor guide
|
||||
|
||||
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
|
||||
Visual style: rounded content islands on a grey frame, low-contrast greys, one cool accent;
|
||||
Islands Light is the default theme. `src/styles/tokens.css` is the source of truth for colours
|
||||
and metrics; `DESIGN.md` and `PRODUCT.md` describe the design system and who the product is for.
|
||||
|
||||
## Layout
|
||||
|
||||
- `crates/ide-*` — backend crates; one domain each. Depend on `ide-core` for shared
|
||||
types; never reach into another crate's internals.
|
||||
- `src-tauri/` — glue only: `state.rs` (AppState / Project), `commands/<domain>.rs`
|
||||
(desktop-only commands; the adapters of `ide-host` commands are derived), `events.rs`.
|
||||
No domain logic here.
|
||||
- `src/bindings.ts` — generated by tauri-specta (`pnpm gen:bindings`). Never edit.
|
||||
- `src/platform/` — ipc (`call`, `onIdeEvent`, `nextRequestId`), actions registry,
|
||||
keymap + dispatcher, context keys / `when` clauses, project store.
|
||||
- `src/workbench/contributions.ts` — extension points (tool windows, status items,
|
||||
overlays, editor kinds) and cross-feature services (editor, tool windows, notifications).
|
||||
- `src/ui/` — design-system primitives. `src/features/<name>/` — one feature each,
|
||||
exporting `activate()` registered in `src/features/index.ts`.
|
||||
- `languages/<id>.toml` — language definitions (detection, comments, LSP, DAP).
|
||||
- `crates/ide-host` — the `openidea-server` binary for remote development and the
|
||||
`openidea-plugin` CLI (plugin starter templates live in its `templates.rs`).
|
||||
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins.
|
||||
Plugin docs: `plugins/README.md`, `plugins/themes.md`.
|
||||
- `java/` — JDT LS extension bundles (`java-usages`, `kotlin-bridge`) and the patched
|
||||
Lombok agent, embedded into the app by `ide-sdk` / `ide-tools`.
|
||||
- `e2e/` — Playwright UI tests (`pnpm e2e`). `evals/` — code-intelligence evals (`pnpm eval`).
|
||||
`fixtures/` — sample projects per language for manual and automated testing.
|
||||
- `docs/` — the Mintlify documentation site (`docs.json` navigation, `en/` and `zh/` pages);
|
||||
preview with `npx mint dev` in `docs/`.
|
||||
|
||||
## Rules
|
||||
|
||||
- IPC coordinates: 0-based lines, **UTF-16** columns/offsets everywhere (`ide-core::text`).
|
||||
- Every command returns `IdeResult<T>`; convert internal errors at the crate edge.
|
||||
- Declare a command once, on its implementation: `#[command(trust = …)]` in `ide-host::ops`
|
||||
plus its module's `domain!` list (Tauri adapter, server handler and bindings are derived);
|
||||
desktop-only commands use `#[desktop_command(trust = …)]` and `desktop_domain!`.
|
||||
- Streaming → `tauri::ipc::Channel<T>`; cancellable → UI-allocated `RequestId` +
|
||||
`cancel_request`. Backend → UI notifications → `IdeEvent` via `EventSink`.
|
||||
- Long work never blocks the UI thread or a Tauri command thread: use
|
||||
`spawn_blocking`/rayon, honour `CancellationToken`.
|
||||
- Frontend features never import each other; communicate via actions, contributions
|
||||
and services. All user-invocable behaviour is an action with a stable id; default
|
||||
shortcuts live in `src/platform/keymaps/`.
|
||||
- Styling: CSS Modules + tokens only (no hex literals in components). Inline SVG
|
||||
icons from `src/ui/icons.tsx`, never emoji. Real `<button>`/`<input>`; `aria-label` on icon buttons.
|
||||
`gap` uses the `--space-*` scale (`src/styles/tokens.css`, 4px grid) where a value is on it.
|
||||
- User-visible text goes through the text catalog: add every new string to both
|
||||
`src/platform/locales/text/en.json` and `zh.json` (`textCatalog.test.ts` enforces it).
|
||||
Other locales may lack entries; their UI shows the English text until a translator adds it.
|
||||
- Keep comments sparse and purposeful; match surrounding style.
|
||||
- New regular expressions in frontend code must run on WebKit (no lookbehind):
|
||||
`src/platform/webkitCompatibility.test.ts` checks them.
|
||||
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
|
||||
unavailable or cannot cover the required checks.
|
||||
|
||||
## UX changes
|
||||
|
||||
A change to what users see or how they interact must look and behave like the rest of the IDE.
|
||||
|
||||
- `DESIGN.md` (colours, type, layout, components, Do's and Don'ts) and `PRODUCT.md`
|
||||
(users, principles, accessibility) are the reference; `docs/en/contribute/guidelines/ui.mdx`
|
||||
has the code-level rules. Build from `src/ui/` primitives and workbench contributions;
|
||||
don't create a one-off control, colour or spacing when an existing one fits.
|
||||
- Check every theme the change touches (at least Islands Light and Islands Dark) and narrow
|
||||
sizes (e.g. the Commit tool window at its default width, a small window). Long translated
|
||||
strings must not break the layout.
|
||||
- Everything works from the keyboard; focus is visible and lands somewhere sensible when a
|
||||
popup or dialog closes. Icon-only buttons have an `aria-label` and a tooltip.
|
||||
- Follow the conventions users of this kind of IDE already know: the same action keeps the
|
||||
same name, place and shortcut across views. Don't invent a new pattern for an existing one.
|
||||
- Agent and MCP features follow good agent-tool practice: restrained, predictable, reversible.
|
||||
- Restructuring a page layout or navigation, or changing a default behaviour, needs a
|
||||
maintainer's decision first: ask in the issue and label it `needs-decision`.
|
||||
- The Impeccable design skills may be used for design critique and polish; they read
|
||||
`DESIGN.md`, `PRODUCT.md` and `.impeccable/`. A detector exception goes in
|
||||
`.impeccable/config.json` with a reason.
|
||||
|
||||
## Issues & PRs
|
||||
|
||||
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one problem per PR
|
||||
(`Closes #<n>` when it resolves an issue), reproduce first, keep the diff focused, short plain
|
||||
description. Unclear product decisions → `needs-decision` and stop.
|
||||
|
||||
Every PR carries evidence a reviewer can accept without re-running everything, in
|
||||
**How it was verified**. It must come from the final version of the branch:
|
||||
|
||||
| Change | Evidence |
|
||||
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Bug fix | A test that fails before the fix and passes after, or exact reproduction steps with before/after result |
|
||||
| Visible UI | Before/after screenshots at the same state and window size; each theme the change touches |
|
||||
| Interaction (multi-step, drag, keyboard, focus) | A short recording or numbered screenshots |
|
||||
| Code intelligence / language support | The fixture used and `language_smoke` output; `pnpm eval` numbers for Java |
|
||||
| Run / debug | `pnpm smoke smoke/run.test.ts` / `smoke/debug.test.ts -t <language>` output |
|
||||
| Performance | Before/after numbers on the same machine (`pnpm perf`, `pnpm perf:rust` or a stated measurement), plus proof the results are unchanged |
|
||||
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine |
|
||||
| Backend / IPC | Test output; regenerated `src/bindings.ts` when types changed |
|
||||
| Remote development | The flow against a real `openidea-server` host |
|
||||
| Plugin API / `wit/` | `plugins/build.sh` run and `dist/` committed; a sample plugin using the change |
|
||||
| Settings / persisted data | Behaviour when starting from data written by the previous version |
|
||||
| Copy, docs, refactor | The commands run; "No visible change" when nothing users see changed |
|
||||
|
||||
Attach screenshots and recordings to the PR description; never commit them. The `pr` skill
|
||||
has the full checklist.
|
||||
|
||||
## Skills
|
||||
|
||||
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
|
||||
`pr` prepares a pull request — checks to run, evidence for the kind of change, description;
|
||||
`verify` drives the running app through Tauri MCP and captures screenshot evidence.
|
||||
|
||||
## Commands
|
||||
|
||||
- Optional: `mise install` provisions the contributor toolchain; `mise tasks` lists the task aliases.
|
||||
See [Development setup](docs/en/contribute/setup.mdx). The direct commands below still work without mise.
|
||||
- `pnpm tauri dev` — run the app with worktree isolation. Use Node 22.22.2 or later on the 22.x line.
|
||||
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
|
||||
this worktree's running MCP bridges and actual ports.
|
||||
- `pnpm build` — typecheck + bundle frontend.
|
||||
- `pnpm dogfood:local [--build-only]` (or `mise run dogfood:local`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
|
||||
- `pnpm dogfood:remote <remote_name> [--restart | --no-restart] [--clean]` (or `mise run dogfood:remote <remote_name>`) — sync backend sources to a host from **Tools › SSH Configurations**, build `openidea-server`, and stage it for Remote Development.
|
||||
- `pnpm dogfood:all <remote_name> [--restart | --no-restart]` (or `mise run dogfood:all <remote_name>`) — run `dogfood:local` and `dogfood:remote <remote_name>` in parallel.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
- `pnpm smoke smoke/run.test.ts -t <language>` — run and test that language's fixture through the
|
||||
run store and a real `openidea-server` (build it first: `cargo build -p ide-host --bin openidea-server`).
|
||||
- `pnpm smoke smoke/debug.test.ts -t <language>` — debug that fixture's entry point the same way, with
|
||||
the debugger the IDE installs (on macOS, CodeLLDB and Delve may need Developer Mode:
|
||||
`sudo DevToolsSecurity -enable`).
|
||||
- `pnpm test`, `pnpm e2e`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm typecheck`,
|
||||
`pnpm gen:bindings`.
|
||||
- `pnpm perf` (UI interaction latency / frames / leaks), `pnpm perf:rust` (criterion
|
||||
benches vs budgets). Budgets: `perf/budgets.json`.
|
||||
- `pnpm eval [--only <id>] [--runs n] [--save-baseline]` — Java code intelligence (navigation,
|
||||
usages, gutter markers) in the production workbench against a release `openidea-server` and
|
||||
jdtls: time to feedback / first result / complete, results vs `evals/<language>/golden/`.
|
||||
Report: `target/eval/report.json`. Goldens and `evals/budgets.json` are changed by people only.
|
||||
Tool versions: `.github/tool-versions.env` (shared with Language smoke).
|
||||
- `pnpm release:prepare <version>` — the release commit's changes: app version everywhere,
|
||||
`Cargo.lock`, and the plugin API snapshot when `wit/` moved to a new version.
|
||||
|
||||
## Before opening a PR
|
||||
|
||||
Run what CI runs for the parts you touched:
|
||||
|
||||
- Rust: `cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`,
|
||||
`cargo nextest run --workspace`. After changing IPC types, run `pnpm gen:bindings` and
|
||||
commit `src/bindings.ts`; CI fails if it differs.
|
||||
- Frontend: `pnpm typecheck` (vitest does not type-check), `pnpm lint`, `pnpm format:check`,
|
||||
`pnpm knip`, `pnpm test`, `pnpm build`, and every `e2e/` spec of the feature you touched.
|
||||
- New text keys: `src/platform/locales/textCatalog.test.ts` and `src/platform/i18n.test.ts`.
|
||||
New or renamed tokens: `pnpm gen:theme-docs`.
|
||||
- Changed a `pub fn` signature in a crate: run that crate's whole `cargo test`, not one test.
|
||||
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`) and collect
|
||||
the evidence above (`.agents/skills/pr`).
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- Run a subset of frontend tests with `pnpm vitest run <path>`. `pnpm test -- <path>` ignores
|
||||
the filter and runs the whole suite, which takes several minutes.
|
||||
- Don't run clippy while iterating: `pnpm tauri dev` compiles anyway. Run
|
||||
`cargo fmt --all` + `cargo clippy -p <crate> --all-targets -- -D warnings` once, right
|
||||
before committing. A cold build cache can take around 5 minutes. Run long checks one at
|
||||
a time, not chained in one shell call that may hit the 10-minute tool timeout.
|
||||
- `pnpm tauri dev` does a full debug build. Clippy only checks the code, so a passing clippy
|
||||
doesn't make the first launch fast.
|
||||
|
||||
## Parallel worktrees
|
||||
|
||||
Several worktrees can be developed and run side by side.
|
||||
|
||||
- Create one per task: `git worktree add ../<name> -b <branch> origin/main`, then
|
||||
`pnpm install` in it.
|
||||
- Launch with `pnpm tauri dev` / `pnpm dev:app`, not the raw `pnpm exec tauri dev` CLI. The
|
||||
wrapper starts Vite on a worktree-derived port (advancing if occupied), passes its actual
|
||||
URL to Tauri, and reports an existing launcher instead of starting another for the same
|
||||
worktree. HMR uses the Vite port.
|
||||
- Debug app identity, data, settings, logs and single-instance scope follow the canonical
|
||||
worktree path captured at build time, independent of launch cwd. Launching the same debug
|
||||
binary again focuses its existing instance and forwards its path argument. Different
|
||||
worktrees and the installed release can coexist. `--release` uses normal release identity
|
||||
and bypasses the development wrapper.
|
||||
- MCP bridge ports are dynamic (9223–9322). Use `pnpm dev:status`, connect to the reported
|
||||
port, verify identifier/cwd, and pass `appIdentifier: <port>` explicitly. Do not assume the
|
||||
default MCP session belongs to this worktree.
|
||||
- Keep each worktree's Cargo output directory separate; do not point `CARGO_TARGET_DIR` or
|
||||
`target` symlinks at a shared directory.
|
||||
- Each worktree's first build is cold (several minutes) and `cargo build` output takes
|
||||
around 9 GB; tests, clippy and incremental builds add more. Avoid running several heavy builds on one machine at the same time.
|
||||
- Stop only processes started for the current worktree/session. Never use broad
|
||||
process-name kills such as `pkill openidea`.
|
||||
- When done: stop that worktree's app and dev session, delete its build output, then
|
||||
`git worktree remove ../<name>`.
|
||||
Symlink
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
@@ -1,6 +1,7 @@
|
||||
# Contributing to OpenIDEA
|
||||
|
||||
These rules apply to everyone, and to any coding agent working on their behalf.
|
||||
Project layout, coding rules, commands, checks and the evidence a PR needs are in [AGENTS.md](AGENTS.md).
|
||||
|
||||
## Issues
|
||||
|
||||
@@ -26,7 +27,12 @@ These rules apply to everyone, and to any coding agent working on their behalf.
|
||||
- **How it was verified** is required: the commands you ran and their results,
|
||||
and what else the change could affect. Changes to what users see need before/after
|
||||
screenshots; multi-step interactions need a recording. UI that goes away with a removed
|
||||
feature, copy-only and non-visual changes don't; say what you checked instead.
|
||||
feature, copy-only and non-visual changes don't; write "No visible change" and say what
|
||||
you checked instead. [AGENTS.md](AGENTS.md#issues--prs) lists the evidence for each kind of
|
||||
change (tests, smoke output, perf numbers, real-machine logs…).
|
||||
- Changes to what users see follow [DESIGN.md](DESIGN.md) and the existing UI: tokens,
|
||||
`src/ui/` primitives, both themes, keyboard access. Restructuring a layout or navigation
|
||||
needs a maintainer's decision first.
|
||||
- If a change needs a product decision you can't make, ask in the issue and stop
|
||||
rather than guessing.
|
||||
|
||||
@@ -35,4 +41,4 @@ and the plugin API. Community plugins live in their authors' repositories and
|
||||
are listed through [l0ng-ai/openidea-plugins](https://github.com/l0ng-ai/openidea-plugins);
|
||||
see [`plugins/README.md`](plugins/README.md) § 8.1.
|
||||
|
||||
A check on each PR adds `needs-info` when the verification section is missing, and removes it once it's filled in.
|
||||
A check on each PR adds `needs-info` when the verification section is missing, or when the PR changes UI files and the section has neither a screenshot nor a recording nor "No visible change". It removes the label once that's fixed.
|
||||
Створено
+320
-410
File diff suppressed because it is too large.
Load diff
+10
-2
@@ -2,10 +2,10 @@
|
||||
resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
# Plugins and the guest SDK build for wasm32-wasip2 in their own workspaces.
|
||||
exclude = ["sdk", "plugins"]
|
||||
exclude = ["sdk", "plugins", "vendor"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.56"
|
||||
version = "0.1.57"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -24,6 +24,7 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
|
||||
ide-lsp = { path = "crates/ide-lsp" }
|
||||
ide-dap = { path = "crates/ide-dap" }
|
||||
ide-vcs = { path = "crates/ide-vcs" }
|
||||
ide-svn = { path = "crates/ide-svn" }
|
||||
ide-github = { path = "crates/ide-github" }
|
||||
ide-terminal = { path = "crates/ide-terminal" }
|
||||
ide-run = { path = "crates/ide-run" }
|
||||
@@ -90,6 +91,7 @@ trash = "5"
|
||||
blake3 = "1"
|
||||
dunce = "1"
|
||||
dirs = "6"
|
||||
jiff = "0.2"
|
||||
memmap2 = "0.9"
|
||||
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
|
||||
flate2 = "1"
|
||||
@@ -99,6 +101,7 @@ tar = "0.4"
|
||||
grep-searcher = "0.1"
|
||||
grep-regex = "0.1"
|
||||
regex-syntax = "0.8"
|
||||
regex = "1"
|
||||
grep-matcher = "0.1"
|
||||
nucleo-matcher = "0.3"
|
||||
redb = "4"
|
||||
@@ -158,3 +161,8 @@ opt-level = 3
|
||||
panic = "unwind"
|
||||
# Keep the symbol table: crash reports and logged backtraces name functions.
|
||||
strip = "debuginfo"
|
||||
|
||||
# tauri-plugin-mcp-bridge 0.13.2 (debug-only E2E bridge) pins `tauri ~2.12`; this copy only widens
|
||||
# that requirement to 2.13. Drop it once a release supporting tauri 2.13 is published.
|
||||
[patch.crates-io]
|
||||
tauri-plugin-mcp-bridge = { path = "vendor/tauri-plugin-mcp-bridge" }
|
||||
@@ -6,6 +6,11 @@ contributors as part of the IntelliJ Platform (https://github.com/JetBrains/inte
|
||||
https://github.com/JetBrains/intellij-plugins), licensed under the Apache License 2.0.
|
||||
Copyright 2000-2026 JetBrains s.r.o. and contributors.
|
||||
|
||||
The Subversion tests (crates/ide-svn/tests/matrix.rs) take the tree-conflict scenarios,
|
||||
their names and file contents from IntelliJ's svn4idea TreeConflictData
|
||||
(plugins/svn4idea/testSource/org/jetbrains/idea/svn/), Apache License 2.0, Copyright
|
||||
2000-2026 JetBrains s.r.o. and contributors.
|
||||
|
||||
Some Simplified Chinese UI terms follow the Visual Studio Code Simplified Chinese
|
||||
language pack (https://github.com/microsoft/vscode-loc), Copyright (c) Microsoft
|
||||
Corporation, licensed under the MIT License.
|
||||
|
||||
+2
-2
@@ -71,10 +71,10 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
|
||||
## Community
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP) — questions, feedback and release news.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
|
||||
<img src=".github/assets/wechat-group-5.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
+2
-2
@@ -71,10 +71,10 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
|
||||
|
||||
## Topluluk
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP): sorular, geri bildirim ve sürüm haberleri.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
|
||||
- WeChat grubu, katılmak için kodu okut:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
|
||||
<img src=".github/assets/wechat-group-5.png" alt="WeChat grubu QR kodu" width="200">
|
||||
|
||||
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
@@ -69,10 +69,10 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
|
||||
## 社区
|
||||
|
||||
- [Discord](https://discord.gg/2Zy4yn7gP):提问、反馈和版本发布消息。
|
||||
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
<img src=".github/assets/wechat-group-5.png" alt="微信群二维码" width="200">
|
||||
|
||||
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
`src/ui/brands/*.svg` use the unmodified logo paths from
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## DuckDB symbol
|
||||
|
||||
@@ -288,6 +288,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## tree-sitter-fsharp queries
|
||||
|
||||
`crates/ide-language/queries/fsharp_signature/highlights.scm` is the signature grammar's
|
||||
`highlights.scm` from [tree-sitter-fsharp](https://github.com/ionide/tree-sitter-fsharp)
|
||||
0.3.13 (the grammar itself is a Cargo dependency).
|
||||
|
||||
### MIT License (tree-sitter-fsharp)
|
||||
|
||||
Copyright (c) 2023 Nikolaj Sidorenco
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
## nvim-treesitter queries
|
||||
|
||||
`crates/ide-syntax/queries/<grammar>/locals.scm` are derived from the `locals.scm`
|
||||
|
||||
@@ -18,14 +18,16 @@ ide-tools = { path = "../ide-tools" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
sqlx.workspace = true
|
||||
tokio.workspace = true
|
||||
toml.workspace = true
|
||||
toml_edit.workspace = true
|
||||
tracing.workspace = true
|
||||
parking_lot.workspace = true
|
||||
dunce.workspace = true
|
||||
jiff.workspace = true
|
||||
uuid.workspace = true
|
||||
tempfile.workspace = true
|
||||
which = "8"
|
||||
semver = "1"
|
||||
sha1 = "0.10"
|
||||
|
||||
|
||||
@@ -105,6 +105,7 @@ fn manager(dir: &Path, agent: Arc<FakeV2Agent>) -> AgentManager {
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
|
||||
@@ -53,6 +53,24 @@ pub(crate) fn auth_required(code: i64, message: &str) -> bool {
|
||||
.any(|w| w == ["logged", "out"] || w == ["sign", "in"] || w == ["log", "in"] || w == ["login", "required"])
|
||||
}
|
||||
|
||||
/// Whether a failed request only means the agent hasn't finished starting up: OpenCode
|
||||
/// rejects session opens until the location's plugins and MCP servers finish activating
|
||||
/// (`ServiceUnavailableError`, "Location plugins did not finish activating") and reports
|
||||
/// an unavailable server as `ServerUnavailable`. Both arrive as internal errors naming
|
||||
/// the cause in `data.errorName`; retrying them once activation completes succeeds.
|
||||
pub(crate) fn service_warming_up(error: &RpcError) -> bool {
|
||||
let RpcError::Server { code: codes::INTERNAL_ERROR, message, data } = error else {
|
||||
return false;
|
||||
};
|
||||
if let Some(name) = data.as_ref().and_then(|d| d.get("errorName")).and_then(Value::as_str)
|
||||
&& matches!(name, "ServiceUnavailableError" | "ServerUnavailable")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let lower = message.to_lowercase();
|
||||
lower.contains("did not finish activating") || lower.contains("opencode server is unavailable")
|
||||
}
|
||||
|
||||
/// The capabilities this client offers, in v1 form.
|
||||
fn client_capabilities() -> Value {
|
||||
json!({
|
||||
|
||||
@@ -52,6 +52,40 @@ fn auth_required_matches_authentication_words_and_sign_in_phrases() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_warming_up_matches_opencode_startup_races_only() {
|
||||
for (code, message, data, expected) in [
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure",
|
||||
Some(json!({"errorName": "ServiceUnavailableError"})),
|
||||
true,
|
||||
),
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: OpenCode server is unavailable",
|
||||
Some(json!({"errorName": "ServerUnavailable"})),
|
||||
true,
|
||||
),
|
||||
(codes::INTERNAL_ERROR, "Location plugins did not finish activating", None, true),
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure",
|
||||
Some(json!({"errorName": "SQLiteError"})),
|
||||
false,
|
||||
),
|
||||
(codes::INTERNAL_ERROR, "Internal error: Internal service failure", None, false),
|
||||
(codes::INTERNAL_ERROR, "boom", None, false),
|
||||
(AUTH_REQUIRED, "Authentication required", None, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
service_warming_up(&RpcError::Server { code, message: message.into(), data: data.clone() }),
|
||||
expected,
|
||||
"code={code}, message={message:?}, data={data:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The messages of a fixture going `dir` (`in` or `out`).
|
||||
pub(crate) fn frames(fixture: &str, dir: &str) -> Vec<Value> {
|
||||
fixture
|
||||
@@ -155,6 +189,7 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
|
||||
store_dir: tmp.path().join("store"),
|
||||
worktrees_dir: tmp.path().join("worktrees"),
|
||||
models_file: tmp.path().join("models.json"),
|
||||
cli_dir: tmp.path().join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -468,7 +468,9 @@ impl AgentCatalogs {
|
||||
model: Option<String>,
|
||||
result: Result<Discovered, String>,
|
||||
) {
|
||||
let current = provider::load(shared.paths.custom_agents_dir.as_deref(), shared.env_secrets())
|
||||
let current = shared
|
||||
.paths
|
||||
.provider_specs()
|
||||
.into_iter()
|
||||
.find(|spec| spec.id == key.2)
|
||||
.map(|spec| LaunchContext::new(spec, &shared.paths.project_root));
|
||||
@@ -622,8 +624,7 @@ impl crate::AgentManager {
|
||||
/// Return cached choices immediately and schedule discovery when eligible.
|
||||
pub fn refresh_models(&self, provider: &str, force: bool, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
// Settings and environment secrets can change while this window is open.
|
||||
*self.shared.providers.write() =
|
||||
provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
*self.shared.providers.write() = self.shared.paths.provider_specs();
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
|
||||
}
|
||||
@@ -631,7 +632,10 @@ impl crate::AgentManager {
|
||||
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
|
||||
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
|
||||
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
|
||||
let mut spec = self
|
||||
.shared
|
||||
.paths
|
||||
.provider_specs()
|
||||
.into_iter()
|
||||
.find(|p| p.id == "copilot")
|
||||
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
|
||||
|
||||
@@ -157,6 +157,7 @@ fn make_manager_at(root: &Path, models_file: &Path, catalogs: Arc<AgentCatalogs>
|
||||
store_dir: root.join("store"),
|
||||
worktrees_dir: root.join("worktrees"),
|
||||
models_file: models_file.to_path_buf(),
|
||||
cli_dir: root.join("agent-cli"),
|
||||
catalogs,
|
||||
custom_agents_dir: Some(root.join("agents")),
|
||||
home_dir: Some(root.to_path_buf()),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Checks and updates only the global npm installation selected by the agent launcher.
|
||||
//! Installs built-in CLIs into IDE-owned npm prefixes and updates the npm installation selected by the launcher.
|
||||
use crate::{AgentManager, AgentSource, provider};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -29,6 +29,14 @@ pub enum AgentCliUpdateResult {
|
||||
Error { code: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "status", rename_all = "camelCase")]
|
||||
pub enum AgentCliInstallResult {
|
||||
Installed,
|
||||
NodeRequired,
|
||||
Error { code: String },
|
||||
}
|
||||
|
||||
pub(crate) fn package(id: &str) -> Option<&'static str> {
|
||||
Some(match id {
|
||||
"claude" => "@anthropic-ai/claude-code",
|
||||
@@ -45,6 +53,64 @@ pub(crate) fn package(id: &str) -> Option<&'static str> {
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
/// Installs the built-in CLI into an npm prefix owned by the IDE on this host.
|
||||
pub fn cli_install(
|
||||
&self,
|
||||
id: &str,
|
||||
approved_command: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliInstallResult> {
|
||||
use AgentCliInstallResult::*;
|
||||
let spec = self.shared.paths.provider_specs().into_iter().find(|spec| spec.id == id);
|
||||
let (Some(spec), Some(pkg), Some(builtin)) = (spec, package(id), provider::builtin_spec(id)) else {
|
||||
return Err(IdeError::invalid("This agent has no built-in CLI installer"));
|
||||
};
|
||||
if spec.source != AgentSource::Builtin || spec.command != builtin.command {
|
||||
return Err(IdeError::invalid("This agent has no built-in CLI installer"));
|
||||
}
|
||||
let prefix = self.shared.paths.cli_dir.join(id);
|
||||
if install_command(&prefix, pkg).as_deref() != Some(approved_command) {
|
||||
return Err(IdeError::invalid("The CLI install command changed. Reopen Agent Setup and try again."));
|
||||
}
|
||||
if provider::installed_with_env(spec.executable(), &spec.env) {
|
||||
return Ok(Installed);
|
||||
}
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let Some(npm) = ide_core::process::find_executable("npm", &search)
|
||||
.filter(|_| ide_core::process::find_executable("node", &search).is_some())
|
||||
else {
|
||||
return Ok(NodeRequired);
|
||||
};
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let _lock = lock_prefix(&prefix)?;
|
||||
if managed_cli(&prefix, pkg, &builtin.command).is_some() {
|
||||
return Ok(Installed);
|
||||
}
|
||||
let installation = Installation::at(&prefix, pkg, &builtin.command);
|
||||
// Only publish a CLI after npm has finished and its launcher has been verified.
|
||||
let marker = prefix.join(INSTALLED_MARKER);
|
||||
if marker.exists() {
|
||||
fs::remove_file(&marker)?;
|
||||
}
|
||||
let spec = format!("{pkg}@latest");
|
||||
match run_npm(&npm, &install_args(prefix.to_str().unwrap(), &spec), cancel) {
|
||||
Err(error) if error.kind == ErrorKind::Unavailable => return Ok(Error { code: error.message }),
|
||||
result => result?,
|
||||
};
|
||||
if installation.version(&installation.link, pkg, &builtin.command)?.is_none()
|
||||
|| !provider::installed_with_env(&installation.link.to_string_lossy(), &[])
|
||||
{
|
||||
return Err(IdeError::invalid("npm installation verification failed"));
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
fs::write(marker, [])?;
|
||||
Ok(Installed)
|
||||
}
|
||||
|
||||
pub fn cli_update(
|
||||
&self,
|
||||
id: &str,
|
||||
@@ -58,15 +124,53 @@ impl AgentManager {
|
||||
if spec.source != AgentSource::Builtin {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
}
|
||||
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
|
||||
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
};
|
||||
let prefix = self.shared.paths.cli_dir.join(id);
|
||||
let managed = spec.managed_cli.is_some().then_some(prefix.as_path());
|
||||
let _lock = if offer.is_some() { managed.map(lock_prefix).transpose()? } else { None };
|
||||
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, managed, offer, cancel) {
|
||||
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const INSTALLED_MARKER: &str = ".openidea-installed";
|
||||
|
||||
fn lock_prefix(prefix: &Path) -> IdeResult<fs::File> {
|
||||
fs::create_dir_all(prefix)?;
|
||||
let lock = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(prefix.join(".openidea-install.lock"))?;
|
||||
lock.try_lock().map_err(|error| match error {
|
||||
fs::TryLockError::WouldBlock => IdeError::new(ErrorKind::AlreadyExists, "CLI installation is in progress"),
|
||||
fs::TryLockError::Error(error) => error.into(),
|
||||
})?;
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
pub(crate) fn managed_cli(prefix: &Path, pkg: &str, bin: &str) -> Option<PathBuf> {
|
||||
let link = Installation::at(prefix, pkg, bin).link;
|
||||
(prefix.join(INSTALLED_MARKER).is_file() && provider::installed_with_env(&link.to_string_lossy(), &[]))
|
||||
.then_some(link)
|
||||
}
|
||||
|
||||
pub(crate) fn install_command(prefix: &Path, pkg: &str) -> Option<String> {
|
||||
let spec = format!("{pkg}@latest");
|
||||
let args = install_args(prefix.to_str()?, &spec);
|
||||
Some(provider::render_shell_command(Path::new("npm"), args, cfg!(windows)))
|
||||
}
|
||||
|
||||
fn install_args<'a>(prefix: &'a str, spec: &'a str) -> [&'a str; 7] {
|
||||
["install", "-g", "--prefix", prefix, "--no-audit", "--no-fund", spec]
|
||||
}
|
||||
|
||||
struct Installation {
|
||||
modules: PathBuf,
|
||||
folder: PathBuf,
|
||||
@@ -149,47 +253,19 @@ fn maintain(
|
||||
program: &Path,
|
||||
bin: &str,
|
||||
pkg: &str,
|
||||
managed: Option<&Path>,
|
||||
approved: Option<&AgentCliOffer>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
use AgentCliUpdateResult::*;
|
||||
let run = |args: &[&str]| {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.args(args)
|
||||
.current_dir(npm.parent().unwrap())
|
||||
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
|
||||
.env("NPM_CONFIG_LOGLEVEL", "error");
|
||||
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
|
||||
if e.kind == ErrorKind::Cancelled {
|
||||
return e;
|
||||
}
|
||||
// npm diagnostics can contain private registry URLs; expose only known codes.
|
||||
let code = e
|
||||
.message
|
||||
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
|
||||
.find(|w| {
|
||||
matches!(
|
||||
*w,
|
||||
"EACCES"
|
||||
| "EPERM"
|
||||
| "EROFS"
|
||||
| "ENOTFOUND"
|
||||
| "EAI_AGAIN"
|
||||
| "ETIMEDOUT"
|
||||
| "E404"
|
||||
| "E401"
|
||||
| "E403"
|
||||
)
|
||||
})
|
||||
.unwrap_or("npm");
|
||||
IdeError::unavailable(code)
|
||||
})
|
||||
let run = |args: &[&str]| run_npm(npm, args, cancel);
|
||||
let output;
|
||||
let prefix = if let Some(prefix) = managed {
|
||||
prefix
|
||||
} else {
|
||||
output = run(&["prefix", "-g"])?;
|
||||
Path::new(output.trim_end())
|
||||
};
|
||||
let output = run(&["prefix", "-g"])?;
|
||||
let prefix = Path::new(output.trim_end());
|
||||
if !prefix.is_absolute() {
|
||||
return Err(IdeError::invalid("Invalid npm global prefix"));
|
||||
}
|
||||
@@ -210,21 +286,42 @@ fn maintain(
|
||||
if approved != Some(&offer) {
|
||||
return Ok(Available(offer));
|
||||
}
|
||||
run(&[
|
||||
"install",
|
||||
"-g",
|
||||
"--prefix",
|
||||
prefix.to_str().unwrap(),
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
&format!("{pkg}@{}", offer.latest),
|
||||
])?;
|
||||
run(&install_args(prefix.to_str().unwrap(), &format!("{pkg}@{}", offer.latest)))?;
|
||||
if installation.version(program, pkg, bin)?.as_ref() != Some(&offer.latest) {
|
||||
return Err(IdeError::invalid("npm installation verification failed"));
|
||||
}
|
||||
Ok(Updated { current: offer.latest })
|
||||
}
|
||||
|
||||
fn run_npm(npm: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<String> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.args(args)
|
||||
.current_dir(npm.parent().unwrap())
|
||||
.env("PATH", ide_core::tool_path::search_path())
|
||||
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
|
||||
.env("NPM_CONFIG_LOGLEVEL", "error");
|
||||
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
|
||||
if e.kind == ErrorKind::Cancelled {
|
||||
return e;
|
||||
}
|
||||
// npm diagnostics can contain private registry URLs; expose only known codes.
|
||||
let code = e
|
||||
.message
|
||||
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
|
||||
.find(|w| {
|
||||
matches!(
|
||||
*w,
|
||||
"EACCES" | "EPERM" | "EROFS" | "ENOTFOUND" | "EAI_AGAIN" | "ETIMEDOUT" | "E404" | "E401" | "E403"
|
||||
)
|
||||
})
|
||||
.unwrap_or("npm");
|
||||
IdeError::unavailable(code)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -312,8 +409,9 @@ esac"#;
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(NPM);
|
||||
let cancel = CancellationToken::new();
|
||||
let run =
|
||||
|offer: Option<&AgentCliOffer>| maintain(&npm, &f.install.link, "claude", PKG, offer, &cancel).unwrap();
|
||||
let run = |offer: Option<&AgentCliOffer>| {
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, offer, &cancel).unwrap()
|
||||
};
|
||||
let latest = f.root.path().join("latest");
|
||||
fs::write(&latest, r#""2.1.12""#).unwrap();
|
||||
let Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
@@ -349,7 +447,7 @@ esac"#;
|
||||
let npm = f.npm(NPM);
|
||||
fs::write(f.root.path().join("latest"), r#""2.1.12""#).unwrap();
|
||||
let run = |offer: Option<&AgentCliOffer>| {
|
||||
maintain(&npm, &f.install.link, "claude", PKG, offer, &CancellationToken::new()).unwrap()
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, offer, &CancellationToken::new()).unwrap()
|
||||
};
|
||||
let AgentCliUpdateResult::Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
@@ -375,13 +473,13 @@ esac"#,
|
||||
);
|
||||
let cancel = CancellationToken::new();
|
||||
let AgentCliUpdateResult::Available(offer) =
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, &cancel).unwrap()
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, None, &cancel).unwrap()
|
||||
else {
|
||||
panic!("expected an offer")
|
||||
};
|
||||
let started = f.root.path().join("started");
|
||||
std::thread::scope(|s| {
|
||||
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, Some(&offer), &cancel));
|
||||
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, None, Some(&offer), &cancel));
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !started.exists() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
|
||||
@@ -131,7 +131,263 @@ fn is_bypass_mode(mode: &str) -> bool {
|
||||
let lower = mode.to_lowercase();
|
||||
let m: String =
|
||||
lower.rsplit(['#', '/']).next().unwrap_or_default().chars().filter(char::is_ascii_lowercase).collect();
|
||||
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous"
|
||||
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous" || m == "autopilot"
|
||||
}
|
||||
|
||||
fn upsert_choice(wanted: &mut Vec<crate::model::AgentConfigChoice>, id: &str, value: &str) {
|
||||
if let Some(existing) = wanted.iter_mut().find(|c| c.id == id) {
|
||||
existing.value = value.to_owned();
|
||||
} else {
|
||||
wanted.push(crate::model::AgentConfigChoice { id: id.to_owned(), value: value.to_owned() });
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
|
||||
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
|
||||
}
|
||||
|
||||
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
|
||||
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
|
||||
}
|
||||
|
||||
/// Applies an automation's permission policy (`mode`) to `config` and `wanted`, enforcing the
|
||||
/// user's interactive approval setting (`interactive`) as a strict ceiling. When `mode` is `None`
|
||||
/// (an in-session `/loop` or `Send Later` turn), clamps any bypass options down when `interactive`
|
||||
/// is [`ide_core::settings::NewTaskApprovals::Ask`].
|
||||
pub(crate) fn clamp_automation_permissions(
|
||||
provider: &str,
|
||||
mode: Option<crate::automation::AutomationPermissionMode>,
|
||||
interactive: ide_core::settings::NewTaskApprovals,
|
||||
config: &mut [AgentConfigOption],
|
||||
wanted: &mut Vec<crate::model::AgentConfigChoice>,
|
||||
) {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
|
||||
return;
|
||||
}
|
||||
|
||||
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
|
||||
|
||||
if !allow_bypass {
|
||||
// Strip any explicit bypass choices from `wanted` first so they cannot re-elevate later.
|
||||
wanted.retain(|c| match c.id.as_str() {
|
||||
"mode" => !is_bypass_mode(&c.value),
|
||||
"allow_all" | "permissions" => !matches!(c.value.to_ascii_lowercase().as_str(), "on" | "true"),
|
||||
"approval" | CURSOR_APPROVAL => !c.value.eq_ignore_ascii_case("bypass"),
|
||||
"approval_policy" => !c.value.eq_ignore_ascii_case("never"),
|
||||
_ => true,
|
||||
});
|
||||
ask_for_approvals(config);
|
||||
}
|
||||
|
||||
match provider {
|
||||
"claude" | "claude-acp" => {
|
||||
let cur_wanted = wanted_val(wanted, "mode");
|
||||
let target = if allow_bypass {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("default" | "plan" | "acceptEdits") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "bypassPermissions".to_owned(),
|
||||
}
|
||||
} else if interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::Assisted) {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("default" | "plan") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "acceptEdits".to_owned(),
|
||||
}
|
||||
} else {
|
||||
// Either Default mode or interactive policy is Ask (where interactive Claude starts in `default`).
|
||||
match cur_wanted.as_deref() {
|
||||
Some("plan") => "plan".to_owned(),
|
||||
_ => "default".to_owned(),
|
||||
}
|
||||
};
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
&& opt.values.iter().any(|v| v.value == target)
|
||||
{
|
||||
let id = opt.id.clone();
|
||||
opt.current = Some(target.clone());
|
||||
upsert_choice(wanted, &id, &target);
|
||||
} else if mode.is_some() || cur_wanted.is_some() {
|
||||
upsert_choice(wanted, "mode", &target);
|
||||
}
|
||||
}
|
||||
"codex" | "codex-acp" => {
|
||||
let cur_wanted = wanted_val(wanted, "mode");
|
||||
let target = if allow_bypass {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "full-access".to_owned(),
|
||||
}
|
||||
} else if mode == Some(AutomationPermissionMode::Default) {
|
||||
"read-only".to_owned()
|
||||
} else if mode.is_some() {
|
||||
// Assisted, or AllowAll clamped by interactive Ask (`ask_for_approvals` maps full-access -> ask).
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only") => "read-only".to_owned(),
|
||||
_ => "ask".to_owned(),
|
||||
}
|
||||
} else {
|
||||
// Scheduled /loop or Send Later under interactive Ask: never full-access.
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "ask".to_owned(),
|
||||
}
|
||||
};
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
&& opt.values.iter().any(|v| v.value == target)
|
||||
{
|
||||
let id = opt.id.clone();
|
||||
opt.current = Some(target.clone());
|
||||
upsert_choice(wanted, &id, &target);
|
||||
} else if mode.is_some() || cur_wanted.is_some() {
|
||||
upsert_choice(wanted, "mode", &target);
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
if allow_bypass {
|
||||
if !matches!(wanted_val(wanted, "allow_all").as_deref(), Some("off" | "false")) {
|
||||
upsert_choice(wanted, "allow_all", "on");
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
|
||||
opt.current = Some("on".into());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
upsert_choice(wanted, "allow_all", "off");
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
|
||||
opt.current = Some("off".into());
|
||||
}
|
||||
let non_auto = match wanted_val(wanted, "mode").as_deref() {
|
||||
Some("plan") => "plan",
|
||||
_ => "agent",
|
||||
};
|
||||
if mode.is_some() || config.iter().any(|o| o.id == "mode" && o.current.as_deref() == Some("autopilot"))
|
||||
{
|
||||
upsert_choice(wanted, "mode", non_auto);
|
||||
}
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode")
|
||||
&& (mode.is_some() || opt.current.as_deref() == Some("autopilot"))
|
||||
&& opt.values.iter().any(|v| v.value == non_auto)
|
||||
{
|
||||
opt.current = Some(non_auto.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
"cursor" => {
|
||||
let target = if allow_bypass && wanted_val(wanted, CURSOR_APPROVAL).as_deref() != Some("ask") {
|
||||
"bypass"
|
||||
} else {
|
||||
"ask"
|
||||
};
|
||||
upsert_choice(wanted, CURSOR_APPROVAL, target);
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == CURSOR_APPROVAL) {
|
||||
opt.current = Some(target.into());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if allow_bypass {
|
||||
let user_chose_non_bypass = config.iter().any(|o| {
|
||||
is_approval_option(o)
|
||||
&& wanted.iter().any(|c| {
|
||||
c.id == o.id && o.category.as_deref().and_then(bypass_value).is_some_and(|b| !b(&c.value))
|
||||
})
|
||||
});
|
||||
if !user_chose_non_bypass {
|
||||
apply_bypass_approvals(config);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure every approval-bearing option in `config` has its enforced value mirrored in `wanted`
|
||||
// so `open_session` actively configures the live session even if the CLI's own config differs.
|
||||
for opt in config.iter().filter(|o| is_approval_option(o)) {
|
||||
if let Some(cur) = opt.current.as_deref() {
|
||||
upsert_choice(wanted, &opt.id, cur);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies that the session's reported `config` options do not exceed the required automation
|
||||
/// permission ceiling (`min(mode, interactive)`). Returns `Err(reason)` if the provider remained
|
||||
/// in a more permissive mode than allowed.
|
||||
pub(crate) fn verify_automation_ceiling(
|
||||
provider: &str,
|
||||
mode: Option<crate::automation::AutomationPermissionMode>,
|
||||
interactive: ide_core::settings::NewTaskApprovals,
|
||||
config: &[AgentConfigOption],
|
||||
) -> Result<(), String> {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
|
||||
if !allow_bypass && bypass_approvals(config) {
|
||||
return Err("Agent did not confirm the required approval ceiling (session remained in bypass mode).".into());
|
||||
}
|
||||
|
||||
let cur_of = |id: &str| config.iter().find(|o| o.id == id).and_then(|o| o.current.as_deref());
|
||||
let mode_cur = config
|
||||
.iter()
|
||||
.find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
.and_then(|o| o.current.as_deref());
|
||||
|
||||
if !allow_bypass {
|
||||
match provider {
|
||||
"claude" | "claude-acp" => {
|
||||
if let Some(cur) = mode_cur {
|
||||
let allowed = if interactive == NewTaskApprovals::Bypass
|
||||
&& mode == Some(AutomationPermissionMode::Assisted)
|
||||
{
|
||||
matches!(cur, "default" | "plan" | "acceptEdits")
|
||||
} else {
|
||||
matches!(cur, "default" | "plan")
|
||||
};
|
||||
if !allowed {
|
||||
return Err(format!(
|
||||
"Claude session remained in mode '{cur}', exceeding the required approval ceiling."
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
"codex" | "codex-acp" => {
|
||||
if let Some(cur) = mode_cur {
|
||||
let allowed = if mode == Some(AutomationPermissionMode::Default) {
|
||||
cur == "read-only"
|
||||
} else if mode.is_some() {
|
||||
matches!(cur, "read-only" | "ask")
|
||||
} else {
|
||||
matches!(cur, "read-only" | "ask" | "auto")
|
||||
};
|
||||
if !allowed {
|
||||
return Err(format!(
|
||||
"Codex session remained in mode '{cur}', exceeding the required approval ceiling."
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
if let Some(cur) = cur_of("allow_all")
|
||||
&& matches!(cur.to_ascii_lowercase().as_str(), "on" | "true")
|
||||
{
|
||||
return Err("Copilot session kept allow_all enabled above the approval ceiling.".into());
|
||||
}
|
||||
if let Some(cur) = mode_cur
|
||||
&& cur.eq_ignore_ascii_case("autopilot")
|
||||
{
|
||||
return Err("Copilot session remained in autopilot mode above the approval ceiling.".into());
|
||||
}
|
||||
}
|
||||
"cursor" if cur_of(CURSOR_APPROVAL).is_some_and(|cur| cur.eq_ignore_ascii_case("bypass")) => {
|
||||
return Err("Cursor session remained in bypass mode above the approval ceiling.".into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
|
||||
@@ -669,6 +925,87 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_permissions_respect_interactive_approval_ceiling() {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use crate::model::AgentConfigChoice;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
let claude_opts = || {
|
||||
options_of(&json!({"configOptions": [{
|
||||
"id": "mode", "category": "mode", "type": "select", "currentValue": "bypassPermissions",
|
||||
"defaultValue": "default",
|
||||
"options": [
|
||||
{"value": "default"}, {"value": "acceptEdits"}, {"value": "plan"}, {"value": "bypassPermissions"}
|
||||
]
|
||||
}]}))
|
||||
};
|
||||
|
||||
// Claude Assisted under interactive Bypass -> acceptEdits; under interactive Ask -> default!
|
||||
let mut c = claude_opts();
|
||||
let mut wanted = Vec::new();
|
||||
clamp_automation_permissions(
|
||||
"claude",
|
||||
Some(AutomationPermissionMode::Assisted),
|
||||
NewTaskApprovals::Bypass,
|
||||
&mut c,
|
||||
&mut wanted,
|
||||
);
|
||||
assert_eq!(c[0].current.as_deref(), Some("acceptEdits"));
|
||||
assert!(wanted.iter().any(|w| w.id == "mode" && w.value == "acceptEdits"));
|
||||
|
||||
let mut c_ask = claude_opts();
|
||||
let mut wanted_ask = vec![AgentConfigChoice { id: "mode".into(), value: "bypassPermissions".into() }];
|
||||
clamp_automation_permissions(
|
||||
"claude",
|
||||
Some(AutomationPermissionMode::AllowAll),
|
||||
NewTaskApprovals::Ask,
|
||||
&mut c_ask,
|
||||
&mut wanted_ask,
|
||||
);
|
||||
assert_eq!(c_ask[0].current.as_deref(), Some("default"));
|
||||
assert_eq!(wanted_ask, vec![AgentConfigChoice { id: "mode".into(), value: "default".into() }]);
|
||||
|
||||
// Copilot AllowAll under interactive Ask clamps allow_all -> off and autopilot -> agent.
|
||||
let mut copilot = options_of(&json!({"configOptions": [
|
||||
{"id": "mode", "category": "mode", "type": "select", "currentValue": "autopilot",
|
||||
"options": [{"value": "agent"}, {"value": "plan"}, {"value": "autopilot"}]},
|
||||
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "on",
|
||||
"options": [{"value": "off"}, {"value": "on"}]}
|
||||
]}));
|
||||
let mut copilot_wanted = vec![AgentConfigChoice { id: "allow_all".into(), value: "on".into() }];
|
||||
clamp_automation_permissions(
|
||||
"copilot",
|
||||
Some(AutomationPermissionMode::AllowAll),
|
||||
NewTaskApprovals::Ask,
|
||||
&mut copilot,
|
||||
&mut copilot_wanted,
|
||||
);
|
||||
assert_eq!(ids(&copilot), [("mode", Some("agent")), ("allow_all", Some("off"))]);
|
||||
assert!(!bypass_approvals(&copilot));
|
||||
|
||||
// Codex Default -> read-only, Assisted -> ask, AllowAll + Ask -> ask, AllowAll + Bypass -> full-access.
|
||||
let codex_opts = || {
|
||||
options_of(&json!({"configOptions": [{
|
||||
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
|
||||
"defaultValue": "ask",
|
||||
"options": [{"value": "read-only"}, {"value": "ask"}, {"value": "auto"}, {"value": "full-access"}]
|
||||
}]}))
|
||||
};
|
||||
for (perm, interactive, expected) in [
|
||||
(AutomationPermissionMode::Default, NewTaskApprovals::Bypass, "read-only"),
|
||||
(AutomationPermissionMode::Assisted, NewTaskApprovals::Bypass, "ask"),
|
||||
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Ask, "ask"),
|
||||
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Bypass, "full-access"),
|
||||
] {
|
||||
let mut opts = codex_opts();
|
||||
let mut w = Vec::new();
|
||||
clamp_automation_permissions("codex", Some(perm), interactive, &mut opts, &mut w);
|
||||
assert_eq!(opts[0].current.as_deref(), Some(expected), "{perm:?} + {interactive:?}");
|
||||
assert!(w.iter().any(|c| c.id == "mode" && c.value == expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_sources_in_updates_and_stored_tasks() {
|
||||
let update = json!({"availableCommands": [
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! ACP elicitation in form mode: the agent's restricted JSON Schema as form fields, and the
|
||||
//! user's answer as the `elicitation/create` response.
|
||||
|
||||
use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption};
|
||||
use crate::model::{
|
||||
AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption, AgentQuestion,
|
||||
AgentQuestionOption,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -10,6 +13,9 @@ use serde_json::{Map, Value, json};
|
||||
/// anything else cancels it.
|
||||
const DECLINE: &str = "decline";
|
||||
|
||||
/// What the question card sends for Skip.
|
||||
const SKIP: &str = "reject";
|
||||
|
||||
/// The form `elicitation/create` asks for; `Err` when it asks for something else.
|
||||
pub(crate) fn form_of(params: &Value) -> Result<AgentForm, String> {
|
||||
if params.get("mode").and_then(Value::as_str) != Some("form") {
|
||||
@@ -148,6 +154,97 @@ fn scalar(value: &Value) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The questions a form asks when it is an agent's question tool in form shape: every field
|
||||
/// a choice, each followed by its own text field for a typed answer, named after it
|
||||
/// (`question_0` + `question_0_custom` from claude-agent-acp's `AskUserQuestion`, `q0` +
|
||||
/// `q0__other` from OMP's `ask`). They are shown and answered as the agent's questions, one
|
||||
/// at a time like a native `AskUserQuestion` (#7359); [`answer_questions`] turns the answers
|
||||
/// back into the form's values. `None` for any other form.
|
||||
pub(crate) fn questions_of(form: &AgentForm, params: &Value, message: &str) -> Option<Vec<AgentQuestion>> {
|
||||
let choices = form.fields.len() / 2;
|
||||
if choices == 0 || form.fields.len() % 2 == 1 {
|
||||
return None;
|
||||
}
|
||||
let properties = params.pointer("/requestedSchema/properties");
|
||||
form.fields
|
||||
.chunks(2)
|
||||
.map(|pair| {
|
||||
let [choice, text] = pair else { return None };
|
||||
let asks = matches!(choice.kind, AgentFormFieldKind::Choice | AgentFormFieldKind::Choices)
|
||||
&& !choice.options.is_empty()
|
||||
&& text.kind == AgentFormFieldKind::Text
|
||||
&& text.name.len() > choice.name.len()
|
||||
&& text.name.starts_with(&choice.name);
|
||||
if !asks {
|
||||
return None;
|
||||
}
|
||||
let (title, description) = (choice.title.trim(), choice.description.trim());
|
||||
let (header, question) = if choices == 1 && !message.is_empty() {
|
||||
(if title == message || title == choice.name { "" } else { title }, message)
|
||||
} else if description.is_empty() {
|
||||
("", title)
|
||||
} else {
|
||||
(if title == choice.name { "" } else { title }, description)
|
||||
};
|
||||
let schema = properties.and_then(|p| p.get(&choice.name));
|
||||
let options = choice
|
||||
.options
|
||||
.iter()
|
||||
.map(|option| AgentQuestionOption {
|
||||
label: option.label.clone(),
|
||||
description: option.description.clone(),
|
||||
preview: schema.and_then(|s| option_preview(s, &option.value)),
|
||||
})
|
||||
.collect();
|
||||
Some(AgentQuestion {
|
||||
answer_key: Some(choice.name.clone()),
|
||||
header: header.to_owned(),
|
||||
question: question.to_owned(),
|
||||
multi_select: choice.kind == AgentFormFieldKind::Choices,
|
||||
options,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The preview claude-agent-acp forwards beside an option (`_meta["_claude/askUserQuestionOption"]`).
|
||||
fn option_preview(schema: &Value, value: &str) -> Option<String> {
|
||||
let listed = schema.get("oneOf").or_else(|| schema.get("anyOf")).or_else(|| schema.pointer("/items/anyOf"));
|
||||
listed?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.find(|o| o.get("const").and_then(Value::as_str) == Some(value))?
|
||||
.pointer("/_meta/_claude~1askUserQuestionOption/preview")?
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// The form reply to the answers of [`questions_of`]'s questions (question key to the picked
|
||||
/// labels and the typed text): picked options as the choice's values, the text in the field
|
||||
/// beside it. The question card's Skip declines the form; nothing passes through.
|
||||
pub(crate) fn answer_questions(form: &AgentForm, reply: Option<&str>) -> Option<String> {
|
||||
let reply = reply?;
|
||||
if reply == SKIP {
|
||||
return Some(DECLINE.to_owned());
|
||||
}
|
||||
let Ok(answers) = serde_json::from_str::<Map<String, Value>>(reply) else { return Some(reply.to_owned()) };
|
||||
let mut values = Map::new();
|
||||
for pair in form.fields.chunks(2) {
|
||||
let [choice, text] = pair else { continue };
|
||||
let items = answers.get(&choice.name).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
|
||||
let (mut picked, mut typed) = (Vec::new(), Vec::new());
|
||||
for item in items {
|
||||
match choice.options.iter().find(|o| o.label == item) {
|
||||
Some(option) => picked.push(json!(option.value)),
|
||||
None => typed.push(item),
|
||||
}
|
||||
}
|
||||
values.insert(choice.name.clone(), Value::Array(picked));
|
||||
values.insert(text.name.clone(), json!([typed.join("\n")]));
|
||||
}
|
||||
Some(Value::Object(values).to_string())
|
||||
}
|
||||
|
||||
/// A form is submitted from its own card; this option only names a declined form.
|
||||
pub(crate) fn options() -> Vec<AgentPermissionOption> {
|
||||
vec![AgentPermissionOption { id: DECLINE.to_owned(), name: "Decline".to_owned(), kind: "reject_once".to_owned() }]
|
||||
@@ -295,6 +392,90 @@ mod tests {
|
||||
assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b");
|
||||
}
|
||||
|
||||
/// What claude-agent-acp sends for `AskUserQuestion` with two questions.
|
||||
fn claude_questions() -> Value {
|
||||
json!({
|
||||
"sessionId": "s", "mode": "form", "message": "Please answer the following questions.",
|
||||
"requestedSchema": { "type": "object", "properties": {
|
||||
"question_0": { "type": "string", "title": "Delivery", "description": "How should it ship?",
|
||||
"oneOf": [{ "const": "Util + table (Recommended)", "title": "Util + table (Recommended)",
|
||||
"description": "Tracks tasks",
|
||||
"_meta": { "_claude/askUserQuestionOption": { "preview": "```\nUtil\n```" } } },
|
||||
{ "const": "Util only", "title": "Util only" }] },
|
||||
"question_0_custom": { "type": "string", "title": "Other" },
|
||||
"question_1": { "type": "array", "title": "Targets", "description": "Who receives it?",
|
||||
"items": { "anyOf": [{ "const": "Members", "title": "Members" },
|
||||
{ "const": "Tags", "title": "Tags" }] } },
|
||||
"question_1_custom": { "type": "string", "title": "Other" }
|
||||
} }
|
||||
})
|
||||
}
|
||||
|
||||
fn in_order(params: &Value, names: &[&str]) -> AgentForm {
|
||||
let mut form = form_of(params).unwrap();
|
||||
form.fields.sort_by_key(|f| names.iter().position(|n| *n == f.name));
|
||||
form
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_question_tool_form_is_asked_as_questions() {
|
||||
let params = claude_questions();
|
||||
let form = in_order(¶ms, &["question_0", "question_0_custom", "question_1", "question_1_custom"]);
|
||||
let questions = questions_of(&form, ¶ms, "Please answer the following questions.").unwrap();
|
||||
let [delivery, targets] = questions.as_slice() else { panic!("{questions:?}") };
|
||||
assert_eq!(
|
||||
(
|
||||
delivery.answer_key.as_deref(),
|
||||
delivery.header.as_str(),
|
||||
delivery.question.as_str(),
|
||||
delivery.multi_select
|
||||
),
|
||||
(Some("question_0"), "Delivery", "How should it ship?", false)
|
||||
);
|
||||
assert_eq!(delivery.options[0].description, "Tracks tasks");
|
||||
assert_eq!(delivery.options[0].preview.as_deref(), Some("```\nUtil\n```"));
|
||||
assert_eq!(delivery.options[1].preview, None);
|
||||
assert_eq!((targets.question.as_str(), targets.multi_select), ("Who receives it?", true));
|
||||
|
||||
let reply = json!({ "question_0": ["Util only", "keep it small"], "question_1": ["Members", "Tags"] });
|
||||
let reply = answer_questions(&form, Some(&reply.to_string()));
|
||||
let (response, chosen) = answer(&form, reply.as_deref());
|
||||
assert_eq!(
|
||||
response,
|
||||
json!({ "action": "accept", "content": {
|
||||
"question_0": "Util only", "question_0_custom": "keep it small", "question_1": ["Members", "Tags"]
|
||||
} })
|
||||
);
|
||||
assert_eq!(chosen, "Delivery: Util only; Other: keep it small; Targets: Members, Tags");
|
||||
assert_eq!(answer_questions(&form, Some(SKIP)).as_deref(), Some(DECLINE));
|
||||
assert_eq!(answer_questions(&form, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_question_reads_from_the_message() {
|
||||
let params = ask();
|
||||
let form = in_order(¶ms, &["q0", "q0__other"]);
|
||||
let questions = questions_of(&form, ¶ms, "Which database?").unwrap();
|
||||
assert_eq!((questions[0].header.as_str(), questions[0].question.as_str()), ("", "Which database?"));
|
||||
assert_eq!(questions[0].options[0].label, "Postgres");
|
||||
let reply = answer_questions(&form, Some(&json!({ "q0": ["SQLite"] }).to_string()));
|
||||
assert_eq!(answer(&form, reply.as_deref()).0, json!({ "action": "accept", "content": { "q0": "sqlite" } }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_forms_stay_forms() {
|
||||
let only_choices = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
|
||||
"size": { "type": "string", "enum": ["s", "l"] }, "env": { "type": "string", "enum": ["dev"] }
|
||||
} } }))
|
||||
.unwrap();
|
||||
assert_eq!(questions_of(&only_choices, &json!({}), "Pick"), None);
|
||||
let unrelated_text = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
|
||||
"size": { "type": "string", "enum": ["s", "l"] }, "note": { "type": "string" }
|
||||
} } }))
|
||||
.unwrap();
|
||||
assert_eq!(questions_of(&unrelated_text, &json!({}), "Pick"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declining_and_dismissing_send_no_content() {
|
||||
let form = form_of(&ask()).unwrap();
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
//! scanned so they can be listed and imported as tasks instead of re-explained (#312).
|
||||
//!
|
||||
//! Only the native providers keep transcripts on disk in a readable form: Claude Code
|
||||
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`) and Codex
|
||||
//! (`<config>/projects/*/<id>.jsonl`, see `native::claude::history`), Codex
|
||||
//! (`<home>/.codex/sessions/**`, rollout files with a `session_meta` line, named in
|
||||
//! `<home>/.codex/session_index.jsonl`).
|
||||
//! `<home>/.codex/session_index.jsonl`), and Copilot
|
||||
//! (`<config>/session-state/<id>/workspace.yaml` plus `events.jsonl`).
|
||||
|
||||
use super::native::claude::history;
|
||||
use serde::Serialize;
|
||||
@@ -17,7 +18,7 @@ use std::path::{Path, PathBuf};
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExternalSession {
|
||||
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`).
|
||||
/// The [`crate::AgentProvider`] id that owns it (`claude`, `codex`, `copilot`).
|
||||
pub provider: String,
|
||||
/// The id resuming it names (`--resume`, `thread/resume`).
|
||||
pub session_id: String,
|
||||
@@ -26,6 +27,9 @@ pub struct ExternalSession {
|
||||
pub cwd: Option<String>,
|
||||
/// File modification time, ms since the epoch.
|
||||
pub updated_ms: f64,
|
||||
/// Another live process (VS Code, a terminal Copilot CLI) has it open: importing would let two
|
||||
/// apps write the same session, so forking a copy is the safe choice.
|
||||
pub in_use: bool,
|
||||
}
|
||||
|
||||
/// Modification time of `path` in ms, else 0.
|
||||
@@ -123,6 +127,7 @@ pub fn claude_sessions(config_dir: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&path),
|
||||
in_use: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -193,6 +198,7 @@ fn codex_file(path: &Path) -> Option<ExternalSession> {
|
||||
session_id,
|
||||
cwd,
|
||||
updated_ms: mtime(path),
|
||||
in_use: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -246,6 +252,289 @@ pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
sessions
|
||||
}
|
||||
|
||||
/// Whether `raw` is a YAML block-scalar header (`|`, `|-`, `|+`, `>`, `>-`, `>+`, with optional indent digit).
|
||||
fn is_yaml_block_header(raw: &str) -> bool {
|
||||
let mut chars = raw.chars();
|
||||
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '-' | '+') || c.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// Unquotes a single-line YAML scalar value from Copilot's `workspace.yaml`.
|
||||
fn parse_yaml_inline_value(raw: &str) -> String {
|
||||
if raw.starts_with('"') {
|
||||
serde_json::from_str(raw).unwrap_or_else(|_| raw.trim_matches('"').to_owned())
|
||||
} else if raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2 {
|
||||
raw[1..raw.len() - 1].replace("''", "'")
|
||||
} else {
|
||||
raw.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata for one Copilot session, read without opening its potentially multi-gigabyte event log.
|
||||
/// Supports both inline scalars (`name: "Fix\nbug"`) and block scalars (`name: |-\n Fix\n bug`).
|
||||
fn copilot_metadata(path: &Path) -> Option<HashMap<String, String>> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut lines = std::io::BufReader::new(file).lines().map_while(Result::ok).peekable();
|
||||
let mut metadata = HashMap::new();
|
||||
while let Some(line) = lines.next() {
|
||||
if line.is_empty() || line.starts_with(char::is_whitespace) || line.trim_start().starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let Some((key, raw)) = line.split_once(':') else { continue };
|
||||
let key = key.trim();
|
||||
let raw = raw.trim();
|
||||
if key.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if is_yaml_block_header(raw) {
|
||||
let folded = raw.starts_with('>');
|
||||
let mut block = Vec::new();
|
||||
while let Some(next) = lines.peek() {
|
||||
if next.is_empty() || next.starts_with(' ') || next.starts_with('\t') {
|
||||
block.push(lines.next().unwrap_or_default());
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
while block.last().is_some_and(|l| l.trim().is_empty()) {
|
||||
block.pop();
|
||||
}
|
||||
let indent = block
|
||||
.iter()
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.map(|l| l.bytes().take_while(|&b| b == b' ').count())
|
||||
.min()
|
||||
.unwrap_or(0);
|
||||
let sep = if folded { " " } else { "\n" };
|
||||
let joined = block
|
||||
.iter()
|
||||
.map(|l| if l.len() >= indent { &l[indent..] } else { l.trim_start() })
|
||||
.collect::<Vec<_>>()
|
||||
.join(sep);
|
||||
if !joined.trim().is_empty() {
|
||||
metadata.insert(key.to_owned(), joined);
|
||||
}
|
||||
} else if !raw.is_empty() {
|
||||
metadata.insert(key.to_owned(), parse_yaml_inline_value(raw));
|
||||
}
|
||||
}
|
||||
(!metadata.is_empty()).then_some(metadata)
|
||||
}
|
||||
|
||||
/// The first real prompt in a Copilot event log, used when an old or unnamed session has no title.
|
||||
fn copilot_prompt(path: &Path) -> Option<String> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
std::io::BufReader::new(file)
|
||||
.lines()
|
||||
.take(400)
|
||||
.filter_map(|line| line.ok())
|
||||
.filter_map(|line| serde_json::from_str::<serde_json::Value>(&line).ok())
|
||||
.find_map(|event| {
|
||||
(event.get("type").and_then(serde_json::Value::as_str) == Some("user.message"))
|
||||
.then(|| event.pointer("/data/content").and_then(serde_json::Value::as_str).map(str::trim))
|
||||
.flatten()
|
||||
.filter(|text| !text.is_empty())
|
||||
.map(short)
|
||||
})
|
||||
}
|
||||
|
||||
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
|
||||
/// ordered oldest-first so a newer database wins when two editions share a session.
|
||||
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
|
||||
let mut bases = vec![home.join("Library/Application Support"), home.join(".config"), home.join("AppData/Roaming")];
|
||||
let real_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
|
||||
if real_home.as_deref().is_some_and(|h| Path::new(h) == home) {
|
||||
for var in ["XDG_CONFIG_HOME", "APPDATA"] {
|
||||
if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from)
|
||||
&& !bases.contains(&dir)
|
||||
{
|
||||
bases.push(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut dbs = Vec::new();
|
||||
for base in bases {
|
||||
for app in ["Code", "Code - Insiders"] {
|
||||
dbs.push(base.join(app).join("User/globalStorage/agent-host.db"));
|
||||
}
|
||||
}
|
||||
for server in [".vscode-server", ".vscode-server-insiders"] {
|
||||
dbs.push(home.join(server).join("data/User/globalStorage/agent-host.db"));
|
||||
}
|
||||
dbs.retain(|p| p.is_file());
|
||||
dbs.sort_by(|a, b| mtime(a).total_cmp(&mtime(b)));
|
||||
dbs
|
||||
}
|
||||
|
||||
fn is_generic_vscode_placeholder(title: &str, source: Option<&str>) -> bool {
|
||||
source != Some("user") && (title.eq_ignore_ascii_case("new session") || title.eq_ignore_ascii_case("new chat"))
|
||||
}
|
||||
|
||||
fn pick_vscode_chat_title(
|
||||
scs_title: Option<&str>,
|
||||
scs_source: Option<&str>,
|
||||
metadata_json: Option<&str>,
|
||||
payload_json: Option<&str>,
|
||||
) -> Option<String> {
|
||||
if let Some(t) = scs_title.map(str::trim).filter(|t| !t.is_empty())
|
||||
&& !is_generic_vscode_placeholder(t, scs_source)
|
||||
{
|
||||
return Some(t.to_owned());
|
||||
}
|
||||
for blob in [metadata_json, payload_json].into_iter().flatten() {
|
||||
let Ok(v) = serde_json::from_str::<serde_json::Value>(blob) else { continue };
|
||||
let summary = v.pointer("/data/summary").and_then(serde_json::Value::as_str).map(str::trim);
|
||||
let source = v.pointer("/data/titleSource").and_then(serde_json::Value::as_str);
|
||||
if let Some(t) = summary.filter(|t| !t.is_empty())
|
||||
&& !is_generic_vscode_placeholder(t, source)
|
||||
{
|
||||
return Some(t.to_owned());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The rows of one `agent-host.db` that map a backing Copilot session (`sdkSessionId`) to its
|
||||
/// title. Read through a read-only connection that sets no `journal_mode` or other write pragma,
|
||||
/// so VS Code's database is never changed. An unknown schema (a newer VS Code) reads nothing.
|
||||
async fn read_vscode_chat_rows(path: &Path) -> Vec<[Option<String>; 5]> {
|
||||
use sqlx::{Connection, Row};
|
||||
const FULL_QUERY: &str = "\
|
||||
SELECT c.provider_data, scs.title, scs.title_source, c.metadata, s.payload \
|
||||
FROM chats_v2 c \
|
||||
LEFT JOIN session_chat_state scs \
|
||||
ON scs.session_uri = c.owner_session_uri AND scs.chat_uri = c.chat_uri \
|
||||
LEFT JOIN sessions_v2 s \
|
||||
ON s.session_uri = c.owner_session_uri \
|
||||
WHERE c.tombstoned = 0 \
|
||||
ORDER BY COALESCE(s.modified_time, 0) ASC, COALESCE(c.chat_order, 0) ASC";
|
||||
const FALLBACK_QUERY: &str = "SELECT provider_data, NULL, NULL, metadata, NULL FROM chats_v2 WHERE tombstoned = 0";
|
||||
|
||||
let options = sqlx::sqlite::SqliteConnectOptions::new()
|
||||
.filename(path)
|
||||
.read_only(true)
|
||||
.create_if_missing(false)
|
||||
.busy_timeout(std::time::Duration::from_millis(200));
|
||||
let Ok(mut conn) = sqlx::SqliteConnection::connect_with(&options).await else { return Vec::new() };
|
||||
let rows = match sqlx::query(FULL_QUERY).fetch_all(&mut conn).await {
|
||||
Ok(rows) => rows,
|
||||
Err(_) => sqlx::query(FALLBACK_QUERY).fetch_all(&mut conn).await.unwrap_or_default(),
|
||||
};
|
||||
let _ = conn.close().await;
|
||||
rows.iter().map(|row| std::array::from_fn(|i| row.try_get::<Option<String>, _>(i).ok().flatten())).collect()
|
||||
}
|
||||
|
||||
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
|
||||
/// sessions (`sdkSessionId` → summary or user rename). VS Code keeps these in its own
|
||||
/// `agent-host.db` rather than in Copilot's `workspace.yaml`, so without them a renamed chat
|
||||
/// would be listed under its first prompt. Best-effort: any failure leaves the CLI titles.
|
||||
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
|
||||
let Some(home) = home else { return HashMap::new() };
|
||||
let dbs = vscode_agent_host_dbs(home);
|
||||
if dbs.is_empty() {
|
||||
return HashMap::new();
|
||||
}
|
||||
// Callers are sync and may run on a runtime thread or none: a private runtime on its own
|
||||
// thread works from either without blocking a runtime worker.
|
||||
let rows: Vec<[Option<String>; 5]> = std::thread::scope(|scope| {
|
||||
scope
|
||||
.spawn(|| {
|
||||
let Ok(rt) = tokio::runtime::Builder::new_current_thread().enable_all().build() else {
|
||||
return Vec::new();
|
||||
};
|
||||
rt.block_on(async {
|
||||
let mut all = Vec::new();
|
||||
for path in &dbs {
|
||||
all.extend(read_vscode_chat_rows(path).await);
|
||||
}
|
||||
all
|
||||
})
|
||||
})
|
||||
.join()
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let mut titles = HashMap::new();
|
||||
for [pdata, scs_title, scs_source, metadata, payload] in rows {
|
||||
let Some(pdata) = pdata else { continue };
|
||||
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
|
||||
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty()) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(title) =
|
||||
pick_vscode_chat_title(scs_title.as_deref(), scs_source.as_deref(), metadata.as_deref(), payload.as_deref())
|
||||
{
|
||||
titles.insert(sdk_id.to_owned(), title);
|
||||
}
|
||||
}
|
||||
titles
|
||||
}
|
||||
|
||||
/// Whether a live process holds the Copilot session in `dir`. Copilot writes `inuse.<pid>.lock`
|
||||
/// while a CLI or SDK host (such as VS Code) has the session open; a crash leaves a stale one,
|
||||
/// so only a lock whose process still runs counts.
|
||||
fn copilot_session_in_use(dir: &Path) -> bool {
|
||||
std::fs::read_dir(dir).into_iter().flatten().flatten().any(|entry| {
|
||||
let name = entry.file_name();
|
||||
let Some(pid) = name
|
||||
.to_str()
|
||||
.and_then(|n| n.strip_prefix("inuse."))
|
||||
.and_then(|n| n.strip_suffix(".lock"))
|
||||
.and_then(|n| n.parse::<u32>().ok())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
ide_core::process::process_alive(pid)
|
||||
})
|
||||
}
|
||||
|
||||
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by VS Code's
|
||||
/// Agent Host summary/rename (when started from VS Code), their recorded CLI name, or first prompt.
|
||||
/// Directories without an event log are unfinished sessions and are not listed.
|
||||
pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -> Vec<ExternalSession> {
|
||||
let mut pending: Vec<(ExternalSession, bool)> = std::fs::read_dir(copilot_home.join("session-state"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let dir = entry.path();
|
||||
let events = dir.join("events.jsonl");
|
||||
if !events.is_file() {
|
||||
return None;
|
||||
}
|
||||
let metadata = copilot_metadata(&dir.join("workspace.yaml"))?;
|
||||
let session_id = metadata.get("id").cloned().or_else(|| entry.file_name().to_str().map(str::to_owned))?;
|
||||
let cwd = metadata.get("cwd").cloned().or_else(|| metadata.get("git_root").cloned());
|
||||
if !in_project(cwd.as_deref(), root) {
|
||||
return None;
|
||||
}
|
||||
let raw_name = metadata.get("name").map(String::as_str).map(str::trim).filter(|name| !name.is_empty());
|
||||
let cli_user_named = metadata.get("user_named").is_some_and(|v| v == "true")
|
||||
&& raw_name.is_some_and(|n| !n.eq_ignore_ascii_case("new session"));
|
||||
let title = raw_name
|
||||
.map(short)
|
||||
.or_else(|| copilot_prompt(&events))
|
||||
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
|
||||
let session = ExternalSession {
|
||||
provider: "copilot".to_owned(),
|
||||
session_id,
|
||||
title,
|
||||
cwd,
|
||||
updated_ms: mtime(&events),
|
||||
in_use: copilot_session_in_use(&dir),
|
||||
};
|
||||
Some((session, cli_user_named))
|
||||
})
|
||||
.collect();
|
||||
if !pending.is_empty() {
|
||||
let vscode_titles = vscode_copilot_titles(home);
|
||||
for (session, cli_user_named) in &mut pending {
|
||||
if !*cli_user_named && let Some(title) = vscode_titles.get(&session.session_id) {
|
||||
session.title = short(title);
|
||||
}
|
||||
}
|
||||
}
|
||||
pending.into_iter().map(|(s, _)| s).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -344,6 +633,111 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
|
||||
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
|
||||
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
|
||||
}
|
||||
|
||||
fn exec_sqlite(path: &Path, sql: &'static str) {
|
||||
use sqlx::Connection;
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
rt.block_on(async {
|
||||
let options = sqlx::sqlite::SqliteConnectOptions::new().filename(path).create_if_missing(true);
|
||||
let mut conn = sqlx::SqliteConnection::connect_with(&options).await.unwrap();
|
||||
sqlx::raw_sql(sql).execute(&mut conn).await.unwrap();
|
||||
conn.close().await.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_copilot_sessions_with_names_block_scalars_vscode_titles_and_prompt_fallbacks() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let copilot_home = tmp.path().join(".copilot");
|
||||
let session = copilot_home.join("session-state/copilot-1");
|
||||
write(
|
||||
&session.join("events.jsonl"),
|
||||
&[
|
||||
json!({"type": "session.start", "data": {}}),
|
||||
json!({"type": "user.message", "data": {"content": "fix the parser"}}),
|
||||
],
|
||||
);
|
||||
std::fs::write(
|
||||
session.join("workspace.yaml"),
|
||||
"id: copilot-1\ncwd: /work/app/api\nname: \"Fix parser\\nand tests\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let block_scalar = copilot_home.join("session-state/copilot-block");
|
||||
write(&block_scalar.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
|
||||
std::fs::write(
|
||||
block_scalar.join("workspace.yaml"),
|
||||
"id: copilot-block\ncwd: /work/app\nname: |-\n check why excalidraw font\n is not displayed\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vscode_renamed = copilot_home.join("session-state/copilot-vscode");
|
||||
write(
|
||||
&vscode_renamed.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "create a branch deng/session add Create Session"}})],
|
||||
);
|
||||
std::fs::write(
|
||||
vscode_renamed.join("workspace.yaml"),
|
||||
"id: copilot-vscode\ncwd: /work/app\nclient_name: vscode-agent-host\nname: create a branch deng/session add Create Session\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vscode_placeholder = copilot_home.join("session-state/copilot-placeholder");
|
||||
write(&vscode_placeholder.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
|
||||
std::fs::write(
|
||||
vscode_placeholder.join("workspace.yaml"),
|
||||
"id: copilot-placeholder\ncwd: /work/app\nname: Greeting exchange\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let unnamed = copilot_home.join("session-state/copilot-2");
|
||||
write(
|
||||
&unnamed.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
|
||||
);
|
||||
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
|
||||
// A live holder marks the session in use; a lock left by a process that exited does not.
|
||||
std::fs::write(session.join(format!("inuse.{}.lock", std::process::id())), "").unwrap();
|
||||
std::fs::write(unnamed.join("inuse.2147483646.lock"), "").unwrap();
|
||||
|
||||
let empty = copilot_home.join("session-state/copilot-empty");
|
||||
std::fs::create_dir_all(&empty).unwrap();
|
||||
std::fs::write(empty.join("workspace.yaml"), "id: copilot-empty\ncwd: /work/app\n").unwrap();
|
||||
|
||||
let other = copilot_home.join("session-state/copilot-other");
|
||||
write(
|
||||
&other.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "unrelated project"}})],
|
||||
);
|
||||
std::fs::write(other.join("workspace.yaml"), "id: copilot-other\ncwd: /other\n").unwrap();
|
||||
|
||||
exec_sqlite(
|
||||
&tmp.path().join(".config/Code/User/globalStorage/agent-host.db"),
|
||||
"CREATE TABLE sessions_v2 (session_uri TEXT PRIMARY KEY, payload TEXT, modified_time INTEGER);
|
||||
CREATE TABLE session_chat_state (session_uri TEXT, chat_uri TEXT, title TEXT, title_source TEXT);
|
||||
CREATE TABLE chats_v2 (chat_uri TEXT PRIMARY KEY, owner_session_uri TEXT, chat_order INTEGER, provider_data TEXT, metadata TEXT, tombstoned INTEGER);
|
||||
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs1', '{}', 100);
|
||||
INSERT INTO chats_v2 VALUES ('chat:/vs1', 'copilotcli:/vs1', 0, '{\"sdkSessionId\":\"copilot-vscode\"}', '{\"data\":{\"summary\":\"Session\",\"titleSource\":\"user\"}}', 0);
|
||||
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs2', '{}', 100);
|
||||
INSERT INTO chats_v2 VALUES ('chat:/vs2', 'copilotcli:/vs2', 0, '{\"sdkSessionId\":\"copilot-placeholder\"}', '{\"data\":{\"summary\":\"New session\",\"titleSource\":\"auto\"}}', 0);",
|
||||
);
|
||||
|
||||
let sessions = copilot_sessions(&copilot_home, Some(tmp.path()), Path::new("/work"));
|
||||
assert_eq!(sessions.len(), 5);
|
||||
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
|
||||
let named = by_id.remove("copilot-1").unwrap();
|
||||
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
|
||||
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
|
||||
assert!(named.in_use);
|
||||
assert_eq!(by_id.remove("copilot-block").unwrap().title, "check why excalidraw font is not displayed");
|
||||
assert_eq!(by_id.remove("copilot-vscode").unwrap().title, "Session");
|
||||
assert_eq!(by_id.remove("copilot-placeholder").unwrap().title, "Greeting exchange");
|
||||
let unnamed = by_id.remove("copilot-2").unwrap();
|
||||
assert_eq!(unnamed.title, "add a regression test");
|
||||
assert!(!unnamed.in_use);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -16,14 +16,19 @@ pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
|
||||
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None, inline_number: None });
|
||||
}
|
||||
from_uri(str_of(content, "uri")?)
|
||||
}
|
||||
"resource" => {
|
||||
let resource = content.get("resource")?;
|
||||
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
|
||||
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
|
||||
mime.starts_with("image/").then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
})
|
||||
}
|
||||
"resource_link" => {
|
||||
let uri = str_of(content, "uri")?;
|
||||
@@ -51,6 +56,7 @@ pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
});
|
||||
}
|
||||
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
|
||||
@@ -67,6 +73,7 @@ pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
|
||||
mime_type: mime.into(),
|
||||
data: base64::engine::general_purpose::STANDARD.encode(bytes),
|
||||
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
|
||||
inline_number: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+1110
-185
File diff suppressed because it is too large.
Load diff
@@ -68,9 +68,27 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
|
||||
headers: cfg.headers.iter().map(|(k, v)| McpKeyValue { name: k.clone(), value: v.clone() }).collect(),
|
||||
agents: cfg.agents.clone(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: cfg.registry_name.clone(),
|
||||
registry_url: cfg.registry_url.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Merges `projected` MCP servers from enabled agent plugins behind `configured` User and
|
||||
/// Workspace servers so standalone settings entries always take precedence on name clashes.
|
||||
pub fn merge_projected_servers(mut configured: Vec<McpServer>, projected: Vec<McpServer>) -> Vec<McpServer> {
|
||||
let existing: HashSet<String> = configured.iter().map(|s| s.name.clone()).collect();
|
||||
// Same-named servers from different bundles are distinct rows (ids are `plugin:<bundle>:<server>`).
|
||||
let mut seen_projected: HashSet<String> = HashSet::new();
|
||||
for srv in projected {
|
||||
if !existing.contains(&srv.name) && seen_projected.insert(srv.id.clone()) {
|
||||
configured.push(srv);
|
||||
}
|
||||
}
|
||||
configured
|
||||
}
|
||||
|
||||
fn normalize_provider(id: &str) -> &str {
|
||||
id.strip_suffix("-acp").unwrap_or(id)
|
||||
}
|
||||
@@ -238,6 +256,28 @@ pub fn apply_save(
|
||||
if input.scope == McpScope::Workspace && !has_workspace {
|
||||
return Err("Open a project to configure workspace MCP servers".into());
|
||||
}
|
||||
let existing_meta = input.id.as_deref().and_then(parse_server_id).and_then(|(prev_scope, prev_name)| {
|
||||
let map = match prev_scope {
|
||||
McpScope::User => &*user,
|
||||
McpScope::Workspace => &*workspace,
|
||||
};
|
||||
map.get(prev_name).map(|prev| (prev.registry_name.clone(), prev.registry_url.clone()))
|
||||
});
|
||||
let registry_name = input
|
||||
.registry_name
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| existing_meta.as_ref().and_then(|(rn, _)| rn.clone()));
|
||||
let registry_url = input
|
||||
.registry_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| existing_meta.and_then(|(_, ru)| ru));
|
||||
|
||||
let cfg = match input.transport {
|
||||
McpTransport::Stdio => {
|
||||
let cmd = input.command.as_deref().map(str::trim).unwrap_or_default();
|
||||
@@ -261,6 +301,8 @@ pub fn apply_save(
|
||||
url: None,
|
||||
headers: BTreeMap::new(),
|
||||
agents: normalize_agents_list(input.agents),
|
||||
registry_name,
|
||||
registry_url,
|
||||
}
|
||||
}
|
||||
McpTransport::Http | McpTransport::Sse => {
|
||||
@@ -285,6 +327,8 @@ pub fn apply_save(
|
||||
url: Some(url.to_owned()),
|
||||
headers,
|
||||
agents: normalize_agents_list(input.agents),
|
||||
registry_name,
|
||||
registry_url,
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -399,13 +443,8 @@ pub fn apply_save_json(
|
||||
Ok(saved_names)
|
||||
}
|
||||
|
||||
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
|
||||
".github/plugin/plugin.json",
|
||||
".plugin/plugin.json",
|
||||
".claude-plugin/plugin.json",
|
||||
".cursor-plugin/plugin.json",
|
||||
"plugin.json",
|
||||
];
|
||||
const COPILOT_PLUGIN_MANIFESTS: &[&str] =
|
||||
&[".github/plugin/plugin.json", ".plugin/plugin.json", ".claude-plugin/plugin.json", "plugin.json"];
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
enum SourceFormat {
|
||||
@@ -1007,6 +1046,8 @@ fn parse_one_server_def(obj: &serde_json::Map<String, Value>) -> Option<AgentMcp
|
||||
url,
|
||||
headers: parse_key_values_map(obj.get("headers")),
|
||||
agents,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1051,6 +1092,14 @@ fn extract_servers_from_root(root: &Value, fallback_name: Option<&str>) -> BTree
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn read_external_mcp_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
|
||||
read_external_file(path)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_mcp_value(root: &Value) -> Result<BTreeMap<String, AgentMcpServer>, String> {
|
||||
Ok(extract_servers_from_root(root, None))
|
||||
}
|
||||
|
||||
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return BTreeMap::new();
|
||||
@@ -1088,15 +1137,7 @@ pub async fn probe_stdio_server(server: &AgentMcpServer, cwd: &Path) -> McpProbe
|
||||
env.push((k.clone(), v.clone()));
|
||||
}
|
||||
}
|
||||
let search_path = env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
let program = ide_core::process::find_executable(raw_cmd, &search_path)
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| raw_cmd.to_owned());
|
||||
let program = ide_jsonrpc::resolve_spawn_program(raw_cmd, &env).to_string_lossy().into_owned();
|
||||
|
||||
let stderr_lines = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
|
||||
let stderr_capture = stderr_lines.clone();
|
||||
@@ -1259,6 +1300,10 @@ mod tests {
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1314,6 +1359,8 @@ mod tests {
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1334,6 +1381,8 @@ mod tests {
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1354,6 +1403,8 @@ mod tests {
|
||||
url: Some("https://example.com/mcp".into()),
|
||||
headers: vec![McpKeyValue { name: "Authorization".into(), value: "Bearer secret".into() }],
|
||||
agents: vec!["claude".into()],
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -453,6 +453,26 @@ pub fn discover_memories(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Age
|
||||
out
|
||||
}
|
||||
|
||||
/// Discovers all standalone memory entries across `workspaces` and `home`, then appends
|
||||
/// projected rule/context entries from enabled agent plugins (deduplicated by canonical path).
|
||||
pub fn discover_memories_with_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
projected: Vec<AgentMemoryEntry>,
|
||||
) -> Vec<AgentMemoryEntry> {
|
||||
let mut out = discover_memories(workspaces, home);
|
||||
let mut seen: HashSet<PathBuf> =
|
||||
out.iter().map(|e| dunce::canonicalize(&e.path.0).unwrap_or_else(|_| e.path.0.clone())).collect();
|
||||
for mut entry in projected {
|
||||
let canon = dunce::canonicalize(&entry.path.0).unwrap_or_else(|_| entry.path.0.clone());
|
||||
entry.path = canon.clone().into();
|
||||
if seen.insert(canon) {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
|
||||
/// against `policy` and optional per-session `session_overrides`.
|
||||
pub fn resolve_catalog(
|
||||
@@ -1412,6 +1432,8 @@ fn parse_cursor_mdc(path: &Path, rel: &str) -> Option<AgentMemoryEntry> {
|
||||
writable: false,
|
||||
valid: true,
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1482,6 +1504,8 @@ fn parse_entry(
|
||||
writable,
|
||||
valid: true,
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ pub enum InterruptionReason {
|
||||
BackendStop,
|
||||
UnexpectedExit,
|
||||
NetworkTimeout,
|
||||
CursorCapacity,
|
||||
}
|
||||
|
||||
impl From<AgentShutdownReason> for InterruptionReason {
|
||||
@@ -199,6 +200,10 @@ pub struct AgentTask {
|
||||
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recovery_window_mins: Option<u32>,
|
||||
/// Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -427,6 +432,9 @@ pub struct AgentImage {
|
||||
/// Base64, without a `data:` prefix.
|
||||
pub data: String,
|
||||
pub name: Option<String>,
|
||||
/// The `[Image #n]` label in the prompt text for an inline attachment.
|
||||
#[specta(optional)]
|
||||
pub inline_number: Option<u32>,
|
||||
}
|
||||
|
||||
impl AgentImage {
|
||||
@@ -454,11 +462,29 @@ pub struct AgentPrompt {
|
||||
pub images: Vec<AgentImage>,
|
||||
}
|
||||
|
||||
/// Provenance carried with a scheduled turn (`SameTask`, `Send Later`, or `/loop`), including
|
||||
/// while queued behind a busy turn, so trust and approval ceilings are re-checked at dispatch.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduledTurnMeta {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub permissions: Option<crate::automation::AutomationPermissionMode>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub extra_choices: Vec<AgentConfigChoice>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub automation_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub session_schedule_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentQueued {
|
||||
pub id: String,
|
||||
pub prompt: AgentPrompt,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(skip)]
|
||||
pub scheduled: Option<ScheduledTurnMeta>,
|
||||
}
|
||||
|
||||
/// A setting chosen for a new task, by [`AgentConfigOption::id`].
|
||||
@@ -616,6 +642,9 @@ pub enum AgentEntry {
|
||||
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
|
||||
#[serde(default)]
|
||||
recovery: Option<InterruptionReason>,
|
||||
/// One-based automatic retry number for this continuation.
|
||||
#[serde(default)]
|
||||
retry_attempt: Option<u32>,
|
||||
},
|
||||
Agent {
|
||||
text: String,
|
||||
@@ -731,6 +760,9 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// Command the project host can run to install this missing built-in CLI.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cli_install_command: Option<String>,
|
||||
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
|
||||
#[serde(default)]
|
||||
pub can_sign_in: bool,
|
||||
@@ -920,7 +952,7 @@ pub struct AgentModelCatalog {
|
||||
}
|
||||
|
||||
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum AgentEvent {
|
||||
/// A task was created or its metadata changed.
|
||||
@@ -1018,6 +1050,22 @@ pub struct McpServer {
|
||||
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
|
||||
#[serde(default)]
|
||||
pub unapproved: bool,
|
||||
/// Parent agent plugin ID when this server is live-projected from an enabled agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
/// Canonical MCP registry server identifier when installed from an MCP registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL when installed from an MCP registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating or updating a user or workspace MCP server.
|
||||
@@ -1044,6 +1092,14 @@ pub struct McpServerInput {
|
||||
/// Agent provider ids this server is enabled for; empty means enabled for all agents.
|
||||
#[serde(default)]
|
||||
pub agents: Vec<String>,
|
||||
/// Canonical MCP registry server identifier when installed from an MCP registry.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL when installed from an MCP registry.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
fn default_true() -> bool {
|
||||
@@ -1051,8 +1107,8 @@ fn default_true() -> bool {
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentProviderMemoryPolicy, AgentSkillMode,
|
||||
AgentSkillPolicy, AutoMemoryMode,
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
|
||||
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
|
||||
};
|
||||
|
||||
/// Kind of discovered agent memory entry.
|
||||
@@ -1165,6 +1221,14 @@ pub struct AgentMemoryEntry {
|
||||
pub valid: bool,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
/// Parent agent plugin ID when this rule/instruction is live-projected from an enabled agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
|
||||
@@ -1337,6 +1401,14 @@ pub struct AgentSkill {
|
||||
pub valid: bool,
|
||||
/// What validation found (`name` mismatch, missing or over-long description…).
|
||||
pub warnings: Vec<String>,
|
||||
/// Parent agent plugin ID when this skill comes from an agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
|
||||
@@ -1398,6 +1470,383 @@ pub struct McpDiscoveredServer {
|
||||
pub header_keys: Vec<String>,
|
||||
}
|
||||
|
||||
/// Which workspace, user, or CLI store an agent plugin bundle was discovered in.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginSource {
|
||||
/// `~/.copilot/installed-plugins/{<marketplace>,_direct}/*`.
|
||||
#[default]
|
||||
CopilotUser,
|
||||
/// `~/.claude/plugins/installed_plugins.json` & `~/.claude/plugins/cache/*`.
|
||||
ClaudeUser,
|
||||
/// `~/.codex/plugins/cache/*`.
|
||||
CodexUser,
|
||||
/// `~/.gemini/extensions/*`.
|
||||
GeminiUser,
|
||||
}
|
||||
|
||||
/// Manifest format(s) recognized inside an agent plugin directory.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginFormat {
|
||||
/// Vendor-neutral Agent Plugins 1.0 / 1.1 (`plugin.json` with `$schema`).
|
||||
#[default]
|
||||
AgentPluginsV1,
|
||||
/// `.openidea/plugin.json`.
|
||||
OpenIdea,
|
||||
/// `.claude-plugin/plugin.json`.
|
||||
Claude,
|
||||
/// `.plugin/plugin.json`, `.github/plugin/plugin.json`, or legacy root `plugin.json`.
|
||||
Copilot,
|
||||
/// `.codex-plugin/plugin.json`.
|
||||
Codex,
|
||||
/// `gemini-extension.json`.
|
||||
GeminiExtension,
|
||||
}
|
||||
|
||||
/// Which policy layer decided an [`AgentPluginState::enabled`] status.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginOrigin {
|
||||
/// Native harness configuration owns the enabled state.
|
||||
#[default]
|
||||
None,
|
||||
/// Locked `Off` because the workspace is untrusted.
|
||||
Trust,
|
||||
/// Locked `Off` until executable capabilities (stdio MCP / lifecycle hooks) are approved.
|
||||
Consent,
|
||||
}
|
||||
|
||||
/// Data type of a plugin `userConfig` / `variables` / `settings` option.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginConfigFieldKind {
|
||||
#[default]
|
||||
String,
|
||||
Number,
|
||||
Boolean,
|
||||
Secret,
|
||||
}
|
||||
|
||||
/// One configurable option declared by an agent plugin (`userConfig`, `variables`, or Gemini `settings`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginConfigField {
|
||||
pub key: String,
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
pub kind: AgentPluginConfigFieldKind,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub default_value: Option<String>,
|
||||
#[serde(default)]
|
||||
pub required: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub env_var: Option<String>,
|
||||
/// Current non-sensitive value (always empty when `kind == Secret`).
|
||||
#[serde(default)]
|
||||
pub value: String,
|
||||
/// True when a secret is stored in OS Keychain for this field.
|
||||
#[serde(default)]
|
||||
pub has_secret: bool,
|
||||
}
|
||||
|
||||
/// Summary of components and executable capabilities bundled inside an agent plugin.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginCapabilities {
|
||||
pub skill_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub skill_names: Vec<String>,
|
||||
pub mcp_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub mcp_names: Vec<String>,
|
||||
pub rule_count: u32,
|
||||
pub subagent_count: u32,
|
||||
pub command_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub hook_files: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub stdio_commands: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub has_lsp: bool,
|
||||
#[serde(default)]
|
||||
pub has_canvas_or_app: bool,
|
||||
/// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub native_harnesses: Vec<String>,
|
||||
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub capability_hash: Option<String>,
|
||||
#[serde(default)]
|
||||
pub requires_consent: bool,
|
||||
}
|
||||
|
||||
/// One discovered agent plugin bundle on disk (or built-in).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPlugin {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub author: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub homepage: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repository: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub license: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
pub source: AgentPluginSource,
|
||||
/// Scope this bundle is installed in. Native plugin folders and enablement config are
|
||||
/// resolved relative to this scope.
|
||||
pub scope: McpScope,
|
||||
/// Workspace whose native configuration owns this row's enablement (workspace scope only).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub workspace_root: Option<IpcPath>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub also_in: Vec<AgentPluginSource>,
|
||||
pub formats: Vec<AgentPluginFormat>,
|
||||
pub root_path: IpcPath,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub manifest_path: Option<IpcPath>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub readme_path: Option<IpcPath>,
|
||||
pub default_enabled: bool,
|
||||
pub approx_tokens: u32,
|
||||
pub capabilities: AgentPluginCapabilities,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub config_fields: Vec<AgentPluginConfigField>,
|
||||
pub valid: bool,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Resolved agent plugin state paired with its policy origin and consent status.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginState {
|
||||
pub plugin: AgentPlugin,
|
||||
pub enabled: bool,
|
||||
pub origin: AgentPluginOrigin,
|
||||
/// True when executable stdio MCP / hook capabilities require user approval before enabling.
|
||||
pub consent_required: bool,
|
||||
}
|
||||
|
||||
/// Summary of a configured or repository-discovered plugin marketplace.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceInfo {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub source: String,
|
||||
pub scope: McpScope,
|
||||
/// True when discovered from a harness-native marketplace/configuration file.
|
||||
pub discovered: bool,
|
||||
}
|
||||
|
||||
/// Full catalog returned to Settings › Agents › Plugins.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginCatalog {
|
||||
pub plugins: Vec<AgentPluginState>,
|
||||
pub marketplaces: Vec<AgentMarketplaceInfo>,
|
||||
pub projected_skills: u32,
|
||||
pub projected_mcp_servers: u32,
|
||||
pub projected_rules: u32,
|
||||
}
|
||||
|
||||
/// One installable plugin entry listed inside a marketplace or repository.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceCandidate {
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub author: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_dark_url: Option<String>,
|
||||
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
|
||||
pub source_spec: String,
|
||||
pub subpath: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub keywords: Vec<String>,
|
||||
pub already_installed_user: bool,
|
||||
pub already_installed_workspace: bool,
|
||||
}
|
||||
|
||||
/// Result of browsing a marketplace (`owner/repo`, local marketplace path, or direct plugin repo).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceBrowseResult {
|
||||
pub source: String,
|
||||
pub marketplace_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
pub candidates: Vec<AgentMarketplaceCandidate>,
|
||||
}
|
||||
|
||||
/// Whether a previewed plugin can be installed for one harness, and where it is already installed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginInstallTarget {
|
||||
pub harness: String,
|
||||
pub supported: bool,
|
||||
/// Why the harness cannot install this plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub reason: Option<String>,
|
||||
/// Whether this harness can enable the plugin for just one workspace.
|
||||
pub workspace_supported: bool,
|
||||
/// This harness already records the plugin for the user / for the current workspace.
|
||||
pub installed_user: bool,
|
||||
pub installed_workspace: bool,
|
||||
/// The harness store already holds this plugin version's folder, so installing replaces it.
|
||||
pub overwrite_required: bool,
|
||||
}
|
||||
|
||||
/// Security and capability preview of an agent plugin bundle before installation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginPreview {
|
||||
/// `"github"` or `"local"`.
|
||||
pub source_kind: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
/// Pinned commit SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub commit_sha: Option<String>,
|
||||
#[serde(default)]
|
||||
pub subpath: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub local_path: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace_source: Option<String>,
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_dark_url: Option<String>,
|
||||
pub formats: Vec<AgentPluginFormat>,
|
||||
pub capabilities: AgentPluginCapabilities,
|
||||
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
|
||||
pub scan_warnings: Vec<crate::skill_installer::SkillScanWarning>,
|
||||
/// Per-harness install eligibility and existing installs for this plugin and marketplace.
|
||||
pub targets: Vec<AgentPluginInstallTarget>,
|
||||
}
|
||||
|
||||
/// Request payload to install a previewed agent plugin into a selected harness's native plugin directory.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InstallAgentPluginRequest {
|
||||
/// `"github"` or `"local"`.
|
||||
pub source_kind: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
/// Pinned root tree SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
/// Pinned commit SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub commit_sha: Option<String>,
|
||||
#[serde(default)]
|
||||
pub subpath: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub local_path: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub marketplace_source: Option<String>,
|
||||
pub scope: McpScope,
|
||||
/// Native harness the plugin is installed for (`claude`, `copilot`, `codex`, or `gemini`).
|
||||
pub harness: String,
|
||||
#[serde(default)]
|
||||
pub approve_capabilities: bool,
|
||||
/// The preview's `capabilityHash` the user approved; the install is refused if the installed
|
||||
/// folder resolves to different executable capabilities.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub approved_capability_hash: Option<String>,
|
||||
#[serde(default)]
|
||||
pub confirm_warnings: bool,
|
||||
#[serde(default)]
|
||||
pub overwrite: bool,
|
||||
}
|
||||
|
||||
/// Selection of one server from an external MCP configuration source to import.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -209,6 +209,17 @@ pub(super) fn cut(chain: &[&Value], turns: usize) -> Result<Option<String>, Stri
|
||||
Ok(parent(first_dropped).map(str::to_owned))
|
||||
}
|
||||
|
||||
/// Where to fork `chain` to keep only its first `turns` turns: the entry the last kept
|
||||
/// turn ends with, as [`cut`] reports it. `None` when the chain has fewer turns.
|
||||
pub(super) fn keep(chain: &[&Value], turns: usize) -> Option<Option<String>> {
|
||||
let total = chain.iter().filter(|e| is_turn_start(e)).count();
|
||||
if turns > total {
|
||||
return None;
|
||||
}
|
||||
// A turn that runs now is in the chain up to where it got: it is dropped like any other.
|
||||
cut(chain, total - turns).ok()
|
||||
}
|
||||
|
||||
/// The newest title Claude Code gave the session.
|
||||
pub(crate) fn title(entries: &[Value]) -> Option<String> {
|
||||
entries
|
||||
|
||||
@@ -58,7 +58,7 @@ pub(crate) fn connect(
|
||||
on_stderr: Box<dyn Fn(String) + Send + Sync>,
|
||||
) -> std::io::Result<Peer> {
|
||||
let config = Config {
|
||||
program: super::newest_install(&spec.command),
|
||||
program: super::newest_install(spec.executable()),
|
||||
args: spec.args.clone(),
|
||||
env: spec.env.clone(),
|
||||
config_dir: cli::config_dir(&spec.env),
|
||||
@@ -347,6 +347,24 @@ impl Shim {
|
||||
}
|
||||
|
||||
/// The conversation a session started with `start` begins with.
|
||||
/// `start` (a fork's) cut after the source's first `turns` turns; `None` when the
|
||||
/// transcript can't be read or has fewer turns.
|
||||
fn pin_fork(&self, cwd: &Path, start: &Start, id: &str, turns: usize) -> Option<Start> {
|
||||
let chain = match self.base_chain(cwd, start) {
|
||||
Ok(chain) => chain,
|
||||
Err(e) => {
|
||||
tracing::debug!("Claude Code fork {id}: can't read the source transcript: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let refs: Vec<&Value> = chain.iter().collect();
|
||||
Some(match (start, history::keep(&refs, turns)?) {
|
||||
(_, None) => Start::New { id: id.to_owned() },
|
||||
(Start::Fork { from, .. }, Some(at)) => Start::Fork { from: from.clone(), id: id.to_owned(), at: Some(at) },
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn base_chain(&self, cwd: &Path, start: &Start) -> Result<Vec<Value>, String> {
|
||||
let (id, at) = match start {
|
||||
Start::New { .. } => return Ok(Vec::new()),
|
||||
@@ -509,11 +527,28 @@ impl Shim {
|
||||
// from its transcript on disk when the task's first prompt starts it.
|
||||
None => (Start::Fork { from: source_id.to_owned(), id: id.clone(), at: None }, Settings::default()),
|
||||
};
|
||||
// Pinned now: the source may go on (or be running a turn) before the fork starts.
|
||||
let wanted = params.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64);
|
||||
let mut kept = None;
|
||||
let start = match wanted {
|
||||
Some(turns) => match self.pin_fork(&cwd, &start, &id, turns as usize) {
|
||||
Some(pinned) => {
|
||||
kept = Some(turns);
|
||||
pinned
|
||||
}
|
||||
None => start,
|
||||
},
|
||||
None => start,
|
||||
};
|
||||
self.save_pending(&id, Some(&start));
|
||||
let session = self.add_session(&id, cwd, start, true, ¶ms);
|
||||
session.st.lock().settings = settings;
|
||||
let options = session.st.lock().settings.options();
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
let mut reply = json!({ "sessionId": id, "configOptions": options });
|
||||
if let Some(turns) = kept {
|
||||
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
"session/set_config_option" | "session/set_mode" => {
|
||||
let session = self.session(¶ms)?;
|
||||
@@ -947,7 +982,7 @@ impl Session {
|
||||
fn steer(&self, prompt: Value) -> Result<(), String> {
|
||||
let uuid = new_uuid(true);
|
||||
let mut message = user_message(&prompt, &uuid, true);
|
||||
message["priority"] = json!("now");
|
||||
message["priority"] = json!("next");
|
||||
let mut st = self.st.lock();
|
||||
let proc = st.proc.clone().ok_or("Claude Code is not running")?;
|
||||
let turn = st.turn.as_mut().filter(|t| !t.cancelled).ok_or("no turn is running")?;
|
||||
|
||||
@@ -212,6 +212,30 @@ async fn steer(h: &Harness) -> (Outcome, String) {
|
||||
(vec![outcome("prompt", r), outcome("steer", steered)], s)
|
||||
}
|
||||
|
||||
/// Stops the turn while a steered message waits for the running tool.
|
||||
async fn steer_stop(h: &Harness) -> (Outcome, String) {
|
||||
let s = h.new_session().await;
|
||||
let prompt = h.prompt(&s, "Run the Bash command `sleep 5 && echo done`, then tell me its output in one line.");
|
||||
let steer_and_stop = async {
|
||||
tokio::time::sleep(Duration::from_millis(3000)).await;
|
||||
let steered = h
|
||||
.request(
|
||||
"_openidea/steer",
|
||||
json!({ "sessionId": s, "prompt": [{ "type": "text", "text": "Also end your answer with the word BANANA." }] }),
|
||||
)
|
||||
.await;
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
h.client.notify("session/cancel", json!({ "sessionId": s })).unwrap();
|
||||
steered
|
||||
};
|
||||
let (r, steered) = tokio::join!(prompt, steer_and_stop);
|
||||
if h.recording {
|
||||
// Long enough for the CLI to run the steered message, had it kept it.
|
||||
tokio::time::sleep(Duration::from_secs(8)).await;
|
||||
}
|
||||
(vec![outcome("prompt", r), outcome("steer", steered)], s)
|
||||
}
|
||||
|
||||
async fn subagent(h: &Harness) -> (Outcome, String) {
|
||||
let s = h.new_session().await;
|
||||
h.answer(&[Some("allow"), Some("allow")]);
|
||||
@@ -253,6 +277,7 @@ const SCENARIOS: &[(&str, ScenarioFn)] = &[
|
||||
("tool_approval", |h| Box::pin(tool_approval(h))),
|
||||
("interrupt", |h| Box::pin(interrupt(h))),
|
||||
("steer", |h| Box::pin(steer(h))),
|
||||
("steer_stop", |h| Box::pin(steer_stop(h))),
|
||||
("subagent", |h| Box::pin(subagent(h))),
|
||||
("resume", |h| Box::pin(resume(h))),
|
||||
];
|
||||
@@ -620,10 +645,20 @@ async fn replay_steer() {
|
||||
assert_eq!(r.stop("prompt"), "end_turn");
|
||||
assert!(r.h.text(&r.session, "agent_message_chunk").contains("BANANA"));
|
||||
let steer = r.sent(0).into_iter().filter(|m| m["type"] == "user").nth(1).unwrap();
|
||||
assert_eq!(steer["priority"], "now");
|
||||
assert_eq!(steer["priority"], "next");
|
||||
assert!(steer["uuid"].as_str().unwrap().ends_with(history::STEER_MARK));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_steer_stop() {
|
||||
let r = replay("steer_stop").await;
|
||||
assert!(r.result("steer").is_ok(), "{:?}", r.result("steer"));
|
||||
assert_eq!(r.stop("prompt"), "cancelled");
|
||||
assert!(!r.h.text(&r.session, "agent_message_chunk").contains("BANANA"));
|
||||
let interrupt = r.sent(0).into_iter().find(|m| m["request"]["subtype"] == "interrupt").unwrap();
|
||||
assert_eq!(interrupt["request"]["cancel_queued"], true);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn replay_subagent() {
|
||||
let r = replay("subagent").await;
|
||||
@@ -695,6 +730,73 @@ async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() {
|
||||
assert_eq!(saved, json!({ "fork": source, "id": target, "at": null }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_pins_the_cut_to_the_kept_turns() {
|
||||
struct NoLaunch;
|
||||
impl Cli for NoLaunch {
|
||||
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
|
||||
panic!("session/fork must not launch the CLI")
|
||||
}
|
||||
}
|
||||
|
||||
let config = tempfile::tempdir().unwrap();
|
||||
let pending = tempfile::tempdir().unwrap();
|
||||
let h = Harness::connect(
|
||||
Arc::new(NoLaunch),
|
||||
config.path().to_path_buf(),
|
||||
pending.path().to_path_buf(),
|
||||
std::env::temp_dir(),
|
||||
Vec::new(),
|
||||
)
|
||||
.await;
|
||||
let source = "11111111-1111-4111-8111-111111111111";
|
||||
// Two finished turns and a third still running.
|
||||
let dir = config.path().join("projects").join(history::escape(&h.cwd));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let mut parent = Value::Null;
|
||||
let mut lines = String::new();
|
||||
for (uuid, kind, text) in [
|
||||
("u1", "user", "one"),
|
||||
("a1", "assistant", "1"),
|
||||
("u2", "user", "two"),
|
||||
("a2", "assistant", "2"),
|
||||
("u3", "user", "three"),
|
||||
("a3", "assistant", "partial"),
|
||||
] {
|
||||
let entry = json!({"type": kind, "uuid": uuid, "parentUuid": parent,
|
||||
"message": {"role": kind, "content": [{"type": "text", "text": text}]}});
|
||||
lines += &format!("{entry}\n");
|
||||
parent = json!(uuid);
|
||||
}
|
||||
std::fs::write(dir.join(format!("{source}.jsonl")), lines).unwrap();
|
||||
|
||||
let fork = |target: &'static str, turns: u64| {
|
||||
h.request(
|
||||
"session/fork",
|
||||
json!({
|
||||
"sessionId": source,
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": { "openidea": { "forkSessionId": target, "forkTurns": turns } }
|
||||
}),
|
||||
)
|
||||
};
|
||||
let saved = |target: &str| -> Value {
|
||||
serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap()
|
||||
};
|
||||
|
||||
let target = "22222222-2222-4222-8222-222222222222";
|
||||
let reply = fork(target, 2).await.unwrap();
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns"), Some(&json!(2)));
|
||||
assert_eq!(saved(target), json!({ "fork": source, "id": target, "at": "a2" }));
|
||||
|
||||
// More turns than the transcript holds: left to the host to settle.
|
||||
let target = "33333333-3333-4333-8333-333333333333";
|
||||
let reply = fork(target, 4).await.unwrap();
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns"), None);
|
||||
assert_eq!(saved(target), json!({ "fork": source, "id": target, "at": null }));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_rejects_a_requested_id_that_is_not_canonical() {
|
||||
struct NoLaunch;
|
||||
@@ -799,7 +901,14 @@ fn scrub(frame: &mut Value) -> bool {
|
||||
json!([{ "name": "review", "description": "Review a pull request", "argumentHint": "" },
|
||||
{ "name": "init", "description": "Write a CLAUDE.md", "argumentHint": "" }]),
|
||||
);
|
||||
for k in ["agents", "account", "available_output_styles", "user_output_styles_dir", "output_style"] {
|
||||
for k in [
|
||||
"agents",
|
||||
"account",
|
||||
"stored_login_organization_uuid",
|
||||
"available_output_styles",
|
||||
"user_output_styles_dir",
|
||||
"output_style",
|
||||
] {
|
||||
o.remove(k);
|
||||
}
|
||||
}
|
||||
@@ -1484,3 +1593,34 @@ async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env()
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md"
|
||||
},
|
||||
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
|
||||
}
|
||||
}
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
|
||||
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
|
||||
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
assert!(parsed["pluginConfigs"]["azure"].is_null());
|
||||
}
|
||||
@@ -34,6 +34,14 @@ const OUTPUT_EVERY: Duration = Duration::from_millis(200);
|
||||
const EARLY_CANCEL: Duration = Duration::from_secs(1);
|
||||
/// How long the client's connection outlives codex.
|
||||
const EXIT_GRACE: Duration = Duration::from_millis(100);
|
||||
/// How often running background terminals are listed again: codex announces neither a
|
||||
/// terminal that outlives its turn nor its end.
|
||||
#[cfg(not(test))]
|
||||
const TERMINAL_POLL: Duration = Duration::from_secs(3);
|
||||
#[cfg(test)]
|
||||
const TERMINAL_POLL: Duration = Duration::from_millis(20);
|
||||
/// How long closing the connection waits for codex to stop the background terminals.
|
||||
const TERMINAL_CLEAN: Duration = Duration::from_secs(3);
|
||||
/// What a thread's name is asked for with, after its first turn.
|
||||
const NAME_PROMPT: &str = "Name this conversation for a list of tasks: a short title of at most six words, in the \
|
||||
language the user writes in. Reply with the title only, without quotes or a closing period.";
|
||||
@@ -66,7 +74,7 @@ pub(crate) fn connect(
|
||||
on_stderr: Box<dyn Fn(String) + Send + Sync>,
|
||||
) -> std::io::Result<Peer> {
|
||||
attach(client, |events| {
|
||||
let command = super::newest_install(&spec.command);
|
||||
let command = super::newest_install(spec.executable());
|
||||
Peer::spawn_framed(&command, &spec.args, cwd, &spec.env, events, on_stderr, Framing::Lines)
|
||||
})
|
||||
}
|
||||
@@ -187,6 +195,10 @@ fn attach(
|
||||
}
|
||||
tokio::spawn(async move {
|
||||
to_client.closed().await;
|
||||
// Background terminals run in process groups of their own: stopping codex alone
|
||||
// would leave them running with nothing left to report or stop them.
|
||||
let threads: Vec<String> = shim.state.lock().threads.keys().cloned().collect();
|
||||
shim.clean_terminals(&threads).await;
|
||||
codex.kill();
|
||||
});
|
||||
Ok(ours)
|
||||
@@ -248,6 +260,14 @@ struct Thread {
|
||||
token_usage: Option<Value>,
|
||||
/// The thread has a name.
|
||||
named: bool,
|
||||
/// Running background terminals of this session and its subagents, by task id:
|
||||
/// `(thread, processId)`.
|
||||
terminals: HashMap<String, (String, String)>,
|
||||
/// The background tasks reported last.
|
||||
shown_tasks: Vec<Value>,
|
||||
/// The background terminals are being followed; `relist` asks for another listing.
|
||||
watching: bool,
|
||||
relist: bool,
|
||||
/// A name is being asked for.
|
||||
naming: bool,
|
||||
}
|
||||
@@ -416,6 +436,7 @@ impl CodexShim {
|
||||
"session/prompt" => self.prompt(¶ms).await,
|
||||
"_openidea/steer" => self.steer(¶ms).await,
|
||||
"_openidea/rollback" => self.rollback(¶ms).await,
|
||||
"_openidea/stop_task" => self.stop_task(¶ms).await,
|
||||
"session/close" => self.close(¶ms).await,
|
||||
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
|
||||
}
|
||||
@@ -439,7 +460,7 @@ impl CodexShim {
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": false, "sse": false, "stdio": true },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "additionalDirectories": {} },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true } },
|
||||
"_meta": { "openidea": { "rollback": true, "steer": true, "backgroundTasks": true } },
|
||||
},
|
||||
"agentInfo": { "name": "codex", "title": "Codex", "version": version },
|
||||
"authMethods": [],
|
||||
@@ -568,9 +589,26 @@ impl CodexShim {
|
||||
}
|
||||
let result = self.call("thread/fork", request).await?;
|
||||
let (id, options) = self.open_thread(&result, &models, settings);
|
||||
// Cut by what the fork holds: a turn the source runs now may or may not be in it.
|
||||
let wanted = params.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64);
|
||||
let held = result.pointer("/thread/turns").and_then(Value::as_array).map(|t| t.len() as u64);
|
||||
let mut kept = None;
|
||||
if let (Some(turns), Some(held)) = (wanted, held)
|
||||
&& turns <= held
|
||||
{
|
||||
let dropped = held - turns;
|
||||
if dropped > 0 {
|
||||
self.rollback(&json!({ "sessionId": id, "turns": dropped })).await?;
|
||||
}
|
||||
kept = Some(turns);
|
||||
}
|
||||
self.apply_skill_roots(&id, params).await;
|
||||
self.publish_skills(&id).await;
|
||||
Ok(json!({ "sessionId": id, "configOptions": options }))
|
||||
let mut reply = json!({ "sessionId": id, "configOptions": options });
|
||||
if let Some(turns) = kept {
|
||||
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
async fn set_config(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
@@ -915,6 +953,16 @@ impl CodexShim {
|
||||
/// Stops following the session's thread (codex unloads it once nothing follows it).
|
||||
async fn close(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let threads: Vec<String> = {
|
||||
let state = self.state.lock();
|
||||
state
|
||||
.threads
|
||||
.iter()
|
||||
.filter(|(id, t)| *id == session || t.parent.as_deref() == Some(session))
|
||||
.map(|(id, _)| id.clone())
|
||||
.collect()
|
||||
};
|
||||
self.clean_terminals(&threads).await;
|
||||
let known = self.state.lock().threads.remove(session).is_some();
|
||||
if known && let Err(e) = self.call("thread/unsubscribe", json!({ "threadId": session })).await {
|
||||
tracing::debug!("codex: unsubscribing from {session}: {}", e.message);
|
||||
@@ -922,6 +970,129 @@ impl CodexShim {
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
/// Follows the background terminals of `session` and its subagents until none runs:
|
||||
/// codex keeps them running after the turn that started them.
|
||||
fn watch_terminals(self: &Arc<Self>, session: &str) {
|
||||
{
|
||||
let mut state = self.state.lock();
|
||||
if state.gone {
|
||||
return;
|
||||
}
|
||||
let Some(t) = state.threads.get_mut(session) else { return };
|
||||
if t.watching {
|
||||
t.relist = true;
|
||||
return;
|
||||
}
|
||||
t.watching = true;
|
||||
}
|
||||
let (shim, session) = (self.clone(), session.to_owned());
|
||||
self.runtime.spawn(async move {
|
||||
loop {
|
||||
let running = shim.list_terminals(&session).await;
|
||||
let relist = {
|
||||
let mut state = shim.state.lock();
|
||||
let Some(t) = state.threads.get_mut(&session) else { return };
|
||||
let relist = std::mem::take(&mut t.relist);
|
||||
if !relist && !running {
|
||||
t.watching = false;
|
||||
return;
|
||||
}
|
||||
relist
|
||||
};
|
||||
if !relist {
|
||||
tokio::time::sleep(TERMINAL_POLL).await;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Reports the running background terminals of `session` and its subagents as the
|
||||
/// session's background tasks; whether any runs. A codex without the (experimental)
|
||||
/// listing has none to report.
|
||||
async fn list_terminals(&self, session: &str) -> bool {
|
||||
let threads: Vec<String> = {
|
||||
let state = self.state.lock();
|
||||
let children = state.threads.iter().filter(|(_, t)| t.parent.as_deref() == Some(session));
|
||||
std::iter::once(session.to_owned()).chain(children.map(|(id, _)| id.clone())).collect()
|
||||
};
|
||||
let mut terminals = HashMap::new();
|
||||
let mut tasks = Vec::new();
|
||||
for thread in &threads {
|
||||
let listed = match self.terminals_of(thread).await {
|
||||
Ok(listed) => listed,
|
||||
Err(e) => {
|
||||
tracing::debug!("codex: listing the background terminals of {thread}: {}", e.message);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for (process, description) in listed {
|
||||
let id = if thread == session { process.clone() } else { format!("{thread}:{process}") };
|
||||
tasks.push(json!({ "task_id": id, "task_type": "local_bash", "description": description }));
|
||||
terminals.insert(id, (thread.clone(), process));
|
||||
}
|
||||
}
|
||||
let running = !tasks.is_empty();
|
||||
let changed = {
|
||||
let mut state = self.state.lock();
|
||||
let Some(t) = state.threads.get_mut(session) else { return false };
|
||||
t.terminals = terminals;
|
||||
let changed = t.shown_tasks != tasks;
|
||||
if changed {
|
||||
t.shown_tasks = tasks.clone();
|
||||
}
|
||||
changed
|
||||
};
|
||||
if changed {
|
||||
self.emit(session, json!({ "sessionUpdate": crate::BACKGROUND_TASKS_UPDATE, "tasks": tasks }));
|
||||
}
|
||||
running
|
||||
}
|
||||
|
||||
/// The running background terminals of `thread`, as `(processId, description)`.
|
||||
async fn terminals_of(&self, thread: &str) -> Result<Vec<(String, String)>, ResponseError> {
|
||||
let mut all = Vec::new();
|
||||
let mut cursor = Value::Null;
|
||||
let mut seen = HashSet::new();
|
||||
loop {
|
||||
let page =
|
||||
self.call("thread/backgroundTerminals/list", json!({ "threadId": thread, "cursor": cursor })).await?;
|
||||
all.extend(translate::background_terminals(&page));
|
||||
match page.get("nextCursor").and_then(Value::as_str) {
|
||||
Some(next) if !next.is_empty() && seen.insert(next.to_owned()) => cursor = json!(next),
|
||||
_ => return Ok(all),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `_openidea/stop_task`: stops one background terminal.
|
||||
async fn stop_task(&self, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session = str_param(params, "sessionId")?;
|
||||
let task = str_param(params, "taskId")?;
|
||||
let known = self.state.lock().threads.get(session).and_then(|t| t.terminals.get(task).cloned());
|
||||
let (thread, process) = known.unwrap_or_else(|| (session.to_owned(), task.to_owned()));
|
||||
self.call("thread/backgroundTerminals/terminate", json!({ "threadId": thread, "processId": process })).await?;
|
||||
self.list_terminals(session).await;
|
||||
Ok(json!({}))
|
||||
}
|
||||
|
||||
/// Stops the background terminals of `threads`; a codex without the (experimental)
|
||||
/// method has none.
|
||||
async fn clean_terminals(&self, threads: &[String]) {
|
||||
if threads.is_empty() || self.state.lock().gone {
|
||||
return;
|
||||
}
|
||||
let clean = async {
|
||||
for thread in threads {
|
||||
if let Err(e) = self.call("thread/backgroundTerminals/clean", json!({ "threadId": thread })).await {
|
||||
tracing::debug!("codex: stopping the background terminals of {thread}: {}", e.message);
|
||||
}
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(TERMINAL_CLEAN, clean).await.is_err() {
|
||||
tracing::warn!("codex: stopping the background terminals timed out");
|
||||
}
|
||||
}
|
||||
|
||||
/// `session/cancel`: interrupts the session's turn, or the one about to start.
|
||||
fn cancel(&self, session: &str) {
|
||||
let mut state = self.state.lock();
|
||||
@@ -1261,6 +1432,19 @@ impl CodexShim {
|
||||
t.turn = None;
|
||||
}
|
||||
t.completed = Some(id.to_owned());
|
||||
// A command still open when its turn completed goes on in the background (a
|
||||
// background terminal): its call returned, so it didn't fail with the turn. Its
|
||||
// own completion reports how it ended. Sent before the prompt's answer settles the
|
||||
// turn.
|
||||
if completed {
|
||||
let commands = t.items.values().filter(|i| i["type"] == "commandExecution");
|
||||
for id in commands.filter_map(|i| i["id"].as_str()) {
|
||||
self.emit(
|
||||
thread,
|
||||
json!({ "sessionUpdate": "tool_call_update", "toolCallId": id, "status": "completed" }),
|
||||
);
|
||||
}
|
||||
}
|
||||
t.items.clear();
|
||||
t.last_chunk = None;
|
||||
let error = t.error.take();
|
||||
@@ -1275,6 +1459,7 @@ impl CodexShim {
|
||||
t.naming |= name;
|
||||
(t.parent.clone(), (answer, error), name)
|
||||
};
|
||||
self.watch_terminals(parent.as_deref().unwrap_or(thread));
|
||||
if name {
|
||||
let (shim, thread, turn) = (self.clone(), thread.to_owned(), id.to_owned());
|
||||
self.runtime.spawn(async move { shim.name_thread(&thread, &turn).await });
|
||||
|
||||
@@ -66,6 +66,7 @@ fn manager(dir: &Path, runtime: Arc<Runtime>) -> AgentManager {
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: Some(agents),
|
||||
home_dir: Some(dir.into()),
|
||||
env_secrets: None,
|
||||
|
||||
@@ -125,6 +125,7 @@ for line in sys.stdin:
|
||||
name: "Codex".into(),
|
||||
driver: crate::provider::Driver::Codex,
|
||||
command: script.to_string_lossy().into_owned(),
|
||||
managed_cli: None,
|
||||
args: Vec::new(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
@@ -1019,10 +1020,12 @@ async fn play<R: AsyncRead + Unpin, W: AsyncWrite + Unpin>(
|
||||
.unwrap()
|
||||
.unwrap_or_else(|| panic!("the shim closed before {frame}"));
|
||||
let actual: Value = serde_json::from_str(&line).unwrap();
|
||||
// Older recordings predate config inspection, skill discovery and thread naming; play an
|
||||
// unsupported server.
|
||||
// Older recordings predate config inspection, skill discovery, thread naming and
|
||||
// background terminals; play an unsupported server.
|
||||
let method = actual["method"].as_str().unwrap_or_default();
|
||||
if matches!(method, "config/read" | "skills/list" | "thread/sample") && frame["method"] != method {
|
||||
let unrecorded = matches!(method, "config/read" | "skills/list" | "thread/sample")
|
||||
|| method.starts_with("thread/backgroundTerminals/");
|
||||
if unrecorded && frame["method"] != method {
|
||||
let reply = json!({ "id": actual["id"], "error": { "code": -32601, "message": "unsupported" } });
|
||||
write.write_all(format!("{reply}\n").as_bytes()).await.unwrap();
|
||||
continue;
|
||||
@@ -1162,6 +1165,60 @@ impl Handler for TrustServer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Forks a thread holding two finished turns and one cut off by the fork.
|
||||
#[derive(Default)]
|
||||
struct ForkServer {
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl Handler for ForkServer {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.calls.lock().push((method.to_owned(), params));
|
||||
match method {
|
||||
"initialize" | "thread/rollback" => Ok(json!({})),
|
||||
"model/list" | "skills/list" => Ok(json!({"data": []})),
|
||||
"config/read" => Ok(json!({"layers": []})),
|
||||
"thread/fork" => Ok(json!({"thread": {"id": "copy", "turns": [
|
||||
{"id": "t1", "status": "completed"},
|
||||
{"id": "t2", "status": "completed"},
|
||||
{"id": "t3", "status": "interrupted"},
|
||||
]}})),
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_keeps_the_asked_turns_of_what_the_fork_holds() {
|
||||
for (turns, rolled_back, kept) in [(Some(2), Some(1), Some(2)), (Some(3), None, Some(3)), (Some(4), None, None)] {
|
||||
let server = Arc::new(ForkServer::default());
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
|
||||
let acp = attach(Arc::new(Client::default()), |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
request(&acp, "initialize", json!({})).await.unwrap();
|
||||
let params = json!({"cwd": "/tmp", "sessionId": "source", "mcpServers": [],
|
||||
"_meta": {"openidea": {"forkTurns": turns}}});
|
||||
let reply = request(&acp, "session/fork", params).await.unwrap();
|
||||
assert_eq!(reply["sessionId"], "copy");
|
||||
assert_eq!(reply.pointer("/_meta/openidea/forkTurns").and_then(Value::as_u64), kept);
|
||||
let rollbacks: Vec<Value> =
|
||||
server.calls.lock().iter().filter(|(m, _)| m == "thread/rollback").map(|(_, p)| p.clone()).collect();
|
||||
assert_eq!(
|
||||
rollbacks,
|
||||
rolled_back.map(|n| json!({"threadId": "copy", "numTurns": n})).into_iter().collect::<Vec<_>>()
|
||||
);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn project_trust_is_confirmed_before_new_resumed_and_forked_sessions() {
|
||||
for method in ["session/new", "session/load", "session/fork"] {
|
||||
@@ -1243,7 +1300,10 @@ async fn auth_failure_names_auth() {
|
||||
let (results, _client, frames, _) = replay(Scenario::AuthFailure).await;
|
||||
let init = result(&results, "initialize").as_ref().unwrap();
|
||||
assert_eq!(init["agentCapabilities"]["loadSession"], true);
|
||||
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"], json!({"rollback": true, "steer": true}));
|
||||
assert_eq!(
|
||||
init["agentCapabilities"]["_meta"]["openidea"],
|
||||
json!({"rollback": true, "steer": true, "backgroundTasks": true})
|
||||
);
|
||||
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
|
||||
let new = result(&results, "new").as_ref().unwrap();
|
||||
let categories: Vec<&str> =
|
||||
@@ -2215,3 +2275,179 @@ async fn an_ephemeral_session_starts_an_ephemeral_thread() {
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
|
||||
/// A codex whose background terminals listings come from `pages` (an empty list after
|
||||
/// them); `None` answers like a codex without the method.
|
||||
struct TerminalServer {
|
||||
pages: Mutex<VecDeque<Value>>,
|
||||
supported: bool,
|
||||
calls: Mutex<Vec<(String, Value)>>,
|
||||
}
|
||||
|
||||
impl TerminalServer {
|
||||
fn new(pages: Vec<Value>, supported: bool) -> Arc<Self> {
|
||||
Arc::new(Self { pages: Mutex::new(pages.into()), supported, calls: Mutex::default() })
|
||||
}
|
||||
|
||||
fn calls_of(&self, method: &str) -> Vec<Value> {
|
||||
self.calls.lock().iter().filter(|(m, _)| m == method).map(|(_, p)| p.clone()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler for TerminalServer {
|
||||
fn on_notification(&self, _: &str, _: Value) {}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
self.calls.lock().push((method.to_owned(), params));
|
||||
match method {
|
||||
"initialize" => Ok(json!({})),
|
||||
"model/list" => Ok(json!({"data": []})),
|
||||
"config/read" => Ok(json!({"layers": []})),
|
||||
"thread/start" => Ok(json!({"thread": {"id": "s", "turns": []}, "cwd": "/w"})),
|
||||
"skills/list" => Ok(json!({"data": []})),
|
||||
"thread/unsubscribe" => Ok(json!({})),
|
||||
m if m.starts_with("thread/backgroundTerminals/") && !self.supported => {
|
||||
Err((codes::INVALID_REQUEST, format!("Invalid request: unknown variant `{m}`")))
|
||||
}
|
||||
"thread/backgroundTerminals/list" => {
|
||||
Ok(self.pages.lock().pop_front().unwrap_or_else(|| json!({"data": [], "nextCursor": null})))
|
||||
}
|
||||
"thread/backgroundTerminals/terminate" => Ok(json!({"terminated": true})),
|
||||
"thread/backgroundTerminals/clean" => Ok(json!({})),
|
||||
_ => Err((codes::METHOD_NOT_FOUND, method.to_owned())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn terminal(process: &str, command: &str) -> Value {
|
||||
json!({"itemId": format!("item-{process}"), "processId": process, "command": command, "cwd": "/w", "osPid": 4242})
|
||||
}
|
||||
|
||||
/// A session over a codex playing `server`; the codex peer and the ACP peer.
|
||||
async fn terminal_session(server: Arc<TerminalServer>, client: Arc<Client>) -> (Peer, Peer) {
|
||||
let (ours, theirs) = tokio::io::duplex(1 << 16);
|
||||
let (read, write) = tokio::io::split(theirs);
|
||||
let native = Peer::connect_framed(read, write, server, Framing::Lines);
|
||||
let acp = attach(client, |events| {
|
||||
let (read, write) = tokio::io::split(ours);
|
||||
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
|
||||
})
|
||||
.unwrap();
|
||||
let init = request(&acp, "initialize", json!({})).await.unwrap();
|
||||
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["backgroundTasks"], true);
|
||||
request(&acp, "session/new", json!({"cwd": "/w", "mcpServers": []})).await.unwrap();
|
||||
(native, acp)
|
||||
}
|
||||
|
||||
fn shown_tasks(client: &Client) -> Vec<Value> {
|
||||
client
|
||||
.of("s")
|
||||
.into_iter()
|
||||
.filter(|u| u["sessionUpdate"] == crate::BACKGROUND_TASKS_UPDATE)
|
||||
.map(|u| u["tasks"].clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn until(what: &str, mut done: impl FnMut() -> bool) {
|
||||
for _ in 0..200 {
|
||||
if done() {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
panic!("timed out waiting for {what}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn background_terminals_outlive_their_turn_as_background_tasks_until_they_end() {
|
||||
let running = json!({"data": [terminal("p1", "/bin/zsh -lc 'sleep 600; echo done'")], "nextCursor": null});
|
||||
let server = TerminalServer::new(vec![running.clone(), running.clone(), running], true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the terminal to end", || shown_tasks(&client).len() == 2).await;
|
||||
assert_eq!(
|
||||
shown_tasks(&client),
|
||||
[json!([{"task_id": "p1", "task_type": "local_bash", "description": "sleep 600; echo done"}]), json!([])]
|
||||
);
|
||||
let listed = server.calls_of("thread/backgroundTerminals/list").len();
|
||||
assert!(listed >= 4, "listed until none ran, got {listed}");
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), listed, "stops listing once none runs");
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_background_terminal_stops_on_request_and_all_stop_with_the_connection() {
|
||||
let running = json!({"data": [terminal("p1", "cargo nextest run")], "nextCursor": null});
|
||||
let server = TerminalServer::new(vec![running; 1000], true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the terminal to show", || !shown_tasks(&client).is_empty()).await;
|
||||
request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.unwrap();
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/terminate"), [json!({"threadId": "s", "processId": "p1"})]);
|
||||
assert!(server.calls_of("thread/backgroundTerminals/clean").is_empty());
|
||||
acp.kill();
|
||||
until("the terminals to be cleaned", || !server.calls_of("thread/backgroundTerminals/clean").is_empty()).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/clean"), [json!({"threadId": "s"})]);
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn closing_a_session_stops_its_background_terminals() {
|
||||
let server = TerminalServer::new(Vec::new(), true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client).await;
|
||||
request(&acp, "session/close", json!({"sessionId": "s"})).await.unwrap();
|
||||
let calls: Vec<String> = server.calls.lock().iter().map(|(m, _)| m.clone()).collect();
|
||||
let clean = calls.iter().position(|m| m == "thread/backgroundTerminals/clean").expect("cleaned");
|
||||
let unsubscribe = calls.iter().position(|m| m == "thread/unsubscribe").expect("unsubscribed");
|
||||
assert!(clean < unsubscribe);
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_codex_without_background_terminals_reports_none() {
|
||||
let server = TerminalServer::new(Vec::new(), false);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server.clone(), client.clone()).await;
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": "interrupted"}})).unwrap();
|
||||
until("the listing", || !server.calls_of("thread/backgroundTerminals/list").is_empty()).await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
assert_eq!(server.calls_of("thread/backgroundTerminals/list").len(), 1);
|
||||
assert!(shown_tasks(&client).is_empty());
|
||||
assert!(request(&acp, "_openidea/stop_task", json!({"sessionId": "s", "taskId": "p1"})).await.is_err());
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_command_left_running_by_a_completed_turn_is_not_a_failure() {
|
||||
for (status, settled) in [("completed", true), ("interrupted", false)] {
|
||||
let server = TerminalServer::new(Vec::new(), true);
|
||||
let client = Arc::new(Client::default());
|
||||
let (native, acp) = terminal_session(server, client.clone()).await;
|
||||
let item = json!({"type": "commandExecution", "id": "call_1", "command": "/bin/zsh -lc 'sleep 240'",
|
||||
"cwd": "/w", "status": "inProgress", "commandActions": []});
|
||||
native.notify("item/started", json!({"threadId": "s", "turnId": "t1", "item": item})).unwrap();
|
||||
native.notify("turn/completed", json!({"threadId": "s", "turn": {"id": "t1", "status": status}})).unwrap();
|
||||
until("the command card", || client.of("s").iter().any(|u| u["sessionUpdate"] == "tool_call")).await;
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
let updates: Vec<Value> = client
|
||||
.of("s")
|
||||
.into_iter()
|
||||
.filter(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "call_1")
|
||||
.collect();
|
||||
let expected = if settled {
|
||||
vec![json!({"sessionUpdate": "tool_call_update", "toolCallId": "call_1", "status": "completed"})]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
assert_eq!(updates, expected, "turn {status}");
|
||||
acp.kill();
|
||||
native.kill();
|
||||
}
|
||||
}
|
||||
@@ -553,7 +553,12 @@ fn image_content(image: &crate::model::AgentImage) -> Value {
|
||||
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
|
||||
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
|
||||
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
|
||||
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
|
||||
let image = crate::model::AgentImage {
|
||||
mime_type: "image/png".into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
};
|
||||
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
|
||||
}
|
||||
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
|
||||
@@ -876,6 +881,20 @@ pub(super) fn decisions(params: &Value, command: bool) -> Vec<Choice> {
|
||||
out
|
||||
}
|
||||
|
||||
/// One page of `thread/backgroundTerminals/list`: the running terminals as
|
||||
/// `(processId, description)`.
|
||||
pub(super) fn background_terminals(page: &Value) -> Vec<(String, String)> {
|
||||
let data = page.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
data.iter()
|
||||
.filter_map(|t| {
|
||||
let process = t.get("processId").and_then(Value::as_str).filter(|p| !p.is_empty())?;
|
||||
let command = t.get("command").and_then(Value::as_str).unwrap_or_default();
|
||||
let description = crate::shell_script(command).unwrap_or_else(|| command.to_owned());
|
||||
Some((process.to_owned(), description))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A command prefix as typed: the script of a `<shell> -lc <script>` wrapper, else the words.
|
||||
fn shell_unwrapped(argv: &[&str]) -> String {
|
||||
match argv {
|
||||
|
||||
@@ -37,6 +37,15 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else
|
||||
const EARLY_CANCEL: Duration = Duration::from_secs(2);
|
||||
const EXIT_GRACE: Duration = Duration::from_millis(100);
|
||||
|
||||
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`).
|
||||
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
|
||||
env.iter()
|
||||
.find(|(key, _)| key == "COPILOT_HOME")
|
||||
.map(|(_, value)| PathBuf::from(value))
|
||||
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
|
||||
.or_else(|| home.map(|home| home.join(".copilot")))
|
||||
}
|
||||
|
||||
/// Pre-session discovery result for `Shared::fetch_settings`.
|
||||
pub(crate) struct Discovered {
|
||||
pub commands: Vec<Value>,
|
||||
@@ -59,7 +68,7 @@ pub(crate) fn connect(
|
||||
) -> std::io::Result<Peer> {
|
||||
let launch_args = spec.args.clone();
|
||||
attach_with_args(client, launch_args, |events| {
|
||||
let command = super::newest_install(&spec.command);
|
||||
let command = super::newest_install(spec.executable());
|
||||
let args = headless_args(&spec.args);
|
||||
Peer::spawn_framed(&command, &args, cwd, &spec.env, events, on_stderr, Framing::ContentLength)
|
||||
})
|
||||
@@ -551,6 +560,7 @@ impl CopilotShim {
|
||||
"initialize" => self.initialize().await,
|
||||
"session/new" => self.new_session(¶ms).await,
|
||||
"session/load" => self.load_session(¶ms).await,
|
||||
"session/fork" => self.fork_session(¶ms).await,
|
||||
"session/set_config_option" => self.set_config(¶ms).await,
|
||||
"session/prompt" => self.prompt(¶ms, false).await,
|
||||
"_openidea/steer" => self.prompt(¶ms, true).await,
|
||||
@@ -569,7 +579,7 @@ impl CopilotShim {
|
||||
"loadSession": true,
|
||||
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
|
||||
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
|
||||
"sessionCapabilities": { "close": {}, "list": {} },
|
||||
"sessionCapabilities": { "fork": {}, "close": {}, "list": {} },
|
||||
"_meta": { "openidea": { "steer": true, "backgroundTasks": true, "contextUsage": true } },
|
||||
},
|
||||
"agentInfo": {
|
||||
@@ -649,6 +659,25 @@ impl CopilotShim {
|
||||
|
||||
async fn load_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
|
||||
let session_id = str_param(params, "sessionId")?.to_owned();
|
||||
let loaded = self.resume_session(params, &session_id).await?;
|
||||
let actual_id = loaded.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
|
||||
self.replay_history(&actual_id).await;
|
||||
Ok(loaded)
|
||||
}
|
||||
|
||||
async fn fork_session(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
|
||||
let source = str_param(params, "sessionId")?;
|
||||
let forked = self.call("sessions.fork", json!({ "sessionId": source })).await?;
|
||||
let target = forked
|
||||
.get("sessionId")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|id| !id.is_empty())
|
||||
.ok_or_else(|| error(codes::INTERNAL_ERROR, "Copilot fork returned no sessionId"))?
|
||||
.to_owned();
|
||||
self.resume_session(params, &target).await
|
||||
}
|
||||
|
||||
async fn resume_session(self: &Arc<Self>, params: &Value, session_id: &str) -> Result<Value, ResponseError> {
|
||||
let cwd = str_param(params, "cwd")?;
|
||||
let catalog = self.models().await?;
|
||||
let defaults = fetch_user_defaults(self.copilot(), &self.args).await;
|
||||
@@ -675,7 +704,8 @@ impl CopilotShim {
|
||||
apply_memory(params, &mut req);
|
||||
|
||||
let resumed = self.call("session.resume", req).await?;
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(session_id).to_owned();
|
||||
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": actual_id })).await {
|
||||
if let Some(model_id) = current.get("modelId").or_else(|| current.get("model")).and_then(Value::as_str) {
|
||||
let _ = settings.set(&catalog, MODEL, model_id);
|
||||
}
|
||||
@@ -686,7 +716,6 @@ impl CopilotShim {
|
||||
let _ = settings.set(&catalog, CONTEXT_TIER, tier);
|
||||
}
|
||||
}
|
||||
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
|
||||
let options = models::config_options(&catalog, &settings);
|
||||
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
|
||||
self.publish_commands(&actual_id, cwd);
|
||||
@@ -697,6 +726,28 @@ impl CopilotShim {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn replay_history(&self, session_id: &str) {
|
||||
let history = match self.call("session.getMessages", json!({ "sessionId": session_id })).await {
|
||||
Ok(history) => history,
|
||||
Err(error) => {
|
||||
tracing::warn!("copilot session {session_id}: could not load history: {}", error.message);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let events = history.get("events").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
let updates = {
|
||||
let mut state = self.state.lock();
|
||||
let Some(entry) = state.sessions.get_mut(session_id) else { return };
|
||||
events
|
||||
.iter()
|
||||
.flat_map(|event| entry.translator.translate_history(session_id, event, None).updates)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
for (target_session, update) in updates {
|
||||
self.send_update(&target_session, update);
|
||||
}
|
||||
}
|
||||
|
||||
fn sync_usage_metrics(self: &Arc<Self>, session_id: &str) {
|
||||
let shim = self.clone();
|
||||
let sid = session_id.to_owned();
|
||||
@@ -1321,6 +1372,10 @@ fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Valu
|
||||
{
|
||||
let path_str = saved.to_string_lossy().into_owned();
|
||||
let name = saved.file_name().and_then(|n| n.to_str()).unwrap_or("image").to_owned();
|
||||
// Copilot takes one text prompt and a separate attachments array.
|
||||
if let Some(number) = block.pointer("/_meta/openideaImageNumber").and_then(Value::as_u64) {
|
||||
text_parts.push(format!("[Image #{number}: {name}]"));
|
||||
}
|
||||
attachments.push(json!({ "type": "file", "path": path_str, "displayName": name }));
|
||||
temp_files.push(saved);
|
||||
}
|
||||
|
||||
@@ -115,6 +115,18 @@ fn sample_price_units() -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_copilot_home_from_agent_env_or_user_home() {
|
||||
let home = std::path::Path::new("/home/test");
|
||||
assert_eq!(
|
||||
super::config_dir(&[("COPILOT_HOME".into(), "/custom/copilot".into())], Some(home)).as_deref(),
|
||||
Some(std::path::Path::new("/custom/copilot"))
|
||||
);
|
||||
if std::env::var_os("COPILOT_HOME").is_none() {
|
||||
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_an_enabled_auto_only_catalog() {
|
||||
let list = json!({
|
||||
@@ -434,6 +446,39 @@ impl Handler for FakeCopilotServer {
|
||||
"skills.discover" => Ok(json!({ "skills": [] })),
|
||||
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
|
||||
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
|
||||
"sessions.fork" => Ok(json!({ "sessionId": "cop-sess-fork" })),
|
||||
"session.getMessages" => Ok(json!({
|
||||
"events": [
|
||||
{
|
||||
"type": "user.message",
|
||||
"data": { "content": "Fix the parser" }
|
||||
},
|
||||
{
|
||||
"type": "assistant.message",
|
||||
"data": {
|
||||
"messageId": "history-message",
|
||||
"reasoningText": "Inspect the grammar first.",
|
||||
"content": "I fixed the parser."
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "tool.execution_start",
|
||||
"data": {
|
||||
"toolCallId": "history-tool",
|
||||
"toolName": "view",
|
||||
"arguments": { "path": "/tmp/parser.rs" }
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "tool.execution_complete",
|
||||
"data": {
|
||||
"toolCallId": "history-tool",
|
||||
"success": true,
|
||||
"result": { "content": "fn parse() {}" }
|
||||
}
|
||||
}
|
||||
]
|
||||
})),
|
||||
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
|
||||
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
|
||||
"session.mode.set" => Ok(json!({})),
|
||||
@@ -674,6 +719,81 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_loads_and_replays_copilot_history() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates.clone(), move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
assert!(init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object());
|
||||
let loaded: Value = client
|
||||
.request("session/load", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(loaded["sessionId"], "cop-sess-1");
|
||||
|
||||
assert!(
|
||||
server
|
||||
.calls
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|(method, params)| { method == "session.getMessages" && params["sessionId"] == "cop-sess-1" })
|
||||
);
|
||||
let seen = updates.0.lock();
|
||||
assert!(
|
||||
seen.iter().any(|u| u["sessionUpdate"] == "user_message_chunk" && u["content"]["text"] == "Fix the parser")
|
||||
);
|
||||
assert!(
|
||||
seen.iter().any(
|
||||
|u| u["sessionUpdate"] == "agent_thought_chunk" && u["content"]["text"] == "Inspect the grammar first."
|
||||
)
|
||||
);
|
||||
assert!(
|
||||
seen.iter()
|
||||
.any(|u| u["sessionUpdate"] == "agent_message_chunk" && u["content"]["text"] == "I fixed the parser.")
|
||||
);
|
||||
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call" && u["toolCallId"] == "history-tool"));
|
||||
assert!(seen.iter().any(|u| u["sessionUpdate"] == "tool_call_update" && u["toolCallId"] == "history-tool"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_forks_copilot_sessions_and_resumes_the_new_id() {
|
||||
let server =
|
||||
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
|
||||
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
|
||||
let server_clone = server.clone();
|
||||
let client = attach(updates, move |events| {
|
||||
let (a, b) = tokio::io::duplex(1 << 16);
|
||||
let (ar, aw) = tokio::io::split(a);
|
||||
let (br, bw) = tokio::io::split(b);
|
||||
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
|
||||
let _ = server_clone.peer.set(srv_peer);
|
||||
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
|
||||
let forked: Value = client
|
||||
.request("session/fork", json!({ "sessionId": "cop-sess-1", "cwd": "/tmp", "mcpServers": [] }), None)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(forked["sessionId"], "cop-sess-fork");
|
||||
let calls = server.calls.lock();
|
||||
assert!(calls.iter().any(|(method, params)| method == "sessions.fork" && params["sessionId"] == "cop-sess-1"));
|
||||
assert!(calls.iter().any(|(method, params)| method == "session.resume" && params["sessionId"] == "cop-sess-fork"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
|
||||
let server =
|
||||
|
||||
@@ -370,6 +370,55 @@ impl EventTranslator {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Translates one persisted Copilot event returned by `session.getMessages`. The live
|
||||
/// event stream omits historical user messages and emits reasoning deltas, while the
|
||||
/// persisted form has complete user and assistant messages.
|
||||
pub fn translate_history(&mut self, main_session: &str, event: &Value, fallback_limit: Option<u32>) -> Translated {
|
||||
let event_type = str_of(event, "type").unwrap_or_default();
|
||||
let data = event.get("data").unwrap_or(&Value::Null);
|
||||
if event_type == "user.message" {
|
||||
let Some(text) = str_of(data, "content").map(str::trim).filter(|text| !text.is_empty()) else {
|
||||
return Translated { updates: Vec::new(), terminal: None };
|
||||
};
|
||||
let target_session = str_of(event, "agentId")
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(|id| format!("{main_session}:sub:{id}"))
|
||||
.unwrap_or_else(|| main_session.to_owned());
|
||||
return Translated {
|
||||
updates: vec![(
|
||||
target_session,
|
||||
json!({
|
||||
"sessionUpdate": "user_message_chunk",
|
||||
"content": { "type": "text", "text": text },
|
||||
}),
|
||||
)],
|
||||
terminal: None,
|
||||
};
|
||||
}
|
||||
|
||||
let mut translated = self.translate(main_session, event, fallback_limit);
|
||||
if event_type == "assistant.message"
|
||||
&& !(data.get("parentToolCallId").and_then(Value::as_str).is_some() && str_of(event, "agentId").is_none())
|
||||
&& let Some(reasoning) = str_of(data, "reasoningText").map(str::trim).filter(|text| !text.is_empty())
|
||||
{
|
||||
let target_session = str_of(event, "agentId")
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(|id| format!("{main_session}:sub:{id}"))
|
||||
.unwrap_or_else(|| main_session.to_owned());
|
||||
translated.updates.insert(
|
||||
0,
|
||||
(
|
||||
target_session,
|
||||
json!({
|
||||
"sessionUpdate": "agent_thought_chunk",
|
||||
"content": { "type": "text", "text": reasoning },
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
translated
|
||||
}
|
||||
}
|
||||
|
||||
fn describe_tool(name: &str, args: &Value) -> ToolInfo {
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
//!
|
||||
//! A shim speaks ACP v1 as the agent side, plus:
|
||||
//! - `agentCapabilities.sessionCapabilities.fork` and `session/fork`
|
||||
//! (`{ sessionId, cwd, mcpServers }` → a `session/new` result for the copy);
|
||||
//! (`{ sessionId, cwd, mcpServers }` → a `session/new` result for the copy). With
|
||||
//! `_meta.openidea.forkTurns`, the copy keeps only the source's first that many turns;
|
||||
//! the result repeats it in its `_meta.openidea.forkTurns` when the shim cut the copy;
|
||||
//! - `agentCapabilities._meta.openidea.rollback` and `_openidea/rollback`
|
||||
//! (`{ sessionId, turns }`: drops the last `turns` user turns from the session);
|
||||
//! - `agentCapabilities._meta.openidea.steer` and `_openidea/steer`
|
||||
@@ -25,11 +27,7 @@ use std::sync::Arc;
|
||||
/// A path, or a name not found on `PATH`, is used as it is; a single match returns its
|
||||
/// resolved path so Windows `PATHEXT` shims (`claude.cmd`, `codex.cmd`) start.
|
||||
pub(crate) fn newest_install(command: &str) -> String {
|
||||
let path = ide_core::process::host_var_os("PATH")
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| *k == "PATH").map(|(_, v)| v.to_owned()))
|
||||
.unwrap_or_default();
|
||||
// Windows: read afresh, so a tool the user installed since the IDE started is found too.
|
||||
newest_install_in(command, &ide_core::process::with_user_path(&path))
|
||||
newest_install_in(command, &ide_core::tool_path::search_path())
|
||||
}
|
||||
|
||||
fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -35,6 +35,7 @@ pub(crate) struct ProviderSpec {
|
||||
pub name: String,
|
||||
pub driver: Driver,
|
||||
pub command: String,
|
||||
pub managed_cli: Option<String>,
|
||||
pub args: Vec<String>,
|
||||
/// Number of trailing arguments added by the built-in agent's settings.
|
||||
pub additional_args_len: usize,
|
||||
@@ -90,6 +91,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
("vibe", "Mistral Vibe", Driver::Acp, &["vibe-acp"], "Run `vibe` in a terminal and sign in."),
|
||||
("omp", "OMP", Driver::Acp, &["omp", "acp"], "Run `omp` in a terminal and sign in."),
|
||||
("hermes", "Hermes Agent", Driver::Acp, &["hermes", "acp"], "Run `hermes model` in a terminal."),
|
||||
("antigravity-acp", "Google Antigravity", Driver::Acp, &["agy", "acp"], "Run `agy acp --login` in a terminal."),
|
||||
];
|
||||
|
||||
fn builtins() -> Vec<ProviderSpec> {
|
||||
@@ -100,6 +102,7 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
name: (*name).into(),
|
||||
driver: *driver,
|
||||
command: cmd[0].into(),
|
||||
managed_cli: None,
|
||||
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
|
||||
additional_args_len: 0,
|
||||
env: Vec::new(),
|
||||
@@ -110,11 +113,15 @@ fn builtins() -> Vec<ProviderSpec> {
|
||||
}
|
||||
|
||||
impl ProviderSpec {
|
||||
pub(crate) fn executable(&self) -> &str {
|
||||
self.managed_cli.as_deref().unwrap_or(&self.command)
|
||||
}
|
||||
|
||||
pub(crate) fn login_hint(&self, program: &Path) -> String {
|
||||
if !program.is_absolute() {
|
||||
return self.login_hint.clone();
|
||||
}
|
||||
let search = ide_core::process::host_var_os("PATH").unwrap_or_default();
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let builtin = builtin_spec(&self.id);
|
||||
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
|
||||
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
|
||||
@@ -135,7 +142,7 @@ impl ProviderSpec {
|
||||
.flatten();
|
||||
let hint = match terminal_args {
|
||||
Some(args) => {
|
||||
let command = render_login_command(program, args, cfg!(windows));
|
||||
let command = render_shell_command(program, args, cfg!(windows));
|
||||
format!("Run `{command}` in a terminal.")
|
||||
}
|
||||
None => self.login_hint(program),
|
||||
@@ -179,7 +186,9 @@ impl ProviderSpec {
|
||||
}
|
||||
|
||||
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
|
||||
if self.driver != Driver::Acp {
|
||||
if let Some(program) = self.managed_cli.take() {
|
||||
self.command = program;
|
||||
} else if self.driver != Driver::Acp {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
@@ -222,7 +231,9 @@ impl ProviderSpec {
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
if let Some(builtin) = builtin_spec(&self.id)
|
||||
&& !(matches!(self.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&self.id))
|
||||
{
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
@@ -533,7 +544,7 @@ fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>
|
||||
return spec.login_hint.clone();
|
||||
}
|
||||
let (args, suffix) = rest.split_once('`').expect("built-in login hints delimit their command");
|
||||
let command = render_login_command(program, args.split_whitespace(), windows);
|
||||
let command = render_shell_command(program, args.split_whitespace(), windows);
|
||||
match suffix {
|
||||
" in a terminal." => format!("Run `{command}` in a terminal."),
|
||||
" in a terminal and sign in." => format!("Run `{command}` in a terminal and sign in."),
|
||||
@@ -541,7 +552,11 @@ fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>
|
||||
}
|
||||
}
|
||||
|
||||
fn render_login_command<'a>(program: &Path, args: impl IntoIterator<Item = &'a str>, windows: bool) -> String {
|
||||
pub(crate) fn render_shell_command<'a>(
|
||||
program: &Path,
|
||||
args: impl IntoIterator<Item = &'a str>,
|
||||
windows: bool,
|
||||
) -> String {
|
||||
let quote = |word: &str| {
|
||||
if windows { format!("'{}'", word.replace('\'', "''")) } else { format!("'{}'", word.replace('\'', "'\\''")) }
|
||||
};
|
||||
@@ -585,6 +600,13 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
|
||||
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
|
||||
}
|
||||
|
||||
/// Built-in CLI agents whose ACP Registry archive ships a separate ACP server binary
|
||||
/// rather than the CLI itself, so the built-in CLI's login subcommand does not apply
|
||||
/// to a registry install.
|
||||
fn registry_uses_separate_binary(id: &str) -> bool {
|
||||
id == "antigravity-acp"
|
||||
}
|
||||
|
||||
fn uses_package_runner(command: &str) -> bool {
|
||||
matches!(command, "npx" | "bunx" | "uvx")
|
||||
}
|
||||
@@ -610,20 +632,21 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
AgentProvider {
|
||||
id: spec.id.clone(),
|
||||
name: spec.name.clone(),
|
||||
command: std::iter::once(spec.command.as_str())
|
||||
command: std::iter::once(spec.executable())
|
||||
.chain(spec.args.iter().map(String::as_str))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" "),
|
||||
program: spec.command.clone(),
|
||||
program: spec.executable().to_owned(),
|
||||
args: spec.args.clone(),
|
||||
additional_args,
|
||||
default_program: builtin.as_ref().map(|b| b.command.clone()),
|
||||
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
|
||||
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))),
|
||||
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(spec.executable(), &spec.env))),
|
||||
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
installed: installed_with_env(spec.executable(), &spec.env),
|
||||
cli_install_command: None,
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
@@ -747,6 +770,20 @@ fn update_builtin(
|
||||
agent.write_with(&file, id, secrets)
|
||||
}
|
||||
|
||||
/// Project backends can share a config directory. Keep the ID check, credential
|
||||
/// changes and file write in the same critical section.
|
||||
fn lock_custom_agents(custom_dir: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::create_dir_all(custom_dir)?;
|
||||
let lock = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(custom_dir.join(".custom-agents.lock"))?;
|
||||
lock.lock()?;
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
/// Saves a new custom agent; refuses built-in and ACP Registry ids, taken ids
|
||||
/// and an empty command. The id is also the agent file's name, so it must be
|
||||
/// a safe file stem.
|
||||
@@ -762,6 +799,7 @@ pub(crate) fn save_custom(
|
||||
if input.command.trim().is_empty() {
|
||||
return Err(IdeError::invalid("the agent command must not be empty"));
|
||||
}
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
if file.try_exists()? {
|
||||
if CustomAgent::read(&file).is_ok_and(|a| a.registry.is_some()) {
|
||||
@@ -790,6 +828,7 @@ pub(crate) fn remove_custom(custom_dir: &Path, secrets: Option<&dyn EnvSecrets>,
|
||||
if builtin_spec(id).is_some() {
|
||||
return Err(IdeError::invalid(format!("{id} is a built-in agent and cannot be removed")));
|
||||
}
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let file = custom_dir.join(format!("{id}.toml"));
|
||||
let agent =
|
||||
CustomAgent::read(&file).map_err(|_| IdeError::not_found(format!("there is no custom agent '{id}'")))?;
|
||||
@@ -829,6 +868,7 @@ pub(crate) fn import_acp(
|
||||
}
|
||||
let parsed: AcpJson =
|
||||
serde_json::from_str(text).map_err(|e| IdeError::invalid(format!("not an acp.json file: {e}")))?;
|
||||
let _lock = lock_custom_agents(custom_dir)?;
|
||||
let mut outcomes = Vec::with_capacity(parsed.agent_servers.len());
|
||||
for (name, server) in parsed.agent_servers {
|
||||
let id = slugify_id(&name);
|
||||
@@ -1024,6 +1064,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
name: agent.name.unwrap_or_else(|| id.clone()),
|
||||
driver: agent.driver,
|
||||
command: agent.command,
|
||||
managed_cli: None,
|
||||
args: agent.args,
|
||||
additional_args_len: 0,
|
||||
env,
|
||||
@@ -1033,7 +1074,9 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
};
|
||||
match specs.iter_mut().find(|s| s.id == spec.id) {
|
||||
Some(existing) => {
|
||||
spec.login_hint = existing.login_hint.clone();
|
||||
if !(matches!(spec.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&spec.id)) {
|
||||
spec.login_hint = existing.login_hint.clone();
|
||||
}
|
||||
if !explicit_driver && existing.driver == Driver::Copilot && spec.driver == Driver::Acp {
|
||||
// Registry installs (`github-copilot-cli`) record `args = ["--acp"]` with no
|
||||
// `driver`; upgrade them in place to the native headless driver (which
|
||||
@@ -1057,19 +1100,23 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
specs
|
||||
}
|
||||
|
||||
/// Whether `command` resolves to an executable (a path, or a name on `PATH`).
|
||||
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn installed(command: &str) -> bool {
|
||||
installed_with_env(command, &[])
|
||||
}
|
||||
|
||||
pub(crate) fn installed_with_env(command: &str, env: &[(String, String)]) -> bool {
|
||||
let p = Path::new(command);
|
||||
if p.components().count() > 1 {
|
||||
if p.components().count() > 1 || p.is_absolute() {
|
||||
return is_executable(p);
|
||||
}
|
||||
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[] };
|
||||
std::env::var_os("PATH").is_some_and(|path| {
|
||||
std::env::split_paths(&path).any(|dir| {
|
||||
let c = dir.join(command);
|
||||
is_executable(&c) || exts.iter().any(|e| is_executable(&c.with_extension(e)))
|
||||
})
|
||||
})
|
||||
if let Some((_, path)) = env.iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
&& ide_core::process::find_executable(command, std::ffi::OsStr::new(path)).is_some()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
|
||||
}
|
||||
|
||||
fn is_executable(p: &Path) -> bool {
|
||||
@@ -1098,6 +1145,55 @@ mod tests {
|
||||
assert_eq!(info.login_hint.as_deref(), Some("Run `hermes model` in a terminal."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn antigravity_is_built_in_over_acp() {
|
||||
let spec = builtin_spec("antigravity-acp").unwrap();
|
||||
assert_eq!(spec.driver, Driver::Acp);
|
||||
assert!(!is_builtin("antigravity-acp"));
|
||||
let info = describe(&spec);
|
||||
assert_eq!((info.name.as_str(), info.command.as_str()), ("Google Antigravity", "agy acp"));
|
||||
assert_eq!(info.login_hint.as_deref(), Some("Run `agy acp --login` in a terminal."));
|
||||
assert!(info.command_editable);
|
||||
assert_eq!(info.additional_args, Some(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_antigravity_does_not_inherit_cli_login_subcommand() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let bin = dir.path().join(if cfg!(windows) { "agy_acp_server.exe" } else { "agy_acp_server.par" });
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
CustomAgent {
|
||||
name: Some("Google Antigravity".into()),
|
||||
driver: Driver::Acp,
|
||||
command: bin.to_string_lossy().into_owned(),
|
||||
args: Vec::new(),
|
||||
additional_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
registry: Some(RegistryRef { id: "antigravity-acp".into(), version: "1.5.2".into() }),
|
||||
}
|
||||
.write(&dir.path().join("antigravity-acp.toml"))
|
||||
.unwrap();
|
||||
|
||||
let reg = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
|
||||
assert_eq!(reg.source, AgentSource::Registry { version: "1.5.2".into(), update: None });
|
||||
assert_eq!(reg.login_hint, "Sign in with the agent's own command line first.");
|
||||
assert_eq!(describe(®).login_hint.as_deref(), Some("Sign in with the agent's own command line first."));
|
||||
assert!(reg.login_launch(dir.path(), None).is_none());
|
||||
let terminal_launch = reg.login_launch(dir.path(), Some(&["--login".into()])).unwrap();
|
||||
assert_eq!(terminal_launch.program, bin);
|
||||
assert_eq!(terminal_launch.args, ["--login"]);
|
||||
|
||||
std::fs::remove_file(dir.path().join("antigravity-acp.toml")).unwrap();
|
||||
let builtin = load(Some(dir.path()), None).into_iter().find(|s| s.id == "antigravity-acp").unwrap();
|
||||
assert_eq!(builtin.source, AgentSource::Builtin);
|
||||
assert_eq!((builtin.command.as_str(), builtin.args.as_slice()), ("agy", &["acp".to_owned()][..]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qoder_global_and_cn_editions_are_both_built_in() {
|
||||
let info = |id: &str| describe(&load(None, None).into_iter().find(|s| s.id == id).unwrap());
|
||||
@@ -1150,6 +1246,7 @@ mod tests {
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert_eq!(args("antigravity-acp"), ["acp", "--login"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
@@ -1224,7 +1321,7 @@ mod tests {
|
||||
(true, "& '/agent''s tools/$cli' auth login --account 'user name' 'a''b' '$token' ''"),
|
||||
] {
|
||||
assert_eq!(
|
||||
render_login_command(
|
||||
render_shell_command(
|
||||
Path::new("/agent's tools/$cli"),
|
||||
["auth", "login", "--account", "user name", "a'b", "$token", ""],
|
||||
windows
|
||||
@@ -1276,10 +1373,10 @@ mod tests {
|
||||
for p in &defaults {
|
||||
assert_eq!(p.source, AgentSource::Builtin);
|
||||
assert!(p.default_program.is_some());
|
||||
assert_eq!(p.command_editable, !p.id.ends_with("-acp"));
|
||||
assert_eq!(p.command_editable, !uses_package_runner(&p.program));
|
||||
assert_eq!(
|
||||
p.command_read_only_reason,
|
||||
p.id.ends_with("-acp").then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
uses_package_runner(&p.program).then_some(AgentCommandReadOnlyReason::PackageRunner)
|
||||
);
|
||||
}
|
||||
set_builtin_command(dir.path(), None, "codex", Some("/path with spaces/codex")).unwrap();
|
||||
@@ -1326,6 +1423,22 @@ mod tests {
|
||||
assert!(installed("sh"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_with_env_resolves_executables_on_provider_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let name = if cfg!(windows) { "fake-agent.cmd" } else { "fake-agent" };
|
||||
let exe = dir.path().join(name);
|
||||
std::fs::write(&exe, "").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert!(!installed("fake-agent"));
|
||||
let env = vec![("PATH".to_owned(), dir.path().to_string_lossy().into_owned())];
|
||||
assert!(installed_with_env("fake-agent", &env));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_builtin_env_writes_and_clears_the_environment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -320,7 +320,7 @@ fn is_builtin(id: &str) -> bool {
|
||||
}
|
||||
|
||||
fn on_path(command: &str) -> bool {
|
||||
which::which(command).is_ok()
|
||||
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
|
||||
}
|
||||
|
||||
/// `1.10.0` > `1.9.2`; a release is newer than its pre-releases.
|
||||
@@ -708,7 +708,8 @@ fn install_npm(
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
let npm = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path())
|
||||
.ok_or_else(|| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
@@ -789,7 +790,8 @@ fn install_uv(
|
||||
_ => format!("{name}=={}", entry.version),
|
||||
};
|
||||
check_spec(&spec)?;
|
||||
let uv = which::which("uv").map_err(|_| IdeError::unavailable(format!("uv is required to install {name}")))?;
|
||||
let uv = ide_core::process::find_executable("uv", &ide_core::tool_path::search_path())
|
||||
.ok_or_else(|| IdeError::unavailable(format!("uv is required to install {name}")))?;
|
||||
let bin = dir.join("bin");
|
||||
let mut cmd = Command::new(uv);
|
||||
cmd.args(["tool", "install", "--force"])
|
||||
|
||||
@@ -185,22 +185,7 @@ pub(crate) fn recorder(out: PathBuf) -> Connector {
|
||||
let file = Arc::new(Mutex::new(String::new()));
|
||||
let connections = Arc::new(Mutex::new(0u32));
|
||||
Arc::new(move |spec, cwd, client, on_stderr| {
|
||||
let program = {
|
||||
let path = Path::new(&spec.command);
|
||||
if path.components().count() > 1 || path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
let search = spec
|
||||
.env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
ide_core::process::find_executable(&spec.command, &search).unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
};
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env);
|
||||
let mut cmd = tokio::process::Command::new(&program);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
let mut child = cmd
|
||||
|
||||
@@ -22,6 +22,7 @@ fn paths(dir: &Path) -> AgentPaths {
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
|
||||
@@ -163,6 +163,15 @@ pub struct RepoRef<'a> {
|
||||
|
||||
pub trait SkillSourceFetcher: Send + Sync {
|
||||
fn default_branch(&self, owner: &str, repo: &str, cancel: &CancellationToken) -> IdeResult<String>;
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String>;
|
||||
/// The root tree SHA recorded in commit `commit_sha`.
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
commit_sha: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String>;
|
||||
fn git_tree(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<GitTree>;
|
||||
fn read_blob(
|
||||
&self,
|
||||
@@ -238,6 +247,63 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
|
||||
.map_err(|e| IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid Git tree: {e}")))
|
||||
}
|
||||
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct CommitMeta {
|
||||
sha: String,
|
||||
}
|
||||
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
validate_git_ref(git_ref)?;
|
||||
let encoded_ref = encode_url_segment(git_ref);
|
||||
let url = format!("https://api.github.com/repos/{owner}/{repo}/commits/{encoded_ref}");
|
||||
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
|
||||
let meta: CommitMeta = serde_json::from_str(&body).map_err(|e| {
|
||||
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid GitHub commit: {e}"))
|
||||
})?;
|
||||
if !is_git_object_id(&meta.sha) {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Protocol,
|
||||
format!("{owner}/{repo}@{git_ref}: invalid GitHub commit SHA"),
|
||||
));
|
||||
}
|
||||
Ok(meta.sha)
|
||||
}
|
||||
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
commit_sha: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct TreeRef {
|
||||
sha: String,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct GitCommit {
|
||||
tree: TreeRef,
|
||||
}
|
||||
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
if !is_git_object_id(commit_sha) {
|
||||
return Err(IdeError::invalid("Invalid commit SHA"));
|
||||
}
|
||||
let url = format!("https://api.github.com/repos/{owner}/{repo}/git/commits/{commit_sha}");
|
||||
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
|
||||
let commit: GitCommit = serde_json::from_str(&body).map_err(|e| {
|
||||
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid Git commit: {e}"))
|
||||
})?;
|
||||
if !is_git_object_id(&commit.tree.sha) {
|
||||
return Err(IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid tree SHA")));
|
||||
}
|
||||
Ok(commit.tree.sha)
|
||||
}
|
||||
|
||||
fn read_blob(
|
||||
&self,
|
||||
target: RepoRef<'_>,
|
||||
@@ -616,6 +682,17 @@ fn sanitize_repo_as_skill_name(repo: &str) -> String {
|
||||
out.trim_matches('-').to_owned()
|
||||
}
|
||||
|
||||
pub(crate) struct FetchedSubtree {
|
||||
pub tree_sha: String,
|
||||
pub normalized_subpath: String,
|
||||
pub files: Vec<RemoteSkillFile>,
|
||||
pub scan_warnings: Vec<SkillScanWarning>,
|
||||
/// `(relative_path, bytes, executable)` for safe non-symlink files to write on disk.
|
||||
pub regular_files: Vec<(PathBuf, Vec<u8>, bool)>,
|
||||
/// `(relative_path, relative_target)` for safe internal symlinks.
|
||||
pub in_root_symlinks: Vec<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
struct PreparedSkillBundle {
|
||||
tree_sha: String,
|
||||
skill_name: String,
|
||||
@@ -629,14 +706,19 @@ struct PreparedSkillBundle {
|
||||
in_root_symlinks: Vec<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
|
||||
fn fetch_and_scan_bundle(
|
||||
/// Fetches `target`'s tree (or exactly `pinned_tree_sha` when set) and scans `subpath` with hardened
|
||||
/// symlink-graph, executable-script, and hidden-Unicode checks.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn fetch_and_scan_subtree(
|
||||
fetcher: &dyn SkillSourceFetcher,
|
||||
target: RepoRef<'_>,
|
||||
subpath: &str,
|
||||
pinned_tree_sha: Option<&str>,
|
||||
max_files: usize,
|
||||
max_subtree_bytes: u64,
|
||||
noun: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PreparedSkillBundle> {
|
||||
) -> IdeResult<FetchedSubtree> {
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
@@ -646,9 +728,8 @@ fn fetch_and_scan_bundle(
|
||||
let tree = match pinned_tree_sha {
|
||||
Some(sha) => {
|
||||
if !is_git_object_id(sha) {
|
||||
return Err(IdeError::invalid("Preview the skill again before installing it"));
|
||||
return Err(IdeError::invalid(format!("Preview the {noun} again before installing it")));
|
||||
}
|
||||
// The Git trees API accepts a tree SHA in place of a ref.
|
||||
let tree = fetcher.git_tree(RepoRef { owner, repo, git_ref: sha }, cancel)?;
|
||||
if !tree.sha.eq_ignore_ascii_case(sha) {
|
||||
return Err(IdeError::new(
|
||||
@@ -660,6 +741,14 @@ fn fetch_and_scan_bundle(
|
||||
}
|
||||
None => fetcher.git_tree(target, cancel)?,
|
||||
};
|
||||
if tree.truncated {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Protocol,
|
||||
format!(
|
||||
"{owner}/{repo}@{git_ref}: GitHub returned a truncated file listing; the {noun} cannot be verified"
|
||||
),
|
||||
));
|
||||
}
|
||||
let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") };
|
||||
|
||||
let subtree_entries: Vec<&GitTreeEntry> = tree
|
||||
@@ -672,27 +761,32 @@ fn fetch_and_scan_bundle(
|
||||
|
||||
if subtree_entries.is_empty() {
|
||||
return Err(IdeError::not_found(format!(
|
||||
"Skill path {:?} was not found in {owner}/{repo}@{git_ref}",
|
||||
"{} path {:?} was not found in {owner}/{repo}@{git_ref}",
|
||||
capitalize(noun),
|
||||
normalized_subpath
|
||||
)));
|
||||
}
|
||||
if subtree_entries.len() > MAX_SKILL_FILES {
|
||||
if subtree_entries.len() > max_files {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Skill exceeds maximum of {MAX_SKILL_FILES} files ({} found)",
|
||||
"{} exceeds maximum of {max_files} files ({} found)",
|
||||
capitalize(noun),
|
||||
subtree_entries.len()
|
||||
)));
|
||||
}
|
||||
|
||||
let declared_total: u64 = subtree_entries.iter().map(|e| e.size.unwrap_or(0)).sum();
|
||||
if declared_total > MAX_SKILL_SUBTREE_BYTES {
|
||||
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
|
||||
if declared_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
}
|
||||
|
||||
let mut files = Vec::with_capacity(subtree_entries.len());
|
||||
let mut scan_warnings = Vec::new();
|
||||
let mut regular_files = Vec::new();
|
||||
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
|
||||
let mut skill_markdown: Option<String> = None;
|
||||
let mut actual_total = 0u64;
|
||||
|
||||
for entry in subtree_entries {
|
||||
@@ -709,12 +803,16 @@ fn fetch_and_scan_bundle(
|
||||
target,
|
||||
&entry.path,
|
||||
&entry.sha,
|
||||
MAX_SINGLE_BLOB_BYTES.min(MAX_SKILL_SUBTREE_BYTES - actual_total),
|
||||
MAX_SINGLE_BLOB_BYTES.min(max_subtree_bytes - actual_total),
|
||||
cancel,
|
||||
)?;
|
||||
actual_total = actual_total.saturating_add(bytes.len() as u64);
|
||||
if actual_total > MAX_SKILL_SUBTREE_BYTES {
|
||||
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
|
||||
if actual_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
}
|
||||
|
||||
if is_symlink {
|
||||
@@ -748,11 +846,15 @@ fn fetch_and_scan_bundle(
|
||||
|
||||
if let Ok(text) = std::str::from_utf8(&bytes) {
|
||||
scan_hidden_unicode(rel_str, text, &mut scan_warnings);
|
||||
if rel_str == "SKILL.md" {
|
||||
skill_markdown = Some(text.to_owned());
|
||||
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
|
||||
for tool in frontmatter_shell_tools(text) {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: rel_str.to_owned(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if rel_str == "SKILL.md" {
|
||||
return Err(IdeError::invalid("SKILL.md is not valid UTF-8 text"));
|
||||
}
|
||||
|
||||
files.push(RemoteSkillFile {
|
||||
@@ -767,13 +869,12 @@ fn fetch_and_scan_bundle(
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
// Symlinks are judged together: one link may point through another, and an entry placed beneath
|
||||
// a symlink would be written wherever that link points.
|
||||
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
|
||||
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
|
||||
if let Some(link) = graph.symlink_ancestor(path) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Skill entry {:?} is inside symlink {link:?}; the repository tree is malformed",
|
||||
"{} entry {:?} is inside symlink {link:?}; the repository tree is malformed",
|
||||
capitalize(noun),
|
||||
path.display().to_string()
|
||||
)));
|
||||
}
|
||||
@@ -786,26 +887,65 @@ fn fetch_and_scan_bundle(
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::OutOfRootSymlink,
|
||||
file: rel_str,
|
||||
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
|
||||
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
in_root_symlinks.sort();
|
||||
|
||||
let Some(skill_markdown) = skill_markdown else {
|
||||
return Err(IdeError::invalid("Selected folder does not contain a regular SKILL.md file"));
|
||||
};
|
||||
Ok(FetchedSubtree { tree_sha: tree.sha, normalized_subpath, files, scan_warnings, regular_files, in_root_symlinks })
|
||||
}
|
||||
|
||||
let folder_hint = normalized_subpath
|
||||
fn capitalize(s: &str) -> String {
|
||||
let mut c = s.chars();
|
||||
match c.next() {
|
||||
None => String::new(),
|
||||
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
|
||||
fn fetch_and_scan_bundle(
|
||||
fetcher: &dyn SkillSourceFetcher,
|
||||
target: RepoRef<'_>,
|
||||
subpath: &str,
|
||||
pinned_tree_sha: Option<&str>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PreparedSkillBundle> {
|
||||
let RepoRef { repo, .. } = target;
|
||||
let mut sub = fetch_and_scan_subtree(
|
||||
fetcher,
|
||||
target,
|
||||
subpath,
|
||||
pinned_tree_sha,
|
||||
MAX_SKILL_FILES,
|
||||
MAX_SKILL_SUBTREE_BYTES,
|
||||
"skill",
|
||||
cancel,
|
||||
)?;
|
||||
|
||||
let skill_bytes = sub
|
||||
.regular_files
|
||||
.iter()
|
||||
.find(|(p, _, _)| p == Path::new("SKILL.md"))
|
||||
.map(|(_, b, _)| b.as_slice())
|
||||
.ok_or_else(|| IdeError::invalid("Selected folder does not contain a regular SKILL.md file"))?;
|
||||
let skill_markdown =
|
||||
std::str::from_utf8(skill_bytes).map_err(|_| IdeError::invalid("SKILL.md is not valid UTF-8 text"))?.to_owned();
|
||||
|
||||
let folder_hint = sub
|
||||
.normalized_subpath
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| sanitize_repo_as_skill_name(repo));
|
||||
|
||||
// Strip any `SKILL.md` shell-tool warnings already collected so `parse_skill_markdown_metadata` emits them in order.
|
||||
sub.scan_warnings.retain(|w| !(w.kind == SkillScanWarningKind::AllowedToolsShell && w.file == "SKILL.md"));
|
||||
let parsed_meta = parse_skill_markdown_metadata(&folder_hint, &skill_markdown)?;
|
||||
for tool in &parsed_meta.shell_tools {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
sub.scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: "SKILL.md".into(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
@@ -813,14 +953,14 @@ fn fetch_and_scan_bundle(
|
||||
}
|
||||
|
||||
Ok(PreparedSkillBundle {
|
||||
tree_sha: tree.sha,
|
||||
tree_sha: sub.tree_sha,
|
||||
skill_name: parsed_meta.name,
|
||||
description: parsed_meta.description,
|
||||
skill_markdown,
|
||||
files,
|
||||
scan_warnings,
|
||||
regular_files,
|
||||
in_root_symlinks,
|
||||
files: sub.files,
|
||||
scan_warnings: sub.scan_warnings,
|
||||
regular_files: sub.regular_files,
|
||||
in_root_symlinks: sub.in_root_symlinks,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1140,6 +1280,33 @@ fn create_parent_dirs_no_follow(root: &Path, rel: &Path) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates `target` below the existing `anchor` (the home or project folder) without following a
|
||||
/// symlink in any directory between them, the harness store root included.
|
||||
fn create_dirs_below_anchor(anchor: &Path, target: &Path) -> IdeResult<()> {
|
||||
if !anchor.is_dir() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", anchor.display())));
|
||||
}
|
||||
let rel = target
|
||||
.strip_prefix(anchor)
|
||||
.map_err(|_| IdeError::invalid(format!("{} is outside {}", target.display(), anchor.display())))?;
|
||||
let mut dir = anchor.to_path_buf();
|
||||
for component in rel.components() {
|
||||
if !matches!(component, Component::Normal(_)) {
|
||||
return Err(IdeError::invalid(format!("{} is not a plain path below the store", target.display())));
|
||||
}
|
||||
dir.push(component);
|
||||
match std::fs::symlink_metadata(&dir) {
|
||||
Ok(meta) if meta.is_dir() => {}
|
||||
Ok(_) => {
|
||||
return Err(IdeError::invalid(format!("{} passes through a symlink or file", dir.display())));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => std::fs::create_dir(&dir)?,
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the symlink at `link` resolves strictly inside `root` (canonical), following links on disk.
|
||||
/// Components that do not exist are resolved lexically.
|
||||
#[cfg(unix)]
|
||||
@@ -1220,15 +1387,16 @@ pub fn install_skill(
|
||||
workspace_root: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let target_root = match req.scope {
|
||||
// Anchored at the home or project folder: nothing below it may be a symlink, store included.
|
||||
let (anchor, target_root) = match req.scope {
|
||||
McpScope::User => {
|
||||
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
|
||||
home.join(".agents").join("skills")
|
||||
(home.to_path_buf(), home.join(".agents").join("skills"))
|
||||
}
|
||||
McpScope::Workspace => {
|
||||
let ws = workspace_root
|
||||
.ok_or_else(|| IdeError::invalid("Open a trusted project to install workspace skills"))?;
|
||||
ws.join(".agents").join("skills")
|
||||
(ws.to_path_buf(), ws.join(".agents").join("skills"))
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1245,20 +1413,60 @@ pub fn install_skill(
|
||||
));
|
||||
}
|
||||
|
||||
std::fs::create_dir_all(&target_root)?;
|
||||
let final_dir = target_root.join(&bundle.skill_name);
|
||||
if final_dir.exists() && !req.overwrite {
|
||||
write_staged_subtree(
|
||||
&anchor,
|
||||
&target_root,
|
||||
&bundle.skill_name,
|
||||
req.overwrite,
|
||||
"Skill",
|
||||
&bundle.regular_files,
|
||||
&bundle.in_root_symlinks,
|
||||
&[],
|
||||
)
|
||||
}
|
||||
|
||||
/// Atomically writes `regular_files`, `in_root_symlinks`, and `extra_files` into a staging folder
|
||||
/// under `target_root`, verifies created symlinks stay inside the folder, and swaps into `<target_root>/<folder_name>`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn write_staged_subtree(
|
||||
anchor: &Path,
|
||||
target_root: &Path,
|
||||
folder_name: &str,
|
||||
overwrite: bool,
|
||||
noun_cap: &str,
|
||||
regular_files: &[(PathBuf, Vec<u8>, bool)],
|
||||
in_root_symlinks: &[(PathBuf, PathBuf)],
|
||||
extra_files: &[(&str, &[u8])],
|
||||
) -> IdeResult<PathBuf> {
|
||||
create_dirs_below_anchor(anchor, target_root)?;
|
||||
if folder_name.is_empty() || !Path::new(folder_name).components().all(|c| matches!(c, Component::Normal(_))) {
|
||||
return Err(IdeError::invalid(format!("Invalid {} folder name", noun_cap.to_ascii_lowercase())));
|
||||
}
|
||||
let final_dir = target_root.join(folder_name);
|
||||
let existing = match std::fs::symlink_metadata(&final_dir) {
|
||||
Ok(meta) if meta.is_dir() => true,
|
||||
Ok(_) => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is a symlink or file, not a {} folder",
|
||||
final_dir.display(),
|
||||
noun_cap.to_ascii_lowercase()
|
||||
)));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
if existing && !overwrite {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::AlreadyExists,
|
||||
format!("Skill `{}` is already installed in {}", bundle.skill_name, target_root.display()),
|
||||
format!("{noun_cap} `{folder_name}` is already installed in {}", target_root.display()),
|
||||
));
|
||||
}
|
||||
|
||||
let nonce = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
|
||||
let staging = target_root.join(format!(".staging-{}-{nonce}-{}", bundle.skill_name, std::process::id()));
|
||||
let staging = target_root.join(format!(".staging-{folder_name}-{nonce}-{}", std::process::id()));
|
||||
let write_res = (|| -> IdeResult<()> {
|
||||
std::fs::create_dir_all(&staging)?;
|
||||
for (rel_path, bytes, is_exec) in &bundle.regular_files {
|
||||
for (rel_path, bytes, is_exec) in regular_files {
|
||||
create_parent_dirs_no_follow(&staging, rel_path)?;
|
||||
let dest = staging.join(rel_path);
|
||||
std::fs::write(&dest, bytes)?;
|
||||
@@ -1270,7 +1478,12 @@ pub fn install_skill(
|
||||
#[cfg(not(unix))]
|
||||
let _ = is_exec;
|
||||
}
|
||||
for (rel_link, target) in &bundle.in_root_symlinks {
|
||||
for (rel_str, bytes) in extra_files {
|
||||
let rel_path = validate_rel_skill_file(rel_str)?;
|
||||
create_parent_dirs_no_follow(&staging, &rel_path)?;
|
||||
std::fs::write(staging.join(&rel_path), bytes)?;
|
||||
}
|
||||
for (rel_link, target) in in_root_symlinks {
|
||||
create_parent_dirs_no_follow(&staging, rel_link)?;
|
||||
let dest = staging.join(rel_link);
|
||||
#[cfg(unix)]
|
||||
@@ -1288,17 +1501,18 @@ pub fn install_skill(
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let root = std::fs::canonicalize(&staging)?;
|
||||
for (rel_link, _) in &bundle.in_root_symlinks {
|
||||
for (rel_link, _) in in_root_symlinks {
|
||||
if !link_resolves_inside(&root, &staging.join(rel_link)) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Symlink {:?} leaves the skill folder",
|
||||
rel_link.display().to_string()
|
||||
"Symlink {:?} leaves the {} folder",
|
||||
rel_link.display().to_string(),
|
||||
noun_cap.to_ascii_lowercase()
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let backup = if final_dir.exists() {
|
||||
let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name));
|
||||
let backup = if existing {
|
||||
let bak = target_root.join(format!(".old-{folder_name}-{nonce}"));
|
||||
std::fs::rename(&final_dir, &bak)?;
|
||||
Some(bak)
|
||||
} else {
|
||||
@@ -1323,6 +1537,179 @@ pub fn install_skill(
|
||||
Ok(final_dir)
|
||||
}
|
||||
|
||||
/// Scans a local directory on disk with the same symlink-graph, executable-script, and hidden-Unicode
|
||||
/// checks used for remote GitHub subtrees.
|
||||
/// Content digest of a scanned local folder, used to pin a local preview to its install.
|
||||
fn local_subtree_digest(regular_files: &[(PathBuf, Vec<u8>, bool)], symlinks: &[(PathBuf, PathBuf)]) -> String {
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher.update(b"openidea-local-subtree-v1\0");
|
||||
for (path, bytes, executable) in regular_files {
|
||||
hasher.update(b"f\0");
|
||||
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(&[0, u8::from(*executable)]);
|
||||
hasher.update(&(bytes.len() as u64).to_le_bytes());
|
||||
hasher.update(bytes);
|
||||
}
|
||||
for (path, target) in symlinks {
|
||||
hasher.update(b"l\0");
|
||||
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(b"\0");
|
||||
hasher.update(target.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(b"\0");
|
||||
}
|
||||
format!("local-blake3:{}", hasher.finalize().to_hex())
|
||||
}
|
||||
|
||||
pub(crate) fn scan_local_subtree(
|
||||
dir: &Path,
|
||||
max_files: usize,
|
||||
max_subtree_bytes: u64,
|
||||
noun: &str,
|
||||
) -> IdeResult<FetchedSubtree> {
|
||||
if !dir.is_dir() {
|
||||
return Err(IdeError::not_found(format!("Directory {} does not exist", dir.display())));
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
let mut scan_warnings = Vec::new();
|
||||
let mut regular_files = Vec::new();
|
||||
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
|
||||
let mut actual_total = 0u64;
|
||||
|
||||
let mut stack = vec![(dir.to_path_buf(), String::new())];
|
||||
while let Some((cur_dir, rel_prefix)) = stack.pop() {
|
||||
let mut entries: Vec<_> = std::fs::read_dir(&cur_dir)?.filter_map(Result::ok).collect();
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let name = entry.file_name();
|
||||
let Some(name_str) = name.to_str() else {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} contains a file name that is not valid UTF-8: {}",
|
||||
capitalize(noun),
|
||||
entry.path().display()
|
||||
)));
|
||||
};
|
||||
if name_str == ".git" || name_str == "node_modules" || name_str == "target" {
|
||||
continue;
|
||||
}
|
||||
let rel_str = if rel_prefix.is_empty() { name_str.to_owned() } else { format!("{rel_prefix}/{name_str}") };
|
||||
let rel_path = validate_rel_skill_file(&rel_str)?;
|
||||
let full = entry.path();
|
||||
let meta = std::fs::symlink_metadata(&full)?;
|
||||
if (meta.file_type().is_symlink() || meta.file_type().is_file())
|
||||
&& regular_files.len() + symlinks.len() >= max_files
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{} exceeds maximum of {max_files} files", capitalize(noun))));
|
||||
}
|
||||
if meta.file_type().is_symlink() {
|
||||
let target_raw = std::fs::read_link(&full)?.to_string_lossy().replace('\\', "/");
|
||||
symlinks.push((rel_path, rel_str.clone(), target_raw));
|
||||
files.push(RemoteSkillFile { path: rel_str, size: 0, executable: false, symlink: true });
|
||||
continue;
|
||||
}
|
||||
if meta.file_type().is_dir() {
|
||||
stack.push((full, rel_str));
|
||||
continue;
|
||||
}
|
||||
if !meta.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
if meta.len() > MAX_SINGLE_BLOB_BYTES {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"File {rel_str:?} exceeds {} MiB size cap",
|
||||
MAX_SINGLE_BLOB_BYTES >> 20
|
||||
)));
|
||||
}
|
||||
let bytes = std::fs::read(&full)?;
|
||||
actual_total = actual_total.saturating_add(bytes.len() as u64);
|
||||
if actual_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let is_exec_mode = {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
meta.permissions().mode() & 0o111 != 0
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let is_exec_mode = false;
|
||||
let has_shebang = bytes.starts_with(b"#!");
|
||||
let is_script_path = is_executable_or_script_path(&rel_path);
|
||||
if is_exec_mode || has_shebang || is_script_path {
|
||||
let reason = if is_exec_mode {
|
||||
"executable file mode"
|
||||
} else if has_shebang {
|
||||
"script with `#!` interpreter header"
|
||||
} else {
|
||||
"bundled script or native binary"
|
||||
};
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::ExecutableScript,
|
||||
file: rel_str.clone(),
|
||||
message: format!("Contains {reason}"),
|
||||
});
|
||||
}
|
||||
if let Ok(text) = std::str::from_utf8(&bytes) {
|
||||
scan_hidden_unicode(&rel_str, text, &mut scan_warnings);
|
||||
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
|
||||
for tool in frontmatter_shell_tools(text) {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: rel_str.clone(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
files.push(RemoteSkillFile {
|
||||
path: rel_str,
|
||||
size: bytes.len() as u64,
|
||||
executable: is_exec_mode || has_shebang,
|
||||
symlink: false,
|
||||
});
|
||||
regular_files.push((rel_path, bytes, is_exec_mode));
|
||||
}
|
||||
}
|
||||
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
|
||||
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
|
||||
if let Some(link) = graph.symlink_ancestor(path) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} entry {:?} is inside symlink {link:?}",
|
||||
capitalize(noun),
|
||||
path.display().to_string()
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut in_root_symlinks = Vec::new();
|
||||
for (rel_path, rel_str, target_raw) in symlinks {
|
||||
if graph.stays_inside(&rel_path, &target_raw) {
|
||||
in_root_symlinks.push((rel_path, PathBuf::from(target_raw)));
|
||||
} else {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::OutOfRootSymlink,
|
||||
file: rel_str,
|
||||
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
in_root_symlinks.sort();
|
||||
|
||||
Ok(FetchedSubtree {
|
||||
tree_sha: local_subtree_digest(®ular_files, &in_root_symlinks),
|
||||
normalized_subpath: String::new(),
|
||||
files,
|
||||
scan_warnings,
|
||||
regular_files,
|
||||
in_root_symlinks,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1374,6 +1761,25 @@ mod tests {
|
||||
.cloned()
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
|
||||
}
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, _cancel: &CancellationToken) -> IdeResult<String> {
|
||||
self.trees
|
||||
.get(target.git_ref)
|
||||
.map(|_| git_blob_id(format!("commit:{}", target.git_ref).as_bytes()))
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
|
||||
}
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
_owner: &str,
|
||||
_repo: &str,
|
||||
commit_sha: &str,
|
||||
_cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
self.trees
|
||||
.iter()
|
||||
.find(|(git_ref, _)| git_blob_id(format!("commit:{git_ref}").as_bytes()) == commit_sha)
|
||||
.map(|(_, tree)| tree.sha.clone())
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown commit {commit_sha}")))
|
||||
}
|
||||
|
||||
fn read_blob(
|
||||
&self,
|
||||
@@ -1440,7 +1846,9 @@ mod tests {
|
||||
let cancel = CancellationToken::new();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
std::fs::create_dir_all(&ws).unwrap();
|
||||
|
||||
// Bare `owner/repo` lists both skills; `owner/repo@clean-skill` falls back from ref lookup to skill filter!
|
||||
let all = browse_skills(&fetcher, "acme/skills", &cancel).unwrap();
|
||||
@@ -1796,4 +2204,66 @@ mod tests {
|
||||
.unwrap();
|
||||
assert!(dest.join("SKILL.md").is_file());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn local_scan_counts_symlinks_toward_the_file_cap() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::write(tmp.path().join("SKILL.md"), "x").unwrap();
|
||||
for i in 0..3 {
|
||||
std::os::unix::fs::symlink("SKILL.md", tmp.path().join(format!("link-{i}"))).unwrap();
|
||||
}
|
||||
let Err(err) = scan_local_subtree(tmp.path(), 3, 1 << 20, "plugin") else { panic!("symlinks must count") };
|
||||
assert!(err.to_string().contains("maximum of 3 files"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_tree_listings_are_rejected() {
|
||||
let mut fetcher = FakeFetcher::new();
|
||||
fetcher.add_tree("main", vec![("skills/a/SKILL.md", "100644", b"---\nname: a\ndescription: a\n---\n")]);
|
||||
fetcher.trees.get_mut("main").unwrap().truncated = true;
|
||||
let cancel = CancellationToken::new();
|
||||
let target = RepoRef { owner: "o", repo: "r", git_ref: "main" };
|
||||
let Err(err) = fetch_and_scan_subtree(&fetcher, target, "skills/a", None, 10, 1 << 20, "skill", &cancel) else {
|
||||
panic!("a truncated listing cannot be verified")
|
||||
};
|
||||
assert!(err.to_string().contains("truncated"), "{err}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn staged_installs_do_not_follow_symlinks_below_the_store() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let store = tmp.path().join("store");
|
||||
let outside = tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&store).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, store.join("mkt")).unwrap();
|
||||
let files = vec![(PathBuf::from("plugin.json"), b"{}".to_vec(), false)];
|
||||
let Err(err) = write_staged_subtree(&store, &store.join("mkt"), "plugin", false, "Plugin", &files, &[], &[])
|
||||
else {
|
||||
panic!("a symlinked marketplace folder must not be written through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the store");
|
||||
|
||||
// The store root itself (`<home>/.claude/plugins` → elsewhere) is checked as well.
|
||||
let home = tmp.path().join("home");
|
||||
std::fs::create_dir_all(home.join(".claude")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, home.join(".claude/plugins")).unwrap();
|
||||
let store_root = home.join(".claude/plugins/cache/mkt");
|
||||
let Err(err) = write_staged_subtree(&home, &store_root, "plugin", false, "Plugin", &files, &[], &[]) else {
|
||||
panic!("a symlinked store root must not be written through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
assert!(std::fs::read_dir(&outside).unwrap().next().is_none());
|
||||
|
||||
std::fs::create_dir_all(store.join("real")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, store.join("real/plugin")).unwrap();
|
||||
let Err(err) = write_staged_subtree(&store, &store.join("real"), "plugin", true, "Plugin", &files, &[], &[])
|
||||
else {
|
||||
panic!("an existing symlinked plugin folder must not be replaced through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
}
|
||||
}
|
||||
@@ -275,12 +275,45 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Ag
|
||||
}
|
||||
|
||||
/// [`discover_skills_in`] plus the `<dir>` skill folders contributed by enabled OpenIDEA
|
||||
/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name
|
||||
/// clash; a plugin skill is never silently renamed.
|
||||
/// plugins (`[[contributes.skills]]`) and unified agent plugin bundles (`plugins.rs`).
|
||||
/// Workspace and user skills take precedence on a name clash; a plugin skill is never silently renamed.
|
||||
pub fn discover_skills_with_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
) -> Vec<AgentSkill> {
|
||||
let default_policy = crate::plugins::PluginsPolicy { workspace_roots: workspaces.to_vec(), ..Default::default() };
|
||||
let states =
|
||||
crate::plugins::resolve_plugins(crate::plugins::discover_plugins(workspaces, home), &default_policy, None);
|
||||
let projected = crate::plugins::projected_skill_roots(&states, None);
|
||||
discover_skills_with_agent_plugins(workspaces, home, plugin_skill_dirs, &projected)
|
||||
}
|
||||
|
||||
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
|
||||
/// and resolved agent plugin bundle roots (`agent_plugin_roots`).
|
||||
pub fn discover_skills_with_agent_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
) -> Vec<AgentSkill> {
|
||||
discover_skills_with_indexed_files(workspaces, home, plugin_skill_dirs, agent_plugin_roots, &[])
|
||||
}
|
||||
|
||||
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
|
||||
/// resolved agent plugin bundle roots (`agent_plugin_roots`), and deeply nested workspace packages
|
||||
/// inferred from `indexed_skill_files` (typically `ProjectIndex::files_with_names(&["SKILL.md"])`).
|
||||
///
|
||||
/// Direct workspace roots and shallow monorepo packages (depth 1–2) are scanned directly on disk
|
||||
/// first so discovery works before indexing finishes and preserves shallow-over-deep precedence.
|
||||
/// Any deeper package roots discovered via `indexed_skill_files` are scanned next, sorted from
|
||||
/// shallowest to deepest and deduplicated by canonical path.
|
||||
pub fn discover_skills_with_indexed_files(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
indexed_skill_files: &[PathBuf],
|
||||
) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
|
||||
@@ -306,6 +339,13 @@ pub fn discover_skills_with_plugins(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Deeply nested packages (arbitrary depth) surfaced by the project file index.
|
||||
for sub in indexed_package_roots(&all_workspaces, indexed_skill_files) {
|
||||
let sub_canon = dunce::canonicalize(&sub).unwrap_or_else(|_| sub.clone());
|
||||
if seen_workspaces.insert(sub_canon) {
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (sub.join(rel), *source)));
|
||||
}
|
||||
}
|
||||
if let Some(home) = home {
|
||||
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
|
||||
}
|
||||
@@ -338,9 +378,19 @@ pub fn discover_skills_with_plugins(
|
||||
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
|
||||
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
|
||||
}
|
||||
if let Some(home) = home {
|
||||
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
|
||||
for skill in skills_of(&root, source) {
|
||||
for proj in agent_plugin_roots {
|
||||
if proj.dir.join("SKILL.md").is_file() && proj.dir.file_name().and_then(|s| s.to_str()) != Some("skills") {
|
||||
let Some(folder) = file_name(&proj.dir) else { continue };
|
||||
if let Ok(text) = std::fs::read_to_string(proj.dir.join("SKILL.md")) {
|
||||
let mut skill = parse_skill_file(&proj.dir, &folder, &text, proj.source);
|
||||
skill.plugin_id = Some(proj.plugin_id.clone());
|
||||
skill.plugin_name = Some(proj.plugin_name.clone());
|
||||
push_skill(skill);
|
||||
}
|
||||
} else {
|
||||
for mut skill in skills_of(&proj.dir, proj.source) {
|
||||
skill.plugin_id = Some(proj.plugin_id.clone());
|
||||
skill.plugin_name = Some(proj.plugin_name.clone());
|
||||
push_skill(skill);
|
||||
}
|
||||
}
|
||||
@@ -388,81 +438,72 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Discovers skill roots inside `~/.copilot/installed-plugins`, supporting both Copilot CLI's
|
||||
/// 2-level `<marketplace-or-_direct>/<plugin>` layout (and `config.json` `installedPlugins`
|
||||
/// enablement) and flat 1-level `<plugin>` folders.
|
||||
fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkillSource)> {
|
||||
let mut disabled_paths: HashSet<PathBuf> = HashSet::new();
|
||||
let mut plugin_dirs: Vec<PathBuf> = Vec::new();
|
||||
let mut seen_dirs: HashSet<PathBuf> = HashSet::new();
|
||||
let mut push_plugin = |dir: PathBuf, disabled: &HashSet<PathBuf>| {
|
||||
if !dir.is_dir() {
|
||||
return;
|
||||
}
|
||||
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
||||
if disabled.contains(&canon) || !seen_dirs.insert(canon) {
|
||||
return;
|
||||
}
|
||||
plugin_dirs.push(dir);
|
||||
};
|
||||
|
||||
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
|
||||
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
|
||||
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
|
||||
{
|
||||
for entry in installed {
|
||||
let Some(raw_cache) = entry.get("cache_path").and_then(serde_json::Value::as_str).map(str::trim) else {
|
||||
continue;
|
||||
};
|
||||
if raw_cache.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let dir =
|
||||
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
|
||||
if entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(false) {
|
||||
disabled_paths.insert(dunce::canonicalize(&dir).unwrap_or(dir));
|
||||
} else {
|
||||
push_plugin(dir, &disabled_paths);
|
||||
}
|
||||
}
|
||||
/// Extracts workspace package roots from indexed `SKILL.md` file paths.
|
||||
///
|
||||
/// Only accepts `SKILL.md` files located inside one of [`WORKSPACE_ROOTS`] at depth 0, 1, or 2
|
||||
/// below `<dot_dir>/skills` (`skills/SKILL.md`, `skills/<name>/SKILL.md`, or
|
||||
/// `skills/<category>/<name>/SKILL.md`), rejecting unrelated fixture/doc `SKILL.md` files as well
|
||||
/// as packages under hidden directories or [`SKIP_MONOREPO_DIRS`]. Returns roots sorted from
|
||||
/// shallowest to deepest (then lexicographically) so shallower packages always win on name clashes.
|
||||
fn indexed_package_roots(workspaces: &[PathBuf], indexed_skill_files: &[PathBuf]) -> Vec<PathBuf> {
|
||||
if workspaces.is_empty() || indexed_skill_files.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let plugins_root = copilot_dir.join("installed-plugins");
|
||||
for entry in sorted(&plugins_root) {
|
||||
if !entry.is_dir() {
|
||||
let workspace_pairs: Vec<(&Path, Option<PathBuf>)> =
|
||||
workspaces.iter().map(|ws| (ws.as_path(), dunce::canonicalize(ws).ok())).collect();
|
||||
let mut candidates: Vec<(usize, PathBuf)> = Vec::new();
|
||||
for file in indexed_skill_files {
|
||||
let Some(pkg_root) = package_root_of_skill_file(file) else { continue };
|
||||
let Some(rel) = relative_within_workspaces(&pkg_root, &workspace_pairs) else { continue };
|
||||
if rel.components().any(|c| match c {
|
||||
std::path::Component::Normal(seg) => {
|
||||
seg.to_str().is_none_or(|s| s.starts_with('.') || SKIP_MONOREPO_DIRS.contains(&s))
|
||||
}
|
||||
_ => true,
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
if looks_like_plugin_dir(&entry) {
|
||||
push_plugin(entry, &disabled_paths);
|
||||
} else {
|
||||
// 2-level `<marketplace>/<plugin>` or `_direct/<plugin>`.
|
||||
for sub in sorted(&entry) {
|
||||
if sub.is_dir() {
|
||||
push_plugin(sub, &disabled_paths);
|
||||
}
|
||||
}
|
||||
if !pkg_root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
candidates.push((rel.components().count(), pkg_root));
|
||||
}
|
||||
|
||||
let mut roots = Vec::new();
|
||||
for plugin in plugin_dirs {
|
||||
let skills_sub = plugin.join("skills");
|
||||
if skills_sub.is_dir() {
|
||||
roots.push((skills_sub, AgentSkillSource::CopilotUser));
|
||||
} else {
|
||||
roots.push((plugin, AgentSkillSource::CopilotUser));
|
||||
}
|
||||
}
|
||||
roots
|
||||
candidates.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
|
||||
candidates.dedup_by(|a, b| a.1 == b.1);
|
||||
candidates.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
||||
fn looks_like_plugin_dir(dir: &Path) -> bool {
|
||||
dir.join("skills").is_dir()
|
||||
|| dir.join("plugin.json").is_file()
|
||||
|| dir.join(".plugin").is_dir()
|
||||
|| dir.join(".claude-plugin").is_dir()
|
||||
|| dir.join(".cursor-plugin").is_dir()
|
||||
|| dir.join("SKILL.md").is_file()
|
||||
/// If `skill_md` sits inside `<pkg>/<dot_dir>/skills[/<category>][/<name>]/SKILL.md` for one of
|
||||
/// [`WORKSPACE_ROOTS`], returns `<pkg>`.
|
||||
fn package_root_of_skill_file(skill_md: &Path) -> Option<PathBuf> {
|
||||
if skill_md.file_name().and_then(|n| n.to_str()) != Some("SKILL.md") {
|
||||
return None;
|
||||
}
|
||||
let mut cur = skill_md.parent()?;
|
||||
for _ in 0..=2 {
|
||||
if cur.file_name().and_then(|n| n.to_str()) == Some("skills")
|
||||
&& let Some(dot_dir) = cur.parent()
|
||||
&& let Some(dot_name) = dot_dir.file_name().and_then(|n| n.to_str())
|
||||
&& WORKSPACE_ROOTS.iter().any(|(rel, _)| rel.split('/').next() == Some(dot_name))
|
||||
&& let Some(pkg_root) = dot_dir.parent()
|
||||
{
|
||||
return Some(pkg_root.to_path_buf());
|
||||
}
|
||||
cur = cur.parent()?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn relative_within_workspaces(pkg_root: &Path, workspaces: &[(&Path, Option<PathBuf>)]) -> Option<PathBuf> {
|
||||
let pick_shortest =
|
||||
|iter: &mut dyn Iterator<Item = &Path>| iter.min_by_key(|rel| rel.components().count()).map(Path::to_path_buf);
|
||||
let mut direct = workspaces.iter().filter_map(|(ws, _)| pkg_root.strip_prefix(ws).ok());
|
||||
if let Some(rel) = pick_shortest(&mut direct) {
|
||||
return Some(rel);
|
||||
}
|
||||
let canon_pkg = dunce::canonicalize(pkg_root).ok()?;
|
||||
let mut canonical = workspaces.iter().filter_map(|(_, canon_ws)| canon_pkg.strip_prefix(canon_ws.as_ref()?).ok());
|
||||
pick_shortest(&mut canonical)
|
||||
}
|
||||
|
||||
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
|
||||
@@ -544,6 +585,8 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
|
||||
paths,
|
||||
valid: warnings.is_empty(),
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1070,6 +1113,8 @@ mod tests {
|
||||
paths: Vec::new(),
|
||||
valid: true,
|
||||
warnings: Vec::new(),
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1517,4 +1562,65 @@ mod tests {
|
||||
let staged_md = std::fs::read_to_string(farm.join("copilot/verify-ux/SKILL.md")).unwrap();
|
||||
assert_eq!(staged_md, raw_md);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_skill_files_discover_deep_monorepo_skills_and_respect_filters_and_precedence() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let ws = root.join("ws");
|
||||
|
||||
let deep_grafana =
|
||||
ws.join("mango/tools/mai-grafana-dashboards/.github/skills/edit-grafana-dashboards/SKILL.md");
|
||||
let deep_category = ws.join("a/b/c/.agents/skills/ops/deploy/SKILL.md");
|
||||
let deep_named_skills = ws.join("a/b/c/.claude/skills/skills/SKILL.md");
|
||||
let shallow_clash = ws.join("pkg/.agents/skills/shared/SKILL.md");
|
||||
let deep_clash = ws.join("a/b/c/.github/skills/shared/SKILL.md");
|
||||
let depth3_clash = ws.join("x/y/z/.github/skills/depth-race/SKILL.md");
|
||||
let depth4_clash = ws.join("x/y/z/w/.agents/skills/depth-race/SKILL.md");
|
||||
let fixture_skill = ws.join("crates/ide-plugin/tests/fixtures/agent-skills/skills/fixture-only/SKILL.md");
|
||||
let hidden_dir_skill = ws.join(".worktrees/branch/.github/skills/wt-only/SKILL.md");
|
||||
let target_dir_skill = ws.join("crates/app/target/gen/.github/skills/build-only/SKILL.md");
|
||||
|
||||
write(&deep_grafana, "---\nname: edit-grafana-dashboards\ndescription: Edit Grafana dashboards\n---\n");
|
||||
write(&deep_category, "---\nname: deploy\ndescription: Deploy service\n---\n");
|
||||
write(&deep_named_skills, "---\nname: skills\ndescription: Skill named skills\n---\n");
|
||||
write(&shallow_clash, "---\nname: shared\ndescription: Shallow copy\n---\n");
|
||||
write(&deep_clash, "---\nname: shared\ndescription: Deep copy\n---\n");
|
||||
write(&depth3_clash, "---\nname: depth-race\ndescription: Depth 3 wins\n---\n");
|
||||
write(&depth4_clash, "---\nname: depth-race\ndescription: Depth 4 loses\n---\n");
|
||||
write(&fixture_skill, "---\nname: fixture-only\ndescription: Fixture not under a skill root\n---\n");
|
||||
write(&hidden_dir_skill, "---\nname: wt-only\ndescription: Inside hidden dir\n---\n");
|
||||
write(&target_dir_skill, "---\nname: build-only\ndescription: Inside target dir\n---\n");
|
||||
|
||||
// Without indexed files, depth-3+ packages are beyond the 2-level direct walk.
|
||||
let shallow_only = discover_skills(&ws, None);
|
||||
assert!(shallow_only.iter().all(|s| s.name != "edit-grafana-dashboards"));
|
||||
assert!(shallow_only.iter().any(|s| s.name == "shared" && s.description == "Shallow copy"));
|
||||
|
||||
// Passing indexed `SKILL.md` paths (even in reversed depth order) surfaces deep skills
|
||||
// while keeping shallow-over-deep precedence and ignoring fixtures/hidden/build dirs.
|
||||
let indexed = vec![
|
||||
depth4_clash,
|
||||
depth3_clash,
|
||||
deep_clash,
|
||||
deep_grafana,
|
||||
deep_category,
|
||||
deep_named_skills,
|
||||
fixture_skill,
|
||||
hidden_dir_skill,
|
||||
target_dir_skill,
|
||||
];
|
||||
let found = discover_skills_with_indexed_files(std::slice::from_ref(&ws), None, &[], &[], &indexed);
|
||||
let by = |n: &str| found.iter().find(|s| s.name == n);
|
||||
|
||||
let grafana = by("edit-grafana-dashboards").expect("depth-3 .github/skills discovered");
|
||||
assert_eq!(grafana.source, AgentSkillSource::GithubWorkspace);
|
||||
assert!(by("deploy").is_some(), "category skill under depth-3 package discovered");
|
||||
assert!(by("skills").is_some(), "skill named `skills` under depth-3 package discovered");
|
||||
assert_eq!(by("shared").unwrap().description, "Shallow copy", "shallow package beats deep package");
|
||||
assert_eq!(by("depth-race").unwrap().description, "Depth 3 wins", "depth 3 beats depth 4");
|
||||
assert!(by("fixture-only").is_none(), "unrelated fixture SKILL.md ignored");
|
||||
assert!(by("wt-only").is_none(), "hidden directory tree ignored");
|
||||
assert!(by("build-only").is_none(), "SKIP_MONOREPO_DIRS tree ignored");
|
||||
}
|
||||
}
|
||||
@@ -65,10 +65,16 @@ struct FakeAgent {
|
||||
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
|
||||
/// The params of every `session/fork`, in order.
|
||||
forks: Mutex<Vec<Value>>,
|
||||
/// Cuts a fork at `_meta.openidea.forkTurns` itself, as the native agents do.
|
||||
cuts_forks: bool,
|
||||
/// The content blocks of each `session/prompt`.
|
||||
prompts: Mutex<Vec<Value>>,
|
||||
/// Queued errors returned on the next `session/prompt` calls before succeeding.
|
||||
prompt_errors: Mutex<VecDeque<(i64, String)>>,
|
||||
/// Number of prompts that stream Cursor's capacity diagnostic before returning end_turn.
|
||||
capacity_errors: Mutex<u32>,
|
||||
/// Queued errors returned on the next session-open calls before succeeding.
|
||||
open_errors: Mutex<VecDeque<(i64, String, Option<Value>)>>,
|
||||
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
|
||||
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
|
||||
}
|
||||
@@ -150,6 +156,12 @@ impl Handler for FakeAgent {
|
||||
let data = json!({"openidea": {"usageLimit": {"resetsAtMs": 1234.0}}});
|
||||
return Err((codes::INTERNAL_ERROR, "You've hit your usage limit".into(), Some(data)));
|
||||
}
|
||||
if matches!(method, "session/new" | "session/load" | "session/fork")
|
||||
&& let Some(err) = self.open_errors.lock().pop_front()
|
||||
{
|
||||
self.calls.lock().push(method.to_owned());
|
||||
return Err(err);
|
||||
}
|
||||
self.on_request(method, params).map_err(|(code, message)| (code, message, None))
|
||||
}
|
||||
|
||||
@@ -220,7 +232,13 @@ impl Handler for FakeAgent {
|
||||
"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") }))
|
||||
let mut reply = json!({ "sessionId": requested.unwrap_or("s2") });
|
||||
if self.cuts_forks
|
||||
&& let Some(turns) = params.pointer("/_meta/openidea/forkTurns")
|
||||
{
|
||||
reply["_meta"] = json!({ "openidea": { "forkTurns": turns } });
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
"_openidea/stop_task" => {
|
||||
self.calls.lock().push(format!("{method} {}", params["taskId"]));
|
||||
@@ -289,6 +307,22 @@ impl Handler for FakeAgent {
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
{
|
||||
let mut remaining = self.capacity_errors.lock();
|
||||
if *remaining > 0 {
|
||||
*remaining -= 1;
|
||||
if text == "edit once" {
|
||||
self.update(
|
||||
&session,
|
||||
json!({"sessionUpdate": "tool_call", "toolCallId": "edit",
|
||||
"title": "Edit file", "kind": "edit", "status": "completed"}),
|
||||
);
|
||||
}
|
||||
self.say(&session, "\n\nError: RetriableError: ");
|
||||
self.say(&session, "[resource_exhausted] Error");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
}
|
||||
if text.starts_with("The previous turn was interrupted because ") {
|
||||
self.say(&session, "resumed cleanly");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -426,6 +460,28 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, &format!("form {answer}"));
|
||||
return Ok(json!({ "stopReason": "end_turn" }));
|
||||
}
|
||||
if text == "question form" {
|
||||
// claude-agent-acp's `AskUserQuestion`, sent as a form.
|
||||
let peer = self.latest();
|
||||
let answer: Value = tokio::runtime::Handle::current()
|
||||
.block_on(peer.request(
|
||||
"elicitation/create",
|
||||
json!({"sessionId": session, "mode": "form",
|
||||
"message": "Please answer the following questions.",
|
||||
"requestedSchema": {"type": "object", "properties": {
|
||||
"question_0": {"type": "string", "title": "Layout", "description": "Which layout?",
|
||||
"oneOf": [{"const": "List", "title": "List"}, {"const": "Grid", "title": "Grid"}]},
|
||||
"question_0_custom": {"type": "string", "title": "Other"},
|
||||
"question_1": {"type": "array", "title": "Checks", "description": "Which checks?",
|
||||
"items": {"anyOf": [{"const": "Disk", "title": "Disk"},
|
||||
{"const": "GPU", "title": "GPU"}]}},
|
||||
"question_1_custom": {"type": "string", "title": "Other"}}}}),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
self.say(&session, &format!("form {answer}"));
|
||||
return Ok(json!({ "stopReason": "end_turn" }));
|
||||
}
|
||||
if text == "ask" {
|
||||
let peer = self.latest();
|
||||
let answer: Value = tokio::runtime::Handle::current()
|
||||
@@ -626,6 +682,7 @@ fn manager_at(dir: &Path, models_file: &Path, agent: Arc<FakeAgent>) -> AgentMan
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: models_file.to_path_buf(),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: Some(agents),
|
||||
// The project is the boundary of the skill walk: nothing above it (such as the
|
||||
// user's profile, when temp lives under it) leaks into the test.
|
||||
@@ -2191,6 +2248,210 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag
|
||||
assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]);
|
||||
}
|
||||
|
||||
/// A locked Codex recording can be forked without resuming it or moving its writer between tasks.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let task = {
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.shutdown();
|
||||
task
|
||||
};
|
||||
let agent = Arc::new(FakeAgent {
|
||||
load_error: Some((codes::INVALID_PARAMS, "thread s1 already has an active writer".into())),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
for _ in 0..2 {
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
}
|
||||
assert!(!agent.calls.lock().iter().any(|c| c == "session/new"));
|
||||
let copy = mgr.fork(&task.id, None).await.unwrap();
|
||||
assert_eq!(agent.forks.lock().last().unwrap()["sessionId"], "s1");
|
||||
let copy_handle = mgr.task(©.id).unwrap();
|
||||
assert_eq!(copy_handle.live.lock().as_ref().unwrap().session, "s2");
|
||||
let loads = agent.calls.lock().iter().filter(|c| *c == "session/load").count();
|
||||
mgr.prompt(©.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, ©.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), loads);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn warming_up_error() -> (i64, String, Option<Value>) {
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure".to_owned(),
|
||||
Some(json!({"errorName": "ServiceUnavailableError"})),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_open_retries_while_the_agent_finishes_starting_up() {
|
||||
// OpenCode rejects session opens until its plugins and MCP servers finish activating.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent =
|
||||
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 2, "retried the startup race");
|
||||
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().expect("a session");
|
||||
mgr.shutdown();
|
||||
|
||||
// The same race when reopening a saved session.
|
||||
let agent =
|
||||
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), 2, "retried the startup race");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(saved.as_str()));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
async fn wait_for_session_open_attempts(agent: &FakeAgent, method: &str, attempts: usize) {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while agent.calls.lock().iter().filter(|call| call.as_str() == method).count() < attempts {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("agent received the session-open requests");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retry_after_warmup_expires_loads_the_saved_session_again() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().unwrap();
|
||||
mgr.shutdown();
|
||||
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(std::iter::repeat_with(warming_up_error).take(16).collect()),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for_session_open_attempts(&agent, "session/load", 2).await;
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(WARMUP_WINDOW - WARMUP_DELAY * 2).await;
|
||||
tokio::time::resume();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
|
||||
entry, AgentEntry::Error { message } if message.contains("Try again") && !message.contains("new session")
|
||||
)));
|
||||
|
||||
agent.open_errors.lock().clear();
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(!agent.calls.lock().iter().any(|call| call == "session/new"));
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
assert_eq!(handle.live.lock().as_ref().unwrap().session, saved);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stalled_warmup_retry_times_out_and_closes_the_connection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
|
||||
hold_session_new: AtomicBool::new(true),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for_session_open_attempts(&agent, "session/new", 2).await;
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(WARMUP_WINDOW).await;
|
||||
tokio::time::resume();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
|
||||
entry, AgentEntry::Error { message } if message.contains("timed out")
|
||||
)));
|
||||
tokio::time::timeout(Duration::from_secs(5), agent.latest().closed())
|
||||
.await
|
||||
.expect("the timed-out connection closes");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_open_authenticates_after_a_warmup_reply() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
|
||||
auth_on_new: true,
|
||||
authenticate_method: Some("agent_login".into()),
|
||||
auth_methods: vec![json!({"id": "agent_login", "name": "Sign in"})],
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let calls = agent.calls.lock();
|
||||
let setup: Vec<_> = calls
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|call| call.starts_with("session/") || call.starts_with("authenticate"))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
setup,
|
||||
["session/new", "session/new", "authenticate", "authenticate agent_login", "session/new", "session/prompt"]
|
||||
);
|
||||
drop(calls);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_open_does_not_retry_unrelated_internal_errors() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(VecDeque::from([(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure".into(),
|
||||
Some(json!({"errorName": "SQLiteError"})),
|
||||
)])),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 1, "no retry on a real failure");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn text(t: &str) -> AgentPrompt {
|
||||
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
|
||||
}
|
||||
@@ -2571,7 +2832,12 @@ async fn subagents_get_their_own_conversation() {
|
||||
|
||||
#[test]
|
||||
fn image_blocks_declare_the_type_of_their_bytes() {
|
||||
let image = |mime: &str, data: &str| AgentImage { mime_type: mime.into(), data: data.into(), name: None };
|
||||
let image = |mime: &str, data: &str| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
};
|
||||
let cases = [
|
||||
// A browser's JPEG pasted as PNG.
|
||||
(image("image/png", "/9j/4AAQSkZJRgABAQ"), "image/jpeg"),
|
||||
@@ -2593,7 +2859,7 @@ fn prompts_become_acp_content_blocks() {
|
||||
let p = AgentPrompt {
|
||||
text: "look".into(),
|
||||
files: vec![IpcPath(PathBuf::from("/p/my file.rs"))],
|
||||
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None }],
|
||||
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None, inline_number: None }],
|
||||
};
|
||||
assert_eq!(
|
||||
blocks(&p, &[]),
|
||||
@@ -2625,6 +2891,32 @@ fn prompts_become_acp_content_blocks() {
|
||||
assert!(clean(text(" ")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_images_are_distinct_content_blocks_in_text_order() {
|
||||
let older: AgentImage = serde_json::from_value(json!({"mimeType":"image/png", "data":"AAA", "name":null})).unwrap();
|
||||
assert!(older.inline_number.is_none());
|
||||
let image = |number, data: &str| AgentImage {
|
||||
mime_type: "image/png".into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: Some(number),
|
||||
};
|
||||
let prompt = AgentPrompt {
|
||||
text: "😀 [Image #2] then [Image #1] and [Image #99]".into(),
|
||||
images: vec![image(1, "AAA"), image(2, "BBB"), image(3, "CCC")],
|
||||
..Default::default()
|
||||
};
|
||||
let content = blocks(&prompt, &[]);
|
||||
assert_eq!(content.len(), 5);
|
||||
assert_eq!(content[0], json!({"type": "text", "text": "😀 "}));
|
||||
assert_eq!(content[1]["type"], "image");
|
||||
assert_eq!(content[1]["data"], "BBB");
|
||||
assert_eq!(content[2], json!({"type": "text", "text": " then "}));
|
||||
assert_eq!(content[3]["type"], "image");
|
||||
assert_eq!(content[3]["data"], "AAA");
|
||||
assert_eq!(content[4], json!({"type": "text", "text": " and [Image #99]"}));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn claude_questions_keep_the_answer_object_as_the_option_id() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -2854,6 +3146,7 @@ async fn real_claude_task_in_a_worktree() {
|
||||
store_dir: tmp.path().join("store"),
|
||||
worktrees_dir: tmp.path().join("wt"),
|
||||
models_file: tmp.path().join("models.json"),
|
||||
cli_dir: tmp.path().join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
@@ -3197,6 +3490,62 @@ fn plant_claude_session(mgr: &AgentManager, root: &Path, session_id: &str) {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn forks_a_running_task_up_to_its_finished_turns() {
|
||||
for cuts_forks in [false, true] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent { cuts_forks, ..Default::default() });
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
mgr.prompt(&task.id, text("wait"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
|
||||
// The running turn stays behind, whatever was asked for.
|
||||
for turns in [None, Some(2)] {
|
||||
let copy = mgr.fork(&task.id, turns).await.unwrap();
|
||||
assert_eq!(copy.status, AgentStatus::Ready);
|
||||
let entries = mgr.entries(©.id, None).unwrap();
|
||||
assert_eq!(turn_starts(&entries).len(), 1);
|
||||
assert!(!entries.iter().any(|e| matches!(e, AgentEntry::User { text, .. } if text == "wait")));
|
||||
let pending = mgr.task(©.id).unwrap().state.lock().pending_rollback;
|
||||
assert_eq!(pending, if cuts_forks { 0 } else { 1 });
|
||||
assert_eq!(agent.forks.lock().last().unwrap().pointer("/_meta/openidea/forkTurns"), Some(&json!(1)));
|
||||
}
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.status, AgentStatus::Running);
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_running_first_turn_cannot_be_forked() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("wait"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Running).await;
|
||||
assert!(mgr.fork(&task.id, None).await.is_err());
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_starts_a_ready_task_as_the_recorded_session_s_fork() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -3241,6 +3590,131 @@ fn plant_codex_session(root: &Path, session_id: &str) {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Plants a recorded Copilot session below the test home.
|
||||
fn plant_copilot_session(root: &Path, session_id: &str) {
|
||||
let dir = root.join(".copilot").join("session-state").join(session_id);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join("workspace.yaml"),
|
||||
format!("id: {session_id}\ncwd: {}\nname: Fix the Copilot parser\n", root.to_string_lossy()),
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.join("events.jsonl"),
|
||||
format!(
|
||||
"{}\n",
|
||||
json!({
|
||||
"type": "user.message",
|
||||
"data": {"content": "fix the Copilot parser"}
|
||||
})
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn imports_copilot_sessions_and_loads_their_history() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let sessions = mgr.external_sessions();
|
||||
assert!(sessions.iter().any(|session| session.provider == "copilot" && session.session_id == NATIVE_SOURCE));
|
||||
let task = mgr.import_session("copilot", NATIVE_SOURCE).unwrap();
|
||||
assert_eq!(task.provider, "copilot");
|
||||
|
||||
for _ in 0..200 {
|
||||
if agent.calls.lock().iter().any(|call| call == "session/load")
|
||||
&& mgr.entries(&task.id, None).unwrap().len() >= 2
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert!(agent.calls.lock().iter().any(|call| call == "session/load"));
|
||||
assert!(
|
||||
mgr.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|entry| matches!(entry, AgentEntry::User { text, .. } if text == "earlier question"))
|
||||
);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn session_calls(agent: &FakeAgent) -> Vec<String> {
|
||||
agent.calls.lock().iter().filter(|c| c.starts_with("session/")).cloned().collect()
|
||||
}
|
||||
|
||||
/// Imports a claude session whose load fails, which leaves what a quit during the load leaves
|
||||
/// too: a task that holds the recorded session but no conversation.
|
||||
async fn import_without_history(dir: &Path) -> String {
|
||||
let agent = Arc::new(FakeAgent {
|
||||
load_error: Some((codes::INTERNAL_ERROR, "Claude Code exited".into())),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(dir, agent.clone());
|
||||
let _down = ShutDown(&mgr);
|
||||
plant_claude_session(&mgr, dir, NATIVE_SOURCE);
|
||||
let id = mgr.import_session("claude", NATIVE_SOURCE).unwrap().id;
|
||||
for _ in 0..300 {
|
||||
if !session_calls(&agent).is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(session_calls(&agent), ["session/load"]);
|
||||
assert_eq!(saved_task(&task_file(dir, &id)).unwrap().1, 0);
|
||||
id
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_imported_task_without_its_history_loads_it_when_shown() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let id = import_without_history(tmp.path()).await;
|
||||
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let _down = ShutDown(&mgr);
|
||||
for _ in 0..300 {
|
||||
if !mgr.entries(&id, None).unwrap().is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
let entries = mgr.entries(&id, None).unwrap();
|
||||
assert!(matches!(&entries[0], AgentEntry::User { text, .. } if text == "earlier question"), "{entries:?}");
|
||||
assert_eq!(session_calls(&agent), ["session/load"], "loaded once, however often it is shown");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_failed_history_load_leaves_the_new_session_to_the_user() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let id = import_without_history(tmp.path()).await;
|
||||
|
||||
let agent = Arc::new(FakeAgent {
|
||||
load_error: Some((codes::INTERNAL_ERROR, "no conversation found".into())),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let _down = ShutDown(&mgr);
|
||||
mgr.entries(&id, None).unwrap();
|
||||
for _ in 0..300 {
|
||||
if !session_calls(&agent).is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
mgr.entries(&id, None).unwrap();
|
||||
assert_eq!(session_calls(&agent), ["session/load"], "tried once in this run");
|
||||
|
||||
mgr.prompt(&id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &id, AgentStatus::Failed).await;
|
||||
assert_eq!(session_calls(&agent), ["session/load", "session/load"], "no new session behind the user's back");
|
||||
assert!(mgr.entries(&id, None).unwrap().iter().any(|e| matches!(e,
|
||||
AgentEntry::Error { message } if message.contains("Send the message again"))));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_uses_the_id_codex_assigns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -3261,6 +3735,28 @@ async fn fork_session_uses_the_id_codex_assigns() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn fork_session_uses_the_id_copilot_assigns() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
plant_copilot_session(tmp.path(), NATIVE_SOURCE);
|
||||
|
||||
let task = mgr.fork_session("copilot", NATIVE_SOURCE, tmp.path()).unwrap();
|
||||
for _ in 0..200 {
|
||||
if !agent.forks.lock().is_empty() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).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(), "copilot 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();
|
||||
@@ -3821,6 +4317,54 @@ async fn an_agent_form_is_answered_declined_or_cancelled_even_when_approvals_are
|
||||
}
|
||||
}
|
||||
|
||||
/// claude-agent-acp asks `AskUserQuestion` as a form: it is shown as the question card, one
|
||||
/// question at a time, and the card's answers fill the form (#7359).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_question_tool_form_is_asked_as_questions() {
|
||||
let answers = json!({"question_0": ["Grid", "with thumbnails"], "question_1": ["Disk", "GPU"]}).to_string();
|
||||
for (reply, said) in [
|
||||
(
|
||||
answers.as_str(),
|
||||
r#"form {"action":"accept","content":{"question_0":"Grid","question_0_custom":"with thumbnails","question_1":["Disk","GPU"]}}"#,
|
||||
),
|
||||
("reject", r#"form {"action":"decline"}"#),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("question form"),
|
||||
provider: "cursor".into(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let (id, questions) = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find_map(|entry| match entry {
|
||||
AgentEntry::Permission { id, questions, form: None, chosen: None, .. } if !questions.is_empty() => {
|
||||
Some((id, questions))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let asked: Vec<_> =
|
||||
questions.iter().map(|q| (q.answer_key.as_deref(), q.question.as_str(), q.multi_select)).collect();
|
||||
assert_eq!(asked, [(Some("question_0"), "Which layout?", false), (Some("question_1"), "Which checks?", true)]);
|
||||
mgr.respond(&task.id, id, Some(reply.to_owned())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == said)), "{entries:?}");
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cursor_approval_choice_applies_before_first_prompt() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -4116,6 +4660,7 @@ async fn reload_providers_updates_registry_install_clears_stale_probes_and_notif
|
||||
store_dir: tmp.path().join("store"),
|
||||
worktrees_dir: tmp.path().join("worktrees"),
|
||||
models_file: tmp.path().join("models.json"),
|
||||
cli_dir: tmp.path().join("agent-cli"),
|
||||
custom_agents_dir: Some(agents_dir.clone()),
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
@@ -4181,6 +4726,7 @@ async fn a_failed_probe_is_retried_instead_of_remembered() {
|
||||
store_dir: tmp.path().join("store"),
|
||||
worktrees_dir: tmp.path().join("worktrees"),
|
||||
models_file: tmp.path().join("models.json"),
|
||||
cli_dir: tmp.path().join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
@@ -4444,6 +4990,7 @@ async fn delete_running_agent(no_load: bool) {
|
||||
store_dir: root.join("store"),
|
||||
worktrees_dir: root.join("worktrees"),
|
||||
models_file: root.join("models.json"),
|
||||
cli_dir: root.join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
@@ -4501,14 +5048,21 @@ async fn delete_running_agent(no_load: bool) {
|
||||
fn mcp_servers_follow_server_state_and_agent_capabilities() {
|
||||
let root = std::path::Path::new("/project");
|
||||
let exe = std::path::Path::new("/app/openidea");
|
||||
assert!(super::stdio_mcp_servers(None, true, root).is_empty());
|
||||
assert!(super::stdio_mcp_servers(Some(exe), false, root).is_empty());
|
||||
let servers = super::stdio_mcp_servers(Some(exe), true, root);
|
||||
assert!(super::stdio_mcp_servers(None, true, root, None).is_empty());
|
||||
assert!(super::stdio_mcp_servers(Some(exe), false, root, None).is_empty());
|
||||
let servers = super::stdio_mcp_servers(Some(exe), true, root, None);
|
||||
assert_eq!(
|
||||
servers,
|
||||
vec![json!({"name":"OpenIDEA","command":"/app/openidea",
|
||||
"args":["--mcp-stdio","--project","/project"],"env":[]})]
|
||||
);
|
||||
let nonce_servers = super::stdio_mcp_servers(Some(exe), true, root, Some("nonce_secret_abc"));
|
||||
assert_eq!(
|
||||
nonce_servers,
|
||||
vec![json!({"name":"OpenIDEA","command":"/app/openidea",
|
||||
"args":["--mcp-stdio","--project","/project"],
|
||||
"env":[{"name": ide_mcp::SESSION_NONCE_ENV, "value":"nonce_secret_abc"}]})]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
@@ -4773,7 +5327,7 @@ fn a_running_tools_output_is_sent_as_appends() {
|
||||
// An image the tool returned is not part of the appended text: it goes with the whole entry.
|
||||
let mut shown = titled.clone();
|
||||
if let AgentEntry::Tool { images, output, .. } = &mut shown {
|
||||
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None });
|
||||
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None, inline_number: None });
|
||||
output.as_mut().unwrap().push('!');
|
||||
}
|
||||
let imaged = event(&mut streamed, None, 2, &shown).unwrap();
|
||||
@@ -5947,6 +6501,10 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
McpServer {
|
||||
id: "user::slack".into(),
|
||||
@@ -5961,6 +6519,10 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
]
|
||||
}));
|
||||
@@ -6267,6 +6829,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
@@ -6390,6 +6953,7 @@ done
|
||||
store_dir: tmp.path().join("store"),
|
||||
worktrees_dir: tmp.path().join("worktrees"),
|
||||
models_file: tmp.path().join("models.json"),
|
||||
cli_dir: tmp.path().join("agent-cli"),
|
||||
custom_agents_dir: Some(agents_dir),
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
@@ -6872,6 +7436,85 @@ async fn transient_network_outage_probes_with_zero_prompts_and_auto_resumes_when
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cursor_capacity_retry_pauses_after_three_continuations_and_resumes_on_request() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.capacity_errors.lock() = 4;
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let _down = ShutDown(&mgr);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let snap = handle.state.lock().snapshot();
|
||||
assert_eq!(snap.interrupted.unwrap().reason, InterruptionReason::CursorCapacity);
|
||||
assert!(snap.retry.is_none());
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
let attempts: Vec<_> = entries
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
AgentEntry::User { retry_attempt, .. } => *retry_attempt,
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(attempts, [1, 2, 3]);
|
||||
assert_eq!(entries.iter().filter(|e| matches!(e, AgentEntry::Tool { .. })).count(), 1);
|
||||
assert_eq!(agent.prompts.lock().len(), 4);
|
||||
mgr.resume(&task.id).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(handle.state.lock().task.interrupted.is_none());
|
||||
assert_eq!(agent.prompts.lock().len(), 5);
|
||||
assert!(
|
||||
agent
|
||||
.prompts
|
||||
.lock()
|
||||
.iter()
|
||||
.skip(1)
|
||||
.all(|p| p[0]["text"].as_str().unwrap().contains("Inspect the current workspace"))
|
||||
);
|
||||
assert!(
|
||||
matches!(mgr.entries(&task.id, None).unwrap().last(), Some(AgentEntry::Agent { text }) if text == "resumed cleanly")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cursor_capacity_retry_can_be_stopped_or_replaced_during_backoff() {
|
||||
for send_now in [false, true] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
*agent.capacity_errors.lock() = 1;
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let _down = ShutDown(&mgr);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "cursor".into(), prompt: text("edit once"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while handle.state.lock().task.retry.is_none() {
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let retry = handle.state.lock().task.retry.clone().unwrap();
|
||||
assert_eq!((retry.attempt, retry.max_retries, retry.deadline_ms), (1, Some(3), None));
|
||||
if !send_now {
|
||||
mgr.cancel(&task.id, None).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.prompts.lock().len(), 1);
|
||||
assert!(handle.state.lock().task.retry.is_none());
|
||||
}
|
||||
mgr.prompt(&task.id, text("again"), send_now).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.prompts.lock().len(), 2);
|
||||
assert_eq!(agent.prompts.lock()[1][0]["text"], "again");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_errors_fail_fast() {
|
||||
use ide_core::settings::{NetworkRetryWindow, ResumeInterruptedPolicy};
|
||||
@@ -6928,3 +7571,36 @@ async fn network_outage_window_off_or_expired_degrades_to_interrupted_and_auth_e
|
||||
mgr2.shutdown();
|
||||
mgr3.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn metadata_edits_do_not_bump_updated_ms() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let _down = ShutDown(&mgr);
|
||||
let task = mgr
|
||||
.create(NewAgentTask { provider: "claude".into(), prompt: text("again"), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
let fixed_ms = 1_234.0;
|
||||
handle.state.lock().task.updated_ms = fixed_ms;
|
||||
|
||||
mgr.rename(&task.id, "Custom Title").unwrap();
|
||||
assert_eq!(handle.state.lock().task.updated_ms, fixed_ms);
|
||||
|
||||
let after_mcp = mgr.set_mcp_overrides(&task.id, BTreeMap::from([("github".into(), false)])).unwrap();
|
||||
assert_eq!(after_mcp.updated_ms, fixed_ms);
|
||||
|
||||
let after_skill =
|
||||
mgr.set_skill_overrides(&task.id, BTreeMap::from([("triage".into(), AgentSkillMode::Off)])).unwrap();
|
||||
assert_eq!(after_skill.updated_ms, fixed_ms);
|
||||
|
||||
let after_memory = mgr
|
||||
.set_memory_overrides(
|
||||
&task.id,
|
||||
AgentMemoryOverrides { auto_memory: Some(AutoMemoryMode::Off), entries: BTreeMap::new() },
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(after_memory.updated_ms, fixed_ms);
|
||||
}
|
||||
@@ -523,7 +523,7 @@ mod tests {
|
||||
t.apply(&update);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
|
||||
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
|
||||
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None, inline_number: None }]);
|
||||
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
|
||||
assert_eq!(*status, AgentToolStatus::Completed);
|
||||
let saved = serde_json::to_string(&t.entries[0]).unwrap();
|
||||
@@ -646,6 +646,7 @@ mod tests {
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
recovery: None,
|
||||
retry_attempt: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0));
|
||||
@@ -668,6 +669,7 @@ mod tests {
|
||||
done_ms: None,
|
||||
steered,
|
||||
recovery: None,
|
||||
retry_attempt: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0, false));
|
||||
|
||||
@@ -9,12 +9,34 @@ use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
pub(crate) struct Created {
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub path: PathBuf,
|
||||
pub cwd: PathBuf,
|
||||
pub branch: String,
|
||||
pub base: String,
|
||||
pub base_commit: String,
|
||||
}
|
||||
|
||||
const OWNERSHIP_MARKER: &str = "openidea-worktree.json";
|
||||
const OWNERSHIP_TAG: &str = "openidea-agent";
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct WorktreeOwnership {
|
||||
owner: String,
|
||||
task_id: String,
|
||||
worktree_root: PathBuf,
|
||||
repo_root: PathBuf,
|
||||
}
|
||||
|
||||
/// Returns the canonical root of the Git repository containing `project_root`, if any.
|
||||
pub fn canonical_repo_root(project_root: &Path) -> IdeResult<Option<PathBuf>> {
|
||||
match Repo::discover(project_root)? {
|
||||
Some(repo) => Ok(Some(dunce::canonicalize(repo.root())?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The repository of `path`, free to execute: the host runs every agent command that
|
||||
/// reaches a repository only in a trusted project.
|
||||
fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
@@ -157,9 +179,38 @@ pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
|
||||
create_for_task(project_root, worktrees_dir, "", title, base)
|
||||
}
|
||||
|
||||
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
|
||||
/// Records an ownership marker in the linked worktree's private `git_dir` and preserves any
|
||||
/// project-relative subdirectory inside `project_root` when `project_root` is below `repo.root()`.
|
||||
pub(crate) fn create_for_task(
|
||||
project_root: &Path,
|
||||
worktrees_dir: &Path,
|
||||
task_id: &str,
|
||||
title: &str,
|
||||
base: Option<&str>,
|
||||
) -> IdeResult<Created> {
|
||||
let repo = repo_at(project_root)?;
|
||||
let canon_repo = dunce::canonicalize(repo.root())?;
|
||||
let canon_proj = dunce::canonicalize(project_root)?;
|
||||
let rel_subdir = if canon_proj != canon_repo {
|
||||
canon_proj
|
||||
.strip_prefix(&canon_repo)
|
||||
.map_err(|_| {
|
||||
IdeError::invalid(format!(
|
||||
"{} is outside git repository {}",
|
||||
canon_proj.display(),
|
||||
canon_repo.display()
|
||||
))
|
||||
})?
|
||||
.to_path_buf()
|
||||
} else {
|
||||
PathBuf::new()
|
||||
};
|
||||
let (base, base_commit) = match base.map(str::trim).filter(|b| !b.is_empty()) {
|
||||
Some(b) => {
|
||||
let commit =
|
||||
@@ -177,7 +228,125 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
|
||||
let path = worktrees_dir.join(&slug);
|
||||
let branch = format!("agent/{slug}");
|
||||
repo.add_worktree(&path, &base_commit, Some(&branch))?;
|
||||
Ok(Created { path, branch, base, base_commit })
|
||||
|
||||
let canon_wt = match dunce::canonicalize(&path) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
let wt_repo = match repo_at(&canon_wt) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let [git_dir, common_dir] = match wt_repo.metadata_dirs() {
|
||||
Ok(dirs) => dirs,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
if dunce::canonicalize(&git_dir).ok() == dunce::canonicalize(&common_dir).ok() {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(IdeError::internal("linked worktree did not receive a separate git metadata directory"));
|
||||
}
|
||||
let marker = WorktreeOwnership {
|
||||
owner: OWNERSHIP_TAG.to_owned(),
|
||||
task_id: task_id.to_owned(),
|
||||
worktree_root: canon_wt.clone(),
|
||||
repo_root: canon_repo,
|
||||
};
|
||||
if let Err(e) = serde_json::to_vec_pretty(&marker)
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
.and_then(|bytes| ide_vfs::write_atomic(&git_dir.join(OWNERSHIP_MARKER), &bytes))
|
||||
{
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let raw_cwd = if rel_subdir.as_os_str().is_empty() { canon_wt.clone() } else { canon_wt.join(&rel_subdir) };
|
||||
if !raw_cwd.is_dir() {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(IdeError::invalid(format!(
|
||||
"project folder {} does not exist in base revision {}",
|
||||
rel_subdir.display(),
|
||||
base
|
||||
)));
|
||||
}
|
||||
let canon_cwd = match verify_confined_worktree_subdir(&canon_wt, &raw_cwd) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
|
||||
}
|
||||
|
||||
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
|
||||
let canon_cwd = dunce::canonicalize(target_cwd)?;
|
||||
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
|
||||
let real_cwd = ide_core::real_path::resolve_real(target_cwd);
|
||||
if !canon_cwd.starts_with(canon_wt_root)
|
||||
|| !real_cwd.starts_with(&real_wt)
|
||||
|| ide_core::real_path::reaches_git_dir(&real_wt, &real_cwd)
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree working directory {} resolves outside worktree {}",
|
||||
target_cwd.display(),
|
||||
canon_wt_root.display()
|
||||
)));
|
||||
}
|
||||
Ok(canon_cwd)
|
||||
}
|
||||
|
||||
/// Canonicalizes `cwd` of an existing `Isolation::Worktree` task and verifies that it still
|
||||
/// resolves strictly inside its own worktree checkout root under `worktrees_dir` (preventing
|
||||
/// symlink escapes on reused sessions/turns).
|
||||
pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) -> IdeResult<PathBuf> {
|
||||
let (wt_root, wt_base) = worktree_checkout_root(worktrees_dir, cwd);
|
||||
if !wt_root.starts_with(&wt_base) || wt_root == wt_base {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree working directory {} is outside managed worktrees directory {}",
|
||||
cwd.display(),
|
||||
worktrees_dir.display()
|
||||
)));
|
||||
}
|
||||
let canon_wt_root = dunce::canonicalize(&wt_root)?;
|
||||
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
|
||||
if !canon_wt_root.starts_with(&canon_wt_dir)
|
||||
|| canon_wt_root == canon_wt_dir
|
||||
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
|
||||
{
|
||||
return Err(IdeError::invalid("worktree checkout root escaped managed worktrees directory"));
|
||||
}
|
||||
verify_confined_worktree_subdir(&canon_wt_root, cwd)
|
||||
}
|
||||
|
||||
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
|
||||
if let Ok(rel) = path.strip_prefix(worktrees_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
|
||||
}
|
||||
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
|
||||
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
}
|
||||
if let Ok(canon_path) = dunce::canonicalize(path)
|
||||
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
}
|
||||
}
|
||||
(path.to_path_buf(), worktrees_dir.to_path_buf())
|
||||
}
|
||||
|
||||
/// `git worktree remove --force -- <path>`. When git no longer recognizes the
|
||||
@@ -186,19 +355,94 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
|
||||
/// ours, so it is removed directly to keep the task deletable (a stale
|
||||
/// registration prunes later); anything else keeps git's error.
|
||||
pub(crate) fn remove(project_root: &Path, worktrees_dir: &Path, path: &Path) -> IdeResult<()> {
|
||||
let (target, wt_base) = worktree_checkout_root(worktrees_dir, path);
|
||||
let repo = repo_at(project_root)?;
|
||||
let err = match repo.remove_worktree(path, true) {
|
||||
let err = match repo.remove_worktree(&target, true) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
if !path.exists() {
|
||||
if !target.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
if !path.starts_with(worktrees_dir) || path == worktrees_dir {
|
||||
if !target.starts_with(&wt_base) || target == wt_base {
|
||||
return Err(err);
|
||||
}
|
||||
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(path))
|
||||
.map_err(|e| IdeError::internal(format!("{}: {e}", path.display())))
|
||||
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(&target))
|
||||
.map_err(|e| IdeError::internal(format!("{}: {e}", target.display())))
|
||||
}
|
||||
|
||||
/// Safely removes an automation worktree ONLY after verifying its private `git_dir` ownership
|
||||
/// marker (`openidea-worktree.json`) matches `task_id` and `worktrees_dir`.
|
||||
///
|
||||
/// - When `require_clean` is `true` (zero-diff GC): verifies `HEAD == base_commit` and both the
|
||||
/// Git index (staged) and working tree (unstaged + untracked) are completely clean right before
|
||||
/// running **non-forced** `git worktree remove` (`force = false`). Returns `Ok(false)` without
|
||||
/// modifying disk if the worktree has any commits, staged changes, unstaged edits, or untracked
|
||||
/// files.
|
||||
/// - Never falls back to `remove_dir_all` on any ownership or Git error: any error keeps the
|
||||
/// checkout intact.
|
||||
pub(crate) fn remove_owned_automation_worktree(
|
||||
project_root: &Path,
|
||||
worktrees_dir: &Path,
|
||||
cwd: &Path,
|
||||
task_id: &str,
|
||||
base_commit: Option<&str>,
|
||||
require_clean: bool,
|
||||
) -> IdeResult<bool> {
|
||||
if !cwd.exists() || !worktrees_dir.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
let canon_worktrees = dunce::canonicalize(worktrees_dir)?;
|
||||
let canon_cwd = dunce::canonicalize(cwd)?;
|
||||
if !canon_cwd.starts_with(&canon_worktrees) || canon_cwd == canon_worktrees {
|
||||
return Err(IdeError::invalid("refusing to clean worktree outside managed worktrees directory"));
|
||||
}
|
||||
let main_repo = repo_at(project_root)?;
|
||||
let wt_repo = repo_at(&canon_cwd)?;
|
||||
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
|
||||
if !canon_wt_root.starts_with(&canon_worktrees)
|
||||
|| canon_wt_root == canon_worktrees
|
||||
|| canon_wt_root.parent() != Some(canon_worktrees.as_path())
|
||||
{
|
||||
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
|
||||
}
|
||||
let [git_dir, wt_common] = wt_repo.metadata_dirs()?;
|
||||
let [_, main_common] = main_repo.metadata_dirs()?;
|
||||
let canon_git_dir = dunce::canonicalize(&git_dir)?;
|
||||
let canon_wt_common = dunce::canonicalize(&wt_common)?;
|
||||
let canon_main_common = dunce::canonicalize(&main_common)?;
|
||||
if canon_git_dir == canon_wt_common || canon_wt_common != canon_main_common {
|
||||
return Err(IdeError::invalid("target checkout is not a linked worktree of this repository"));
|
||||
}
|
||||
let marker_bytes = std::fs::read(canon_git_dir.join(OWNERSHIP_MARKER))
|
||||
.map_err(|_| IdeError::invalid("refusing to remove worktree without OpenIDEA ownership marker"))?;
|
||||
let marker: WorktreeOwnership = serde_json::from_slice(&marker_bytes)
|
||||
.map_err(|_| IdeError::invalid("corrupt OpenIDEA worktree ownership marker"))?;
|
||||
let marker_root = dunce::canonicalize(&marker.worktree_root).unwrap_or(marker.worktree_root);
|
||||
if marker.owner != OWNERSHIP_TAG || marker.task_id != task_id || marker_root != canon_wt_root {
|
||||
return Err(IdeError::invalid("worktree ownership marker does not match task"));
|
||||
}
|
||||
|
||||
if require_clean {
|
||||
let Some(base) = base_commit else {
|
||||
return Ok(false);
|
||||
};
|
||||
if wt_repo.head()?.1.as_deref() != Some(base) {
|
||||
return Ok(false);
|
||||
}
|
||||
// `status()` checks BOTH HEAD↔index (staged) and index↔worktree (unstaged + untracked).
|
||||
if !wt_repo.status()?.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
if !wt_repo.diff_with_worktree(base)?.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
main_repo.remove_worktree(&canon_wt_root, false)?;
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
main_repo.remove_worktree(&canon_wt_root, true)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// On Windows a folder can't be deleted while a process still has a file in it open
|
||||
@@ -1944,4 +2188,130 @@ mod tests {
|
||||
changed.sort();
|
||||
assert_eq!(changed, ["edited", "new", "reverted"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_worktree_cleanup_preserves_subproject_cwd_catches_staged_changes_and_verifies_ownership() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
let sub = repo.join("packages").join("subapp");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
git(&repo, &["config", "core.autocrlf", "false"]);
|
||||
std::fs::write(repo.join("root.txt"), "root\n").unwrap();
|
||||
std::fs::write(sub.join("index.ts"), "export const x = 1;\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&sub, &wt_dir, "task-1", "Sub Audit", None).unwrap();
|
||||
assert_eq!(
|
||||
dunce::canonicalize(&created.cwd).unwrap(),
|
||||
dunce::canonicalize(&created.path).unwrap().join("packages").join("subapp"),
|
||||
"project-relative cwd inside parent repo must be preserved inside worktree"
|
||||
);
|
||||
|
||||
// Wrong task_id is refused and keeps the checkout untouched.
|
||||
assert!(
|
||||
remove_owned_automation_worktree(
|
||||
&sub,
|
||||
&wt_dir,
|
||||
&created.cwd,
|
||||
"wrong-task",
|
||||
Some(&created.base_commit),
|
||||
true,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(created.path.exists());
|
||||
|
||||
// Staged-only change (index differs from HEAD while working tree matches HEAD!) is NOT clean!
|
||||
std::fs::write(created.cwd.join("index.ts"), "export const x = 2;\n").unwrap();
|
||||
git(&created.path, &["add", "packages/subapp/index.ts"]);
|
||||
std::fs::write(created.cwd.join("index.ts"), "export const x = 1;\n").unwrap();
|
||||
let removed_staged =
|
||||
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
|
||||
.unwrap();
|
||||
assert!(!removed_staged, "staged-only index change must prevent zero-diff worktree GC");
|
||||
assert!(created.path.exists());
|
||||
|
||||
// Reset index back to HEAD -> zero-diff GC removes the worktree via non-forced `git worktree remove`.
|
||||
git(&created.path, &["reset", "-q", "HEAD", "--", "packages/subapp/index.ts"]);
|
||||
let removed_clean =
|
||||
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
|
||||
.unwrap();
|
||||
assert!(removed_clean);
|
||||
assert!(!created.path.exists());
|
||||
|
||||
// Foreign / manually created git worktree inside `wt_dir` without ownership marker is NEVER deleted.
|
||||
let manual_wt = wt_dir.join("foreign");
|
||||
git(&repo, &["worktree", "add", "-q", "-b", "manual-branch", manual_wt.to_str().unwrap(), "HEAD"]);
|
||||
assert!(
|
||||
remove_owned_automation_worktree(&repo, &wt_dir, &manual_wt, "task-2", Some(&created.base_commit), false,)
|
||||
.is_err()
|
||||
);
|
||||
assert!(manual_wt.exists(), "worktree without OpenIDEA ownership marker must never be deleted");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlinked_subproject_cwd_escaping_worktree_is_rejected_on_create_and_reuse() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let outside = tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(outside.join("secret.txt"), "nope\n").unwrap();
|
||||
|
||||
let repo = tmp.path().join("repo");
|
||||
let packages = repo.join("packages");
|
||||
std::fs::create_dir_all(&packages).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
git(&repo, &["config", "core.autocrlf", "false"]);
|
||||
|
||||
// 1a. Direct symlink pointing outside git is rejected immediately.
|
||||
let escape_link = packages.join("escape");
|
||||
std::os::unix::fs::symlink(&outside, &escape_link).unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "symlink escape"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
assert!(create_for_task(&escape_link, &wt_dir, "task-escape-direct", "Escape", None).is_err());
|
||||
|
||||
// 1b. Committed symlink in `HEAD` (`packages/tricky -> ../../outside`) while the main
|
||||
// checkout temporarily has a real directory at `packages/tricky`: `git worktree add`
|
||||
// checks out `HEAD`'s symlink inside the worktree, and `verify_confined_worktree_subdir`
|
||||
// must catch the escape and clean up the worktree!
|
||||
let tricky = packages.join("tricky");
|
||||
std::os::unix::fs::symlink(&outside, &tricky).unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "committed tricky symlink"]);
|
||||
std::fs::remove_file(&tricky).unwrap();
|
||||
std::fs::create_dir_all(&tricky).unwrap();
|
||||
|
||||
let Err(err) = create_for_task(&tricky, &wt_dir, "task-escape-head", "Tricky", None) else {
|
||||
panic!("expected committed symlink escaping worktree root to be rejected");
|
||||
};
|
||||
assert!(
|
||||
err.to_string().contains("outside worktree") || err.to_string().contains("escapes worktree root"),
|
||||
"unexpected error for committed symlink cwd: {err}"
|
||||
);
|
||||
|
||||
// 2. Normal directory at creation time, later replaced with an escaping symlink before reuse,
|
||||
// must be rejected by `verify_confined_worktree_cwd`!
|
||||
let legit_sub = packages.join("legit");
|
||||
std::fs::create_dir_all(&legit_sub).unwrap();
|
||||
std::fs::write(legit_sub.join("ok.txt"), "ok\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "legit sub"]);
|
||||
|
||||
let created = create_for_task(&legit_sub, &wt_dir, "task-reuse", "Legit", None).unwrap();
|
||||
let verified = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap();
|
||||
assert!(verified.starts_with(dunce::canonicalize(&created.path).unwrap()));
|
||||
|
||||
std::fs::remove_dir_all(&created.cwd).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, &created.cwd).unwrap();
|
||||
let reuse_err = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap_err();
|
||||
assert!(
|
||||
reuse_err.to_string().contains("outside worktree") || reuse_err.to_string().contains("escapes"),
|
||||
"symlink swap on worktree reuse must be rejected: {reuse_err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
+107
-111
@@ -1,112 +1,108 @@
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6"]}
|
||||
{"from":"shim","msg":{"request":{"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","feedback_mode":{"kind":"post"},"ide_rc_auto_enable_gate":true,"models":[{"description":"Sonnet 5.5 · Efficient for routine tasks","displayName":"Default (recommended)","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.1","resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","resolvedModel":"claude-sonnet-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-4-6"}],"pid":23982,"remote_control_auto_connect_default":false,"remote_control_auto_enable":false,"remote_control_auto_on_by_default":false,"remote_control_available":true,"session_state":"idle"},"subtype":"success"},"type":"control_response"}}
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","a89e008b-23b6-41ea-bebb-612440f38e3c"]}
|
||||
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
|
||||
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"effort":"medium","model":"claude-haiku-5-5","ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false},"effective":{"model":"opus"}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"running","subtype":"session_state_changed","type":"system","uuid":"5e39fde0-9f18-47f0-8b7e-21007ec957c0"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"ad1291e3-8d79-4048-a10c-599eafd30c9b"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"0ed63980-6c4a-40b9-b94d-3bc062cddd58"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"17b7ad4c-6ad3-4d9c-aeef-2e027b0d75ae","view_mode":"default"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"7b8f8fcd-669e-4606-ad6f-3368116e7a75"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"org_level_disabled","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1793203800,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1793203800,"status":"allowed","utilization":0.31},"seven_day":{"resetsAt":1793631600,"status":"allowed","utilization":0.32}}},"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"rate_limit_event","uuid":"b3ef3e2a-11ad-46f9-8ea5-fd01f8d0fe39"}}
|
||||
{"from":"cli","msg":{"commands":[{"argumentHint":"","description":"Review a pull request","name":"review"}],"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"commands_changed","type":"system","uuid":"5f60f663-94ff-4885-9167-b12cae835fca"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1661,"type":"stream_event","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"4fb86b8a-bfa9-439b-b46b-6ef6e381d243"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0bc16cbc-fcbb-4d52-bd5b-4d864b307bbd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0510612a-2068-496a-85f4-f61706fb8cd5"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"{\"command\": \"sleep 3","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"281a35ac-8285-4591-8c60-5ddc743b7036"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"44c02159-084d-48d1-a23c-5bd3628e69e7"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"ca641c1e-c60b-4943-a07b-9ea03c9b8845"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"leep 3 se","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"bc5c34f0-653a-4041-a6cf-42c0dcd0fc2c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"conds then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"00cd396e-f45d-4b60-b484-9fb0ddfc3384"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6987c232-0dbf-43be-83fe-2164d6d701ee"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhj5SvXJc5aP46FPBxn","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:00.931Z","type":"assistant","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"b7befa90-ef05-44ff-9822-ec00f61130b2","wire_tool_inputs":{"toolu_01RLgKZhL3rEQrnb6R4yD7LH":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"01897941-b66d-4657-a87b-14dde2420f38"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"daf07992-fd3c-46c2-8fe7-3014bf6e6cf0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6c4b9511-1539-45a7-9184-9efc1ce9384d"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"now","session_id":"","type":"user","uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"6ae9f6be-c8d5-4feb-8c17-71bfc3d4880e"}}
|
||||
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"task_started","task_id":"bk6c5st9v","task_type":"local_bash","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"e45f0b55-eb72-4cc6-8bb7-0ba207583cc7"}}
|
||||
{"from":"cli","msg":{"output_file":"","run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bk6c5st9v","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"0d23dced-54be-49b0-963b-a9e67ae4b75c"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:04.328Z","tool_result_meta":[{"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"998e4d6c-47bf-4e81-b630-1eb86398d192"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":2891,"duration_ms":5544,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1797,"first_request_input_tokens":29936,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":1,"request_sent_wall_ms":1793193598927,"result":"","result_index":0,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"aborted_tools","time_to_request_ms":138,"total_cost_usd":0.0033443400000000003,"ttft_ms":2142,"ttft_stream_ms":1797,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"a4afa59a-be05-41e3-bc85-4cc8e9b28506"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"cancelled","type":"command_lifecycle","uuid":"4911bef5-6b3d-4c0e-803e-5f21202ce766"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"89c8590f-1c08-4183-b430-5e888745fbfc"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"a05d013f-558f-4581-9ac1-49e4329e9d7d","view_mode":"default"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"d00d3b7f-227d-4373-9092-676090723763"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1500,"type":"stream_event","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"c634f9c8-ff1c-44fa-9138-5d357a418f58"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0db4c93b-e0cb-4fcf-857f-c79fed9a2609"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e7d95fb9-826f-45e1-8e7c-4e6abcdef7c9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"27c0c433-3ee8-42fc-830a-90d67cb371d1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"cc8a606b-0251-4927-96c5-160880f430f6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" s","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1c859e8c-52fe-4fb3-8ad1-0122752cdccf"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"202bcadf-3533-4744-a259-97bfc7bef0e3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"leep task","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2a273607-1f22-4a49-860c-30184e6bfe01"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":9,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"63d703f5-6eec-4a89-a6c7-c38245001004"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" completed with","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"dba1141d-78a3-406a-9125-bf02b5b4a2a3"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2618ae50-9e26-4724-89f6-7fda1f105f42"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" output \"done.\"","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ba6f0b4d-aa70-4347-903e-46119eaa15e6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":16,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"beaeb52e-0825-47b9-ba7e-e09d6de4818c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" The user as","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"3408f5ca-fe05-4bbf-8ae0-b1bc4db97033"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"b5f0f099-f629-469e-a51b-bcb1abaf5f66"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ked me","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"32b263d1-ff54-48f3-a61d-96e98eddce23"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":22,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"581160fb-90e0-4831-b087-d702a7a42fa4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" to end my answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"af0f7710-cb0d-4192-85b6-2a458a17a463"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1ea97064-de2c-4b80-9f32-09ce3a9ce60b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"er with the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ad449330-cf10-4919-b4a0-9f510c259d38"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"9c7d8148-ced4-4647-bdb0-fca91d88aab9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" word BAN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2e4fed14-2110-4d2c-81d0-033f66954ed6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":29,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"dea229d8-9c12-4bf9-9cea-bf9813d41840"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"AN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"a4c1bb86-c884-4f6b-b752-3d57bbb36b1c"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":31,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1cbe8e9c-f44c-4dfb-b6e0-8032d35991db"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"A, which","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0a79f76a-a558-4de1-8323-7547d8628d28"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1961a504-ee75-484f-9c2d-8418496ff795"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" is a har","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"5fa188a2-6e70-4af5-8900-13c30c78c7ad"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":7,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a4d053b7-4485-4d18-8fd2-2354b2a22310"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"mless request, and there's a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"d734fe28-ce41-4002-ad2f-ea0dbc0857a0"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"7fa6189b-3633-4814-9755-a93619616466"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" note","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6dfd60d4-172b-456e-bb66-4f2d6c966233"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":45,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"4aa94d3f-16be-48dc-aa05-1a85105921bb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" about","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"9eb2805d-f684-40ee-b368-468facc4890a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"992053c7-e234-4d72-9c11-d00786dd2c52"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" repl","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"10f0c715-33ad-44fc-8818-7d1a4549fef3"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":49,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e1dad1ff-ec95-4ce1-b07b-b3b42c5f0a15"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ying in","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"244ce6fc-4dfd-4f6e-abf5-57f860663fdc"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":54,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"6f4e3a68-8a38-4ef1-a1d8-5d16b0bdb9e0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" Chinese per inst","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6fce552c-bfa4-4705-b50e-1e162b487f9d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":58,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"491e90c9-da11-4f2f-96d1-2e6c501a13b9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ructions, but","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"cee9edc1-dac1-4997-9b0e-a64e6cc17173"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":61,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2ad92491-7893-4f66-9f8c-8e0c49a0dd21"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" the user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0d10f6b1-daf3-4c40-92cc-78a3b7addc0d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":65,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"48d2ff82-0a78-43f7-bd6e-41170fd9be53"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"rote in English—","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"7af06734-f004-4264-aa76-0e5404fb1da7"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":66,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a607027c-4b06-467b-bd39-99a40085c05b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"I","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f651bfee-b7bb-4d2f-8872-bc43aff55c2b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":72,"estimated_tokens_delta":6,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"862b7d4a-8d66-48ce-a954-764541537982"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"'ll decide how to handle","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f9a8266d-7203-49f1-b14e-cdbcd5311bda"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":75,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"c5bc3ec1-229c-4acc-8a9a-b1184be9a1bf"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" that bal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1ea067e9-fbb8-4685-a217-e42170c35740"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":80,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"ce143939-c780-4938-ba2c-f6a54b8f4a6f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ance while including","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"77668dd2-c3ad-4df5-87a3-4b76a2219c65"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":81,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"0475f779-b12b-4ae0-a42a-4ae723a6d468"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"49727b38-d58a-4ad0-9728-aa4bc223b54d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":86,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"02f8ee0c-36d8-4de5-af74-fe7d19969366"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA at the end.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2adc15b2-5b1c-4add-b3ad-1ceaaa665bae"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":87,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"eb0ae205-deb6-4b79-9726-98fd9d1d533c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"40e6df26-1321-45ea-8ca5-9d96ca00087b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":287,"estimated_tokens_delta":200,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"57a445b0-9671-4073-89c6-f72835125be3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"aaf131b8-99e0-4fd9-9169-00be0b4e360a"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The sleep task completed with output \"done.\" The user asked me to end my answer with the word BANANA, which is a harmless request, and there's a note about replying in Chinese per instructions, but the user wrote in English—I'll decide how to handle that balance while including BANANA at the end.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","thinking_duration_ms":3423,"timestamp":"2026-10-28T13:20:09.346Z","type":"assistant","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"ecaa1288-7581-48ad-9c59-89e4bb9f063f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"549a0ef9-e0b3-40af-bb4a-8aba4c08eb8d"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d3049aaf-53af-4878-b273-68835033ff92"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"命","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"4a3271f3-0c7d-427c-9407-c610ad454b15"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"令输出为 `done`","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"3558f94f-6fcb-4c7a-96a5-6f6e415a5f93"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"。\n\nB","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fea97b73-1f25-4f88-94db-0f0fdd401d2b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"ANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"303a047a-fc87-48ea-9524-e102e112b10a"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"命令输出为 `done`。\n\nBANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:09.358Z","type":"assistant","uuid":"73a78906-d0d9-432d-b1d7-a34ac4d05707"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d665c80a-e37f-476e-ac86-e12d44f26fad"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"46798358-6519-4878-af21-22006f465f53"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fe0e0673-335a-41a0-b7c2-7b5d78e99739"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":7859,"duration_ms":5066,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1586,"first_request_input_tokens":33868,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":19042,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":19042,"cacheReadInputTokens":44758,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00453478,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":318,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":3932,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":3932,"cacheReadInputTokens":29934,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00119044,"inputTokens":2,"maxOutputTokens":128000,"outputTokens":209,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"num_turns":1,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"request_sent_wall_ms":1793193604397,"result":"命令输出为 `done`。\n\nBANANA","result_index":1,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_ms":59,"total_cost_usd":0.00453478,"ttft_ms":5008,"ttft_stream_ms":1563,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"8172897e-6304-4855-9480-f4e579da730f"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"completed","type":"command_lifecycle","uuid":"3c5163f4-90c0-4939-a3e5-aba1cf13bca3"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"idle","subtype":"session_state_changed","type":"system","uuid":"57c31a3d-da32-4a0c-9124-372c880779b7"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"e745940b-18ac-4078-b11e-72be2ae6401b","written_at":"2026-12-03T13:51:32.578Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"f85c6752-6469-4ce7-bbb2-0349f3fabfa8","written_at":"2026-12-03T13:51:32.579Z"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/992375695253/scratchpad","served_by_anthropic":true,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":69,"other_plugin":17,"user_settings":37},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":69,"own":69},"phase_start_ms":{"first_message_handle_ms":282,"first_message_read_ms":0,"grove_check_ms":187,"headless_post_load_ms":257,"headless_prologue_ms":186,"hooks_init_ms":178,"init_emit_ms":343,"initial_messages_load_ms":189,"input_ready_ms":0,"mcp_client_module_load_ms":192,"mcp_config_wait_ms":170,"mcp_connect_ms":182,"mcp_prewait_ms":283,"model_catalog_decision_ms":166,"node_boot_ms":0,"permission_context_ms":89,"pre_action_client_data_url_ms":84,"pre_action_init_ms":46,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":45,"pre_action_migrations_ms":84,"pre_action_ms":45,"print_import_ms":183,"prompt_submit_hooks_ms":301,"qe_plugin_skills_load_ms":341,"qe_system_prompt_ms":286,"sdk_mcp_update_ms":282,"settings_load_ms":44,"setup_file_watcher_ms":118,"setup_hooks_snapshot_ms":118,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":119,"setup_uds_dir_ms":96,"setup_uds_listen_ms":114,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":117,"skills_load_ms":95,"tools_commands_load_ms":130},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":282,"grove_check_ms":1,"headless_post_load_ms":1,"headless_prologue_ms":2,"hooks_init_ms":78,"init_emit_ms":1,"initial_messages_load_ms":68,"input_ready_ms":265,"mcp_client_module_load_ms":0,"mcp_config_load_ms":62,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":3,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":37,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":43,"print_import_ms":3,"prompt_submit_hooks_ms":37,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":4,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":31,"setup_release_notes_ms":8,"setup_uds_dir_ms":18,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":23,"setup_uds_publish_ms":0,"skills_load_ms":66,"tools_commands_load_ms":35},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305892295.906,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"488f600b-a63e-4882-99b1-8dcdfe076157","view_mode":"default","written_at":"2026-12-03T13:51:32.639Z"}}
|
||||
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"b6a40890-0e2f-40ab-afc9-8a609749d59e","written_at":"2026-12-03T13:51:32.642Z"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.21},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"rate_limit_event","uuid":"0cafd103-637f-4025-913d-3d23ec776453","written_at":"2026-12-03T13:51:33.412Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":1089,"type":"stream_event","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"1eba9396-f0bb-4de5-8627-5cebfc962d2a"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5abf5f-2492-4471-b355-ffb886685b08"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"3df5ecdd-e701-43ab-8ad3-90428c0a9bf4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a78c66ea-06f0-4c08-93c3-073ac79ce208"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":3,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58e5f0b8-1cae-4e6e-8142-28c83c20d09c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a66bf075-7a36-4bb4-9b94-090567a1047e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c1baabcf-b72e-438b-8b98-42b628a6c14b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ants a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"25f84cb1-9180-49b0-b722-0ae6617e00f5"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":11,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"9d1b3935-0637-45ca-a613-f1d02b08bf36"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" Bash command run. The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"de8666db-803f-4a33-8cb2-9faa68ff3e2a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"e0d0e6f0-dad3-4075-95d3-cf993ac621d9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" session","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"85784fb7-e5a4-4e17-acb8-2018e82e8458"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"962c83d1-069c-4ff4-b27f-1199d1b3d1b9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"-start hook points","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd405da7-abb7-443d-b309-ac6e805014ed"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":19,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c77e142c-8284-48f4-b67f-24f6fd1cc99b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" to","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"4957baf5-5e7a-4e23-bfe6-7bd1be56cee1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":24,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"2f3e6875-f0b9-4da6-806b-6420f8e11801"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ward skills, but n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ec0306de-6581-4dcb-8ef0-8bc9a2dffe5b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"08432ff1-c798-4640-bb4e-9c6bcb1fa879"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"othing here cal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"934bdb11-4eac-4db8-ba78-d751a132767a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":33,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b68b320e-d34a-4dd2-a52f-d4eb23b6e631"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ls for one, so I'll","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"1a0911c3-5d56-4df6-a490-ca853de74fe0"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":40,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"a0659fe6-3f44-4ee7-8f28-86561a981c00"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" just run the command direct","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"d243b5f8-2ad4-4137-abc0-993b12b30faf"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"0ff88c48-df4d-4fb0-9e10-aad67ea6f912"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ly.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"43859418-f19d-4dab-b439-e24db14015f1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":42,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"bcb9947d-4522-4206-bc6c-2fe20b0ee3f0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"480e67e5-6243-4a07-80dc-5e7218eea10d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":198,"estimated_tokens_delta":156,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"72763f2b-38bb-45f8-b9b4-6dce76fe87dd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2c35aff5-f8f1-423d-ab16-a50fe7f92d2c"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The user wants a Bash command run. The session-start hook points toward skills, but nothing here calls for one, so I'll just run the command directly.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1155,"timestamp":"2026-12-03T13:51:35.067Z","type":"assistant","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"f53249a7-87bb-48d3-8a4d-46fb2bc373c3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"50eafebf-1675-454d-b48d-4c33f9c46fd0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{},"name":"Bash","type":"tool_use"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"df423477-fdd3-40b4-bd3f-a6e5e2f4285a"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2840ddf3-7a52-45a6-bcee-28d02c695ce1"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"{\"command\": \"sleep 3 && ech","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"f279d761-fe64-4811-ba7a-d3389c7fa1d6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"o done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2d7cc471-fe87-49cc-975e-5aefe894bd35"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"77a255b8-8924-4cd2-8239-13d56352e157"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"leep 3 seconds","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5ddf158c-a8ed-475e-b425-4d6aa69d9216"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"8c902fdc-adb0-4db8-91fd-a3c9f799193b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"1019a3dc-64e5-4166-981a-f57347563c32"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:35.072Z","type":"assistant","uuid":"717bc1de-feb1-41aa-81d7-3ac47c772112","wire_tool_inputs":{"toolu_012tPQXDR9Kw59zBCFJqSuXP":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"149df489-36d1-4db3-8f19-ae26b6733dc9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"output_tokens":142,"type":"message"}],"output_tokens":142,"output_tokens_details":{"thinking_tokens":51}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"84156816-f10d-4dd6-8dca-f441fea39795"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"93925996-0953-4359-9383-f6db7885eb3f"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"58a87b31-0fab-415d-b450-0ed1f58ec0bc","written_at":"2026-12-03T13:51:35.084Z"}}
|
||||
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP"},"level":"warning","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"1bb27652-e9f7-4277-8138-8840aa03937c","written_at":"2026-12-03T13:51:35.090Z"}}
|
||||
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"task_started","task_id":"bzep4576h","task_type":"local_bash","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"9f3e9fb8-34cd-4f9c-95f9-b4a7af80eb18","written_at":"2026-12-03T13:51:39.785Z"}}
|
||||
{"from":"cli","msg":{"duration_ms":3020,"output_file":"","run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bzep4576h","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"63898564-4e95-4aa3-8e90-7fc67025ddce","written_at":"2026-12-03T13:51:39.802Z"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:39.838Z","tool_result_meta":[{"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"8103e7bc-d615-4e6a-9c31-c7d36db98577"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"93252284-65fe-4529-ba8f-485b97e6734a","written_at":"2026-12-03T13:51:39.892Z"}}
|
||||
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"1f01a672-b108-46e4-9637-57b2abd60258","written_at":"2026-12-03T13:51:39.892Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":931,"type":"stream_event","uuid":"29de849c-06bb-40e5-a9ad-b70c2f061329"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"92b49174-c189-466f-ad5d-5eea3b3afc2e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b8ec03ca-333f-4fac-a597-c43aa181360f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"I need","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ab10276f-535b-4f19-948c-3f31c090a94e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":8,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"44beb4b3-366d-4725-8781-17a8ab0c2743"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" to make sure the answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"fa8db41b-008b-4779-8269-e3df396df9b2"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":10,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58821ddd-b1aa-437b-b6ea-120c4a781f6b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"er fin","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a4b2ec90-2589-4308-b773-1d95de4e39ab"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"11a853c1-af93-4d0d-b600-e7f2e51a3a16"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ishes with B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3a9a743b-6a39-4572-b86e-4b07355aad6c"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":17,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"42ca95a6-a59d-4e50-8633-8689136027ad"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA, and the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e1173332-7e42-470a-bba6-28348e046d10"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":21,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"1c94c3c4-4eba-42e7-a8a4-00c60bb98763"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" Bash result was","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"c9e62676-e267-4934-85f2-79d124d4bae8"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"03d96f9b-adf7-4f6f-b28b-d427db8b8630"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" just \"done.\" So","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bcbdb107-0d53-4872-a6d0-ea0443ab46a6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":26,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"383344f4-e9c7-4fc6-8156-2a455fc315d4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd677e6a-ccc0-460c-b78c-d146e412fdfc"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":27,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"95673280-0801-43f2-a343-0e1e2294440d"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" re","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3ceba820-e7a1-406d-85cc-4e737440db84"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"ec3fefec-de8f-49c3-832f-ee8cdb9098ba"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ply will start with \"Output:","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"479a0469-81c6-44ed-901f-3b5ba5919286"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":38,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f1187702-1431-4c3f-b55b-b5d6b6e1b4cf"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" done\" and close","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"256ff2f5-a3c1-4c39-ba87-85a6f8a66995"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"db91d155-3a27-4751-8f44-9f55e24a2d56"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" with BANANA on the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"96de0914-3708-4b8f-afcd-6b1834e0a46a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":46,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f315f874-841c-471a-aa95-c7b30c4ecca9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" last line.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5125ea-c014-4134-9967-bfc89d40f300"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"7be0f157-678f-462f-b2ed-f69ee1306d62"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e17e4edd-aef5-4819-ae50-94d9b359f5e9"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":199,"estimated_tokens_delta":152,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"344c71df-0721-4f7a-bf9d-a2c9ac2b0431"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5e790c6d-4323-451b-9dbf-9f36e94b59d0"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"I need to make sure the answer finishes with BANANA, and the Bash result was just \"done.\" So the reply will start with \"Output: done\" and close with BANANA on the last line.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1170,"timestamp":"2026-12-03T13:51:42.004Z","type":"assistant","uuid":"19f7c707-0b92-43f4-a1ff-6f6ba28c9158"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"66f6946c-8aa7-4893-8a3f-fc7c023ea3f6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"6bef1d9a-bcfa-42d8-b3fa-865bbe31804e"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"The command print","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5866afb3-f9f8-42ba-9ae6-928e88f63709"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"ed `done`.","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"22c7b7dc-dfa8-49c6-a931-a2a5f179eebe"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":" BANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"265276d2-0f17-4bd8-8719-b6c0464079fc"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"The command printed `done`. BANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:42.006Z","type":"assistant","uuid":"4edeb5e3-ae9c-4e64-ab43-dd864db6636c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"950b3a05-26db-4a0b-bb6e-62d584a38638"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":72,"output_tokens_details":{"thinking_tokens":58}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"3fb8dfd0-35eb-49ff-a0f9-94c6cff59bcd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"eafb6e94-6aeb-4c20-929f-6d5dc4f8df6a"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"e5548a7e-c304-42d1-a536-2e123ebd58d4","written_at":"2026-12-03T13:51:42.067Z"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"begun_message_ids":["msg_011CheuFeb6zou7Nmj7hYFnf","msg_011CheuGALWJsYSxwR2j7F3W"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":4974,"duration_ms":9488,"fast_mode_state":"off","first_content_frame_ms":1332,"first_request_cache_read_input_tokens":26096,"first_request_input_tokens":42859,"input_attachments_detail":{"ambient_start_ms":1,"ambient_wait_ms":5,"cpu_ms":15,"major_faults":0,"producers":44,"prompt_producers_ms":0,"render_ms":0,"setup_ms":0,"slowest_producer":"deferred_tools_delta","slowest_producer_ms":6,"token_counts":0},"is_error":false,"message_normalization_detail":{"after_ms":0,"before_ms":0,"images_ms":0,"messages":19,"normalize_ms":0,"other_ms":1,"post_process_ms":0,"wire_messages":2},"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"process_turn_index":0,"queued_turn_count":0,"request_build_detail":{"cache_break_record_ms":1,"headers_ms":0,"other_ms":0,"plans_ms":0,"record_attempt_ms":0,"records_ms":0,"retry_setup_ms":0,"sent_build_cache_breakpoints_ms":0,"sent_build_ms":1,"sent_build_safety_context_ms":0,"sent_build_surrogate_scan_ms":0,"system_ms":0},"request_sent_wall_ms":1796305892823,"result":"The command printed `done`. BANANA","result_index":0,"safety_stops":0,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_cpu_ms":107,"time_to_request_loop_lag_ms":1,"time_to_request_major_faults":1,"time_to_request_ms":243,"time_to_request_phases_ms":{"autocompact":1,"client_creation":2,"conversation_append":1,"engine_pickup":1,"init_frame_send":1,"init_message":2,"input_attachments":8,"input_hooks":37,"loop_entry":1,"message_normalization":1,"message_prep":1,"model_config_wait":0,"model_gates":163,"other":2,"process_user_input":2,"query_setup":0,"request_announcements":3,"request_build":2,"resume_other":0,"system_prompt":5,"tool_pool_refresh":1,"tool_schema_build":8,"transcript_persist":1},"tool_schema_build_detail":{"after_ms":0,"betas_ms":0,"new_schemas":13,"other_ms":0,"placement_ms":2,"render_ms":3,"tools":13,"waits_ms":3},"total_cost_usd":0.0067110300000000015,"ttft_ms":2487,"ttft_stream_ms":1331,"turn_start_resume_kind":"none","type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":28926,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":28926,"cache_read_input_tokens":68953,"fallback_credit":null,"inference_geo":"global","input_tokens":4,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":214,"output_tokens_details":{"thinking_tokens":109},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"d3f210c9-67ad-4ec5-b122-3d4477ae65b5","written_at":"2026-12-03T13:51:42.069Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"32e0888f-d2b7-4721-bc7c-6c5320d3c99c","written_at":"2026-12-03T13:51:42.070Z"}}
|
||||
@@ -0,0 +1,34 @@
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","f782ff38-9bfe-4bd7-a857-f3cb10b38bcf"]}
|
||||
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
|
||||
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 5 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"750456ba-c54c-493b-bb61-40a9d825a457"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"b57b173d-a184-4e10-8ac6-46bd57c905b2","written_at":"2026-12-03T13:52:52.103Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"started","type":"command_lifecycle","uuid":"cd26e730-c57b-49c0-bfed-0ed2202ba6f5","written_at":"2026-12-03T13:52:52.104Z"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/443805216073/scratchpad","served_by_anthropic":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":79,"other_plugin":23,"user_settings":51},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":79,"own":79},"phase_start_ms":{"first_message_handle_ms":299,"first_message_read_ms":0,"grove_check_ms":193,"headless_post_load_ms":273,"headless_prologue_ms":192,"hooks_init_ms":184,"init_emit_ms":361,"initial_messages_load_ms":196,"input_ready_ms":0,"mcp_client_module_load_ms":200,"mcp_config_wait_ms":175,"mcp_connect_ms":188,"mcp_prewait_ms":300,"model_catalog_decision_ms":170,"node_boot_ms":0,"permission_context_ms":90,"pre_action_client_data_url_ms":84,"pre_action_init_ms":45,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":44,"pre_action_migrations_ms":84,"pre_action_ms":44,"print_import_ms":189,"prompt_submit_hooks_ms":319,"qe_plugin_skills_load_ms":360,"qe_system_prompt_ms":302,"sdk_mcp_update_ms":299,"settings_load_ms":43,"setup_file_watcher_ms":119,"setup_hooks_snapshot_ms":119,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":120,"setup_uds_dir_ms":97,"setup_uds_listen_ms":116,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":119,"skills_load_ms":96,"tools_commands_load_ms":132},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":299,"grove_check_ms":2,"headless_post_load_ms":1,"headless_prologue_ms":3,"hooks_init_ms":89,"init_emit_ms":1,"initial_messages_load_ms":77,"input_ready_ms":280,"mcp_client_module_load_ms":0,"mcp_config_load_ms":67,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":2,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":39,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":45,"print_import_ms":3,"prompt_submit_hooks_ms":38,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":5,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":32,"setup_release_notes_ms":9,"setup_uds_dir_ms":19,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":24,"setup_uds_publish_ms":0,"skills_load_ms":69,"tools_commands_load_ms":38},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305971804.1318,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"4614d51b-c114-4e3a-87c1-474dd3221ccb","view_mode":"default","written_at":"2026-12-03T13:52:52.166Z"}}
|
||||
{"from":"cli","msg":{"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","status":"requesting","subtype":"status","type":"system","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"1334ad42-52e2-4940-a881-df02701bbce2","written_at":"2026-12-03T13:52:52.168Z"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.22},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"rate_limit_event","uuid":"2d31cd09-90af-4542-9ab8-d6d35208343a","written_at":"2026-12-03T13:52:52.848Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","thinking_display":"summarized","ttft_ms":870,"type":"stream_event","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"a07fd809-d225-4ae9-8a9a-1cfcd3ba452b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"d87d4b0c-0817-44f3-ba3d-506b145416eb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"7ebaa4fa-4334-42cd-87b9-86efb45b06fd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"{\"command\": \"sleep 5","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"92f03d38-e933-444a-af9e-5d97a3bc17e1"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"156dfb71-8647-402b-81f1-d28209de7f6b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f2218947-8767-4812-b6e9-5081d444668e"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"leep 5 seconds","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"645079d4-6f4f-403c-aef0-add49e320bdb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"fc1582cb-4fe7-4747-b65a-5d57351c1749"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"8de2ab6a-1c5f-43be-99c5-accf562bded5"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuMVa2bRTBYmxzHrdZU","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:53.341Z","type":"assistant","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"543df181-f94c-4c59-8a54-6790d7c146fe","wire_tool_inputs":{"toolu_013cYTr5SPmttma9grssUDvs":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"}}}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"c95ced13-7ba7-4081-96dc-72e2e1ee9c67"}}
|
||||
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs"},"level":"warning","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"c5ce69e8-b5c8-4e04-b6af-b1a4d9760a3d","written_at":"2026-12-03T13:52:53.356Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f1c31fc2-e095-4a52-a92c-752feb90d83c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"5fd7d71c-5822-414a-b3e1-d11395fd7022"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee"}}
|
||||
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"d4038320-e65f-4937-b14c-8948234e08c4","written_at":"2026-12-03T13:52:55.103Z"}}
|
||||
{"from":"shim","msg":{"request":{"cancel_queued":true,"subtype":"interrupt"},"request_id":"req_3","type":"control_request"}}
|
||||
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"24e8c7aa-31e8-455f-a456-12ee15e0e8f9","written_at":"2026-12-03T13:52:55.604Z"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_3","response":{"cancelled":["6e50c1f5-335e-4d89-a2ef-725e845b57ee"],"still_queued":[]},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed. Correction to the text above: this call was stopped while running, not refused before it ran. It may have run in part or in full, and its changes may have been written. No permission prompt was involved. Work it started elsewhere (a remote command, a background process) may still be running, so check before starting the same work again. The instruction to stop and wait still stands.","is_error":true,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.608Z","tool_result_meta":[{"id":"toolu_013cYTr5SPmttma9grssUDvs","non_execution_kind":"user-rejected"}],"tool_use_result":"User rejected tool use","type":"user","uuid":"087df73f-b2fe-42d9-9de4-f3fab77aefe0"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"text":"[Request interrupted by user for tool use]","type":"text"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.610Z","type":"user","uuid":"900c03e1-b662-4e5f-aaf6-384263031910"}}
|
||||
{"from":"cli","msg":{"begun_message_ids":["msg_011CheuMVnw6EQjt4etKk278"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":1721,"duration_ms":3506,"errors":["[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"],"fast_mode_state":"off","is_error":true,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":3,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"result_index":0,"safety_stops":0,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"error_during_execution","terminal_reason":"aborted_tools","total_cost_usd":0.00340499,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"5c62e1de-fdfc-44f7-ae20-cd70b87590e5","written_at":"2026-12-03T13:52:55.613Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","idle":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"53cf7918-cf6e-4c94-984c-8401081fa93e","written_at":"2026-12-03T13:52:55.615Z"}}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"version": 2,
|
||||
"plugins": {
|
||||
"evidence-plugin@evidence-mkt": [
|
||||
{
|
||||
"scope": "user",
|
||||
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
|
||||
"version": "1.2.3",
|
||||
"installedAt": "2026-11-30T21:50:25.665Z",
|
||||
"lastUpdated": "2026-11-30T21:50:25.665Z",
|
||||
"gitCommitSha": "1111111111111111111111111111111111111111"
|
||||
},
|
||||
{
|
||||
"scope": "project",
|
||||
"projectPath": "$WORKSPACE",
|
||||
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
|
||||
"version": "1.2.3",
|
||||
"installedAt": "2026-11-30T21:50:25.665Z",
|
||||
"lastUpdated": "2026-11-30T21:50:25.665Z",
|
||||
"gitCommitSha": "1111111111111111111111111111111111111111"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
[marketplaces.evidence-mkt]
|
||||
source_type = "local"
|
||||
source = "$HOME/.codex/.tmp/marketplaces/evidence-mkt"
|
||||
|
||||
[plugins."evidence-plugin@evidence-mkt"]
|
||||
enabled = false
|
||||
@@ -0,0 +1,19 @@
|
||||
// This file is managed automatically.
|
||||
{
|
||||
"installedPlugins": [
|
||||
{
|
||||
"name": "evidence-plugin",
|
||||
"marketplace": "evidence-mkt",
|
||||
"installed_at": "2026-11-30T21:50:25.665Z",
|
||||
"enabled": true,
|
||||
"version": "1.2.3",
|
||||
"cache_path": "$HOME/.copilot/installed-plugins/evidence-mkt/evidence-plugin",
|
||||
"source": {
|
||||
"source": "github",
|
||||
"repo": "acme/plugins",
|
||||
"sha": "1111111111111111111111111111111111111111",
|
||||
"path": "plugins/evidence-plugin"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"evidence-extension": {
|
||||
"overrides": [
|
||||
"$HOME/*",
|
||||
"!$WORKSPACE/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,7 @@ pub(crate) fn stream_batched<T>(
|
||||
}
|
||||
}
|
||||
flush(&mut batch, on_batch);
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
Ok((lines.finish(cancel)?.success(), stderr_tail))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
|
||||
@@ -17,12 +17,13 @@ pub use launch_resources::process_launch_resources;
|
||||
pub use modules::record_module_build;
|
||||
pub use single::{
|
||||
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
|
||||
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
|
||||
single_file_classpath, single_file_target,
|
||||
has_gradle_file_target, javac_step, maven_system_classpath, module_classpath, module_classpath_without_build,
|
||||
module_classpaths, single_file_classpath, single_file_target,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
|
||||
StructureBuildContext, StructureJdk, StructureRoots, artifact_file, artifact_output, language_release,
|
||||
structure_build, structure_build_war, structure_compile_file_plan, structure_outputs, structure_plan,
|
||||
structure_war_plan, structure_web_artifacts,
|
||||
};
|
||||
pub use tsc_watch::{tsc_watch, tsc_watch_roots};
|
||||
pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
@@ -358,16 +359,14 @@ pub(super) fn maven_steps(
|
||||
};
|
||||
// The reactor root containing the module builds it with what it depends on (`-pl … -am`).
|
||||
let rel = rel_str(root, module);
|
||||
if !m.projects.iter().any(|p| p.dir == rel) {
|
||||
let Some(target) = m.projects.iter().find(|p| p.dir == rel) else {
|
||||
return Err(IdeError::not_found("no linked Maven project found for module"));
|
||||
}
|
||||
};
|
||||
let top = maven_reactor(m, &rel).ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
if module == top_dir {
|
||||
return Ok(vec![step(top, &[])]);
|
||||
if let Some(pl) = maven::module_selector(root, top, target) {
|
||||
return Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])]);
|
||||
}
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or(rel);
|
||||
Ok(vec![step(top, &["-pl".into(), pl, "-am".into()])])
|
||||
Ok(vec![step(top, &[])])
|
||||
}
|
||||
|
||||
fn gradle_steps(root: &Path, model: &BuildModel, kind: BuildKind, module: Option<&Path>) -> IdeResult<Vec<BuildStep>> {
|
||||
@@ -421,13 +420,14 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
}
|
||||
|
||||
/// CLion's Build Project for a CMake project: configures the build directory when it has no
|
||||
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per
|
||||
/// `CMakeCache.txt` or no File API reply yet, then `cmake --build` (`--clean-first` to rebuild), one job per
|
||||
/// logical CPU unless the profile's build arguments choose a count. The directory and
|
||||
/// options come from the CMake profile; without one, a configured directory of the project
|
||||
/// (the first by name), else `build`, as the generated run configurations use.
|
||||
fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec<BuildStep> {
|
||||
let build_dir = match profile {
|
||||
Some(p) if !p.build_dir.trim().is_empty() => p.build_dir.trim().to_owned(),
|
||||
Some(p) if p.build_type.is_empty() => "cmake-build-default".into(),
|
||||
Some(p) => format!("cmake-build-{}", p.build_type.to_lowercase()),
|
||||
None => {
|
||||
let mut configured: Vec<String> = std::fs::read_dir(dir)
|
||||
@@ -444,18 +444,49 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
|
||||
let build_type = profile.map_or("Debug", |p| p.build_type.as_str());
|
||||
let env = profile.map(|p| p.env.clone()).unwrap_or_default();
|
||||
let mut steps = Vec::new();
|
||||
if !dir.join(&build_dir).join("CMakeCache.txt").is_file() {
|
||||
let mut configure = BuildStep::new("cmake", &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
|
||||
if let Some(p) = profile.filter(|p| !p.generator.trim().is_empty()) {
|
||||
configure.args.extend(["-G".into(), p.generator.clone()]);
|
||||
}
|
||||
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
|
||||
let preset = profile.and_then(|p| p.preset.as_ref());
|
||||
// The profile's toolchain may bring its own cmake.
|
||||
let cmake = profile.and_then(|p| p.cmake_program.as_ref()).map_or("cmake".into(), |c| c.to_string_lossy());
|
||||
let cmake = cmake.as_ref();
|
||||
let build_path = dir.join(&build_dir);
|
||||
// Configured without the File API queries (by another tool, or before they were written):
|
||||
// configure again so the targets, and their run configurations, become known.
|
||||
let fresh = !build_path.join("CMakeCache.txt").is_file();
|
||||
if fresh || !build_path.join(ide_core::cmake_file_api::REPLY).is_dir() {
|
||||
// Best effort: without the queries the build still runs, only the targets stay unknown.
|
||||
let _ = ide_core::cmake_file_api::write_queries(&build_path);
|
||||
let mut configure = match preset {
|
||||
// The preset sets the generator and cache variables.
|
||||
Some(preset) => BuildStep::new(cmake, &["--preset", &preset.configure], dir, Format::Gcc),
|
||||
None => {
|
||||
let mut configure = BuildStep::new(cmake, &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
|
||||
// A configured directory keeps its generator (CMake refuses another one) and,
|
||||
// without a profile, its build type.
|
||||
if let Some(p) = profile.filter(|p| fresh && !p.generator.trim().is_empty()) {
|
||||
configure.args.extend(["-G".into(), p.generator.clone()]);
|
||||
}
|
||||
if fresh || profile.is_some() {
|
||||
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
|
||||
}
|
||||
configure
|
||||
}
|
||||
};
|
||||
configure.args.push("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".into());
|
||||
configure.args.extend(profile.map(|p| p.cmake_args.clone()).unwrap_or_default());
|
||||
configure.env = env.clone();
|
||||
steps.push(configure);
|
||||
}
|
||||
let mut build = BuildStep::new("cmake", &["--build", &build_dir, "--config", build_type], dir, Format::Gcc);
|
||||
let mut build = match preset.and_then(|p| p.build.as_deref()) {
|
||||
Some(build) => BuildStep::new(cmake, &["--build", "--preset", build], dir, Format::Gcc),
|
||||
None => {
|
||||
let mut build = BuildStep::new(cmake, &["--build", &build_dir], dir, Format::Gcc);
|
||||
// CLion's "Default" build type: no configuration at all.
|
||||
if !build_type.is_empty() {
|
||||
build.args.extend(["--config".into(), build_type.into()]);
|
||||
}
|
||||
build
|
||||
}
|
||||
};
|
||||
if kind == BuildKind::Rebuild {
|
||||
build.args.push("--clean-first".into());
|
||||
}
|
||||
@@ -538,6 +569,27 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
Ok(vec![step])
|
||||
}
|
||||
|
||||
/// `dotnet format` of a solution or C# / VB project file; `verify` only reports what it would
|
||||
/// change and fails when there is anything.
|
||||
pub fn dotnet_format_plan(file: &Path, verify: bool) -> IdeResult<BuildPlan> {
|
||||
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
let (Some(dir), Some(name), true) =
|
||||
(file.parent(), file.file_name(), matches!(ext.as_str(), "sln" | "slnx" | "csproj" | "vbproj"))
|
||||
else {
|
||||
return Err(IdeError::invalid("dotnet format needs a solution or a C# / VB project"));
|
||||
};
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
|
||||
}
|
||||
let name = name.to_string_lossy();
|
||||
// Verbose output names the files it changed; verifying changes none.
|
||||
let options: &[&str] = if verify { &["--verify-no-changes"] } else { &["--verbosity", "normal"] };
|
||||
let mut step = BuildStep::new("dotnet", &["format", &name], dir, Format::Msbuild);
|
||||
step.args.extend(options.iter().map(|o| (*o).to_owned()));
|
||||
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
|
||||
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet format {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
let script = has_build_script(dir);
|
||||
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
|
||||
@@ -926,17 +978,7 @@ pub fn has_non_java_sources(module: &Path) -> bool {
|
||||
}
|
||||
|
||||
fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject) -> Vec<&'a maven::MavenProject> {
|
||||
let mut projects = Vec::new();
|
||||
let mut pending = vec![top];
|
||||
let mut seen = HashSet::new();
|
||||
while let Some(p) = pending.pop() {
|
||||
if !seen.insert(&p.pom) {
|
||||
continue;
|
||||
}
|
||||
projects.push(p);
|
||||
pending.extend(m.projects.iter().filter(|child| p.modules.contains(&child.pom)));
|
||||
}
|
||||
projects
|
||||
maven::reactor_projects(m, top)
|
||||
}
|
||||
|
||||
/// A step running Maven, its output parsed as Maven's.
|
||||
@@ -962,7 +1004,7 @@ pub(crate) fn reactor_projects_of<'a>(
|
||||
}
|
||||
|
||||
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
|
||||
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
|
||||
maven::reactor_for_dir(m, module)
|
||||
}
|
||||
|
||||
/// Launch module first, followed by its upstream modules in the same Maven reactor.
|
||||
@@ -986,7 +1028,7 @@ fn maven_launch_projects<'a>(
|
||||
}
|
||||
projects.push(p);
|
||||
for dep in &p.dependencies {
|
||||
if !dep.resolved() || (dep.scope == "test" && (!test || p.pom != start.pom)) {
|
||||
if !dep.resolved() || dep.scope == "system" || (dep.scope == "test" && (!test || p.pom != start.pom)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(upstream) = reactor.iter().find(|u| {
|
||||
@@ -1659,6 +1701,15 @@ mod tests {
|
||||
"an unconfigured project is configured first"
|
||||
);
|
||||
write(&cm, "cmake-build-release/CMakeCache.txt", "");
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
p.steps[0].args,
|
||||
["-S", ".", "-B", "cmake-build-release", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"],
|
||||
"configured again, as it was, when it has no File API reply"
|
||||
);
|
||||
assert!(cm.join("cmake-build-release/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file());
|
||||
std::fs::create_dir_all(cm.join("cmake-build-release").join(ide_core::cmake_file_api::REPLY)).unwrap();
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
@@ -1694,6 +1745,33 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]);
|
||||
let preset = CMakeProfile {
|
||||
build_dir: "out/dev".into(),
|
||||
preset: Some(ide_core::settings::CMakePresetRef {
|
||||
configure: "dev".into(),
|
||||
build: Some("dev-build".into()),
|
||||
..Default::default()
|
||||
}),
|
||||
..CMakeProfile::default()
|
||||
};
|
||||
let p = plan(
|
||||
&cm,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
None,
|
||||
Some(std::slice::from_ref(&preset)),
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
[
|
||||
"--preset dev -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
|
||||
format!("--build --preset dev-build {jobs}")
|
||||
],
|
||||
"a preset profile configures and builds with its presets"
|
||||
);
|
||||
|
||||
let siblings = tmp.path().join("siblings");
|
||||
write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
|
||||
@@ -1993,6 +2071,34 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sibling_reactor_launch_uses_relative_module_selector() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(
|
||||
root,
|
||||
"parent/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"common/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId></project>",
|
||||
);
|
||||
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
|
||||
let plan =
|
||||
launch_plan(root, &model, &root.join("app"), false, BuildKind::Build, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(plan.steps.len(), 1);
|
||||
assert_eq!(plan.steps[0].cwd, root.join("parent"));
|
||||
let pl = plan.steps[0].args.iter().position(|a| a == "-pl").unwrap();
|
||||
assert_eq!(&plan.steps[0].args[pl..pl + 3], &["-pl", "../app", "-am"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn external_launch_returns_upstream_outputs_and_blocks_failure_or_cancellation() {
|
||||
@@ -2162,4 +2268,60 @@ mod tests {
|
||||
assert_eq!(whole.steps[0].cwd, root);
|
||||
assert_eq!(whole.steps[0].args, ["build", "./..."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_format_runs_on_the_given_solution_or_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj", "App.fsproj", "A.cs"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj"] {
|
||||
let plan = super::dotnet_format_plan(&dir.path().join(name), false).unwrap();
|
||||
assert_eq!(plan.steps[0].args, ["format", name, "--verbosity", "normal"]);
|
||||
assert_eq!(plan.steps[0].cwd, dir.path());
|
||||
let verify = super::dotnet_format_plan(&dir.path().join(name), true).unwrap();
|
||||
assert_eq!(verify.steps[0].args, ["format", name, "--verify-no-changes"]);
|
||||
}
|
||||
for name in ["App.fsproj", "A.cs", "Missing.sln"] {
|
||||
assert!(super::dotnet_format_plan(&dir.path().join(name), false).is_err(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The real `dotnet format` (`-- --ignored`): verifying reports and changes nothing, formatting rewrites.
|
||||
#[test]
|
||||
#[ignore = "needs the .NET SDK"]
|
||||
fn dotnet_format_reports_and_rewrites_with_the_real_sdk() {
|
||||
let found = std::process::Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success());
|
||||
if !found {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for args in [
|
||||
&["new", "console", "-n", "App", "-o", "App"][..],
|
||||
&["new", "sln", "-n", "Sln", "--format", "slnx"],
|
||||
&["new", "sln", "-n", "Classic", "--format", "sln"],
|
||||
&["sln", "Sln.slnx", "add", "App/App.csproj"],
|
||||
&["sln", "Classic.sln", "add", "App/App.csproj"],
|
||||
] {
|
||||
assert!(std::process::Command::new("dotnet").args(args).current_dir(&root).status().unwrap().success());
|
||||
}
|
||||
let source = root.join("App").join("中 A.cs");
|
||||
let messy = "class A{void M( ){var x=1;}}\n";
|
||||
for target in ["Sln.slnx", "Classic.sln", "App/App.csproj"] {
|
||||
std::fs::write(&source, messy).unwrap();
|
||||
let run = |verify| {
|
||||
let plan = super::dotnet_format_plan(&root.join(target), verify).unwrap();
|
||||
super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap()
|
||||
};
|
||||
let verified = run(true);
|
||||
assert!(!verified.success, "{target}");
|
||||
let message = verified.messages.iter().find(|m| m.code.as_deref() == Some("WHITESPACE")).unwrap();
|
||||
assert!(message.path.as_ref().unwrap().ends_with("中 A.cs"), "{message:?}");
|
||||
assert_eq!(std::fs::read_to_string(&source).unwrap(), messy);
|
||||
assert!(run(false).success, "{target}");
|
||||
assert_ne!(std::fs::read_to_string(&source).unwrap(), messy);
|
||||
assert!(run(true).success, "{target}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,15 +72,19 @@ fn affected_projects(reactor: &[&maven::MavenProject], changed: &HashSet<String>
|
||||
/// `-pl` entries of the affected modules, relative to the reactor root the step
|
||||
/// runs in, sorted so the command line does not depend on the model's project
|
||||
/// order (Maven reorders the selection into its own reactor order anyway).
|
||||
fn selection(reactor: &[&maven::MavenProject], top_dir: &str, affected: &HashSet<String>) -> String {
|
||||
fn selection(
|
||||
root: &Path,
|
||||
top: &maven::MavenProject,
|
||||
reactor: &[&maven::MavenProject],
|
||||
affected: &HashSet<String>,
|
||||
) -> String {
|
||||
let mut entries: Vec<String> = reactor
|
||||
.iter()
|
||||
.filter(|p| affected.contains(&p.dir))
|
||||
.map(|p| {
|
||||
Path::new(&p.dir).strip_prefix(top_dir).unwrap_or(Path::new(&p.dir)).to_string_lossy().replace('\\', "/")
|
||||
})
|
||||
.filter_map(|p| maven::module_selector(root, top, p))
|
||||
.collect();
|
||||
entries.sort();
|
||||
entries.dedup();
|
||||
entries.join(",")
|
||||
}
|
||||
|
||||
@@ -130,8 +134,12 @@ pub(super) fn narrowed_maven_steps(
|
||||
if affected.len() >= reactor.len() || affected.contains(&top.dir) {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
let pl = selection(&reactor, &top.dir, &affected);
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
let pl = selection(root, top, &reactor, &affected);
|
||||
if pl.is_empty() {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(steps))
|
||||
@@ -405,4 +413,36 @@ mod tests {
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "solo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sibling_reactor_narrows_with_relative_module_selectors() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
write(
|
||||
root,
|
||||
"parent/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"common/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(root, "common/src/main/java/t/C.java", "package t; public class C {}");
|
||||
write(root, "app/src/main/java/t/A.java", "package t; public class A {}");
|
||||
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, "common/src/main/java/t/C.java", "package t; public class C { int x; }");
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "parent"));
|
||||
assert_eq!(pl_arg(&steps[0]), "../app,../common");
|
||||
assert!(steps[0].args.contains(&"-am".into()));
|
||||
}
|
||||
}
|
||||
@@ -143,8 +143,7 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe
|
||||
let module = subdir(root, &project.dir);
|
||||
let top = maven_reactor(m, &project.dir)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
|
||||
let pl = maven::module_selector(root, top, project).unwrap_or_default();
|
||||
// Test sources see the test classpath and compile into test classes.
|
||||
let test = is_test_source(&rel);
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
@@ -164,8 +163,7 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
|
||||
let top = maven_reactor(m, &project.dir)
|
||||
.ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?;
|
||||
let top_dir = subdir(root, &top.dir);
|
||||
let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default();
|
||||
let pl = maven::module_selector(root, top, project).unwrap_or_default();
|
||||
let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" });
|
||||
Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version })
|
||||
}
|
||||
@@ -180,6 +178,30 @@ pub fn find_javac(env: &BTreeMap<String, String>) -> String {
|
||||
exe.to_owned()
|
||||
}
|
||||
|
||||
/// Existing system-scope dependencies of this module. Maven resolves these from
|
||||
/// their local files and does not pass them transitively to reactor dependents.
|
||||
pub fn maven_system_classpath(root: &Path, model: &BuildModel, module: &Path) -> Vec<PathBuf> {
|
||||
let Some(maven) = &model.maven else { return Vec::new() };
|
||||
let module = root.join(module);
|
||||
maven
|
||||
.projects
|
||||
.iter()
|
||||
.find(|p| root.join(&p.dir) == module)
|
||||
.into_iter()
|
||||
.flat_map(|p| &p.system_paths)
|
||||
.filter(|p| p.is_file())
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn with_system_classpath(root: &Path, model: &BuildModel, module: &Path, classpath: String) -> String {
|
||||
let system = maven_system_classpath(root, model, module);
|
||||
if system.is_empty() {
|
||||
return classpath;
|
||||
}
|
||||
join_classpath(std::env::split_paths(&classpath).chain(system).map(|p| p.to_string_lossy().into_owned()))
|
||||
}
|
||||
|
||||
/// Dependency classpath of the module: existing reactor class directories plus
|
||||
/// `mvn dependency:build-classpath` (which resolves without compiling anything,
|
||||
/// so `-am` stays cheap). Entries are platform-separated (`;` on Windows).
|
||||
@@ -233,7 +255,7 @@ pub fn module_classpath_without_build(
|
||||
&& cached.version == CLASSPATH_CACHE_VERSION
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
return Ok(cached.classpath);
|
||||
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
|
||||
}
|
||||
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
|
||||
}
|
||||
@@ -270,7 +292,7 @@ pub fn module_classpaths(
|
||||
&& classpath_entries_exist(root, &cached.classpath)
|
||||
{
|
||||
if i == 0 {
|
||||
return Ok(cached.classpath);
|
||||
return Ok(with_system_classpath(root, model, &target.module, cached.classpath));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -298,7 +320,7 @@ pub fn module_classpaths(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(classpaths.into_iter().next().unwrap())
|
||||
Ok(with_system_classpath(root, model, &modules[0], classpaths.into_iter().next().unwrap()))
|
||||
}
|
||||
|
||||
/// A module whose classpath the Maven probe resolves, with its cache key and file.
|
||||
@@ -346,7 +368,8 @@ fn classpath(
|
||||
compile_first: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap())
|
||||
let classpath = classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap();
|
||||
Ok(with_system_classpath(root, model, &target.module, classpath))
|
||||
}
|
||||
|
||||
/// The classpath of each of `targets` (modules of one reactor) from one Maven probe.
|
||||
@@ -912,6 +935,64 @@ mod tests {
|
||||
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn system_jars_augment_maven_javac_and_launch_classpaths() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"pom.xml",
|
||||
r#"<project><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version>
|
||||
<packaging>pom</packaging><modules><module>app</module></modules>
|
||||
<properties><lib.dir>src/main/resources/lib</lib.dir></properties></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
r#"<project><parent><groupId>demo</groupId><artifactId>parent</artifactId><version>1</version></parent>
|
||||
<artifactId>app</artifactId>
|
||||
<properties><lib.file>${lib.dir}/offline.jar</lib.file></properties>
|
||||
<dependencies>
|
||||
<dependency><groupId>local</groupId><artifactId>offline</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${pom.basedir}/${lib.file}</systemPath></dependency>
|
||||
<dependency><groupId>local</groupId><artifactId>late</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}/late.jar</systemPath></dependency>
|
||||
<dependency><groupId>local</groupId><artifactId>directory</artifactId><version>1</version>
|
||||
<scope>system</scope><systemPath>${project.basedir}/${lib.dir}</systemPath></dependency>
|
||||
</dependencies></project>"#,
|
||||
);
|
||||
let jars = "app/src/main/resources/lib";
|
||||
write(&root, &format!("{jars}/offline.jar"), "");
|
||||
write(&root, "app/src/main/java/demo/Main.java", "class Main {}");
|
||||
// The scope-filtered Maven classpath can contain no dependencies.
|
||||
write(&root, "mvnw", "#!/bin/sh\nmkdir -p app/target\n: > app/target/ide-compile-cp.txt\n");
|
||||
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let cache = root.join("cache");
|
||||
let model = crate::load(&root, &cache, None);
|
||||
let module = root.join("app");
|
||||
let file = module.join("src/main/java/demo/Main.java");
|
||||
let jar = root.join(jars).join("offline.jar");
|
||||
let plan = compile_file_plan(&root, &model, &file).unwrap();
|
||||
assert!(plan.steps[0].args.windows(2).any(|arg| arg[0] == "-cp" && Path::new(&arg[1]) == jar));
|
||||
let cancel = CancellationToken::new();
|
||||
let cp = module_classpath(&root, &model, &module, false, None, &cache, &cancel).unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert_eq!(paths, [module.join("target/classes"), jar.clone()]);
|
||||
assert!(maven_system_classpath(&root, &model, &root).is_empty());
|
||||
|
||||
// Adding a previously absent jar or deleting an old one updates a no-build launch.
|
||||
fs::remove_file(jar).unwrap();
|
||||
write(&root, &format!("{jars}/late.jar"), "");
|
||||
fs::remove_file(root.join("mvnw")).unwrap();
|
||||
let cp = module_classpath_without_build(&root, &model, &module, false, &cache, &cancel).unwrap();
|
||||
let paths: Vec<_> = std::env::split_paths(&cp).collect();
|
||||
assert_eq!(paths, [module.join("target/classes"), root.join(jars).join("late.jar")]);
|
||||
}
|
||||
|
||||
/// Modules launched together resolve their classpaths in one Maven probe and leave
|
||||
/// the others' cached; a probe another module breaks still resolves the first one.
|
||||
#[cfg(unix)]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -234,9 +234,7 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
@@ -283,11 +281,28 @@ pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
entries.push(entry);
|
||||
i += 1;
|
||||
if wide {
|
||||
if i == count {
|
||||
return None;
|
||||
}
|
||||
entries.push(Entry::Empty);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let pool = Pool(entries);
|
||||
Some(Pool(entries))
|
||||
}
|
||||
|
||||
/// Reads the internal class name (e.g. `com/acme/Order$Line`) from `this_class`.
|
||||
pub fn class_file_name(data: &[u8]) -> Option<String> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
r.u2()?; // access_flags
|
||||
Some(pool.class(r.u2()?)?.to_owned())
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
let mut refs = BTreeSet::new();
|
||||
for entry in &pool.0 {
|
||||
match entry {
|
||||
|
||||
@@ -22,7 +22,7 @@ mod incremental;
|
||||
mod javac;
|
||||
mod model;
|
||||
|
||||
pub use classfile::ClassFile;
|
||||
pub use classfile::{ClassFile, class_file_name};
|
||||
pub use javac::{JavacPool, Reply, ServerKey};
|
||||
|
||||
use incremental::{ClassRecord, SetStamp, SetState};
|
||||
@@ -64,9 +64,300 @@ pub struct JavaBuildService {
|
||||
}
|
||||
|
||||
impl JavaBuildService {
|
||||
fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
|
||||
pub(crate) fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
|
||||
self.locks.lock().unwrap().entry(dir.to_path_buf()).or_default().clone()
|
||||
}
|
||||
|
||||
/// Compiles what changed in one source set (see [`incremental`]).
|
||||
pub fn compile_incremental(
|
||||
&self,
|
||||
set: &IncrementalSet<'_>,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
messages: &mut Vec<BuildMessage>,
|
||||
) -> IdeResult<IncrementalOutcome> {
|
||||
if set.clean {
|
||||
remove_classes(&set.output);
|
||||
let _ = std::fs::remove_dir_all(&set.generated_dir);
|
||||
let _ = std::fs::remove_file(&set.state_file);
|
||||
}
|
||||
let source_stamps: BTreeMap<PathBuf, FileStamp> =
|
||||
set.sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect();
|
||||
let previous = incremental::load_state(&set.state_file);
|
||||
let reactor: Vec<PathBuf> = set.upstream_states.iter().map(|(o, _)| o.clone()).collect();
|
||||
let stamp = SetStamp {
|
||||
options: set.options.clone(),
|
||||
libraries: set.libraries.iter().map(|e| (e.clone(), file_stamp(e))).collect(),
|
||||
reactor,
|
||||
processor_path: set.processor_path.iter().map(|p| (p.clone(), file_stamp(p))).collect(),
|
||||
java_home: set.java_home.clone(),
|
||||
};
|
||||
|
||||
// What the upstream outputs it compiles against changed since it last compiled.
|
||||
let mut upstream = BTreeMap::new();
|
||||
let mut upstream_changed = BTreeSet::new();
|
||||
let mut upstream_all = false;
|
||||
for (entry, up_state_file) in &set.upstream_states {
|
||||
let state = incremental::load_state(up_state_file);
|
||||
let generation = state.as_ref().map_or(0, |s| s.generation);
|
||||
upstream.insert(entry.clone(), generation);
|
||||
let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied();
|
||||
if recorded == Some(generation) {
|
||||
continue;
|
||||
}
|
||||
match (recorded, state.and_then(|s| s.changes_since(recorded?))) {
|
||||
(Some(_), Some(changed)) => upstream_changed.extend(changed),
|
||||
_ => upstream_all = true,
|
||||
}
|
||||
}
|
||||
|
||||
let had_state = previous.is_some();
|
||||
let previous = previous.unwrap_or_default();
|
||||
let mut changed: BTreeSet<PathBuf> = source_stamps
|
||||
.iter()
|
||||
.filter(|(path, stamp)| {
|
||||
previous.sources.get(*path) != Some(*stamp)
|
||||
|| previous.dirty.contains(*path)
|
||||
|| set.force.contains(*path)
|
||||
})
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
let removed: BTreeSet<PathBuf> =
|
||||
previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect();
|
||||
let mut from_scratch = !had_state
|
||||
|| previous.stamp != stamp
|
||||
|| upstream_all
|
||||
|| !set.output.is_dir()
|
||||
|| (!previous.success && previous.dirty.is_empty());
|
||||
if had_state && !from_scratch {
|
||||
for record in previous.classes.values() {
|
||||
if !record.file.is_file() {
|
||||
match &record.source {
|
||||
Some(src) if source_stamps.contains_key(src) => {
|
||||
changed.insert(src.clone());
|
||||
}
|
||||
Some(src) if removed.contains(src) => {}
|
||||
_ => {
|
||||
from_scratch = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
|
||||
return Ok(IncrementalOutcome { failed: false, compiled_files: 0, outputs_changed: false });
|
||||
}
|
||||
// Processors that aggregate (or name no originating source) can't be followed class by class.
|
||||
let has_changes = !changed.is_empty() || !removed.is_empty() || !upstream_changed.is_empty();
|
||||
let from_scratch =
|
||||
from_scratch || ((!previous.generated.is_empty() || !previous.unowned.is_empty()) && has_changes);
|
||||
|
||||
let mut state = SetState {
|
||||
stamp,
|
||||
sources: source_stamps.clone(),
|
||||
generation: previous.generation,
|
||||
upstream,
|
||||
classes: previous.classes,
|
||||
changes: previous.changes,
|
||||
..Default::default()
|
||||
};
|
||||
let mut api_changed = BTreeSet::new();
|
||||
let mut constants_changed = false;
|
||||
// Classes of removed sources go first, and count as changed.
|
||||
let gone: Vec<String> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect();
|
||||
let gone_empty = gone.is_empty();
|
||||
for name in gone {
|
||||
let record = state.classes.remove(&name).expect("listed");
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
constants_changed |= record.constants != incremental::NO_CONSTANTS;
|
||||
api_changed.insert(name);
|
||||
}
|
||||
let mut to_compile: BTreeSet<PathBuf> = if from_scratch || constants_changed {
|
||||
remove_classes(&set.output);
|
||||
for file in previous.generated.iter().chain(&previous.unowned) {
|
||||
let _ = std::fs::remove_file(file);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&set.generated_dir);
|
||||
state.classes.retain(|_, r| r.source.is_some());
|
||||
source_stamps.keys().cloned().collect()
|
||||
} else {
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
|
||||
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
|
||||
};
|
||||
std::fs::create_dir_all(&set.output)?;
|
||||
std::fs::create_dir_all(&set.generated_dir)?;
|
||||
|
||||
let total = source_stamps.len();
|
||||
let mut compiled: BTreeSet<PathBuf> = BTreeSet::new();
|
||||
let mut server = None;
|
||||
loop {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let batch: BTreeSet<PathBuf> = to_compile
|
||||
.iter()
|
||||
.filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s))
|
||||
.cloned()
|
||||
.collect();
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
// The classes the batch replaces: their files go first, so nothing stale is left.
|
||||
let replaced: BTreeMap<String, ClassRecord> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
|
||||
.map(|(n, r)| (n.clone(), r.clone()))
|
||||
.collect();
|
||||
for (name, record) in &replaced {
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
state.classes.remove(name);
|
||||
}
|
||||
let files: Vec<PathBuf> = batch.iter().cloned().collect();
|
||||
let noun = if total == 1 { "file" } else { "files" };
|
||||
let count = if files.len() == total {
|
||||
format!("{total} {noun}")
|
||||
} else {
|
||||
format!("{} of {total} {noun}", files.len())
|
||||
};
|
||||
on_event(BuildEvent::Step {
|
||||
command: format!("javac {} ({}, {count})", set.module_name, set.set_name),
|
||||
cwd: set.cwd.clone().into(),
|
||||
});
|
||||
if server.is_none() {
|
||||
let key = ServerKey { java_home: set.java_home.clone(), jvm_args: set.jvm_args.clone() };
|
||||
server = Some(self.servers.server(set.jar, &key)?);
|
||||
}
|
||||
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
|
||||
let result =
|
||||
server.as_ref().expect("started").compile(&set.options, &files, set.encoding, cancel, |reply| {
|
||||
match reply {
|
||||
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
|
||||
Reply::Generated { path, .. } => state.generated.push(path.clone()),
|
||||
Reply::OutputText { text } => {
|
||||
on_event(BuildEvent::Output { text: text.clone(), stderr: false })
|
||||
}
|
||||
Reply::Diagnostic { .. } => {
|
||||
if let Some(m) = diagnostic(reply) {
|
||||
on_event(BuildEvent::Output {
|
||||
text: message_text(&m),
|
||||
stderr: m.severity == Severity::Error,
|
||||
});
|
||||
on_event(BuildEvent::Message { message: m.clone() });
|
||||
messages.push(m);
|
||||
}
|
||||
}
|
||||
Reply::Done { .. } => {}
|
||||
}
|
||||
});
|
||||
if !matches!(result, Ok(true)) {
|
||||
for (path, _) in &written {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
// The next build starts from the state this one started from, with whatever this
|
||||
// one had to compile still to compile. Its earlier rounds' classes are not the
|
||||
// baseline: compared with them, the API and constant changes those rounds found
|
||||
// would never reach this set's dependents or the sets compiled against it.
|
||||
let mut retry = incremental::load_state(&set.state_file).unwrap_or_default();
|
||||
retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned());
|
||||
retry.success = false;
|
||||
let _ = model::write_json(&set.state_file, &retry);
|
||||
return result.map(|_| IncrementalOutcome {
|
||||
failed: true,
|
||||
compiled_files: compiled.len(),
|
||||
outputs_changed: false,
|
||||
});
|
||||
}
|
||||
// javac names sources as they were passed; other spellings are matched canonically,
|
||||
// and classes of sources outside the set (processors' output) are unowned.
|
||||
let canonical: HashMap<PathBuf, &PathBuf> =
|
||||
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
|
||||
let own = |source: PathBuf| -> Option<PathBuf> {
|
||||
if source_stamps.contains_key(&source) {
|
||||
return Some(source);
|
||||
}
|
||||
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
|
||||
};
|
||||
let mut fresh = BTreeMap::new();
|
||||
for (path, source) in written {
|
||||
let source = source.and_then(own);
|
||||
let class = (path.extension().is_some_and(|e| e == "class"))
|
||||
.then(|| std::fs::read(&path).ok())
|
||||
.flatten()
|
||||
.and_then(|bytes| classfile::parse(&bytes));
|
||||
match (class, source) {
|
||||
(Some(class), Some(source)) => {
|
||||
let (name, record) = ClassRecord::new(class, path, Some(source));
|
||||
fresh.insert(name, record);
|
||||
}
|
||||
_ => state.unowned.push(path),
|
||||
}
|
||||
}
|
||||
let round = incremental::diff(&replaced, &fresh);
|
||||
constants_changed |= round.constants;
|
||||
api_changed.extend(round.api.iter().cloned());
|
||||
state.classes.extend(fresh);
|
||||
compiled.extend(batch);
|
||||
if constants_changed {
|
||||
// Constants are copied into the classes that use them: compile the rest too.
|
||||
to_compile.extend(source_stamps.keys().cloned());
|
||||
continue;
|
||||
}
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
|
||||
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
|
||||
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
|
||||
}
|
||||
state.success = true;
|
||||
if !compiled.is_empty() || !api_changed.is_empty() {
|
||||
let changed =
|
||||
incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect());
|
||||
state.log(now_generation(), changed, !had_state || constants_changed);
|
||||
}
|
||||
model::write_json(&set.state_file, &state)?;
|
||||
Ok(IncrementalOutcome {
|
||||
failed: false,
|
||||
compiled_files: compiled.len(),
|
||||
outputs_changed: !compiled.is_empty() || !gone_empty,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Inputs for compiling one source set incrementally with the resident `javac` server.
|
||||
pub struct IncrementalSet<'a> {
|
||||
pub module_name: String,
|
||||
pub set_name: &'static str,
|
||||
pub cwd: PathBuf,
|
||||
pub sources: Vec<PathBuf>,
|
||||
pub output: PathBuf,
|
||||
pub options: Vec<String>,
|
||||
pub libraries: Vec<PathBuf>,
|
||||
/// Upstream `(output_dir, state_file)` pairs this set compiles against.
|
||||
pub upstream_states: Vec<(PathBuf, PathBuf)>,
|
||||
pub processor_path: Vec<PathBuf>,
|
||||
pub java_home: PathBuf,
|
||||
pub jvm_args: Vec<String>,
|
||||
pub encoding: Option<&'a str>,
|
||||
pub state_file: PathBuf,
|
||||
pub generated_dir: PathBuf,
|
||||
pub force: &'a BTreeSet<PathBuf>,
|
||||
pub jar: &'a Path,
|
||||
pub clean: bool,
|
||||
}
|
||||
|
||||
/// Result of compiling one source set incrementally.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct IncrementalOutcome {
|
||||
pub failed: bool,
|
||||
pub compiled_files: usize,
|
||||
pub outputs_changed: bool,
|
||||
}
|
||||
|
||||
/// One build of the IDE's Java build service.
|
||||
@@ -79,6 +370,8 @@ pub struct JavaBuild<'a> {
|
||||
/// Changes when the jar does, so models recorded by an older extension are prepared again.
|
||||
pub jar_version: &'a str,
|
||||
pub local_repo: Option<PathBuf>,
|
||||
/// Explicit Maven goals the project's settings allow the IDE to skip in compile phases.
|
||||
pub ignored_maven_compile_goals: &'a [String],
|
||||
pub service: &'a JavaBuildService,
|
||||
/// The JDK home that compiles for a release, when Maven's environment names none.
|
||||
pub jdk: &'a (dyn Fn(Option<u32>) -> Option<PathBuf> + Sync),
|
||||
@@ -250,15 +543,11 @@ fn java_sources(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<Vec<Pa
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `-g`, `-g:lines,vars` or `-g:none`, as maven-compiler-plugin passes them.
|
||||
fn debug_args(c: &CompilerConfig) -> Vec<String> {
|
||||
if c.debug == Some(false) {
|
||||
return vec!["-g:none".into()];
|
||||
}
|
||||
match c.debuglevel.as_deref().map(str::trim).filter(|l| !l.is_empty()) {
|
||||
Some(level) => vec![format!("-g:{level}")],
|
||||
None => vec!["-g".into()],
|
||||
}
|
||||
/// A javac debug-info option (`-g`, `-g:none`, `-g:lines,vars`). The IDE's build always
|
||||
/// compiles with `-g`: breakpoints need line numbers and local variables, whatever
|
||||
/// maven-compiler-plugin's `<debug>` / `<debuglevel>` ask of Maven's own build (#7786).
|
||||
fn is_debug_option(arg: &str) -> bool {
|
||||
arg == "-g" || arg.starts_with("-g:")
|
||||
}
|
||||
|
||||
/// The JDK feature version of `release` / `source` (`1.8` → 8).
|
||||
@@ -294,7 +583,7 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
|
||||
if let Some(proc) = c.proc.as_deref().filter(|p| !p.is_empty()) {
|
||||
args.push(format!("-proc:{proc}"));
|
||||
}
|
||||
args.extend(debug_args(&c));
|
||||
args.push("-g".into());
|
||||
if c.parameters == Some(true) {
|
||||
args.push("-parameters".into());
|
||||
}
|
||||
@@ -323,15 +612,19 @@ fn javac_options(set: &SourceSet, classpath: &[PathBuf], generated: &Path, jdk_m
|
||||
}
|
||||
}
|
||||
for (key, value) in &c.compiler_arguments {
|
||||
args.push(if key.starts_with('-') { key.clone() } else { format!("-{key}") });
|
||||
let key = if key.starts_with('-') { key.clone() } else { format!("-{key}") };
|
||||
if is_debug_option(&key) {
|
||||
continue;
|
||||
}
|
||||
args.push(key);
|
||||
if let Some(value) = value.as_ref().filter(|v| !v.is_empty()) {
|
||||
args.push(value.clone());
|
||||
}
|
||||
}
|
||||
if let Some(argument) = &c.compiler_argument {
|
||||
args.extend(argument.split_whitespace().map(str::to_owned));
|
||||
args.extend(argument.split_whitespace().filter(|a| !is_debug_option(a)).map(str::to_owned));
|
||||
}
|
||||
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty()).cloned());
|
||||
args.extend(c.compiler_args.iter().filter(|a| !a.is_empty() && !is_debug_option(a)).cloned());
|
||||
args
|
||||
}
|
||||
|
||||
@@ -558,7 +851,7 @@ impl JavaBuild<'_> {
|
||||
}
|
||||
};
|
||||
for (project, test) in &projects {
|
||||
if let Some(reason) = project.unsupported(*test) {
|
||||
if let Some(reason) = project.unsupported(*test, self.ignored_maven_compile_goals) {
|
||||
return Ok(Built::Unsupported(reason));
|
||||
}
|
||||
// A launch of a Java module runs it from the module path, which the language server reports.
|
||||
@@ -667,6 +960,7 @@ impl JavaBuild<'_> {
|
||||
for project in &reactor_model.projects {
|
||||
for test in [false, true] {
|
||||
let stamp = resource_stamp(project.set(test), cancel)?;
|
||||
self.prune_resources(dir, project, test, cancel)?;
|
||||
model::write_json(&state_path(dir, project, test, "resources"), &stamp)?;
|
||||
}
|
||||
}
|
||||
@@ -702,7 +996,11 @@ impl JavaBuild<'_> {
|
||||
let step = match top {
|
||||
Reactor::Maven(top) => {
|
||||
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
|
||||
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection];
|
||||
// The resources plugin copies a file only when it is newer than the copy; content
|
||||
// replaced without moving the mtime (a sync tool, PowerShell `Copy-Item`) would stay
|
||||
// stale while its stamp is recorded as processed.
|
||||
let mut extra =
|
||||
vec!["-q".to_owned(), "-pl".to_owned(), selection, "-Dmaven.resources.overwrite=true".to_owned()];
|
||||
extra.push("resources:resources".into());
|
||||
if changed.iter().any(|(_, test, _)| *test) {
|
||||
extra.push("resources:testResources".into());
|
||||
@@ -730,11 +1028,42 @@ impl JavaBuild<'_> {
|
||||
}));
|
||||
}
|
||||
for (project, test, stamp) in changed {
|
||||
self.prune_resources(dir, project, test, cancel)?;
|
||||
model::write_json(&state_path(dir, project, test, "resources"), &stamp)?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Removes what the sources no longer have from a source set's output: the resources step
|
||||
/// copies and overwrites, it never deletes, so a file deleted from the sources would stay on
|
||||
/// the launch's classpath (a stale `META-INF/spring.factories` then fails the application).
|
||||
fn prune_resources(
|
||||
&self,
|
||||
dir: &Path,
|
||||
project: &ProjectModel,
|
||||
test: bool,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<()> {
|
||||
let set = project.set(test);
|
||||
let expected = resource_outputs(set, cancel)?;
|
||||
let recorded: BTreeSet<PathBuf> = std::fs::read(state_path(dir, project, test, "resource-outputs"))
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
||||
.unwrap_or_default();
|
||||
for stale in recorded.difference(&expected) {
|
||||
let _ = std::fs::remove_file(stale);
|
||||
// The folders a removed resource leaves empty are not part of the output either.
|
||||
let mut parent = stale.parent();
|
||||
while let Some(folder) = parent.filter(|d| d.starts_with(&set.output) && *d != set.output) {
|
||||
if std::fs::remove_dir(folder).is_err() {
|
||||
break;
|
||||
}
|
||||
parent = folder.parent();
|
||||
}
|
||||
}
|
||||
model::write_json(&state_path(dir, project, test, "resource-outputs"), &expected)
|
||||
}
|
||||
|
||||
/// Removes the classes of a source set and its record: the next build compiles it from scratch.
|
||||
fn clean(&self, dir: &Path, project: &ProjectModel, test: bool) -> IdeResult<()> {
|
||||
let set = project.set(test);
|
||||
@@ -758,244 +1087,46 @@ impl JavaBuild<'_> {
|
||||
return Ok(false);
|
||||
}
|
||||
let sources = java_sources(set, cancel)?;
|
||||
let source_stamps: BTreeMap<PathBuf, FileStamp> =
|
||||
sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect();
|
||||
let state_file = state_path(dir, project, test, "compile");
|
||||
let previous = incremental::load_state(&state_file);
|
||||
let config = set.compiler.clone().unwrap_or_default();
|
||||
let release = config.release.as_deref().or(config.source.as_deref()).and_then(feature);
|
||||
let java_home = self.java_home(top, &config, release)?;
|
||||
let generated = generated_dir(dir, project, test);
|
||||
let generated_dir = generated_dir(dir, project, test);
|
||||
let classpath: Vec<PathBuf> = if test {
|
||||
std::iter::once(project.main.output.clone()).chain(set.classpath.iter().cloned()).collect()
|
||||
} else {
|
||||
set.classpath.clone()
|
||||
};
|
||||
let options = javac_options(set, &classpath, &generated, jdk_major(&java_home));
|
||||
let reactor: Vec<PathBuf> =
|
||||
classpath.iter().filter(|e| **e != set.output && outputs.contains_key(*e)).cloned().collect();
|
||||
let stamp = SetStamp {
|
||||
options: options.clone(),
|
||||
libraries: classpath
|
||||
.iter()
|
||||
.filter(|e| **e != set.output && !outputs.contains_key(*e))
|
||||
.map(|e| (e.clone(), file_stamp(e)))
|
||||
.collect(),
|
||||
reactor: reactor.clone(),
|
||||
processor_path: config.processor_path.iter().flatten().map(|p| (p.clone(), file_stamp(p))).collect(),
|
||||
java_home: java_home.clone(),
|
||||
};
|
||||
|
||||
// What the reactor outputs it compiles against changed since it last compiled.
|
||||
let mut upstream = BTreeMap::new();
|
||||
let mut upstream_changed = BTreeSet::new();
|
||||
let mut upstream_all = false;
|
||||
for entry in &reactor {
|
||||
let (key, entry_test) = &outputs[entry];
|
||||
let state = incremental::load_state(&state_path_of(dir, key, *entry_test, "compile"));
|
||||
let generation = state.as_ref().map_or(0, |s| s.generation);
|
||||
upstream.insert(entry.clone(), generation);
|
||||
let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied();
|
||||
if recorded == Some(generation) {
|
||||
continue;
|
||||
}
|
||||
match (recorded, state.and_then(|s| s.changes_since(recorded?))) {
|
||||
(Some(_), Some(changed)) => upstream_changed.extend(changed),
|
||||
_ => upstream_all = true,
|
||||
}
|
||||
}
|
||||
|
||||
let had_state = previous.is_some();
|
||||
let previous = previous.unwrap_or_default();
|
||||
let changed: BTreeSet<PathBuf> = source_stamps
|
||||
let options = javac_options(set, &classpath, &generated_dir, jdk_major(&java_home));
|
||||
let upstream_states: Vec<(PathBuf, PathBuf)> = classpath
|
||||
.iter()
|
||||
.filter(|(path, stamp)| {
|
||||
previous.sources.get(*path) != Some(*stamp) || previous.dirty.contains(*path) || force.contains(*path)
|
||||
.filter(|e| **e != set.output)
|
||||
.filter_map(|e| {
|
||||
outputs.get(e).map(|(key, entry_test)| (e.clone(), state_path_of(dir, key, *entry_test, "compile")))
|
||||
})
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
let removed: BTreeSet<PathBuf> =
|
||||
previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect();
|
||||
let from_scratch = !had_state
|
||||
|| previous.stamp != stamp
|
||||
|| upstream_all
|
||||
|| !set.output.is_dir()
|
||||
|| (!previous.success && previous.dirty.is_empty());
|
||||
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
// Processors that aggregate (or name no originating source) can't be followed class by class.
|
||||
let from_scratch = from_scratch
|
||||
|| (!previous.generated.is_empty() || !previous.unowned.is_empty())
|
||||
&& !(changed.is_empty() && removed.is_empty() && upstream_changed.is_empty());
|
||||
|
||||
let mut state = SetState {
|
||||
stamp,
|
||||
sources: source_stamps.clone(),
|
||||
generation: previous.generation,
|
||||
upstream,
|
||||
classes: previous.classes,
|
||||
changes: previous.changes,
|
||||
..Default::default()
|
||||
let libraries: Vec<PathBuf> =
|
||||
classpath.iter().filter(|e| **e != set.output && !outputs.contains_key(*e)).cloned().collect();
|
||||
let incremental_set = IncrementalSet {
|
||||
module_name: project.artifact_id.clone(),
|
||||
set_name: if test { "tests" } else { "main" },
|
||||
cwd: project.dir.clone(),
|
||||
sources,
|
||||
output: set.output.clone(),
|
||||
options,
|
||||
libraries,
|
||||
upstream_states,
|
||||
processor_path: config.processor_path.unwrap_or_default(),
|
||||
jvm_args: jvm_config(top, &subdir(self.root, top.rel_dir())),
|
||||
java_home,
|
||||
encoding: config.encoding.as_deref(),
|
||||
state_file: state_path(dir, project, test, "compile"),
|
||||
generated_dir,
|
||||
force,
|
||||
jar: self.jar,
|
||||
clean: false,
|
||||
};
|
||||
let mut api_changed = BTreeSet::new();
|
||||
let mut constants_changed = false;
|
||||
// Classes of removed sources go first, and count as changed.
|
||||
let gone: Vec<String> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect();
|
||||
for name in gone {
|
||||
let record = state.classes.remove(&name).expect("listed");
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
constants_changed |= record.constants != incremental::NO_CONSTANTS;
|
||||
api_changed.insert(name);
|
||||
}
|
||||
let mut to_compile: BTreeSet<PathBuf> = if from_scratch || constants_changed {
|
||||
remove_classes(&set.output);
|
||||
for file in previous.generated.iter().chain(&previous.unowned) {
|
||||
let _ = std::fs::remove_file(file);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&generated);
|
||||
state.classes.retain(|_, r| r.source.is_some());
|
||||
source_stamps.keys().cloned().collect()
|
||||
} else {
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
|
||||
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
|
||||
};
|
||||
std::fs::create_dir_all(&set.output)?;
|
||||
std::fs::create_dir_all(&generated)?;
|
||||
|
||||
let set_name = if test { "tests" } else { "main" };
|
||||
let total = source_stamps.len();
|
||||
let mut compiled: BTreeSet<PathBuf> = BTreeSet::new();
|
||||
let mut server = None;
|
||||
loop {
|
||||
let batch: BTreeSet<PathBuf> = to_compile
|
||||
.iter()
|
||||
.filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s))
|
||||
.cloned()
|
||||
.collect();
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
// The classes the batch replaces: their files go first, so nothing stale is left.
|
||||
let replaced: BTreeMap<String, ClassRecord> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
|
||||
.map(|(n, r)| (n.clone(), r.clone()))
|
||||
.collect();
|
||||
for (name, record) in &replaced {
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
state.classes.remove(name);
|
||||
}
|
||||
let files: Vec<PathBuf> = batch.iter().cloned().collect();
|
||||
let noun = if total == 1 { "file" } else { "files" };
|
||||
let count = if files.len() == total {
|
||||
format!("{total} {noun}")
|
||||
} else {
|
||||
format!("{} of {total} {noun}", files.len())
|
||||
};
|
||||
on_event(BuildEvent::Step {
|
||||
command: format!("javac {} ({set_name}, {count})", project.artifact_id),
|
||||
cwd: project.dir.clone().into(),
|
||||
});
|
||||
if server.is_none() {
|
||||
let key = ServerKey {
|
||||
java_home: java_home.clone(),
|
||||
jvm_args: jvm_config(top, &subdir(self.root, top.rel_dir())),
|
||||
};
|
||||
server = Some(self.service.servers.server(self.jar, &key)?);
|
||||
}
|
||||
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
|
||||
let result = server.as_ref().expect("started").compile(
|
||||
&options,
|
||||
&files,
|
||||
config.encoding.as_deref(),
|
||||
cancel,
|
||||
|reply| match reply {
|
||||
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
|
||||
Reply::Generated { path, .. } => state.generated.push(path.clone()),
|
||||
Reply::OutputText { text } => on_event(BuildEvent::Output { text: text.clone(), stderr: false }),
|
||||
Reply::Diagnostic { .. } => {
|
||||
if let Some(m) = diagnostic(reply) {
|
||||
on_event(BuildEvent::Output {
|
||||
text: message_text(&m),
|
||||
stderr: m.severity == Severity::Error,
|
||||
});
|
||||
on_event(BuildEvent::Message { message: m.clone() });
|
||||
messages.push(m);
|
||||
}
|
||||
}
|
||||
Reply::Done { .. } => {}
|
||||
},
|
||||
);
|
||||
if !matches!(result, Ok(true)) {
|
||||
for (path, _) in &written {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
// The next build starts from the state this one started from, with whatever this
|
||||
// one had to compile still to compile. Its earlier rounds' classes are not the
|
||||
// baseline: compared with them, the API and constant changes those rounds found
|
||||
// would never reach this set's dependents or the sets compiled against it.
|
||||
let mut retry = incremental::load_state(&state_file).unwrap_or_default();
|
||||
retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned());
|
||||
retry.success = false;
|
||||
let _ = model::write_json(&state_file, &retry);
|
||||
return result.map(|_| true);
|
||||
}
|
||||
// javac names sources as they were passed; other spellings are matched canonically,
|
||||
// and classes of sources outside the set (processors' output) are unowned.
|
||||
let canonical: HashMap<PathBuf, &PathBuf> =
|
||||
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
|
||||
let own = |source: PathBuf| -> Option<PathBuf> {
|
||||
if source_stamps.contains_key(&source) {
|
||||
return Some(source);
|
||||
}
|
||||
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
|
||||
};
|
||||
let mut fresh = BTreeMap::new();
|
||||
for (path, source) in written {
|
||||
let source = source.and_then(own);
|
||||
let class = (path.extension().is_some_and(|e| e == "class"))
|
||||
.then(|| std::fs::read(&path).ok())
|
||||
.flatten()
|
||||
.and_then(|bytes| classfile::parse(&bytes));
|
||||
match (class, source) {
|
||||
(Some(class), Some(source)) => {
|
||||
let (name, record) = ClassRecord::new(class, path, Some(source));
|
||||
fresh.insert(name, record);
|
||||
}
|
||||
_ => state.unowned.push(path),
|
||||
}
|
||||
}
|
||||
let round = incremental::diff(&replaced, &fresh);
|
||||
constants_changed |= round.constants;
|
||||
api_changed.extend(round.api.iter().cloned());
|
||||
state.classes.extend(fresh);
|
||||
compiled.extend(batch);
|
||||
if constants_changed {
|
||||
// Constants are copied into the classes that use them: compile the rest too.
|
||||
to_compile.extend(source_stamps.keys().cloned());
|
||||
continue;
|
||||
}
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
|
||||
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
|
||||
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
|
||||
}
|
||||
state.success = true;
|
||||
if !compiled.is_empty() || !api_changed.is_empty() {
|
||||
let changed =
|
||||
incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect());
|
||||
state.log(now_generation(), changed, !had_state || constants_changed);
|
||||
}
|
||||
model::write_json(&state_file, &state)?;
|
||||
Ok(false)
|
||||
let outcome = self.service.compile_incremental(&incremental_set, cancel, on_event, messages)?;
|
||||
Ok(outcome.failed)
|
||||
}
|
||||
|
||||
/// The JDK compiling a source set: the compiler plugin's forked `executable`, else Maven's
|
||||
@@ -1129,5 +1260,35 @@ fn resource_stamp(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTre
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Where `process-resources` puts each file of a source set's resource folders: the output folder,
|
||||
/// the root's target path, then the path under the root, filtered by its includes and excludes.
|
||||
fn resource_outputs(set: &SourceSet, cancel: &CancellationToken) -> IdeResult<BTreeSet<PathBuf>> {
|
||||
let mut out = BTreeSet::new();
|
||||
for root in &set.resources {
|
||||
let mut pending = vec![root.directory.clone()];
|
||||
while let Some(dir) = pending.pop() {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
pending.push(path);
|
||||
continue;
|
||||
}
|
||||
let rel = path.strip_prefix(&root.directory).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let included = root.includes.is_empty() || root.includes.iter().any(|p| ant_match(p, &rel));
|
||||
if !included || root.excludes.iter().any(|p| ant_match(p, &rel)) {
|
||||
continue;
|
||||
}
|
||||
let target = root.target_path.as_deref().unwrap_or("").replace('\\', "/");
|
||||
out.insert(set.output.join(target.trim_matches('/')).join(&rel));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -105,13 +105,26 @@ impl ProjectModel {
|
||||
}
|
||||
|
||||
/// Why the IDE can't compile this project with javac itself, if it can't.
|
||||
pub fn unsupported(&self, test: bool) -> Option<String> {
|
||||
pub fn unsupported(&self, test: bool, ignored_maven_compile_goals: &[String]) -> Option<String> {
|
||||
// What the build tool couldn't resolve or read: the model would be incomplete.
|
||||
if let Some(problem) = self.problems.first() {
|
||||
return Some(format!("{}: {problem}", self.artifact_id));
|
||||
}
|
||||
if !self.other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
|
||||
// Keep the recorded model intact: adding or removing a project override must also
|
||||
// affect an already prepared model. Gradle tasks never use Maven overrides.
|
||||
let other_compilers: Vec<&str> = self
|
||||
.other_compilers
|
||||
.iter()
|
||||
.filter(|execution| {
|
||||
!(self.gradle_path.is_none()
|
||||
&& execution.split_once('@').is_some_and(|(goal, _)| {
|
||||
ignored_maven_compile_goals.iter().any(|ignored| ignored.trim() == goal)
|
||||
}))
|
||||
})
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
if !other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, other_compilers.join(", ")));
|
||||
}
|
||||
if test && !self.test_generators.is_empty() {
|
||||
return Some(format!(
|
||||
|
||||
@@ -55,6 +55,75 @@ fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
|
||||
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_apply_to_cached_models_and_can_be_removed() {
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{goal}@default-jar"), format!("{goal}@extra-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
let cached: ProjectModel = serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap();
|
||||
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
|
||||
assert_eq!(cached.unsupported(false, &[goal.into()]), None);
|
||||
assert_eq!(cached.unsupported(false, &[format!(" {goal} ")]), None);
|
||||
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
|
||||
assert_eq!(cached.other_compilers, project.other_compilers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_match_exact_goals_and_keep_other_executions() {
|
||||
let jar = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let kotlin = "org.jetbrains.kotlin:kotlin-maven-plugin:compile";
|
||||
let mut project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{jar}@default-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
for unmatched in [
|
||||
"",
|
||||
"*",
|
||||
"org.apache.maven.plugins:maven-jar-plugin",
|
||||
"maven-jar-plugin:jar",
|
||||
"org.apache.maven.plugins:maven-jar-plugin:test-jar",
|
||||
"org.apache.maven.plugins:*:jar",
|
||||
] {
|
||||
assert!(project.unsupported(false, &[unmatched.into()]).is_some(), "{unmatched}");
|
||||
}
|
||||
project.other_compilers.push(format!("{kotlin}@compile"));
|
||||
let reason = project.unsupported(false, &[jar.into()]).unwrap();
|
||||
assert!(reason.contains(kotlin));
|
||||
assert!(!reason.contains(jar));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_do_not_affect_gradle_or_other_safety_checks() {
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let ignored = [goal.into()];
|
||||
let mut project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{goal}@default-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
project.gradle_path = Some(":app".into());
|
||||
assert!(project.unsupported(false, &ignored).is_some());
|
||||
project.gradle_path = None;
|
||||
project.problems.push("unresolved dependency".into());
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("unresolved dependency"));
|
||||
project.problems.clear();
|
||||
project.test_generators.push("org.example:generator:test@tests".into());
|
||||
assert_eq!(project.unsupported(false, &ignored), None);
|
||||
assert!(project.unsupported(true, &ignored).unwrap().contains("generates test sources"));
|
||||
project.test_generators.clear();
|
||||
project.main.compiler = Some(CompilerConfig { compiler_id: Some("eclipse".into()), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("eclipse"));
|
||||
project.main.compiler = Some(CompilerConfig { multi_release_output: Some(true), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("multi-release"));
|
||||
project.main.compiler =
|
||||
Some(CompilerConfig { processor_path_error: Some("missing processor".into()), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("missing processor"));
|
||||
}
|
||||
|
||||
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
|
||||
fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
|
||||
@@ -169,6 +238,17 @@ impl Fixture {
|
||||
}
|
||||
|
||||
fn build(&self, target: Target) -> LaunchOutputs {
|
||||
match self.try_build(target, &[]) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_build(&self, target: Target, ignored_maven_compile_goals: &[String]) -> IdeResult<Built> {
|
||||
let jdk = |_: Option<u32>| None;
|
||||
let build = JavaBuild {
|
||||
root: &self.root,
|
||||
@@ -177,18 +257,12 @@ impl Fixture {
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
ignored_maven_compile_goals,
|
||||
service: &self.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event)
|
||||
}
|
||||
|
||||
/// The steps of the launch builds since the last call.
|
||||
@@ -213,6 +287,37 @@ impl Fixture {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_maven_compile_goal_can_be_skipped_with_a_cached_reactor() {
|
||||
let pom = APP_POM.replace(
|
||||
"</build>",
|
||||
concat!(
|
||||
"<plugins><plugin><groupId>org.apache.maven.plugins</groupId>",
|
||||
"<artifactId>maven-jar-plugin</artifactId><version>3.4.1</version>",
|
||||
"<executions><execution><id>early-jar</id><phase>compile</phase>",
|
||||
"<goals><goal>jar</goal></goals></execution></executions></plugin></plugins></build>",
|
||||
),
|
||||
);
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/pom.xml", &pom),
|
||||
("lib/src/main/java/l/L.java", "package l; public class L {}"),
|
||||
("app/src/main/java/a/A.java", "package a; public class A { l.L dependency; }"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let module = f.root.join("app");
|
||||
let go = |ignored: &[String]| f.try_build(Target::Launch { module: &module, test: false }, ignored).unwrap();
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
|
||||
f.steps();
|
||||
let Built::Done(output) = go(&[goal.into()]) else { panic!("expected the configured build to use javac") };
|
||||
assert!(output.failure.is_none(), "{:?}", output.messages);
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
assert!(!f.root.join("app/target/app-1.jar").exists());
|
||||
assert!(f.steps().iter().all(|step| step.starts_with("javac")), "the prepared model was reused");
|
||||
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
@@ -258,6 +363,8 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl t:app"), "{steps:?}");
|
||||
// #7340: content replaced without a newer mtime is copied too.
|
||||
assert!(steps[0].contains("-Dmaven.resources.overwrite=true"), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
|
||||
|
||||
// A deleted source leaves no class behind.
|
||||
@@ -309,6 +416,104 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
assert!(f.out("t.app/test-classes/a/AggTest.class").is_file());
|
||||
}
|
||||
|
||||
/// #7743: a dependency's own dependencies come before its next sibling on the classpath, as in
|
||||
/// `mvn compile`, so of two artifacts with the same classes (`dom4j:dom4j` 1.x and
|
||||
/// `org.dom4j:dom4j` 2.x) javac sees the one Maven does.
|
||||
#[test]
|
||||
fn maven_classpath_lists_dependencies_in_maven_order() {
|
||||
let module = |name: &str, deps: &[&str]| {
|
||||
let deps: String = deps
|
||||
.iter()
|
||||
.map(|d| {
|
||||
format!("<dependency><groupId>t</groupId><artifactId>{d}</artifactId><version>1</version></dependency>")
|
||||
})
|
||||
.collect();
|
||||
format!(
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId>\
|
||||
<version>1</version></parent><artifactId>{name}</artifactId><dependencies>{deps}</dependencies></project>"
|
||||
)
|
||||
};
|
||||
let root = ROOT_POM.replace(
|
||||
"<module>lib</module>",
|
||||
"<module>newdom</module><module>olddom</module><module>x</module><module>lib</module>",
|
||||
);
|
||||
let (newdom, olddom, x, lib) =
|
||||
(module("newdom", &[]), module("olddom", &[]), module("x", &["newdom"]), module("lib", &["x", "olddom"]));
|
||||
let Some(f) = Fixture::new(&[
|
||||
("pom.xml", &root),
|
||||
("newdom/pom.xml", &newdom),
|
||||
("olddom/pom.xml", &olddom),
|
||||
("x/pom.xml", &x),
|
||||
("lib/pom.xml", &lib),
|
||||
("newdom/src/main/java/d/Element.java", "package d;\npublic class Element { public void fresh() {} }\n"),
|
||||
("olddom/src/main/java/d/Element.java", "package d;\npublic class Element {}\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { void f() { new d.Element().fresh(); } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let built = f.launch(false);
|
||||
assert_eq!(built.failure, None, "{:?}", built.messages);
|
||||
let position = |name: &str| built.class_paths.iter().position(|p| *p == f.out(&format!("t.{name}/classes")));
|
||||
assert!(position("newdom") < position("olddom"), "{:?}", built.class_paths);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_resources_to_the_output_paths_the_build_tool_writes() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
write(&root, "src/main/resources/app.properties", "a=1");
|
||||
write(&root, "src/main/resources/notes.txt", "n");
|
||||
write(&root, "src/main/resources/deep/app.properties", "b=2");
|
||||
let resources = root.join("src/main/resources");
|
||||
let output = root.join("out/classes");
|
||||
let set = SourceSet {
|
||||
output: output.clone(),
|
||||
resources: vec![
|
||||
ResourceRoot { directory: resources.clone(), ..Default::default() },
|
||||
// A `<targetPath>` and an `<includes>` pattern, as a POM can configure them.
|
||||
ResourceRoot {
|
||||
directory: resources,
|
||||
target_path: Some("META-INF".into()),
|
||||
includes: vec!["*.properties".into()],
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
resource_outputs(&set, &CancellationToken::new()).unwrap(),
|
||||
BTreeSet::from([
|
||||
output.join("app.properties"),
|
||||
output.join("notes.txt"),
|
||||
output.join("deep/app.properties"),
|
||||
output.join("META-INF/app.properties"),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletes_the_output_of_a_resource_removed_from_the_sources() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
|
||||
("app/src/main/resources/app.properties", "version=${project.version}\n"),
|
||||
("app/src/main/resources/META-INF/spring.factories", "a.A\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/META-INF/spring.factories")).unwrap(), "a.A\n");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
|
||||
// A deleted resource leaves no copy behind: the launch would read a file the sources no longer have.
|
||||
fs::remove_file(f.root.join("app/src/main/resources/META-INF/spring.factories")).unwrap();
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps.iter().any(|s| s.contains("resources:resources")), "{steps:?}");
|
||||
assert!(!f.out("t.app/classes/META-INF/spring.factories").exists(), "the removed resource stays on the classpath");
|
||||
// The resource that is still there keeps its copy, and a launch with nothing changed runs nothing.
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
|
||||
assert!(f.steps_of_launch().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recompiles_the_classes_an_api_change_reaches() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
@@ -485,7 +690,7 @@ fn javac_options_follow_the_compiler_configuration() {
|
||||
"-processorpath /p.jar",
|
||||
"-processor a.P",
|
||||
"-proc:none",
|
||||
"-g:lines,vars",
|
||||
"-g",
|
||||
"-parameters",
|
||||
"-nowarn",
|
||||
"-encoding UTF-8",
|
||||
@@ -500,6 +705,28 @@ fn javac_options_follow_the_compiler_configuration() {
|
||||
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_options_always_keep_debug_info() {
|
||||
// `<debug>false</debug>` makes Maven pass `-g:none`; the IDE's build still emits the line
|
||||
// numbers and variables the debugger needs (#7786).
|
||||
let set = SourceSet {
|
||||
output: PathBuf::from("/o"),
|
||||
compiler: Some(CompilerConfig {
|
||||
debug: Some(false),
|
||||
debuglevel: Some("source".into()),
|
||||
compiler_args: vec!["-g:none".into(), "-Xlint:all".into()],
|
||||
compiler_argument: Some("-g:source -Xlint:none".into()),
|
||||
compiler_arguments: [("g:none".to_owned(), None)].into(),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let args = javac_options(&set, &[], Path::new("/gen"), Some(21));
|
||||
let debug: Vec<_> = args.iter().filter(|a| a.starts_with("-g")).collect();
|
||||
assert_eq!(debug, ["-g"], "{args:?}");
|
||||
assert!(args.iter().any(|a| a == "-Xlint:all") && args.iter().any(|a| a == "-Xlint:none"), "{args:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_gradle_projects_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
@@ -581,6 +808,7 @@ fn leaves_gradle_projects_with_other_compilers_to_gradle() {
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
ignored_maven_compile_goals: &[],
|
||||
service: &f.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
|
||||
@@ -69,6 +69,9 @@ pub struct MavenProject {
|
||||
pub aggregated: bool,
|
||||
pub plugins: Vec<MavenPlugin>,
|
||||
pub dependencies: Vec<MavenDependency>,
|
||||
/// Local classpath entries from the POM. The synced dependency tree has coordinates only.
|
||||
#[serde(skip)]
|
||||
pub system_paths: Vec<PathBuf>,
|
||||
/// Profile ids declared in this POM.
|
||||
pub profiles: Vec<String>,
|
||||
/// Java feature version the project compiles for (`maven.compiler.release`, `java.version`…).
|
||||
@@ -89,6 +92,100 @@ impl MavenProject {
|
||||
}
|
||||
}
|
||||
|
||||
/// All projects belonging to the Maven reactor rooted at `top`, traversed through `<modules>`.
|
||||
pub(crate) fn reactor_projects<'a>(m: &'a MavenModel, top: &'a MavenProject) -> Vec<&'a MavenProject> {
|
||||
let mut projects = Vec::new();
|
||||
let mut pending = vec![top];
|
||||
let mut seen = HashSet::new();
|
||||
while let Some(p) = pending.pop() {
|
||||
if !seen.insert(&p.pom) {
|
||||
continue;
|
||||
}
|
||||
projects.push(p);
|
||||
pending.extend(m.projects.iter().filter(|child| p.modules.contains(&child.pom)));
|
||||
}
|
||||
projects
|
||||
}
|
||||
|
||||
fn reactor_for<'a>(m: &'a MavenModel, target: &'a MavenProject) -> &'a MavenProject {
|
||||
if !target.aggregated {
|
||||
return target;
|
||||
}
|
||||
let mut matches =
|
||||
m.projects.iter().filter(|top| !top.aggregated && reactor_projects(m, top).iter().any(|p| p.pom == target.pom));
|
||||
let first = matches.next();
|
||||
let ancestor = first
|
||||
.into_iter()
|
||||
.chain(matches)
|
||||
.filter(|top| top.dir.is_empty() || target.dir == top.dir || target.dir.starts_with(&format!("{}/", top.dir)))
|
||||
.max_by_key(|top| top.dir.len());
|
||||
ancestor.or(first).unwrap_or(target)
|
||||
}
|
||||
|
||||
/// The linked reactor root owning the project at `pom` (project-relative).
|
||||
pub(crate) fn reactor_for_pom<'a>(m: &'a MavenModel, pom: &str) -> Option<&'a MavenProject> {
|
||||
m.projects.iter().find(|p| p.pom == pom).map(|target| reactor_for(m, target))
|
||||
}
|
||||
|
||||
/// The linked reactor root owning the project at `dir` (project-relative).
|
||||
pub(crate) fn reactor_for_dir<'a>(m: &'a MavenModel, dir: &str) -> Option<&'a MavenProject> {
|
||||
m.projects.iter().find(|p| p.dir == dir).map(|target| reactor_for(m, target))
|
||||
}
|
||||
|
||||
/// `/`-separated relative path from `from` to `to`, supporting sibling (`../app`) and parent (`..`)
|
||||
/// module layouts. Returns `None` when the paths do not share a root/drive.
|
||||
pub(crate) fn relative_module_path(from: &Path, to: &Path) -> Option<String> {
|
||||
use std::path::Component;
|
||||
let from = crate::gradle::normalize(from);
|
||||
let to = crate::gradle::normalize(to);
|
||||
let from_comps: Vec<_> = from.components().collect();
|
||||
let to_comps: Vec<_> = to.components().collect();
|
||||
let common = from_comps.iter().zip(&to_comps).take_while(|(a, b)| a == b).count();
|
||||
let mut parts = Vec::new();
|
||||
for comp in &from_comps[common..] {
|
||||
match comp {
|
||||
Component::Normal(_) => parts.push("..".into()),
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir | Component::Prefix(_) | Component::RootDir => return None,
|
||||
}
|
||||
}
|
||||
for comp in &to_comps[common..] {
|
||||
match comp {
|
||||
Component::Normal(s) => parts.push(s.to_string_lossy().into_owned()),
|
||||
Component::ParentDir => parts.push("..".into()),
|
||||
Component::CurDir => {}
|
||||
Component::Prefix(_) | Component::RootDir => return None,
|
||||
}
|
||||
}
|
||||
Some(parts.join("/"))
|
||||
}
|
||||
|
||||
/// Maven `-pl` selector for `module` when invoked from reactor `top` (`None` when `module` is `top`).
|
||||
pub(crate) fn module_selector(root: &Path, top: &MavenProject, module: &MavenProject) -> Option<String> {
|
||||
if top.pom == module.pom {
|
||||
return None;
|
||||
}
|
||||
let base = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
|
||||
let resolve_dir = |dir: &str| {
|
||||
let raw = if dir.is_empty() { base.clone() } else { base.join(dir) };
|
||||
dunce::canonicalize(&raw).unwrap_or(raw)
|
||||
};
|
||||
let from = resolve_dir(&top.dir);
|
||||
let to = resolve_dir(&module.dir);
|
||||
if let Some(rel) = relative_module_path(&from, &to)
|
||||
&& !rel.is_empty()
|
||||
{
|
||||
return Some(rel);
|
||||
}
|
||||
if !module.group_id.is_empty() && !module.artifact_id.is_empty() {
|
||||
Some(format!("{}:{}", module.group_id, module.artifact_id))
|
||||
} else if !module.artifact_id.is_empty() {
|
||||
Some(format!(":{}", module.artifact_id))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MavenPlugin {
|
||||
@@ -176,6 +273,7 @@ struct RawDep {
|
||||
kind: Option<String>,
|
||||
classifier: Option<String>,
|
||||
scope: Option<String>,
|
||||
system_path: Option<String>,
|
||||
optional: bool,
|
||||
}
|
||||
|
||||
@@ -248,6 +346,7 @@ fn read_dep(e: &Element) -> Option<RawDep> {
|
||||
kind: e.text_of("type"),
|
||||
classifier: e.text_of("classifier"),
|
||||
scope: e.text_of("scope"),
|
||||
system_path: e.text_of("systemPath"),
|
||||
optional: e.text_of("optional").is_some_and(|o| o == "true"),
|
||||
})
|
||||
}
|
||||
@@ -1335,6 +1434,22 @@ pub fn external_pom_dirs(root: &Path, linked: &[String]) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Linked POMs inside the opened root that a folder scan doesn't reach: it stops at the
|
||||
/// first folder with a `pom.xml` and follows only that project's modules, so a POM linked
|
||||
/// below another Maven project's folder (a deployable module its parent doesn't list) is
|
||||
/// never found. jdtls imports this way.
|
||||
pub fn linked_poms_below_projects(root: &Path, linked: &[String]) -> Vec<PathBuf> {
|
||||
let base = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
|
||||
linked_poms(root, linked)
|
||||
.into_iter()
|
||||
.filter(|pom| {
|
||||
let Some(dir) = pom.parent() else { return false };
|
||||
dir.starts_with(&base)
|
||||
&& dir.ancestors().skip(1).take_while(|d| d.starts_with(&base)).any(|d| is_pom_file(&d.join("pom.xml")))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
type FileStamp = Option<(Option<std::time::SystemTime>, u64)>;
|
||||
|
||||
fn file_stamp(path: &Path) -> FileStamp {
|
||||
@@ -1519,7 +1634,13 @@ pub fn load_with_linked_jdk(
|
||||
let packaging = i(pom.packaging.as_deref().unwrap_or("jar"));
|
||||
let managed: HashMap<String, &RawDep> = ctx.managed.iter().map(|m| (m.key(), m)).collect();
|
||||
let managed_version = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.version.clone());
|
||||
let managed_scope = |d: &RawDep| managed.get(&d.key()).and_then(|m| m.scope.clone());
|
||||
let scope = |d: &RawDep| {
|
||||
d.scope
|
||||
.as_deref()
|
||||
.or_else(|| managed.get(&d.key()).and_then(|m| m.scope.as_deref()))
|
||||
.map(i)
|
||||
.unwrap_or_else(|| "compile".into())
|
||||
};
|
||||
let dependencies = ctx
|
||||
.deps
|
||||
.iter()
|
||||
@@ -1529,11 +1650,26 @@ pub fn load_with_linked_jdk(
|
||||
version: d.version.clone().or_else(|| managed_version(d)).map(|v| i(&v)),
|
||||
kind: d.kind.clone().unwrap_or_else(|| "jar".into()),
|
||||
classifier: d.classifier.clone(),
|
||||
scope: d.scope.clone().or_else(|| managed_scope(d)).unwrap_or_else(|| "compile".into()),
|
||||
scope: scope(d),
|
||||
optional: d.optional,
|
||||
..MavenDependency::default()
|
||||
})
|
||||
.collect();
|
||||
let system_paths = ctx
|
||||
.deps
|
||||
.iter()
|
||||
.filter(|d| scope(d) == "system")
|
||||
.filter_map(|d| {
|
||||
let path = d
|
||||
.system_path
|
||||
.as_deref()
|
||||
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
|
||||
let path = i(path);
|
||||
// Rebuilt from its components: `${pom.basedir}/lib/x.jar` on Windows mixes `\\` and `/`.
|
||||
(!path.contains("${") && Path::new(&path).is_absolute())
|
||||
.then(|| Path::new(&path).components().collect::<PathBuf>())
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut plugins: Vec<RawPlugin> = ctx.plugins.clone();
|
||||
for a in lifecycle_plugins(&packaging) {
|
||||
@@ -1592,6 +1728,7 @@ pub fn load_with_linked_jdk(
|
||||
aggregated,
|
||||
plugins,
|
||||
dependencies,
|
||||
system_paths,
|
||||
profiles: ctx.profiles.iter().map(|(id, _)| id.clone()).collect(),
|
||||
java_version: jv,
|
||||
command: wrapper(&canonical_root, &dir_canon),
|
||||
|
||||
@@ -110,27 +110,15 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
|
||||
}
|
||||
fs::write(cache.join("artifact-id.txt"), id)?;
|
||||
if let Some(pom) = id.strip_prefix("maven:") {
|
||||
let p = model
|
||||
.maven
|
||||
.as_ref()
|
||||
.and_then(|m| m.projects.iter().find(|p| p.pom == pom && p.packaging == "war"))
|
||||
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let projects = &model.maven.as_ref().unwrap().projects;
|
||||
let top = projects
|
||||
let maven = model.maven.as_ref().ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let p = maven
|
||||
.projects
|
||||
.iter()
|
||||
.filter(|t| {
|
||||
!t.aggregated && (t.dir.is_empty() || p.dir == t.dir || p.dir.starts_with(&format!("{}/", t.dir)))
|
||||
})
|
||||
.max_by_key(|t| t.dir.len())
|
||||
.unwrap_or(p);
|
||||
.find(|p| p.pom == pom && p.packaging == "war")
|
||||
.ok_or_else(|| IdeError::invalid("Choose a Maven WAR module"))?;
|
||||
let top = crate::maven::reactor_for_pom(maven, &p.pom).unwrap_or(p);
|
||||
let mut args = top.options.clone();
|
||||
if top.pom != p.pom {
|
||||
let module = root
|
||||
.join(&p.dir)
|
||||
.strip_prefix(root.join(&top.dir))
|
||||
.map_err(|e| IdeError::invalid(e.to_string()))?
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
if let Some(module) = crate::maven::module_selector(root, top, p) {
|
||||
args.extend(["-pl".into(), module, "-am".into()]);
|
||||
}
|
||||
// help:evaluate runs once, in the reactor's first project. Query the selected
|
||||
@@ -316,4 +304,90 @@ mod tests {
|
||||
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_sibling_reactor_builds_war_through_aggregator_with_relative_pl() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["parent", "common", "app"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
fs::write(
|
||||
root.join("parent/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("common/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("app/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging><dependencies><dependency><groupId>test</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
let a = artifacts(root, &model);
|
||||
assert_eq!(a.len(), 1);
|
||||
assert_eq!(a[0].id, "maven:app/pom.xml");
|
||||
|
||||
let plan = build(root, &model, &a[0].id, &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, "parent");
|
||||
assert_eq!(&plan.args[..3], &["-pl", "../app", "-am"]);
|
||||
let (probe, _) = plan.maven_project.as_ref().unwrap();
|
||||
assert!(probe.contains(&root.join("app/pom.xml").to_string_lossy().into_owned()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_subfolder_aggregator_builds_root_war_with_parent_pl() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["parent", "common"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
}
|
||||
fs::write(
|
||||
root.join("pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>parent/pom.xml</relativePath></parent><artifactId>app</artifactId><packaging>war</packaging></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("parent/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../</module><module>../common</module></modules></project>",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("common/pom.xml"),
|
||||
"<project><modelVersion>4.0.0</modelVersion><parent><groupId>test</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let settings =
|
||||
ide_core::settings::MavenSettings { linked_projects: vec!["parent/pom.xml".into()], ..Default::default() };
|
||||
let model = crate::load_linked(root, &root.join("cache"), None, &settings, &Default::default());
|
||||
let plan = build(root, &model, "maven:pom.xml", &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, "parent");
|
||||
assert_eq!(&plan.args[..3], &["-pl", "..", "-am"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_independent_sibling_wars_keep_own_reactor() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
for dir in ["a", "b"] {
|
||||
fs::create_dir_all(root.join(dir)).unwrap();
|
||||
fs::write(
|
||||
root.join(dir).join("pom.xml"),
|
||||
format!("<project><modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>{dir}</artifactId><version>1</version><packaging>war</packaging></project>"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let model = crate::load(root, &root.join("cache"), None);
|
||||
for dir in ["a", "b"] {
|
||||
let plan = build(root, &model, &format!("maven:{dir}/pom.xml"), &root.join("base")).unwrap();
|
||||
assert_eq!(plan.cwd, dir);
|
||||
assert!(!plan.args.contains(&"-pl".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
|
||||
png = "0.18"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
gtk = "0.18"
|
||||
gtk = "0.19"
|
||||
|
||||
[dev-dependencies]
|
||||
png = "0.18"
|
||||
@@ -175,7 +175,7 @@ impl CliTool {
|
||||
Poll::Finished => break,
|
||||
}
|
||||
}
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
Ok((lines.finish(cancel)?.success(), stderr_tail))
|
||||
}
|
||||
|
||||
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
|
||||
@@ -301,9 +301,9 @@ impl Lines {
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
|
||||
/// killing it, when `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
|
||||
/// Waits for the child to exit and returns how it exited. Fails, after killing it, when
|
||||
/// `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<std::process::ExitStatus> {
|
||||
let status = loop {
|
||||
if let Some(status) = self.child.try_wait()? {
|
||||
break status;
|
||||
@@ -314,6 +314,6 @@ impl Lines {
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(status.success())
|
||||
Ok(status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! The CMake File API queries the IDE writes into a build directory, shared by the run
|
||||
//! configurations (which read the replies) and Build Project (which configures).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The objects asked for: targets, cache, toolchains and the CMake files.
|
||||
pub const QUERIES: [&str; 4] = ["codemodel-v2", "cache-v2", "toolchains-v1", "cmakeFiles-v1"];
|
||||
const QUERY: &str = ".cmake/api/v1/query/client-openidea";
|
||||
/// Where CMake writes its replies, relative to the build directory.
|
||||
pub const REPLY: &str = ".cmake/api/v1/reply";
|
||||
|
||||
/// Asks CMake to answer [`QUERIES`] on the next configure of `build`.
|
||||
pub fn write_queries(build: &Path) -> std::io::Result<()> {
|
||||
let query = build.join(QUERY);
|
||||
std::fs::create_dir_all(&query)?;
|
||||
for name in QUERIES {
|
||||
std::fs::write(query.join(name), "")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -314,6 +314,30 @@ pub struct SmartKeysSettings {
|
||||
pub insert_doc_stub: bool,
|
||||
/// Backspace › Unindent: `autoindent` (proper indent position) | `nearest` indent position | `none`.
|
||||
pub backspace_unindent: String,
|
||||
/// The styles Cycle Identifier Case goes through.
|
||||
pub cycle_case: CycleCaseSettings,
|
||||
}
|
||||
|
||||
/// Editor › General › Smart Keys › Cycle Identifier Case: the styles the action goes through.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CycleCaseSettings {
|
||||
/// `snake_case`
|
||||
pub snake: bool,
|
||||
/// `SCREAMING_SNAKE_CASE`
|
||||
pub screaming: bool,
|
||||
/// `kebab-case`
|
||||
pub kebab: bool,
|
||||
/// `camelCase`
|
||||
pub camel: bool,
|
||||
/// `PascalCase`
|
||||
pub pascal: bool,
|
||||
}
|
||||
|
||||
impl Default for CycleCaseSettings {
|
||||
fn default() -> Self {
|
||||
Self { snake: true, screaming: true, kebab: true, camel: true, pascal: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SmartKeysSettings {
|
||||
@@ -335,6 +359,7 @@ impl Default for SmartKeysSettings {
|
||||
smart_indent: true,
|
||||
insert_doc_stub: true,
|
||||
backspace_unindent: "autoindent".into(),
|
||||
cycle_case: CycleCaseSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -376,6 +401,8 @@ impl Default for CodeEditingSettings {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct InlayHintsSettings {
|
||||
pub types: bool,
|
||||
/// Inferred variable and field types from the JavaScript and TypeScript servers (on, as in WebStorm).
|
||||
pub js_ts_types: bool,
|
||||
pub parameters: bool,
|
||||
/// Hints of other kinds (chaining, closing labels…).
|
||||
pub other: bool,
|
||||
@@ -411,6 +438,7 @@ impl Default for InlayHintsSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
types: true,
|
||||
js_ts_types: true,
|
||||
parameters: true,
|
||||
other: true,
|
||||
closing_labels: true,
|
||||
@@ -685,6 +713,19 @@ mod folding_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod inlay_hints_tests {
|
||||
use super::InlayHintsSettings;
|
||||
|
||||
#[test]
|
||||
fn existing_settings_enable_js_ts_type_hints_by_default() {
|
||||
let settings: InlayHintsSettings = serde_json::from_str(r#"{"parameters":false}"#).unwrap();
|
||||
assert!(settings.types);
|
||||
assert!(settings.js_ts_types);
|
||||
assert!(!settings.parameters);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sticky_lines_tests {
|
||||
use super::CodeEditingSettings;
|
||||
|
||||
@@ -11,6 +11,14 @@ use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The execution target recorded with an MCP agent run.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum McpAgentRunTarget {
|
||||
Host,
|
||||
Container { id: String },
|
||||
}
|
||||
|
||||
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
|
||||
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
|
||||
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
|
||||
@@ -27,6 +35,10 @@ pub enum McpUiRequest {
|
||||
subject: String,
|
||||
project: String,
|
||||
detail: Option<String>,
|
||||
/// The project is served without a window: the request shows in another project's window,
|
||||
/// which names it and keeps the keyboard focus where it is.
|
||||
#[serde(default)]
|
||||
background: bool,
|
||||
},
|
||||
OpenFile {
|
||||
path: crate::IpcPath,
|
||||
@@ -38,6 +50,7 @@ pub enum McpUiRequest {
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
target: McpAgentRunTarget,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
@@ -95,6 +108,8 @@ pub enum IdeEvent {
|
||||
WindowGroupsChanged,
|
||||
/// A project was loaded or unloaded for the MCP server without a window of its own.
|
||||
McpBackgroundProjectsChanged,
|
||||
/// Agent automations, run history, or session schedules changed on the host.
|
||||
AutomationsChanged,
|
||||
/// A window entered or left full screen, itself or as a member of a full-screen window group.
|
||||
WindowFullscreenChanged,
|
||||
/// This remote window's connection ended or another window took over the session.
|
||||
@@ -102,6 +117,14 @@ pub enum IdeEvent {
|
||||
host: String,
|
||||
#[serde(default)]
|
||||
taken_over: bool,
|
||||
/// Plain-language explanation when a dev container exited from the OOM killer (`OOMKilled` / exit 137).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
oom_message: Option<String>,
|
||||
/// Local configuration file (`devcontainer.json` or Compose file) that sets the container's limit.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
oom_config_path: Option<String>,
|
||||
},
|
||||
ProjectTrustChanged {
|
||||
root: crate::IpcPath,
|
||||
@@ -424,6 +447,8 @@ pub enum LspRefreshKind {
|
||||
Inheritance,
|
||||
/// The Dart server published a document's Flutter outline.
|
||||
FlutterOutline,
|
||||
/// Spring bean markers of open documents may have changed.
|
||||
SpringBeanMarkers,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
pub mod build_jobs;
|
||||
pub mod cli_process;
|
||||
pub mod cmake_file_api;
|
||||
pub mod editor_settings;
|
||||
pub mod error;
|
||||
pub mod event;
|
||||
|
||||
@@ -1,5 +1,35 @@
|
||||
//! Returning freed heap pages to the OS.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Like [`release_free_pages`], on a background thread once 2 s pass without another call:
|
||||
/// closing a project or a batch of tabs frees memory in bursts, released once.
|
||||
pub fn release_free_pages_soon() {
|
||||
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
debounce(&DUE, Duration::from_secs(2), release_free_pages);
|
||||
}
|
||||
|
||||
/// Runs `run` on a background thread once `delay` passes after the last call.
|
||||
fn debounce(due: &'static Mutex<Option<Instant>>, delay: Duration, run: fn()) {
|
||||
let idle = due.lock().unwrap().replace(Instant::now() + delay).is_none();
|
||||
if idle {
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
let mut slot = due.lock().unwrap();
|
||||
let left = slot.map_or(Duration::ZERO, |at| at.saturating_duration_since(Instant::now()));
|
||||
if left.is_zero() {
|
||||
*slot = None;
|
||||
drop(slot);
|
||||
return run();
|
||||
}
|
||||
drop(slot);
|
||||
std::thread::sleep(left);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands pages the allocator has freed but kept back to the OS. Call after a burst of
|
||||
/// short-lived allocations (a full index scan); until then they still count towards the
|
||||
/// process's memory footprint.
|
||||
@@ -18,3 +48,45 @@ pub fn release_free_pages() {
|
||||
libc::malloc_trim(0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
|
||||
|
||||
static DUE: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
static RUNS: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
fn count() {
|
||||
RUNS.fetch_add(1, SeqCst);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_of_calls_runs_once_after_the_delay() {
|
||||
// Timing-based: a loaded CI machine can oversleep, so each check allows for that.
|
||||
let delay = Duration::from_millis(500);
|
||||
let (mut last, mut widest_gap) = (None::<Instant>, Duration::ZERO);
|
||||
for _ in 0..5 {
|
||||
debounce(&DUE, delay, count);
|
||||
let now = Instant::now();
|
||||
widest_gap = widest_gap.max(last.map_or(Duration::ZERO, |l| now - l));
|
||||
last = Some(now);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
if last.unwrap().elapsed() < delay {
|
||||
assert_eq!(RUNS.load(SeqCst), 0, "ran before the delay passed");
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while RUNS.load(SeqCst) == 0 && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
// A second run would come within another delay.
|
||||
std::thread::sleep(delay);
|
||||
if widest_gap < delay {
|
||||
assert_eq!(RUNS.load(SeqCst), 1);
|
||||
} else {
|
||||
assert!(RUNS.load(SeqCst) >= 1);
|
||||
}
|
||||
release_free_pages_soon();
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,24 @@ pub fn own_group(cmd: &mut Command) -> &mut Command {
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Starts the child as the leader of a session of its own on Unix. Like [`own_group`] it leads
|
||||
/// its process group, so [`kill_tree`] and [`terminate_tree`] reach what it starts; unlike it,
|
||||
/// the child has no controlling terminal, so a tool that would ask on `/dev/tty` (and be
|
||||
/// stopped there as a background job when the app was started from a shell) falls back to
|
||||
/// its pipes. Use it in place of `own_group`: a group leader cannot start a session. A no-op
|
||||
/// elsewhere.
|
||||
pub fn own_session(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
// SAFETY: `setsid` is async-signal-safe and touches none of the parent's memory.
|
||||
unsafe {
|
||||
cmd.pre_exec(|| if libc::setsid() == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) });
|
||||
}
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Kills the child and everything it started, then reaps it.
|
||||
///
|
||||
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
|
||||
@@ -622,6 +640,30 @@ pub fn host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
|
||||
apply_changes(std::env::vars_os().collect(), &child_env_changes(Some(dir))).into_iter()
|
||||
}
|
||||
|
||||
/// Whether `(key, value)` can go into a Windows environment block (`KEY=VALUE\0`
|
||||
/// entries, then a final `\0`). `CreateProcessW` / `NtCreateUserProcess` returns
|
||||
/// `ERROR_INVALID_PARAMETER` (os error 87) when an entry has an empty name or an
|
||||
/// interior NUL. That happens when a `REG_MULTI_SZ` user environment value is
|
||||
/// loaded into the process or re-read from the registry (#6806): the extra NUL
|
||||
/// is treated as an entry separator and leaves a fragment with no `=`.
|
||||
pub fn is_spawnable_env_pair(key: &OsStr, value: &OsStr) -> bool {
|
||||
!key.is_empty() && !contains_ascii(key, 0) && !contains_ascii(key, b'=') && !contains_ascii(value, 0)
|
||||
}
|
||||
|
||||
fn contains_ascii(s: &OsStr, byte: u8) -> bool {
|
||||
s.as_encoded_bytes().contains(&byte)
|
||||
}
|
||||
|
||||
/// [`host_vars`] without pairs that a Windows PTY spawn would reject.
|
||||
pub fn spawnable_host_vars() -> impl Iterator<Item = (OsString, OsString)> {
|
||||
host_vars().filter(|(k, v)| is_spawnable_env_pair(k, v))
|
||||
}
|
||||
|
||||
/// [`host_vars_in`] without pairs that a Windows PTY spawn would reject.
|
||||
pub fn spawnable_host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
|
||||
host_vars_in(dir).filter(|(k, v)| is_spawnable_env_pair(k, v))
|
||||
}
|
||||
|
||||
/// [`std::env::var_os`] as a child should see it (see [`host_env`]), the login shell's value
|
||||
/// included when this process lacks the variable.
|
||||
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
|
||||
@@ -946,6 +988,28 @@ fn append_path_entries(path: &OsStr, extra: &OsStr) -> OsString {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn own_session_leaves_the_controlling_terminal_behind() {
|
||||
// `ps` prints `?` (Linux) or `??` (macOS) for a process without a controlling terminal.
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.args(["-c", "ps -o tty= -p $$"]);
|
||||
let out = own_session(&mut cmd).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).trim().chars().all(|c| c == '?'), "{:?}", out.stdout);
|
||||
// Without a terminal (CI) the line above holds anyway: the child must lead a session
|
||||
// of its own, which only `setsid` makes it.
|
||||
let mut cmd = Command::new("sleep");
|
||||
cmd.arg("5");
|
||||
let mut child = own_session(&mut cmd).spawn().unwrap();
|
||||
let pid = libc::pid_t::try_from(child.id()).unwrap();
|
||||
// SAFETY: plain syscall on a child not reaped yet.
|
||||
let session = unsafe { libc::getsid(pid) };
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
assert_eq!(session, pid, "the child leads its own session");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_alive_tells_live_from_dead_pids() {
|
||||
assert!(process_alive(std::process::id()));
|
||||
@@ -1240,6 +1304,35 @@ mod tests {
|
||||
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
|
||||
}
|
||||
|
||||
fn os_from_bytes(bytes: &[u8]) -> OsString {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
OsString::from_vec(bytes.to_vec())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
OsString::from_wide(&bytes.iter().copied().map(u16::from).collect::<Vec<_>>())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawnable_env_pairs_reject_empty_keys_equals_and_interior_nuls() {
|
||||
let ok_key = OsString::from("PATH");
|
||||
let ok_val = OsString::from("/bin");
|
||||
assert!(is_spawnable_env_pair(&ok_key, &ok_val));
|
||||
assert!(!is_spawnable_env_pair(OsStr::new(""), &ok_val));
|
||||
assert!(!is_spawnable_env_pair(OsStr::new("FOO=BAR"), &ok_val));
|
||||
// A REG_MULTI_SZ value's interior NUL would split the environment block,
|
||||
// leaving a fragment with no `=` (#6806). An empty name is also rejected.
|
||||
assert!(!is_spawnable_env_pair(&os_from_bytes(b""), &os_from_bytes(b"132786")));
|
||||
assert!(!is_spawnable_env_pair(&ok_key, &os_from_bytes(b"1788051509\x00132786")));
|
||||
assert!(!is_spawnable_env_pair(&os_from_bytes(b"132786\x00"), &ok_val));
|
||||
assert!(spawnable_host_vars().all(|(k, v)| is_spawnable_env_pair(&k, &v)));
|
||||
assert!(spawnable_host_vars().any(|(k, _)| k == "PATH" || k == "Path"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_apply_in_order() {
|
||||
let vars = apply_changes(
|
||||
|
||||
@@ -5,6 +5,29 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const SEARCH_DEPTH: usize = 3;
|
||||
|
||||
/// Folders that hold dependencies or build output rather than the project's own builds: hidden
|
||||
/// folders (`.build`, `.git`), package checkouts (`node_modules`, `SourcePackages`, `Pods`,
|
||||
/// `Carthage`) and build products (`target`, `build`, `DerivedData`, …).
|
||||
pub fn is_skipped_dir(name: &str) -> bool {
|
||||
name.starts_with('.')
|
||||
|| matches!(
|
||||
name,
|
||||
"node_modules"
|
||||
| "target"
|
||||
| "build"
|
||||
| "dist"
|
||||
| "vendor"
|
||||
| "out"
|
||||
| "bin"
|
||||
| "obj"
|
||||
| "venv"
|
||||
| "SourcePackages"
|
||||
| "Pods"
|
||||
| "Carthage"
|
||||
| "DerivedData"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn children(dir: &Path) -> Vec<PathBuf> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut dirs: Vec<_> = entries
|
||||
@@ -13,13 +36,7 @@ pub fn children(dir: &Path) -> Vec<PathBuf> {
|
||||
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
return false;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
!name.starts_with('.')
|
||||
&& !matches!(
|
||||
name.as_ref(),
|
||||
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
|
||||
)
|
||||
!is_skipped_dir(&entry.file_name().to_string_lossy())
|
||||
})
|
||||
.map(|entry| entry.path())
|
||||
.collect();
|
||||
|
||||
@@ -203,6 +203,9 @@ pub enum RunTargetKind {
|
||||
Docker,
|
||||
/// A new container of a Compose service (`docker compose run --rm`).
|
||||
Compose,
|
||||
/// A WSL distribution on this Windows machine (`wsl.exe -d <distro>`), the project read
|
||||
/// through `/mnt/<drive>`.
|
||||
Wsl,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Run Targets: run configurations on another machine
|
||||
@@ -215,7 +218,8 @@ pub struct RunTarget {
|
||||
pub name: String,
|
||||
/// [`SshConfiguration::id`] (SSH).
|
||||
pub ssh_config: String,
|
||||
/// Remote folder the project is synchronised to and run from (SSH).
|
||||
/// Remote folder the project is synchronised to and run from (SSH); the project's Linux
|
||||
/// path, empty = its `/mnt/<drive>` path (WSL).
|
||||
pub project_root: String,
|
||||
/// Upload changed project files before each run (SSH).
|
||||
pub sync_before_run: bool,
|
||||
@@ -223,6 +227,7 @@ pub struct RunTarget {
|
||||
pub python: String,
|
||||
pub node: String,
|
||||
pub java: String,
|
||||
pub php: String,
|
||||
/// Id of a Docker connection of the Services tool window (Docker, Compose);
|
||||
/// empty = the CLI's own daemon.
|
||||
pub docker_connection: String,
|
||||
@@ -241,6 +246,8 @@ pub struct RunTarget {
|
||||
pub run_options: String,
|
||||
/// Run as the image's user instead of the project folder's owner (Linux).
|
||||
pub image_user: bool,
|
||||
/// Distribution name, as `wsl.exe -l -q` lists it (WSL).
|
||||
pub distro: String,
|
||||
}
|
||||
|
||||
/// A plugin-owned argv wrapper for project runs (API 1.4).
|
||||
|
||||
@@ -68,6 +68,8 @@ pub struct Settings {
|
||||
/// Build, Execution, Deployment › Run Targets.
|
||||
pub run_targets: Vec<RunTarget>,
|
||||
pub cmake: CMakeSettings,
|
||||
/// Build, Execution, Deployment › Toolchains; the first is the default.
|
||||
pub toolchains: Vec<Toolchain>,
|
||||
/// Settings › Agents.
|
||||
pub agents: AgentSettings,
|
||||
/// Agents › MCP Server (global only).
|
||||
@@ -160,6 +162,9 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = BTreeMap<String, AgentMcpServer>)]
|
||||
pub mcp_servers: BTreeMap<String, AgentMcpServer>,
|
||||
/// Custom MCP Registry base URL (`agents.mcpRegistryUrl`); empty = GitHub MCP Registry.
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
pub mcp_registry_url: String,
|
||||
/// How agent skills may run, keyed by skill name (`[agents.skills.<name>]`); `SKILL.md`
|
||||
/// files on disk are never modified.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
@@ -170,6 +175,15 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentMemorySettings)]
|
||||
pub memory: AgentMemorySettings,
|
||||
/// Agent plugin bundle policies (`[agents.plugins]`): registered marketplaces and non-sensitive
|
||||
/// config. Enablement lives in each harness's native config; capability consent is stored per machine.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentPluginSettings)]
|
||||
pub plugins: AgentPluginSettings,
|
||||
/// Scheduled agent automations and headless scheduler host policies (`[agents.automations]`).
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentAutomationSettings)]
|
||||
pub automations: AgentAutomationSettings,
|
||||
}
|
||||
|
||||
impl Default for AgentSettings {
|
||||
@@ -200,8 +214,11 @@ impl Default for AgentSettings {
|
||||
confirm_terminate_on_close: true,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
mcp_registry_url: String::new(),
|
||||
skills: BTreeMap::new(),
|
||||
memory: AgentMemorySettings::default(),
|
||||
plugins: AgentPluginSettings::default(),
|
||||
automations: AgentAutomationSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -240,6 +257,14 @@ pub struct AgentMcpServer {
|
||||
/// empty means enabled for all agents.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub agents: Vec<String>,
|
||||
/// Canonical MCP registry server identifier (e.g. `microsoft/playwright-mcp`) when installed from a registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL (e.g. `https://api.mcp.github.com`) when installed from a registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for AgentMcpServer {
|
||||
@@ -253,6 +278,8 @@ impl Default for AgentMcpServer {
|
||||
url: None,
|
||||
headers: BTreeMap::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -358,6 +385,96 @@ pub struct AgentMemorySettings {
|
||||
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
}
|
||||
|
||||
/// One agent plugin bundle's policy in Settings › Agents › Plugins
|
||||
/// (`[agents.plugins.entries."<harness>:<plugin>@<marketplace>"]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentPluginEntryPolicy {
|
||||
/// Non-sensitive `userConfig` / `variables` key-value pairs; sensitive values live in OS Keychain.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub config: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// Agent plugin bundle settings (`[agents.plugins]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentPluginSettings {
|
||||
/// Registered plugin marketplaces (`owner/repo[#ref]`, GitHub URL, or local directory/manifest path).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub marketplaces: Vec<String>,
|
||||
/// Per-plugin non-sensitive native option hints, keyed by `<harness>:<plugin>@<marketplace>`.
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentPluginEntryPolicy>)]
|
||||
pub entries: BTreeMap<String, AgentPluginEntryPolicy>,
|
||||
}
|
||||
|
||||
/// When OpenIDEA holds an OS idle-sleep assertion during active automation turns.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutomationPreventSleep {
|
||||
/// Prevent idle sleep while plugged into AC power.
|
||||
#[default]
|
||||
Ac,
|
||||
/// Prevent idle sleep whenever an automated turn is running.
|
||||
Always,
|
||||
/// Never hold an idle-sleep assertion.
|
||||
Never,
|
||||
}
|
||||
|
||||
/// What the scheduler does when one or more scheduled occurrences fell due while asleep or offline.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutomationMisfirePolicy {
|
||||
/// Coalesce all missed occurrences into at most one catch-up run once awake and online.
|
||||
#[default]
|
||||
RunOnce,
|
||||
/// Skip missed occurrences and advance to the next future slot.
|
||||
Skip,
|
||||
}
|
||||
|
||||
/// Agent automation and headless scheduler settings (`[agents.automations]`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentAutomationSettings {
|
||||
/// Automatically register the headless login/boot scheduler service while at least one
|
||||
/// automation is enabled, and unregister it when none remain enabled.
|
||||
pub auto_start_service: bool,
|
||||
/// Keep the local OpenIDEA host alive in the background when windows close while local
|
||||
/// automations are enabled.
|
||||
pub keep_alive_in_background: bool,
|
||||
/// Prevent system idle sleep while an automated turn is running.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutomationPreventSleep)]
|
||||
pub prevent_sleep: AutomationPreventSleep,
|
||||
/// Default policy for scheduled occurrences missed during sleep, offline downtime, or reboot.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutomationMisfirePolicy)]
|
||||
pub misfire_policy: AutomationMisfirePolicy,
|
||||
/// Keep `openidea-server --daemon` alive across disconnects while the remote host has
|
||||
/// enabled scheduled automations.
|
||||
pub keep_remote_daemon_alive: bool,
|
||||
/// Automatically remove temporary automation worktrees when a run finishes with zero diff
|
||||
/// and zero commits.
|
||||
pub auto_clean_worktrees: bool,
|
||||
/// Maximum retained non-clean automation worktrees per automation before pruning oldest
|
||||
/// finished ones.
|
||||
pub max_dirty_worktrees: u32,
|
||||
}
|
||||
|
||||
impl Default for AgentAutomationSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
auto_start_service: false,
|
||||
keep_alive_in_background: true,
|
||||
prevent_sleep: AutomationPreventSleep::Ac,
|
||||
misfire_policy: AutomationMisfirePolicy::RunOnce,
|
||||
keep_remote_daemon_alive: true,
|
||||
auto_clean_worktrees: true,
|
||||
max_dirty_worktrees: 5,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A hand-edited value these settings don't know reads as the default, rather than
|
||||
/// failing the whole settings file.
|
||||
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
|
||||
@@ -602,6 +719,8 @@ pub struct ToolDownloadSettings {
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
/// The managed Vue Language Server release. Empty selects it from the project's Vue dependency.
|
||||
pub vue_language_server_version: String,
|
||||
}
|
||||
|
||||
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
|
||||
@@ -649,9 +768,42 @@ impl Default for SettingsSyncSettings {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CMakeSettings {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
/// Serialized as `null` when absent, so `cmake.profiles` stays a known settings key.
|
||||
#[specta(optional)]
|
||||
pub profiles: Option<Vec<CMakeProfile>>,
|
||||
/// `true` ignores `CMakePresets.json` / `CMakeUserPresets.json`; otherwise every visible
|
||||
/// configure preset whose condition holds is listed after the explicit profiles.
|
||||
pub ignore_presets: bool,
|
||||
/// Configure presets (by name) enabled as profiles. As in CLion, a preset is listed but
|
||||
/// disabled until enabled here.
|
||||
pub enabled_presets: Vec<String>,
|
||||
/// The profile (by name) that build, run and debug use, as CLion's toolbar switcher;
|
||||
/// empty or unknown = the first enabled one.
|
||||
pub active_profile: String,
|
||||
}
|
||||
|
||||
/// The presets a profile made from `CMakePresets.json` runs with.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CMakePresetRef {
|
||||
pub configure: String,
|
||||
/// The first build preset of `configure`, used by `cmake --build --preset`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub build: Option<String>,
|
||||
/// The first test preset of `configure`, used by `ctest --preset`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub test: Option<String>,
|
||||
/// Cache variables the resolved preset sets itself, read when presets are loaded (never
|
||||
/// saved): a toolchain does not override them.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub cache_variables: Vec<String>,
|
||||
/// The preset names a toolchain file, which picks the compilers.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub toolchain_file: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -665,6 +817,23 @@ pub struct CMakeProfile {
|
||||
pub build_dir: String,
|
||||
pub build_args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// `false` keeps the profile listed but unused (CLion's "Enable profile").
|
||||
pub enabled: bool,
|
||||
/// Toolchain name (Settings › Toolchains); empty = the default (first) toolchain.
|
||||
pub toolchain: String,
|
||||
/// Set only on the profiles made from presets: configure with `cmake --preset`, and the
|
||||
/// generator and cache variables come from the preset.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub preset: Option<CMakePresetRef>,
|
||||
/// Resolved from the toolchain when profiles are put to use (never saved): the `cmake`
|
||||
/// to run (`ctest` next to it) and the debugger to prefer.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub cmake_program: Option<std::path::PathBuf>,
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub debugger: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for CMakeProfile {
|
||||
@@ -677,10 +846,44 @@ impl Default for CMakeProfile {
|
||||
build_dir: String::new(),
|
||||
build_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
enabled: true,
|
||||
toolchain: String::new(),
|
||||
preset: None,
|
||||
cmake_program: None,
|
||||
debugger: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ToolchainKind {
|
||||
/// Tools from the chosen paths, else from `PATH`.
|
||||
#[default]
|
||||
System,
|
||||
/// A MinGW / MSYS2 directory: its `bin` goes first on `PATH`, with gcc, g++,
|
||||
/// mingw32-make and gdb from there.
|
||||
#[serde(rename = "mingw")]
|
||||
MinGw,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are
|
||||
/// detected: from the MinGW directory, else from `PATH`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Toolchain {
|
||||
pub name: String,
|
||||
pub kind: ToolchainKind,
|
||||
/// The MinGW directory (the one holding `bin`).
|
||||
pub path: String,
|
||||
pub cmake: String,
|
||||
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make or ninja.
|
||||
pub build_tool: String,
|
||||
pub c_compiler: String,
|
||||
pub cxx_compiler: String,
|
||||
pub debugger: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ToolSettings {
|
||||
@@ -792,6 +995,7 @@ impl Default for Settings {
|
||||
deployment: DeploymentSettings::default(),
|
||||
run_targets: Vec::new(),
|
||||
cmake: CMakeSettings::default(),
|
||||
toolchains: Vec::new(),
|
||||
agents: AgentSettings::default(),
|
||||
mcp_server: McpServerSettings::default(),
|
||||
agent_security: AgentSecuritySettings::default(),
|
||||
@@ -1157,6 +1361,7 @@ pub struct FileIconThemeOptions {
|
||||
pub hollow_folders: bool,
|
||||
pub hide_ui_icons: bool,
|
||||
pub hide_psi_icons: bool,
|
||||
pub file_icons_for_code: bool,
|
||||
pub monochrome: Option<String>,
|
||||
pub saturation: Option<u8>,
|
||||
pub opacity: Option<u8>,
|
||||
@@ -1240,6 +1445,10 @@ pub struct CustomColorScheme {
|
||||
pub struct EditorSettings {
|
||||
pub font_family: String,
|
||||
pub font_size: f32,
|
||||
/// Largest document (in MiB) eligible for syntax analysis and language-server features.
|
||||
#[serde(deserialize_with = "code_insight_limit_mb")]
|
||||
#[specta(type = u8)]
|
||||
pub max_code_insight_file_size_mb: u8,
|
||||
pub line_height: f32,
|
||||
pub tab_size: u32,
|
||||
pub insert_spaces: bool,
|
||||
@@ -1293,11 +1502,23 @@ pub struct EditorSettings {
|
||||
pub encodings: EncodingSettings,
|
||||
}
|
||||
|
||||
pub const DEFAULT_CODE_INSIGHT_LIMIT_MB: u8 = 5;
|
||||
pub const MAX_CODE_INSIGHT_LIMIT_MB: u8 = 50;
|
||||
|
||||
fn code_insight_limit_mb<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u8, D::Error> {
|
||||
Ok(serde_json::Value::deserialize(d)?
|
||||
.as_u64()
|
||||
.and_then(|n| u8::try_from(n).ok())
|
||||
.filter(|n| (1..=MAX_CODE_INSIGHT_LIMIT_MB).contains(n))
|
||||
.unwrap_or(DEFAULT_CODE_INSIGHT_LIMIT_MB))
|
||||
}
|
||||
|
||||
impl Default for EditorSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
font_family: "JetBrains Mono".into(),
|
||||
font_size: 13.0,
|
||||
max_code_insight_file_size_mb: DEFAULT_CODE_INSIGHT_LIMIT_MB,
|
||||
line_height: 22.0,
|
||||
tab_size: 4,
|
||||
insert_spaces: true,
|
||||
@@ -1509,6 +1730,9 @@ pub struct MarkdownSettings {
|
||||
pub preview_layout: MarkdownPreviewLayout,
|
||||
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
|
||||
pub preview_font_size: Option<u32>,
|
||||
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
|
||||
/// trusted projects, or stay in static safe mode.
|
||||
pub mdx_execution: MdxExecutionPolicy,
|
||||
/// "Detect commands that can be run right from Markdown files": gutter run icons on
|
||||
/// shell code blocks and on command lines in code blocks.
|
||||
pub run_commands: bool,
|
||||
@@ -1521,12 +1745,22 @@ impl Default for MarkdownSettings {
|
||||
Self {
|
||||
preview_layout: MarkdownPreviewLayout::default(),
|
||||
preview_font_size: None,
|
||||
mdx_execution: MdxExecutionPolicy::default(),
|
||||
run_commands: true,
|
||||
command_directory: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MdxExecutionPolicy {
|
||||
#[default]
|
||||
Ask,
|
||||
Trusted,
|
||||
Off,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MarkdownPreviewLayout {
|
||||
@@ -1935,6 +2169,8 @@ pub struct MavenSettings {
|
||||
pub active_profiles: String,
|
||||
/// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ).
|
||||
pub delegate_build: bool,
|
||||
/// Maven goals (`groupId:artifactId:goal`) the IDE may skip in compile phases. Empty by default.
|
||||
pub ignored_compile_goals: Vec<String>,
|
||||
/// Download `-sources.jar` of dependencies when the Java language server imports the
|
||||
/// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
|
||||
/// from a library class's Download Sources banner.
|
||||
@@ -2054,6 +2290,37 @@ pub struct ProjectLibrary {
|
||||
pub scope: DependencyScope,
|
||||
}
|
||||
|
||||
/// A library class entry written as a jar glob: `dir/*.jar` → `(dir, false)`, `dir/**/*.jar` → `(dir, true)`.
|
||||
pub fn split_jar_glob(entry: &str) -> Option<(&str, bool)> {
|
||||
let entry = entry.trim();
|
||||
if let Some(base) = entry.strip_suffix("/**/*.jar").or_else(|| entry.strip_suffix(r"\**\*.jar")) {
|
||||
return Some((base, true));
|
||||
}
|
||||
entry.strip_suffix("/*.jar").or_else(|| entry.strip_suffix(r"\*.jar")).map(|base| (base, false))
|
||||
}
|
||||
|
||||
/// The `.jar` files in `dir` (and its subfolders when `recursive`), sorted by name per folder.
|
||||
pub fn jar_files(dir: &std::path::Path, recursive: bool) -> Vec<std::path::PathBuf> {
|
||||
fn walk(dir: &std::path::Path, recursive: bool, out: &mut Vec<std::path::PathBuf>) {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
let mut entries: Vec<_> = entries.flatten().collect();
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
match entry.file_type() {
|
||||
Ok(t) if t.is_dir() && recursive => walk(&path, true, out),
|
||||
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x.eq_ignore_ascii_case("jar")) => {
|
||||
out.push(path)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(dir, recursive, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Dependency entry of a module (Project Structure › Modules › Dependencies).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -2342,12 +2609,12 @@ mod tests {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"fileIconTheme":"p/t"}}"#).unwrap();
|
||||
assert!(old.appearance.file_icon_theme_options.is_empty());
|
||||
let json = serde_json::json!({"appearance":{"fileIconThemeOptions":{"p/t":{
|
||||
"groups":{"tests":true},"choices":{"arrows":"plusminus"},"hideFiles":true,"hideFolders":false,"hollowFolders":true,"hideUiIcons":true,"hidePsiIcons":false,
|
||||
"groups":{"tests":true},"choices":{"arrows":"plusminus"},"hideFiles":true,"hideFolders":false,"hollowFolders":true,"hideUiIcons":true,"hidePsiIcons":false,"fileIconsForCode":true,
|
||||
"monochrome":"#546e7a","saturation":5,"opacity":80,"iconSize":20,"rowHeight":30,"accent":"#009688"}}}});
|
||||
let settings: Settings = serde_json::from_value(json.clone()).unwrap();
|
||||
let options = &settings.appearance.file_icon_theme_options["p/t"];
|
||||
assert!(options.hide_files && options.hollow_folders && !options.hide_folders);
|
||||
assert!(options.hide_ui_icons && !options.hide_psi_icons);
|
||||
assert!(options.hide_ui_icons && !options.hide_psi_icons && options.file_icons_for_code);
|
||||
assert!(options.groups["tests"]);
|
||||
assert_eq!(options.choices["arrows"], "plusminus");
|
||||
assert_eq!(
|
||||
@@ -2363,6 +2630,7 @@ mod tests {
|
||||
assert_eq!(plain["hideFiles"], false);
|
||||
assert_eq!(plain["hideUiIcons"], false);
|
||||
assert_eq!(plain["hidePsiIcons"], false);
|
||||
assert_eq!(plain["fileIconsForCode"], false);
|
||||
assert_eq!(plain["monochrome"], serde_json::Value::Null);
|
||||
assert_eq!(plain["groups"], serde_json::json!({}));
|
||||
}
|
||||
|
||||
@@ -296,6 +296,14 @@ pub struct OutlineItem {
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub visibility: Option<Visibility>,
|
||||
/// Rust `impl Trait for Type`: the trait's name in the header (its last path segment, where go-to-definition lands), from the syntax tree.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub implements: Option<Range>,
|
||||
/// Rust `impl [Trait for] Type`: the implementing type's name (its last path segment), from the syntax tree.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub self_type: Option<Range>,
|
||||
}
|
||||
|
||||
/// Fuzzy-match highlight: indices (in chars of the displayed string) that matched.
|
||||
|
||||
@@ -8,6 +8,21 @@ use std::collections::HashSet;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Why netcoredbg can't be installed here, for the two platforms Samsung publishes no build
|
||||
/// for; the tool installer and the debugger's "not found" error both say it.
|
||||
pub fn netcoredbg_no_prebuilt(intel_mac: bool, windows_arm64: bool) -> Option<String> {
|
||||
let platform = match (intel_mac, windows_arm64) {
|
||||
(true, _) => "Intel Macs",
|
||||
(_, true) => "Windows on ARM64",
|
||||
_ => return None,
|
||||
};
|
||||
Some(format!(
|
||||
"Samsung publishes no prebuilt netcoredbg for {platform}. Build it from source \
|
||||
(https://github.com/Samsung/netcoredbg#building-from-source-code), then put `netcoredbg` on PATH \
|
||||
or set its executable path in Settings › Languages & Frameworks › Language Servers"
|
||||
))
|
||||
}
|
||||
|
||||
/// Where executables are looked up: this process's `PATH` (the login shell's in the
|
||||
/// app), the login shell's `PATH` as last read, then per-user directories and mise's,
|
||||
/// asdf's and pyenv's shims, for when the shell's setup didn't reach the app. Language server
|
||||
@@ -133,6 +148,7 @@ fn search_dirs(
|
||||
dirs.extend(USER_DIRS.iter().map(|d| home.join(d)));
|
||||
dirs.extend(nvm_bins(&home.join(".nvm/versions/node")));
|
||||
}
|
||||
dirs.extend(RUSTUP_PROXY_DIRS.iter().map(PathBuf::from));
|
||||
// Version managers' shims after real tool directories: a shim exists for a command any
|
||||
// installed version has, and fails when the selected one lacks it. Before the system's,
|
||||
// as the managers' shell setup puts them.
|
||||
@@ -165,6 +181,11 @@ const USER_DIRS: &[&str] = &[
|
||||
"Library/pnpm",
|
||||
];
|
||||
|
||||
/// Homebrew's `rustup` keeps its toolchain proxies (`cargo`, `rust-analyzer`, …) in its own
|
||||
/// prefix, off `PATH` unless the shell adds it: these play the part of `~/.cargo/bin`.
|
||||
pub const RUSTUP_PROXY_DIRS: &[&str] =
|
||||
&["/opt/homebrew/opt/rustup/bin", "/usr/local/opt/rustup/bin", "/home/linuxbrew/.linuxbrew/opt/rustup/bin"];
|
||||
|
||||
const SYSTEM_DIRS: &[&str] = &["/opt/homebrew/bin", "/usr/local/go/bin", "/usr/local/bin", "/usr/bin", "/bin"];
|
||||
|
||||
/// Whether `dir` is one of the system's own bin directories, which [`search_path`] adds
|
||||
@@ -250,13 +271,16 @@ mod tests {
|
||||
assert!(at("/home/me/.npm-global/bin") < at("/home/me/.pyenv/shims"));
|
||||
// Global .NET tools (fsautocomplete, csharp-ls) install here, off PATH.
|
||||
assert!(at("/home/me/.dotnet/tools") < at("/usr/local/bin"));
|
||||
// Homebrew rustup's proxies, after rustup-init's.
|
||||
assert!(at("/home/me/.cargo/bin") < at("/opt/homebrew/opt/rustup/bin"));
|
||||
assert!(at("/opt/homebrew/opt/rustup/bin") < at("/opt/homebrew/bin"));
|
||||
assert!(at("/home/me/.local/share/mise/shims") < at("/usr/local/bin"));
|
||||
assert!(dirs.iter().all(|d| d.is_absolute()));
|
||||
let unique: HashSet<&PathBuf> = dirs.iter().collect();
|
||||
assert_eq!(unique.len(), dirs.len());
|
||||
// A `:` can't be in a `PATH` entry: those below such a home are left out.
|
||||
let dirs = search_dirs(Some(OsStr::new("/usr/bin")), None, None, Some(Path::new("/home/a:b")), &[]);
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home")));
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home/a:b")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -27,6 +27,35 @@ pub struct VcsSettings {
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
/// Settings › Version Control › Subversion.
|
||||
pub svn: SvnSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Subversion (`vcs.svn`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SvnSettings {
|
||||
/// Path to the svn executable; empty = auto-detect.
|
||||
pub executable: String,
|
||||
/// Run svn as if in a terminal: its password, passphrase and certificate prompts open
|
||||
/// dialogs. Off, svn runs with `--non-interactive` and a rejected login asks once.
|
||||
pub interactive: bool,
|
||||
/// Pass `--config-dir config_dir` to every svn command.
|
||||
pub use_custom_config_dir: bool,
|
||||
pub config_dir: String,
|
||||
}
|
||||
|
||||
impl Default for SvnSettings {
|
||||
/// Interactive except on Windows: svn there asks on the console, which an IDE's child
|
||||
/// process has hidden, so a prompt could not be answered (not verified on Windows yet).
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
executable: String::new(),
|
||||
interactive: !cfg!(windows),
|
||||
use_custom_config_dir: false,
|
||||
config_dir: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
@@ -80,6 +109,7 @@ impl Default for VcsSettings {
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
svn: SvnSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -447,12 +477,15 @@ pub struct BuildSettings {
|
||||
pub open_tool_window: String,
|
||||
/// When to focus the Build tool window: `always` | `onError` | `never`.
|
||||
pub focus_tool_window: String,
|
||||
/// Build an Xcode project in the background when xcode-build-server has no build log to read
|
||||
/// yet, so cross-file code insight works before the first Run.
|
||||
pub xcode_index_build: bool,
|
||||
}
|
||||
|
||||
impl Default for BuildSettings {
|
||||
fn default() -> Self {
|
||||
// Builds open the tool window without taking focus.
|
||||
Self { open_tool_window: "always".into(), focus_tool_window: "never".into() }
|
||||
Self { open_tool_window: "always".into(), focus_tool_window: "never".into(), xcode_index_build: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -530,6 +563,7 @@ pub struct DebuggerSettings {
|
||||
/// Java: whether to reload changed classes into running debug sessions after compilation.
|
||||
pub hot_swap_after_compile: HotSwapPolicy,
|
||||
pub python: PythonDebuggerSettings,
|
||||
pub cpp: CppDebuggerSettings,
|
||||
}
|
||||
|
||||
impl Default for DebuggerSettings {
|
||||
@@ -552,6 +586,7 @@ impl Default for DebuggerSettings {
|
||||
flutter_hot_reload_on_save: true,
|
||||
hot_swap_after_compile: HotSwapPolicy::Ask,
|
||||
python: PythonDebuggerSettings::default(),
|
||||
cpp: CppDebuggerSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -570,6 +605,14 @@ impl Default for PythonDebuggerSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// C/C++ debugger executables. Empty paths use automatic discovery.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CppDebuggerSettings {
|
||||
pub gdb_executable: String,
|
||||
pub lldb_dap_executable: String,
|
||||
}
|
||||
|
||||
/// Run/Debug configuration behaviour.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -616,13 +659,14 @@ pub struct TerminalSettings {
|
||||
pub close_on_exit: bool,
|
||||
pub mouse_reporting: bool,
|
||||
pub copy_on_selection: bool,
|
||||
/// Programs may set the clipboard with OSC 52 (tmux, Neovim, TUIs over SSH); never read it.
|
||||
pub osc52_clipboard: bool,
|
||||
pub paste_on_middle_click: bool,
|
||||
/// Right-click pastes instead of opening the context menu (Ctrl or Shift + right-click still opens it).
|
||||
pub right_click_paste: bool,
|
||||
pub override_ide_shortcuts: bool,
|
||||
pub shell_integration: bool,
|
||||
pub highlight_hyperlinks: bool,
|
||||
pub highlight_selection: bool,
|
||||
/// Highlights typed commands the IDE recognises; Run Highlighted Command runs them with it.
|
||||
pub run_commands_using_ide: bool,
|
||||
pub option_as_meta: bool,
|
||||
@@ -656,12 +700,12 @@ impl Default for TerminalSettings {
|
||||
close_on_exit: true,
|
||||
mouse_reporting: true,
|
||||
copy_on_selection: false,
|
||||
osc52_clipboard: true,
|
||||
paste_on_middle_click: true,
|
||||
right_click_paste: false,
|
||||
override_ide_shortcuts: true,
|
||||
shell_integration: true,
|
||||
highlight_hyperlinks: true,
|
||||
highlight_selection: true,
|
||||
run_commands_using_ide: true,
|
||||
option_as_meta: false,
|
||||
escape_to_editor: false,
|
||||
@@ -800,4 +844,17 @@ mod tests {
|
||||
assert_eq!(serialized["hotSwapAfterCompile"], raw);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpp_debugger_paths_default_to_empty_and_roundtrip() {
|
||||
let missing: DebuggerSettings = serde_json::from_str("{}").unwrap();
|
||||
assert!(missing.cpp.gdb_executable.is_empty());
|
||||
assert!(missing.cpp.lldb_dap_executable.is_empty());
|
||||
|
||||
let cpp = serde_json::json!({"gdbExecutable": "tools/gdb-16", "lldbDapExecutable": "/opt/llvm/bin/lldb-dap"});
|
||||
let settings: DebuggerSettings = serde_json::from_value(serde_json::json!({"cpp": cpp})).unwrap();
|
||||
assert_eq!(settings.cpp.gdb_executable, "tools/gdb-16");
|
||||
assert_eq!(settings.cpp.lldb_dap_executable, "/opt/llvm/bin/lldb-dap");
|
||||
assert_eq!(serde_json::to_value(&settings).unwrap()["cpp"], cpp);
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,24 @@ pub fn parse(path: &Path) -> Option<WslPath> {
|
||||
Some(WslPath { distro: distro.to_owned(), path: format!("/{}", tail.trim_end_matches('/')) })
|
||||
}
|
||||
|
||||
/// The Linux path of a Windows path seen from `distro`: `C:\a` → `/mnt/c/a` (WSL's default
|
||||
/// automount root), `\\wsl.localhost\<distro>\a` → `/a`. `None` for another distro's share,
|
||||
/// other network shares and relative paths.
|
||||
pub fn linux_path(path: &Path, distro: &str) -> Option<String> {
|
||||
if let Some(w) = parse(path) {
|
||||
return w.distro.eq_ignore_ascii_case(distro).then_some(w.path);
|
||||
}
|
||||
let s = path.to_string_lossy().replace('\\', "/");
|
||||
let s = s.strip_prefix("//?/").unwrap_or(&s);
|
||||
let mut chars = s.chars();
|
||||
let drive = chars.next().filter(char::is_ascii_alphabetic)?;
|
||||
let rest = chars.as_str().strip_prefix(':')?;
|
||||
if !(rest.is_empty() || rest.starts_with('/')) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("/mnt/{}{}", drive.to_ascii_lowercase(), rest.trim_end_matches('/')))
|
||||
}
|
||||
|
||||
/// A distro name `wsl.exe -d` can be given safely: Windows creates them from letters, digits,
|
||||
/// `.`, `_` and `-`. A leading `-` would be read as an option, so it is refused too.
|
||||
pub fn is_valid_distro(name: &str) -> bool {
|
||||
@@ -86,6 +104,57 @@ pub fn list_distros() -> Vec<String> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Where this machine reads `distro`'s file system.
|
||||
pub fn share_root(distro: &str) -> std::path::PathBuf {
|
||||
format!(r"\\wsl.localhost\{distro}").into()
|
||||
}
|
||||
|
||||
/// The names of a Linux path, `.` dropped and `..` taking the name before it.
|
||||
pub fn path_parts(linux: &str) -> Vec<&str> {
|
||||
let mut parts: Vec<&str> = Vec::new();
|
||||
for c in linux.split('/').filter(|c| !c.is_empty() && *c != ".") {
|
||||
if c == ".." {
|
||||
parts.pop();
|
||||
} else {
|
||||
parts.push(c);
|
||||
}
|
||||
}
|
||||
parts
|
||||
}
|
||||
|
||||
/// Where this machine reads the absolute path `linux` of `distro`: a drive mounted at
|
||||
/// `/mnt/<drive>` is read directly, anything else through [`share_root`]. `..` goes up
|
||||
/// within `linux`, never above the drive or the share.
|
||||
pub fn windows_path(linux: &str, distro: &str) -> std::path::PathBuf {
|
||||
let parts = path_parts(linux);
|
||||
let base = match parts.as_slice() {
|
||||
["mnt", drive, ..] if drive.len() == 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) => {
|
||||
let base = std::path::PathBuf::from(format!("{}:\\", drive.to_ascii_uppercase()));
|
||||
return parts[2..].iter().fold(base, |p, c| p.join(c));
|
||||
}
|
||||
_ => share_root(distro),
|
||||
};
|
||||
parts.iter().fold(base, |p, c| p.join(c))
|
||||
}
|
||||
|
||||
/// Runs `args` in `distro` without its shell and returns the standard output; a failed
|
||||
/// run is an error with its output. `wsl.exe`'s own messages are UTF-16: their NULs go.
|
||||
pub fn exec(distro: &str, args: &[&str], timeout: std::time::Duration) -> crate::IdeResult<String> {
|
||||
use crate::cli_process::{CliTool, Decoding};
|
||||
if !is_valid_distro(distro) {
|
||||
return Err(crate::IdeError::invalid(format!("'{distro}' is not a WSL distribution name")));
|
||||
}
|
||||
let mut cmd = std::process::Command::new(EXE);
|
||||
cmd.args(["-d", distro, "--exec"]).args(args);
|
||||
let out = CliTool::new(EXE, Decoding::Utf8Lossy).run(cmd, timeout, None)?;
|
||||
let (stdout, stderr) = (out.stdout.replace('\0', ""), out.stderr.replace('\0', ""));
|
||||
if out.success {
|
||||
return Ok(stdout);
|
||||
}
|
||||
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
|
||||
Err(crate::IdeError::internal(format!("{EXE} -d {distro} --exec {}: {detail}", args.first().unwrap_or(&""))))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -103,6 +172,21 @@ mod tests {
|
||||
assert_eq!(p(r"\\?\UNC\WSL.LOCALHOST\Ubuntu-24.04\home\me\app"), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_paths_map_onto_the_distro() {
|
||||
let l = |s: &str| linux_path(Path::new(s), "Ubuntu");
|
||||
assert_eq!(l(r"C:\Users\me\app"), Some("/mnt/c/Users/me/app".into()));
|
||||
assert_eq!(l(r"D:\"), Some("/mnt/d".into()));
|
||||
assert_eq!(l("e:/work/x/"), Some("/mnt/e/work/x".into()));
|
||||
assert_eq!(l(r"\\?\C:\proj"), Some("/mnt/c/proj".into()));
|
||||
assert_eq!(l(r"\\wsl.localhost\ubuntu\home\me"), Some("/home/me".into()));
|
||||
assert_eq!(l(r"\\wsl$\Debian\home\me"), None);
|
||||
assert_eq!(l(r"\\server\share\a"), None);
|
||||
assert_eq!(l(r"C:relative"), None);
|
||||
assert_eq!(l("app"), None);
|
||||
assert_eq!(l("/home/me"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distro_root_and_foreign_paths() {
|
||||
assert_eq!(p(r"\\wsl.localhost\Debian"), Some(("Debian".to_owned(), "/".to_owned())));
|
||||
@@ -127,6 +211,14 @@ mod tests {
|
||||
assert!(parse_distro_list(b"").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_paths_are_read_on_their_drive_or_through_the_share() {
|
||||
use std::path::PathBuf;
|
||||
assert_eq!(windows_path("/mnt/d/lib/../x.py", "U"), PathBuf::from("D:\\").join("x.py"));
|
||||
assert_eq!(windows_path("/usr/lib/a.py", "U"), share_root("U").join("usr").join("lib").join("a.py"));
|
||||
assert_eq!(windows_path("/mnt/wsl/x", "U"), share_root("U").join("mnt").join("wsl").join("x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distro_names_cannot_smuggle_options_or_paths() {
|
||||
for bad in ["", "-d", "--exec", "a b", "a/b", r"a\b", "a;b", "a$(x)", "a\"b"] {
|
||||
|
||||
@@ -360,9 +360,46 @@ fn find_binary_in(
|
||||
}
|
||||
|
||||
/// [`find_binary`], plus Xcode's toolchain on macOS (`xcrun -f lldb-dap`): Xcode ships
|
||||
/// lldb-dap without putting it on `PATH`.
|
||||
/// lldb-dap without putting it on `PATH`. Elsewhere lldb-dap may carry its LLVM version.
|
||||
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
|
||||
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd))
|
||||
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd)).or_else(|| {
|
||||
(command == "lldb-dap" && !cfg!(windows))
|
||||
.then(|| versioned_lldb_dap(&search_dirs(cwd), Path::new("/usr/lib")))
|
||||
.flatten()
|
||||
})
|
||||
}
|
||||
|
||||
/// Debian and Ubuntu install LLVM's lldb-dap as `lldb-dap-18` (`lldb-vscode-14` before
|
||||
/// LLVM 18 renamed it; same protocol) on `PATH`, or only as `/usr/lib/llvm-18/bin/lldb-dap`.
|
||||
/// The newest LLVM wins.
|
||||
fn versioned_lldb_dap(dirs: &[PathBuf], lib: &Path) -> Option<PathBuf> {
|
||||
let version = |name: &str| -> Option<u32> {
|
||||
let v = name.strip_prefix("lldb-dap-").or_else(|| name.strip_prefix("lldb-vscode-"))?;
|
||||
v.parse().ok()
|
||||
};
|
||||
let mut found: Vec<(u32, PathBuf)> = Vec::new();
|
||||
for dir in dirs {
|
||||
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
if let Some(v) = path.file_name().and_then(|n| n.to_str()).and_then(version)
|
||||
&& is_executable(&path, false)
|
||||
{
|
||||
found.push((v, path));
|
||||
}
|
||||
}
|
||||
}
|
||||
for entry in std::fs::read_dir(lib).into_iter().flatten().flatten() {
|
||||
let Some(v) = entry.file_name().to_str().and_then(|n| n.strip_prefix("llvm-")?.parse::<u32>().ok()) else {
|
||||
continue;
|
||||
};
|
||||
for name in ["lldb-dap", "lldb-vscode"] {
|
||||
let path = entry.path().join("bin").join(name);
|
||||
if is_executable(&path, false) {
|
||||
found.push((v, path));
|
||||
}
|
||||
}
|
||||
}
|
||||
found.into_iter().max_by_key(|(v, _)| *v).map(|(_, p)| p)
|
||||
}
|
||||
|
||||
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
|
||||
@@ -472,7 +509,7 @@ fn is_app_execution_alias(path: &Path) -> bool {
|
||||
|
||||
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
|
||||
/// "Interpreter `dap' unrecognized".
|
||||
const GDB_MIN_MAJOR: u32 = 14;
|
||||
pub(crate) const GDB_MIN_MAJOR: u32 = 14;
|
||||
|
||||
/// `(major, minor)` of the first version number in the output of `gdb --version`
|
||||
/// (`GNU gdb (GDB) 14.2`, `GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1`, `GNU gdb
|
||||
@@ -513,24 +550,29 @@ pub fn parse_gdb_version(output: &str) -> Option<(u32, u32)> {
|
||||
|
||||
/// Probe the already resolved and verified executable with its launch environment.
|
||||
async fn gdb_version(binary: &Path, spec: &AdapterSpec) -> IdeResult<Option<(u32, u32)>> {
|
||||
Ok(probe_gdb_version(binary, &spec.cwd, &spec.env).await)
|
||||
}
|
||||
|
||||
/// `(major, minor)` of `binary --version`, run in `cwd` with `env`; `None` when it doesn't say.
|
||||
pub(crate) async fn probe_gdb_version(binary: &Path, cwd: &Path, env: &[(String, String)]) -> Option<(u32, u32)> {
|
||||
let mut probe = Command::new(binary);
|
||||
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
|
||||
if let Some(path) = adapter_path(env, cwd) {
|
||||
probe.env("PATH", path);
|
||||
}
|
||||
probe.current_dir(&spec.cwd);
|
||||
probe.current_dir(cwd);
|
||||
ide_core::process::prepare(probe.as_std_mut());
|
||||
let probe = probe
|
||||
.arg("--version")
|
||||
.envs(spec.env.iter().cloned())
|
||||
.envs(env.iter().cloned())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output();
|
||||
let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(15), probe).await else {
|
||||
return Ok(None);
|
||||
return None;
|
||||
};
|
||||
Ok(parse_gdb_version(&String::from_utf8_lossy(&out.stdout)))
|
||||
parse_gdb_version(&String::from_utf8_lossy(&out.stdout))
|
||||
}
|
||||
|
||||
/// Refuse old GDB versions and report whether launch must follow configurationDone.
|
||||
@@ -543,8 +585,9 @@ async fn prepare_gdb(spec: &AdapterSpec, binary: &Path) -> IdeResult<bool> {
|
||||
return Ok(major == 15);
|
||||
}
|
||||
let mut msg = format!(
|
||||
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor}): \
|
||||
this one has no DAP interpreter (`gdb -i dap`)"
|
||||
"debugging with GDB needs GDB {GDB_MIN_MAJOR} or newer (found {major}.{minor} at {}): \
|
||||
this one has no DAP interpreter (`gdb -i dap`)",
|
||||
binary.display(),
|
||||
);
|
||||
if let Some(hint) = &spec.install_hint {
|
||||
msg.push_str(". ");
|
||||
@@ -570,11 +613,20 @@ pub fn not_standalone(spec: &AdapterSpec) -> IdeError {
|
||||
}
|
||||
|
||||
pub fn missing(spec: &AdapterSpec) -> IdeError {
|
||||
let no_prebuilt = ide_core::tool_path::netcoredbg_no_prebuilt(
|
||||
cfg!(all(target_os = "macos", target_arch = "x86_64")),
|
||||
cfg!(all(windows, target_arch = "aarch64")),
|
||||
)
|
||||
.filter(|_| spec.adapter == "netcoredbg");
|
||||
missing_with(spec, no_prebuilt.as_deref().or(spec.install_hint.as_deref()))
|
||||
}
|
||||
|
||||
fn missing_with(spec: &AdapterSpec, hint: Option<&str>) -> IdeError {
|
||||
let mut msg = format!(
|
||||
"debug adapter `{}` not found (`{}` is neither installed by OpenIDEA nor on PATH)",
|
||||
spec.adapter, spec.command
|
||||
);
|
||||
if let Some(hint) = &spec.install_hint {
|
||||
if let Some(hint) = hint {
|
||||
msg.push_str(". ");
|
||||
msg.push_str(hint);
|
||||
}
|
||||
@@ -1026,6 +1078,48 @@ mod tests {
|
||||
assert!(builtin("nope").is_none());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn gdb_version_check_probes_the_adapter_command() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let binary = dir.path().join("custom gdb");
|
||||
std::fs::write(&binary, "#!/bin/sh\n[ \"$1\" = --version ] && echo 'GNU gdb (GDB) 13.2'\n").unwrap();
|
||||
std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let mut spec = resolve(&builtin("gdb").unwrap(), dir.path().to_path_buf());
|
||||
spec.command = binary.to_str().unwrap().to_owned();
|
||||
|
||||
let Err(error) = ProcessLauncher.launch(spec, None).await else {
|
||||
panic!("GDB 13 was started as a DAP adapter");
|
||||
};
|
||||
assert_eq!(error.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(error.message.contains("needs GDB 14 or newer (found 13.2 at "), "{}", error.message);
|
||||
assert!(error.message.contains(binary.to_str().unwrap()), "{}", error.message);
|
||||
}
|
||||
|
||||
/// Debian/Ubuntu's versioned lldb-dap (and lldb-vscode before LLVM 18): the newest LLVM wins.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn finds_versioned_lldb_dap() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let exe = |p: &Path| {
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, "").unwrap();
|
||||
std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
};
|
||||
let (bin, lib) = (tmp.path().join("bin"), tmp.path().join("lib"));
|
||||
exe(&bin.join("lldb-vscode-14"));
|
||||
std::fs::write(bin.join("lldb-dap-99"), "").unwrap(); // not executable
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-vscode-14")));
|
||||
exe(&lib.join("llvm-18/bin/lldb-dap"));
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(lib.join("llvm-18/bin/lldb-dap")));
|
||||
exe(&bin.join("lldb-dap-19"));
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-dap-19")));
|
||||
assert_eq!(versioned_lldb_dap(&[], &tmp.path().join("none")), None);
|
||||
}
|
||||
|
||||
/// The first version number of `gdb --version`'s first line, however the distro decorates it.
|
||||
#[test]
|
||||
fn parses_gdb_versions() {
|
||||
@@ -1120,6 +1214,17 @@ mod tests {
|
||||
assert!(err.message.contains("Settings › Languages & Frameworks › Language Servers"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_netcoredbg_without_a_build_says_how_to_get_one() {
|
||||
let spec = resolve(&builtin("netcoredbg").unwrap(), std::env::temp_dir());
|
||||
let hint = ide_core::tool_path::netcoredbg_no_prebuilt(true, false).unwrap();
|
||||
let message = missing_with(&spec, Some(&hint)).message;
|
||||
assert!(message.starts_with("debug adapter `netcoredbg` not found"), "{message}");
|
||||
assert!(message.contains("no prebuilt netcoredbg for Intel Macs"), "{message}");
|
||||
assert!(message.contains("on PATH"), "{message}");
|
||||
assert_eq!(ide_core::tool_path::netcoredbg_no_prebuilt(false, false), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn process_launcher_reports_missing_binary() {
|
||||
let mut spec = resolve(&builtin("netcoredbg").unwrap(), std::env::temp_dir());
|
||||
|
||||
@@ -22,6 +22,7 @@ mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
mod memory;
|
||||
pub mod native;
|
||||
mod session;
|
||||
mod stream_trace;
|
||||
mod swiftpm;
|
||||
@@ -507,6 +508,11 @@ fn child_name(configuration: &Value, parent: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// LLDB-based adapters, which debug native programs (and Swift on Apple platforms).
|
||||
fn is_native(adapter: &str) -> bool {
|
||||
matches!(adapter, "lldb-dap" | "codelldb")
|
||||
}
|
||||
|
||||
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
|
||||
/// adapter.
|
||||
pub const RUN_LINK: &str = "__openideaRun";
|
||||
@@ -1049,6 +1055,15 @@ impl DebugManager {
|
||||
if let Some(command) = custom_command(&spec.command) {
|
||||
spec.command = command;
|
||||
}
|
||||
// The debugger of the run configuration's toolchain (a MinGW gdb), over every other choice.
|
||||
if let Some(command) = arguments
|
||||
.as_object_mut()
|
||||
.and_then(|o| o.remove(native::ADAPTER_COMMAND))
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
{
|
||||
spec.command = command;
|
||||
spec.pinned = None;
|
||||
}
|
||||
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy),
|
||||
// or with the launcher's when the debuggee runs through a manager (`uv run python`).
|
||||
if config.adapter == "debugpy" {
|
||||
@@ -1637,11 +1652,16 @@ impl DebugManager {
|
||||
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
|
||||
}
|
||||
if !graceful && (!own_terminate || killed) {
|
||||
// A native attach to a program a run started for the debugger (an Xcode app launched
|
||||
// with `simctl launch --wait-for-debugger`) ends it too: detached, the app can be
|
||||
// left stopped with the SIGTERM the run's Stop sent while it was traced, and the
|
||||
// simulator then holds its launch (and the next one) forever.
|
||||
let ends_debuggee = s.request == "launch" || (terminate && s.run.is_some() && is_native(&s.adapter));
|
||||
let _ = s
|
||||
.conn
|
||||
.request_timeout(
|
||||
"disconnect",
|
||||
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
|
||||
json!({ "restart": false, "terminateDebuggee": ends_debuggee }),
|
||||
SHUTDOWN_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
@@ -1785,7 +1805,8 @@ impl DebugManager {
|
||||
let mut states = self.states.lock();
|
||||
let Some(slot) = states.get_mut(path).and_then(|v| v.get_mut(index)) else { return false };
|
||||
let next = session::state_from(bp, slot.line);
|
||||
let next = BreakpointState { message: next.message.or_else(|| slot.message.clone()), ..next };
|
||||
let kept = slot.message.clone().filter(|m| !(next.verified && m == session::UNBOUND_NATIVE));
|
||||
let next = BreakpointState { message: next.message.or(kept), ..next };
|
||||
let changed = *slot != next;
|
||||
*slot = next;
|
||||
changed
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
//! C/C++ launches made for lldb-dap (CMake, Swift packages) fall back to CodeLLDB, then to
|
||||
//! GDB 14 or newer, when the host has no lldb-dap: Linux hosts rarely put one on `PATH`, and
|
||||
//! CodeLLDB is the debugger OpenIDEA can install itself.
|
||||
|
||||
use crate::LaunchConfig;
|
||||
use crate::adapter::{GDB_MIN_MAJOR, probe_gdb_version};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Launch argument naming the debugger to run (a toolchain's gdb or lldb-dap), which replaces
|
||||
/// the search: lldb-dap if its name says so, else GDB.
|
||||
pub const ADAPTER_COMMAND: &str = "__adapterCommand";
|
||||
|
||||
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
|
||||
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
|
||||
|
||||
/// `config` for the first of lldb-dap, CodeLLDB and GDB 14+ that `lookup` finds (it resolves a
|
||||
/// debugger command: a configured tool path, else the search path). Other launches pass through.
|
||||
pub async fn choose(
|
||||
mut config: LaunchConfig,
|
||||
lookup: impl Fn(&str) -> Option<PathBuf> + Send + 'static,
|
||||
) -> IdeResult<LaunchConfig> {
|
||||
if config.adapter != "lldb-dap" || config.request != "launch" {
|
||||
return Ok(config);
|
||||
}
|
||||
let chosen = config
|
||||
.extra_json
|
||||
.as_deref()
|
||||
.and_then(|e| serde_json::from_str::<Value>(e).ok())
|
||||
.and_then(|e| e[ADAPTER_COMMAND].as_str().map(PathBuf::from));
|
||||
let found = tokio::task::spawn_blocking(move || {
|
||||
if let Some(chosen) = chosen {
|
||||
let name = chosen.file_stem().map(|s| s.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
return if name.contains("lldb-dap") { Found::LldbDap } else { Found::Gdb(chosen) };
|
||||
}
|
||||
if lookup("lldb-dap").is_some() {
|
||||
return Found::LldbDap;
|
||||
}
|
||||
if lookup("codelldb").is_some() {
|
||||
return Found::CodeLldb;
|
||||
}
|
||||
lookup("gdb").map_or(Found::Nothing, Found::Gdb)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let cwd = config.cwd.clone().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
|
||||
match found {
|
||||
Found::LldbDap => {}
|
||||
Found::CodeLldb => convert(&mut config, "codelldb")?,
|
||||
Found::Gdb(gdb) => match probe_gdb_version(&gdb, &cwd, &[]).await {
|
||||
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((&gdb, major, minor)))),
|
||||
// Unknown versions are left to GDB itself, as a GDB launch does.
|
||||
_ => convert(&mut config, "gdb")?,
|
||||
},
|
||||
Found::Nothing => return Err(missing(None)),
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
enum Found {
|
||||
LldbDap,
|
||||
CodeLldb,
|
||||
Gdb(PathBuf),
|
||||
Nothing,
|
||||
}
|
||||
|
||||
fn missing(gdb: Option<(&Path, u32, u32)>) -> IdeError {
|
||||
let found = match gdb {
|
||||
Some((path, major, minor)) => format!(
|
||||
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} at {} cannot debug through DAP \
|
||||
(it needs GDB {GDB_MIN_MAJOR} or newer)",
|
||||
path.display(),
|
||||
),
|
||||
None => "lldb-dap, CodeLLDB and GDB are not installed".to_owned(),
|
||||
};
|
||||
IdeError::unavailable(format!(
|
||||
"{NO_NATIVE_DEBUGGER}: {found}. Install CodeLLDB, or install lldb-dap or GDB {GDB_MIN_MAJOR} or newer on this host"
|
||||
))
|
||||
}
|
||||
|
||||
/// Rewrites an lldb-dap launch for `to` (`codelldb` or `gdb`). lldb-dap takes the environment as
|
||||
/// `KEY=VALUE` strings and the source map as pairs; the others take the run configuration's
|
||||
/// environment map (`config.env`), CodeLLDB its source map as an object, GDB none.
|
||||
fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
|
||||
let mut extra = match config.extra_json.as_deref().filter(|e| !e.trim().is_empty()).map(serde_json::from_str) {
|
||||
None => Map::new(),
|
||||
Some(Ok(Value::Object(extra))) => extra,
|
||||
Some(Ok(other)) => return Err(IdeError::invalid(format!("launch arguments are not an object: {other}"))),
|
||||
Some(Err(e)) => return Err(IdeError::invalid(format!("invalid launch JSON: {e}"))),
|
||||
};
|
||||
extra.remove("env");
|
||||
let source_map = extra.remove("sourceMap");
|
||||
if to == "codelldb" {
|
||||
if let Some(Value::Array(pairs)) = source_map {
|
||||
let map: Map<String, Value> = pairs
|
||||
.iter()
|
||||
.filter_map(|pair| match pair.as_array().map(Vec::as_slice) {
|
||||
Some([Value::String(from), to]) => Some((from.clone(), to.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if !map.is_empty() {
|
||||
extra.insert("sourceMap".into(), Value::Object(map));
|
||||
}
|
||||
}
|
||||
// CodeLLDB evaluates as Rust unless told otherwise (ide-dap's default for it).
|
||||
let language = if extra.contains_key("swiftpm") { "swift" } else { "cpp" };
|
||||
extra.entry("sourceLanguages").or_insert_with(|| json!([language]));
|
||||
}
|
||||
config.adapter = to.to_owned();
|
||||
config.extra_json = (!extra.is_empty()).then(|| Value::Object(extra).to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn cmake_launch() -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
name: "hello".into(),
|
||||
adapter: "lldb-dap".into(),
|
||||
request: "launch".into(),
|
||||
program: Some("/home/dev/hello/build/hello".into()),
|
||||
args: vec![],
|
||||
cwd: Some(std::path::PathBuf::from("/").into()),
|
||||
env: BTreeMap::from([("A".into(), "1".into())]),
|
||||
extra_json: Some(json!({"env": ["A=1"], "sourceMap": [["/src", "/real/src"]]}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn extra(config: &LaunchConfig) -> Value {
|
||||
config.extra_json.as_deref().map_or(Value::Null, |e| serde_json::from_str(e).unwrap())
|
||||
}
|
||||
|
||||
fn only(names: &'static [&'static str]) -> impl Fn(&str) -> Option<PathBuf> + Send + 'static {
|
||||
move |c| names.contains(&c).then(|| PathBuf::from(format!("/usr/bin/{c}")))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn keeps_lldb_dap_when_it_is_there() {
|
||||
let config = choose(cmake_launch(), only(&["lldb-dap", "codelldb", "gdb"])).await.unwrap();
|
||||
assert_eq!(config.adapter, "lldb-dap");
|
||||
assert_eq!(config.extra_json, cmake_launch().extra_json);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn falls_back_to_codelldb_with_its_launch_shape() {
|
||||
let config = choose(cmake_launch(), only(&["codelldb", "gdb"])).await.unwrap();
|
||||
assert_eq!(config.adapter, "codelldb");
|
||||
assert_eq!(config.env, cmake_launch().env, "the environment comes from the run configuration's map");
|
||||
assert_eq!(
|
||||
extra(&config),
|
||||
json!({"sourceMap": {"/src": "/real/src"}, "sourceLanguages": ["cpp"]}),
|
||||
"no KEY=VALUE env strings; the source map as an object; C++ evaluation"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_swift_package_evaluates_swift_under_codelldb() {
|
||||
let mut launch = cmake_launch();
|
||||
launch.extra_json = Some(json!({"env": [], "swiftpm": {"product": "app", "buildArgs": []}}).to_string());
|
||||
let config = choose(launch, only(&["codelldb"])).await.unwrap();
|
||||
assert_eq!(extra(&config)["sourceLanguages"], json!(["swift"]));
|
||||
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_toolchain_debugger_replaces_the_search() {
|
||||
let mut launch = cmake_launch();
|
||||
launch.extra_json = Some(json!({"env": ["A=1"], ADAPTER_COMMAND: "/opt/mingw/bin/gdb.exe"}).to_string());
|
||||
// lldb-dap is there, but the toolchain names its GDB (an unknown version is left to GDB).
|
||||
let config = choose(launch, only(&["lldb-dap"])).await.unwrap();
|
||||
assert_eq!(config.adapter, "gdb");
|
||||
assert_eq!(extra(&config)[ADAPTER_COMMAND], "/opt/mingw/bin/gdb.exe", "kept for the adapter launch");
|
||||
let mut launch = cmake_launch();
|
||||
launch.extra_json = Some(json!({ADAPTER_COMMAND: "/opt/llvm/bin/lldb-dap"}).to_string());
|
||||
assert_eq!(choose(launch, only(&[])).await.unwrap().adapter, "lldb-dap");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_any_debugger_says_what_to_install() {
|
||||
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
|
||||
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
|
||||
assert!(e.message.contains("Install CodeLLDB"), "{}", e.message);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn other_launches_pass_through() {
|
||||
let mut attach = cmake_launch();
|
||||
attach.request = "attach".into();
|
||||
assert_eq!(choose(attach, only(&[])).await.unwrap().adapter, "lldb-dap");
|
||||
let mut rust = cmake_launch();
|
||||
rust.adapter = "codelldb".into();
|
||||
assert_eq!(choose(rust, only(&[])).await.unwrap().adapter, "codelldb");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn fake_gdb(dir: &Path, version: &str) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let gdb = dir.join("gdb");
|
||||
std::fs::write(&gdb, format!("#!/bin/sh\necho '{version}'\n")).unwrap();
|
||||
std::fs::set_permissions(&gdb, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
gdb
|
||||
}
|
||||
|
||||
/// Ubuntu 22.04's GDB 12 has no DAP interpreter: the error names its version (#7001).
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn an_old_gdb_is_named_in_the_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let gdb = fake_gdb(dir.path(), "GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1");
|
||||
let path = gdb.clone();
|
||||
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| path.clone())).await.unwrap_err();
|
||||
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
|
||||
assert!(e.message.contains("GDB 12.1"), "{}", e.message);
|
||||
assert!(e.message.contains(gdb.to_str().unwrap()), "{}", e.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn falls_back_to_a_gdb_with_dap() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let gdb = fake_gdb(dir.path(), "GNU gdb (GDB) 14.2");
|
||||
let config = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap();
|
||||
assert_eq!(config.adapter, "gdb");
|
||||
assert_eq!(extra(&config), Value::Null, "GDB takes the environment map and has no source map");
|
||||
}
|
||||
}
|
||||
@@ -293,6 +293,11 @@ impl Suspension {
|
||||
/// symlinked path (`/tmp/game` while the editor has `/private/tmp/game`).
|
||||
const RESOLVES_PATHS: &[&str] = &["godot"];
|
||||
|
||||
/// LLDB answers a breakpoint it can't bind yet with no reason: the code may simply not be loaded.
|
||||
const NATIVE_ADAPTERS: &[&str] = &["lldb-dap", "codelldb"];
|
||||
/// One literal: the UI looks it up in the text catalogs to translate it.
|
||||
pub(crate) const UNBOUND_NATIVE: &str = "No loaded code at this line yet. If it stays unbound after its module loads, the debug info may record this file under another path (through a symlink, or /tmp for /private/tmp): set a source map from that path to this one";
|
||||
|
||||
impl Session {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
@@ -514,6 +519,9 @@ impl Session {
|
||||
ids.insert(id, (path.to_path_buf(), i));
|
||||
}
|
||||
states[i] = state_from(r, breakpoints[i].line);
|
||||
if !states[i].verified && states[i].message.is_none() && NATIVE_ADAPTERS.contains(&self.adapter.as_str()) {
|
||||
states[i].message = Some(UNBOUND_NATIVE.to_owned());
|
||||
}
|
||||
}
|
||||
Ok(states)
|
||||
}
|
||||
@@ -1134,21 +1142,27 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
|
||||
// CodeLLDB's launcher clears the terminal first; the console keeps the session's earlier output.
|
||||
cmd.args(rest.iter().filter(|a| *a != "--clear-screen"));
|
||||
let cwd = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()).map_or(s.spec.cwd.as_path(), Path::new);
|
||||
for (k, v) in ide_core::process::host_env_fixes_in(cwd) {
|
||||
match v {
|
||||
Some(v) => cmd.env(k, v),
|
||||
None => cmd.env_remove(k),
|
||||
}
|
||||
// See #6806: do not inherit portable-pty's registry-built Windows env block.
|
||||
cmd.env_clear();
|
||||
for (k, v) in ide_core::process::spawnable_host_vars_in(cwd) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
for (k, v) in ide_core::process::shell_env_in(cwd) {
|
||||
cmd.env(k, v);
|
||||
if ide_core::process::is_spawnable_env_pair(&k, &v) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
}
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.cwd(cwd);
|
||||
if let Some(env) = args.get("env").and_then(Value::as_object) {
|
||||
for (k, v) in env {
|
||||
match v.as_str() {
|
||||
Some(v) => cmd.env(k, v),
|
||||
Some(v)
|
||||
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) =>
|
||||
{
|
||||
cmd.env(k, v)
|
||||
}
|
||||
Some(_) => {}
|
||||
None => cmd.env_remove(k),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -138,6 +138,8 @@ struct Script {
|
||||
output_after_terminate: bool,
|
||||
/// Advertise `supportsTerminateRequest` (java-debug does not, so Stop signals the program).
|
||||
supports_terminate: bool,
|
||||
/// Answer `setBreakpoints` with unverified breakpoints and no reason (LLDB before the code loads).
|
||||
unbound_breakpoints: bool,
|
||||
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
|
||||
hold_set_breakpoints: usize,
|
||||
/// Send a `continued` event right after the first `stopped` one.
|
||||
@@ -220,6 +222,7 @@ impl Default for Script {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
run_in_terminal: None,
|
||||
unbound_breakpoints: false,
|
||||
start_debugging: false,
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
@@ -414,7 +417,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
.unwrap()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
|
||||
.map(|(i, b)| json!({"id": i + 1, "verified": !script.unbound_breakpoints, "line": b["line"]}))
|
||||
.collect();
|
||||
ok!(msg, json!({"breakpoints": bps}));
|
||||
}
|
||||
@@ -4019,6 +4022,50 @@ async fn stop_detaches_from_an_attached_program() {
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
/// Xcode Debug: lldb-dap attaches to the app a run launched suspended. Stop ends the app through
|
||||
/// the debugger; detaching would leave it stopped with the run's SIGTERM, holding the simulator.
|
||||
#[tokio::test]
|
||||
async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
|
||||
let h = harness(Script::default());
|
||||
let linked = |adapter: &str| LaunchConfig {
|
||||
adapter: adapter.into(),
|
||||
request: "attach".into(),
|
||||
extra_json: Some(json!({ RUN_LINK: 7, "pid": 4242 }).to_string()),
|
||||
..config()
|
||||
};
|
||||
let id = h.start(linked("lldb-dap")).await.unwrap();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], true);
|
||||
|
||||
// Another adapter's attach to a run (a Gradle test worker JVM) still only detaches.
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(linked("debugpy")).await.unwrap();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
|
||||
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
|
||||
#[tokio::test]
|
||||
async fn an_unbound_native_breakpoint_says_why() {
|
||||
for (adapter, hint) in [("lldb-dap", true), ("codelldb", true), ("debugpy", false)] {
|
||||
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
|
||||
h.start(LaunchConfig { adapter: adapter.into(), ..config() }).await.unwrap();
|
||||
let path = PathBuf::from("/private/tmp/app/Counter.swift");
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path, vec![bp(6)]).await.unwrap();
|
||||
assert!(!states[0].verified);
|
||||
assert_eq!(states[0].message.as_deref() == Some(crate::session::UNBOUND_NATIVE), hint, "{adapter}");
|
||||
}
|
||||
|
||||
// Bound once the module loads (lldb-dap's `breakpoint` event has no message): the hint goes.
|
||||
let path = PathBuf::from("/private/tmp/app/Counter.swift");
|
||||
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
|
||||
h.start(LaunchConfig { adapter: "lldb-dap".into(), ..config() }).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(6)]).await.unwrap();
|
||||
assert!(h.manager.update_breakpoint_state(&path, 0, &json!({"id": 1, "verified": true, "line": 7})));
|
||||
assert_eq!(h.manager.breakpoint_states(&path)[0].message, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
|
||||
use crate::jvm_memory::test_support::bare_session_of;
|
||||
|
||||
Loaded 100 of 2189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача