дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 09:11:10 +02:00
Порівняти коміти
317
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
eaacc876a8 | ||
|
|
16e160f5b9 | ||
|
|
0d3e9a27cc | ||
|
|
3a31ec25aa | ||
|
|
693b24bf65 | ||
|
|
6304811ac9 | ||
|
|
d55f116add | ||
|
|
d62c978032 | ||
|
|
5f452a8e36 | ||
|
|
7992063ef2 | ||
|
|
34cb6a45cd | ||
|
|
e670463b8e | ||
|
|
2b0cc6b733 | ||
|
|
152f7123a0 | ||
|
|
a223f3e6b2 | ||
|
|
9c73f7d784 | ||
|
|
9ad7f91c04 | ||
|
|
5ec05b3aca | ||
|
|
26688a79f7 | ||
|
|
c6428a8e4c | ||
|
|
9e3077753d | ||
|
|
7d33b470f2 | ||
|
|
5bfdaf679d | ||
|
|
ab08c3d245 | ||
|
|
1ee5f0d71d | ||
|
|
d2686f922d | ||
|
|
35682aadc2 | ||
|
|
35529ddd64 | ||
|
|
f5abe8b509 | ||
|
|
c1cde544fb | ||
|
|
40ea4267bd | ||
|
|
377e900e84 | ||
|
|
74b2b5113b | ||
|
|
68a322edad | ||
|
|
ba04c34710 | ||
|
|
cddf57d4c7 | ||
|
|
8c82d9924c | ||
|
|
a050a8054f | ||
|
|
a12999c3d5 | ||
|
|
309a805794 | ||
|
|
ac9198dd52 | ||
|
|
7eed207163 | ||
|
|
952c67f752 | ||
|
|
e4d0a36b5a | ||
|
|
d1f311d2a3 | ||
|
|
52e81f8158 | ||
|
|
7cca129a8e | ||
|
|
006ab617e8 | ||
|
|
fbc4c51c8f | ||
|
|
6f68b8659d | ||
|
|
f49782daaf | ||
|
|
69374c8868 | ||
|
|
7c9fa1dc3b | ||
|
|
c412491972 | ||
|
|
6fbbab6c6f | ||
|
|
eb2be13a1e | ||
|
|
7fd5ad50b8 | ||
|
|
b21be36bf8 | ||
|
|
35e4b4cc92 | ||
|
|
f1876f1260 | ||
|
|
703c33a089 | ||
|
|
16def0187c | ||
|
|
d61ffa5430 | ||
|
|
9fcd7c1468 | ||
|
|
a6aa26ea2a | ||
|
|
ea4ac8cc6e | ||
|
|
f62b89fccc | ||
|
|
3edc7ee1a0 | ||
|
|
42b6363646 | ||
|
|
7ff13704ff | ||
|
|
a53e25f398 | ||
|
|
ade8bdd36a | ||
|
|
0e221ba78a | ||
|
|
5f31f1292a | ||
|
|
5de7b0964e | ||
|
|
61418e9cb5 | ||
|
|
fd22254194 | ||
|
|
e666bb2e33 | ||
|
|
4f2d85007b | ||
|
|
6e5f91f7fd | ||
|
|
e38599b82b | ||
|
|
437008c517 | ||
|
|
5947204022 | ||
|
|
d4a2a84c36 | ||
|
|
1c94aeb476 | ||
|
|
b9014f34cf | ||
|
|
0920f189d6 | ||
|
|
a3c7591624 | ||
|
|
1ba9ace7e2 | ||
|
|
d8e58296be | ||
|
|
196057019f | ||
|
|
272a183442 | ||
|
|
cd57b7f053 | ||
|
|
45dd96cdeb | ||
|
|
22db3ab9c3 | ||
|
|
343dd51082 | ||
|
|
75c57e2691 | ||
|
|
856fc3009e | ||
|
|
3f7a072fa1 | ||
|
|
c9a2b6200e | ||
|
|
c1d552e578 | ||
|
|
02d22fe658 | ||
|
|
7f9a618cac | ||
|
|
1877d8c1a1 | ||
|
|
839da450f7 | ||
|
|
ba42061885 | ||
|
|
2b359f9a98 | ||
|
|
b83c1a60c2 | ||
|
|
f213999338 | ||
|
|
920e321109 | ||
|
|
ede0705bd5 | ||
|
|
a75c332905 | ||
|
|
954180beb0 | ||
|
|
eb6483030c | ||
|
|
6c9c02417e | ||
|
|
9e7f842caf | ||
|
|
0bda7b194b | ||
|
|
9ab90941ef | ||
|
|
1dc1c67095 | ||
|
|
6f7c8e246f | ||
|
|
5638f8d04e | ||
|
|
f156baa976 | ||
|
|
d41bccc50c | ||
|
|
9087fa61d9 | ||
|
|
6404c30718 | ||
|
|
66a765664c | ||
|
|
fe1b5eacf8 | ||
|
|
21c4b08a5d | ||
|
|
f8e0ad57ff | ||
|
|
72e1d6afc1 | ||
|
|
8ffd6c9e2c | ||
|
|
dbfec0c433 | ||
|
|
1bdd5b4094 | ||
|
|
88eba9f3bd | ||
|
|
8044948178 | ||
|
|
0425004ecd | ||
|
|
c1b45b037d | ||
|
|
f5732dd706 | ||
|
|
e86e28ae63 | ||
|
|
82fdd97588 | ||
|
|
1757d26e78 | ||
|
|
766e1edc0c | ||
|
|
fc52975be0 | ||
|
|
c3726daed6 | ||
|
|
69c9521e85 | ||
|
|
fc60719d4b | ||
|
|
e35ba7d805 | ||
|
|
fa0783ab03 | ||
|
|
5338a34008 | ||
|
|
1d3547a953 | ||
|
|
14ed7aa647 | ||
|
|
27164e8919 | ||
|
|
62bac6ec8c | ||
|
|
17a32e0c1f | ||
|
|
e0ed6a0a3b | ||
|
|
db0cdccd66 | ||
|
|
4237117f2c | ||
|
|
26edc6d826 | ||
|
|
92c71837cb | ||
|
|
0791e73974 | ||
|
|
a8773a196c | ||
|
|
5f50469d7e | ||
|
|
9e4fbe863d | ||
|
|
7fdd39a628 | ||
|
|
9d8fdab75e | ||
|
|
f09d51bd49 | ||
|
|
00aef16862 | ||
|
|
87b659b3ac | ||
|
|
709cde907e | ||
|
|
6a69707220 | ||
|
|
e30651473d | ||
|
|
8397e5e2a3 | ||
|
|
890fade636 | ||
|
|
dfe4784874 | ||
|
|
43c9053624 | ||
|
|
05c64c2475 | ||
|
|
3334d1016b | ||
|
|
637e227efa | ||
|
|
5432d7f288 | ||
|
|
2fdc024358 | ||
|
|
84267f44ed | ||
|
|
e08e455fe5 | ||
|
|
ceb020857a | ||
|
|
e8f5f6d6ba | ||
|
|
b0f5c9aed0 | ||
|
|
f40550e0cf | ||
|
|
43d668dc75 | ||
|
|
81a746b8e2 | ||
|
|
0aaa586cec | ||
|
|
159f10ba82 | ||
|
|
355d6005aa | ||
|
|
98a6de6ff0 | ||
|
|
2f3f08efde | ||
|
|
797904c308 | ||
|
|
c8f9f9cc37 | ||
|
|
db57c0961e | ||
|
|
70f6316a69 | ||
|
|
ac68fbe39e | ||
|
|
41f4e22b29 | ||
|
|
af2e515d0f | ||
|
|
a1ed7af5cf | ||
|
|
43dac21ac3 | ||
|
|
0d3b001191 | ||
|
|
0f328854a2 | ||
|
|
5ae211ecd6 | ||
|
|
55274d2dd1 | ||
|
|
72f7b59e3b | ||
|
|
581672eebc | ||
|
|
eace2fc741 | ||
|
|
f39b728947 | ||
|
|
f307355369 | ||
|
|
611f40c6ce | ||
|
|
391b91539f | ||
|
|
5633d76da1 | ||
|
|
310cbaad66 | ||
|
|
bc63e8e029 | ||
|
|
a579d81694 | ||
|
|
6eb1f0713d | ||
|
|
95d4a41b62 | ||
|
|
18ac414b52 | ||
|
|
10e399cbec | ||
|
|
ce4b2f9655 | ||
|
|
65686e246e | ||
|
|
3078674a86 | ||
|
|
82d8a6ea19 | ||
|
|
3785b75582 | ||
|
|
15b55c66ca | ||
|
|
d6d6fd0909 | ||
|
|
7bfad25bb5 | ||
|
|
5c31ccfe70 | ||
|
|
304674d0fe | ||
|
|
aa003541a3 | ||
|
|
d2699c430e | ||
|
|
f404a33e7a | ||
|
|
05e7db4be6 | ||
|
|
8ad3fc4faf | ||
|
|
3f7b83e8fd | ||
|
|
7fa280e9e0 | ||
|
|
3c8acf8ee3 | ||
|
|
0d94a8973e | ||
|
|
18f28cd804 | ||
|
|
37f2dd3ced | ||
|
|
ba5eb92c70 | ||
|
|
bbbcf23c77 | ||
|
|
ac9f745dcf | ||
|
|
86cfabfbe4 | ||
|
|
6b038245fd | ||
|
|
e985322f3a | ||
|
|
1f329cbc87 | ||
|
|
0f0cdd4672 | ||
|
|
875b17938e | ||
|
|
6820d27af5 | ||
|
|
02aa916a26 | ||
|
|
a7b9529109 | ||
|
|
0303a513cd | ||
|
|
a2bf7fb0c4 | ||
|
|
17dd723a3d | ||
|
|
f1097831d7 | ||
|
|
ad0a755f07 | ||
|
|
099bb57abd | ||
|
|
1ba2ce55bb | ||
|
|
24588b0975 | ||
|
|
8dc1fecc0e | ||
|
|
cb7668d4f0 | ||
|
|
90377204aa | ||
|
|
1d3de3c366 | ||
|
|
4466a059b3 | ||
|
|
b7bacc8ff5 | ||
|
|
50508b0af0 | ||
|
|
ef4458c04c | ||
|
|
0666f9ea5a | ||
|
|
3fe4e12252 | ||
|
|
9ecb664036 | ||
|
|
e6c8d6d9ac | ||
|
|
a68ebc1293 | ||
|
|
8b267c6307 | ||
|
|
67460f1275 | ||
|
|
4a620287c8 | ||
|
|
607812d8fa | ||
|
|
90f9d4ffd0 | ||
|
|
0f359ddf3b | ||
|
|
51a6b40314 | ||
|
|
bd5af356f4 | ||
|
|
d3cb8513be | ||
|
|
29d1a52d91 | ||
|
|
5b24b61b49 | ||
|
|
1dd8ea9b3b | ||
|
|
2221afad01 | ||
|
|
471bce2bb1 | ||
|
|
b630dfad55 | ||
|
|
74b50f7592 | ||
|
|
95bc3622ab | ||
|
|
b911366115 | ||
|
|
b2a9d105e2 | ||
|
|
b83c2cf11a | ||
|
|
6648f502f1 | ||
|
|
115003f0b6 | ||
|
|
02d912d72a | ||
|
|
70fe0e6653 | ||
|
|
950bf986d6 | ||
|
|
310d923480 | ||
|
|
0c506fa479 | ||
|
|
bc86836492 | ||
|
|
dead55af21 | ||
|
|
c7a4201ce9 | ||
|
|
91cf66e72e | ||
|
|
4a87022e58 | ||
|
|
c92bd0999b | ||
|
|
880835f0ac | ||
|
|
ce938df81b | ||
|
|
9abe3d7e3c | ||
|
|
4e5ae49aa9 | ||
|
|
9443517d1c | ||
|
|
29f6131f9d | ||
|
|
4027b8341f | ||
|
|
ddc483fd2a | ||
|
|
23d81a2b3d |
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
|
||||
Бінарний файл не відображається.
|
До Ширина: | Висота: | Розмір: 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:
|
||||
@@ -370,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
|
||||
|
||||
@@ -47,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"
|
||||
@@ -111,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|inlineBg|lineNumberOptions|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);
|
||||
|
||||
+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/
|
||||
@@ -20,6 +20,7 @@
|
||||
"pnpm-lock.yaml",
|
||||
"**/*.toml",
|
||||
"fixtures",
|
||||
"vendor",
|
||||
"plugins/*/web",
|
||||
"plugins/official/*/web",
|
||||
"crates/**/tests/fixtures"
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"src/editor/core/cm/angular/parser*.ts",
|
||||
"src/editor/core/cm/astro/parser*.ts",
|
||||
"fixtures",
|
||||
"vendor",
|
||||
"plugins",
|
||||
"test-results",
|
||||
"playwright-report",
|
||||
|
||||
@@ -0,0 +1,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.
|
||||
Створено
+279
-411
File diff suppressed because it is too large.
Load diff
+7
-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"
|
||||
@@ -161,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" }
|
||||
+1
-1
@@ -74,7 +74,7 @@ the [official plugins](plugins/official). The plugin API is still a preview.
|
||||
- [Discord](https://discord.gg/AsZqMgxZm) — questions, feedback and release news.
|
||||
- WeChat group — scan to join:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat group QR code" width="200">
|
||||
<img src=".github/assets/wechat-group-5.png" alt="WeChat group QR code" width="200">
|
||||
|
||||
- Contributing: see [CONTRIBUTING.md](CONTRIBUTING.md) and the [contributor docs](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ Eklentileri Ayarlar › Eklentiler (Settings › Plugins) bölümünden kur ya d
|
||||
- [Discord](https://discord.gg/AsZqMgxZm): sorular, geri bildirim ve sürüm haberleri.
|
||||
- WeChat grubu, katılmak için kodu okut:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="WeChat grubu QR kodu" width="200">
|
||||
<img src=".github/assets/wechat-group-5.png" alt="WeChat grubu QR kodu" width="200">
|
||||
|
||||
- Katkıda bulunmak için: [CONTRIBUTING.md](CONTRIBUTING.md) ve [katkıcı belgeleri](https://openidea.sh/en/contribute/setup).
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ WebAssembly 组件运行;主题、图标主题和语言无需编写代码。
|
||||
- [Discord](https://discord.gg/AsZqMgxZm):提问、反馈和版本发布消息。
|
||||
- 微信群,扫码加入:
|
||||
|
||||
<img src=".github/assets/wechat-group-4.png" alt="微信群二维码" width="200">
|
||||
<img src=".github/assets/wechat-group-5.png" alt="微信群二维码" width="200">
|
||||
|
||||
- 参与贡献:参见 [CONTRIBUTING.md](CONTRIBUTING.md) 和[贡献者文档](https://openidea.sh/zh/contribute/setup)。
|
||||
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -189,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,
|
||||
|
||||
@@ -50,6 +50,10 @@ fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
/// Whether each scheduled firing starts a fresh task or continues the previous task's conversation.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -242,6 +246,10 @@ pub struct AgentAutomation {
|
||||
#[specta(optional)]
|
||||
pub memory_overrides: Option<AgentMemoryOverrides>,
|
||||
pub trigger: AutomationTrigger,
|
||||
/// When `true`, runs of this automation may call the `schedule_next_run` MCP tool to set
|
||||
/// their own next firing time and prompt without interactive human confirmation.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub allow_agent_schedule: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub misfire_policy: Option<AutomationMisfirePolicy>,
|
||||
@@ -254,6 +262,16 @@ pub struct AgentAutomation {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub next_run_ms: Option<f64>,
|
||||
/// Pending one-time firing timestamp scheduled by the agent via `schedule_next_run`.
|
||||
/// Consumed on the next firing without altering [`Self::trigger`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub next_run_override_ms: Option<f64>,
|
||||
/// Pending one-time prompt instructions scheduled by the agent via `schedule_next_run`.
|
||||
/// Consumed on the next firing without altering [`Self::prompt`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub next_prompt_override: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub paused_reason: Option<String>,
|
||||
@@ -292,6 +310,13 @@ pub struct SaveAutomationInput {
|
||||
pub memory_overrides: Option<AgentMemoryOverrides>,
|
||||
pub trigger: AutomationTrigger,
|
||||
#[serde(default)]
|
||||
pub allow_agent_schedule: bool,
|
||||
/// When `true` on an update, explicitly discards any pending agent-scheduled
|
||||
/// `next_run_override_ms` / `next_prompt_override` and reverts to the regular `trigger`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub clear_override: bool,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub misfire_policy: Option<AutomationMisfirePolicy>,
|
||||
#[serde(default)]
|
||||
@@ -739,6 +764,34 @@ pub fn preview_trigger_runs(trigger: &AutomationTrigger, from_ms: f64, count: us
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats an epoch-millisecond timestamp in `trigger`'s timezone (or system local timezone for
|
||||
/// `OneShot` / `Manual`) as an ISO-8601 zoned string.
|
||||
pub fn format_trigger_timestamp(trigger: &AutomationTrigger, ms: f64) -> Option<String> {
|
||||
if !ms.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let ts = jiff::Timestamp::from_millisecond(ms.round() as i64).ok()?;
|
||||
let tz_name = match trigger {
|
||||
AutomationTrigger::Hourly { time_zone, .. }
|
||||
| AutomationTrigger::Daily { time_zone, .. }
|
||||
| AutomationTrigger::Weekdays { time_zone, .. }
|
||||
| AutomationTrigger::Weekly { time_zone, .. }
|
||||
| AutomationTrigger::Cron { time_zone, .. } => time_zone.as_str(),
|
||||
AutomationTrigger::Manual | AutomationTrigger::OneShot { .. } => "local",
|
||||
};
|
||||
let tz = resolve_time_zone(tz_name).ok()?;
|
||||
Some(ts.to_zoned(tz).to_string())
|
||||
}
|
||||
|
||||
/// Parses an ISO-8601 / RFC-3339 timestamp string into epoch milliseconds.
|
||||
pub fn parse_iso_timestamp_ms(raw: &str) -> IdeResult<f64> {
|
||||
let ts = raw
|
||||
.trim()
|
||||
.parse::<jiff::Timestamp>()
|
||||
.map_err(|e| IdeError::invalid(format!("invalid ISO-8601 timestamp '{}': {e}", raw.trim())))?;
|
||||
Ok(ts.as_millisecond() as f64)
|
||||
}
|
||||
|
||||
/// Parses an interval string such as `"10m"`, `"90s"`, `"2h"`, `"1d"`, `"15 minutes"` into seconds.
|
||||
pub fn parse_interval_secs(raw: &str, min_secs: u64, max_secs: u64) -> IdeResult<u64> {
|
||||
let trimmed = raw.trim().to_ascii_lowercase();
|
||||
@@ -783,6 +836,8 @@ pub struct PortableAutomation {
|
||||
#[specta(optional)]
|
||||
pub description: Option<String>,
|
||||
pub trigger: AutomationTrigger,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub allow_agent_schedule: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub disable_after_ms: Option<f64>,
|
||||
@@ -813,7 +868,7 @@ pub fn slugify_id(name: &str) -> String {
|
||||
/// Exports an [`AgentAutomation`] into the portable `.automation.md` format (YAML frontmatter + prompt body).
|
||||
pub fn export_markdown(automation: &AgentAutomation) -> IdeResult<String> {
|
||||
let has_disable = automation.disable_after_ms.is_some() || automation.max_runs.is_some();
|
||||
let version = if has_disable { 2 } else { 1 };
|
||||
let version = if has_disable || automation.allow_agent_schedule { 2 } else { 1 };
|
||||
let slug = slugify_id(&automation.name);
|
||||
let id = if slug.is_empty() { automation.id.clone() } else { slug };
|
||||
let mut out = String::new();
|
||||
@@ -821,6 +876,9 @@ pub fn export_markdown(automation: &AgentAutomation) -> IdeResult<String> {
|
||||
out.push_str(&format!("version: {version}\n"));
|
||||
out.push_str(&format!("id: {}\n", yaml_scalar(&id)));
|
||||
out.push_str(&format!("name: {}\n", yaml_scalar(&automation.name)));
|
||||
if automation.allow_agent_schedule {
|
||||
out.push_str("allowAgentSchedule: true\n");
|
||||
}
|
||||
out.push_str("schedule:\n");
|
||||
match &automation.trigger {
|
||||
AutomationTrigger::Manual => {
|
||||
@@ -883,6 +941,7 @@ pub fn parse_markdown(markdown: &str) -> IdeResult<PortableAutomation> {
|
||||
let mut id: Option<String> = None;
|
||||
let mut name: Option<String> = None;
|
||||
let mut description: Option<String> = None;
|
||||
let mut allow_agent_schedule = false;
|
||||
let mut sched_kind = String::from("manual");
|
||||
let mut sched_expr: Option<String> = None;
|
||||
let mut sched_run_at: Option<String> = None;
|
||||
@@ -921,6 +980,7 @@ pub fn parse_markdown(markdown: &str) -> IdeResult<PortableAutomation> {
|
||||
"id" => id = Some(val),
|
||||
"name" => name = Some(val),
|
||||
"description" => description = Some(val),
|
||||
"allowAgentSchedule" => allow_agent_schedule = val.eq_ignore_ascii_case("true"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -989,7 +1049,7 @@ pub fn parse_markdown(markdown: &str) -> IdeResult<PortableAutomation> {
|
||||
other => return Err(IdeError::invalid(format!("unsupported schedule kind '{other}'"))),
|
||||
};
|
||||
|
||||
Ok(PortableAutomation { id, name, description, trigger, disable_after_ms, max_runs, prompt })
|
||||
Ok(PortableAutomation { id, name, description, trigger, allow_agent_schedule, disable_after_ms, max_runs, prompt })
|
||||
}
|
||||
|
||||
fn yaml_scalar(s: &str) -> String {
|
||||
@@ -1182,10 +1242,13 @@ mod tests {
|
||||
expression: "30 10 * * FRI".into(),
|
||||
time_zone: "America/Los_Angeles".into(),
|
||||
},
|
||||
allow_agent_schedule: true,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: Some(ts_ms("2027-03-01T00:00:00Z")),
|
||||
max_runs: Some(25),
|
||||
next_run_ms: None,
|
||||
next_run_override_ms: None,
|
||||
next_prompt_override: None,
|
||||
paused_reason: None,
|
||||
run_count: 0,
|
||||
unread_runs: 0,
|
||||
@@ -1194,9 +1257,11 @@ mod tests {
|
||||
};
|
||||
let md = export_markdown(&auto).unwrap();
|
||||
assert!(md.contains("version: 2\n"));
|
||||
assert!(md.contains("allowAgentSchedule: true\n"));
|
||||
let parsed = parse_markdown(&md).unwrap();
|
||||
assert_eq!(parsed.id, "weekly-review-core-rpc");
|
||||
assert_eq!(parsed.name, "Weekly Review: Core & RPC");
|
||||
assert!(parsed.allow_agent_schedule);
|
||||
assert_eq!(parsed.disable_after_ms, Some(ts_ms("2027-03-01T00:00:00Z")));
|
||||
assert_eq!(parsed.max_runs, Some(25));
|
||||
assert_eq!(parsed.prompt, "Inspect open PRs and run /code-review.");
|
||||
|
||||
@@ -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,
|
||||
@@ -61,14 +127,50 @@ impl AgentManager {
|
||||
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
};
|
||||
let prefix = self.shared.paths.cli_dir.join(id);
|
||||
let managed = spec.managed_cli.is_some().then_some(prefix.as_path());
|
||||
let _lock = if offer.is_some() { managed.map(lock_prefix).transpose()? } else { None };
|
||||
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, managed, offer, cancel) {
|
||||
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const INSTALLED_MARKER: &str = ".openidea-installed";
|
||||
|
||||
fn lock_prefix(prefix: &Path) -> IdeResult<fs::File> {
|
||||
fs::create_dir_all(prefix)?;
|
||||
let lock = fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(prefix.join(".openidea-install.lock"))?;
|
||||
lock.try_lock().map_err(|error| match error {
|
||||
fs::TryLockError::WouldBlock => IdeError::new(ErrorKind::AlreadyExists, "CLI installation is in progress"),
|
||||
fs::TryLockError::Error(error) => error.into(),
|
||||
})?;
|
||||
Ok(lock)
|
||||
}
|
||||
|
||||
pub(crate) fn managed_cli(prefix: &Path, pkg: &str, bin: &str) -> Option<PathBuf> {
|
||||
let link = Installation::at(prefix, pkg, bin).link;
|
||||
(prefix.join(INSTALLED_MARKER).is_file() && provider::installed_with_env(&link.to_string_lossy(), &[]))
|
||||
.then_some(link)
|
||||
}
|
||||
|
||||
pub(crate) fn install_command(prefix: &Path, pkg: &str) -> Option<String> {
|
||||
let spec = format!("{pkg}@latest");
|
||||
let args = install_args(prefix.to_str()?, &spec);
|
||||
Some(provider::render_shell_command(Path::new("npm"), args, cfg!(windows)))
|
||||
}
|
||||
|
||||
fn install_args<'a>(prefix: &'a str, spec: &'a str) -> [&'a str; 7] {
|
||||
["install", "-g", "--prefix", prefix, "--no-audit", "--no-fund", spec]
|
||||
}
|
||||
|
||||
struct Installation {
|
||||
modules: PathBuf,
|
||||
folder: PathBuf,
|
||||
@@ -151,47 +253,19 @@ fn maintain(
|
||||
program: &Path,
|
||||
bin: &str,
|
||||
pkg: &str,
|
||||
managed: Option<&Path>,
|
||||
approved: Option<&AgentCliOffer>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<AgentCliUpdateResult> {
|
||||
use AgentCliUpdateResult::*;
|
||||
let run = |args: &[&str]| {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.args(args)
|
||||
.current_dir(npm.parent().unwrap())
|
||||
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
|
||||
.env("NPM_CONFIG_LOGLEVEL", "error");
|
||||
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
|
||||
if e.kind == ErrorKind::Cancelled {
|
||||
return e;
|
||||
}
|
||||
// npm diagnostics can contain private registry URLs; expose only known codes.
|
||||
let code = e
|
||||
.message
|
||||
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
|
||||
.find(|w| {
|
||||
matches!(
|
||||
*w,
|
||||
"EACCES"
|
||||
| "EPERM"
|
||||
| "EROFS"
|
||||
| "ENOTFOUND"
|
||||
| "EAI_AGAIN"
|
||||
| "ETIMEDOUT"
|
||||
| "E404"
|
||||
| "E401"
|
||||
| "E403"
|
||||
)
|
||||
})
|
||||
.unwrap_or("npm");
|
||||
IdeError::unavailable(code)
|
||||
})
|
||||
let run = |args: &[&str]| run_npm(npm, args, cancel);
|
||||
let output;
|
||||
let prefix = if let Some(prefix) = managed {
|
||||
prefix
|
||||
} else {
|
||||
output = run(&["prefix", "-g"])?;
|
||||
Path::new(output.trim_end())
|
||||
};
|
||||
let output = run(&["prefix", "-g"])?;
|
||||
let prefix = Path::new(output.trim_end());
|
||||
if !prefix.is_absolute() {
|
||||
return Err(IdeError::invalid("Invalid npm global prefix"));
|
||||
}
|
||||
@@ -212,21 +286,42 @@ fn maintain(
|
||||
if approved != Some(&offer) {
|
||||
return Ok(Available(offer));
|
||||
}
|
||||
run(&[
|
||||
"install",
|
||||
"-g",
|
||||
"--prefix",
|
||||
prefix.to_str().unwrap(),
|
||||
"--no-audit",
|
||||
"--no-fund",
|
||||
&format!("{pkg}@{}", offer.latest),
|
||||
])?;
|
||||
run(&install_args(prefix.to_str().unwrap(), &format!("{pkg}@{}", offer.latest)))?;
|
||||
if installation.version(program, pkg, bin)?.as_ref() != Some(&offer.latest) {
|
||||
return Err(IdeError::invalid("npm installation verification failed"));
|
||||
}
|
||||
Ok(Updated { current: offer.latest })
|
||||
}
|
||||
|
||||
fn run_npm(npm: &Path, args: &[&str], cancel: &CancellationToken) -> IdeResult<String> {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let mut cmd = Command::new(npm);
|
||||
cmd.args(args)
|
||||
.current_dir(npm.parent().unwrap())
|
||||
.env("PATH", ide_core::tool_path::search_path())
|
||||
.env("NPM_CONFIG_UPDATE_NOTIFIER", "false")
|
||||
.env("NPM_CONFIG_LOGLEVEL", "error");
|
||||
ide_tools::run_streamed(cmd, cancel, &|_| {}).map_err(|e| {
|
||||
if e.kind == ErrorKind::Cancelled {
|
||||
return e;
|
||||
}
|
||||
// npm diagnostics can contain private registry URLs; expose only known codes.
|
||||
let code = e
|
||||
.message
|
||||
.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
|
||||
.find(|w| {
|
||||
matches!(
|
||||
*w,
|
||||
"EACCES" | "EPERM" | "EROFS" | "ENOTFOUND" | "EAI_AGAIN" | "ETIMEDOUT" | "E404" | "E401" | "E403"
|
||||
)
|
||||
})
|
||||
.unwrap_or("npm");
|
||||
IdeError::unavailable(code)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -314,8 +409,9 @@ esac"#;
|
||||
let f = Fixture::new();
|
||||
let npm = f.npm(NPM);
|
||||
let cancel = CancellationToken::new();
|
||||
let run =
|
||||
|offer: Option<&AgentCliOffer>| maintain(&npm, &f.install.link, "claude", PKG, offer, &cancel).unwrap();
|
||||
let run = |offer: Option<&AgentCliOffer>| {
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, offer, &cancel).unwrap()
|
||||
};
|
||||
let latest = f.root.path().join("latest");
|
||||
fs::write(&latest, r#""2.1.12""#).unwrap();
|
||||
let Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
@@ -351,7 +447,7 @@ esac"#;
|
||||
let npm = f.npm(NPM);
|
||||
fs::write(f.root.path().join("latest"), r#""2.1.12""#).unwrap();
|
||||
let run = |offer: Option<&AgentCliOffer>| {
|
||||
maintain(&npm, &f.install.link, "claude", PKG, offer, &CancellationToken::new()).unwrap()
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, offer, &CancellationToken::new()).unwrap()
|
||||
};
|
||||
let AgentCliUpdateResult::Available(offer) = run(None) else { panic!("expected an offer") };
|
||||
fs::set_permissions(&f.install.folder, fs::Permissions::from_mode(0o555)).unwrap();
|
||||
@@ -377,13 +473,13 @@ esac"#,
|
||||
);
|
||||
let cancel = CancellationToken::new();
|
||||
let AgentCliUpdateResult::Available(offer) =
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, &cancel).unwrap()
|
||||
maintain(&npm, &f.install.link, "claude", PKG, None, None, &cancel).unwrap()
|
||||
else {
|
||||
panic!("expected an offer")
|
||||
};
|
||||
let started = f.root.path().join("started");
|
||||
std::thread::scope(|s| {
|
||||
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, Some(&offer), &cancel));
|
||||
let op = s.spawn(|| maintain(&npm, &f.install.link, "claude", PKG, None, Some(&offer), &cancel));
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while !started.exists() && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
|
||||
@@ -146,6 +146,10 @@ pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
|
||||
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
|
||||
}
|
||||
|
||||
pub(crate) fn is_approval_option_id(id: &str) -> bool {
|
||||
id == CURSOR_APPROVAL || matches!(id, "mode" | "allow_all" | "permissions" | "approval" | "approval_policy")
|
||||
}
|
||||
|
||||
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
|
||||
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
|
||||
}
|
||||
@@ -425,15 +429,19 @@ pub(crate) fn is_fast_option(id: &str) -> bool {
|
||||
id == "fast"
|
||||
}
|
||||
|
||||
/// Whether a raw config option id belongs to the selected model rather than the provider.
|
||||
pub(crate) fn is_per_model_option_id(id: &str) -> bool {
|
||||
matches!(id, "effort" | "reasoning_effort" | "thinking" | "reasoning" | "service_tier")
|
||||
|| is_fast_option(id)
|
||||
|| is_context_option(id)
|
||||
}
|
||||
|
||||
/// Whether an option's available values and default belong to the selected model
|
||||
/// (`thought_level`, `context_tier`, and `model_config` options like `context`, `fast` and `service_tier`)
|
||||
/// rather than the provider as a whole.
|
||||
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
|
||||
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|
||||
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|
||||
|| is_fast_option(&o.id)
|
||||
|| is_context_option(&o.id)
|
||||
|| o.id == "service_tier"
|
||||
|| is_per_model_option_id(&o.id)
|
||||
}
|
||||
|
||||
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -70,6 +70,8 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: cfg.registry_name.clone(),
|
||||
registry_url: cfg.registry_url.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,6 +256,28 @@ pub fn apply_save(
|
||||
if input.scope == McpScope::Workspace && !has_workspace {
|
||||
return Err("Open a project to configure workspace MCP servers".into());
|
||||
}
|
||||
let existing_meta = input.id.as_deref().and_then(parse_server_id).and_then(|(prev_scope, prev_name)| {
|
||||
let map = match prev_scope {
|
||||
McpScope::User => &*user,
|
||||
McpScope::Workspace => &*workspace,
|
||||
};
|
||||
map.get(prev_name).map(|prev| (prev.registry_name.clone(), prev.registry_url.clone()))
|
||||
});
|
||||
let registry_name = input
|
||||
.registry_name
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| existing_meta.as_ref().and_then(|(rn, _)| rn.clone()));
|
||||
let registry_url = input
|
||||
.registry_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| existing_meta.and_then(|(_, ru)| ru));
|
||||
|
||||
let cfg = match input.transport {
|
||||
McpTransport::Stdio => {
|
||||
let cmd = input.command.as_deref().map(str::trim).unwrap_or_default();
|
||||
@@ -277,6 +301,8 @@ pub fn apply_save(
|
||||
url: None,
|
||||
headers: BTreeMap::new(),
|
||||
agents: normalize_agents_list(input.agents),
|
||||
registry_name,
|
||||
registry_url,
|
||||
}
|
||||
}
|
||||
McpTransport::Http | McpTransport::Sse => {
|
||||
@@ -301,6 +327,8 @@ pub fn apply_save(
|
||||
url: Some(url.to_owned()),
|
||||
headers,
|
||||
agents: normalize_agents_list(input.agents),
|
||||
registry_name,
|
||||
registry_url,
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1018,6 +1046,8 @@ fn parse_one_server_def(obj: &serde_json::Map<String, Value>) -> Option<AgentMcp
|
||||
url,
|
||||
headers: parse_key_values_map(obj.get("headers")),
|
||||
agents,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1272,6 +1302,8 @@ mod tests {
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1327,6 +1359,8 @@ mod tests {
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1347,6 +1381,8 @@ mod tests {
|
||||
url: None,
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
@@ -1367,6 +1403,8 @@ mod tests {
|
||||
url: Some("https://example.com/mcp".into()),
|
||||
headers: vec![McpKeyValue { name: "Authorization".into(), value: "Bearer secret".into() }],
|
||||
agents: vec!["claude".into()],
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -71,6 +71,7 @@ pub enum InterruptionReason {
|
||||
BackendStop,
|
||||
UnexpectedExit,
|
||||
NetworkTimeout,
|
||||
CursorCapacity,
|
||||
}
|
||||
|
||||
impl From<AgentShutdownReason> for InterruptionReason {
|
||||
@@ -641,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,
|
||||
@@ -756,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,
|
||||
@@ -1051,6 +1058,14 @@ pub struct McpServer {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
/// Canonical MCP registry server identifier when installed from an MCP registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_name: Option<String>,
|
||||
/// Normalized MCP registry base URL when installed from an MCP registry.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub registry_url: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating or updating a user or workspace MCP server.
|
||||
@@ -1077,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 {
|
||||
@@ -1666,6 +1689,12 @@ pub struct AgentMarketplaceCandidate {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_dark_url: Option<String>,
|
||||
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
|
||||
pub source_spec: String,
|
||||
pub subpath: String,
|
||||
@@ -1754,6 +1783,12 @@ pub struct AgentPluginPreview {
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub icon_dark_url: Option<String>,
|
||||
pub formats: Vec<AgentPluginFormat>,
|
||||
pub capabilities: AgentPluginCapabilities,
|
||||
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -881,6 +881,20 @@ pub(super) fn decisions(params: &Value, command: bool) -> Vec<Choice> {
|
||||
out
|
||||
}
|
||||
|
||||
/// One page of `thread/backgroundTerminals/list`: the running terminals as
|
||||
/// `(processId, description)`.
|
||||
pub(super) fn background_terminals(page: &Value) -> Vec<(String, String)> {
|
||||
let data = page.get("data").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
|
||||
data.iter()
|
||||
.filter_map(|t| {
|
||||
let process = t.get("processId").and_then(Value::as_str).filter(|p| !p.is_empty())?;
|
||||
let command = t.get("command").and_then(Value::as_str).unwrap_or_default();
|
||||
let description = crate::shell_script(command).unwrap_or_else(|| command.to_owned());
|
||||
Some((process.to_owned(), description))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A command prefix as typed: the script of a `<shell> -lc <script>` wrapper, else the words.
|
||||
fn shell_unwrapped(argv: &[&str]) -> String {
|
||||
match argv {
|
||||
|
||||
@@ -68,7 +68,7 @@ pub(crate) fn connect(
|
||||
) -> std::io::Result<Peer> {
|
||||
let launch_args = spec.args.clone();
|
||||
attach_with_args(client, launch_args, |events| {
|
||||
let command = super::newest_install(&spec.command);
|
||||
let command = super::newest_install(spec.executable());
|
||||
let args = headless_args(&spec.args);
|
||||
Peer::spawn_framed(&command, &args, cwd, &spec.env, events, on_stderr, Framing::ContentLength)
|
||||
})
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use base64::Engine as _;
|
||||
use ide_core::settings::{AgentMcpServer, AgentPluginEntryPolicy, AgentPluginSettings};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -46,6 +47,37 @@ const MARKETPLACE_MANIFEST_PATHS: &[&str] = &[
|
||||
".github/plugin/marketplace.json",
|
||||
];
|
||||
|
||||
/// Maximum local icon file size inlined as a base64 `data:` URI (64 KiB).
|
||||
const MAX_INLINE_ICON_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// Conventional icon file locations checked inside a plugin directory when no explicit icon is declared.
|
||||
const CONVENTIONAL_ICON_PATHS: &[&str] = &[
|
||||
".claude-plugin/icon.png",
|
||||
".claude-plugin/icon.svg",
|
||||
".claude-plugin/icon.webp",
|
||||
".plugin/icon.png",
|
||||
".plugin/icon.svg",
|
||||
".plugin/icon.webp",
|
||||
".github/plugin/icon.png",
|
||||
".github/plugin/icon.svg",
|
||||
".github/plugin/icon.webp",
|
||||
".codex-plugin/icon.png",
|
||||
".codex-plugin/icon.svg",
|
||||
".codex-plugin/icon.webp",
|
||||
"assets/logo.png",
|
||||
"assets/logo.svg",
|
||||
"assets/logo.webp",
|
||||
"assets/icon.png",
|
||||
"assets/icon.svg",
|
||||
"assets/icon.webp",
|
||||
"icon.png",
|
||||
"icon.svg",
|
||||
"icon.webp",
|
||||
"logo.png",
|
||||
"logo.svg",
|
||||
"logo.webp",
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InstalledPluginProvenance {
|
||||
@@ -1461,6 +1493,8 @@ pub fn projected_mcp_servers(
|
||||
unapproved: false,
|
||||
plugin_id: Some(state.plugin.id.clone()),
|
||||
plugin_name: Some(state.plugin.display_name.clone()),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1551,6 +1585,7 @@ pub fn browse_marketplace(
|
||||
let tree = fetcher.git_tree(RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &git_ref }, cancel)?;
|
||||
|
||||
let target = RepoRef { owner: &parsed.owner, repo: &parsed.repo, git_ref: &git_ref };
|
||||
let tree_paths: HashSet<&str> = tree.tree.iter().filter(|e| e.kind == "blob").map(|e| e.path.as_str()).collect();
|
||||
|
||||
// 1. Check for a `marketplace.json` manifest in the repository (under `parsed.subpath` if given, or root).
|
||||
let sub_prefix = parsed.subpath.as_deref().map(|s| format!("{s}/")).unwrap_or_default();
|
||||
@@ -1561,10 +1596,9 @@ pub fn browse_marketplace(
|
||||
let text = String::from_utf8(bytes).map_err(|_| IdeError::invalid("marketplace.json is not UTF-8"))?;
|
||||
let (mkt_name, candidates) = parse_marketplace_json_remote(
|
||||
&text,
|
||||
&parsed.owner,
|
||||
&parsed.repo,
|
||||
&git_ref,
|
||||
target,
|
||||
parsed.subpath.as_deref(),
|
||||
&tree_paths,
|
||||
user_home,
|
||||
workspace_root,
|
||||
)?;
|
||||
@@ -1614,6 +1648,7 @@ pub fn browse_marketplace(
|
||||
let mut description = String::new();
|
||||
let mut author = None;
|
||||
let mut keywords = Vec::new();
|
||||
let mut manifest_val: Option<Value> = None;
|
||||
|
||||
for (manifest_rel, _) in MANIFEST_CANDIDATES {
|
||||
let p = format!("{prefix}{manifest_rel}");
|
||||
@@ -1644,10 +1679,18 @@ pub fn browse_marketplace(
|
||||
if keywords.is_empty() {
|
||||
keywords = extract_string_array(val.get("keywords"));
|
||||
}
|
||||
manifest_val = Some(val);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let (icon_url, icon_dark_url) = resolve_remote_plugin_icons(
|
||||
manifest_val.as_ref(),
|
||||
Some((&parsed.owner, &parsed.repo, &git_ref, root_dir.as_str(), Some(&tree_paths))),
|
||||
None,
|
||||
Some(&parsed.owner),
|
||||
);
|
||||
|
||||
let source_spec = if root_dir.is_empty() {
|
||||
format!("{}/{}#{git_ref}", parsed.owner, parsed.repo)
|
||||
} else {
|
||||
@@ -1661,6 +1704,8 @@ pub fn browse_marketplace(
|
||||
description,
|
||||
author,
|
||||
marketplace: None,
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec,
|
||||
subpath: root_dir,
|
||||
keywords,
|
||||
@@ -1717,7 +1762,7 @@ pub fn preview_plugin(
|
||||
}
|
||||
let scanned = scan_local_subtree(&canon, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin")?;
|
||||
let inspected =
|
||||
inspect_fetched_subtree(&scanned, canon.file_name().and_then(|s| s.to_str()).unwrap_or("plugin"))?;
|
||||
inspect_fetched_subtree(&scanned, canon.file_name().and_then(|s| s.to_str()).unwrap_or("plugin"), None)?;
|
||||
let marketplace_source = marketplace
|
||||
.and_then(|name| local_marketplace_source(&local_dir, name))
|
||||
.map(|path| path.to_string_lossy().into_owned());
|
||||
@@ -1746,6 +1791,8 @@ pub fn preview_plugin(
|
||||
display_name: inspected.display_name,
|
||||
version: inspected.version,
|
||||
description: inspected.description,
|
||||
icon_url: inspected.icon_url,
|
||||
icon_dark_url: inspected.icon_dark_url,
|
||||
formats: inspected.formats,
|
||||
capabilities: inspected.capabilities,
|
||||
files: scanned.files,
|
||||
@@ -1764,7 +1811,11 @@ pub fn preview_plugin(
|
||||
let scanned =
|
||||
fetch_and_scan_subtree(fetcher, target, &subpath, None, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin", cancel)?;
|
||||
let fallback_name = subpath.rsplit('/').next().filter(|s| !s.is_empty()).unwrap_or(&parsed.repo);
|
||||
let inspected = inspect_fetched_subtree(&scanned, fallback_name)?;
|
||||
let inspected = inspect_fetched_subtree(
|
||||
&scanned,
|
||||
fallback_name,
|
||||
Some((&parsed.owner, &parsed.repo, &commit_sha, scanned.normalized_subpath.as_str())),
|
||||
)?;
|
||||
let targets = plugin_install_targets(
|
||||
&inspected.name,
|
||||
inspected.version.as_deref(),
|
||||
@@ -1791,6 +1842,8 @@ pub fn preview_plugin(
|
||||
display_name: inspected.display_name,
|
||||
version: inspected.version,
|
||||
description: inspected.description,
|
||||
icon_url: inspected.icon_url,
|
||||
icon_dark_url: inspected.icon_dark_url,
|
||||
formats: inspected.formats,
|
||||
capabilities: inspected.capabilities,
|
||||
files: scanned.files,
|
||||
@@ -1919,7 +1972,7 @@ pub fn install_plugin(
|
||||
));
|
||||
}
|
||||
|
||||
let inspected = inspect_fetched_subtree(&scanned, &fallback_name)?;
|
||||
let inspected = inspect_fetched_subtree(&scanned, &fallback_name, None)?;
|
||||
if let Some(reason) = plugin_install_blocker(
|
||||
source,
|
||||
&inspected.formats,
|
||||
@@ -2057,16 +2110,23 @@ struct InspectedSubtreeMeta {
|
||||
display_name: String,
|
||||
version: Option<String>,
|
||||
description: String,
|
||||
icon_url: Option<String>,
|
||||
icon_dark_url: Option<String>,
|
||||
formats: Vec<AgentPluginFormat>,
|
||||
capabilities: AgentPluginCapabilities,
|
||||
}
|
||||
|
||||
fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> IdeResult<InspectedSubtreeMeta> {
|
||||
fn inspect_fetched_subtree(
|
||||
scanned: &FetchedSubtree,
|
||||
fallback_name: &str,
|
||||
remote_repo: Option<(&str, &str, &str, &str)>,
|
||||
) -> IdeResult<InspectedSubtreeMeta> {
|
||||
let mut formats = Vec::new();
|
||||
let mut name: Option<String> = None;
|
||||
let mut display_name: Option<String> = None;
|
||||
let mut version: Option<String> = None;
|
||||
let mut description = String::new();
|
||||
let mut primary_manifest: Option<Value> = None;
|
||||
let mut native_harnesses = BTreeSet::new();
|
||||
|
||||
let file_map: BTreeMap<String, &[u8]> =
|
||||
@@ -2108,6 +2168,9 @@ fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> Ide
|
||||
{
|
||||
description = d.trim().to_owned();
|
||||
}
|
||||
if primary_manifest.is_none() {
|
||||
primary_manifest = Some(val);
|
||||
}
|
||||
}
|
||||
|
||||
let mut skill_names = Vec::new();
|
||||
@@ -2158,12 +2221,15 @@ fn inspect_fetched_subtree(scanned: &FetchedSubtree, fallback_name: &str) -> Ide
|
||||
|
||||
let final_name = name.unwrap_or_else(|| sanitize_plugin_slug(fallback_name));
|
||||
let final_display = display_name.unwrap_or_else(|| final_name.clone());
|
||||
let (icon_url, icon_dark_url) = resolve_subtree_icons(primary_manifest.as_ref(), &file_map, remote_repo);
|
||||
|
||||
Ok(InspectedSubtreeMeta {
|
||||
name: final_name,
|
||||
display_name: final_display,
|
||||
version,
|
||||
description,
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
formats,
|
||||
capabilities: AgentPluginCapabilities {
|
||||
skill_count: skill_names.len() as u32,
|
||||
@@ -3654,6 +3720,13 @@ fn browse_local_marketplace(
|
||||
if source_spec.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let local_plugin_dir = Path::new(&source_spec);
|
||||
let (icon_url, icon_dark_url) = if local_plugin_dir.is_dir() {
|
||||
resolve_local_plugin_icons(Some(item), local_plugin_dir)
|
||||
} else {
|
||||
let ext_repo = source_spec.split('#').next();
|
||||
resolve_remote_plugin_icons(Some(item), None, ext_repo, None)
|
||||
};
|
||||
let (already_user, already_ws) =
|
||||
plugin_installed_anywhere(&name, Some(&mkt_name), user_home, workspace_root);
|
||||
candidates.push(AgentMarketplaceCandidate {
|
||||
@@ -3663,6 +3736,8 @@ fn browse_local_marketplace(
|
||||
description,
|
||||
author,
|
||||
marketplace: Some(mkt_name.clone()),
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec,
|
||||
subpath,
|
||||
keywords,
|
||||
@@ -3685,6 +3760,11 @@ fn browse_local_marketplace(
|
||||
// Direct local plugin folder. The source only selects how metadata is read; the target
|
||||
// harness is chosen at install time.
|
||||
if let Some(plug) = inspect_plugin_dir(local_path, AgentPluginSource::CopilotUser, McpScope::User, None, true) {
|
||||
let manifest_val = MANIFEST_CANDIDATES.iter().find_map(|(rel, _)| {
|
||||
let text = std::fs::read_to_string(local_path.join(rel)).ok()?;
|
||||
parse_jsonc(&text).ok()
|
||||
});
|
||||
let (icon_url, icon_dark_url) = resolve_local_plugin_icons(manifest_val.as_ref(), local_path);
|
||||
let (already_user, already_ws) = plugin_installed_anywhere(&plug.name, None, user_home, workspace_root);
|
||||
return Ok(AgentMarketplaceBrowseResult {
|
||||
source: raw_source.to_owned(),
|
||||
@@ -3700,6 +3780,8 @@ fn browse_local_marketplace(
|
||||
description: plug.description,
|
||||
author: plug.author,
|
||||
marketplace: None,
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec: local_path.to_string_lossy().into_owned(),
|
||||
subpath: String::new(),
|
||||
keywords: Vec::new(),
|
||||
@@ -3836,13 +3918,13 @@ fn safe_marketplace_repo(raw: &str) -> Option<String> {
|
||||
|
||||
fn parse_marketplace_json_remote(
|
||||
text: &str,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
git_ref: &str,
|
||||
target: RepoRef<'_>,
|
||||
base_subpath: Option<&str>,
|
||||
tree_paths: &HashSet<&str>,
|
||||
user_home: Option<&Path>,
|
||||
workspace_root: Option<&Path>,
|
||||
) -> IdeResult<(String, Vec<AgentMarketplaceCandidate>)> {
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
let val = parse_jsonc(text).map_err(|e| IdeError::invalid(format!("Invalid marketplace.json: {e}")))?;
|
||||
let mkt_name =
|
||||
val.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).unwrap_or(repo).to_owned();
|
||||
@@ -3872,7 +3954,7 @@ fn parse_marketplace_json_remote(
|
||||
let author = extract_author(item);
|
||||
let keywords = extract_string_array(item.get("keywords"));
|
||||
|
||||
let (source_spec, subpath) = match item.get("source") {
|
||||
let (source_spec, subpath, ext_repo_owner, in_marketplace_repo) = match item.get("source") {
|
||||
Some(Value::String(rel)) => {
|
||||
let Some(clean) = safe_marketplace_subpath(rel) else { continue };
|
||||
let mut parts: Vec<&str> = Vec::new();
|
||||
@@ -3891,7 +3973,7 @@ fn parse_marketplace_json_remote(
|
||||
} else {
|
||||
format!("{owner}/{repo}/{joined}#{git_ref}")
|
||||
};
|
||||
(spec, joined)
|
||||
(spec, joined, None, true)
|
||||
}
|
||||
Some(Value::Object(obj)) => match obj.get("source").and_then(Value::as_str).unwrap_or_default() {
|
||||
"local" => {
|
||||
@@ -3916,7 +3998,7 @@ fn parse_marketplace_json_remote(
|
||||
} else {
|
||||
format!("{owner}/{repo}/{joined}#{git_ref}")
|
||||
};
|
||||
(spec, joined)
|
||||
(spec, joined, None, true)
|
||||
}
|
||||
"github" => {
|
||||
let Some(ext_repo) = obj.get("repo").and_then(Value::as_str).and_then(safe_marketplace_repo) else {
|
||||
@@ -3926,9 +4008,9 @@ fn parse_marketplace_json_remote(
|
||||
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else { continue };
|
||||
let spec = match r {
|
||||
Some(gr) => format!("{ext_repo}#{gr}"),
|
||||
None => ext_repo.to_owned(),
|
||||
None => ext_repo.clone(),
|
||||
};
|
||||
(spec, String::new())
|
||||
(spec, String::new(), Some(ext_repo), false)
|
||||
}
|
||||
"git-subdir" => {
|
||||
let Some(ext_repo) = obj
|
||||
@@ -3949,15 +4031,19 @@ fn parse_marketplace_json_remote(
|
||||
let Ok(r) = r.map(|r| safe_marketplace_ref(r).ok_or(())).transpose() else { continue };
|
||||
let spec = match r {
|
||||
Some(gr) => format!("{ext_repo}#{gr}"),
|
||||
None => ext_repo.to_owned(),
|
||||
None => ext_repo.clone(),
|
||||
};
|
||||
(spec, sub)
|
||||
(spec, sub, Some(ext_repo), false)
|
||||
}
|
||||
_ => continue,
|
||||
},
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
let in_repo_ctx = in_marketplace_repo.then_some((owner, repo, git_ref, subpath.as_str(), Some(tree_paths)));
|
||||
let (icon_url, icon_dark_url) =
|
||||
resolve_remote_plugin_icons(Some(item), in_repo_ctx, ext_repo_owner.as_deref(), Some(owner));
|
||||
|
||||
let (already_user, already_ws) = plugin_installed_anywhere(&name, Some(&mkt_name), user_home, workspace_root);
|
||||
out.push(AgentMarketplaceCandidate {
|
||||
name,
|
||||
@@ -3966,6 +4052,8 @@ fn parse_marketplace_json_remote(
|
||||
description,
|
||||
author,
|
||||
marketplace: Some(mkt_name.clone()),
|
||||
icon_url,
|
||||
icon_dark_url,
|
||||
source_spec,
|
||||
subpath,
|
||||
keywords,
|
||||
@@ -3977,6 +4065,302 @@ fn parse_marketplace_json_remote(
|
||||
Ok((mkt_name, out))
|
||||
}
|
||||
|
||||
fn safe_https_icon_url(raw: &str) -> Option<String> {
|
||||
let trimmed = raw.trim();
|
||||
let rest = trimmed.strip_prefix("https://")?;
|
||||
if trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) {
|
||||
return None;
|
||||
}
|
||||
let authority = rest.split('/').next().unwrap_or_default();
|
||||
if authority.is_empty() || authority.contains('@') {
|
||||
return None;
|
||||
}
|
||||
Some(trimmed.to_owned())
|
||||
}
|
||||
|
||||
fn icon_mime_for_path(path: &str) -> Option<&'static str> {
|
||||
let lower = path.to_ascii_lowercase();
|
||||
if lower.ends_with(".png") {
|
||||
Some("image/png")
|
||||
} else if lower.ends_with(".svg") {
|
||||
Some("image/svg+xml")
|
||||
} else if lower.ends_with(".webp") {
|
||||
Some("image/webp")
|
||||
} else if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
|
||||
Some("image/jpeg")
|
||||
} else if lower.ends_with(".ico") {
|
||||
Some("image/x-icon")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_data_uri(mime: &str, bytes: &[u8]) -> Option<String> {
|
||||
if bytes.is_empty() || bytes.len() > MAX_INLINE_ICON_BYTES {
|
||||
return None;
|
||||
}
|
||||
let b64 = base64::engine::general_purpose::STANDARD.encode(bytes);
|
||||
Some(format!("data:{mime};base64,{b64}"))
|
||||
}
|
||||
|
||||
fn percent_encode_path_segment(segment: &str) -> String {
|
||||
let mut out = String::with_capacity(segment.len());
|
||||
for byte in segment.bytes() {
|
||||
let unreserved = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~');
|
||||
if unreserved {
|
||||
out.push(byte as char);
|
||||
} else {
|
||||
out.push('%');
|
||||
let hi = byte >> 4;
|
||||
let lo = byte & 0x0f;
|
||||
out.push(if hi < 10 { (b'0' + hi) as char } else { (b'A' + hi - 10) as char });
|
||||
out.push(if lo < 10 { (b'0' + lo) as char } else { (b'A' + lo - 10) as char });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn github_raw_file_url(owner: &str, repo: &str, git_ref: &str, repo_path: &str) -> String {
|
||||
let enc_ref = git_ref.split('/').map(percent_encode_path_segment).collect::<Vec<_>>().join("/");
|
||||
let enc_path = repo_path.split('/').map(percent_encode_path_segment).collect::<Vec<_>>().join("/");
|
||||
format!("https://raw.githubusercontent.com/{owner}/{repo}/{enc_ref}/{enc_path}")
|
||||
}
|
||||
|
||||
fn is_valid_github_owner(owner: &str) -> bool {
|
||||
!owner.is_empty()
|
||||
&& owner.len() <= 39
|
||||
&& owner.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
|
||||
&& !owner.starts_with('-')
|
||||
&& !owner.ends_with('-')
|
||||
}
|
||||
|
||||
fn github_owner_from_url(raw: &str) -> Option<&str> {
|
||||
let trimmed = raw.trim();
|
||||
let rest = trimmed
|
||||
.strip_prefix("https://github.com/")
|
||||
.or_else(|| trimmed.strip_prefix("http://github.com/"))
|
||||
.or_else(|| trimmed.strip_prefix("https://www.github.com/"))?;
|
||||
let owner = rest.split('/').next()?;
|
||||
is_valid_github_owner(owner).then_some(owner)
|
||||
}
|
||||
|
||||
fn github_owner_from_repo_slug(slug: &str) -> Option<&str> {
|
||||
let owner = slug.trim().split('/').next()?;
|
||||
is_valid_github_owner(owner).then_some(owner)
|
||||
}
|
||||
|
||||
fn github_owner_avatar(val: Option<&Value>, ext_repo: Option<&str>, fallback_owner: Option<&str>) -> Option<String> {
|
||||
if let Some(owner) = ext_repo.and_then(github_owner_from_repo_slug) {
|
||||
return Some(format!("https://github.com/{owner}.png?size=64"));
|
||||
}
|
||||
if let Some(v) = val {
|
||||
let candidate_urls = [
|
||||
v.get("repository").and_then(|r| r.get("url").or(Some(r))).and_then(Value::as_str),
|
||||
v.get("homepage").and_then(Value::as_str),
|
||||
v.pointer("/author/url").and_then(Value::as_str),
|
||||
];
|
||||
for raw_url in candidate_urls.into_iter().flatten() {
|
||||
if let Some(owner) = github_owner_from_url(raw_url) {
|
||||
return Some(format!("https://github.com/{owner}.png?size=64"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(owner) = fallback_owner.filter(|o| is_valid_github_owner(o)) {
|
||||
return Some(format!("https://github.com/{owner}.png?size=64"));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Resolves explicit icon references `(light, dark)` from a marketplace entry or plugin manifest,
|
||||
/// skipping any invalid/unresolvable entries before picking light/dark variants.
|
||||
fn resolve_manifest_icon_refs(
|
||||
val: &Value,
|
||||
resolve: impl Fn(&str) -> Option<String>,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
if let Some(icons) = val.get("icons").and_then(Value::as_array) {
|
||||
let mut light: Option<String> = None;
|
||||
let mut dark: Option<String> = None;
|
||||
let mut unthemed: Option<String> = None;
|
||||
let mut first: Option<String> = None;
|
||||
for item in icons {
|
||||
let Some(obj) = item.as_object() else { continue };
|
||||
let Some(src) = obj.get("src").and_then(Value::as_str).and_then(&resolve) else {
|
||||
continue;
|
||||
};
|
||||
if first.is_none() {
|
||||
first = Some(src.clone());
|
||||
}
|
||||
match obj.get("theme").and_then(Value::as_str).map(|s| s.trim().to_ascii_lowercase()).as_deref() {
|
||||
Some("light") if light.is_none() => light = Some(src),
|
||||
Some("dark") if dark.is_none() => dark = Some(src),
|
||||
None | Some("") if unthemed.is_none() => unthemed = Some(src),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let resolved_light = light.or_else(|| unthemed.clone()).or(first);
|
||||
if resolved_light.is_some() {
|
||||
let resolved_dark = dark.or(unthemed).filter(|d| Some(d.as_str()) != resolved_light.as_deref());
|
||||
return (resolved_light, resolved_dark);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(icon) = val.get("icon") {
|
||||
if let Some(resolved) = icon.as_str().and_then(&resolve) {
|
||||
return (Some(resolved), None);
|
||||
}
|
||||
if let Some(obj) = icon.as_object() {
|
||||
let light = obj.get("light").and_then(Value::as_str).and_then(&resolve);
|
||||
let dark = obj.get("dark").and_then(Value::as_str).and_then(&resolve);
|
||||
if light.is_some() || dark.is_some() {
|
||||
let eff_light = light.or_else(|| dark.clone());
|
||||
let eff_dark = dark.filter(|d| Some(d.as_str()) != eff_light.as_deref());
|
||||
return (eff_light, eff_dark);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for candidate in [
|
||||
val.get("logo"),
|
||||
val.pointer("/interface/logo"),
|
||||
val.pointer("/interface/composerIcon"),
|
||||
val.get("iconUrl"),
|
||||
val.get("icon_url"),
|
||||
] {
|
||||
if let Some(resolved) = candidate.and_then(Value::as_str).and_then(&resolve) {
|
||||
return (Some(resolved), None);
|
||||
}
|
||||
}
|
||||
|
||||
(None, None)
|
||||
}
|
||||
|
||||
fn join_repo_subpath(subpath: &str, rel: &str) -> String {
|
||||
if subpath.is_empty() { rel.to_owned() } else { format!("{subpath}/{rel}") }
|
||||
}
|
||||
|
||||
type RemoteRepoIconContext<'a> = (&'a str, &'a str, &'a str, &'a str, Option<&'a HashSet<&'a str>>);
|
||||
|
||||
fn resolve_remote_icon_ref(raw: &str, in_repo: Option<RemoteRepoIconContext<'_>>) -> Option<String> {
|
||||
if let Some(https) = safe_https_icon_url(raw) {
|
||||
return Some(https);
|
||||
}
|
||||
let (owner, repo, git_ref, subpath, tree_paths) = in_repo?;
|
||||
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
|
||||
icon_mime_for_path(clean)?;
|
||||
let full = join_repo_subpath(subpath, clean);
|
||||
if let Some(paths) = tree_paths
|
||||
&& !paths.contains(full.as_str())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(github_raw_file_url(owner, repo, git_ref, &full))
|
||||
}
|
||||
|
||||
fn resolve_remote_plugin_icons(
|
||||
val: Option<&Value>,
|
||||
in_repo: Option<RemoteRepoIconContext<'_>>,
|
||||
ext_repo: Option<&str>,
|
||||
fallback_owner: Option<&str>,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
if let Some(v) = val {
|
||||
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_remote_icon_ref(r, in_repo));
|
||||
if light.is_some() || dark.is_some() {
|
||||
return (light, dark);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((owner, repo, git_ref, subpath, Some(tree_paths))) = in_repo {
|
||||
for rel in CONVENTIONAL_ICON_PATHS {
|
||||
let full = join_repo_subpath(subpath, rel);
|
||||
if tree_paths.contains(full.as_str()) {
|
||||
return (Some(github_raw_file_url(owner, repo, git_ref, &full)), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(github_owner_avatar(val, ext_repo, fallback_owner), None)
|
||||
}
|
||||
|
||||
fn resolve_local_icon_ref(raw: &str, plugin_dir: &Path) -> Option<String> {
|
||||
if let Some(https) = safe_https_icon_url(raw) {
|
||||
return Some(https);
|
||||
}
|
||||
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
|
||||
let mime = icon_mime_for_path(clean)?;
|
||||
let path = contained_join(plugin_dir, clean).ok()?;
|
||||
let meta = std::fs::metadata(&path).ok()?;
|
||||
if !meta.is_file() || meta.len() > MAX_INLINE_ICON_BYTES as u64 {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::fs::read(&path).ok()?;
|
||||
encode_data_uri(mime, &bytes)
|
||||
}
|
||||
|
||||
fn resolve_local_plugin_icons(val: Option<&Value>, plugin_dir: &Path) -> (Option<String>, Option<String>) {
|
||||
if let Some(v) = val {
|
||||
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_local_icon_ref(r, plugin_dir));
|
||||
if light.is_some() || dark.is_some() {
|
||||
return (light, dark);
|
||||
}
|
||||
}
|
||||
|
||||
for rel in CONVENTIONAL_ICON_PATHS {
|
||||
if let Some(data_uri) = resolve_local_icon_ref(rel, plugin_dir) {
|
||||
return (Some(data_uri), None);
|
||||
}
|
||||
}
|
||||
|
||||
(github_owner_avatar(val, None, None), None)
|
||||
}
|
||||
|
||||
fn resolve_subtree_icon_ref(
|
||||
raw: &str,
|
||||
file_map: &BTreeMap<String, &[u8]>,
|
||||
remote_repo: Option<(&str, &str, &str, &str)>,
|
||||
) -> Option<String> {
|
||||
if let Some(https) = safe_https_icon_url(raw) {
|
||||
return Some(https);
|
||||
}
|
||||
let clean = safe_marketplace_subpath(raw).filter(|s| !s.is_empty())?;
|
||||
let mime = icon_mime_for_path(clean)?;
|
||||
let bytes = file_map.get(clean)?;
|
||||
if let Some((owner, repo, git_ref, subpath)) = remote_repo {
|
||||
let full = join_repo_subpath(subpath, clean);
|
||||
return Some(github_raw_file_url(owner, repo, git_ref, &full));
|
||||
}
|
||||
encode_data_uri(mime, bytes)
|
||||
}
|
||||
|
||||
fn resolve_subtree_icons(
|
||||
val: Option<&Value>,
|
||||
file_map: &BTreeMap<String, &[u8]>,
|
||||
remote_repo: Option<(&str, &str, &str, &str)>,
|
||||
) -> (Option<String>, Option<String>) {
|
||||
if let Some(v) = val {
|
||||
let (light, dark) = resolve_manifest_icon_refs(v, |r| resolve_subtree_icon_ref(r, file_map, remote_repo));
|
||||
if light.is_some() || dark.is_some() {
|
||||
return (light, dark);
|
||||
}
|
||||
}
|
||||
|
||||
for rel in CONVENTIONAL_ICON_PATHS {
|
||||
if let Some(bytes) = file_map.get(*rel)
|
||||
&& let Some(mime) = icon_mime_for_path(rel)
|
||||
{
|
||||
if let Some((owner, repo, git_ref, subpath)) = remote_repo {
|
||||
let full = join_repo_subpath(subpath, rel);
|
||||
return (Some(github_raw_file_url(owner, repo, git_ref, &full)), None);
|
||||
}
|
||||
if let Some(data_uri) = encode_data_uri(mime, bytes) {
|
||||
return (Some(data_uri), None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fallback_owner = remote_repo.map(|(owner, _, _, _)| owner);
|
||||
(github_owner_avatar(val, None, fallback_owner), None)
|
||||
}
|
||||
|
||||
const INSTALL_SOURCES: [AgentPluginSource; 4] = [
|
||||
AgentPluginSource::ClaudeUser,
|
||||
AgentPluginSource::CopilotUser,
|
||||
@@ -5553,7 +5937,7 @@ mod tests {
|
||||
|
||||
let on_disk = inspect_plugin_dir(&dir, AgentPluginSource::ClaudeUser, McpScope::User, Some("m"), true).unwrap();
|
||||
let scanned = scan_local_subtree(&dir, MAX_PLUGIN_FILES, MAX_PLUGIN_BYTES, "plugin").unwrap();
|
||||
let preview = inspect_fetched_subtree(&scanned, "hooked").unwrap();
|
||||
let preview = inspect_fetched_subtree(&scanned, "hooked", None).unwrap();
|
||||
for hooks in [&on_disk.capabilities.hook_files, &preview.capabilities.hook_files] {
|
||||
assert!(hooks.contains(&".claude-plugin/plugin.json#hooks".to_owned()), "{hooks:?}");
|
||||
assert!(hooks.contains(&"config/copilot-hooks.json".to_owned()), "{hooks:?}");
|
||||
@@ -5698,19 +6082,19 @@ mod tests {
|
||||
{"name":"gh-bad-ref","source":{"source":"github","repo":"acme/tools","ref":"main#x"}},
|
||||
{"name":"sub-bad","source":{"source":"git-subdir","url":"https://github.com/acme/tools.git","path":"../x"}}
|
||||
]}"##;
|
||||
let (_, candidates) =
|
||||
parse_marketplace_json_remote(manifest, "acme", "repo", "main", None, None, None).unwrap();
|
||||
let empty_tree = HashSet::new();
|
||||
let target = RepoRef { owner: "acme", repo: "repo", git_ref: "main" };
|
||||
let (_, candidates) = parse_marketplace_json_remote(manifest, target, None, &empty_tree, None, None).unwrap();
|
||||
let specs: Vec<_> = candidates.iter().map(|c| (c.name.as_str(), c.source_spec.as_str())).collect();
|
||||
assert_eq!(specs, [("ok", "acme/repo/plugins/ok#main"), ("gh-ok", "acme/tools#v1.2")]);
|
||||
assert!(
|
||||
parse_marketplace_json_remote(
|
||||
r#"{"metadata":{"pluginRoot":"../up"},"plugins":[]}"#,
|
||||
"acme",
|
||||
"repo",
|
||||
"main",
|
||||
target,
|
||||
None,
|
||||
&empty_tree,
|
||||
None,
|
||||
None,
|
||||
None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
@@ -5828,4 +6212,112 @@ mod tests {
|
||||
&& plugin.scope == McpScope::Workspace
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marketplace_browse_and_preview_resolve_explicit_bundled_local_and_avatar_icons() {
|
||||
let cancel = CancellationToken::new();
|
||||
let marketplace_json = br#"{
|
||||
"name": "claude-plugins-official",
|
||||
"plugins": [
|
||||
{
|
||||
"name": "themed-ext",
|
||||
"description": "Explicit light/dark icons",
|
||||
"source": "./plugins/themed-ext",
|
||||
"icons": [
|
||||
{ "src": "javascript:alert(1)", "theme": "light" },
|
||||
{ "src": "https://cdn.example.com/light.png", "theme": "light" },
|
||||
{ "src": "https://cdn.example.com/dark.png", "theme": "dark" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "champion-kit",
|
||||
"description": "Bundled .claude-plugin/icon.png",
|
||||
"source": "./plugins/champion-kit"
|
||||
},
|
||||
{
|
||||
"name": "adobe-for-creativity",
|
||||
"description": "External git-subdir plugin",
|
||||
"source": {
|
||||
"source": "git-subdir",
|
||||
"url": "https://github.com/adobe/skills.git",
|
||||
"path": "plugins/creative-cloud/adobe-for-creativity"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "first-party",
|
||||
"description": "Falls back to marketplace repo owner avatar",
|
||||
"source": "./plugins/first-party"
|
||||
},
|
||||
{
|
||||
"name": "unsafe-icon",
|
||||
"description": "Rejects http:// and escaping relative paths",
|
||||
"source": "./plugins/unsafe-icon",
|
||||
"icon": "../escape.png"
|
||||
}
|
||||
]
|
||||
}"#;
|
||||
|
||||
let gh = FakeGitHub::new(
|
||||
&[
|
||||
(".claude-plugin/marketplace.json", marketplace_json.as_slice(), "100644"),
|
||||
("plugins/champion-kit/.claude-plugin/plugin.json", br#"{"name":"champion-kit"}"#, "100644"),
|
||||
("plugins/champion-kit/.claude-plugin/icon.png", b"\x89PNG\r\n\x1a\n", "100644"),
|
||||
("plugins/first-party/.claude-plugin/plugin.json", br#"{"name":"first-party"}"#, "100644"),
|
||||
],
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
);
|
||||
|
||||
let browse = browse_marketplace(&gh, "anthropics/claude-plugins-official", None, None, &cancel).unwrap();
|
||||
let by = |name: &str| browse.candidates.iter().find(|c| c.name == name).unwrap();
|
||||
|
||||
assert_eq!(by("themed-ext").icon_url.as_deref(), Some("https://cdn.example.com/light.png"));
|
||||
assert_eq!(by("themed-ext").icon_dark_url.as_deref(), Some("https://cdn.example.com/dark.png"));
|
||||
assert_eq!(
|
||||
by("champion-kit").icon_url.as_deref(),
|
||||
Some(
|
||||
"https://raw.githubusercontent.com/anthropics/claude-plugins-official/main/plugins/champion-kit/.claude-plugin/icon.png"
|
||||
)
|
||||
);
|
||||
assert_eq!(by("adobe-for-creativity").icon_url.as_deref(), Some("https://github.com/adobe.png?size=64"));
|
||||
assert_eq!(by("first-party").icon_url.as_deref(), Some("https://github.com/anthropics.png?size=64"));
|
||||
assert_eq!(by("unsafe-icon").icon_url.as_deref(), Some("https://github.com/anthropics.png?size=64"));
|
||||
|
||||
// Remote preview also resolves bundled icons to raw.githubusercontent.com at commit_sha.
|
||||
let remote_preview = preview_plugin(
|
||||
&gh,
|
||||
"anthropics/claude-plugins-official/plugins/champion-kit#main",
|
||||
None,
|
||||
Some("claude-plugins-official"),
|
||||
None,
|
||||
None,
|
||||
&cancel,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
remote_preview.icon_url.as_deref(),
|
||||
Some(
|
||||
"https://raw.githubusercontent.com/anthropics/claude-plugins-official/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/plugins/champion-kit/.claude-plugin/icon.png"
|
||||
)
|
||||
);
|
||||
|
||||
// Local marketplace & preview inline small local PNG icons as data URIs.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let local_plugin = tmp.path().join("my-local-plugin");
|
||||
write(
|
||||
&local_plugin.join(".codex-plugin/plugin.json"),
|
||||
r#"{"name":"my-local-plugin","interface":{"logo":"./assets/logo.png"}}"#,
|
||||
);
|
||||
std::fs::create_dir_all(local_plugin.join("assets")).unwrap();
|
||||
std::fs::write(local_plugin.join("assets/logo.png"), b"\x89PNG\r\n\x1a\n").unwrap();
|
||||
|
||||
let local_browse = browse_marketplace(&gh, local_plugin.to_str().unwrap(), None, None, &cancel).unwrap();
|
||||
assert_eq!(local_browse.candidates.len(), 1);
|
||||
assert!(
|
||||
local_browse.candidates[0].icon_url.as_deref().is_some_and(|u| u.starts_with("data:image/png;base64,"))
|
||||
);
|
||||
|
||||
let local_preview =
|
||||
preview_plugin(&gh, local_plugin.to_str().unwrap(), None, None, None, None, &cancel).unwrap();
|
||||
assert!(local_preview.icon_url.as_deref().is_some_and(|u| u.starts_with("data:image/png;base64,")));
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ pub(crate) struct ProviderSpec {
|
||||
pub name: String,
|
||||
pub driver: Driver,
|
||||
pub command: String,
|
||||
pub managed_cli: Option<String>,
|
||||
pub args: Vec<String>,
|
||||
/// Number of trailing arguments added by the built-in agent's settings.
|
||||
pub additional_args_len: usize,
|
||||
@@ -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,6 +113,10 @@ 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();
|
||||
@@ -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_with_env(&spec.command, &spec.env),
|
||||
installed: installed_with_env(spec.executable(), &spec.env),
|
||||
cli_install_command: None,
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
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
|
||||
@@ -1102,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());
|
||||
@@ -1154,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());
|
||||
}
|
||||
|
||||
@@ -1228,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
|
||||
@@ -1280,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();
|
||||
|
||||
@@ -22,6 +22,7 @@ fn paths(dir: &Path) -> AgentPaths {
|
||||
store_dir: dir.join("store"),
|
||||
worktrees_dir: dir.join("worktrees"),
|
||||
models_file: dir.join("models.json"),
|
||||
cli_dir: dir.join("agent-cli"),
|
||||
custom_agents_dir: None,
|
||||
home_dir: None,
|
||||
env_secrets: None,
|
||||
|
||||
@@ -296,6 +296,24 @@ pub fn discover_skills_with_agent_plugins(
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
) -> Vec<AgentSkill> {
|
||||
discover_skills_with_indexed_files(workspaces, home, plugin_skill_dirs, agent_plugin_roots, &[])
|
||||
}
|
||||
|
||||
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
|
||||
/// resolved agent plugin bundle roots (`agent_plugin_roots`), and deeply nested workspace packages
|
||||
/// inferred from `indexed_skill_files` (typically `ProjectIndex::files_with_names(&["SKILL.md"])`).
|
||||
///
|
||||
/// Direct workspace roots and shallow monorepo packages (depth 1–2) are scanned directly on disk
|
||||
/// first so discovery works before indexing finishes and preserves shallow-over-deep precedence.
|
||||
/// Any deeper package roots discovered via `indexed_skill_files` are scanned next, sorted from
|
||||
/// shallowest to deepest and deduplicated by canonical path.
|
||||
pub fn discover_skills_with_indexed_files(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
indexed_skill_files: &[PathBuf],
|
||||
) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
|
||||
@@ -321,6 +339,13 @@ pub fn discover_skills_with_agent_plugins(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Deeply nested packages (arbitrary depth) surfaced by the project file index.
|
||||
for sub in indexed_package_roots(&all_workspaces, indexed_skill_files) {
|
||||
let sub_canon = dunce::canonicalize(&sub).unwrap_or_else(|_| sub.clone());
|
||||
if seen_workspaces.insert(sub_canon) {
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (sub.join(rel), *source)));
|
||||
}
|
||||
}
|
||||
if let Some(home) = home {
|
||||
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
|
||||
}
|
||||
@@ -413,6 +438,74 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Extracts workspace package roots from indexed `SKILL.md` file paths.
|
||||
///
|
||||
/// Only accepts `SKILL.md` files located inside one of [`WORKSPACE_ROOTS`] at depth 0, 1, or 2
|
||||
/// below `<dot_dir>/skills` (`skills/SKILL.md`, `skills/<name>/SKILL.md`, or
|
||||
/// `skills/<category>/<name>/SKILL.md`), rejecting unrelated fixture/doc `SKILL.md` files as well
|
||||
/// as packages under hidden directories or [`SKIP_MONOREPO_DIRS`]. Returns roots sorted from
|
||||
/// shallowest to deepest (then lexicographically) so shallower packages always win on name clashes.
|
||||
fn indexed_package_roots(workspaces: &[PathBuf], indexed_skill_files: &[PathBuf]) -> Vec<PathBuf> {
|
||||
if workspaces.is_empty() || indexed_skill_files.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let workspace_pairs: Vec<(&Path, Option<PathBuf>)> =
|
||||
workspaces.iter().map(|ws| (ws.as_path(), dunce::canonicalize(ws).ok())).collect();
|
||||
let mut candidates: Vec<(usize, PathBuf)> = Vec::new();
|
||||
for file in indexed_skill_files {
|
||||
let Some(pkg_root) = package_root_of_skill_file(file) else { continue };
|
||||
let Some(rel) = relative_within_workspaces(&pkg_root, &workspace_pairs) else { continue };
|
||||
if rel.components().any(|c| match c {
|
||||
std::path::Component::Normal(seg) => {
|
||||
seg.to_str().is_none_or(|s| s.starts_with('.') || SKIP_MONOREPO_DIRS.contains(&s))
|
||||
}
|
||||
_ => true,
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
if !pkg_root.is_dir() {
|
||||
continue;
|
||||
}
|
||||
candidates.push((rel.components().count(), pkg_root));
|
||||
}
|
||||
candidates.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
|
||||
candidates.dedup_by(|a, b| a.1 == b.1);
|
||||
candidates.into_iter().map(|(_, p)| p).collect()
|
||||
}
|
||||
|
||||
/// If `skill_md` sits inside `<pkg>/<dot_dir>/skills[/<category>][/<name>]/SKILL.md` for one of
|
||||
/// [`WORKSPACE_ROOTS`], returns `<pkg>`.
|
||||
fn package_root_of_skill_file(skill_md: &Path) -> Option<PathBuf> {
|
||||
if skill_md.file_name().and_then(|n| n.to_str()) != Some("SKILL.md") {
|
||||
return None;
|
||||
}
|
||||
let mut cur = skill_md.parent()?;
|
||||
for _ in 0..=2 {
|
||||
if cur.file_name().and_then(|n| n.to_str()) == Some("skills")
|
||||
&& let Some(dot_dir) = cur.parent()
|
||||
&& let Some(dot_name) = dot_dir.file_name().and_then(|n| n.to_str())
|
||||
&& WORKSPACE_ROOTS.iter().any(|(rel, _)| rel.split('/').next() == Some(dot_name))
|
||||
&& let Some(pkg_root) = dot_dir.parent()
|
||||
{
|
||||
return Some(pkg_root.to_path_buf());
|
||||
}
|
||||
cur = cur.parent()?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn relative_within_workspaces(pkg_root: &Path, workspaces: &[(&Path, Option<PathBuf>)]) -> Option<PathBuf> {
|
||||
let pick_shortest =
|
||||
|iter: &mut dyn Iterator<Item = &Path>| iter.min_by_key(|rel| rel.components().count()).map(Path::to_path_buf);
|
||||
let mut direct = workspaces.iter().filter_map(|(ws, _)| pkg_root.strip_prefix(ws).ok());
|
||||
if let Some(rel) = pick_shortest(&mut direct) {
|
||||
return Some(rel);
|
||||
}
|
||||
let canon_pkg = dunce::canonicalize(pkg_root).ok()?;
|
||||
let mut canonical = workspaces.iter().filter_map(|(_, canon_ws)| canon_pkg.strip_prefix(canon_ws.as_ref()?).ok());
|
||||
pick_shortest(&mut canonical)
|
||||
}
|
||||
|
||||
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
|
||||
/// category folders, validated.
|
||||
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
|
||||
@@ -1469,4 +1562,65 @@ mod tests {
|
||||
let staged_md = std::fs::read_to_string(farm.join("copilot/verify-ux/SKILL.md")).unwrap();
|
||||
assert_eq!(staged_md, raw_md);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_skill_files_discover_deep_monorepo_skills_and_respect_filters_and_precedence() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let ws = root.join("ws");
|
||||
|
||||
let deep_grafana =
|
||||
ws.join("mango/tools/mai-grafana-dashboards/.github/skills/edit-grafana-dashboards/SKILL.md");
|
||||
let deep_category = ws.join("a/b/c/.agents/skills/ops/deploy/SKILL.md");
|
||||
let deep_named_skills = ws.join("a/b/c/.claude/skills/skills/SKILL.md");
|
||||
let shallow_clash = ws.join("pkg/.agents/skills/shared/SKILL.md");
|
||||
let deep_clash = ws.join("a/b/c/.github/skills/shared/SKILL.md");
|
||||
let depth3_clash = ws.join("x/y/z/.github/skills/depth-race/SKILL.md");
|
||||
let depth4_clash = ws.join("x/y/z/w/.agents/skills/depth-race/SKILL.md");
|
||||
let fixture_skill = ws.join("crates/ide-plugin/tests/fixtures/agent-skills/skills/fixture-only/SKILL.md");
|
||||
let hidden_dir_skill = ws.join(".worktrees/branch/.github/skills/wt-only/SKILL.md");
|
||||
let target_dir_skill = ws.join("crates/app/target/gen/.github/skills/build-only/SKILL.md");
|
||||
|
||||
write(&deep_grafana, "---\nname: edit-grafana-dashboards\ndescription: Edit Grafana dashboards\n---\n");
|
||||
write(&deep_category, "---\nname: deploy\ndescription: Deploy service\n---\n");
|
||||
write(&deep_named_skills, "---\nname: skills\ndescription: Skill named skills\n---\n");
|
||||
write(&shallow_clash, "---\nname: shared\ndescription: Shallow copy\n---\n");
|
||||
write(&deep_clash, "---\nname: shared\ndescription: Deep copy\n---\n");
|
||||
write(&depth3_clash, "---\nname: depth-race\ndescription: Depth 3 wins\n---\n");
|
||||
write(&depth4_clash, "---\nname: depth-race\ndescription: Depth 4 loses\n---\n");
|
||||
write(&fixture_skill, "---\nname: fixture-only\ndescription: Fixture not under a skill root\n---\n");
|
||||
write(&hidden_dir_skill, "---\nname: wt-only\ndescription: Inside hidden dir\n---\n");
|
||||
write(&target_dir_skill, "---\nname: build-only\ndescription: Inside target dir\n---\n");
|
||||
|
||||
// Without indexed files, depth-3+ packages are beyond the 2-level direct walk.
|
||||
let shallow_only = discover_skills(&ws, None);
|
||||
assert!(shallow_only.iter().all(|s| s.name != "edit-grafana-dashboards"));
|
||||
assert!(shallow_only.iter().any(|s| s.name == "shared" && s.description == "Shallow copy"));
|
||||
|
||||
// Passing indexed `SKILL.md` paths (even in reversed depth order) surfaces deep skills
|
||||
// while keeping shallow-over-deep precedence and ignoring fixtures/hidden/build dirs.
|
||||
let indexed = vec![
|
||||
depth4_clash,
|
||||
depth3_clash,
|
||||
deep_clash,
|
||||
deep_grafana,
|
||||
deep_category,
|
||||
deep_named_skills,
|
||||
fixture_skill,
|
||||
hidden_dir_skill,
|
||||
target_dir_skill,
|
||||
];
|
||||
let found = discover_skills_with_indexed_files(std::slice::from_ref(&ws), None, &[], &[], &indexed);
|
||||
let by = |n: &str| found.iter().find(|s| s.name == n);
|
||||
|
||||
let grafana = by("edit-grafana-dashboards").expect("depth-3 .github/skills discovered");
|
||||
assert_eq!(grafana.source, AgentSkillSource::GithubWorkspace);
|
||||
assert!(by("deploy").is_some(), "category skill under depth-3 package discovered");
|
||||
assert!(by("skills").is_some(), "skill named `skills` under depth-3 package discovered");
|
||||
assert_eq!(by("shared").unwrap().description, "Shallow copy", "shallow package beats deep package");
|
||||
assert_eq!(by("depth-race").unwrap().description, "Depth 3 wins", "depth 3 beats depth 4");
|
||||
assert!(by("fixture-only").is_none(), "unrelated fixture SKILL.md ignored");
|
||||
assert!(by("wt-only").is_none(), "hidden directory tree ignored");
|
||||
assert!(by("build-only").is_none(), "SKIP_MONOREPO_DIRS tree ignored");
|
||||
}
|
||||
}
|
||||
@@ -65,10 +65,14 @@ 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`.
|
||||
@@ -228,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"]));
|
||||
@@ -297,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"}));
|
||||
@@ -637,6 +663,30 @@ async fn subscribers_do_not_replace_or_close_each_other() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detach_ui_sinks_preserves_internal_host_subscribers() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let ui = Arc::new(Mutex::new(Vec::new()));
|
||||
let watcher = Arc::new(Mutex::new(Vec::new()));
|
||||
let subscribe = |key: &str, events: &Arc<Mutex<Vec<AgentEvent>>>| {
|
||||
let events = events.clone();
|
||||
mgr.subscribe_as(key, Arc::new(move |event| events.lock().push(event)));
|
||||
};
|
||||
subscribe("main", &ui);
|
||||
subscribe("__automation_watch_run1", &watcher);
|
||||
|
||||
mgr.detach_ui_sinks();
|
||||
mgr.shared.emit(AgentEvent::Providers);
|
||||
assert_eq!(ui.lock().len(), 0, "UI window sink must be detached");
|
||||
assert_eq!(watcher.lock().len(), 1, "internal __-prefixed automation watcher must stay attached");
|
||||
|
||||
mgr.detach_sinks();
|
||||
mgr.shared.emit(AgentEvent::Providers);
|
||||
assert_eq!(watcher.lock().len(), 1, "detach_sinks clears all remaining sinks");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn manager_at(dir: &Path, models_file: &Path, agent: Arc<FakeAgent>) -> AgentManager {
|
||||
// These tests speak to FakeAgent, never an installed CLI, including after a provider reload.
|
||||
let agents = dir.join("agents");
|
||||
@@ -656,6 +706,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.
|
||||
@@ -3119,6 +3170,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,
|
||||
@@ -3462,6 +3514,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();
|
||||
@@ -3558,6 +3666,79 @@ async fn imports_copilot_sessions_and_loads_their_history() {
|
||||
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();
|
||||
@@ -4503,6 +4684,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,
|
||||
@@ -4568,6 +4750,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,
|
||||
@@ -4831,6 +5014,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,
|
||||
@@ -4888,14 +5072,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")]
|
||||
@@ -6336,6 +6527,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
McpServer {
|
||||
id: "user::slack".into(),
|
||||
@@ -6352,6 +6545,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
},
|
||||
]
|
||||
}));
|
||||
@@ -6658,6 +6853,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,
|
||||
@@ -6781,6 +6977,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,
|
||||
@@ -7263,6 +7460,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};
|
||||
@@ -7352,3 +7628,22 @@ async fn metadata_edits_do_not_bump_updated_ms() {
|
||||
.unwrap();
|
||||
assert_eq!(after_memory.updated_ms, fixed_ms);
|
||||
}
|
||||
|
||||
/// An automation reads the status as soon as its prompt is accepted: the previous turn's
|
||||
/// `Ready` would complete the run before its turn started.
|
||||
#[tokio::test]
|
||||
async fn an_accepted_scheduled_prompt_no_longer_reads_as_ready() {
|
||||
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;
|
||||
|
||||
mgr.prompt_scheduled(&task.id, text("again"), ScheduledTurnMeta::default()).await.unwrap();
|
||||
// The single-threaded runtime has not started the spawned turn yet.
|
||||
assert_eq!(mgr.task_snapshot(&task.id).unwrap().status, AgentStatus::Starting);
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
+107
-111
@@ -1,112 +1,108 @@
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6"]}
|
||||
{"from":"shim","msg":{"request":{"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","feedback_mode":{"kind":"post"},"ide_rc_auto_enable_gate":true,"models":[{"description":"Sonnet 5.5 · Efficient for routine tasks","displayName":"Default (recommended)","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.1","resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","resolvedModel":"claude-sonnet-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-4-6"}],"pid":23982,"remote_control_auto_connect_default":false,"remote_control_auto_enable":false,"remote_control_auto_on_by_default":false,"remote_control_available":true,"session_state":"idle"},"subtype":"success"},"type":"control_response"}}
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","a89e008b-23b6-41ea-bebb-612440f38e3c"]}
|
||||
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
|
||||
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"effort":"medium","model":"claude-haiku-5-5","ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false},"effective":{"model":"opus"}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"running","subtype":"session_state_changed","type":"system","uuid":"5e39fde0-9f18-47f0-8b7e-21007ec957c0"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"ad1291e3-8d79-4048-a10c-599eafd30c9b"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"0ed63980-6c4a-40b9-b94d-3bc062cddd58"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"17b7ad4c-6ad3-4d9c-aeef-2e027b0d75ae","view_mode":"default"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"7b8f8fcd-669e-4606-ad6f-3368116e7a75"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"org_level_disabled","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1793203800,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1793203800,"status":"allowed","utilization":0.31},"seven_day":{"resetsAt":1793631600,"status":"allowed","utilization":0.32}}},"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"rate_limit_event","uuid":"b3ef3e2a-11ad-46f9-8ea5-fd01f8d0fe39"}}
|
||||
{"from":"cli","msg":{"commands":[{"argumentHint":"","description":"Review a pull request","name":"review"}],"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"commands_changed","type":"system","uuid":"5f60f663-94ff-4885-9167-b12cae835fca"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1661,"type":"stream_event","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"4fb86b8a-bfa9-439b-b46b-6ef6e381d243"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0bc16cbc-fcbb-4d52-bd5b-4d864b307bbd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"0510612a-2068-496a-85f4-f61706fb8cd5"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"{\"command\": \"sleep 3","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"281a35ac-8285-4591-8c60-5ddc743b7036"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"44c02159-084d-48d1-a23c-5bd3628e69e7"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"ca641c1e-c60b-4943-a07b-9ea03c9b8845"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"leep 3 se","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"bc5c34f0-653a-4041-a6cf-42c0dcd0fc2c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"conds then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"00cd396e-f45d-4b60-b484-9fb0ddfc3384"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6987c232-0dbf-43be-83fe-2164d6d701ee"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhj5mGEZkoUv4HmADLr","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhj5SvXJc5aP46FPBxn","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:00.931Z","type":"assistant","user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"b7befa90-ef05-44ff-9822-ec00f61130b2","wire_tool_inputs":{"toolu_01RLgKZhL3rEQrnb6R4yD7LH":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"01897941-b66d-4657-a87b-14dde2420f38"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"daf07992-fd3c-46c2-8fe7-3014bf6e6cf0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhj5mGEZkoUv4HmADLr","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"6c4b9511-1539-45a7-9184-9efc1ce9384d"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"now","session_id":"","type":"user","uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"queued","type":"command_lifecycle","uuid":"6ae9f6be-c8d5-4feb-8c17-71bfc3d4880e"}}
|
||||
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"task_started","task_id":"bk6c5st9v","task_type":"local_bash","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"e45f0b55-eb72-4cc6-8bb7-0ba207583cc7"}}
|
||||
{"from":"cli","msg":{"output_file":"","run_id":"0mvs568cx-76274178","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bk6c5st9v","tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"system","uuid":"0d23dced-54be-49b0-963b-a9e67ae4b75c"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:04.328Z","tool_result_meta":[{"id":"toolu_01RLgKZhL3rEQrnb6R4yD7LH","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"998e4d6c-47bf-4e81-b630-1eb86398d192"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":2891,"duration_ms":5544,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1797,"first_request_input_tokens":29936,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":15110,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":15110,"cacheReadInputTokens":14824,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0033443400000000003,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":1,"request_sent_wall_ms":1793193598927,"result":"","result_index":0,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"aborted_tools","time_to_request_ms":138,"total_cost_usd":0.0033443400000000003,"ttft_ms":2142,"ttft_stream_ms":1797,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":15110,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":15110,"cache_read_input_tokens":14824,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","user_message_uuids":["f5f7de43-8575-4db0-a20d-7890bc534ace"],"uuid":"a4afa59a-be05-41e3-bc85-4cc8e9b28506"}}
|
||||
{"from":"cli","msg":{"command_uuid":"f5f7de43-8575-4db0-a20d-7890bc534ace","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"cancelled","type":"command_lifecycle","uuid":"4911bef5-6b3d-4c0e-803e-5f21202ce766"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"started","type":"command_lifecycle","uuid":"89c8590f-1c08-4183-b430-5e888745fbfc"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1"],"claude_code_version":"2.1.312","cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/gx/1228y8wj7bx6dl6m9syzrb340000gn/T/.tmpC932yI","output_style":"Concise","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"init","terminal_slash_commands":["doctor","color","focus","reload-plugins"],"type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"a05d013f-558f-4581-9ac1-49e4329e9d7d","view_mode":"default"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","status":"requesting","subtype":"status","type":"system","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"d00d3b7f-227d-4373-9092-676090723763"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","ttft_ms":1500,"type":"stream_event","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"c634f9c8-ff1c-44fa-9138-5d357a418f58"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0db4c93b-e0cb-4fcf-857f-c79fed9a2609"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e7d95fb9-826f-45e1-8e7c-4e6abcdef7c9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"27c0c433-3ee8-42fc-830a-90d67cb371d1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"cc8a606b-0251-4927-96c5-160880f430f6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" s","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1c859e8c-52fe-4fb3-8ad1-0122752cdccf"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"202bcadf-3533-4744-a259-97bfc7bef0e3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"leep task","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2a273607-1f22-4a49-860c-30184e6bfe01"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":9,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"63d703f5-6eec-4a89-a6c7-c38245001004"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" completed with","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"dba1141d-78a3-406a-9125-bf02b5b4a2a3"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2618ae50-9e26-4724-89f6-7fda1f105f42"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" output \"done.\"","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ba6f0b4d-aa70-4347-903e-46119eaa15e6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":16,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"beaeb52e-0825-47b9-ba7e-e09d6de4818c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" The user as","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"3408f5ca-fe05-4bbf-8ae0-b1bc4db97033"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"b5f0f099-f629-469e-a51b-bcb1abaf5f66"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ked me","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"32b263d1-ff54-48f3-a61d-96e98eddce23"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":22,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"581160fb-90e0-4831-b087-d702a7a42fa4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" to end my answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"af0f7710-cb0d-4192-85b6-2a458a17a463"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1ea97064-de2c-4b80-9f32-09ce3a9ce60b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"er with the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"ad449330-cf10-4919-b4a0-9f510c259d38"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"9c7d8148-ced4-4647-bdb0-fca91d88aab9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" word BAN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2e4fed14-2110-4d2c-81d0-033f66954ed6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":29,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"dea229d8-9c12-4bf9-9cea-bf9813d41840"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"AN","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"a4c1bb86-c884-4f6b-b752-3d57bbb36b1c"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":31,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1cbe8e9c-f44c-4dfb-b6e0-8032d35991db"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"A, which","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0a79f76a-a558-4de1-8323-7547d8628d28"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"1961a504-ee75-484f-9c2d-8418496ff795"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" is a har","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"5fa188a2-6e70-4af5-8900-13c30c78c7ad"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":7,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a4d053b7-4485-4d18-8fd2-2354b2a22310"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"mless request, and there's a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"d734fe28-ce41-4002-ad2f-ea0dbc0857a0"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"7fa6189b-3633-4814-9755-a93619616466"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" note","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6dfd60d4-172b-456e-bb66-4f2d6c966233"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":45,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"4aa94d3f-16be-48dc-aa05-1a85105921bb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" about","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"9eb2805d-f684-40ee-b368-468facc4890a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"992053c7-e234-4d72-9c11-d00786dd2c52"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" repl","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"10f0c715-33ad-44fc-8818-7d1a4549fef3"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":49,"estimated_tokens_delta":2,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"e1dad1ff-ec95-4ce1-b07b-b3b42c5f0a15"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ying in","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"244ce6fc-4dfd-4f6e-abf5-57f860663fdc"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":54,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"6f4e3a68-8a38-4ef1-a1d8-5d16b0bdb9e0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" Chinese per inst","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"6fce552c-bfa4-4705-b50e-1e162b487f9d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":58,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"491e90c9-da11-4f2f-96d1-2e6c501a13b9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ructions, but","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"cee9edc1-dac1-4997-9b0e-a64e6cc17173"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":61,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"2ad92491-7893-4f66-9f8c-8e0c49a0dd21"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" the user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"0d10f6b1-daf3-4c40-92cc-78a3b7addc0d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":65,"estimated_tokens_delta":4,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"48d2ff82-0a78-43f7-bd6e-41170fd9be53"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"rote in English—","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"7af06734-f004-4264-aa76-0e5404fb1da7"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":66,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"a607027c-4b06-467b-bd39-99a40085c05b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"I","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f651bfee-b7bb-4d2f-8872-bc43aff55c2b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":72,"estimated_tokens_delta":6,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"862b7d4a-8d66-48ce-a954-764541537982"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"'ll decide how to handle","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"f9a8266d-7203-49f1-b14e-cdbcd5311bda"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":75,"estimated_tokens_delta":3,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"c5bc3ec1-229c-4acc-8a9a-b1184be9a1bf"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" that bal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"1ea067e9-fbb8-4685-a217-e42170c35740"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":80,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"ce143939-c780-4938-ba2c-f6a54b8f4a6f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ance while including","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"77668dd2-c3ad-4df5-87a3-4b76a2219c65"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":81,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"0475f779-b12b-4ae0-a42a-4ae723a6d468"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":" B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"49727b38-d58a-4ad0-9728-aa4bc223b54d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":86,"estimated_tokens_delta":5,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"02f8ee0c-36d8-4de5-af74-fe7d19969366"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA at the end.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"2adc15b2-5b1c-4add-b3ad-1ceaaa665bae"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":87,"estimated_tokens_delta":1,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"eb0ae205-deb6-4b79-9726-98fd9d1d533c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","type":"stream_event","uuid":"40e6df26-1321-45ea-8ca5-9d96ca00087b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":287,"estimated_tokens_delta":200,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","subtype":"thinking_tokens","type":"system","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","uuid":"57a445b0-9671-4073-89c6-f72835125be3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"aaf131b8-99e0-4fd9-9169-00be0b4e360a"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The sleep task completed with output \"done.\" The user asked me to end my answer with the word BANANA, which is a harmless request, and there's a note about replying in Chinese per instructions, but the user wrote in English—I'll decide how to handle that balance while including BANANA at the end.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","thinking_display":"summarized","thinking_duration_ms":3423,"timestamp":"2026-10-28T13:20:09.346Z","type":"assistant","user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"ecaa1288-7581-48ad-9c59-89e4bb9f063f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"549a0ef9-e0b3-40af-bb4a-8aba4c08eb8d"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d3049aaf-53af-4878-b273-68835033ff92"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"命","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"4a3271f3-0c7d-427c-9407-c610ad454b15"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"令输出为 `done`","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"3558f94f-6fcb-4c7a-96a5-6f6e415a5f93"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"。\n\nB","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fea97b73-1f25-4f88-94db-0f0fdd401d2b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"delta":{"text":"ANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"303a047a-fc87-48ea-9524-e102e112b10a"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"命令输出为 `done`。\n\nBANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CgUhjUjtfNy2NL2chxrF5","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"inference_geo":"global","input_tokens":2,"output_tokens":4,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CgUhjUTmHT72RxnP7ze5J","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","timestamp":"2026-10-28T13:20:09.358Z","type":"assistant","uuid":"73a78906-d0d9-432d-b1d7-a34ac4d05707"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"d665c80a-e37f-476e-ac86-e12d44f26fad"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192}}},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"46798358-6519-4878-af21-22006f465f53"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CgUhjUjtfNy2NL2chxrF5","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","type":"stream_event","uuid":"fe0e0673-335a-41a0-b7c2-7b5d78e99739"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"duration_api_ms":7859,"duration_ms":5066,"fast_mode_disabled_reason":"sdk_opt_in_required","fast_mode_state":"off","first_content_frame_ms":1586,"first_request_input_tokens":33868,"is_error":false,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":19042,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":19042,"cacheReadInputTokens":44758,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00453478,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":318,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":3932,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":3932,"cacheReadInputTokens":29934,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00119044,"inputTokens":2,"maxOutputTokens":128000,"outputTokens":209,"provider":"firstParty","thinkingTokens":192,"webSearchRequests":0}},"num_turns":1,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"request_sent_wall_ms":1793193604397,"result":"命令输出为 `done`。\n\nBANANA","result_index":1,"safety_stops":0,"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_ms":59,"total_cost_usd":0.00453478,"ttft_ms":5008,"ttft_stream_ms":1563,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":3932,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":3932,"cache_read_input_tokens":29934,"input_tokens":2,"output_tokens":209,"type":"message"}],"output_tokens":209,"output_tokens_details":{"thinking_tokens":192},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","user_message_uuids":["5a435507-7a2d-49cd-9399-6d6e640c57ee"],"uuid":"8172897e-6304-4855-9480-f4e579da730f"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5a435507-7a2d-49cd-9399-6d6e640c57ee","session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"completed","type":"command_lifecycle","uuid":"3c5163f4-90c0-4939-a3e5-aba1cf13bca3"}}
|
||||
{"from":"cli","msg":{"session_id":"5bcd95e5-bf92-45e9-a1b6-d68a7b8ffef6","state":"idle","subtype":"session_state_changed","type":"system","uuid":"57c31a3d-da32-4a0c-9124-372c880779b7"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 3 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"e745940b-18ac-4078-b11e-72be2ae6401b","written_at":"2026-12-03T13:51:32.578Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"f85c6752-6469-4ce7-bbb2-0349f3fabfa8","written_at":"2026-12-03T13:51:32.579Z"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpX66GLs","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/992375695253/scratchpad","served_by_anthropic":true,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":69,"other_plugin":17,"user_settings":37},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":69,"own":69},"phase_start_ms":{"first_message_handle_ms":282,"first_message_read_ms":0,"grove_check_ms":187,"headless_post_load_ms":257,"headless_prologue_ms":186,"hooks_init_ms":178,"init_emit_ms":343,"initial_messages_load_ms":189,"input_ready_ms":0,"mcp_client_module_load_ms":192,"mcp_config_wait_ms":170,"mcp_connect_ms":182,"mcp_prewait_ms":283,"model_catalog_decision_ms":166,"node_boot_ms":0,"permission_context_ms":89,"pre_action_client_data_url_ms":84,"pre_action_init_ms":46,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":45,"pre_action_migrations_ms":84,"pre_action_ms":45,"print_import_ms":183,"prompt_submit_hooks_ms":301,"qe_plugin_skills_load_ms":341,"qe_system_prompt_ms":286,"sdk_mcp_update_ms":282,"settings_load_ms":44,"setup_file_watcher_ms":118,"setup_hooks_snapshot_ms":118,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":119,"setup_uds_dir_ms":96,"setup_uds_listen_ms":114,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":117,"skills_load_ms":95,"tools_commands_load_ms":130},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":282,"grove_check_ms":1,"headless_post_load_ms":1,"headless_prologue_ms":2,"hooks_init_ms":78,"init_emit_ms":1,"initial_messages_load_ms":68,"input_ready_ms":265,"mcp_client_module_load_ms":0,"mcp_config_load_ms":62,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":3,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":37,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":43,"print_import_ms":3,"prompt_submit_hooks_ms":37,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":4,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":31,"setup_release_notes_ms":8,"setup_uds_dir_ms":18,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":23,"setup_uds_publish_ms":0,"skills_load_ms":66,"tools_commands_load_ms":35},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305892295.906,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"488f600b-a63e-4882-99b1-8dcdfe076157","view_mode":"default","written_at":"2026-12-03T13:51:32.639Z"}}
|
||||
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"b6a40890-0e2f-40ab-afc9-8a609749d59e","written_at":"2026-12-03T13:51:32.642Z"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.21},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"rate_limit_event","uuid":"0cafd103-637f-4025-913d-3d23ec776453","written_at":"2026-12-03T13:51:33.412Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":1089,"type":"stream_event","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"1eba9396-f0bb-4de5-8627-5cebfc962d2a"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5abf5f-2492-4471-b355-ffb886685b08"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":1,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"3df5ecdd-e701-43ab-8ad3-90428c0a9bf4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a78c66ea-06f0-4c08-93c3-073ac79ce208"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":3,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58e5f0b8-1cae-4e6e-8142-28c83c20d09c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" user w","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a66bf075-7a36-4bb4-9b94-090567a1047e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":5,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c1baabcf-b72e-438b-8b98-42b628a6c14b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ants a","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"25f84cb1-9180-49b0-b722-0ae6617e00f5"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":11,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"9d1b3935-0637-45ca-a613-f1d02b08bf36"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" Bash command run. The","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"de8666db-803f-4a33-8cb2-9faa68ff3e2a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"e0d0e6f0-dad3-4075-95d3-cf993ac621d9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" session","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"85784fb7-e5a4-4e17-acb8-2018e82e8458"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":18,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"962c83d1-069c-4ff4-b27f-1199d1b3d1b9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"-start hook points","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd405da7-abb7-443d-b309-ac6e805014ed"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":19,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"c77e142c-8284-48f4-b67f-24f6fd1cc99b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" to","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"4957baf5-5e7a-4e23-bfe6-7bd1be56cee1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":24,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"2f3e6875-f0b9-4da6-806b-6420f8e11801"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ward skills, but n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ec0306de-6581-4dcb-8ef0-8bc9a2dffe5b"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":28,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"08432ff1-c798-4640-bb4e-9c6bcb1fa879"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"othing here cal","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"934bdb11-4eac-4db8-ba78-d751a132767a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":33,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b68b320e-d34a-4dd2-a52f-d4eb23b6e631"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ls for one, so I'll","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"1a0911c3-5d56-4df6-a490-ca853de74fe0"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":40,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"a0659fe6-3f44-4ee7-8f28-86561a981c00"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":" just run the command direct","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"d243b5f8-2ad4-4137-abc0-993b12b30faf"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":41,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"0ff88c48-df4d-4fb0-9e10-aad67ea6f912"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"ly.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"43859418-f19d-4dab-b439-e24db14015f1"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":42,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"bcb9947d-4522-4206-bc6c-2fe20b0ee3f0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"480e67e5-6243-4a07-80dc-5e7218eea10d"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":198,"estimated_tokens_delta":156,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"72763f2b-38bb-45f8-b9b4-6dce76fe87dd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2c35aff5-f8f1-423d-ab16-a50fe7f92d2c"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"The user wants a Bash command run. The session-start hook points toward skills, but nothing here calls for one, so I'll just run the command directly.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1155,"timestamp":"2026-12-03T13:51:35.067Z","type":"assistant","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d"],"uuid":"f53249a7-87bb-48d3-8a4d-46fb2bc373c3"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"50eafebf-1675-454d-b48d-4c33f9c46fd0"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{},"name":"Bash","type":"tool_use"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"df423477-fdd3-40b4-bd3f-a6e5e2f4285a"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2840ddf3-7a52-45a6-bcee-28d02c695ce1"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"{\"command\": \"sleep 3 && ech","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"f279d761-fe64-4811-ba7a-d3389c7fa1d6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"o done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"2d7cc471-fe87-49cc-975e-5aefe894bd35"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"77a255b8-8924-4cd2-8239-13d56352e157"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"leep 3 seconds","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5ddf158c-a8ed-475e-b425-4d6aa69d9216"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"8c902fdc-adb0-4db8-91fd-a3c9f799193b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"1019a3dc-64e5-4166-981a-f57347563c32"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","input":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuFeb6zou7Nmj7hYFnf","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"inference_geo":"global","input_tokens":2,"output_tokens":8,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuFePCVDFQ6Zs47Mqbi","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:35.072Z","type":"assistant","uuid":"717bc1de-feb1-41aa-81d7-3ac47c772112","wire_tool_inputs":{"toolu_012tPQXDR9Kw59zBCFJqSuXP":{"command":"sleep 3 && echo done","description":"Sleep 3 seconds then echo done"}}}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"149df489-36d1-4db3-8f19-ae26b6733dc9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":16761,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":16761,"cache_read_input_tokens":26096,"input_tokens":2,"output_tokens":142,"type":"message"}],"output_tokens":142,"output_tokens_details":{"thinking_tokens":51}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"84156816-f10d-4dd6-8dca-f441fea39795"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuFeb6zou7Nmj7hYFnf","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"93925996-0953-4359-9383-f6db7885eb3f"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"queued","type":"command_lifecycle","uuid":"58a87b31-0fab-415d-b450-0ed1f58ec0bc","written_at":"2026-12-03T13:51:35.084Z"}}
|
||||
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP"},"level":"warning","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"1bb27652-e9f7-4277-8138-8840aa03937c","written_at":"2026-12-03T13:51:35.090Z"}}
|
||||
{"from":"cli","msg":{"description":"Sleep 3 seconds then echo done","is_backgrounded":false,"run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"task_started","task_id":"bzep4576h","task_type":"local_bash","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"9f3e9fb8-34cd-4f9c-95f9-b4a7af80eb18","written_at":"2026-12-03T13:51:39.785Z"}}
|
||||
{"from":"cli","msg":{"duration_ms":3020,"output_file":"","run_id":"0mx7m5ix4-f838229f","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"completed","subtype":"task_notification","summary":"Sleep 3 seconds then echo done","task_id":"bzep4576h","tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"system","uuid":"63898564-4e95-4aa3-8e90-7fc67025ddce","written_at":"2026-12-03T13:51:39.802Z"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"done","is_error":false,"tool_use_id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:39.838Z","tool_result_meta":[{"id":"toolu_012tPQXDR9Kw59zBCFJqSuXP","permission_decision":{"decision":"accept","reason_type":"subcommandResults","source":"config"}}],"tool_use_result":{"interrupted":false,"isImage":false,"noOutputExpected":false,"stderr":"","stdout":"done"},"type":"user","uuid":"8103e7bc-d615-4e6a-9c31-c7d36db98577"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"started","type":"command_lifecycle","uuid":"93252284-65fe-4529-ba8f-485b97e6734a","written_at":"2026-12-03T13:51:39.892Z"}}
|
||||
{"from":"cli","msg":{"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","status":"requesting","subtype":"status","type":"system","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"1f01a672-b108-46e4-9637-57b2abd60258","written_at":"2026-12-03T13:51:39.892Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","ttft_ms":931,"type":"stream_event","uuid":"29de849c-06bb-40e5-a9ad-b70c2f061329"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"thinking":"","type":"thinking"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"92b49174-c189-466f-ad5d-5eea3b3afc2e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":2,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"b8ec03ca-333f-4fac-a597-c43aa181360f"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"I need","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"ab10276f-535b-4f19-948c-3f31c090a94e"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":8,"estimated_tokens_delta":6,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"44beb4b3-366d-4725-8781-17a8ab0c2743"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" to make sure the answ","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"fa8db41b-008b-4779-8269-e3df396df9b2"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":10,"estimated_tokens_delta":2,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"58821ddd-b1aa-437b-b6ea-120c4a781f6b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"er fin","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"a4b2ec90-2589-4308-b773-1d95de4e39ab"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":13,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"11a853c1-af93-4d0d-b600-e7f2e51a3a16"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ishes with B","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3a9a743b-6a39-4572-b86e-4b07355aad6c"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":17,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"42ca95a6-a59d-4e50-8633-8689136027ad"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ANANA, and the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e1173332-7e42-470a-bba6-28348e046d10"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":21,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"1c94c3c4-4eba-42e7-a8a4-00c60bb98763"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" Bash result was","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"c9e62676-e267-4934-85f2-79d124d4bae8"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":25,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"03d96f9b-adf7-4f6f-b28b-d427db8b8630"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" just \"done.\" So","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bcbdb107-0d53-4872-a6d0-ea0443ab46a6"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":26,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"383344f4-e9c7-4fc6-8156-2a455fc315d4"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"bd677e6a-ccc0-460c-b78c-d146e412fdfc"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":27,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"95673280-0801-43f2-a343-0e1e2294440d"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" re","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"3ceba820-e7a1-406d-85cc-4e737440db84"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":34,"estimated_tokens_delta":7,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"ec3fefec-de8f-49c3-832f-ee8cdb9098ba"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"ply will start with \"Output:","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"479a0469-81c6-44ed-901f-3b5ba5919286"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":38,"estimated_tokens_delta":4,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f1187702-1431-4c3f-b55b-b5d6b6e1b4cf"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" done\" and close","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"256ff2f5-a3c1-4c39-ba87-85a6f8a66995"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":43,"estimated_tokens_delta":5,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"db91d155-3a27-4751-8f44-9f55e24a2d56"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" with BANANA on the","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"96de0914-3708-4b8f-afcd-6b1834e0a46a"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":46,"estimated_tokens_delta":3,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"f315f874-841c-471a-aa95-c7b30c4ecca9"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":" last line.","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"8b5125ea-c014-4134-9967-bfc89d40f300"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":47,"estimated_tokens_delta":1,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"7be0f157-678f-462f-b2ed-f69ee1306d62"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"estimated_tokens":null,"thinking":"\n\n","type":"thinking_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","type":"stream_event","uuid":"e17e4edd-aef5-4819-ae50-94d9b359f5e9"}}
|
||||
{"from":"cli","msg":{"estimated_tokens":199,"estimated_tokens_delta":152,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","subtype":"thinking_tokens","type":"system","user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","uuid":"344c71df-0721-4f7a-bf9d-a2c9ac2b0431"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"type":"signature_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5e790c6d-4323-451b-9dbf-9f36e94b59d0"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"thinking":"I need to make sure the answer finishes with BANANA, and the Bash result was just \"done.\" So the reply will start with \"Output: done\" and close with BANANA on the last line.\n\n","type":"thinking"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","thinking_display":"summarized","thinking_duration_ms":1170,"timestamp":"2026-12-03T13:51:42.004Z","type":"assistant","uuid":"19f7c707-0b92-43f4-a1ff-6f6ba28c9158"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"66f6946c-8aa7-4893-8a3f-fc7c023ea3f6"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"content_block":{"text":"","type":"text"},"index":1,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"6bef1d9a-bcfa-42d8-b3fa-865bbe31804e"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"The command print","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"5866afb3-f9f8-42ba-9ae6-928e88f63709"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":"ed `done`.","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"22c7b7dc-dfa8-49c6-a931-a2a5f179eebe"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"delta":{"text":" BANANA","type":"text_delta"},"index":1,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"265276d2-0f17-4bd8-8719-b6c0464079fc"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"text":"The command printed `done`. BANANA","type":"text"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuGALWJsYSxwR2j7F3W","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"inference_geo":"global","input_tokens":2,"output_tokens":3,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuGA4t6XHrNhvpU1gjW","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","timestamp":"2026-12-03T13:51:42.006Z","type":"assistant","uuid":"4edeb5e3-ae9c-4e64-ab43-dd864db6636c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"index":1,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"950b3a05-26db-4a0b-bb6e-62d584a38638"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"end_turn","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":72,"output_tokens_details":{"thinking_tokens":58}}},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"3fb8dfd0-35eb-49ff-a0f9-94c6cff59bcd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuGALWJsYSxwR2j7F3W","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","type":"stream_event","uuid":"eafb6e94-6aeb-4c20-929f-6d5dc4f8df6a"}}
|
||||
{"from":"cli","msg":{"command_uuid":"5cf21cb4-f4c7-4360-8932-61818a8e57ee","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"e5548a7e-c304-42d1-a536-2e123ebd58d4","written_at":"2026-12-03T13:51:42.067Z"}}
|
||||
{"from":"cli","msg":{"api_error_status":null,"begun_message_ids":["msg_011CheuFeb6zou7Nmj7hYFnf","msg_011CheuGALWJsYSxwR2j7F3W"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":4974,"duration_ms":9488,"fast_mode_state":"off","first_content_frame_ms":1332,"first_request_cache_read_input_tokens":26096,"first_request_input_tokens":42859,"input_attachments_detail":{"ambient_start_ms":1,"ambient_wait_ms":5,"cpu_ms":15,"major_faults":0,"producers":44,"prompt_producers_ms":0,"render_ms":0,"setup_ms":0,"slowest_producer":"deferred_tools_delta","slowest_producer_ms":6,"token_counts":0},"is_error":false,"message_normalization_detail":{"after_ms":0,"before_ms":0,"images_ms":0,"messages":19,"normalize_ms":0,"other_ms":1,"post_process_ms":0,"wire_messages":2},"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":28926,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":28926,"cacheReadInputTokens":68953,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.0067110300000000015,"inputTokens":1198,"maxOutputTokens":128000,"outputTokens":233,"provider":"firstParty","thinkingTokens":109,"webSearchRequests":0}},"num_turns":2,"origin":{"kind":"human"},"permission_denials":[],"process_turn_index":0,"queued_turn_count":0,"request_build_detail":{"cache_break_record_ms":1,"headers_ms":0,"other_ms":0,"plans_ms":0,"record_attempt_ms":0,"records_ms":0,"retry_setup_ms":0,"sent_build_cache_breakpoints_ms":0,"sent_build_ms":1,"sent_build_safety_context_ms":0,"sent_build_surrogate_scan_ms":0,"system_ms":0},"request_sent_wall_ms":1796305892823,"result":"The command printed `done`. BANANA","result_index":0,"safety_stops":0,"session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","stop_reason":"end_turn","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"success","terminal_reason":"completed","time_to_request_cpu_ms":107,"time_to_request_loop_lag_ms":1,"time_to_request_major_faults":1,"time_to_request_ms":243,"time_to_request_phases_ms":{"autocompact":1,"client_creation":2,"conversation_append":1,"engine_pickup":1,"init_frame_send":1,"init_message":2,"input_attachments":8,"input_hooks":37,"loop_entry":1,"message_normalization":1,"message_prep":1,"model_config_wait":0,"model_gates":163,"other":2,"process_user_input":2,"query_setup":0,"request_announcements":3,"request_build":2,"resume_other":0,"system_prompt":5,"tool_pool_refresh":1,"tool_schema_build":8,"transcript_persist":1},"tool_schema_build_detail":{"after_ms":0,"betas_ms":0,"new_schemas":13,"other_ms":0,"placement_ms":2,"render_ms":3,"tools":13,"waits_ms":3},"total_cost_usd":0.0067110300000000015,"ttft_ms":2487,"ttft_stream_ms":1331,"turn_start_resume_kind":"none","type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":28926,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":28926,"cache_read_input_tokens":68953,"fallback_credit":null,"inference_geo":"global","input_tokens":4,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":12165,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":12165,"cache_read_input_tokens":42857,"input_tokens":2,"output_tokens":72,"type":"message"}],"output_tokens":214,"output_tokens_details":{"thinking_tokens":109},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","user_message_uuids":["85d18ab2-e0be-452f-8db8-5f5cfa76152d","5cf21cb4-f4c7-4360-8932-61818a8e57ee"],"uuid":"d3f210c9-67ad-4ec5-b122-3d4477ae65b5","written_at":"2026-12-03T13:51:42.069Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"85d18ab2-e0be-452f-8db8-5f5cfa76152d","session_id":"a89e008b-23b6-41ea-bebb-612440f38e3c","state":"completed","type":"command_lifecycle","uuid":"32e0888f-d2b7-4721-bc7c-6c5320d3c99c","written_at":"2026-12-03T13:51:42.070Z"}}
|
||||
@@ -0,0 +1,34 @@
|
||||
{"launch":["--model","haiku","-p","--input-format","stream-json","--output-format","stream-json","--verbose","--permission-prompt-tool","stdio","--include-partial-messages","--thinking-display","summarized","--allow-dangerously-skip-permissions","--session-id","f782ff38-9bfe-4bd7-a857-f3cb10b38bcf"]}
|
||||
{"from":"shim","msg":{"request":{"perTaskStopAffordance":true,"subtype":"initialize"},"request_id":"req_1","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"pending_permission_requests":[],"pending_user_dialog_requests":[],"request_id":"req_1","response":{"analytics_disabled":false,"capabilities":["ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1"],"claude_code_version":"2.1.335","commands":[{"argumentHint":"","description":"Review a pull request","name":"review"},{"argumentHint":"","description":"Write a CLAUDE.md","name":"init"}],"current_permission_mode":"default","fast_mode_state":"off","feedback_mode":{"kind":"post"},"hook_on_failure_supported":true,"hooks_when_unanswered_kept":0,"ide_rc_auto_enable_gate":true,"models":[{"description":"Opus 5.5 · Best for everyday, complex tasks","displayName":"Default (recommended)","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"default"},{"description":"For complex work and everyday tasks","displayName":"Opus 5.5","resolvedModel":"claude-opus-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"opus"},{"description":"For your toughest challenges","displayName":"Fable 5.2","resolvedModel":"claude-fable-5-2","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":false,"value":"fable"},{"description":"Most efficient for simpler tasks","displayName":"Sonnet 5.5","resolvedModel":"claude-sonnet-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"sonnet"},{"description":"Fastest for quick answers","displayName":"Haiku 5.5","resolvedModel":"claude-haiku-5-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"haiku"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5.1","overflow":true,"resolvedModel":"claude-fable-5-1","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5-1"},{"description":"Fastest for quick answers","displayName":"Haiku 4.5","overflow":true,"resolvedModel":"claude-haiku-4-5-20251001","supportsThinkingOff":true,"value":"claude-haiku-4-5-20251001"},{"description":"Efficient for routine tasks","displayName":"Sonnet 5","overflow":true,"resolvedModel":"claude-sonnet-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-sonnet-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 5","overflow":true,"resolvedModel":"claude-opus-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-5"},{"description":"Most capable for your hardest and longest-running tasks","displayName":"Fable 5","overflow":true,"resolvedModel":"claude-fable-5","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":false,"value":"claude-fable-5"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.8","overflow":true,"resolvedModel":"claude-opus-4-8","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsFastMode":true,"supportsThinkingOff":true,"value":"claude-opus-4-8"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.7","overflow":true,"resolvedModel":"claude-opus-4-7","supportedEffortLevels":["low","medium","high","xhigh","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-7"},{"description":"Best for everyday, complex tasks","displayName":"Opus 4.6","overflow":true,"resolvedModel":"claude-opus-4-6","supportedEffortLevels":["low","medium","high","max"],"supportsAdaptiveThinking":true,"supportsAutoMode":true,"supportsEffort":true,"supportsThinkingOff":true,"value":"claude-opus-4-6"},{"description":"Efficient for routine tasks","displayName":"Sonnet 4.6","overflow":true,"resolvedModel":"claude-sonnet-4-6","supportedEffortLevelsLine truncated
|
||||
{"from":"shim","msg":{"request":{"subtype":"get_settings"},"request_id":"req_2","type":"control_request"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_2","response":{"applied":{"advisor":null,"apiProvider":"firstParty","effort":"medium","launchEnvLeftOwnFilesInPlace":false,"model":"claude-haiku-5-5","outsideBlocksCountLaunchFoldersOnly":false,"outsideFileToolReadsBlocked":false,"outsideFileToolWritesBlocked":false,"ultracode":false,"ultracodeAvailable":true,"ultracodeRequested":false,"ultrathinkAvailable":false},"effective":{"model":null}},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Run the Bash command `sleep 5 && echo done`, then tell me its output in one line.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"session_id":"","type":"user","uuid":"750456ba-c54c-493b-bb61-40a9d825a457"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"b57b173d-a184-4e10-8ac6-46bd57c905b2","written_at":"2026-12-03T13:52:52.103Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"started","type":"command_lifecycle","uuid":"cd26e730-c57b-49c0-bfed-0ed2202ba6f5","written_at":"2026-12-03T13:52:52.104Z"}}
|
||||
{"from":"cli","msg":{"additional_directories":[],"analytics_disabled":false,"apiKeySource":"none","capabilities":["interrupt_receipt_v1","interrupt_cancel_queued_v1","interrupt_send_now_v1","interrupt_requeue_taken_v1","msg_lifecycle_v1","request_marker_lists_v1","ask_user_question_unanswered_v1","lifecycle_wakeup_source_v1","sdk_mcp_tools_list_changed","sdk_mcp_manifests","mcp_read_resource_v1","mcp_tool_ui_meta_v1","ui_surface_v1","mcp_call_result_not_for_model_v1","mcp_call_soft_error_result_v1","mcp_call_check_permissions_v1","voice_call_talk_line_v1","withdrawn_files_note_v2","withdrawn_tools_v1","ui_pane_widget_v1","reload_plugins_refuse_if_busy_v1","get_usage_detached_v1","silent_resend_files_v1","lifecycle_idle_v1","comment_images_v1"],"claude_code_version":"2.1.335","cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","fast_mode_state":"off","model":"claude-haiku-5-5","original_cwd":"/private/var/folders/vh/wtcmszn53mvbqcdfy6xrrg5w0000gn/T/.tmpbIsGYj","output_style":"default","per_turn_effort_active":true,"permissionMode":"default","product_feedback_disabled":false,"sandbox_enabled":false,"scratchpad_path":"/private/tmp/claude-501/s/443805216073/scratchpad","served_by_anthropic":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","startup_timing":{"entrypoint":"claude-vscode","flag_fetch_kick":"not_eligible","flag_fetch_kick_judged_at_ms":84,"hooks_init_origin_ms":{"official_plugin":79,"other_plugin":23,"user_settings":51},"hooks_init_source":"startup","hooks_init_without_silent_ms":{"any":79,"own":79},"phase_start_ms":{"first_message_handle_ms":299,"first_message_read_ms":0,"grove_check_ms":193,"headless_post_load_ms":273,"headless_prologue_ms":192,"hooks_init_ms":184,"init_emit_ms":361,"initial_messages_load_ms":196,"input_ready_ms":0,"mcp_client_module_load_ms":200,"mcp_config_wait_ms":175,"mcp_connect_ms":188,"mcp_prewait_ms":300,"model_catalog_decision_ms":170,"node_boot_ms":0,"permission_context_ms":90,"pre_action_client_data_url_ms":84,"pre_action_init_ms":45,"pre_action_managed_settings_ms":84,"pre_action_mdm_keychain_ms":44,"pre_action_migrations_ms":84,"pre_action_ms":44,"print_import_ms":189,"prompt_submit_hooks_ms":319,"qe_plugin_skills_load_ms":360,"qe_system_prompt_ms":302,"sdk_mcp_update_ms":299,"settings_load_ms":43,"setup_file_watcher_ms":119,"setup_hooks_snapshot_ms":119,"setup_import_ms":93,"setup_ms":96,"setup_release_notes_ms":120,"setup_uds_dir_ms":97,"setup_uds_listen_ms":116,"setup_uds_messaging_ms":95,"setup_uds_publish_ms":119,"skills_load_ms":96,"tools_commands_load_ms":132},"phases":{"first_message_handle_cpu_ms":0,"first_message_handle_loop_lag_ms":0,"first_message_handle_ms":0,"first_message_read_ms":299,"grove_check_ms":2,"headless_post_load_ms":1,"headless_prologue_ms":3,"hooks_init_ms":89,"init_emit_ms":1,"initial_messages_load_ms":77,"input_ready_ms":280,"mcp_client_module_load_ms":0,"mcp_config_load_ms":67,"mcp_config_wait_ms":2,"mcp_connect_ms":1,"mcp_prewait_ms":0,"model_catalog_decision_ms":2,"node_boot_ms":43,"permission_context_ms":3,"pre_action_client_data_url_ms":0,"pre_action_init_ms":39,"pre_action_managed_settings_ms":1,"pre_action_mdm_keychain_ms":1,"pre_action_migrations_ms":0,"pre_action_ms":45,"print_import_ms":3,"prompt_submit_hooks_ms":38,"qe_plugin_skills_load_ms":1,"qe_system_prompt_ms":5,"sdk_mcp_update_ms":0,"settings_load_ms":0,"setup_file_watcher_ms":0,"setup_hooks_snapshot_ms":0,"setup_import_ms":0,"setup_ms":32,"setup_release_notes_ms":9,"setup_uds_dir_ms":19,"setup_uds_listen_ms":3,"setup_uds_messaging_ms":24,"setup_uds_publish_ms":0,"skills_load_ms":69,"tools_commands_load_ms":38},"plugin_full_loads":0,"sdk_mcp_dial_runs":0,"sdk_mcp_servers_dialed":0,"time_origin_ms":1796305971804.1318,"user_context_builds":2,"warm_spare_claimed":false},"subtype":"init","terminal_slash_commands":["doctor","send-to-project","color","focus","reload-plugins"],"type":"system","ultrathink_available":false,"ultrathink_typed_raises":false,"user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"4614d51b-c114-4e3a-87c1-474dd3221ccb","view_mode":"default","written_at":"2026-12-03T13:52:52.166Z"}}
|
||||
{"from":"cli","msg":{"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","status":"requesting","subtype":"status","type":"system","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"1334ad42-52e2-4940-a881-df02701bbce2","written_at":"2026-12-03T13:52:52.168Z"}}
|
||||
{"from":"cli","msg":{"rate_limit_info":{"isUsingOverage":false,"overageDisabledReason":"out_of_credits","overageStatus":"rejected","rateLimitType":"five_hour","resetsAt":1796320200,"status":"allowed","unifiedWindows":{"five_hour":{"resetsAt":1796320200,"status":"allowed","utilization":0.22},"seven_day":{"resetsAt":1796889600,"status":"allowed","utilization":0.13}}},"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"rate_limit_event","uuid":"2d31cd09-90af-4542-9ab8-d6d35208343a","written_at":"2026-12-03T13:52:52.848Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"message":{"container":null,"content":[],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"type":"message_start"},"owed_rows":[],"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","thinking_display":"summarized","ttft_ms":870,"type":"stream_event","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"a07fd809-d225-4ae9-8a9a-1cfcd3ba452b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"content_block":{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{},"name":"Bash","type":"tool_use"},"index":0,"type":"content_block_start"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"d87d4b0c-0817-44f3-ba3d-506b145416eb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"7ebaa4fa-4334-42cd-87b9-86efb45b06fd"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"{\"command\": \"sleep 5","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"92f03d38-e933-444a-af9e-5d97a3bc17e1"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" && echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"156dfb71-8647-402b-81f1-d28209de7f6b"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\", \"description\": \"S","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f2218947-8767-4812-b6e9-5081d444668e"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"leep 5 seconds","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"645079d4-6f4f-403c-aef0-add49e320bdb"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":" then echo done","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"fc1582cb-4fe7-4747-b65a-5d57351c1749"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"delta":{"partial_json":"\"}","type":"input_json_delta"},"index":0,"type":"content_block_delta"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"8de2ab6a-1c5f-43be-99c5-accf562bded5"}}
|
||||
{"from":"cli","msg":{"message":{"container":null,"content":[{"caller":{"type":"direct"},"id":"toolu_013cYTr5SPmttma9grssUDvs","input":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"},"name":"Bash","type":"tool_use"}],"context_management":null,"diagnostics":null,"id":"msg_011CheuMVnw6EQjt4etKk278","input_transformations":[],"model":"claude-haiku-5-5","role":"assistant","stop_details":null,"stop_reason":null,"stop_sequence":null,"type":"message","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"inference_geo":"global","input_tokens":2,"output_tokens":16,"service_tier":"standard","speed":"standard"}},"parent_tool_use_id":null,"request_id":"req_011CheuMVa2bRTBYmxzHrdZU","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:53.341Z","type":"assistant","user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"543df181-f94c-4c59-8a54-6790d7c146fe","wire_tool_inputs":{"toolu_013cYTr5SPmttma9grssUDvs":{"command":"sleep 5 && echo done","description":"Sleep 5 seconds then echo done"}}}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"index":0,"type":"content_block_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"c95ced13-7ba7-4081-96dc-72e2e1ee9c67"}}
|
||||
{"from":"cli","msg":{"content":"A hook gave no usable answer, so it didn't check this action.","hook_no_verdict":{"hook_event":"PreToolUse","timed_out":false,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs"},"level":"warning","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","subtype":"informational","tag":"hook_no_verdict","type":"system","uuid":"c5ce69e8-b5c8-4e04-b6af-b1a4d9760a3d","written_at":"2026-12-03T13:52:53.356Z"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"context_management":{"applied_edits":[]},"delta":{"container":null,"stop_details":null,"stop_reason":"tool_use","stop_sequence":null},"type":"message_delta","usage":{"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0}}},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"f1c31fc2-e095-4a52-a92c-752feb90d83c"}}
|
||||
{"from":"cli","msg":{"api_message_id":"msg_011CheuMVnw6EQjt4etKk278","event":{"type":"message_stop"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","type":"stream_event","uuid":"5fd7d71c-5822-414a-b3e1-d11395fd7022"}}
|
||||
{"from":"shim","msg":{"message":{"content":[{"text":"Also end your answer with the word BANANA.","type":"text"}],"role":"user"},"origin":{"kind":"human"},"parent_tool_use_id":null,"priority":"next","session_id":"","type":"user","uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee"}}
|
||||
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"queued","type":"command_lifecycle","uuid":"d4038320-e65f-4937-b14c-8948234e08c4","written_at":"2026-12-03T13:52:55.103Z"}}
|
||||
{"from":"shim","msg":{"request":{"cancel_queued":true,"subtype":"interrupt"},"request_id":"req_3","type":"control_request"}}
|
||||
{"from":"cli","msg":{"command_uuid":"6e50c1f5-335e-4d89-a2ef-725e845b57ee","session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"24e8c7aa-31e8-455f-a456-12ee15e0e8f9","written_at":"2026-12-03T13:52:55.604Z"}}
|
||||
{"from":"cli","msg":{"response":{"request_id":"req_3","response":{"cancelled":["6e50c1f5-335e-4d89-a2ef-725e845b57ee"],"still_queued":[]},"subtype":"success"},"type":"control_response"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"content":"The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed. Correction to the text above: this call was stopped while running, not refused before it ran. It may have run in part or in full, and its changes may have been written. No permission prompt was involved. Work it started elsewhere (a remote command, a background process) may still be running, so check before starting the same work again. The instruction to stop and wait still stands.","is_error":true,"tool_use_id":"toolu_013cYTr5SPmttma9grssUDvs","type":"tool_result"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.608Z","tool_result_meta":[{"id":"toolu_013cYTr5SPmttma9grssUDvs","non_execution_kind":"user-rejected"}],"tool_use_result":"User rejected tool use","type":"user","uuid":"087df73f-b2fe-42d9-9de4-f3fab77aefe0"}}
|
||||
{"from":"cli","msg":{"message":{"content":[{"text":"[Request interrupted by user for tool use]","type":"text"}],"role":"user"},"parent_tool_use_id":null,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","timestamp":"2026-12-03T13:52:55.610Z","type":"user","uuid":"900c03e1-b662-4e5f-aaf6-384263031910"}}
|
||||
{"from":"cli","msg":{"begun_message_ids":["msg_011CheuMVnw6EQjt4etKk278"],"credential_expires_at":"2026-12-30T17:21:30.368Z","duration_api_ms":1721,"duration_ms":3506,"errors":["[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"],"fast_mode_state":"off","is_error":true,"modelUsage":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"model_usage_since_last_result":{"claude-haiku-5-5":{"cacheCreationEphemeral1hInputTokens":14749,"cacheCreationEphemeral5mInputTokens":0,"cacheCreationInputTokens":14749,"cacheReadInputTokens":28109,"canonicalModel":"claude-haiku-5-5","contextWindow":1000000,"costBasis":"list","costUSD":0.00340499,"inputTokens":1196,"maxOutputTokens":128000,"outputTokens":109,"provider":"firstParty","thinkingTokens":0,"webSearchRequests":0}},"num_turns":3,"origin":{"kind":"human"},"permission_denials":[],"queued_turn_count":0,"result_index":0,"safety_stops":0,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","stop_reason":"tool_use","subagent_stats":{"by_type":{},"completed":0,"failed":0,"killed":{"parent":0,"system":0,"user":0},"max_depth":0,"refused":{"budget":0,"concurrency_limit":0,"depth_limit":0},"requested":{"background":0,"foreground":0,"unset":0},"spawned":0,"spawned_by_subagents":0,"started_in_background":0},"subtype":"error_during_execution","terminal_reason":"aborted_tools","total_cost_usd":0.00340499,"type":"result","usage":{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"fallback_credit":null,"inference_geo":"global","input_tokens":2,"iterations":[{"cache_creation":{"ephemeral_1h_input_tokens":14749,"ephemeral_5m_input_tokens":0},"cache_creation_input_tokens":14749,"cache_read_input_tokens":28109,"input_tokens":2,"output_tokens":90,"type":"message"}],"output_tokens":90,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_fetch_requests":0,"web_search_requests":0},"service_tier":"standard","speed":"standard"},"user_message_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","user_message_uuids":["750456ba-c54c-493b-bb61-40a9d825a457"],"uuid":"5c62e1de-fdfc-44f7-ae20-cd70b87590e5","written_at":"2026-12-03T13:52:55.613Z"}}
|
||||
{"from":"cli","msg":{"command_uuid":"750456ba-c54c-493b-bb61-40a9d825a457","idle":true,"session_id":"f782ff38-9bfe-4bd7-a857-f3cb10b38bcf","state":"cancelled","type":"command_lifecycle","uuid":"53cf7918-cf6e-4c94-984c-8401081fa93e","written_at":"2026-12-03T13:52:55.615Z"}}
|
||||
@@ -63,7 +63,7 @@ pub(crate) fn stream_batched<T>(
|
||||
}
|
||||
}
|
||||
flush(&mut batch, on_batch);
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
Ok((lines.finish(cancel)?.success(), stderr_tail))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
|
||||
@@ -21,8 +21,9 @@ pub use single::{
|
||||
module_classpaths, single_file_classpath, single_file_target,
|
||||
};
|
||||
pub use structure::{
|
||||
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
|
||||
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
|
||||
StructureBuildContext, StructureJdk, StructureRoots, artifact_file, artifact_output, language_release,
|
||||
structure_build, structure_build_war, structure_compile_file_plan, structure_outputs, structure_plan,
|
||||
structure_war_plan, structure_web_artifacts,
|
||||
};
|
||||
pub use tsc_watch::{tsc_watch, tsc_watch_roots};
|
||||
pub use up_to_date::{menu_up_to_date, record_menu_build};
|
||||
@@ -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>> {
|
||||
@@ -570,6 +569,77 @@ fn dotnet_steps(dir: &Path, kind: BuildKind) -> IdeResult<Vec<BuildStep>> {
|
||||
Ok(vec![step])
|
||||
}
|
||||
|
||||
/// A `dotnet` command the .NET tool window runs on a solution or project file.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DotnetCommand {
|
||||
Build,
|
||||
Clean,
|
||||
Restore,
|
||||
}
|
||||
|
||||
/// `dotnet build` / `clean` / `restore` of one solution or project file, followed by `options`
|
||||
/// (`--configuration`, `--framework`, `-p:…`).
|
||||
pub fn dotnet_command_plan(file: &Path, command: DotnetCommand, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
let verb = match command {
|
||||
DotnetCommand::Build => "build",
|
||||
DotnetCommand::Clean => "clean",
|
||||
DotnetCommand::Restore => "restore",
|
||||
};
|
||||
dotnet_file_plan(file, verb, true, options)
|
||||
}
|
||||
|
||||
/// `dotnet publish` of one project file with the publish dialog's `options` (`-p:PublishProfile=…`,
|
||||
/// or `--configuration` / `--runtime` / `--output`).
|
||||
pub fn dotnet_publish_plan(file: &Path, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
dotnet_file_plan(file, "publish", false, options)
|
||||
}
|
||||
|
||||
fn dotnet_file_plan(file: &Path, verb: &str, solutions: bool, options: &[String]) -> IdeResult<BuildPlan> {
|
||||
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
let accepted = match ext.as_str() {
|
||||
"csproj" | "fsproj" | "vbproj" => true,
|
||||
"sln" | "slnx" => solutions,
|
||||
_ => false,
|
||||
};
|
||||
let (Some(dir), Some(name), true) = (file.parent(), file.file_name(), accepted) else {
|
||||
return Err(IdeError::invalid(if solutions {
|
||||
format!("dotnet {verb} needs a solution or a C#, F# or VB project")
|
||||
} else {
|
||||
format!("dotnet {verb} needs a C#, F# or VB project")
|
||||
}));
|
||||
};
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
|
||||
}
|
||||
let name = name.to_string_lossy();
|
||||
let mut step = BuildStep::new("dotnet", &[verb, &name, "-nologo", "-clp:NoSummary"], dir, Format::Msbuild);
|
||||
step.args.extend_from_slice(options);
|
||||
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
|
||||
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet {verb} {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
/// `dotnet format` of a solution or C# / VB project file; `verify` only reports what it would
|
||||
/// change and fails when there is anything.
|
||||
pub fn dotnet_format_plan(file: &Path, verify: bool) -> IdeResult<BuildPlan> {
|
||||
let ext = file.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
|
||||
let (Some(dir), Some(name), true) =
|
||||
(file.parent(), file.file_name(), matches!(ext.as_str(), "sln" | "slnx" | "csproj" | "vbproj"))
|
||||
else {
|
||||
return Err(IdeError::invalid("dotnet format needs a solution or a C# / VB project"));
|
||||
};
|
||||
if !file.is_file() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", file.display())));
|
||||
}
|
||||
let name = name.to_string_lossy();
|
||||
// Verbose output names the files it changed; verifying changes none.
|
||||
let options: &[&str] = if verify { &["--verify-no-changes"] } else { &["--verbosity", "normal"] };
|
||||
let mut step = BuildStep::new("dotnet", &["format", &name], dir, Format::Msbuild);
|
||||
step.args.extend(options.iter().map(|o| (*o).to_owned()));
|
||||
step.env.insert("MSBUILDTERMINALLOGGER".into(), "off".into());
|
||||
Ok(BuildPlan { system: BuildSystem::Dotnet, title: format!("dotnet format {name}"), steps: vec![step] })
|
||||
}
|
||||
|
||||
fn ts_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
let script = has_build_script(dir);
|
||||
if script && (kind == BuildKind::Artifacts || !dir.join("tsconfig.json").is_file()) {
|
||||
@@ -958,17 +1028,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.
|
||||
@@ -994,7 +1054,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.
|
||||
@@ -2061,6 +2121,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() {
|
||||
@@ -2230,4 +2318,142 @@ mod tests {
|
||||
assert_eq!(whole.steps[0].cwd, root);
|
||||
assert_eq!(whole.steps[0].args, ["build", "./..."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_format_runs_on_the_given_solution_or_project() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj", "App.fsproj", "A.cs"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
for name in ["App.sln", "App.slnx", "App.csproj", "App.vbproj"] {
|
||||
let plan = super::dotnet_format_plan(&dir.path().join(name), false).unwrap();
|
||||
assert_eq!(plan.steps[0].args, ["format", name, "--verbosity", "normal"]);
|
||||
assert_eq!(plan.steps[0].cwd, dir.path());
|
||||
let verify = super::dotnet_format_plan(&dir.path().join(name), true).unwrap();
|
||||
assert_eq!(verify.steps[0].args, ["format", name, "--verify-no-changes"]);
|
||||
}
|
||||
for name in ["App.fsproj", "A.cs", "Missing.sln"] {
|
||||
assert!(super::dotnet_format_plan(&dir.path().join(name), false).is_err(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The real `dotnet format` (`-- --ignored`): verifying reports and changes nothing, formatting rewrites.
|
||||
#[test]
|
||||
#[ignore = "needs the .NET SDK"]
|
||||
fn dotnet_format_reports_and_rewrites_with_the_real_sdk() {
|
||||
let found = std::process::Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success());
|
||||
if !found {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for args in [
|
||||
&["new", "console", "-n", "App", "-o", "App"][..],
|
||||
&["new", "sln", "-n", "Sln", "--format", "slnx"],
|
||||
&["new", "sln", "-n", "Classic", "--format", "sln"],
|
||||
&["sln", "Sln.slnx", "add", "App/App.csproj"],
|
||||
&["sln", "Classic.sln", "add", "App/App.csproj"],
|
||||
] {
|
||||
assert!(std::process::Command::new("dotnet").args(args).current_dir(&root).status().unwrap().success());
|
||||
}
|
||||
let source = root.join("App").join("中 A.cs");
|
||||
let messy = "class A{void M( ){var x=1;}}\n";
|
||||
for target in ["Sln.slnx", "Classic.sln", "App/App.csproj"] {
|
||||
std::fs::write(&source, messy).unwrap();
|
||||
let run = |verify| {
|
||||
let plan = super::dotnet_format_plan(&root.join(target), verify).unwrap();
|
||||
super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap()
|
||||
};
|
||||
let verified = run(true);
|
||||
assert!(!verified.success, "{target}");
|
||||
let message = verified.messages.iter().find(|m| m.code.as_deref() == Some("WHITESPACE")).unwrap();
|
||||
assert!(message.path.as_ref().unwrap().ends_with("中 A.cs"), "{message:?}");
|
||||
assert_eq!(std::fs::read_to_string(&source).unwrap(), messy);
|
||||
assert!(run(false).success, "{target}");
|
||||
assert_ne!(std::fs::read_to_string(&source).unwrap(), messy);
|
||||
assert!(run(true).success, "{target}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_publish_runs_on_one_project_file() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.csproj", "App.fsproj", "App.vbproj", "Sln.slnx"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
let options = ["-p:PublishProfile=My Folder".to_owned()];
|
||||
for name in ["App.csproj", "App.fsproj", "App.vbproj"] {
|
||||
let plan = super::dotnet_publish_plan(&dir.path().join(name), &options).unwrap();
|
||||
assert_eq!(
|
||||
plan.steps[0].args,
|
||||
["publish", name, "-nologo", "-clp:NoSummary", "-p:PublishProfile=My Folder"]
|
||||
);
|
||||
}
|
||||
for name in ["Sln.slnx", "Missing.csproj"] {
|
||||
assert!(super::dotnet_publish_plan(&dir.path().join(name), &[]).is_err(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dotnet_commands_run_on_one_solution_or_project_file() {
|
||||
use super::DotnetCommand;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for name in ["App.csproj", "Sln.sln", "Sln.slnx", "notes.txt"] {
|
||||
std::fs::write(dir.path().join(name), "").unwrap();
|
||||
}
|
||||
let options = ["--configuration".to_owned(), "Release".to_owned()];
|
||||
for (name, command, verb) in [
|
||||
("Sln.sln", DotnetCommand::Build, "build"),
|
||||
("Sln.slnx", DotnetCommand::Clean, "clean"),
|
||||
("App.csproj", DotnetCommand::Restore, "restore"),
|
||||
] {
|
||||
let plan = super::dotnet_command_plan(&dir.path().join(name), command, &options).unwrap();
|
||||
assert_eq!(plan.title, format!("dotnet {verb} {name}"));
|
||||
assert_eq!(plan.steps[0].args, [verb, name, "-nologo", "-clp:NoSummary", "--configuration", "Release"]);
|
||||
assert_eq!(plan.steps[0].cwd, dir.path());
|
||||
}
|
||||
for name in ["notes.txt", "Missing.sln"] {
|
||||
assert!(super::dotnet_command_plan(&dir.path().join(name), DotnetCommand::Build, &[]).is_err(), "{name}");
|
||||
}
|
||||
assert!(super::dotnet_publish_plan(&dir.path().join("Sln.sln"), &[]).is_err(), "publish takes a project");
|
||||
}
|
||||
|
||||
/// The real `dotnet publish` (`-- --ignored`): publishes, reports compile errors, and stops
|
||||
/// when cancelled.
|
||||
#[test]
|
||||
#[ignore = "needs the .NET SDK"]
|
||||
fn dotnet_publish_publishes_fails_and_cancels_with_the_real_sdk() {
|
||||
let found = std::process::Command::new("dotnet").arg("--version").output().is_ok_and(|o| o.status.success());
|
||||
if !found {
|
||||
return;
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let new = ["new", "console", "-n", "App", "-o", "App"];
|
||||
assert!(std::process::Command::new("dotnet").args(new).current_dir(&root).status().unwrap().success());
|
||||
let project = root.join("App").join("App.csproj");
|
||||
let options = ["--output".to_owned(), "out dir".to_owned()];
|
||||
let plan = super::dotnet_publish_plan(&project, &options).unwrap();
|
||||
|
||||
let published = super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert!(published.success);
|
||||
let output = root.join("App").join("out dir").join("App.dll");
|
||||
assert!(output.is_file());
|
||||
|
||||
std::fs::remove_dir_all(root.join("App").join("out dir")).unwrap();
|
||||
let token = CancellationToken::new();
|
||||
let cancel = token.clone();
|
||||
let result = super::run(&root, &plan, &token, &|e| {
|
||||
if matches!(e, BuildEvent::Output { .. }) {
|
||||
cancel.cancel();
|
||||
}
|
||||
});
|
||||
assert!(result.is_err(), "a cancelled publish is not a result");
|
||||
assert!(!output.exists());
|
||||
|
||||
std::fs::write(root.join("App").join("Program.cs"), "nope\n").unwrap();
|
||||
let failed = super::run(&root, &plan, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
assert!(!failed.success);
|
||||
assert!(failed.messages.iter().any(|m| m.path.as_ref().is_some_and(|p| p.ends_with("Program.cs"))));
|
||||
}
|
||||
}
|
||||
@@ -72,15 +72,19 @@ fn affected_projects(reactor: &[&maven::MavenProject], changed: &HashSet<String>
|
||||
/// `-pl` entries of the affected modules, relative to the reactor root the step
|
||||
/// runs in, sorted so the command line does not depend on the model's project
|
||||
/// order (Maven reorders the selection into its own reactor order anyway).
|
||||
fn selection(reactor: &[&maven::MavenProject], top_dir: &str, affected: &HashSet<String>) -> String {
|
||||
fn selection(
|
||||
root: &Path,
|
||||
top: &maven::MavenProject,
|
||||
reactor: &[&maven::MavenProject],
|
||||
affected: &HashSet<String>,
|
||||
) -> String {
|
||||
let mut entries: Vec<String> = reactor
|
||||
.iter()
|
||||
.filter(|p| affected.contains(&p.dir))
|
||||
.map(|p| {
|
||||
Path::new(&p.dir).strip_prefix(top_dir).unwrap_or(Path::new(&p.dir)).to_string_lossy().replace('\\', "/")
|
||||
})
|
||||
.filter_map(|p| maven::module_selector(root, top, p))
|
||||
.collect();
|
||||
entries.sort();
|
||||
entries.dedup();
|
||||
entries.join(",")
|
||||
}
|
||||
|
||||
@@ -130,8 +134,12 @@ pub(super) fn narrowed_maven_steps(
|
||||
if affected.len() >= reactor.len() || affected.contains(&top.dir) {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
let pl = selection(&reactor, &top.dir, &affected);
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
let pl = selection(root, top, &reactor, &affected);
|
||||
if pl.is_empty() {
|
||||
steps.push(step(top, &[]));
|
||||
} else {
|
||||
steps.push(step(top, &["-pl".into(), pl, "-am".into()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(steps))
|
||||
@@ -405,4 +413,36 @@ mod tests {
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "solo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sibling_reactor_narrows_with_relative_module_selectors() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
write(
|
||||
root,
|
||||
"parent/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><packaging>pom</packaging><modules><module>../common</module><module>../app</module></modules></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"common/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>common</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"app/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>parent</artifactId><version>1</version><relativePath>../parent/pom.xml</relativePath></parent><artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>common</artifactId><version>1</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(root, "common/src/main/java/t/C.java", "package t; public class C {}");
|
||||
write(root, "app/src/main/java/t/A.java", "package t; public class A {}");
|
||||
let model = BuildModel { maven: Some(maven::load(root)), ..Default::default() };
|
||||
let cache = root.join("cache");
|
||||
record_module_build(&cache, root, &model, &CancellationToken::new());
|
||||
write(root, "common/src/main/java/t/C.java", "package t; public class C { int x; }");
|
||||
let steps = steps(&cache, root, &model).unwrap();
|
||||
assert_eq!(steps.len(), 1);
|
||||
assert_eq!(steps[0].cwd, subdir(root, "parent"));
|
||||
assert_eq!(pl_arg(&steps[0]), "../app,../common");
|
||||
assert!(steps[0].args.contains(&"-am".into()));
|
||||
}
|
||||
}
|
||||
@@ -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 })
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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)?;
|
||||
}
|
||||
}
|
||||
@@ -734,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);
|
||||
@@ -762,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
|
||||
@@ -1133,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(&[
|
||||
@@ -311,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(&[
|
||||
@@ -487,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",
|
||||
@@ -502,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(&[
|
||||
@@ -583,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,
|
||||
};
|
||||
|
||||
@@ -43,6 +43,10 @@ pub struct MavenModel {
|
||||
/// Build files changed since that sync.
|
||||
pub stale: bool,
|
||||
pub sync_error: Option<String>,
|
||||
/// The `<activation><jdk>` values of the projects' own POMs that the JDK matches.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub(crate) jdk_activations: std::collections::BTreeSet<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -92,6 +96,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 {
|
||||
@@ -1340,6 +1438,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 {
|
||||
@@ -1510,6 +1624,8 @@ pub fn load_with_linked_jdk(
|
||||
for p in resolver.active(&pom.profiles) {
|
||||
module_names.extend(p.modules.iter().cloned());
|
||||
}
|
||||
let jdks = pom.profiles.iter().filter_map(|p| p.activation_jdk.as_ref());
|
||||
model.jdk_activations.extend(jdks.filter(|spec| jdk_matches(spec, jdk_version)).cloned());
|
||||
let mut modules: Vec<PathBuf> = Vec::new();
|
||||
for m in module_names {
|
||||
let mut mp = crate::gradle::normalize(&dir.join(i(&m)));
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::process::{self, Output};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use specta::Type;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock, Mutex};
|
||||
use std::time::SystemTime;
|
||||
@@ -32,6 +32,8 @@ pub struct SyncOptions {
|
||||
pub profiles: Vec<String>,
|
||||
/// Extra environment (`JAVA_HOME`).
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Major version of the JDK Maven runs on, the same as the model is loaded with.
|
||||
pub jdk_version: Option<u32>,
|
||||
/// Maven launcher replacing the project's `mvnw` / `mvn` (Settings › Maven home).
|
||||
pub maven_command: Option<String>,
|
||||
/// Resolved Gradle launcher from Settings.
|
||||
@@ -62,6 +64,9 @@ struct MavenCache {
|
||||
/// The trees list omitted occurrences (`-Dverbose`); older caches are reloaded.
|
||||
#[serde(default)]
|
||||
verbose: bool,
|
||||
/// [`MavenModel::jdk_activations`] of the sync; `None` in caches from before they were recorded.
|
||||
#[serde(default)]
|
||||
jdk_activations: Option<BTreeSet<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
@@ -233,7 +238,9 @@ pub fn apply_maven_cache(root: &Path, cache_dir: &Path, model: &mut MavenModel)
|
||||
}
|
||||
model.synced_at = Some(cache.at_ms);
|
||||
model.sync_error = cache.error;
|
||||
let changed = cache.hash != hash_files(&maven::build_files(root, model));
|
||||
// Another JDK can switch profiles of the same build files.
|
||||
let changed = cache.hash != hash_files(&maven::build_files(root, model))
|
||||
|| cache.jdk_activations.is_some_and(|jdks| jdks != model.jdk_activations);
|
||||
model.stale = !cache.verbose || changed;
|
||||
// A cache older than the current build files: its effective-POM plugins and
|
||||
// resolved dependencies would hide what the POMs declare now (a just added
|
||||
@@ -368,10 +375,11 @@ pub fn sync_maven(
|
||||
cancel: &CancellationToken,
|
||||
progress: &dyn Fn(SyncProgress),
|
||||
) -> IdeResult<()> {
|
||||
let mut model = maven::load_with_linked(
|
||||
let mut model = maven::load_with_linked_jdk(
|
||||
root,
|
||||
maven::default_local_repo(),
|
||||
&options.maven_settings.profiles(&options.profiles),
|
||||
options.jdk_version,
|
||||
&options.maven_settings.linked_projects,
|
||||
);
|
||||
maven::UnlinkedProjects::from_model(&model, &options.maven_settings).filter(&mut model);
|
||||
@@ -380,6 +388,7 @@ pub fn sync_maven(
|
||||
version: MAVEN_CACHE_VERSION,
|
||||
hash: hash_files(&maven::build_files(root, &model)),
|
||||
verbose: true,
|
||||
jdk_activations: Some(model.jdk_activations.clone()),
|
||||
..MavenCache::default()
|
||||
};
|
||||
// Where the build resolves its jars, and therefore where the plugin goals are read from.
|
||||
@@ -683,6 +692,7 @@ mod tests {
|
||||
at_ms: 5.0,
|
||||
error: None,
|
||||
verbose: true,
|
||||
jdk_activations: None,
|
||||
projects: vec![CachedMavenProject {
|
||||
key: "g:a".into(),
|
||||
plugins: vec![maven::plugin(
|
||||
@@ -733,6 +743,7 @@ mod tests {
|
||||
at_ms: 5.0,
|
||||
error: None,
|
||||
verbose: true,
|
||||
jdk_activations: None,
|
||||
projects: vec![CachedMavenProject {
|
||||
key: "g:a".into(),
|
||||
plugins: vec![maven::plugin(
|
||||
@@ -1055,6 +1066,95 @@ mod tests {
|
||||
assert_eq!(std::fs::metadata(&mvnw).unwrap().permissions().mode() & 0o777, 0o644);
|
||||
}
|
||||
|
||||
/// `root` with module `core`, and what `profile` adds when the JDK activates it: the module
|
||||
/// `modern` or only a property. Synced with `jdk` by a launcher printing `core`'s tree.
|
||||
#[cfg(unix)]
|
||||
fn synced_with_a_jdk_profile(base: &Path, profile: &str, jdk: Option<u32>) -> (PathBuf, PathBuf) {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let (root, cache) = (base.join("p"), base.join("cache"));
|
||||
let project = "<project><groupId>g</groupId><version>1</version>";
|
||||
for module in ["core", "modern"] {
|
||||
std::fs::create_dir_all(root.join(module)).unwrap();
|
||||
let pom = format!("{project}<artifactId>{module}</artifactId></project>");
|
||||
std::fs::write(root.join(module).join("pom.xml"), pom).unwrap();
|
||||
}
|
||||
let pom = format!(
|
||||
"{project}<artifactId>root</artifactId><packaging>pom</packaging><modules><module>core</module></modules>\
|
||||
<profiles><profile><id>modern</id><activation><jdk>[11,)</jdk></activation>{profile}</profile></profiles>\
|
||||
</project>"
|
||||
);
|
||||
std::fs::write(root.join("pom.xml"), pom).unwrap();
|
||||
let launcher = base.join("mvn");
|
||||
let tree = "[INFO] --- dependency:3.8.1:tree (default-cli) @ core ---\\n[INFO] g:core:jar:1\\n\
|
||||
[INFO] \\\\- g:lib:jar:1:compile\\n[INFO] \\\\- g:transitive:jar:1:compile\\n";
|
||||
std::fs::write(&launcher, format!("#!/bin/sh\nprintf '{tree}'\n")).unwrap();
|
||||
std::fs::set_permissions(&launcher, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let options = SyncOptions {
|
||||
maven_command: Some(launcher.to_string_lossy().into_owned()),
|
||||
jdk_version: jdk,
|
||||
..Default::default()
|
||||
};
|
||||
sync_maven(&root, &cache, &options, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
(root, cache)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn loaded_with_jdk((root, cache): &(PathBuf, PathBuf), jdk: Option<u32>) -> MavenModel {
|
||||
crate::load_linked_with_jdk(root, cache, None, &Default::default(), &Default::default(), jdk).maven.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
const MODULE: &str = "<modules><module>modern</module></modules>";
|
||||
#[cfg(unix)]
|
||||
const PROPERTY: &str = "<properties><x>1</x></properties>";
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_synced_model_with_a_jdk_profile_is_current() {
|
||||
for (profile, jdk, modules) in
|
||||
[(MODULE, Some(17), 3), (MODULE, Some(8), 2), (MODULE, None, 2), (PROPERTY, Some(17), 2)]
|
||||
{
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, jdk), jdk);
|
||||
assert_eq!(model.projects.len(), modules, "{profile} {jdk:?}");
|
||||
assert!(!model.stale, "{profile} {jdk:?}");
|
||||
let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap();
|
||||
assert_eq!(core.dependencies[0].children[0].artifact_id, "transitive", "{profile} {jdk:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_jdk_change_is_stale_when_it_switches_a_profile() {
|
||||
for profile in [MODULE, PROPERTY] {
|
||||
for (synced, loaded, stale) in [
|
||||
(Some(17), Some(21), false),
|
||||
(Some(17), Some(8), true),
|
||||
(Some(8), Some(17), true),
|
||||
(Some(17), None, true),
|
||||
(None, Some(17), true),
|
||||
(None, Some(8), false),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let model = loaded_with_jdk(&synced_with_a_jdk_profile(tmp.path(), profile, synced), loaded);
|
||||
assert_eq!(model.stale, stale, "{profile} {synced:?} {loaded:?}");
|
||||
let core = model.projects.iter().find(|p| p.artifact_id == "core").unwrap();
|
||||
assert_eq!(core.dependencies.is_empty(), stale, "{profile} {synced:?} {loaded:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_sync_from_before_jdk_profiles_were_recorded_stays_current() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let project = synced_with_a_jdk_profile(tmp.path(), PROPERTY, Some(17));
|
||||
let mut json: serde_json::Value = read_cache(&project.1, MAVEN_CACHE).unwrap();
|
||||
assert!(json.as_object_mut().unwrap().remove("jdk_activations").is_some());
|
||||
write_cache(&project.1, MAVEN_CACHE, &json).unwrap();
|
||||
assert!(!loaded_with_jdk(&project, Some(17)).stale);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn maven_sync_runs_the_daemon_command_serially() {
|
||||
|
||||
@@ -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"
|
||||
@@ -27,4 +27,4 @@ libc = "0.2"
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
dirs.workspace = true
|
||||
tracing.workspace = true
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61", features = ["Wdk_System_SystemServices", "Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Environment", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_LibraryLoader", "Win32_System_Registry", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }
|
||||
@@ -175,7 +175,7 @@ impl CliTool {
|
||||
Poll::Finished => break,
|
||||
}
|
||||
}
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
Ok((lines.finish(cancel)?.success(), stderr_tail))
|
||||
}
|
||||
|
||||
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
|
||||
@@ -301,9 +301,9 @@ impl Lines {
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
|
||||
/// killing it, when `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
|
||||
/// Waits for the child to exit and returns how it exited. Fails, after killing it, when
|
||||
/// `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<std::process::ExitStatus> {
|
||||
let status = loop {
|
||||
if let Some(status) = self.child.try_wait()? {
|
||||
break status;
|
||||
@@ -314,6 +314,6 @@ impl Lines {
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(status.success())
|
||||
Ok(status)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,14 @@ use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The execution target recorded with an MCP agent run.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum McpAgentRunTarget {
|
||||
Host,
|
||||
Container { id: String },
|
||||
}
|
||||
|
||||
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
|
||||
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
|
||||
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
|
||||
@@ -42,6 +50,7 @@ pub enum McpUiRequest {
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
target: McpAgentRunTarget,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
@@ -108,6 +117,14 @@ pub enum IdeEvent {
|
||||
host: String,
|
||||
#[serde(default)]
|
||||
taken_over: bool,
|
||||
/// Plain-language explanation when a dev container exited from the OOM killer (`OOMKilled` / exit 137).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
oom_message: Option<String>,
|
||||
/// Local configuration file (`devcontainer.json` or Compose file) that sets the container's limit.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
oom_config_path: Option<String>,
|
||||
},
|
||||
ProjectTrustChanged {
|
||||
root: crate::IpcPath,
|
||||
@@ -311,6 +328,18 @@ pub enum IdeEvent {
|
||||
AskpassDone {
|
||||
id: u64,
|
||||
},
|
||||
/// An external `/api/file` request asks the target project window to confirm opening a file;
|
||||
/// answered with `web_file_api_confirm`.
|
||||
FileApiConfirm {
|
||||
id: u64,
|
||||
source: String,
|
||||
path: crate::IpcPath,
|
||||
line: Option<u32>,
|
||||
},
|
||||
/// File-open confirmation prompt `id` was answered or cancelled.
|
||||
FileApiConfirmDone {
|
||||
id: u64,
|
||||
},
|
||||
/// The kernel of an open notebook changed state (`starting`, `idle`, `busy`,
|
||||
/// `dead`); `message` says why it failed to start or died.
|
||||
NotebookKernel {
|
||||
@@ -430,6 +459,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)]
|
||||
|
||||
@@ -285,6 +285,190 @@ fn taskkill_tree_of(pid: u32) {
|
||||
windows_tree::wait_all(&started, TREE_EXIT_WAIT);
|
||||
}
|
||||
|
||||
/// The registry environment behind [`registry_env_changes`], read with
|
||||
/// `CreateEnvironmentBlock` as Explorer does for the programs it starts after a
|
||||
/// `WM_SETTINGCHANGE`. It is read again only after `HKCU\Environment` or the machine's
|
||||
/// `Environment` key reports a change, so spawning a child costs two event polls.
|
||||
#[cfg(windows)]
|
||||
mod registry_env {
|
||||
use std::ffi::OsString;
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
|
||||
use std::sync::Mutex;
|
||||
use windows_sys::Win32::Foundation::{ERROR_SUCCESS, HANDLE, WAIT_OBJECT_0};
|
||||
use windows_sys::Win32::Security::{TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_QUERY};
|
||||
use windows_sys::Win32::System::Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock};
|
||||
use windows_sys::Win32::System::Registry::{
|
||||
HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_NOTIFY, REG_NOTIFY_CHANGE_LAST_SET, REG_NOTIFY_CHANGE_NAME,
|
||||
REG_NOTIFY_THREAD_AGNOSTIC, RegCloseKey, RegNotifyChangeKeyValue, RegOpenKeyExW,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
CreateEventW, GetCurrentProcess, OpenProcessToken, ResetEvent, WaitForSingleObject,
|
||||
};
|
||||
|
||||
type Vars = Vec<(OsString, OsString)>;
|
||||
|
||||
/// An open registry key and the event its next change signals.
|
||||
struct Watch {
|
||||
key: HKEY,
|
||||
event: OwnedHandle,
|
||||
}
|
||||
|
||||
// SAFETY: a registry key handle is a kernel handle, usable from any thread.
|
||||
unsafe impl Send for Watch {}
|
||||
|
||||
impl Watch {
|
||||
fn new(root: HKEY, path: &str) -> Option<Self> {
|
||||
let path: Vec<u16> = path.encode_utf16().chain(Some(0)).collect();
|
||||
let mut key: HKEY = std::ptr::null_mut();
|
||||
// SAFETY: `path` is NUL-terminated; `key` receives a handle the watch owns.
|
||||
if unsafe { RegOpenKeyExW(root, path.as_ptr(), 0, KEY_NOTIFY, &mut key) } != ERROR_SUCCESS {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: plain call; a non-null result is a manual-reset event handle owned here.
|
||||
let event = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) };
|
||||
if event.is_null() {
|
||||
// SAFETY: `key` was opened above and is closed once.
|
||||
unsafe { RegCloseKey(key) };
|
||||
return None;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
let watch = Watch { key, event: unsafe { OwnedHandle::from_raw_handle(event) } };
|
||||
watch.arm().then_some(watch)
|
||||
}
|
||||
|
||||
/// Asks to be told of the key's next change; `false` when it cannot be watched.
|
||||
fn arm(&self) -> bool {
|
||||
let filter = REG_NOTIFY_CHANGE_NAME | REG_NOTIFY_CHANGE_LAST_SET | REG_NOTIFY_THREAD_AGNOSTIC;
|
||||
// SAFETY: both handles are owned by the watch and open.
|
||||
let status = unsafe { RegNotifyChangeKeyValue(self.key, 0, filter, self.event.as_raw_handle(), 1) };
|
||||
status == ERROR_SUCCESS
|
||||
}
|
||||
|
||||
/// Whether the key changed since the last call; re-arms the watch when it did.
|
||||
fn changed(&self) -> bool {
|
||||
let event: HANDLE = self.event.as_raw_handle();
|
||||
// SAFETY: an event handle owned by the watch.
|
||||
if unsafe { WaitForSingleObject(event, 0) } != WAIT_OBJECT_0 {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
unsafe { ResetEvent(event) };
|
||||
self.arm();
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Watch {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the key was opened by `Watch::new` and is closed once.
|
||||
unsafe { RegCloseKey(self.key) };
|
||||
}
|
||||
}
|
||||
|
||||
struct State {
|
||||
startup: Vars,
|
||||
current: Vars,
|
||||
watches: Vec<Watch>,
|
||||
}
|
||||
|
||||
static STATE: Mutex<Option<State>> = Mutex::new(None);
|
||||
|
||||
pub(super) fn record() {
|
||||
let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if state.is_none() {
|
||||
*state = Some(start());
|
||||
}
|
||||
}
|
||||
|
||||
fn start() -> State {
|
||||
// Watch before reading: a change in between is then read again, not missed.
|
||||
let watches = [
|
||||
(HKEY_CURRENT_USER, "Environment"),
|
||||
(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(root, path)| Watch::new(root, path))
|
||||
.collect();
|
||||
let startup = read().unwrap_or_default();
|
||||
State { current: startup.clone(), startup, watches }
|
||||
}
|
||||
|
||||
pub(super) fn changes() -> Vec<(OsString, Option<OsString>)> {
|
||||
let mut guard = STATE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let state = guard.get_or_insert_with(start);
|
||||
// Poll every watch: each one that fired must be re-armed.
|
||||
let changed = state.watches.iter().fold(false, |any, watch| watch.changed() | any);
|
||||
if changed && let Some(fresh) = read() {
|
||||
state.current = fresh;
|
||||
}
|
||||
if state.current == state.startup {
|
||||
return Vec::new();
|
||||
}
|
||||
super::registry_diff(&|k| std::env::var_os(k), &state.startup, &state.current)
|
||||
}
|
||||
|
||||
/// The environment a program Explorer starts now would get; `None` when it cannot be read.
|
||||
pub(super) fn read() -> Option<Vars> {
|
||||
let mut token: HANDLE = std::ptr::null_mut();
|
||||
let access = TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE;
|
||||
// SAFETY: this process's pseudo-handle; `token` receives a handle owned here.
|
||||
if unsafe { OpenProcessToken(GetCurrentProcess(), access, &mut token) } == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: as above.
|
||||
let token = unsafe { OwnedHandle::from_raw_handle(token) };
|
||||
let mut block: *mut core::ffi::c_void = std::ptr::null_mut();
|
||||
// SAFETY: an open token; `block` receives a block destroyed below.
|
||||
if unsafe { CreateEnvironmentBlock(&mut block, token.as_raw_handle(), 0) } == 0 || block.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the block holds `NAME=VALUE` entries, each NUL-terminated, then a final NUL.
|
||||
let vars = unsafe { parse_block(block as *const u16) };
|
||||
// SAFETY: the block was created above and is destroyed once.
|
||||
unsafe { DestroyEnvironmentBlock(block) };
|
||||
Some(vars)
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `block` points to UTF-16 entries, each NUL-terminated, ended by an empty one.
|
||||
unsafe fn parse_block(block: *const u16) -> Vars {
|
||||
let mut vars = Vars::new();
|
||||
let mut at = block;
|
||||
loop {
|
||||
let mut len = 0;
|
||||
// SAFETY: the caller guarantees the terminating NULs.
|
||||
while unsafe { *at.add(len) } != 0 {
|
||||
len += 1;
|
||||
}
|
||||
if len == 0 {
|
||||
return vars;
|
||||
}
|
||||
// SAFETY: the `len` units before the NUL were just read.
|
||||
let entry = unsafe { std::slice::from_raw_parts(at, len) };
|
||||
// Per-drive directories (`=C:=C:\dir`) have an empty name: skip them.
|
||||
if let Some(eq) = entry.iter().skip(1).position(|&c| c == u16::from(b'=')) {
|
||||
let eq = eq + 1;
|
||||
vars.push((OsString::from_wide(&entry[..eq]), OsString::from_wide(&entry[eq + 1..])));
|
||||
}
|
||||
// SAFETY: the entry's NUL is followed by the next entry or the final NUL.
|
||||
at = unsafe { at.add(len + 1) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn reads_this_users_environment() {
|
||||
let vars = super::read().expect("environment block");
|
||||
let get = |k: &str| vars.iter().find(|(n, _)| n.eq_ignore_ascii_case(k)).map(|(_, v)| v.clone());
|
||||
assert!(get("SystemRoot").is_some_and(|v| !v.is_empty()), "{vars:?}");
|
||||
assert!(get("Path").is_some_and(|v| !v.is_empty()), "{vars:?}");
|
||||
assert!(vars.iter().all(|(k, _)| !k.is_empty() && !k.to_string_lossy().contains('=')));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows_tree {
|
||||
use std::collections::HashSet;
|
||||
@@ -676,7 +860,7 @@ pub fn host_var_os_in(dir: &Path, key: impl AsRef<OsStr>) -> Option<OsString> {
|
||||
}
|
||||
|
||||
fn host_var_os_for(dir: Option<&Path>, key: &OsStr) -> Option<OsString> {
|
||||
match child_env_changes(dir).into_iter().find(|(k, _)| k == key) {
|
||||
match child_env_changes(dir).into_iter().find(|(k, _)| same_key(k, key)) {
|
||||
Some((_, fixed)) => fixed,
|
||||
None => std::env::var_os(key).or_else(|| shell_env_for(dir).find(|(k, _)| k == key).map(|(_, v)| v)),
|
||||
}
|
||||
@@ -688,7 +872,7 @@ fn apply_changes(
|
||||
changes: &[(OsString, Option<OsString>)],
|
||||
) -> Vec<(OsString, OsString)> {
|
||||
for (key, value) in changes {
|
||||
let at = vars.iter().position(|(k, _)| k == key);
|
||||
let at = vars.iter().position(|(k, _)| same_key(k, key));
|
||||
match (at, value) {
|
||||
(Some(i), Some(v)) => vars[i].1 = v.clone(),
|
||||
(Some(i), None) => {
|
||||
@@ -701,25 +885,126 @@ fn apply_changes(
|
||||
vars
|
||||
}
|
||||
|
||||
/// The AppImage fixes, the overlay, the manual proxy's, then those of the project holding
|
||||
/// `dir` (a later one wins); one entry per name.
|
||||
/// The registry's changes (Windows), the AppImage fixes, the overlay, the manual proxy's,
|
||||
/// then those of the project holding `dir` (a later one wins); one entry per name.
|
||||
fn child_env_changes(dir: Option<&Path>) -> Vec<(OsString, Option<OsString>)> {
|
||||
let mut changes = appimage_fixes();
|
||||
let mut changes = registry_env_changes();
|
||||
changes.extend(appimage_fixes());
|
||||
let overlay = env_overlay();
|
||||
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| o == k));
|
||||
changes.retain(|(k, _)| !overlay.iter().any(|(o, _)| same_key(o, k)));
|
||||
changes.extend(overlay.iter().cloned());
|
||||
// A manual HTTP proxy reaches tools that read `HTTP_PROXY` (language servers, git, curl).
|
||||
let proxy = crate::proxy_settings::proxy().child_env();
|
||||
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| p == k));
|
||||
changes.retain(|(k, _)| !proxy.iter().any(|(p, _)| same_key(p, k)));
|
||||
changes.extend(proxy);
|
||||
if let Some(dir) = dir {
|
||||
let project = crate::project_env::for_dir(dir);
|
||||
changes.retain(|(k, _)| !project.iter().any(|(p, _)| p == k));
|
||||
changes.retain(|(k, _)| !project.iter().any(|(p, _)| same_key(p, k)));
|
||||
changes.extend(project.iter().cloned());
|
||||
}
|
||||
changes
|
||||
}
|
||||
|
||||
/// Whether two variable names are the same variable: Windows ignores case (`Path` is `PATH`).
|
||||
fn same_key(a: &OsStr, b: &OsStr) -> bool {
|
||||
if cfg!(windows) { a.eq_ignore_ascii_case(b) } else { a == b }
|
||||
}
|
||||
|
||||
/// What changed in the environment Windows gives new programs (the registry's machine and
|
||||
/// user variables) since this process started. A program installed meanwhile (Node.js, a
|
||||
/// JDK) adds its folder to `Path`; a child of the IDE must find it, as a program started
|
||||
/// from Explorer would, without restarting the IDE. Empty elsewhere.
|
||||
fn registry_env_changes() -> Vec<(OsString, Option<OsString>)> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
registry_env::changes()
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Remembers the registry environment this process starts with, so that later changes reach
|
||||
/// new children. Call at startup (otherwise the first child spawn records it). Does nothing
|
||||
/// outside Windows.
|
||||
pub fn record_startup_registry_env() {
|
||||
#[cfg(windows)]
|
||||
registry_env::record();
|
||||
}
|
||||
|
||||
/// The entry of a `PATH`-like list as compared: without a trailing separator, and on
|
||||
/// Windows without case.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn path_entry_key(dir: &Path) -> String {
|
||||
let text = dir.to_string_lossy();
|
||||
let text = text.trim_end_matches(['\\', '/']);
|
||||
if cfg!(windows) { text.to_ascii_lowercase() } else { text.to_owned() }
|
||||
}
|
||||
|
||||
/// `old` → `fresh` applied to this process's `PATH`-like list `process`: entries that
|
||||
/// `fresh` dropped are removed and those it added are appended, so what the IDE put on
|
||||
/// `PATH` itself (managed tools, the user's `Path`) stays where it is.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn rebase_path_list(process: &OsStr, old: &OsStr, fresh: &OsStr) -> OsString {
|
||||
let entries = |list: &OsStr| -> Vec<std::path::PathBuf> {
|
||||
std::env::split_paths(list).filter(|d| !d.as_os_str().is_empty()).collect()
|
||||
};
|
||||
let old: Vec<String> = entries(old).iter().map(|d| path_entry_key(d)).collect();
|
||||
let fresh = entries(fresh);
|
||||
let fresh_keys: Vec<String> = fresh.iter().map(|d| path_entry_key(d)).collect();
|
||||
let mut out: Vec<std::path::PathBuf> = entries(process)
|
||||
.into_iter()
|
||||
.filter(|d| {
|
||||
let key = path_entry_key(d);
|
||||
!old.contains(&key) || fresh_keys.contains(&key)
|
||||
})
|
||||
.collect();
|
||||
for (dir, key) in fresh.into_iter().zip(fresh_keys) {
|
||||
if !old.contains(&key) && !out.iter().any(|d| path_entry_key(d) == key) {
|
||||
out.push(dir);
|
||||
}
|
||||
}
|
||||
std::env::join_paths(out).unwrap_or_else(|_| process.to_owned())
|
||||
}
|
||||
|
||||
/// The changes that bring this process's environment (`process`) from the registry
|
||||
/// environment it started with (`old`) to the current one (`fresh`): new and changed
|
||||
/// variables; removed ones while this process still has the value it started with; and
|
||||
/// `PATH` rebased ([`rebase_path_list`]).
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn registry_diff(
|
||||
process: &dyn Fn(&OsStr) -> Option<OsString>,
|
||||
old: &[(OsString, OsString)],
|
||||
fresh: &[(OsString, OsString)],
|
||||
) -> Vec<(OsString, Option<OsString>)> {
|
||||
let get =
|
||||
|vars: &[(OsString, OsString)], k: &OsStr| vars.iter().find(|(n, _)| same_key(n, k)).map(|(_, v)| v.clone());
|
||||
let mut out = Vec::new();
|
||||
for (key, value) in fresh {
|
||||
let before = get(old, key);
|
||||
if before.as_ref() == Some(value) {
|
||||
continue;
|
||||
}
|
||||
let current = process(key);
|
||||
if key.eq_ignore_ascii_case("PATH") {
|
||||
let current = current.unwrap_or_default();
|
||||
let rebased = rebase_path_list(¤t, before.as_deref().unwrap_or_default(), value);
|
||||
if rebased != current {
|
||||
out.push((key.clone(), Some(rebased)));
|
||||
}
|
||||
} else if current.as_ref() != Some(value) {
|
||||
out.push((key.clone(), Some(value.clone())));
|
||||
}
|
||||
}
|
||||
for (key, value) in old {
|
||||
if get(fresh, key).is_none() && process(key).as_ref() == Some(value) {
|
||||
out.push((key.clone(), None));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Read on every call, not cached: startup rewrites `PATH` (login shell, managed tools).
|
||||
fn appimage_fixes() -> Vec<(OsString, Option<OsString>)> {
|
||||
if !cfg!(target_os = "linux") || std::env::var_os("APPDIR").is_none() {
|
||||
@@ -1459,6 +1744,118 @@ mod tests {
|
||||
assert!(fixes(&[("APPDIR", "/"), ("PATH", "/usr/bin")]).is_empty());
|
||||
}
|
||||
|
||||
fn os(vars: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
|
||||
vars.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect()
|
||||
}
|
||||
|
||||
fn list(dirs: &[&str]) -> OsString {
|
||||
std::env::join_paths(dirs).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_path_changes_keep_what_the_ide_added_to_path() {
|
||||
// The IDE put `tools` first at startup; meanwhile an installer appended `node`
|
||||
// and an uninstaller removed `old`.
|
||||
let process = list(&["tools", "sys", "old", "user"]);
|
||||
let rebased = rebase_path_list(&process, &list(&["sys", "old", "user"]), &list(&["sys", "user", "node"]));
|
||||
assert_eq!(rebased, list(&["tools", "sys", "user", "node"]));
|
||||
// Nothing to add when the entry is already there (a trailing separator aside).
|
||||
let sep = std::path::MAIN_SEPARATOR.to_string();
|
||||
let rebased =
|
||||
rebase_path_list(&list(&["sys", "node"]), &list(&["sys"]), &list(&["sys", &format!("node{sep}")]));
|
||||
assert_eq!(rebased, list(&["sys", "node"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_changes_are_new_changed_and_removed_variables() {
|
||||
let old = os(&[("KEEP", "1"), ("CHANGED", "a"), ("GONE", "x"), ("OVERRIDDEN", "y"), ("PATH", "sys")]);
|
||||
let fresh = os(&[("KEEP", "1"), ("CHANGED", "b"), ("NEW", "n"), ("PATH", "sys")]);
|
||||
// The IDE was launched with `OVERRIDDEN` set otherwise: that value stays.
|
||||
let process = |k: &OsStr| match k.to_str()?.to_ascii_uppercase().as_str() {
|
||||
"KEEP" => Some("1".into()),
|
||||
"CHANGED" => Some("a".into()),
|
||||
"GONE" => Some("x".into()),
|
||||
"OVERRIDDEN" => Some("launcher".into()),
|
||||
"PATH" => Some(list(&["tools", "sys"])),
|
||||
_ => None,
|
||||
};
|
||||
let got = registry_diff(&process, &old, &fresh);
|
||||
let want: Vec<(OsString, Option<OsString>)> =
|
||||
vec![("CHANGED".into(), Some("b".into())), ("NEW".into(), Some("n".into())), ("GONE".into(), None)];
|
||||
assert_eq!(got, want);
|
||||
assert!(registry_diff(&process, &old, &old).is_empty());
|
||||
// A `Path` change reaches the process `PATH` (another case of the same variable).
|
||||
let got = registry_diff(&process, &os(&[("Path", "sys")]), &os(&[("Path", "sys;node")]));
|
||||
if cfg!(windows) {
|
||||
assert_eq!(got, vec![("Path".into(), Some(list(&["tools", "sys", "node"])))]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_match_variable_names_as_the_platform_does() {
|
||||
let vars = os(&[("Path", "a")]);
|
||||
let got = apply_changes(vars, &[("PATH".into(), Some("b".into()))]);
|
||||
if cfg!(windows) {
|
||||
assert_eq!(got, os(&[("Path", "b")]));
|
||||
} else {
|
||||
assert_eq!(got, os(&[("Path", "a"), ("PATH", "b")]));
|
||||
}
|
||||
}
|
||||
|
||||
/// A variable set in `HKCU\Environment` after startup (as an installer or the System
|
||||
/// Properties dialog does) reaches the next child without a restart.
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_user_variable_set_after_startup_reaches_new_children() {
|
||||
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
||||
use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, REG_SZ, RegDeleteKeyValueW, RegSetKeyValueW};
|
||||
|
||||
fn wide(s: &str) -> Vec<u16> {
|
||||
s.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
struct Cleanup(Vec<u16>);
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: NUL-terminated names of a value this test created.
|
||||
unsafe { RegDeleteKeyValueW(HKEY_CURRENT_USER, wide("Environment").as_ptr(), self.0.as_ptr()) };
|
||||
}
|
||||
}
|
||||
|
||||
record_startup_registry_env();
|
||||
let name = format!("OPENIDEA_REGISTRY_ENV_TEST_{}", std::process::id());
|
||||
let value = wide("installed");
|
||||
let wide_name = wide(&name);
|
||||
// SAFETY: NUL-terminated names; the data is `value`'s bytes, NUL included.
|
||||
let status = unsafe {
|
||||
RegSetKeyValueW(
|
||||
HKEY_CURRENT_USER,
|
||||
wide("Environment").as_ptr(),
|
||||
wide_name.as_ptr(),
|
||||
REG_SZ,
|
||||
value.as_ptr().cast(),
|
||||
(value.len() * 2) as u32,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, ERROR_SUCCESS);
|
||||
let cleanup = Cleanup(wide_name);
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
let seen = loop {
|
||||
let seen = host_var_os(&name);
|
||||
if seen.is_some() || std::time::Instant::now() >= deadline {
|
||||
break seen;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
assert_eq!(seen.as_deref(), Some(OsStr::new("installed")));
|
||||
assert!(spawnable_host_vars().any(|(k, v)| k == name.as_str() && v == "installed"));
|
||||
drop(cleanup);
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while host_var_os(&name).is_some() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
assert_eq!(host_var_os(&name), None, "a removed variable is gone again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_env_keeps_what_the_call_site_set() {
|
||||
let mut cmd = Command::new("true");
|
||||
|
||||
@@ -227,6 +227,7 @@ pub struct RunTarget {
|
||||
pub python: String,
|
||||
pub node: String,
|
||||
pub java: String,
|
||||
pub php: String,
|
||||
/// Id of a Docker connection of the Services tool window (Docker, Compose);
|
||||
/// empty = the CLI's own daemon.
|
||||
pub docker_connection: String,
|
||||
|
||||
@@ -162,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")]
|
||||
@@ -211,6 +214,7 @@ impl Default for AgentSettings {
|
||||
confirm_terminate_on_close: true,
|
||||
defaults: BTreeMap::new(),
|
||||
mcp_servers: BTreeMap::new(),
|
||||
mcp_registry_url: String::new(),
|
||||
skills: BTreeMap::new(),
|
||||
memory: AgentMemorySettings::default(),
|
||||
plugins: AgentPluginSettings::default(),
|
||||
@@ -253,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 {
|
||||
@@ -266,6 +278,8 @@ impl Default for AgentMcpServer {
|
||||
url: None,
|
||||
headers: BTreeMap::new(),
|
||||
agents: Vec::new(),
|
||||
registry_name: None,
|
||||
registry_url: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -705,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.
|
||||
@@ -1084,6 +1100,8 @@ pub struct GeneralSettings {
|
||||
pub project_name: String,
|
||||
/// Where updates come from: `auto` (the CNB mirror for the Chinese UI, else GitHub) | `github` | `cnb`.
|
||||
pub update_source: String,
|
||||
/// `stable` | `nightly`; defaults to the running build's channel.
|
||||
pub update_channel: String,
|
||||
pub auto_check_updates: bool,
|
||||
/// System Settings › Updates: open the What's New page after the app starts a new version.
|
||||
pub show_whats_new_after_update: bool,
|
||||
@@ -1106,6 +1124,7 @@ impl Default for GeneralSettings {
|
||||
power_save_mode: false,
|
||||
project_name: String::new(),
|
||||
update_source: "auto".into(),
|
||||
update_channel: crate::updates::UpdateChannel::of_version(env!("CARGO_PKG_VERSION")).as_str().into(),
|
||||
auto_check_updates: true,
|
||||
show_whats_new_after_update: true,
|
||||
last_run_version: String::new(),
|
||||
@@ -1345,6 +1364,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>,
|
||||
@@ -1428,6 +1448,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,
|
||||
@@ -1445,6 +1469,9 @@ pub struct EditorSettings {
|
||||
/// Color Scheme › Language Defaults › Semantic highlighting: local variables and
|
||||
/// parameters get a colour derived from their name (IDEA's rainbow identifiers).
|
||||
pub semantic_highlighting: bool,
|
||||
/// Color Scheme › Language Defaults › Dim inactive preprocessor code: grey out the
|
||||
/// `#if`/`#ifdef` branches clangd reports as inactive (C and C++).
|
||||
pub dim_inactive_code: bool,
|
||||
/// Docstring markup format whose tags and keywords the Python editor highlights
|
||||
/// (`plain`, `rest`, `epytext`, `google`, `numpy`).
|
||||
pub docstring_format: String,
|
||||
@@ -1481,11 +1508,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,
|
||||
@@ -1498,6 +1537,7 @@ impl Default for EditorSettings {
|
||||
color_overrides: BTreeMap::new(),
|
||||
custom_schemes: BTreeMap::new(),
|
||||
semantic_highlighting: false,
|
||||
dim_inactive_code: true,
|
||||
docstring_format: "rest".into(),
|
||||
rainbow_brackets: false,
|
||||
rainbow_bracket_kinds: RainbowBracketKinds::default(),
|
||||
@@ -1697,6 +1737,8 @@ pub struct MarkdownSettings {
|
||||
pub preview_layout: MarkdownPreviewLayout,
|
||||
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
|
||||
pub preview_font_size: Option<u32>,
|
||||
/// How single newlines inside a paragraph are rendered in the Markdown preview.
|
||||
pub soft_line_breaks: MarkdownSoftLineBreaks,
|
||||
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
|
||||
/// trusted projects, or stay in static safe mode.
|
||||
pub mdx_execution: MdxExecutionPolicy,
|
||||
@@ -1712,6 +1754,7 @@ impl Default for MarkdownSettings {
|
||||
Self {
|
||||
preview_layout: MarkdownPreviewLayout::default(),
|
||||
preview_font_size: None,
|
||||
soft_line_breaks: MarkdownSoftLineBreaks::default(),
|
||||
mdx_execution: MdxExecutionPolicy::default(),
|
||||
run_commands: true,
|
||||
command_directory: None,
|
||||
@@ -1719,6 +1762,16 @@ impl Default for MarkdownSettings {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MarkdownSoftLineBreaks {
|
||||
/// Standard Markdown: a single newline collapses into a space.
|
||||
#[default]
|
||||
Standard,
|
||||
/// Render each single newline inside a paragraph as a line break (`<br>`).
|
||||
Break,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MdxExecutionPolicy {
|
||||
@@ -2136,6 +2189,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.
|
||||
@@ -2542,12 +2597,16 @@ mod tests {
|
||||
let old: Settings = serde_json::from_str(r#"{"languages":{"markdown":{"previewFontSize":16}}}"#).unwrap();
|
||||
assert_eq!(old.languages.markdown.preview_layout, MarkdownPreviewLayout::SideBySide);
|
||||
assert_eq!(old.languages.markdown.preview_font_size, Some(16));
|
||||
assert_eq!(old.languages.markdown.soft_line_breaks, MarkdownSoftLineBreaks::Standard);
|
||||
|
||||
let stacked: Settings =
|
||||
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked"}}}"#).unwrap();
|
||||
serde_json::from_str(r#"{"languages":{"markdown":{"previewLayout":"stacked","softLineBreaks":"break"}}}"#)
|
||||
.unwrap();
|
||||
assert_eq!(stacked.languages.markdown.preview_layout, MarkdownPreviewLayout::Stacked);
|
||||
assert_eq!(stacked.languages.markdown.soft_line_breaks, MarkdownSoftLineBreaks::Break);
|
||||
let saved = serde_json::to_value(&stacked).unwrap();
|
||||
assert_eq!(saved["languages"]["markdown"]["previewLayout"], "stacked");
|
||||
assert_eq!(saved["languages"]["markdown"]["softLineBreaks"], "break");
|
||||
assert_eq!(serde_json::from_value::<Settings>(saved).unwrap().languages.markdown, stacked.languages.markdown);
|
||||
}
|
||||
|
||||
@@ -2574,12 +2633,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!(
|
||||
@@ -2595,6 +2654,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!({}));
|
||||
}
|
||||
@@ -2663,6 +2723,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dim_inactive_code_defaults_on_and_round_trips() {
|
||||
let mut settings = Settings::default();
|
||||
assert!(settings.editor.dim_inactive_code);
|
||||
settings.editor.dim_inactive_code = false;
|
||||
let json = serde_json::to_value(&settings).unwrap();
|
||||
assert_eq!(json["editor"]["dimInactiveCode"], false);
|
||||
let restored: Settings = serde_json::from_value(json).unwrap();
|
||||
assert!(!restored.editor.dim_inactive_code);
|
||||
// Settings written before the option existed keep clangd's inactive-code grey.
|
||||
let old: Settings = serde_json::from_str(r#"{"editor":{"semanticHighlighting":true}}"#).unwrap();
|
||||
assert!(old.editor.dim_inactive_code);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_window_badges_default_on_and_round_trip() {
|
||||
let old: Settings = serde_json::from_str(r#"{"appearance":{"showToolWindowNames":true}}"#).unwrap();
|
||||
|
||||
@@ -8,6 +8,21 @@ use std::collections::HashSet;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Why netcoredbg can't be installed here, for the two platforms Samsung publishes no build
|
||||
/// for; the tool installer and the debugger's "not found" error both say it.
|
||||
pub fn netcoredbg_no_prebuilt(intel_mac: bool, windows_arm64: bool) -> Option<String> {
|
||||
let platform = match (intel_mac, windows_arm64) {
|
||||
(true, _) => "Intel Macs",
|
||||
(_, true) => "Windows on ARM64",
|
||||
_ => return None,
|
||||
};
|
||||
Some(format!(
|
||||
"Samsung publishes no prebuilt netcoredbg for {platform}. Build it from source \
|
||||
(https://github.com/Samsung/netcoredbg#building-from-source-code), then put `netcoredbg` on PATH \
|
||||
or set its executable path in Settings › Languages & Frameworks › Language Servers"
|
||||
))
|
||||
}
|
||||
|
||||
/// Where executables are looked up: this process's `PATH` (the login shell's in the
|
||||
/// app), the login shell's `PATH` as last read, then per-user directories and mise's,
|
||||
/// asdf's and pyenv's shims, for when the shell's setup didn't reach the app. Language server
|
||||
@@ -133,6 +148,7 @@ fn search_dirs(
|
||||
dirs.extend(USER_DIRS.iter().map(|d| home.join(d)));
|
||||
dirs.extend(nvm_bins(&home.join(".nvm/versions/node")));
|
||||
}
|
||||
dirs.extend(RUSTUP_PROXY_DIRS.iter().map(PathBuf::from));
|
||||
// Version managers' shims after real tool directories: a shim exists for a command any
|
||||
// installed version has, and fails when the selected one lacks it. Before the system's,
|
||||
// as the managers' shell setup puts them.
|
||||
@@ -165,6 +181,11 @@ const USER_DIRS: &[&str] = &[
|
||||
"Library/pnpm",
|
||||
];
|
||||
|
||||
/// Homebrew's `rustup` keeps its toolchain proxies (`cargo`, `rust-analyzer`, …) in its own
|
||||
/// prefix, off `PATH` unless the shell adds it: these play the part of `~/.cargo/bin`.
|
||||
pub const RUSTUP_PROXY_DIRS: &[&str] =
|
||||
&["/opt/homebrew/opt/rustup/bin", "/usr/local/opt/rustup/bin", "/home/linuxbrew/.linuxbrew/opt/rustup/bin"];
|
||||
|
||||
const SYSTEM_DIRS: &[&str] = &["/opt/homebrew/bin", "/usr/local/go/bin", "/usr/local/bin", "/usr/bin", "/bin"];
|
||||
|
||||
/// Whether `dir` is one of the system's own bin directories, which [`search_path`] adds
|
||||
@@ -250,13 +271,16 @@ mod tests {
|
||||
assert!(at("/home/me/.npm-global/bin") < at("/home/me/.pyenv/shims"));
|
||||
// Global .NET tools (fsautocomplete, csharp-ls) install here, off PATH.
|
||||
assert!(at("/home/me/.dotnet/tools") < at("/usr/local/bin"));
|
||||
// Homebrew rustup's proxies, after rustup-init's.
|
||||
assert!(at("/home/me/.cargo/bin") < at("/opt/homebrew/opt/rustup/bin"));
|
||||
assert!(at("/opt/homebrew/opt/rustup/bin") < at("/opt/homebrew/bin"));
|
||||
assert!(at("/home/me/.local/share/mise/shims") < at("/usr/local/bin"));
|
||||
assert!(dirs.iter().all(|d| d.is_absolute()));
|
||||
let unique: HashSet<&PathBuf> = dirs.iter().collect();
|
||||
assert_eq!(unique.len(), dirs.len());
|
||||
// A `:` can't be in a `PATH` entry: those below such a home are left out.
|
||||
let dirs = search_dirs(Some(OsStr::new("/usr/bin")), None, None, Some(Path::new("/home/a:b")), &[]);
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home")));
|
||||
assert!(dirs.contains(&PathBuf::from("/usr/bin")) && !dirs.iter().any(|d| d.starts_with("/home/a:b")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -30,6 +30,38 @@ impl UpdateSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// System Settings › Updates › Update channel: which release line updates come from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum UpdateChannel {
|
||||
/// `releases/latest`, never a prerelease, mirrored on CNB.
|
||||
Stable,
|
||||
/// The rolling `nightly` release (nightly.yml), on GitHub only.
|
||||
Nightly,
|
||||
}
|
||||
|
||||
impl UpdateChannel {
|
||||
/// The channel a build of `version` updates from unless the setting says otherwise.
|
||||
pub fn of_version(version: &str) -> Self {
|
||||
if version.contains("-nightly.") { Self::Nightly } else { Self::Stable }
|
||||
}
|
||||
|
||||
/// The `general.updateChannel` setting; anything else follows this build.
|
||||
pub fn resolve(preference: &str) -> Self {
|
||||
match preference {
|
||||
"stable" => Self::Stable,
|
||||
"nightly" => Self::Nightly,
|
||||
_ => Self::of_version(env!("CARGO_PKG_VERSION")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Stable => "stable",
|
||||
Self::Nightly => "nightly",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UpdateInfo {
|
||||
@@ -109,6 +141,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_follows_the_build_unless_chosen() {
|
||||
assert_eq!(UpdateChannel::of_version("0.1.57"), UpdateChannel::Stable);
|
||||
assert_eq!(UpdateChannel::of_version("0.1.58-nightly.20261203"), UpdateChannel::Nightly);
|
||||
assert_eq!(UpdateChannel::of_version("0.1.58-nightly.20261203.2"), UpdateChannel::Nightly);
|
||||
assert_eq!(UpdateChannel::of_version("0.2.0-beta.1"), UpdateChannel::Stable);
|
||||
assert_eq!(UpdateChannel::resolve("stable"), UpdateChannel::Stable);
|
||||
assert_eq!(UpdateChannel::resolve("nightly"), UpdateChannel::Nightly);
|
||||
let build = UpdateChannel::of_version(env!("CARGO_PKG_VERSION"));
|
||||
for other in ["", "auto", "Nightly", "eap"] {
|
||||
assert_eq!(UpdateChannel::resolve(other), build);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checks_at_startup_and_every_four_hours_even_after_failure() {
|
||||
let mut policy = UpdatePolicy::default();
|
||||
|
||||
@@ -31,6 +31,17 @@ pub struct VcsSettings {
|
||||
pub svn: SvnSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Subversion (`vcs.svn`).
|
||||
/// Branch and tag URL layout configured for one Subversion repository.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SvnBranchConfig {
|
||||
/// Trunk URL (e.g. `https://svn.example.com/repos/project/trunk`).
|
||||
pub trunk_url: String,
|
||||
/// Folders holding branches/tags (e.g. `["https://svn.example.com/repos/project/branches"]`).
|
||||
pub branch_locations: Vec<String>,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Subversion (`vcs.svn`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
@@ -43,6 +54,8 @@ pub struct SvnSettings {
|
||||
/// Pass `--config-dir config_dir` to every svn command.
|
||||
pub use_custom_config_dir: bool,
|
||||
pub config_dir: String,
|
||||
/// Configured trunk/branch locations keyed by normalized repository root URL or WC root.
|
||||
pub branch_configurations: std::collections::BTreeMap<String, SvnBranchConfig>,
|
||||
}
|
||||
|
||||
impl Default for SvnSettings {
|
||||
@@ -54,6 +67,7 @@ impl Default for SvnSettings {
|
||||
interactive: !cfg!(windows),
|
||||
use_custom_config_dir: false,
|
||||
config_dir: String::new(),
|
||||
branch_configurations: std::collections::BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -562,6 +576,8 @@ pub struct DebuggerSettings {
|
||||
pub flutter_hot_reload_on_save: bool,
|
||||
/// Java: whether to reload changed classes into running debug sessions after compilation.
|
||||
pub hot_swap_after_compile: HotSwapPolicy,
|
||||
/// Built-in Server: starting loopback port for `/api/file/<path>:<line>` requests.
|
||||
pub built_in_server_port: u16,
|
||||
pub python: PythonDebuggerSettings,
|
||||
pub cpp: CppDebuggerSettings,
|
||||
}
|
||||
@@ -585,6 +601,7 @@ impl Default for DebuggerSettings {
|
||||
debug_server_page: false,
|
||||
flutter_hot_reload_on_save: true,
|
||||
hot_swap_after_compile: HotSwapPolicy::Ask,
|
||||
built_in_server_port: 63342,
|
||||
python: PythonDebuggerSettings::default(),
|
||||
cpp: CppDebuggerSettings::default(),
|
||||
}
|
||||
@@ -667,7 +684,6 @@ pub struct TerminalSettings {
|
||||
pub override_ide_shortcuts: bool,
|
||||
pub shell_integration: bool,
|
||||
pub highlight_hyperlinks: bool,
|
||||
pub highlight_selection: bool,
|
||||
/// Highlights typed commands the IDE recognises; Run Highlighted Command runs them with it.
|
||||
pub run_commands_using_ide: bool,
|
||||
pub option_as_meta: bool,
|
||||
@@ -707,7 +723,6 @@ impl Default for TerminalSettings {
|
||||
override_ide_shortcuts: true,
|
||||
shell_integration: true,
|
||||
highlight_hyperlinks: true,
|
||||
highlight_selection: true,
|
||||
run_commands_using_ide: true,
|
||||
option_as_meta: false,
|
||||
escape_to_editor: false,
|
||||
@@ -729,6 +744,8 @@ impl Default for TerminalSettings {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ActionsOnSaveSettings {
|
||||
pub optimize_imports: bool,
|
||||
/// Rearrange code: class members in arrangement order, for the languages that have it.
|
||||
pub rearrange: bool,
|
||||
/// Run code cleanup (`source.fixAll`).
|
||||
pub cleanup: bool,
|
||||
}
|
||||
|
||||
@@ -613,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);
|
||||
}
|
||||
@@ -1205,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());
|
||||
|
||||
@@ -805,7 +805,7 @@ macro_rules! backend_id {
|
||||
mod cursor;
|
||||
mod pg_read_only;
|
||||
pub(crate) use cursor::{Cursors, Key as CursorKey};
|
||||
pub(crate) use pg_read_only::validate as validate_pg_read_only;
|
||||
pub(crate) use pg_read_only::{leading_word, validate as validate_pg_read_only};
|
||||
|
||||
/// Whether the pages of `sql`'s result can be read by a cursor (see [`cursor`]): a query that
|
||||
/// leaves the session as it was.
|
||||
@@ -1058,7 +1058,8 @@ impl Pool {
|
||||
opts = opts.statement_cache_capacity(n);
|
||||
}
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(MAX)
|
||||
// sqlx opens connections for a pool only, so console sessions count here.
|
||||
.max_connections(MAX + crate::console_session::MAX_SESSIONS)
|
||||
.acquire_timeout(timeout)
|
||||
.after_connect(after_connect!())
|
||||
.connect_with(opts)
|
||||
@@ -1428,6 +1429,7 @@ impl Pool {
|
||||
conn.discard().await;
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
conn.release_after(sql, self.driver()).await;
|
||||
r
|
||||
}
|
||||
|
||||
@@ -1513,13 +1515,38 @@ impl Pool {
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection taken out of a pool: for one statement, or held by a
|
||||
/// manual-commit console across statements with its transaction open.
|
||||
/// A connection of a pool, or one opened beside it that closes when dropped.
|
||||
pub enum Lease<M: ManageConnection> {
|
||||
Pooled(bb8::PooledConnection<'static, M>),
|
||||
Own(M::Connection),
|
||||
}
|
||||
|
||||
impl<M: ManageConnection> std::ops::Deref for Lease<M> {
|
||||
type Target = M::Connection;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match self {
|
||||
Lease::Pooled(c) => c,
|
||||
Lease::Own(c) => c,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<M: ManageConnection> std::ops::DerefMut for Lease<M> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
match self {
|
||||
Lease::Pooled(c) => c,
|
||||
Lease::Own(c) => c,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection taken out of a pool: for one statement, or held by a console
|
||||
/// across statements (its manual transaction or its session).
|
||||
pub enum Held {
|
||||
Sqlite(PoolConnection<Sqlite>),
|
||||
Postgres(Box<bb8::PooledConnection<'static, PgManager>>),
|
||||
Mysql(Box<bb8::PooledConnection<'static, MysqlManager>>),
|
||||
SqlServer(Box<bb8::PooledConnection<'static, MssqlConnectionManager>>),
|
||||
Postgres(Box<Lease<PgManager>>),
|
||||
Mysql(Box<Lease<MysqlManager>>),
|
||||
SqlServer(Box<Lease<MssqlConnectionManager>>),
|
||||
Clickhouse(crate::clickhouse::ClickhousePool),
|
||||
Oracle(Box<crate::oracle::OracleConnection>),
|
||||
/// The shared session, and the schema this holder's statements run in.
|
||||
@@ -1531,9 +1558,11 @@ impl Held {
|
||||
Ok(match pool {
|
||||
Pool::Jdbc(_) => return Err(IdeError::invalid("Custom JDBC manual transactions are unsupported")),
|
||||
Pool::Sqlite(p) => Held::Sqlite(p.acquire().await.map_err(db_err)?),
|
||||
Pool::Postgres(p) => Held::Postgres(Box::new(p.get().await?)),
|
||||
Pool::Mysql(p) => Held::Mysql(Box::new(p.get().await?)),
|
||||
Pool::SqlServer(p) => Held::SqlServer(Box::new(p.get_owned().await.map_err(mssql_pool_err)?)),
|
||||
Pool::Postgres(p) => Held::Postgres(Box::new(Lease::Pooled(p.get().await?))),
|
||||
Pool::Mysql(p) => Held::Mysql(Box::new(Lease::Pooled(p.get().await?))),
|
||||
Pool::SqlServer(p) => {
|
||||
Held::SqlServer(Box::new(Lease::Pooled(p.get_owned().await.map_err(mssql_pool_err)?)))
|
||||
}
|
||||
Pool::Clickhouse(p) => {
|
||||
if p.is_closed() {
|
||||
return Err(IdeError::new(ErrorKind::Io, "ClickHouse connection is closed"));
|
||||
@@ -1550,6 +1579,47 @@ impl Held {
|
||||
})
|
||||
}
|
||||
|
||||
/// A connection that takes none of the pool's; [`discard`](Self::discard) it when done.
|
||||
pub(crate) async fn acquire_own(pool: &Pool) -> IdeResult<Self> {
|
||||
Ok(match pool {
|
||||
Pool::Postgres(p) => {
|
||||
Held::Postgres(Box::new(Lease::Own(p.inner.dedicated_connection().await.map_err(db_err)?)))
|
||||
}
|
||||
Pool::Mysql(p) => Held::Mysql(Box::new(Lease::Own(p.inner.dedicated_connection().await.map_err(db_err)?))),
|
||||
Pool::SqlServer(p) => {
|
||||
Held::SqlServer(Box::new(Lease::Own(p.dedicated_connection().await.map_err(mssql_err)?)))
|
||||
}
|
||||
Pool::Oracle(p) => Held::Oracle(Box::new(p.open_own().await?)),
|
||||
_ => Self::acquire(pool).await?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the server still answers, also inside a failed transaction.
|
||||
pub(crate) async fn is_alive(&mut self) -> bool {
|
||||
let ping = async {
|
||||
match self {
|
||||
Held::Sqlite(c) => c.ping().await.is_ok(),
|
||||
Held::Postgres(c) => c.conn.is_some() && c.ping().await.is_ok(),
|
||||
Held::Mysql(c) => c.conn.is_some() && c.ping().await.is_ok(),
|
||||
Held::SqlServer(c) => c.0.is_some() && mssql_command(c, "SELECT 1").await.is_ok(),
|
||||
Held::Oracle(c) => {
|
||||
crate::oracle::run(c, "SELECT 1 FROM DUAL", 0, 1, Cells::Text, &CancellationToken::new())
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
Held::Clickhouse(_) | Held::Snowflake(..) => true,
|
||||
}
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(5), ping).await.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Returns the connection that ran `sql` to its pool, unless `sql` left a transaction open on it.
|
||||
pub(crate) async fn release_after(self, sql: &str, driver: DbDriver) {
|
||||
if crate::console_session::opens_transaction(sql, driver) {
|
||||
self.discard().await;
|
||||
}
|
||||
}
|
||||
|
||||
fn context(&mut self) -> Option<&mut Context> {
|
||||
match self {
|
||||
Held::Postgres(c) => Some(&mut c.context),
|
||||
|
||||
@@ -7,7 +7,8 @@ use sqlx::{Executor, SqlSafeStr};
|
||||
// Take the first snapshot before user SQL, fixing the transaction characteristics on this backend.
|
||||
pub(super) const BEGIN: &str = "BEGIN READ ONLY; SELECT 1";
|
||||
|
||||
fn leading_word<'a>(input: &mut &'a str) -> &'a str {
|
||||
/// Takes the first word off `input`, past comments; empty when something else comes first.
|
||||
pub(crate) fn leading_word<'a>(input: &mut &'a str) -> &'a str {
|
||||
loop {
|
||||
*input = input.trim_start_matches([' ', '\t', '\r', '\n', '\x0c', '\x0b', ';']);
|
||||
if let Some(comment) = input.strip_prefix("--") {
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
//! The connection a SQL console keeps in auto-commit mode.
|
||||
//!
|
||||
//! Plain queries and changes run on any connection of the pool. The first statement that leaves
|
||||
//! something on its connection (a transaction, a temporary table, a setting) opens the console's
|
||||
//! own one, which then runs everything the console runs until the console is released.
|
||||
|
||||
use crate::conn::{Held, Pool, leading_word};
|
||||
use crate::source::DbDriver;
|
||||
use crate::{QueryResult, split};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{Mutex as AsyncMutex, OwnedSemaphorePermit, Semaphore};
|
||||
|
||||
/// Consoles of one target that can keep a connection, beside those of the pool.
|
||||
pub(crate) const MAX_SESSIONS: u32 = 4;
|
||||
|
||||
/// `Some(true)`: `sql` opens a transaction, `Some(false)`: it ends the open one.
|
||||
fn transaction_control(sql: &str, driver: DbDriver) -> Option<bool> {
|
||||
let mut rest = sql;
|
||||
let first = leading_word(&mut rest).to_ascii_uppercase();
|
||||
let second = leading_word(&mut rest).to_ascii_uppercase();
|
||||
match first.as_str() {
|
||||
// A block, not a transaction.
|
||||
"BEGIN" if driver == DbDriver::Oracle => None,
|
||||
"BEGIN" if driver == DbDriver::SqlServer => second.starts_with("TRAN").then_some(true),
|
||||
"BEGIN" | "SAVEPOINT" => Some(true),
|
||||
"START" if second == "TRANSACTION" => Some(true),
|
||||
"SET" if matches!(second.as_str(), "AUTOCOMMIT" | "IMPLICIT_TRANSACTIONS") => Some(true),
|
||||
"COMMIT" | "END" | "ABORT" => Some(false),
|
||||
"ROLLBACK" if !sql.split_whitespace().any(|word| word.eq_ignore_ascii_case("TO")) => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn statements(sql: &str, driver: DbDriver) -> Vec<String> {
|
||||
// The `;` in the body of a routine or trigger ends none of its creator's statements.
|
||||
if sql.contains(';') && !leading_word(&mut &*sql).eq_ignore_ascii_case("CREATE") {
|
||||
split::split(sql, driver).into_iter().map(|s| s.text).collect()
|
||||
} else {
|
||||
vec![sql.to_owned()]
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn opens_transaction(sql: &str, driver: DbDriver) -> bool {
|
||||
statements(sql, driver).iter().any(|sql| transaction_control(sql, driver) == Some(true))
|
||||
}
|
||||
|
||||
/// Whether a later statement of the console depends on `sql` having run on its connection.
|
||||
/// Unknown statements do.
|
||||
fn needs_session(sql: &str, driver: DbDriver) -> bool {
|
||||
statements(sql, driver).iter().any(|sql| {
|
||||
let mut rest = sql.as_str();
|
||||
let mut first = leading_word(&mut rest);
|
||||
while first.is_empty()
|
||||
&& let Some(inner) = rest.strip_prefix('(')
|
||||
{
|
||||
rest = inner;
|
||||
first = leading_word(&mut rest);
|
||||
}
|
||||
let first = first.to_ascii_uppercase();
|
||||
let words = || rest.split_whitespace().map(str::to_ascii_uppercase);
|
||||
match first.as_str() {
|
||||
"SELECT" | "WITH" | "VALUES" | "TABLE" | "INSERT" | "UPDATE" | "DELETE" | "REPLACE" | "MERGE" => {
|
||||
let text = rest.to_ascii_uppercase();
|
||||
let into = words().any(|word| word == "INTO");
|
||||
["SET_CONFIG", "ADVISORY_LOCK", "GET_LOCK", ":="].iter().any(|state| text.contains(state))
|
||||
|| (into && words().any(|word| is_temporary(&word, driver)))
|
||||
}
|
||||
"CREATE" => words().take(4).any(|word| is_temporary(&word, driver)),
|
||||
"ALTER" => words().next().is_some_and(|word| word == "SESSION"),
|
||||
"SHOW" | "EXPLAIN" | "DESCRIBE" | "DESC" | "DROP" | "TRUNCATE" | "RENAME" | "COMMENT" | "GRANT"
|
||||
| "REVOKE" | "ANALYZE" | "VACUUM" | "REINDEX" | "OPTIMIZE" | "COMMIT" | "END" | "ABORT" | "ROLLBACK" => {
|
||||
false
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn is_temporary(word: &str, driver: DbDriver) -> bool {
|
||||
matches!(word, "TEMP" | "TEMPORARY")
|
||||
|| (driver == DbDriver::SqlServer
|
||||
&& word.starts_with(['#', '['])
|
||||
&& word.trim_start_matches('[').starts_with('#'))
|
||||
}
|
||||
|
||||
struct Open {
|
||||
connection: Held,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
/// The console's schema the connection was last put in. Reapplied only when the console picks
|
||||
/// another one, so a `USE` or `SET search_path` of the user stays.
|
||||
schema: Option<String>,
|
||||
transaction: bool,
|
||||
/// The schema was set inside the open transaction, whose rollback may restore the one before.
|
||||
schema_in_transaction: bool,
|
||||
}
|
||||
|
||||
impl Open {
|
||||
async fn new(pool: &Pool, capacity: &Arc<Semaphore>, schema: Option<&str>) -> IdeResult<Self> {
|
||||
let permit = capacity.clone().try_acquire_owned().map_err(|_| {
|
||||
IdeError::unavailable(format!(
|
||||
"{MAX_SESSIONS} consoles already keep a session on this data source. Close one of them and its results, then run the statement again."
|
||||
))
|
||||
})?;
|
||||
let mut connection = Held::acquire_own(pool).await?;
|
||||
connection.apply_context(schema).await?;
|
||||
Ok(Self {
|
||||
connection,
|
||||
_permit: permit,
|
||||
schema: schema.map(str::to_owned),
|
||||
transaction: false,
|
||||
schema_in_transaction: false,
|
||||
})
|
||||
}
|
||||
|
||||
async fn run(
|
||||
&mut self,
|
||||
pool: &Pool,
|
||||
statement: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let driver = pool.driver();
|
||||
// A failed transaction refuses everything but its end, switching the schema included.
|
||||
if self.schema.as_deref() != schema && transaction_control(statement, driver) != Some(false) {
|
||||
self.connection.apply_context(schema).await?;
|
||||
self.schema = schema.map(str::to_owned);
|
||||
self.schema_in_transaction = self.transaction;
|
||||
}
|
||||
let result = self.connection.execute_from(pool, statement, skip, max_rows, cancel).await?;
|
||||
for control in statements(statement, driver).iter().filter_map(|sql| transaction_control(sql, driver)) {
|
||||
self.transaction = control;
|
||||
}
|
||||
if !self.transaction && std::mem::take(&mut self.schema_in_transaction) {
|
||||
self.connection.apply_context(self.schema.as_deref()).await?;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
async fn close(mut self) {
|
||||
if self.transaction {
|
||||
let _ = tokio::time::timeout(Duration::from_secs(5), self.connection.finish_manual(false)).await;
|
||||
}
|
||||
self.connection.discard().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Slot {
|
||||
open: Option<Open>,
|
||||
/// The connection ended inside a transaction, so the statements that follow must not commit on their own.
|
||||
lost_transaction: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ConsoleSession {
|
||||
slot: AsyncMutex<Slot>,
|
||||
retired: CancellationToken,
|
||||
}
|
||||
|
||||
impl ConsoleSession {
|
||||
/// Runs `statement` on the console's connection; `None` when it has none and needs none.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn execute(
|
||||
&self,
|
||||
pool: &Pool,
|
||||
capacity: &Arc<Semaphore>,
|
||||
statement: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
request: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<Option<QueryResult>> {
|
||||
let cancel = self.retired.child_token();
|
||||
let mut slot = tokio::select! {
|
||||
biased;
|
||||
() = request.cancelled() => return Err(IdeError::cancelled()),
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
slot = self.slot.lock() => slot,
|
||||
};
|
||||
if std::mem::take(&mut slot.lost_transaction) {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::OutOfSync,
|
||||
"The console's connection was closed and its open transaction rolled back. Run the statement again to start over in a new session.",
|
||||
));
|
||||
}
|
||||
let schema = schema.filter(|s| !s.is_empty());
|
||||
if slot.open.is_none() {
|
||||
if !needs_session(statement, pool.driver()) {
|
||||
return Ok(None);
|
||||
}
|
||||
slot.open = Some(tokio::select! {
|
||||
biased;
|
||||
() = request.cancelled() => return Err(IdeError::cancelled()),
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
open = Open::new(pool, capacity, schema) => open?,
|
||||
});
|
||||
}
|
||||
let open = slot.open.as_mut().expect("opened above");
|
||||
let result = {
|
||||
let execute = open.run(pool, statement, skip, max_rows, &cancel, schema);
|
||||
tokio::pin!(execute);
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = request.cancelled() => {
|
||||
cancel.cancel();
|
||||
execute.await
|
||||
}
|
||||
result = &mut execute => result,
|
||||
}
|
||||
};
|
||||
let cancelled = cancel.is_cancelled();
|
||||
if cancelled || (result.is_err() && !open.connection.is_alive().await) {
|
||||
let open = slot.open.take().expect("opened above");
|
||||
slot.lost_transaction = open.transaction;
|
||||
open.connection.discard().await;
|
||||
}
|
||||
if cancelled {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
result.map(Some)
|
||||
}
|
||||
|
||||
/// Stops a running statement, rolls back and closes the connection.
|
||||
pub(super) async fn retire(&self) {
|
||||
self.retired.cancel();
|
||||
let open = self.slot.lock().await.open.take();
|
||||
if let Some(open) = open {
|
||||
open.close().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn statements_that_leave_something_on_their_connection_need_a_session() {
|
||||
use DbDriver::{Mysql, Oracle, Postgres, SqlServer, Sqlite};
|
||||
for (driver, sql) in [
|
||||
(Sqlite, "/* note */ BEGIN"),
|
||||
(Sqlite, "PRAGMA foreign_keys = ON"),
|
||||
(Sqlite, "ATTACH 'other.db' AS other"),
|
||||
(Postgres, "SET work_mem = '64MB'"),
|
||||
(Postgres, "CREATE TEMP TABLE t (id int)"),
|
||||
(Postgres, "create local temporary table t (id int)"),
|
||||
(Postgres, "SELECT * INTO TEMP t FROM u"),
|
||||
(Postgres, "SELECT pg_advisory_lock(1)"),
|
||||
(Postgres, "INSERT INTO t VALUES (1); BEGIN"),
|
||||
(Mysql, "USE shop"),
|
||||
(Mysql, "SELECT @n := 1"),
|
||||
(Mysql, "LOCK TABLES t WRITE"),
|
||||
(SqlServer, "BEGIN TRAN"),
|
||||
(SqlServer, "CREATE TABLE #work (id int)"),
|
||||
(SqlServer, "SELECT * INTO #work FROM t"),
|
||||
(Oracle, "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY'"),
|
||||
] {
|
||||
assert!(needs_session(sql, driver), "{sql}");
|
||||
}
|
||||
for (driver, sql) in [
|
||||
(Postgres, "SELECT temp FROM weather"),
|
||||
(Postgres, "-- all\n(SELECT 1) UNION (SELECT 2)"),
|
||||
(Postgres, "WITH x AS (SELECT 1) SELECT * FROM x"),
|
||||
(Postgres, "INSERT INTO t VALUES ('a;b')"),
|
||||
(Postgres, "CREATE TABLE t (temp int)"),
|
||||
(Postgres, "ALTER TABLE t ADD c int"),
|
||||
(Postgres, "ROLLBACK"),
|
||||
(Sqlite, "DELETE FROM t; DELETE FROM u"),
|
||||
(Mysql, "SHOW TABLES"),
|
||||
] {
|
||||
assert!(!needs_session(sql, driver), "{sql}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocks_and_partial_rollbacks_do_not_change_the_transaction() {
|
||||
assert_eq!(transaction_control("BEGIN NULL; END;", DbDriver::Oracle), None);
|
||||
assert_eq!(transaction_control("BEGIN TRY SELECT 1 END TRY", DbDriver::SqlServer), None);
|
||||
assert_eq!(transaction_control("rollback to savepoint s", DbDriver::Postgres), None);
|
||||
assert_eq!(transaction_control("-- done\nROLLBACK", DbDriver::Mysql), Some(false));
|
||||
assert_eq!(transaction_control("START TRANSACTION", DbDriver::Mysql), Some(true));
|
||||
assert!(opens_transaction("DELETE FROM t; BEGIN", DbDriver::Sqlite));
|
||||
assert!(!opens_transaction("SELECT 'BEGIN; x'", DbDriver::Sqlite));
|
||||
}
|
||||
}
|
||||
@@ -255,6 +255,13 @@ impl Helper {
|
||||
"TEMP",
|
||||
"TMP",
|
||||
"SSH_AUTH_SOCK",
|
||||
// kubectl, gcloud and other cloud CLIs find their configuration here.
|
||||
"KUBECONFIG",
|
||||
"CLOUDSDK_CONFIG",
|
||||
"AWS_PROFILE",
|
||||
"AWS_CONFIG_FILE",
|
||||
"AWS_SHARED_CREDENTIALS_FILE",
|
||||
"AZURE_CONFIG_DIR",
|
||||
"NO_PROXY",
|
||||
"no_proxy",
|
||||
] {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
pub mod catalog;
|
||||
mod clickhouse;
|
||||
mod console_session;
|
||||
mod external_tunnel;
|
||||
pub use external_tunnel::stop_external_tunnels_on_exit;
|
||||
mod jdbc;
|
||||
@@ -1652,11 +1653,19 @@ impl DbManager {
|
||||
let pool = self.pool(id).await?;
|
||||
let driver = pool.driver();
|
||||
let missing = || IdeError::not_found(format!("{schema}.{name}"));
|
||||
if let Pool::Jdbc(jdbc) = &*pool {
|
||||
return jdbc
|
||||
.metadata(&["tableDdl", schema, name])
|
||||
.await?
|
||||
.into_iter()
|
||||
.find_map(|row| row.into_iter().next().flatten())
|
||||
.ok_or_else(missing);
|
||||
}
|
||||
let cells = |rows: Vec<Vec<Option<String>>>, i: usize| -> Vec<String> {
|
||||
rows.into_iter().filter_map(|r| r.into_iter().nth(i).flatten()).collect()
|
||||
};
|
||||
match driver {
|
||||
DbDriver::Jdbc => Err(IdeError::invalid("Custom JDBC sources do not provide vendor-specific DDL")),
|
||||
DbDriver::Jdbc => unreachable!("JDBC uses driver metadata"),
|
||||
DbDriver::Sqlite => {
|
||||
let stmts = cells(pool.rows(&sql::sqlite_ddl(schema, name), MAX_META_ROWS).await?, 0);
|
||||
if stmts.is_empty() {
|
||||
@@ -2095,6 +2104,8 @@ impl DbManager {
|
||||
let _ = self.run(id, &plan::oracle_plan_cleanup(&plan_id), 0, 0, cancel, None, None).await;
|
||||
return nodes;
|
||||
}
|
||||
// SHOWPLAN is a setting of the connection that would stay on in the console's session.
|
||||
let console = console.filter(|_| driver != DbDriver::SqlServer);
|
||||
let result = self
|
||||
.run(id, &plan::explain_statement(driver, statement), 0, MAX_META_ROWS, cancel, schema, console)
|
||||
.await?;
|
||||
@@ -2142,6 +2153,7 @@ impl DbManager {
|
||||
{
|
||||
return p.execute_in_console(statement, skip, max_rows, cancel, console).await;
|
||||
}
|
||||
let editor = console.filter(|_| !matches!(&*pool, Pool::Snowflake(_)) && !pool.transaction_read_only());
|
||||
let console = console.filter(|_| matches!(&*pool, Pool::Postgres(_)));
|
||||
let session = match console {
|
||||
Some(console) => connection.console_transactions.session(console),
|
||||
@@ -2156,6 +2168,15 @@ impl DbManager {
|
||||
// A cursor's open statement could keep this one waiting (a lock), and would show data from before it.
|
||||
self.cursors.release_target(id);
|
||||
}
|
||||
if session.is_none()
|
||||
&& let Some(editor) = editor
|
||||
&& let Some(result) = connection
|
||||
.console_transactions
|
||||
.execute_auto(editor, &pool, statement, skip, max_rows, cancel, schema)
|
||||
.await?
|
||||
{
|
||||
return Ok(result);
|
||||
}
|
||||
if paging && session.is_none() && (skip > 0 || protected) && pool.keeps_cursors() && cursor {
|
||||
let key = conn::CursorKey::new(id, statement, schema).with_console(console);
|
||||
let started = std::time::Instant::now();
|
||||
@@ -2188,6 +2209,7 @@ impl DbManager {
|
||||
conn.discard().await;
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
conn.release_after(statement, pool.driver()).await;
|
||||
return r;
|
||||
};
|
||||
if pool.driver() == DbDriver::Clickhouse {
|
||||
@@ -2208,6 +2230,12 @@ impl DbManager {
|
||||
if self.source(id)?.driver == DbDriver::Clickhouse {
|
||||
return Err(IdeError::invalid("ClickHouse manual transactions are unsupported"));
|
||||
}
|
||||
if self.source(id)?.driver != DbDriver::Postgres
|
||||
&& let Some(connection) = self.opened_connection(id)
|
||||
{
|
||||
// Their statements now run in the transaction of the whole data source.
|
||||
connection.console_transactions.release_all_auto().await;
|
||||
}
|
||||
self.sessions.lock().entry(id.to_owned()).or_default();
|
||||
} else {
|
||||
let session = self.sessions.lock().remove(id);
|
||||
@@ -2237,7 +2265,9 @@ impl DbManager {
|
||||
return Err(IdeError::invalid("Scoped manual transactions require a PostgreSQL data source"));
|
||||
}
|
||||
if manual {
|
||||
self.connection(id).await?.console_transactions.enable(console)
|
||||
let connection = self.connection(id).await?;
|
||||
connection.console_transactions.release_auto(console).await;
|
||||
connection.console_transactions.enable(console)
|
||||
} else {
|
||||
if let Some(connection) = self.opened_connection(id) {
|
||||
connection.console_transactions.release(console).await?;
|
||||
@@ -2443,10 +2473,17 @@ mod tests {
|
||||
DataSource { url_only: true, ..source.clone() },
|
||||
DataSource { plugin_owner: Some("sample".into()), ..source.clone() },
|
||||
DataSource { driver: DbDriver::Jdbc, ..source.clone() },
|
||||
DataSource { driver: DbDriver::Sqlite, ..source.clone() },
|
||||
DataSource { driver: DbDriver::Snowflake, ..source.clone() },
|
||||
DataSource { ssh: Some(DbSsh { enabled: true, ..Default::default() }), ..source.clone() },
|
||||
] {
|
||||
assert!(db.approve_external_tunnel(&bad).await.is_err());
|
||||
}
|
||||
// Every driver an SSH tunnel can carry can use a helper too (kubectl port-forward and the like).
|
||||
for driver in [DbDriver::Postgres, DbDriver::Mysql, DbDriver::SqlServer, DbDriver::Clickhouse, DbDriver::Oracle]
|
||||
{
|
||||
assert!(db.external_config(&DataSource { driver, ..source.clone() }).is_ok(), "{driver:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::console_session::{ConsoleSession, MAX_SESSIONS};
|
||||
use crate::{ConsoleId, Held, Pool, QueryResult};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
@@ -144,14 +145,23 @@ impl ManualSession {
|
||||
|
||||
pub(super) struct ConsoleTransactions {
|
||||
sessions: Mutex<HashMap<ConsoleKey, Session>>,
|
||||
/// Consoles in auto-commit mode.
|
||||
auto: Mutex<HashMap<ConsoleKey, Arc<ConsoleSession>>>,
|
||||
closed: CancellationToken,
|
||||
/// The four-slot pool also serves ordinary work and one retained result cursor.
|
||||
pub(super) capacity: Arc<Semaphore>,
|
||||
auto_capacity: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl Default for ConsoleTransactions {
|
||||
fn default() -> Self {
|
||||
Self { sessions: Mutex::default(), closed: CancellationToken::new(), capacity: Arc::new(Semaphore::new(2)) }
|
||||
Self {
|
||||
sessions: Mutex::default(),
|
||||
auto: Mutex::default(),
|
||||
closed: CancellationToken::new(),
|
||||
capacity: Arc::new(Semaphore::new(2)),
|
||||
auto_capacity: Arc::new(Semaphore::new(MAX_SESSIONS as usize)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,7 +188,43 @@ impl ConsoleTransactions {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `statement` in the console's session; `None` when it has none and needs none.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) async fn execute_auto(
|
||||
&self,
|
||||
console: ConsoleId<'_>,
|
||||
pool: &Pool,
|
||||
statement: &str,
|
||||
skip: usize,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
schema: Option<&str>,
|
||||
) -> IdeResult<Option<QueryResult>> {
|
||||
let session = {
|
||||
let mut auto = self.auto.lock();
|
||||
if self.closed.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
auto.entry(key(console)).or_default().clone()
|
||||
};
|
||||
// Boxed: the connect inside would double the size of every statement's future.
|
||||
Box::pin(session.execute(pool, &self.auto_capacity, statement, skip, max_rows, cancel, schema)).await
|
||||
}
|
||||
|
||||
pub(super) async fn release_auto(&self, console: ConsoleId<'_>) {
|
||||
let session = self.auto.lock().remove(&key(console));
|
||||
if let Some(session) = session {
|
||||
session.retire().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn release_all_auto(&self) {
|
||||
let sessions = std::mem::take(&mut *self.auto.lock());
|
||||
futures::future::join_all(sessions.values().map(|session| session.retire())).await;
|
||||
}
|
||||
|
||||
pub(super) async fn release(&self, console: ConsoleId<'_>) -> IdeResult<()> {
|
||||
self.release_auto(console).await;
|
||||
let session = self.sessions.lock().remove(&key(console));
|
||||
if let Some(session) = session {
|
||||
session.retire().await?;
|
||||
@@ -198,5 +244,6 @@ impl ConsoleTransactions {
|
||||
for session in sessions.into_values() {
|
||||
let _ = session.rollback_and_release().await;
|
||||
}
|
||||
self.release_all_auto().await;
|
||||
}
|
||||
}
|
||||
@@ -203,7 +203,12 @@ impl OraclePool {
|
||||
/// A connection taken out of the pool for one statement or a held session.
|
||||
pub async fn get(&self) -> IdeResult<OracleConnection> {
|
||||
let pooled = self.pool.get_owned().await.map_err(|e| pool_err(e).into_ide())?;
|
||||
Ok(OracleConnection { state: self.state.clone(), pooled })
|
||||
Ok(OracleConnection { state: self.state.clone(), pooled: crate::conn::Lease::Pooled(pooled) })
|
||||
}
|
||||
|
||||
pub(crate) async fn open_own(&self) -> IdeResult<OracleConnection> {
|
||||
let own = self.pool.dedicated_connection().await.map_err(OracleError::into_ide)?;
|
||||
Ok(OracleConnection { state: self.state.clone(), pooled: crate::conn::Lease::Own(own) })
|
||||
}
|
||||
|
||||
pub fn is_closed(&self) -> bool {
|
||||
@@ -273,7 +278,7 @@ impl ManageConnection for OracleConnectionManager {
|
||||
/// unless its statement was cancelled (then it is discarded).
|
||||
pub struct OracleConnection {
|
||||
state: Arc<State>,
|
||||
pooled: bb8::PooledConnection<'static, OracleConnectionManager>,
|
||||
pooled: crate::conn::Lease<OracleConnectionManager>,
|
||||
}
|
||||
|
||||
impl OracleConnection {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//! statement valid, which the ignored live test does for the commands that only read.
|
||||
|
||||
use super::tests::{CLOSED_OK, LOGIN_OK, bind, ok, result, serve, source};
|
||||
use super::{first_word, is_write};
|
||||
use super::{Use, first_word, is_write, use_kind};
|
||||
use crate::conn::Pool;
|
||||
use crate::source::DbDriver;
|
||||
use crate::split::split;
|
||||
@@ -106,11 +106,16 @@ async fn every_command_reaches_the_server_as_written_and_its_answer_is_read() {
|
||||
let mut replies = vec![ok(LOGIN_OK)];
|
||||
let mut entered = true;
|
||||
for c in commands.iter().filter(|c| !transfers(c)) {
|
||||
if !entered && first_word(&c.sql) != "USE" {
|
||||
// A role switch enters the schema first, like a statement that runs in it.
|
||||
let switch = use_kind(&c.sql);
|
||||
if !entered && matches!(switch, None | Some(Use::Role)) {
|
||||
replies.push(ok(status.clone()));
|
||||
}
|
||||
// These leave the session wherever they went: its schema is entered again afterwards.
|
||||
entered = !matches!(first_word(&c.sql).as_str(), "USE" | "CALL" | "EXECUTE");
|
||||
// A warehouse leaves it as it was.
|
||||
if switch != Some(Use::Warehouse) {
|
||||
entered = switch != Some(Use::Place) && !matches!(first_word(&c.sql).as_str(), "CALL" | "EXECUTE");
|
||||
}
|
||||
let dml = matches!(first_word(&c.sql).as_str(), "INSERT" | "UPDATE" | "DELETE" | "MERGE");
|
||||
replies.push(ok(if c.reads && first_word(&c.sql) != "USE" {
|
||||
rows.clone()
|
||||
|
||||
@@ -259,12 +259,17 @@ pub(crate) async fn catalog(pool: &SnowflakePool, database: &str) -> IdeResult<V
|
||||
pub(crate) async fn session(pool: &SnowflakePool) -> IdeResult<crate::SessionContext> {
|
||||
// The consoles' session: `USE WAREHOUSE` / `USE ROLE` there is what the pickers show.
|
||||
let sql = "SELECT CURRENT_WAREHOUSE(), CURRENT_ROLE(), CURRENT_AVAILABLE_ROLES()";
|
||||
let current = pool.execute(sql, 1, &CancellationToken::new()).await?.rows;
|
||||
// It names no table: the role just switched to may not use this target's schema.
|
||||
let cancel = CancellationToken::new();
|
||||
let current = pool.execute_here(sql, 1, &cancel).await?.rows;
|
||||
let cell = |i: usize| current.first().and_then(|r| r.get(i).cloned().flatten()).unwrap_or_default();
|
||||
let mut roles: Vec<String> = serde_json::from_str(&cell(2)).unwrap_or_default();
|
||||
roles.sort();
|
||||
let warehouses = match show(pool, "SHOW WAREHOUSES").await {
|
||||
Ok(shown) => shown.values("name").flatten().map(str::to_owned).collect(),
|
||||
let warehouses = match pool.execute_here("SHOW WAREHOUSES", MAX_ROWS, &cancel).await {
|
||||
Ok(result) => {
|
||||
let shown = Shown { columns: result.columns.into_iter().map(|c| c.name).collect(), rows: result.rows };
|
||||
shown.values("name").flatten().map(str::to_owned).collect()
|
||||
}
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
Ok(crate::SessionContext { warehouse: cell(0), role: cell(1), warehouses, roles })
|
||||
|
||||
@@ -209,7 +209,8 @@ fn typed(name: &str) -> String {
|
||||
crate::sql::quote_ident(crate::DbDriver::Snowflake, &name)
|
||||
}
|
||||
|
||||
fn first_word(sql: &str) -> String {
|
||||
/// `sql` without the comments and blanks it starts with.
|
||||
fn skip_comments(sql: &str) -> &str {
|
||||
let mut sql = sql.trim_start();
|
||||
loop {
|
||||
if let Some(rest) = sql.strip_prefix("--").or_else(|| sql.strip_prefix("//")) {
|
||||
@@ -220,7 +221,41 @@ fn first_word(sql: &str) -> String {
|
||||
break;
|
||||
}
|
||||
}
|
||||
sql.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').next().unwrap_or_default().to_ascii_uppercase()
|
||||
sql
|
||||
}
|
||||
|
||||
fn word(sql: &str) -> &str {
|
||||
sql.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').next().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn first_word(sql: &str) -> String {
|
||||
word(skip_comments(sql)).to_ascii_uppercase()
|
||||
}
|
||||
|
||||
/// What a `USE` statement switches.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Use {
|
||||
/// `USE ROLE`, `USE SECONDARY ROLES`: what the session may reach changes, not where it is.
|
||||
Role,
|
||||
/// `USE WAREHOUSE`: neither.
|
||||
Warehouse,
|
||||
/// `USE DATABASE`, `USE SCHEMA`, `USE <name>`: the session moves.
|
||||
Place,
|
||||
}
|
||||
|
||||
fn use_kind(sql: &str) -> Option<Use> {
|
||||
let sql = skip_comments(sql);
|
||||
let first = word(sql);
|
||||
if !first.eq_ignore_ascii_case("USE") {
|
||||
return None;
|
||||
}
|
||||
let rest = skip_comments(&sql[first.len()..]);
|
||||
// `USE "ROLE"` is a database of that name.
|
||||
Some(match word(rest).to_ascii_uppercase().as_str() {
|
||||
"ROLE" | "SECONDARY" => Use::Role,
|
||||
"WAREHOUSE" => Use::Warehouse,
|
||||
_ => Use::Place,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `sql` may change data or objects (a read-only data source refuses it).
|
||||
@@ -657,17 +692,33 @@ impl SnowflakePool {
|
||||
() = self.closed.cancelled() => return Err(closed()),
|
||||
turn = self.lane().turn.lock() => turn,
|
||||
};
|
||||
let switch = use_kind(sql);
|
||||
// A `USE` needs no schema to run in, and may be what makes the schema reachable. Ending a
|
||||
// transaction needs none either, and must not fail because the schema is gone meanwhile.
|
||||
let context = match first_word(sql).as_str() {
|
||||
"USE" | "COMMIT" | "ROLLBACK" => None,
|
||||
let first = first_word(sql);
|
||||
let context = match first.as_str() {
|
||||
"USE" => {
|
||||
// The role being left may use this schema and the next one may not: the session
|
||||
// goes there first, and stays there, as a session of its own would. Refused: the
|
||||
// new role may be the one that can.
|
||||
if switch == Some(Use::Role)
|
||||
&& let Err(error) = self.enter(schema, cancel).await
|
||||
&& error.kind != ErrorKind::InvalidInput
|
||||
{
|
||||
return Err(error);
|
||||
}
|
||||
None
|
||||
}
|
||||
"COMMIT" | "ROLLBACK" => None,
|
||||
_ => {
|
||||
self.enter(schema, cancel).await?;
|
||||
self.context(schema)
|
||||
}
|
||||
};
|
||||
// These can move the session to another database or schema.
|
||||
let moves = matches!(first_word(sql).as_str(), "USE" | "CALL" | "EXECUTE");
|
||||
// These can move the session to another database or schema. A role or a warehouse does
|
||||
// not: the schema is not asked for again, which the new role may not be allowed to use
|
||||
// while its statements name what they read in full.
|
||||
let moves = switch == Some(Use::Place) || matches!(first.as_str(), "CALL" | "EXECUTE");
|
||||
let result = self.statement(sql, skip, max_rows, Lost::Enter(context.as_deref()), cancel).await;
|
||||
if moves {
|
||||
*self.lane().context.lock() = None;
|
||||
@@ -675,18 +726,45 @@ impl SnowflakePool {
|
||||
result.map_err(|error| explain_use(sql, error))
|
||||
}
|
||||
|
||||
/// A statement about the session itself (its role, its warehouse): it runs wherever the
|
||||
/// session is and leaves it there, so the session's role need not be allowed to use this
|
||||
/// target's schema.
|
||||
pub(crate) async fn execute_here(
|
||||
&self,
|
||||
sql: &str,
|
||||
max_rows: usize,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<QueryResult> {
|
||||
let _turn = tokio::select! {
|
||||
biased;
|
||||
() = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
() = self.closed.cancelled() => return Err(closed()),
|
||||
turn = self.lane().turn.lock() => turn,
|
||||
};
|
||||
self.statement(sql, 0, max_rows, Lost::Enter(None), cancel).await
|
||||
}
|
||||
|
||||
/// Puts the session under this target's database and `schema` when it is not there already.
|
||||
async fn enter(&self, schema: Option<&str>, cancel: &CancellationToken) -> IdeResult<()> {
|
||||
if let Some(wanted) = self.context(schema)
|
||||
&& self.lane().context.lock().as_deref() != Some(wanted.as_str())
|
||||
{
|
||||
*self.lane().context.lock() = None;
|
||||
// Refused (the session's role may not use this database or schema): the statement
|
||||
// does not run, since the session is still wherever it was, which may be another
|
||||
// target's database. Tried again with the next statement.
|
||||
if let Err(error) = self.statement(&wanted, 0, 0, Lost::Enter(None), cancel).await {
|
||||
// Snowflake's own refusal leaves the session where it was known to be; after
|
||||
// anything else (cancelled, the session lost) it may be anywhere.
|
||||
if error.kind != ErrorKind::InvalidInput {
|
||||
*self.lane().context.lock() = None;
|
||||
}
|
||||
let hint = if error.kind == ErrorKind::InvalidInput {
|
||||
"\nChoose a schema the current role can use, or switch roles."
|
||||
} else {
|
||||
""
|
||||
};
|
||||
return Err(IdeError {
|
||||
message: format!("{wanted} failed, so the statement was not run: {}", error.message),
|
||||
message: format!("{wanted} failed, so the statement was not run: {}{hint}", error.message),
|
||||
..error
|
||||
});
|
||||
}
|
||||
|
||||
@@ -764,22 +764,122 @@ async fn a_console_schema_is_switched_with_its_statement_and_only_when_needed()
|
||||
);
|
||||
}
|
||||
|
||||
fn status() -> String {
|
||||
json!({ "success": true, "data": { "rowtype": [{ "name": "status", "type": "text" }],
|
||||
"rowset": [["Statement executed successfully."]], "queryResultFormat": "json", "statementTypeId": 0x5000 } })
|
||||
.to_string()
|
||||
}
|
||||
|
||||
const REFUSED: &str = r#"{"success":false,"code":"002043","message":"SQL compilation error:\nObject does not exist, or operation cannot be performed."}"#;
|
||||
|
||||
#[test]
|
||||
fn a_use_statement_says_whether_it_moves_the_session() {
|
||||
assert_eq!(use_kind("use role auditor"), Some(Use::Role));
|
||||
assert_eq!(use_kind("-- admin\n/* now */ USE /* the */ ROLE \"Auditor\""), Some(Use::Role));
|
||||
assert_eq!(use_kind("Use Secondary Roles ALL"), Some(Use::Role));
|
||||
assert_eq!(use_kind("use warehouse wh"), Some(Use::Warehouse));
|
||||
assert_eq!(use_kind("use database d"), Some(Use::Place));
|
||||
assert_eq!(use_kind("use schema d.s"), Some(Use::Place));
|
||||
assert_eq!(use_kind("use d.s"), Some(Use::Place));
|
||||
// A database called ROLE.
|
||||
assert_eq!(use_kind("use \"ROLE\""), Some(Use::Place));
|
||||
assert_eq!(use_kind("use"), Some(Use::Place));
|
||||
assert_eq!(use_kind("select 'use role x'"), None);
|
||||
assert_eq!(use_kind("user_defined()"), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_role_that_may_not_use_the_schema_runs_nothing_elsewhere() {
|
||||
let status = || {
|
||||
json!({ "success": true, "data": { "rowtype": [{ "name": "status", "type": "text" }],
|
||||
"rowset": [["Statement executed successfully."]], "queryResultFormat": "json", "statementTypeId": 0x5000 } })
|
||||
.to_string()
|
||||
};
|
||||
let refused = r#"{"success":false,"code":"002043","message":"SQL compilation error:\nObject does not exist, or operation cannot be performed."}"#;
|
||||
async fn a_role_switch_keeps_the_session_where_it_is() {
|
||||
let (listener, port) = bind().await;
|
||||
// use role | the schema is refused, the statement is not sent | asked again, refused again |
|
||||
// use role back, the schema is entered, the statement runs
|
||||
// The schema is not asked for again after a role or a warehouse: the new role may not use it,
|
||||
// and statements that name what they read in full still run.
|
||||
let replies =
|
||||
vec![ok(LOGIN_OK), ok(status()), ok(one()), ok(status()), ok(one()), ok(status()), ok(one()), ok(CLOSED_OK)];
|
||||
let server = serve(listener, replies);
|
||||
let pool = Pool::connect(&source(port), None, None).await.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let statements =
|
||||
["use role auditor", "select 1", "USE WAREHOUSE \"Big\"", "select 2", "use secondary roles all", "select 3"];
|
||||
for sql in statements {
|
||||
pool.execute(sql, 1, &cancel).await.unwrap();
|
||||
}
|
||||
pool.close().await;
|
||||
let sent: Vec<String> =
|
||||
server.await.unwrap()[1..7].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(sent, statements);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_role_switch_first_enters_the_consoles_schema() {
|
||||
let (listener, port) = bind().await;
|
||||
// select 1 in PUBLIC | the console's schema, while the role being left may use it, use role |
|
||||
// select 2 without asking for the schema again
|
||||
let replies = vec![ok(LOGIN_OK), ok(one()), ok(status()), ok(status()), ok(one()), ok(CLOSED_OK)];
|
||||
let server = serve(listener, replies);
|
||||
let pool = Pool::connect(&source(port), None, None).await.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
pool.execute("select 1", 1, &cancel).await.unwrap();
|
||||
let mut console = crate::conn::Held::acquire(&pool).await.unwrap();
|
||||
console.apply_context(Some("SALES")).await.unwrap();
|
||||
console.execute(&pool, "use role auditor", 0, &cancel).await.unwrap();
|
||||
console.execute(&pool, "select 2", 1, &cancel).await.unwrap();
|
||||
pool.close().await;
|
||||
let sent: Vec<String> =
|
||||
server.await.unwrap()[1..5].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect();
|
||||
assert_eq!(sent, ["select 1", "USE SCHEMA \"ANALYTICS\".\"SALES\"", "use role auditor", "select 2"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reading_the_role_and_warehouse_leaves_the_session_where_it_is() {
|
||||
let (listener, port) = bind().await;
|
||||
let current = json!({ "success": true, "data": { "rowtype": [{ "name": "W", "type": "text" },
|
||||
{ "name": "R", "type": "text" }, { "name": "A", "type": "text" }],
|
||||
"rowset": [["WH", "AUDITOR", "[\"AUDITOR\",\"ANALYST\"]"]], "queryResultFormat": "json" } })
|
||||
.to_string();
|
||||
let warehouses = json!({ "success": true, "data": { "rowtype": [{ "name": "name", "type": "text" }],
|
||||
"rowset": [["AUDIT_WH"]], "queryResultFormat": "json" } })
|
||||
.to_string();
|
||||
// Both pickers read the console session, where the new role is active.
|
||||
let replies = vec![ok(LOGIN_OK), ok(status()), ok(status()), ok(current), ok(warehouses), ok(one()), ok(CLOSED_OK)];
|
||||
let server = serve(listener, replies);
|
||||
let pool = Pool::connect(&source(port), None, None).await.unwrap();
|
||||
let Pool::Snowflake(snowflake) = &pool else { unreachable!() };
|
||||
let cancel = CancellationToken::new();
|
||||
let mut console = crate::conn::Held::acquire(&pool).await.unwrap();
|
||||
console.apply_context(Some("SALES")).await.unwrap();
|
||||
console.execute(&pool, "use role auditor", 0, &cancel).await.unwrap();
|
||||
let session = meta::session(snowflake).await.unwrap();
|
||||
assert_eq!((session.role.as_str(), session.roles.len()), ("AUDITOR", 2));
|
||||
assert_eq!(session.warehouses, ["AUDIT_WH"]);
|
||||
console.execute(&pool, "select 1", 1, &cancel).await.unwrap();
|
||||
pool.close().await;
|
||||
let seen = server.await.unwrap();
|
||||
let sent: Vec<String> = seen.iter().filter_map(|r| r.json()["sqlText"].as_str().map(str::to_owned)).collect();
|
||||
assert_eq!(
|
||||
sent,
|
||||
[
|
||||
"USE SCHEMA \"ANALYTICS\".\"SALES\"",
|
||||
"use role auditor",
|
||||
"SELECT CURRENT_WAREHOUSE(), CURRENT_ROLE(), CURRENT_AVAILABLE_ROLES()",
|
||||
"SHOW WAREHOUSES",
|
||||
"select 1"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_schema_the_role_may_not_use_runs_nothing_elsewhere() {
|
||||
let (listener, port) = bind().await;
|
||||
// use role in PUBLIC | the console's schema is refused, its statement is not sent | select 2
|
||||
// in PUBLIC, where the session still is | refused again | refused before use role, which is
|
||||
// sent all the same | the schema is entered, select 4
|
||||
let replies = vec![
|
||||
ok(LOGIN_OK),
|
||||
ok(status()),
|
||||
ok(refused),
|
||||
ok(refused),
|
||||
ok(REFUSED),
|
||||
ok(one()),
|
||||
ok(REFUSED),
|
||||
ok(REFUSED),
|
||||
ok(status()),
|
||||
ok(status()),
|
||||
ok(one()),
|
||||
@@ -788,8 +888,10 @@ async fn a_role_that_may_not_use_the_schema_runs_nothing_elsewhere() {
|
||||
let server = serve(listener, replies);
|
||||
let pool = Pool::connect(&source(port), None, None).await.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let mut console = crate::conn::Held::acquire(&pool).await.unwrap();
|
||||
console.apply_context(Some("SALES")).await.unwrap();
|
||||
pool.execute("use role auditor", 0, &cancel).await.unwrap();
|
||||
let error = pool.execute("delete from t", 1, &cancel).await.unwrap_err();
|
||||
let error = console.execute(&pool, "delete from t", 1, &cancel).await.unwrap_err();
|
||||
assert!(
|
||||
error.message.contains("USE SCHEMA")
|
||||
&& error.message.contains("was not run")
|
||||
@@ -797,14 +899,46 @@ async fn a_role_that_may_not_use_the_schema_runs_nothing_elsewhere() {
|
||||
"{}",
|
||||
error.message
|
||||
);
|
||||
assert!(pool.execute("select 2", 1, &cancel).await.is_err());
|
||||
pool.execute("use role analyst", 0, &cancel).await.unwrap();
|
||||
pool.execute("select 3", 1, &cancel).await.unwrap();
|
||||
pool.execute("select 2", 1, &cancel).await.unwrap();
|
||||
assert!(console.execute(&pool, "select 3", 1, &cancel).await.is_err());
|
||||
console.execute(&pool, "use role analyst", 0, &cancel).await.unwrap();
|
||||
console.execute(&pool, "select 4", 1, &cancel).await.unwrap();
|
||||
pool.close().await;
|
||||
let sent: Vec<String> =
|
||||
server.await.unwrap()[1..7].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect();
|
||||
let schema = "USE SCHEMA \"ANALYTICS\".\"PUBLIC\"";
|
||||
assert_eq!(sent, ["use role auditor", schema, schema, "use role analyst", schema, "select 3"]);
|
||||
server.await.unwrap()[1..9].iter().map(|r| r.json()["sqlText"].as_str().unwrap().to_owned()).collect();
|
||||
let sales = "USE SCHEMA \"ANALYTICS\".\"SALES\"";
|
||||
assert_eq!(sent, ["use role auditor", sales, "select 2", sales, sales, "use role analyst", sales, "select 4"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_schema_refusal_after_login_does_not_restore_the_old_context() {
|
||||
let (listener, port) = bind().await;
|
||||
let gone = r#"{"success":false,"code":"390114","message":"Session closed."}"#;
|
||||
let server = serve(
|
||||
listener,
|
||||
vec![
|
||||
ok(LOGIN_OK),
|
||||
ok(status()),
|
||||
ok(status()),
|
||||
ok(gone),
|
||||
ok(LOGIN_OK),
|
||||
ok(REFUSED),
|
||||
ok(status()),
|
||||
ok(one()),
|
||||
ok(CLOSED_OK),
|
||||
],
|
||||
);
|
||||
let pool = Pool::connect(&source(port), None, None).await.unwrap();
|
||||
let cancel = CancellationToken::new();
|
||||
let mut sales = crate::conn::Held::acquire(&pool).await.unwrap();
|
||||
sales.apply_context(Some("SALES")).await.unwrap();
|
||||
sales.execute(&pool, "use role auditor", 0, &cancel).await.unwrap();
|
||||
assert!(pool.execute("select 1", 1, &cancel).await.is_err());
|
||||
sales.execute(&pool, "select 2", 1, &cancel).await.unwrap();
|
||||
pool.close().await;
|
||||
let seen = server.await.unwrap();
|
||||
assert_eq!(seen[6].json()["sqlText"], "USE SCHEMA \"ANALYTICS\".\"SALES\"");
|
||||
assert_eq!(seen[7].json()["sqlText"], "select 2");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Splitting SQL scripts into statements (`;`-terminated), aware of string
|
||||
//! literals, quoted identifiers, comments and PostgreSQL dollar quoting.
|
||||
//! MySQL strings take backslash escapes (no `NO_BACKSLASH_ESCAPES`) and double
|
||||
//! quotes (no `ANSI_QUOTES`), its defaults; the console's lexer.ts reads them alike.
|
||||
//! Offsets are UTF-16 code units, like everything on the IPC boundary.
|
||||
|
||||
use crate::DbDriver;
|
||||
@@ -22,12 +24,13 @@ enum State {
|
||||
Single,
|
||||
Double,
|
||||
Backtick,
|
||||
Bracket,
|
||||
LineComment,
|
||||
BlockComment,
|
||||
}
|
||||
|
||||
// Starts just after the opening `/*`. ClickHouse supports nested block comments.
|
||||
fn after_clickhouse_block_comment(mut text: &str) -> &str {
|
||||
// Starts just after the opening `/*`.
|
||||
fn after_nested_block_comment(mut text: &str) -> &str {
|
||||
let mut depth = 1usize;
|
||||
while let Some(at) = text.find(['/', '*']) {
|
||||
text = &text[at..];
|
||||
@@ -55,7 +58,7 @@ pub(super) fn clickhouse_keyword<'a>(sql: &mut &'a str) -> Option<&'a str> {
|
||||
if let Some(comment) = text.strip_prefix('#').or_else(|| text.strip_prefix("--")) {
|
||||
text = comment.split_once('\n').map_or("", |(_, rest)| rest);
|
||||
} else if let Some(comment) = text.strip_prefix("/*") {
|
||||
text = after_clickhouse_block_comment(comment);
|
||||
text = after_nested_block_comment(comment);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
@@ -76,6 +79,10 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
// PL/SQL: `;` inside BEGIN…END / DECLARE…END blocks does not terminate a statement.
|
||||
let plsql = driver == DbDriver::Oracle;
|
||||
let snowflake = driver == DbDriver::Snowflake;
|
||||
let postgres = driver == DbDriver::Postgres;
|
||||
let sqlite = driver == DbDriver::Sqlite;
|
||||
let sql_server = driver == DbDriver::SqlServer;
|
||||
let nested_comments = clickhouse || postgres || sql_server;
|
||||
let chars: Vec<(usize, char)> = text.char_indices().collect();
|
||||
// UTF-16 offset of each char index (plus the end).
|
||||
let mut u16_at = Vec::with_capacity(chars.len() + 1);
|
||||
@@ -105,6 +112,8 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
let mut script = false;
|
||||
// The segment may carry a Scripting block as its body (`CREATE TASK … AS BEGIN … END`).
|
||||
let mut defines = false;
|
||||
// The open string is PostgreSQL's `E'…'`.
|
||||
let mut escape_string = false;
|
||||
let push = |out: &mut Vec<SqlStatement>, s: usize, e: usize, has_code: bool| {
|
||||
if !has_code {
|
||||
return;
|
||||
@@ -164,6 +173,18 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
defines = false;
|
||||
}
|
||||
';' => has_code = true,
|
||||
// Words are read whole: the `E` of `E'…'` starts one, and a `$` inside one quotes nothing.
|
||||
_ if postgres && (c.is_alphabetic() || c == '_') => {
|
||||
has_code = true;
|
||||
if matches!(c, 'E' | 'e') && next == Some('\'') {
|
||||
(state, escape_string) = (State::Single, true);
|
||||
i += 1;
|
||||
} else {
|
||||
while chars.get(i + 1).is_some_and(|&(_, c)| c.is_alphanumeric() || matches!(c, '_' | '$')) {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
'\'' => {
|
||||
state = State::Single;
|
||||
has_code = true;
|
||||
@@ -172,13 +193,17 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
state = State::Double;
|
||||
has_code = true;
|
||||
}
|
||||
'`' if mysql || clickhouse => {
|
||||
'`' if mysql || clickhouse || sqlite => {
|
||||
state = State::Backtick;
|
||||
has_code = true;
|
||||
}
|
||||
'[' if sqlite || sql_server => {
|
||||
state = State::Bracket;
|
||||
has_code = true;
|
||||
}
|
||||
'/' if next == Some('*') => {
|
||||
if clickhouse {
|
||||
let rest = after_clickhouse_block_comment(&text[byte_at(i + 2)..]);
|
||||
if nested_comments {
|
||||
let rest = after_nested_block_comment(&text[byte_at(i + 2)..]);
|
||||
let end = text.len() - rest.len();
|
||||
i = chars.partition_point(|&(offset, _)| offset < end);
|
||||
continue;
|
||||
@@ -199,7 +224,10 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
block = false;
|
||||
package = false;
|
||||
}
|
||||
'-' if next == Some('-') => {
|
||||
// MySQL reads `5--1` as a subtraction.
|
||||
'-' if next == Some('-')
|
||||
&& (!mysql || chars.get(i + 2).is_none_or(|&(_, c)| c == ' ' || c.is_ascii_control())) =>
|
||||
{
|
||||
state = State::LineComment;
|
||||
i += 1;
|
||||
}
|
||||
@@ -213,7 +241,7 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
state = State::LineComment;
|
||||
i += 1;
|
||||
}
|
||||
'$' if driver == DbDriver::Postgres || snowflake => {
|
||||
'$' if postgres || snowflake => {
|
||||
// `$tag$ … $tag$` (tag may be empty); `$1` parameters are not quotes.
|
||||
let rest = &text[byte_at(i)..];
|
||||
let tag_len = rest[1..].find('$').filter(|&n| {
|
||||
@@ -289,18 +317,18 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
_ => {}
|
||||
},
|
||||
State::Single => {
|
||||
if (mysql || clickhouse || snowflake) && c == '\\' {
|
||||
if (mysql || clickhouse || snowflake || escape_string) && c == '\\' {
|
||||
i += 1;
|
||||
} else if c == '\'' {
|
||||
if next == Some('\'') {
|
||||
i += 1;
|
||||
} else {
|
||||
state = State::Code;
|
||||
(state, escape_string) = (State::Code, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
State::Double => {
|
||||
if clickhouse && c == '\\' {
|
||||
if (mysql || clickhouse) && c == '\\' {
|
||||
i += 1;
|
||||
} else if c == '"' {
|
||||
if next == Some('"') {
|
||||
@@ -317,6 +345,13 @@ pub fn split(text: &str, driver: DbDriver) -> Vec<SqlStatement> {
|
||||
state = State::Code;
|
||||
}
|
||||
}
|
||||
State::Bracket => {
|
||||
if sql_server && c == ']' && next == Some(']') {
|
||||
i += 1;
|
||||
} else if c == ']' {
|
||||
state = State::Code;
|
||||
}
|
||||
}
|
||||
State::LineComment => {
|
||||
if c == '\n' {
|
||||
state = State::Code;
|
||||
@@ -510,6 +545,76 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_and_sql_server_nest_block_comments() {
|
||||
let sql = "/* outer /* inner */ ; DELETE FROM b; */ SELECT 1";
|
||||
for driver in [DbDriver::Postgres, DbDriver::SqlServer] {
|
||||
assert_eq!(texts(&format!("{sql}; SELECT 2"), driver), vec![sql, "SELECT 2"]);
|
||||
assert_eq!(statement_at(sql, 25, driver).map(|s| s.text).as_deref(), Some(sql));
|
||||
assert_eq!(texts("/* open /* ; */ ; DELETE FROM b", driver), Vec::<String>::new());
|
||||
}
|
||||
for driver in [DbDriver::Mysql, DbDriver::Sqlite, DbDriver::Oracle, DbDriver::Snowflake] {
|
||||
assert_eq!(texts("/* a /* b */ SELECT 1; SELECT 2", driver), vec!["/* a /* b */ SELECT 1", "SELECT 2"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postgres_escape_strings_and_dollars_in_names() {
|
||||
for sql in [r"SELECT E'it\'s; DELETE FROM b; --'", r"SELECT e'a\\', E'it''s; \';'"] {
|
||||
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Postgres), vec![sql, "SELECT 2"]);
|
||||
assert_eq!(statement_at(sql, 22, DbDriver::Postgres).map(|s| s.text).as_deref(), Some(sql));
|
||||
}
|
||||
// A backslash is plain in other strings, also after a word that ends in `e`.
|
||||
for sql in [r"SELECT 'a\'", r"SELECT date'\'", r"SELECT U&'\'", r#"SELECT "a\""#] {
|
||||
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Postgres), vec![sql, "SELECT 2"]);
|
||||
}
|
||||
// A `$` inside a name opens no dollar quote.
|
||||
assert_eq!(
|
||||
texts("SELECT a$b$ FROM t; SELECT b$b$ FROM t", DbDriver::Postgres),
|
||||
vec!["SELECT a$b$ FROM t", "SELECT b$b$ FROM t"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mysql_double_quoted_strings_and_dashes() {
|
||||
let sql = r#"SELECT "say \"hi; DELETE FROM b; \"", 'a''b;', "c"";", `d``;`"#;
|
||||
assert_eq!(texts(&format!("{sql}; SELECT 2"), DbDriver::Mysql), vec![sql, "SELECT 2"]);
|
||||
assert_eq!(statement_at(sql, 24, DbDriver::Mysql).map(|s| s.text).as_deref(), Some(sql));
|
||||
// `--` starts a comment only before whitespace, a control character or the end.
|
||||
assert_eq!(texts("SELECT 5--1; SELECT 2", DbDriver::Mysql), vec!["SELECT 5--1", "SELECT 2"]);
|
||||
for comment in ["-- a;", "--\ta;", "--"] {
|
||||
assert_eq!(texts(&format!("SELECT 5 {comment}\n+ 1; SELECT 2"), DbDriver::Mysql).len(), 2);
|
||||
assert_eq!(texts(&format!("SELECT 1; {comment}"), DbDriver::Mysql), vec!["SELECT 1"]);
|
||||
}
|
||||
for driver in [DbDriver::Postgres, DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Oracle] {
|
||||
assert_eq!(texts("SELECT 5--1; SELECT 2", driver), vec!["SELECT 5--1; SELECT 2"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bracketed_and_backtick_names() {
|
||||
for (sql, driver) in [
|
||||
("SELECT * FROM [a;b]", DbDriver::SqlServer),
|
||||
("SELECT * FROM [a]];'b]", DbDriver::SqlServer),
|
||||
("SELECT * FROM `a;b`, `c``;'d`", DbDriver::Sqlite),
|
||||
("SELECT * FROM [c;d], [it's]", DbDriver::Sqlite),
|
||||
("SELECT * FROM [e[;]", DbDriver::Sqlite),
|
||||
] {
|
||||
assert_eq!(texts(&format!("{sql}; SELECT 2"), driver), vec![sql, "SELECT 2"]);
|
||||
assert_eq!(statement_at(sql, 16, driver).map(|s| s.text).as_deref(), Some(sql));
|
||||
}
|
||||
// Array subscripts and literals elsewhere.
|
||||
assert_eq!(texts("SELECT a[1; SELECT 2", DbDriver::Postgres), vec!["SELECT a[1", "SELECT 2"]);
|
||||
assert_eq!(texts("SELECT [1; SELECT 2", DbDriver::Clickhouse), vec!["SELECT [1", "SELECT 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_keeps_literals_whole() {
|
||||
let sql = "SELECT 0; SELECT E'\\';'; SELECT 2";
|
||||
let s = statements_in(sql, 10, sql.len() as u32, DbDriver::Postgres);
|
||||
assert_eq!(s.iter().map(|s| s.text.as_str()).collect::<Vec<_>>(), vec!["SELECT E'\\';'", "SELECT 2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_offsets() {
|
||||
let sql = "select '😀';\nselect 2;";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Only an explicit desktop action can trust a helper. The project file is portable;
|
||||
//! the authorization belongs to this machine and to the reviewed destination.
|
||||
use crate::{DataSource, DbDriver, DbExternalTunnel, DbManager, DbSslMode, local_settings::persist_local};
|
||||
use crate::{DataSource, DbExternalTunnel, DbManager, DbSslMode, local_settings::persist_local};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -14,9 +14,9 @@ impl DbManager {
|
||||
if !self.local_external_tunnels {
|
||||
return Err(IdeError::invalid("External database tunnels require a local desktop project"));
|
||||
}
|
||||
if source.driver != DbDriver::Postgres || source.plugin_owner.is_some() || source.url_only {
|
||||
if !crate::tunneled(source.driver) || source.plugin_owner.is_some() || source.url_only {
|
||||
return Err(IdeError::invalid(
|
||||
"Use a user-managed PostgreSQL source with host and port for an external tunnel",
|
||||
"Use a user-managed network database source with host and port for an external tunnel",
|
||||
));
|
||||
}
|
||||
if source.ssh.as_ref().is_some_and(|ssh| ssh.enabled) {
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
use ide_core::{CancellationToken, IdeResult, error::ErrorKind};
|
||||
use ide_db::{ConsoleId, DataSource, DbDriver, DbManager, QueryResult};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
const TARGET: &str = "fixture";
|
||||
const A: ConsoleId<'static> = ConsoleId::new("main", "a.sql");
|
||||
const B: ConsoleId<'static> = ConsoleId::new("main", "b.sql");
|
||||
const ROWS: &str = "SELECT id FROM public.console_session ORDER BY id";
|
||||
|
||||
async fn run_in(db: &DbManager, console: ConsoleId<'_>, sql: &str, schema: &str) -> IdeResult<QueryResult> {
|
||||
let cancel = CancellationToken::new();
|
||||
// Boxed: one test awaiting this many statements inline overflows a debug build's stack.
|
||||
Box::pin(db.execute_in_console(TARGET, sql, 0, 10, &cancel, Some(schema), Some(console))).await
|
||||
}
|
||||
|
||||
async fn run(db: &DbManager, console: ConsoleId<'_>, sql: &str) -> IdeResult<QueryResult> {
|
||||
run_in(db, console, sql, "public").await
|
||||
}
|
||||
|
||||
async fn value(db: &DbManager, console: ConsoleId<'_>, sql: &str) -> IdeResult<String> {
|
||||
Ok(run(db, console, sql).await?.rows[0][0].clone().unwrap())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires a disposable local PostgreSQL fixture with OPENIDEA_PG_CONSOLE_PORT and console_fixture db/user"]
|
||||
async fn console_sessions_keep_transactions_settings_and_temporary_tables() -> IdeResult<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let root = dir.path();
|
||||
let ssh = Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = DbManager::new(root.into(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![DataSource {
|
||||
id: TARGET.into(),
|
||||
name: "Local PostgreSQL".into(),
|
||||
driver: DbDriver::Postgres,
|
||||
host: "127.0.0.1".into(),
|
||||
port: Some(std::env::var("OPENIDEA_PG_CONSOLE_PORT").expect("disposable fixture port").parse().unwrap()),
|
||||
user: "console_fixture".into(),
|
||||
database: "console_fixture".into(),
|
||||
..Default::default()
|
||||
}])
|
||||
.await?;
|
||||
let cancel = CancellationToken::new();
|
||||
for sql in [
|
||||
"DROP TABLE IF EXISTS public.console_session",
|
||||
"CREATE TABLE public.console_session (id int PRIMARY KEY)",
|
||||
"CREATE SCHEMA IF NOT EXISTS console_other",
|
||||
] {
|
||||
db.execute(TARGET, sql, 0, &cancel).await?;
|
||||
}
|
||||
let observer = db.pool(TARGET).await?;
|
||||
|
||||
run(&db, A, "BEGIN").await?;
|
||||
run(&db, A, "INSERT INTO console_session VALUES (1)").await?;
|
||||
let pid = value(&db, A, "SELECT pg_backend_pid()").await?;
|
||||
assert!(run(&db, B, ROWS).await?.rows.is_empty());
|
||||
assert!(observer.rows(ROWS, 10).await?.is_empty());
|
||||
run(&db, A, "ROLLBACK").await?;
|
||||
assert!(run(&db, A, ROWS).await?.rows.is_empty());
|
||||
assert_eq!(value(&db, A, "SELECT pg_backend_pid()").await?, pid);
|
||||
|
||||
run(&db, A, "SET work_mem = '77MB'").await?;
|
||||
run(&db, A, "CREATE TEMP TABLE work AS SELECT 7 AS n").await?;
|
||||
assert_eq!(value(&db, A, "SHOW work_mem").await?, "77MB");
|
||||
assert_eq!(value(&db, A, "SELECT n FROM work").await?, "7");
|
||||
assert!(run(&db, B, "SELECT n FROM work").await.is_err());
|
||||
assert_ne!(value(&db, B, "SHOW work_mem").await?, "77MB");
|
||||
|
||||
// The picker's schema is applied when it changes and leaves the user's own SET alone otherwise.
|
||||
run(&db, A, "SET search_path TO console_other").await?;
|
||||
assert_eq!(value(&db, A, "SELECT current_schema()").await?, "console_other");
|
||||
run(&db, A, "BEGIN").await?;
|
||||
assert_eq!(run_in(&db, A, "SELECT current_schema()", "pg_catalog").await?.rows, [[Some("pg_catalog".into())]]);
|
||||
assert!(run_in(&db, A, "SELECT 1/0", "pg_catalog").await.is_err());
|
||||
run(&db, A, "ROLLBACK").await?;
|
||||
assert_eq!(value(&db, A, "SELECT current_schema()").await?, "public");
|
||||
assert_eq!(value(&db, A, "SELECT pg_backend_pid()").await?, pid, "errors keep the session");
|
||||
|
||||
// Every session slot taken, both manual slots and a result cursor leave ordinary work running.
|
||||
let paths: Vec<_> = (0..4).map(|n| format!("{n}.sql")).collect();
|
||||
for path in &paths[..3] {
|
||||
run(&db, ConsoleId::new("main", path), "SET work_mem = '5MB'").await?;
|
||||
}
|
||||
let full = run(&db, ConsoleId::new("main", &paths[3]), "BEGIN").await.unwrap_err();
|
||||
assert_eq!(full.kind, ErrorKind::Unavailable);
|
||||
for path in ["m.sql", "n.sql"] {
|
||||
let console = ConsoleId::new("main", path);
|
||||
db.set_postgres_console_manual(TARGET, console, true).await?;
|
||||
run(&db, console, ROWS).await?;
|
||||
}
|
||||
let page = db
|
||||
.execute_in_console(TARGET, "SELECT generate_series(1, 1000)", 10, 10, &cancel, Some("public"), Some(B))
|
||||
.await?;
|
||||
assert!(page.has_more);
|
||||
tokio::time::timeout(Duration::from_secs(5), db.completion(TARGET)).await.expect("completion does not wait")?;
|
||||
assert_eq!(value(&db, A, "SELECT n FROM work").await?, "7");
|
||||
for path in paths[..3].iter().map(String::as_str).chain(["m.sql", "n.sql"]) {
|
||||
db.release_console(ConsoleId::new("main", path)).await?;
|
||||
}
|
||||
|
||||
// A session that ends inside a transaction is reported before anything else commits on its own.
|
||||
run(&db, A, "BEGIN").await?;
|
||||
run(&db, A, "INSERT INTO console_session VALUES (2)").await?;
|
||||
observer.rows(&format!("SELECT pg_terminate_backend({pid})"), 1).await?;
|
||||
assert!(run(&db, A, "INSERT INTO console_session VALUES (3)").await.is_err());
|
||||
assert_eq!(run(&db, A, "INSERT INTO console_session VALUES (3)").await.unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert!(run(&db, A, ROWS).await?.rows.is_empty());
|
||||
|
||||
run(&db, A, "BEGIN").await?;
|
||||
run(&db, A, "INSERT INTO console_session VALUES (4)").await?;
|
||||
let stop = CancellationToken::new();
|
||||
let (stopped, ()) = tokio::join!(
|
||||
db.execute_in_console(TARGET, "SELECT pg_sleep(8)", 0, 10, &stop, Some("public"), Some(A)),
|
||||
async {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
stop.cancel();
|
||||
}
|
||||
);
|
||||
assert_eq!(stopped.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
assert_eq!(run(&db, A, "SELECT 1").await.unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert!(observer.rows(ROWS, 10).await?.is_empty());
|
||||
|
||||
run(&db, A, "BEGIN").await?;
|
||||
run(&db, A, "INSERT INTO console_session VALUES (5)").await?;
|
||||
db.release_console(A).await?;
|
||||
run(&db, A, "BEGIN").await?;
|
||||
run(&db, A, "INSERT INTO console_session VALUES (5)").await?;
|
||||
assert!(db.set_postgres_console_manual(TARGET, A, true).await?);
|
||||
assert!(run(&db, A, ROWS).await?.rows.is_empty(), "manual mode starts its own transaction");
|
||||
db.release_console(A).await?;
|
||||
|
||||
db.execute(TARGET, "BEGIN", 0, &cancel).await?;
|
||||
db.execute_from(TARGET, "START TRANSACTION", 0, 0, &cancel, Some("public")).await?;
|
||||
let open = "SELECT count(*) FROM pg_stat_activity WHERE state LIKE 'idle in transaction%'";
|
||||
assert_eq!(observer.rows(open, 1).await?, [[Some("0".into())]]);
|
||||
|
||||
run(&db, A, "BEGIN").await?;
|
||||
tokio::time::timeout(Duration::from_secs(5), db.disconnect(TARGET)).await.expect("disconnects");
|
||||
let observer = db.pool(TARGET).await?;
|
||||
assert_eq!(observer.rows(open, 1).await?, [[Some("0".into())]]);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
//! What a SQL console in auto-commit mode keeps between its statements.
|
||||
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind};
|
||||
use ide_db::{CellValue, ConsoleId, DataSource, DbDriver, DbManager, DbRowEdit, QueryResult};
|
||||
use std::time::Duration;
|
||||
|
||||
const A: ConsoleId<'static> = ConsoleId::new("main", "a.sql");
|
||||
const B: ConsoleId<'static> = ConsoleId::new("main", "b.sql");
|
||||
const COUNT: &str = "SELECT count(*) FROM t";
|
||||
|
||||
async fn setup() -> (tempfile::TempDir, DbManager) {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().to_path_buf();
|
||||
std::fs::File::create(root.join("app.db")).unwrap();
|
||||
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
|
||||
let db = DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
|
||||
db.save_sources(vec![DataSource {
|
||||
id: "s1".into(),
|
||||
name: "app".into(),
|
||||
driver: DbDriver::Sqlite,
|
||||
file: Some("app.db".into()),
|
||||
..Default::default()
|
||||
}])
|
||||
.await
|
||||
.unwrap();
|
||||
for sql in ["CREATE TABLE t (id INTEGER PRIMARY KEY)", "INSERT INTO t VALUES (1), (2), (3)"] {
|
||||
db.execute("s1", sql, 0, &CancellationToken::new()).await.unwrap();
|
||||
}
|
||||
(tmp, db)
|
||||
}
|
||||
|
||||
async fn run(db: &DbManager, console: ConsoleId<'_>, sql: &str) -> IdeResult<QueryResult> {
|
||||
db.execute_in_console("s1", sql, 0, 10, &CancellationToken::new(), None, Some(console)).await
|
||||
}
|
||||
|
||||
async fn run_all(db: &DbManager, console: ConsoleId<'_>, script: &[&str]) -> IdeResult<()> {
|
||||
for sql in script {
|
||||
run(db, console, sql).await.map_err(|e| IdeError::invalid(format!("{sql}: {}", e.message)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn count(db: &DbManager, console: Option<ConsoleId<'_>>) -> IdeResult<String> {
|
||||
let token = CancellationToken::new();
|
||||
let result = db.execute_in_console("s1", COUNT, 0, 10, &token, None, console).await?;
|
||||
Ok(result.rows[0][0].clone().unwrap())
|
||||
}
|
||||
|
||||
async fn insert_in_table_editor(db: &DbManager, id: &str) -> IdeResult<u64> {
|
||||
let values = vec![CellValue { column: "id".into(), value: Some(id.into()) }];
|
||||
db.apply_edits("s1", "main", "t", &[DbRowEdit::Insert { values }]).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rollback_undoes_the_statements_since_begin() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
|
||||
assert_eq!(count(&db, Some(A)).await?, "0");
|
||||
assert_eq!(count(&db, Some(B)).await?, "3", "another console reads committed rows");
|
||||
assert_eq!(count(&db, None).await?, "3", "so does a statement outside any console");
|
||||
run(&db, A, "ROLLBACK").await?;
|
||||
assert_eq!(count(&db, Some(A)).await?, "3");
|
||||
run_all(&db, A, &["-- comment first\nBEGIN IMMEDIATE", "DELETE FROM t WHERE id = 1", "COMMIT"]).await?;
|
||||
assert_eq!(count(&db, Some(B)).await?, "2");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn temporary_tables_and_settings_belong_to_their_console() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["CREATE TEMP TABLE work (id INTEGER)", "PRAGMA cache_size = 123"]).await?;
|
||||
run_all(&db, A, &["INSERT INTO work SELECT id FROM t"; 3]).await?;
|
||||
assert_eq!(run(&db, A, "SELECT count(*) FROM work").await?.rows, [[Some("9".into())]]);
|
||||
assert_eq!(run(&db, A, "PRAGMA cache_size").await?.rows, [[Some("123".into())]]);
|
||||
assert!(run(&db, B, "SELECT count(*) FROM work").await.is_err());
|
||||
assert_ne!(run(&db, B, "PRAGMA cache_size").await?.rows, [[Some("123".into())]]);
|
||||
let outside = db.execute("s1", "SELECT count(*) FROM work", 10, &CancellationToken::new()).await;
|
||||
assert!(outside.is_err());
|
||||
|
||||
// A later page of the console's own result reads the same session.
|
||||
let page = db
|
||||
.execute_in_console("s1", "SELECT id FROM work ORDER BY id", 3, 3, &CancellationToken::new(), None, Some(A))
|
||||
.await?;
|
||||
assert_eq!(page.rows, vec![vec![Some("2".to_owned())]; 3]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_a_console_rolls_back_and_frees_the_file() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
|
||||
db.release_target_console(A, Some("other")).await?;
|
||||
assert_eq!(count(&db, Some(A)).await?, "0", "another target's release leaves this session alone");
|
||||
db.release_console(A).await?;
|
||||
assert_eq!(count(&db, None).await?, "3");
|
||||
assert_eq!(insert_in_table_editor(&db, "4").await?, 1);
|
||||
assert_eq!(count(&db, Some(A)).await?, "4");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disconnecting_rolls_back_an_open_transaction() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
|
||||
tokio::time::timeout(Duration::from_secs(5), db.disconnect("s1")).await.expect("the pool closes");
|
||||
assert_eq!(count(&db, Some(A)).await?, "3");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn manual_mode_ends_the_console_sessions_of_its_data_source() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
|
||||
db.set_manual_commit("s1", true).await?;
|
||||
assert_eq!(count(&db, Some(A)).await?, "3");
|
||||
run(&db, B, "INSERT INTO t VALUES (4)").await?;
|
||||
db.finish_transaction("s1", true).await?;
|
||||
db.set_manual_commit("s1", false).await?;
|
||||
assert_eq!(count(&db, Some(A)).await?, "4");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_session_without_a_transaction_leaves_the_table_editor_free() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["CREATE TEMP TABLE work (id INTEGER)", "BEGIN", "INSERT INTO t VALUES (4)", "COMMIT"]).await?;
|
||||
let token = CancellationToken::new();
|
||||
// The rows after the first stay unread on the session's connection.
|
||||
assert!(db.execute_in_console("s1", "SELECT id FROM t", 0, 1, &token, None, Some(A)).await?.has_more);
|
||||
let saved = tokio::time::timeout(Duration::from_secs(2), insert_in_table_editor(&db, "5"));
|
||||
assert_eq!(saved.await.expect("the table editor does not wait for the console")?, 1);
|
||||
assert_eq!(count(&db, Some(A)).await?, "5");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_rolls_back_and_the_next_statement_says_so() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t"]).await?;
|
||||
let slow = "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 3000000) SELECT sum(i) FROM n";
|
||||
let token = CancellationToken::new();
|
||||
let (stopped, ()) = tokio::join!(db.execute_in_console("s1", slow, 0, 10, &token, None, Some(A)), async {
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
token.cancel();
|
||||
});
|
||||
assert_eq!(stopped.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
let refused = run(&db, A, "DELETE FROM t WHERE id = 1").await.unwrap_err();
|
||||
assert_eq!(refused.kind, ErrorKind::OutOfSync, "it would commit outside the transaction: {}", refused.message);
|
||||
assert_eq!(count(&db, Some(A)).await?, "3");
|
||||
run_all(&db, A, &["BEGIN", "DELETE FROM t", "ROLLBACK"]).await?;
|
||||
assert_eq!(count(&db, None).await?, "3");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sessions_are_bounded_and_leave_ordinary_statements_their_connections() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
let paths: Vec<_> = (0..5).map(|n| format!("{n}.sql")).collect();
|
||||
let consoles: Vec<_> = paths.iter().map(|path| ConsoleId::new("main", path)).collect();
|
||||
for console in &consoles[..4] {
|
||||
run(&db, *console, "PRAGMA cache_size = 99").await?;
|
||||
}
|
||||
let refused = run(&db, consoles[4], "BEGIN").await.unwrap_err();
|
||||
assert_eq!(refused.kind, ErrorKind::Unavailable, "{}", refused.message);
|
||||
assert_eq!(count(&db, Some(consoles[4])).await?, "3", "a plain query needs no session");
|
||||
run(&db, consoles[4], "INSERT INTO t VALUES (4)").await?;
|
||||
db.completion("s1").await?;
|
||||
assert_eq!(insert_in_table_editor(&db, "5").await?, 1);
|
||||
db.release_console(consoles[0]).await?;
|
||||
run_all(&db, consoles[4], &["BEGIN", "DELETE FROM t", "ROLLBACK"]).await?;
|
||||
assert_eq!(count(&db, None).await?, "5");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_transaction_opened_outside_a_console_never_reaches_another_statement() -> IdeResult<()> {
|
||||
let (_tmp, db) = setup().await;
|
||||
let token = CancellationToken::new();
|
||||
db.execute("s1", "BEGIN", 0, &token).await?;
|
||||
db.execute("s1", "BEGIN; DELETE FROM t", 0, &token).await?;
|
||||
assert_eq!(count(&db, None).await?, "3");
|
||||
assert_eq!(insert_in_table_editor(&db, "4").await?, 1);
|
||||
db.execute("s1", "BEGIN; DELETE FROM t WHERE id = 1; COMMIT", 0, &token).await?;
|
||||
assert_eq!(count(&db, None).await?, "3");
|
||||
Ok(())
|
||||
}
|
||||
@@ -7,8 +7,8 @@
|
||||
|
||||
use crate::{
|
||||
COMPOSE_DIR, COMPOSE_FILES, COMPOSE_PROJECT, COMPOSE_SERVICE, ContainerOp, DockerAvailability, DockerContainer,
|
||||
DockerEndpoint, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject, DockerProcessList,
|
||||
DockerSnapshot, DockerVolume, split_csv,
|
||||
DockerEndpoint, DockerHostResources, DockerImage, DockerImageLayer, DockerLogLine, DockerNetwork, DockerObject,
|
||||
DockerProcessList, DockerSnapshot, DockerVolume, parse_info, split_csv,
|
||||
};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::Deserialize;
|
||||
@@ -356,6 +356,21 @@ fn server_version(addr: &Address, timeout: Duration) -> IdeResult<String> {
|
||||
.map_err(|e| IdeError::internal(format!("the Docker daemon version is not JSON: {e}")))
|
||||
}
|
||||
|
||||
/// CPU and memory capacity of `ep`'s Docker daemon / VM (`GET /info`).
|
||||
pub(crate) fn info(ep: &DockerEndpoint, timeout: Duration) -> Option<IdeResult<DockerHostResources>> {
|
||||
let addr = address(ep)?;
|
||||
Some((|| {
|
||||
let body = check(request(&addr, "GET", "/info", timeout)?)?;
|
||||
parse_info(&body).ok_or_else(|| IdeError::internal("the Docker daemon info is not JSON"))
|
||||
})())
|
||||
}
|
||||
|
||||
/// Containers of `ep`'s daemon (`GET /containers/json?all=1`).
|
||||
pub(crate) fn containers(ep: &DockerEndpoint, timeout: Duration) -> Option<IdeResult<Vec<DockerContainer>>> {
|
||||
let addr = address(ep)?;
|
||||
Some(list_containers(&addr, timeout))
|
||||
}
|
||||
|
||||
/// Everything the Services tree shows, fetched straight from the Engine API.
|
||||
pub(crate) fn snapshot(ep: &DockerEndpoint, timeout: Duration) -> Option<DockerSnapshot> {
|
||||
let addr = address(ep)?;
|
||||
|
||||
@@ -193,6 +193,25 @@ pub fn snapshot(ep: &DockerEndpoint) -> DockerSnapshot {
|
||||
snap
|
||||
}
|
||||
|
||||
/// The containers (running or not) that carry every label in `labels`, each `key=value` (or
|
||||
/// just `key`): `docker ps --all --filter label=…`.
|
||||
pub fn containers(ep: &DockerEndpoint, labels: &[String]) -> IdeResult<Vec<DockerContainer>> {
|
||||
if docker_executable().is_none()
|
||||
&& let Some(listed) = engine::containers(ep, QUICK)
|
||||
{
|
||||
let has = |c: &DockerContainer, label: &String| match label.split_once('=') {
|
||||
Some((key, value)) => c.labels.get(key).is_some_and(|v| v == value),
|
||||
None => c.labels.contains_key(label),
|
||||
};
|
||||
return listed.map(|all| all.into_iter().filter(|c| labels.iter().all(|l| has(c, l))).collect());
|
||||
}
|
||||
let filters: Vec<String> = labels.iter().flat_map(|l| ["--filter".to_owned(), format!("label={l}")]).collect();
|
||||
let mut args: Vec<&str> = vec!["ps", "--all", "--no-trunc"];
|
||||
args.extend(filters.iter().map(String::as_str));
|
||||
args.extend(["--format", PS_FORMAT]);
|
||||
run(ep, &args, QUICK).map(|text| parse_containers(&text))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ContainerOp {
|
||||
@@ -324,6 +343,41 @@ pub fn container_stats(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContain
|
||||
parse_container_stats(&out).ok_or_else(|| IdeError::not_found("no container stats returned"))
|
||||
}
|
||||
|
||||
/// CPU and memory capacity of the Docker daemon / VM (`docker info`).
|
||||
pub fn host_resources(ep: &DockerEndpoint) -> IdeResult<DockerHostResources> {
|
||||
if docker_executable().is_none()
|
||||
&& let Some(res) = engine::info(ep, QUICK)
|
||||
{
|
||||
return res;
|
||||
}
|
||||
let out = run(ep, &["info", "--format", INFO_FORMAT], QUICK)?;
|
||||
parse_info(&out).ok_or_else(|| IdeError::internal("docker info did not return JSON"))
|
||||
}
|
||||
|
||||
/// Resource limits (`HostConfig`), OOM state (`State`) and labels of container `id`.
|
||||
pub fn container_resource_inspect(ep: &DockerEndpoint, id: &str) -> IdeResult<DockerContainerResourceInspect> {
|
||||
let id = check_id(id)?;
|
||||
let out = inspect(ep, DockerObject::Container, id)?;
|
||||
parse_container_resource_inspect(&out).ok_or_else(|| IdeError::internal("docker inspect did not return JSON"))
|
||||
}
|
||||
|
||||
/// Finds the dev container matching local `folder` (and optional `config_path`).
|
||||
pub fn find_devcontainer(
|
||||
ep: &DockerEndpoint,
|
||||
folder: &Path,
|
||||
config_path: Option<&Path>,
|
||||
) -> IdeResult<Option<DockerContainer>> {
|
||||
let containers = if docker_executable().is_none()
|
||||
&& let Some(list) = engine::containers(ep, QUICK)
|
||||
{
|
||||
list?
|
||||
} else {
|
||||
let out = run(ep, &["ps", "--all", "--no-trunc", "--format", PS_FORMAT], QUICK)?;
|
||||
parse_containers(&out)
|
||||
};
|
||||
Ok(find_devcontainer_in(&containers, folder, config_path))
|
||||
}
|
||||
|
||||
/// Per-volume disk usage (`docker system df -v --format '{{json .Volumes}}'`).
|
||||
pub fn volume_sizes(ep: &DockerEndpoint) -> IdeResult<std::collections::BTreeMap<String, String>> {
|
||||
if docker_executable().is_none()
|
||||
|
||||
@@ -145,6 +145,50 @@ pub struct DockerContainerStats {
|
||||
pub pids: String,
|
||||
}
|
||||
|
||||
/// CPU and memory capacity of the Docker daemon / VM (`docker info`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DockerHostResources {
|
||||
pub cpus: Option<u32>,
|
||||
pub memory_bytes: Option<u64>,
|
||||
pub operating_system: Option<String>,
|
||||
}
|
||||
|
||||
/// Effective cgroup resource limits on a Docker container (`HostConfig`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DockerContainerLimits {
|
||||
/// CPU core limit (`NanoCpus / 1e9`, else `CpuQuota / CpuPeriod`), `None` if unlimited.
|
||||
pub cpus: Option<f64>,
|
||||
/// Memory limit in bytes (`HostConfig.Memory`), `None` if unlimited (`0`).
|
||||
pub memory_bytes: Option<u64>,
|
||||
/// Memory + swap limit in bytes (`HostConfig.MemorySwap`, if > 0).
|
||||
pub memory_swap_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
/// Exit / OOM state of a Docker container (`State`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DockerContainerOomState {
|
||||
/// A stopped container whose `State.OOMKilled` flag is set.
|
||||
pub oom_killed: bool,
|
||||
/// Raw `State.OOMKilled` flag reported by Docker.
|
||||
pub oom_killed_flag: bool,
|
||||
pub exit_code: Option<i64>,
|
||||
pub running: bool,
|
||||
pub status: String,
|
||||
pub finished_at: Option<String>,
|
||||
}
|
||||
|
||||
/// Limits, OOM state and labels extracted from `docker inspect <container>`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DockerContainerResourceInspect {
|
||||
pub limits: DockerContainerLimits,
|
||||
pub oom: DockerContainerOomState,
|
||||
pub labels: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// Everything the Services tree shows, fetched in one go.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -473,6 +517,163 @@ pub fn parse_container_stats(text: &str) -> Option<DockerContainerStats> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `docker info --format` template for daemon / VM CPU and memory capacity.
|
||||
pub const INFO_FORMAT: &str =
|
||||
r#"{"NCPU":{{json .NCPU}},"MemTotal":{{json .MemTotal}},"OperatingSystem":{{json .OperatingSystem}}}"#;
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct RawInfo {
|
||||
#[serde(rename = "NCPU")]
|
||||
ncpu: Option<u32>,
|
||||
#[serde(rename = "MemTotal")]
|
||||
mem_total: Option<u64>,
|
||||
#[serde(rename = "OperatingSystem")]
|
||||
operating_system: Option<String>,
|
||||
}
|
||||
|
||||
/// Parses `docker info --format` [`INFO_FORMAT`] or Engine API `GET /info` JSON.
|
||||
pub fn parse_info(text: &str) -> Option<DockerHostResources> {
|
||||
let raw: RawInfo = text
|
||||
.lines()
|
||||
.find(|l| l.trim_start().starts_with('{'))
|
||||
.and_then(|l| serde_json::from_str(l).ok())
|
||||
.or_else(|| serde_json::from_str(text).ok())?;
|
||||
Some(DockerHostResources {
|
||||
cpus: raw.ncpu.filter(|&n| n > 0),
|
||||
memory_bytes: raw.mem_total.filter(|&m| m > 0),
|
||||
operating_system: raw.operating_system.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct RawInspect {
|
||||
host_config: RawInspectHostConfig,
|
||||
state: RawInspectState,
|
||||
config: RawInspectConfig,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct RawInspectHostConfig {
|
||||
nano_cpus: i64,
|
||||
cpu_quota: i64,
|
||||
cpu_period: i64,
|
||||
memory: i64,
|
||||
memory_swap: i64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct RawInspectState {
|
||||
status: String,
|
||||
running: bool,
|
||||
#[serde(rename = "OOMKilled")]
|
||||
oom_killed: bool,
|
||||
exit_code: Option<i64>,
|
||||
finished_at: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct RawInspectConfig {
|
||||
labels: Option<BTreeMap<String, String>>,
|
||||
}
|
||||
|
||||
/// Parses resource limits (`HostConfig`), OOM/exit status (`State`) and labels from `docker inspect` JSON
|
||||
/// (either a single container object or a 1-element array).
|
||||
pub fn parse_container_resource_inspect(text: &str) -> Option<DockerContainerResourceInspect> {
|
||||
let value: serde_json::Value = serde_json::from_str(text).ok()?;
|
||||
let obj = match value {
|
||||
serde_json::Value::Array(mut items) => items.drain(..).next()?,
|
||||
other => other,
|
||||
};
|
||||
let raw: RawInspect = serde_json::from_value(obj).ok()?;
|
||||
let cpus = if raw.host_config.nano_cpus > 0 {
|
||||
Some(raw.host_config.nano_cpus as f64 / 1_000_000_000.0)
|
||||
} else if raw.host_config.cpu_quota > 0 {
|
||||
let period = if raw.host_config.cpu_period > 0 { raw.host_config.cpu_period } else { 100_000 };
|
||||
Some(raw.host_config.cpu_quota as f64 / period as f64)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let memory_bytes = (raw.host_config.memory > 0).then_some(raw.host_config.memory as u64);
|
||||
let memory_swap_bytes = (raw.host_config.memory_swap > 0).then_some(raw.host_config.memory_swap as u64);
|
||||
let oom_killed_flag = raw.state.oom_killed;
|
||||
let oom_killed = !raw.state.running && oom_killed_flag;
|
||||
let finished_at = (!raw.state.finished_at.is_empty() && !raw.state.finished_at.starts_with("0001-01-01"))
|
||||
.then_some(raw.state.finished_at);
|
||||
Some(DockerContainerResourceInspect {
|
||||
limits: DockerContainerLimits { cpus, memory_bytes, memory_swap_bytes },
|
||||
oom: DockerContainerOomState {
|
||||
oom_killed,
|
||||
oom_killed_flag,
|
||||
exit_code: raw.state.exit_code,
|
||||
running: raw.state.running,
|
||||
status: raw.state.status,
|
||||
finished_at,
|
||||
},
|
||||
labels: raw.config.labels.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn normalize_label_path(path: &str) -> String {
|
||||
let normalized = path.trim().replace('\\', "/");
|
||||
let trimmed = normalized.trim_end_matches('/');
|
||||
if trimmed.is_empty() && normalized.starts_with('/') { "/".to_owned() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
/// Finds the dev container matching `folder` (and optional `config_path`) among `containers`,
|
||||
/// preferring running containers and exact config file matches.
|
||||
pub fn find_devcontainer_in(
|
||||
containers: &[DockerContainer],
|
||||
folder: &std::path::Path,
|
||||
config_path: Option<&std::path::Path>,
|
||||
) -> Option<DockerContainer> {
|
||||
let want_folder = normalize_label_path(&folder.to_string_lossy());
|
||||
let want_canon = std::fs::canonicalize(folder).ok().map(|p| normalize_label_path(&p.to_string_lossy()));
|
||||
let want_cfg = config_path.map(|p| normalize_label_path(&p.to_string_lossy()));
|
||||
let want_cfg_canon =
|
||||
config_path.and_then(|p| std::fs::canonicalize(p).ok()).map(|p| normalize_label_path(&p.to_string_lossy()));
|
||||
|
||||
let mut matches: Vec<(u8, &DockerContainer)> = containers
|
||||
.iter()
|
||||
.filter_map(|c| {
|
||||
let label_folder = c
|
||||
.labels
|
||||
.get("devcontainer.local_folder")
|
||||
.or_else(|| c.labels.get("vsch.local.folder"))
|
||||
.map(|s| normalize_label_path(s))?;
|
||||
let folder_match = label_folder == want_folder
|
||||
|| want_canon.as_deref() == Some(label_folder.as_str())
|
||||
|| std::fs::canonicalize(&label_folder)
|
||||
.ok()
|
||||
.map(|p| normalize_label_path(&p.to_string_lossy()))
|
||||
.is_some_and(|p| p == want_folder || want_canon.as_deref() == Some(p.as_str()));
|
||||
if !folder_match {
|
||||
return None;
|
||||
}
|
||||
let cfg_score: u8 = match (&want_cfg, c.labels.get("devcontainer.config_file")) {
|
||||
(Some(want), Some(actual)) => {
|
||||
let norm = normalize_label_path(actual);
|
||||
if norm == *want || want_cfg_canon.as_deref() == Some(norm.as_str()) {
|
||||
2
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(Some(_), None) => 1,
|
||||
(None, _) => 1,
|
||||
};
|
||||
let run_score: u8 = if c.running() { 4 } else { 0 };
|
||||
Some((run_score + cfg_score, c))
|
||||
})
|
||||
.collect();
|
||||
matches.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.name.cmp(&b.1.name)));
|
||||
matches.into_iter().next().map(|(_, c)| c.clone())
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(rename_all = "PascalCase", default)]
|
||||
struct RawVolumeUsage {
|
||||
@@ -660,4 +861,80 @@ mod tests {
|
||||
assert_eq!(parse_event(daemon), None);
|
||||
assert_eq!(parse_event("not json"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_docker_info_and_container_resource_inspect() {
|
||||
let info = parse_info(r#"{"NCPU":6,"MemTotal":8589934592,"OperatingSystem":"OrbStack"}"#).unwrap();
|
||||
assert_eq!(
|
||||
info,
|
||||
DockerHostResources {
|
||||
cpus: Some(6),
|
||||
memory_bytes: Some(8 * 1024 * 1024 * 1024),
|
||||
operating_system: Some("OrbStack".into()),
|
||||
}
|
||||
);
|
||||
|
||||
let inspect_nano = r#"[{
|
||||
"HostConfig": { "NanoCpus": 2500000000, "Memory": 4294967296, "MemorySwap": 8589934592 },
|
||||
"State": { "Status": "exited", "Running": false, "OOMKilled": true, "ExitCode": 137, "FinishedAt": "2026-12-02T10:00:00Z" },
|
||||
"Config": { "Labels": { "devcontainer.local_folder": "/work/app" } }
|
||||
}]"#;
|
||||
let parsed = parse_container_resource_inspect(inspect_nano).unwrap();
|
||||
assert_eq!(parsed.limits.cpus, Some(2.5));
|
||||
assert_eq!(parsed.limits.memory_bytes, Some(4 * 1024 * 1024 * 1024));
|
||||
assert_eq!(parsed.limits.memory_swap_bytes, Some(8 * 1024 * 1024 * 1024));
|
||||
assert!(parsed.oom.oom_killed);
|
||||
assert!(parsed.oom.oom_killed_flag);
|
||||
assert_eq!(parsed.oom.exit_code, Some(137));
|
||||
|
||||
// CpuQuota/CpuPeriod fallback. A SIGKILL alone does not identify an OOM exit.
|
||||
let inspect_quota = r#"{
|
||||
"HostConfig": { "NanoCpus": 0, "CpuQuota": 150000, "CpuPeriod": 100000, "Memory": 0, "MemorySwap": -1 },
|
||||
"State": { "Status": "exited", "Running": false, "OOMKilled": false, "ExitCode": 137, "FinishedAt": "0001-01-01T00:00:00Z" },
|
||||
"Config": {}
|
||||
}"#;
|
||||
let parsed_quota = parse_container_resource_inspect(inspect_quota).unwrap();
|
||||
assert_eq!(parsed_quota.limits.cpus, Some(1.5));
|
||||
assert_eq!(parsed_quota.limits.memory_bytes, None);
|
||||
assert_eq!(parsed_quota.limits.memory_swap_bytes, None);
|
||||
assert!(!parsed_quota.oom.oom_killed);
|
||||
assert!(!parsed_quota.oom.oom_killed_flag);
|
||||
assert_eq!(parsed_quota.oom.finished_at, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_matching_devcontainer_preferring_running() {
|
||||
let make = |id: &str, state: &str, folder: &str, cfg: &str| DockerContainer {
|
||||
id: id.into(),
|
||||
name: id.into(),
|
||||
image: "debian".into(),
|
||||
command: "sleep".into(),
|
||||
state: state.into(),
|
||||
status: state.into(),
|
||||
ports: String::new(),
|
||||
created_at: String::new(),
|
||||
compose_project: None,
|
||||
compose_service: None,
|
||||
compose_working_dir: None,
|
||||
compose_files: Vec::new(),
|
||||
mounts: Vec::new(),
|
||||
networks: Vec::new(),
|
||||
labels: BTreeMap::from([
|
||||
("devcontainer.local_folder".into(), folder.into()),
|
||||
("devcontainer.config_file".into(), cfg.into()),
|
||||
]),
|
||||
};
|
||||
let list = vec![
|
||||
make("stopped-c", "exited", "/work/app", "/work/app/.devcontainer/devcontainer.json"),
|
||||
make("running-c", "running", "/work/app", "/work/app/.devcontainer/devcontainer.json"),
|
||||
make("other-c", "running", "/work/other", "/work/other/.devcontainer/devcontainer.json"),
|
||||
];
|
||||
let found = find_devcontainer_in(
|
||||
&list,
|
||||
std::path::Path::new("/work/app"),
|
||||
Some(std::path::Path::new("/work/app/.devcontainer/devcontainer.json")),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(found.id, "running-c");
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ license.workspace = true
|
||||
[dependencies]
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
gtk = "0.18"
|
||||
gtk = "0.19"
|
||||
|
||||
[target.'cfg(any(windows, target_os = "macos"))'.dependencies]
|
||||
raw-window-handle = "0.6"
|
||||
|
||||
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.20.0";
|
||||
pub const ENGINE_VERSION: &str = "1.21.0";
|
||||
/// The longest `[capabilities.reasons]` entry, in characters: a sentence or two.
|
||||
pub const MAX_CAPABILITY_REASON: usize = 500;
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
@@ -168,6 +168,7 @@ impl ActivationEvent {
|
||||
pub const EVENT_KINDS: &[&str] = &[
|
||||
"document-changed",
|
||||
"websocket-ready",
|
||||
"run-started",
|
||||
"run-exited",
|
||||
"terminal-exited",
|
||||
"content-tab-action",
|
||||
@@ -475,6 +476,9 @@ impl Manifest {
|
||||
{
|
||||
self.needs_api(&format!("`{event}`"), 18)?;
|
||||
}
|
||||
if matches!(event, ActivationEvent::Event(kind) if kind == "run-started") {
|
||||
self.needs_api(&format!("`{event}`"), 21)?;
|
||||
}
|
||||
if !seen.insert(event) {
|
||||
return Err(format!("duplicate activation event {event}"));
|
||||
}
|
||||
|
||||
@@ -301,11 +301,12 @@ impl AutomationService {
|
||||
(self.now_ms() as u64) >= ready_at
|
||||
}
|
||||
|
||||
/// Whether any scheduled (non-manual) automation or unpaused session schedule is enabled.
|
||||
/// Whether any scheduled automation (including a `Manual` automation with a pending agent
|
||||
/// override) or unpaused session schedule is enabled.
|
||||
pub fn has_enabled_schedules(&self) -> bool {
|
||||
self.reload_from_disk();
|
||||
let state = self.state.lock();
|
||||
let has_auto = state.automations.iter().any(|a| a.enabled && !matches!(a.trigger, AutomationTrigger::Manual));
|
||||
let has_auto = state.automations.iter().any(is_actively_scheduled);
|
||||
let has_sess = state.session_schedules.iter().any(|s| !s.paused);
|
||||
has_auto || has_sess
|
||||
}
|
||||
@@ -318,6 +319,18 @@ impl AutomationService {
|
||||
self.has_enabled_schedules() || self.has_running_runs()
|
||||
}
|
||||
|
||||
/// Whether the local desktop host should stay alive in the background when editor windows close.
|
||||
///
|
||||
/// Independent of `auto_start_service` (the opt-in OS login service that runs `--scheduler`
|
||||
/// after the desktop app quits). Covers both active schedules and in-flight runs (such as a
|
||||
/// manual run or an already-fired one-shot run) so closing the last window does not abort them.
|
||||
pub fn keeps_local_host_alive(&self, host: &Host) -> bool {
|
||||
if !host.global_settings.effective().agents.automations.keep_alive_in_background {
|
||||
return false;
|
||||
}
|
||||
self.has_enabled_schedules() || self.has_running_runs()
|
||||
}
|
||||
|
||||
pub fn has_running_runs(&self) -> bool {
|
||||
self.reconcile_abandoned_claims(None);
|
||||
self.reload_from_disk();
|
||||
@@ -392,6 +405,7 @@ impl AutomationService {
|
||||
now: f64,
|
||||
) -> bool {
|
||||
let mut mutated = false;
|
||||
let mut abandoned_auto_ids: Vec<String> = Vec::new();
|
||||
for run in &mut state.runs {
|
||||
if matches!(run.status, AutomationRunStatus::Running | AutomationRunStatus::NeedsInput)
|
||||
&& !self.is_claim_owner_live(run.owner_instance_id.as_deref(), &run.id, in_flight_runs)
|
||||
@@ -400,6 +414,12 @@ impl AutomationService {
|
||||
run.finished_ms = Some(now);
|
||||
run.error = Some("Interrupted: host exited before run finished".into());
|
||||
run.unread = true;
|
||||
abandoned_auto_ids.push(run.automation_id.clone());
|
||||
mutated = true;
|
||||
}
|
||||
}
|
||||
for auto_id in abandoned_auto_ids {
|
||||
if finalize_exhausted_oneshot_locked(state, &auto_id, now) {
|
||||
mutated = true;
|
||||
}
|
||||
}
|
||||
@@ -466,8 +486,7 @@ impl AutomationService {
|
||||
// Strict lock order: `self.state` -> `self.in_flight`.
|
||||
let state = self.state.lock();
|
||||
let in_flight = self.in_flight.lock();
|
||||
let has_enabled =
|
||||
state.automations.iter().any(|a| a.enabled && !matches!(a.trigger, AutomationTrigger::Manual));
|
||||
let has_enabled = state.automations.iter().any(is_actively_scheduled);
|
||||
let live_runs = state
|
||||
.runs
|
||||
.iter()
|
||||
@@ -503,9 +522,7 @@ impl AutomationService {
|
||||
self.reload_from_disk();
|
||||
let boot_state = self.boot.status(host.home_dir().as_deref(), remote);
|
||||
let state = self.state.lock();
|
||||
let active_schedules =
|
||||
state.automations.iter().filter(|a| a.enabled && !matches!(a.trigger, AutomationTrigger::Manual)).count()
|
||||
as u32;
|
||||
let active_schedules = state.automations.iter().filter(|a| is_actively_scheduled(a)).count() as u32;
|
||||
let running_runs = state.runs.iter().filter(|r| r.status == AutomationRunStatus::Running).count() as u32;
|
||||
let needs_input_runs = state.runs.iter().filter(|r| r.status == AutomationRunStatus::NeedsInput).count() as u32;
|
||||
let unread_runs = state.runs.iter().filter(|r| r.unread).count() as u32;
|
||||
@@ -598,7 +615,7 @@ impl AutomationService {
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
out.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
|
||||
out.sort_by(compare_automations_by_schedule);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -660,23 +677,47 @@ impl AutomationService {
|
||||
}
|
||||
|
||||
let now = self.now_ms();
|
||||
let computed_next = if input.enabled {
|
||||
let next = input.trigger.next_run_after(now)?;
|
||||
if matches!(input.trigger, AutomationTrigger::OneShot { .. }) && next.is_none() {
|
||||
return Err(IdeError::invalid("one-shot timestamp must be in the future when enabled"));
|
||||
}
|
||||
next
|
||||
} else {
|
||||
// Still validate syntax even when saved disabled.
|
||||
let _ = input.trigger.next_run_after(now)?;
|
||||
None
|
||||
};
|
||||
// Always validate trigger syntax even when disabled or when an agent override is preserved.
|
||||
let regular_next = input.trigger.next_run_after(now)?;
|
||||
|
||||
let saved = self.with_mutated_state(|state| {
|
||||
if let Some(existing_id) = input.id.as_deref() {
|
||||
let has_active_run = state.runs.iter().any(|r| {
|
||||
r.automation_id == existing_id
|
||||
&& matches!(r.status, AutomationRunStatus::Running | AutomationRunStatus::NeedsInput)
|
||||
});
|
||||
let Some(existing) = state.automations.iter_mut().find(|a| a.id == existing_id) else {
|
||||
return Err(IdeError::not_found(format!("unknown automation '{existing_id}'")));
|
||||
};
|
||||
let trigger_unchanged = existing.trigger == input.trigger;
|
||||
let max_runs_reached = input.max_runs.is_some_and(|max| existing.run_count >= max);
|
||||
let preserved_override = if input.enabled
|
||||
&& input.allow_agent_schedule
|
||||
&& !input.clear_override
|
||||
&& trigger_unchanged
|
||||
&& !max_runs_reached
|
||||
{
|
||||
existing
|
||||
.next_run_override_ms
|
||||
.filter(|&ms| ms > now && input.disable_after_ms.is_none_or(|exp| ms < exp))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let effective_next = if !input.enabled {
|
||||
None
|
||||
} else if let Some(ov) = preserved_override {
|
||||
Some(ov)
|
||||
} else {
|
||||
if matches!(input.trigger, AutomationTrigger::OneShot { .. })
|
||||
&& regular_next.is_none()
|
||||
&& !(trigger_unchanged && input.allow_agent_schedule && has_active_run)
|
||||
{
|
||||
return Err(IdeError::invalid("one-shot timestamp must be in the future when enabled"));
|
||||
}
|
||||
regular_next
|
||||
};
|
||||
|
||||
existing.name = name;
|
||||
existing.enabled = input.enabled;
|
||||
existing.paused_reason = None;
|
||||
@@ -690,13 +731,25 @@ impl AutomationService {
|
||||
existing.skill_overrides = input.skill_overrides;
|
||||
existing.memory_overrides = input.memory_overrides;
|
||||
existing.trigger = input.trigger;
|
||||
existing.allow_agent_schedule = input.allow_agent_schedule;
|
||||
existing.misfire_policy = input.misfire_policy;
|
||||
existing.disable_after_ms = input.disable_after_ms;
|
||||
existing.max_runs = input.max_runs;
|
||||
existing.next_run_ms = computed_next;
|
||||
if let Some(ov) = preserved_override {
|
||||
existing.next_run_override_ms = Some(ov);
|
||||
} else {
|
||||
existing.next_run_override_ms = None;
|
||||
existing.next_prompt_override = None;
|
||||
}
|
||||
existing.next_run_ms = effective_next;
|
||||
existing.updated_ms = now;
|
||||
Ok((existing.clone(), true))
|
||||
} else {
|
||||
if input.enabled && matches!(input.trigger, AutomationTrigger::OneShot { .. }) && regular_next.is_none()
|
||||
{
|
||||
return Err(IdeError::invalid("one-shot timestamp must be in the future when enabled"));
|
||||
}
|
||||
let computed_next = if input.enabled { regular_next } else { None };
|
||||
let id = format!("auto_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
|
||||
let out = AgentAutomation {
|
||||
id,
|
||||
@@ -713,10 +766,13 @@ impl AutomationService {
|
||||
skill_overrides: input.skill_overrides,
|
||||
memory_overrides: input.memory_overrides,
|
||||
trigger: input.trigger,
|
||||
allow_agent_schedule: input.allow_agent_schedule,
|
||||
misfire_policy: input.misfire_policy,
|
||||
disable_after_ms: input.disable_after_ms,
|
||||
max_runs: input.max_runs,
|
||||
next_run_ms: computed_next,
|
||||
next_run_override_ms: None,
|
||||
next_prompt_override: None,
|
||||
paused_reason: None,
|
||||
run_count: 0,
|
||||
unread_runs: 0,
|
||||
@@ -744,14 +800,23 @@ impl AutomationService {
|
||||
check_workspace_trust(host, &auto.workspace).map_err(IdeError::invalid)?;
|
||||
}
|
||||
let next = if enabled {
|
||||
let computed = auto.trigger.next_run_after(now)?;
|
||||
if matches!(auto.trigger, AutomationTrigger::OneShot { .. }) && computed.is_none() {
|
||||
return Err(IdeError::invalid(
|
||||
"one-shot timestamp is in the past; update its schedule before enabling",
|
||||
));
|
||||
let valid_override = auto.next_run_override_ms.filter(|&ms| ms > now);
|
||||
if let Some(ov) = valid_override {
|
||||
Some(ov)
|
||||
} else {
|
||||
auto.next_run_override_ms = None;
|
||||
auto.next_prompt_override = None;
|
||||
let computed = auto.trigger.next_run_after(now)?;
|
||||
if matches!(auto.trigger, AutomationTrigger::OneShot { .. }) && computed.is_none() {
|
||||
return Err(IdeError::invalid(
|
||||
"one-shot timestamp is in the past; update its schedule before enabling",
|
||||
));
|
||||
}
|
||||
computed
|
||||
}
|
||||
computed
|
||||
} else {
|
||||
auto.next_run_override_ms = None;
|
||||
auto.next_prompt_override = None;
|
||||
None
|
||||
};
|
||||
auto.enabled = enabled;
|
||||
@@ -794,6 +859,8 @@ impl AutomationService {
|
||||
auto.enabled = false;
|
||||
auto.paused_reason = None;
|
||||
auto.next_run_ms = None;
|
||||
auto.next_run_override_ms = None;
|
||||
auto.next_prompt_override = None;
|
||||
auto.updated_ms = now;
|
||||
n += 1;
|
||||
}
|
||||
@@ -970,6 +1037,8 @@ impl AutomationService {
|
||||
skill_overrides: Default::default(),
|
||||
memory_overrides: None,
|
||||
trigger: parsed.trigger,
|
||||
allow_agent_schedule: parsed.allow_agent_schedule,
|
||||
clear_override: false,
|
||||
misfire_policy: None,
|
||||
disable_after_ms: parsed.disable_after_ms,
|
||||
max_runs: parsed.max_runs,
|
||||
@@ -982,6 +1051,129 @@ impl AutomationService {
|
||||
preview_trigger_runs(trigger, self.now_ms(), n)
|
||||
}
|
||||
|
||||
/// Previews up to `max_count` upcoming firing timestamps for MCP callers without altering the
|
||||
/// IPC command's `1..=10` clamp.
|
||||
pub fn preview_schedule_capped(
|
||||
&self,
|
||||
trigger: &AutomationTrigger,
|
||||
count: u32,
|
||||
max_count: u32,
|
||||
) -> IdeResult<Vec<f64>> {
|
||||
let n = count.clamp(1, max_count) as usize;
|
||||
preview_trigger_runs(trigger, self.now_ms(), n)
|
||||
}
|
||||
|
||||
/// Resolves a live per-session MCP capability nonce across all in-memory [`AgentManager`]s of
|
||||
/// `host` without touching disk or running claim reconciliation.
|
||||
pub fn resolve_mcp_caller(&self, host: &Host, session_nonce: &str) -> Option<ide_agent::McpCallerSession> {
|
||||
for p in host.projects() {
|
||||
if let Some(caller) = p.agents.resolve_mcp_session_nonce(session_nonce) {
|
||||
return Some(caller);
|
||||
}
|
||||
}
|
||||
if let Some(caller) =
|
||||
self.headless_agents.lock().values().find_map(|mgr| mgr.resolve_mcp_session_nonce(session_nonce))
|
||||
{
|
||||
return Some(caller);
|
||||
}
|
||||
if let Some(caller) =
|
||||
self.chat_agents.lock().as_ref().and_then(|mgr| mgr.resolve_mcp_session_nonce(session_nonce))
|
||||
{
|
||||
return Some(caller);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Unattended self-rescheduling invoked by `schedule_next_run` ONLY while `caller` is actively
|
||||
/// executing a scheduled turn of an [`AgentAutomation`] whose `allow_agent_schedule` is `true`.
|
||||
///
|
||||
/// Keeps the user's `trigger` and `prompt` untouched, storing a one-time override
|
||||
/// (`next_run_override_ms` + `next_prompt_override`) consumed on the next firing. `done: true`
|
||||
/// clears any pending override and lets the regular `trigger` continue, leaving `Manual`
|
||||
/// automations idle.
|
||||
pub(crate) fn schedule_next_run_from_agent(
|
||||
&self,
|
||||
host: &Arc<Host>,
|
||||
caller: &ide_agent::McpCallerSession,
|
||||
schedule: Option<SelfScheduleTime>,
|
||||
next_prompt: Option<String>,
|
||||
) -> IdeResult<AgentAutomation> {
|
||||
const MIN_SELF_SCHEDULE_DELAY_MS: f64 = 60_000.0;
|
||||
|
||||
let Some(auto_id) = caller.active_automation_id.as_deref() else {
|
||||
return Err(IdeError::invalid(
|
||||
"schedule_next_run can only be called while an Agent Automation's scheduled run is actively executing; interactive turns cannot self-schedule",
|
||||
));
|
||||
};
|
||||
|
||||
let cleaned_prompt = next_prompt.map(|p| p.trim().to_owned()).filter(|p| !p.is_empty());
|
||||
|
||||
let updated = self.with_mutated_state(|state| {
|
||||
let now = self.now_ms();
|
||||
let Some(auto) = state.automations.iter_mut().find(|a| a.id == auto_id) else {
|
||||
return Err(IdeError::not_found(format!("unknown automation '{auto_id}'")));
|
||||
};
|
||||
if !auto.allow_agent_schedule {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Automation '{}' does not allow unattended self-scheduling; enable 'Allow agent to schedule its next run' in the automation settings",
|
||||
auto.name
|
||||
)));
|
||||
}
|
||||
if !auto.enabled {
|
||||
return Err(IdeError::invalid("The automation is disabled; enable it before scheduling another run"));
|
||||
}
|
||||
|
||||
let Some(schedule) = schedule else {
|
||||
auto.next_run_override_ms = None;
|
||||
auto.next_prompt_override = None;
|
||||
auto.next_run_ms = auto.trigger.next_run_after(now)?;
|
||||
if matches!(auto.trigger, AutomationTrigger::OneShot { .. }) && auto.next_run_ms.is_none() {
|
||||
auto.enabled = false;
|
||||
}
|
||||
auto.updated_ms = now;
|
||||
return Ok((auto.clone(), true));
|
||||
};
|
||||
|
||||
let target_ms = match schedule {
|
||||
SelfScheduleTime::After(delay_ms) => now + delay_ms,
|
||||
SelfScheduleTime::At(run_at_ms) => run_at_ms,
|
||||
};
|
||||
if !target_ms.is_finite() || target_ms < now + MIN_SELF_SCHEDULE_DELAY_MS {
|
||||
return Err(IdeError::invalid("next run must be at least 60 seconds in the future"));
|
||||
}
|
||||
|
||||
check_workspace_trust(host, &auto.workspace).map_err(IdeError::invalid)?;
|
||||
|
||||
if let Some(max) = auto.max_runs
|
||||
&& auto.run_count >= max
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Automation '{}' reached its maxRuns limit ({max}); further runs cannot be scheduled",
|
||||
auto.name
|
||||
)));
|
||||
}
|
||||
if let Some(exp) = auto.disable_after_ms
|
||||
&& target_ms >= exp
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Requested next run exceeds the disableAfter date of automation '{}'",
|
||||
auto.name
|
||||
)));
|
||||
}
|
||||
|
||||
auto.next_run_override_ms = Some(target_ms);
|
||||
auto.next_prompt_override = cleaned_prompt;
|
||||
auto.next_run_ms = Some(target_ms);
|
||||
auto.updated_ms = now;
|
||||
Ok((auto.clone(), true))
|
||||
})?;
|
||||
|
||||
self.sync_boot_service(host);
|
||||
self.notify.notify_waiters();
|
||||
self.broadcast_changed(host);
|
||||
Ok(updated)
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// In-Session Schedules (`Send Later` and `/loop`)
|
||||
// -----------------------------------------------------------------------
|
||||
@@ -1163,6 +1355,8 @@ impl AutomationService {
|
||||
if expired_date || expired_runs {
|
||||
state.automations[idx].enabled = false;
|
||||
state.automations[idx].next_run_ms = None;
|
||||
state.automations[idx].next_run_override_ms = None;
|
||||
state.automations[idx].next_prompt_override = None;
|
||||
state.automations[idx].updated_ms = now;
|
||||
mutated = true;
|
||||
disabled_any = true;
|
||||
@@ -1178,14 +1372,42 @@ impl AutomationService {
|
||||
let late_ms = now - scheduled_for;
|
||||
let is_misfire = late_ms >= misfire_threshold;
|
||||
let policy = state.automations[idx].misfire_policy.unwrap_or(default_misfire);
|
||||
let skip_misfire = is_misfire && policy == AutomationMisfirePolicy::Skip;
|
||||
// Idempotency by stable occurrence_id + single active scheduled slot per automation.
|
||||
let duplicate_occ =
|
||||
state.runs.iter().any(|r| r.occurrence_id.as_deref() == Some(occurrence_id.as_str()));
|
||||
let already_active = state.runs.iter().any(|r| {
|
||||
r.automation_id == auto_id
|
||||
&& matches!(r.status, AutomationRunStatus::Running | AutomationRunStatus::NeedsInput)
|
||||
});
|
||||
let will_launch = !skip_misfire && !duplicate_occ && !already_active;
|
||||
|
||||
// Advance schedule past `now` inside the same `state.lock` transaction as the claim.
|
||||
// Consume any one-time agent override and advance the underlying regular schedule
|
||||
// past `now` inside the same `state.lock` transaction as the claim.
|
||||
let had_override = state.automations[idx].next_run_override_ms.take().is_some();
|
||||
let override_prompt = state.automations[idx].next_prompt_override.take();
|
||||
let allow_self_sched = state.automations[idx].allow_agent_schedule;
|
||||
match &state.automations[idx].trigger {
|
||||
AutomationTrigger::OneShot { run_at_ms } if *run_at_ms > now => {
|
||||
state.automations[idx].next_run_ms = Some(*run_at_ms);
|
||||
}
|
||||
AutomationTrigger::OneShot { .. } if allow_self_sched && (will_launch || already_active) => {
|
||||
// Keep self-scheduling OneShot enabled while its run executes so the agent
|
||||
// can call `schedule_next_run`; `finish_run` disables it if no follow-up
|
||||
// override is scheduled.
|
||||
state.automations[idx].next_run_ms = None;
|
||||
}
|
||||
AutomationTrigger::OneShot { .. } => {
|
||||
state.automations[idx].enabled = false;
|
||||
state.automations[idx].next_run_ms = None;
|
||||
disabled_any = true;
|
||||
}
|
||||
AutomationTrigger::Manual => {
|
||||
state.automations[idx].next_run_ms = None;
|
||||
if had_override {
|
||||
disabled_any = true;
|
||||
}
|
||||
}
|
||||
trigger => {
|
||||
state.automations[idx].next_run_ms = trigger.next_run_after(now).ok().flatten();
|
||||
}
|
||||
@@ -1193,17 +1415,7 @@ impl AutomationService {
|
||||
state.automations[idx].updated_ms = now;
|
||||
mutated = true;
|
||||
|
||||
if is_misfire && policy == AutomationMisfirePolicy::Skip {
|
||||
continue;
|
||||
}
|
||||
// Idempotency by stable occurrence_id + single active scheduled slot per automation.
|
||||
let duplicate_occ =
|
||||
state.runs.iter().any(|r| r.occurrence_id.as_deref() == Some(occurrence_id.as_str()));
|
||||
let already_active = state.runs.iter().any(|r| {
|
||||
r.automation_id == auto_id
|
||||
&& matches!(r.status, AutomationRunStatus::Running | AutomationRunStatus::NeedsInput)
|
||||
});
|
||||
if duplicate_occ || already_active {
|
||||
if !will_launch {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1212,6 +1424,7 @@ impl AutomationService {
|
||||
idx,
|
||||
AutomationRunOrigin::Scheduled { scheduled_for_ms: scheduled_for, catch_up: is_misfire },
|
||||
occurrence_id,
|
||||
override_prompt,
|
||||
&self.owner.instance_id,
|
||||
now,
|
||||
&mut disabled_any,
|
||||
@@ -1478,6 +1691,8 @@ impl AutomationService {
|
||||
{
|
||||
auto.enabled = false;
|
||||
auto.next_run_ms = None;
|
||||
auto.next_run_override_ms = None;
|
||||
auto.next_prompt_override = None;
|
||||
auto.paused_reason = Some(reason.to_owned());
|
||||
auto.updated_ms = now;
|
||||
mutated = true;
|
||||
@@ -1498,8 +1713,7 @@ impl AutomationService {
|
||||
let (has_enabled, has_live_claims) = {
|
||||
let state = self.state.lock();
|
||||
let in_flight = self.in_flight.lock();
|
||||
let has_enabled =
|
||||
state.automations.iter().any(|a| a.enabled && !matches!(a.trigger, AutomationTrigger::Manual));
|
||||
let has_enabled = state.automations.iter().any(is_actively_scheduled);
|
||||
let live_runs = state
|
||||
.runs
|
||||
.iter()
|
||||
@@ -1552,12 +1766,29 @@ impl AutomationService {
|
||||
}
|
||||
|
||||
let occ_id = format!("manual:{automation_id}:{}", uuid::Uuid::new_v4().simple());
|
||||
let had_override = state.automations[auto_idx].next_run_override_ms.take().is_some();
|
||||
let override_prompt = state.automations[auto_idx].next_prompt_override.take();
|
||||
if had_override && state.automations[auto_idx].enabled {
|
||||
let regular_next = state.automations[auto_idx].trigger.next_run_after(now).ok().flatten();
|
||||
match &state.automations[auto_idx].trigger {
|
||||
AutomationTrigger::OneShot { .. } if regular_next.is_none() => {
|
||||
if !state.automations[auto_idx].allow_agent_schedule {
|
||||
state.automations[auto_idx].enabled = false;
|
||||
}
|
||||
state.automations[auto_idx].next_run_ms = None;
|
||||
}
|
||||
_ => {
|
||||
state.automations[auto_idx].next_run_ms = regular_next;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut disabled_max = false;
|
||||
let work = allocate_claimed_run_locked(
|
||||
state,
|
||||
auto_idx,
|
||||
AutomationRunOrigin::Manual,
|
||||
occ_id,
|
||||
override_prompt,
|
||||
&self.owner.instance_id,
|
||||
now,
|
||||
&mut disabled_max,
|
||||
@@ -1600,6 +1831,8 @@ impl AutomationService {
|
||||
{
|
||||
stored.enabled = false;
|
||||
stored.next_run_ms = None;
|
||||
stored.next_run_override_ms = None;
|
||||
stored.next_prompt_override = None;
|
||||
stored.paused_reason = Some(reason.clone());
|
||||
stored.updated_ms = now;
|
||||
return Ok(((), true));
|
||||
@@ -1752,7 +1985,11 @@ impl AutomationService {
|
||||
AutomationWorkspace::ChatOnly => (Isolation::Local, None, None),
|
||||
};
|
||||
|
||||
let title = format!("{} (#{run_number})", auto.name);
|
||||
let title = if auto.continuity == AutomationContinuity::SameTask {
|
||||
auto.name.clone()
|
||||
} else {
|
||||
format!("{} (#{run_number})", auto.name)
|
||||
};
|
||||
let created = agents
|
||||
.create_automated(
|
||||
NewAgentTask {
|
||||
@@ -2122,7 +2359,10 @@ impl AutomationService {
|
||||
run.branch = branch;
|
||||
}
|
||||
run.worktree_cleaned = worktree_cleaned;
|
||||
Ok((run.clone(), true))
|
||||
let finished = run.clone();
|
||||
let auto_id = finished.automation_id.clone();
|
||||
let _ = finalize_exhausted_oneshot_locked(state, &auto_id, now);
|
||||
Ok((finished, true))
|
||||
})?;
|
||||
self.sync_boot_service(host);
|
||||
self.broadcast_changed(host);
|
||||
@@ -2155,6 +2395,8 @@ impl AutomationService {
|
||||
run.branch = branch;
|
||||
}
|
||||
run.worktree_cleaned = worktree_cleaned;
|
||||
let auto_id = run.automation_id.clone();
|
||||
let _ = finalize_exhausted_oneshot_locked(state, &auto_id, now);
|
||||
Ok(((), true))
|
||||
} else {
|
||||
Ok(((), false))
|
||||
@@ -2882,7 +3124,7 @@ impl AutomationService {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_workspace_trust(host: &Host, workspace: &AutomationWorkspace) -> Result<(), String> {
|
||||
pub(crate) fn check_workspace_trust(host: &Host, workspace: &AutomationWorkspace) -> Result<(), String> {
|
||||
let AutomationWorkspace::Project { root, isolation, .. } = workspace else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -2902,11 +3144,82 @@ fn check_workspace_trust(host: &Host, workspace: &AutomationWorkspace) -> Result
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) enum SelfScheduleTime {
|
||||
After(f64),
|
||||
At(f64),
|
||||
}
|
||||
|
||||
fn is_actively_scheduled(a: &AgentAutomation) -> bool {
|
||||
a.enabled
|
||||
&& match a.trigger {
|
||||
AutomationTrigger::Manual => a.next_run_override_ms.is_some(),
|
||||
AutomationTrigger::OneShot { .. } => a.next_run_ms.is_some() || a.next_run_override_ms.is_some(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Orders automations as an upcoming schedule queue:
|
||||
/// 1. Enabled schedules with a future `next_run_ms` (soonest first),
|
||||
/// 2. Enabled idle/manual schedules with no upcoming firing (most recently updated first),
|
||||
/// 3. Paused automations (most recently updated first).
|
||||
fn compare_automations_by_schedule(a: &AgentAutomation, b: &AgentAutomation) -> std::cmp::Ordering {
|
||||
let tier = |x: &AgentAutomation| -> u8 {
|
||||
if !x.enabled {
|
||||
2
|
||||
} else if x.next_run_ms.is_some() {
|
||||
0
|
||||
} else {
|
||||
1
|
||||
}
|
||||
};
|
||||
tier(a)
|
||||
.cmp(&tier(b))
|
||||
.then_with(|| {
|
||||
match (a.enabled.then_some(a.next_run_ms).flatten(), b.enabled.then_some(b.next_run_ms).flatten()) {
|
||||
(Some(na), Some(nb)) => na.total_cmp(&nb),
|
||||
_ => std::cmp::Ordering::Equal,
|
||||
}
|
||||
})
|
||||
.then_with(|| b.updated_ms.total_cmp(&a.updated_ms))
|
||||
.then_with(|| a.name.cmp(&b.name))
|
||||
}
|
||||
|
||||
/// Disables a `OneShot` automation whose seed timestamp has elapsed once no active run remains
|
||||
/// and the agent did not schedule a future `next_run_override_ms`.
|
||||
fn finalize_exhausted_oneshot_locked(state: &mut StoredState, automation_id: &str, now: f64) -> bool {
|
||||
let has_active_run = state.runs.iter().any(|r| {
|
||||
r.automation_id == automation_id
|
||||
&& matches!(r.status, AutomationRunStatus::Running | AutomationRunStatus::NeedsInput)
|
||||
});
|
||||
if has_active_run {
|
||||
return false;
|
||||
}
|
||||
let Some(auto) = state.automations.iter_mut().find(|a| a.id == automation_id) else {
|
||||
return false;
|
||||
};
|
||||
if !auto.enabled || !matches!(auto.trigger, AutomationTrigger::OneShot { .. }) {
|
||||
return false;
|
||||
}
|
||||
let has_future_override = auto.next_run_override_ms.is_some_and(|ms| ms > now);
|
||||
let has_future_seed = auto.trigger.next_run_after(now).ok().flatten().is_some();
|
||||
if has_future_override || has_future_seed {
|
||||
return false;
|
||||
}
|
||||
auto.enabled = false;
|
||||
auto.next_run_ms = None;
|
||||
auto.next_run_override_ms = None;
|
||||
auto.next_prompt_override = None;
|
||||
auto.updated_ms = now;
|
||||
true
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn allocate_claimed_run_locked(
|
||||
state: &mut StoredState,
|
||||
auto_idx: usize,
|
||||
origin: AutomationRunOrigin,
|
||||
occurrence_id: String,
|
||||
override_prompt: Option<String>,
|
||||
owner_instance_id: &str,
|
||||
now: f64,
|
||||
disabled_any: &mut bool,
|
||||
@@ -2917,10 +3230,15 @@ fn allocate_claimed_run_locked(
|
||||
if auto.max_runs.is_some_and(|max| run_number >= max) {
|
||||
auto.enabled = false;
|
||||
auto.next_run_ms = None;
|
||||
auto.next_run_override_ms = None;
|
||||
auto.next_prompt_override = None;
|
||||
*disabled_any = true;
|
||||
}
|
||||
auto.updated_ms = now;
|
||||
let cloned_auto = auto.clone();
|
||||
let mut cloned_auto = auto.clone();
|
||||
if let Some(prompt_text) = override_prompt {
|
||||
cloned_auto.prompt.text = prompt_text;
|
||||
}
|
||||
|
||||
let project_root = match &cloned_auto.workspace {
|
||||
AutomationWorkspace::Project { root, .. } => Some(root.clone()),
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! Dev containers as the backend sees them: the Dev Containers CLI, and which containers a
|
||||
//! window is open in.
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The Dev Containers CLI: the IDE-managed copy (Settings › Languages & Frameworks › Language Servers) or one on `PATH`.
|
||||
pub fn cli(data_dir: &Path) -> IdeResult<PathBuf> {
|
||||
ide_tools::Tools::new(data_dir)
|
||||
.info("devcontainer", &[])
|
||||
.ok()
|
||||
.and_then(|t| t.path)
|
||||
.map(ide_core::IpcPath::into_path_buf)
|
||||
.ok_or_else(|| {
|
||||
IdeError::unavailable(
|
||||
"The Dev Containers CLI is not installed. Install it in Settings › Languages & Frameworks › Language Servers.",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// The containers a window is attached to (Reopen in Container), by id. A container may be held
|
||||
/// by more than one window.
|
||||
#[derive(Default)]
|
||||
pub struct AttachedContainers(Mutex<Vec<String>>);
|
||||
|
||||
impl AttachedContainers {
|
||||
/// Marks `id` attached until the returned guard is dropped.
|
||||
pub fn hold(self: &Arc<Self>, id: &str) -> AttachedContainer {
|
||||
self.0.lock().push(id.to_owned());
|
||||
AttachedContainer { set: self.clone(), id: id.to_owned() }
|
||||
}
|
||||
|
||||
/// Whether a window is attached to the container `id` (a full id or a prefix of one).
|
||||
pub fn contains(&self, id: &str) -> bool {
|
||||
!id.is_empty() && self.0.lock().iter().any(|held| held.starts_with(id) || id.starts_with(held.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A window's attachment to a container, released on drop.
|
||||
pub struct AttachedContainer {
|
||||
set: Arc<AttachedContainers>,
|
||||
id: String,
|
||||
}
|
||||
|
||||
impl Drop for AttachedContainer {
|
||||
fn drop(&mut self) {
|
||||
let mut held = self.set.0.lock();
|
||||
if let Some(at) = held.iter().position(|id| *id == self.id) {
|
||||
held.remove(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_container_stays_attached_until_every_window_released_it() {
|
||||
let set = Arc::new(AttachedContainers::default());
|
||||
let id = "3f1c2b9a7d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8";
|
||||
let (first, second) = (set.hold(id), set.hold(id));
|
||||
assert!(set.contains(id) && set.contains(&id[..12]));
|
||||
assert!(!set.contains("ffffffffffff") && !set.contains(""));
|
||||
drop(first);
|
||||
assert!(set.contains(id));
|
||||
drop(second);
|
||||
assert!(!set.contains(id));
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,54 @@ const BIOME_MARKERS: [&str; 3] = ["biome.json", "biome.jsonc", "node_modules/@bi
|
||||
const DPRINT_MARKERS: [&str; 5] =
|
||||
["dprint.json", ".dprint.json", "dprint.jsonc", ".dprint.jsonc", "node_modules/dprint/package.json"];
|
||||
|
||||
/// CSharpier's configuration and ignore files.
|
||||
const CSHARPIER_CONFIGS: [&str; 5] =
|
||||
[".csharpierrc", ".csharpierrc.json", ".csharpierrc.yaml", ".csharpierrc.yml", ".csharpierignore"];
|
||||
|
||||
/// The version of CSharpier in the `dotnet` tool manifest that applies to `file`: the nearest one
|
||||
/// in the project that lists it, up to a manifest marked `isRoot` (as `dotnet` searches).
|
||||
fn local_csharpier(file: &Path, root: &Path) -> Option<String> {
|
||||
for dir in file.parent()?.ancestors().take_while(|dir| dir.starts_with(root)) {
|
||||
let mut is_root = false;
|
||||
// .NET 10's `dotnet new tool-manifest` writes the second location.
|
||||
for manifest in [dir.join(".config").join("dotnet-tools.json"), dir.join("dotnet-tools.json")] {
|
||||
let Some(json) = std::fs::read_to_string(manifest).ok().and_then(|text| {
|
||||
let text = text.trim_start_matches('\u{feff}');
|
||||
serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(text)).ok()
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let tool = json["tools"].as_object().and_then(|tools| {
|
||||
tools.iter().find(|(name, _)| name.eq_ignore_ascii_case("csharpier")).map(|(_, tool)| tool)
|
||||
});
|
||||
if let Some(tool) = tool {
|
||||
return Some(tool["version"].as_str().unwrap_or_default().to_owned());
|
||||
}
|
||||
is_root |= json["isRoot"] == serde_json::Value::Bool(true);
|
||||
}
|
||||
if is_root {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// CSharpier for a `.cs` file of a project that uses it. `None` keeps the language server: another
|
||||
/// language, a project without CSharpier, or only its configuration with no CSharpier installed.
|
||||
fn csharpier_for(tools: &Tools, file: &Path, root: &Path) -> Option<IdeResult<formatter::CSharpierCommand>> {
|
||||
if !file.extension().is_some_and(|e| e.eq_ignore_ascii_case("cs")) {
|
||||
return None;
|
||||
}
|
||||
let local = local_csharpier(file, root);
|
||||
if local.is_none() && find_in_project(file, root, &CSHARPIER_CONFIGS).is_none() {
|
||||
return None;
|
||||
}
|
||||
match tools.csharpier_command(file, local.as_deref()) {
|
||||
Err(_) if local.is_none() => None,
|
||||
command => Some(command),
|
||||
}
|
||||
}
|
||||
|
||||
/// The nearest of `names` in `file`'s folder or above, up to the project `root` (none outside it).
|
||||
fn find_in_project(file: &Path, root: &Path, names: &[&str]) -> Option<PathBuf> {
|
||||
file.parent()?
|
||||
@@ -304,10 +352,21 @@ fn external_tool(
|
||||
let id = formatter_language(language.id.as_str());
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == id);
|
||||
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
|
||||
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
|
||||
Some(Black)
|
||||
let black = enabled(Black).then_some(Black);
|
||||
let ruff = enabled(Ruff).then_some(Ruff);
|
||||
// An explicit selection on either page wins over the other tool's configuration
|
||||
// probe: Ruff chosen on its page formats even below a [tool.black] pyproject,
|
||||
// Black chosen on its page formats without one. A tool whose languages opt the
|
||||
// language out stays out. Automatic keeps the probe: a project with [tool.black]
|
||||
// wants Black; both pages explicit falls back to that answer.
|
||||
return Ok(if settings.black.prefer {
|
||||
black.or(ruff)
|
||||
} else if settings.ruff.prefer {
|
||||
ruff
|
||||
} else if black.is_some() && black_configured(file) {
|
||||
black
|
||||
} else {
|
||||
enabled(Ruff).then_some(Ruff)
|
||||
ruff
|
||||
});
|
||||
}
|
||||
let found = |names: &[&str]| names.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some());
|
||||
@@ -363,10 +422,53 @@ fn php_cs_fixer_edits(
|
||||
let copy = dir.path().join(name);
|
||||
std::fs::write(©, unsaved)?;
|
||||
formatter::run_php_cs_fixer(tools.php_cs_fixer_command(php, fixer, ©)?, &Default::default())?;
|
||||
let formatted = std::fs::read_to_string(©)?;
|
||||
fixed_edits(unsaved, &std::fs::read_to_string(©)?)
|
||||
}
|
||||
|
||||
/// Where a container finds the copy PHP-CS-Fixer fixes.
|
||||
const PHP_CS_FIXER_COPY: &str = "/openidea-php-cs-fixer";
|
||||
|
||||
/// [`php_cs_fixer_edits`] with the PHP of `target`, the container run target PHP runs in: the
|
||||
/// folder of the copy is mounted for this run, the configuration and `vendor` are in the project.
|
||||
fn php_cs_fixer_container_edits(
|
||||
data_dir: &Path,
|
||||
root: &Path,
|
||||
target: &ide_core::remote_settings::RunTarget,
|
||||
fixer: &formatter::PhpCsFixer,
|
||||
path: &Path,
|
||||
unsaved: &str,
|
||||
) -> IdeResult<Vec<TextEdit>> {
|
||||
let name = path.file_name().ok_or_else(|| IdeError::invalid("PHP-CS-Fixer: file has no name"))?;
|
||||
let dir = tempfile::tempdir()?;
|
||||
let copy = dir.path().join(name);
|
||||
std::fs::write(©, unsaved)?;
|
||||
let php = crate::ops::run::container::PhpContainer::open(data_dir, root, target)?;
|
||||
let args = [
|
||||
php.path(&fixer.bin)?,
|
||||
"fix".into(),
|
||||
"--config".into(),
|
||||
php.path(&fixer.config)?,
|
||||
"--using-cache=no".into(),
|
||||
"--no-interaction".into(),
|
||||
"--show-progress=none".into(),
|
||||
format!("{PHP_CS_FIXER_COPY}/{}", name.to_string_lossy()),
|
||||
];
|
||||
let cwd = php.path(fixer.config.parent().unwrap_or(root))?;
|
||||
let volumes = [(dir.path().to_path_buf(), PHP_CS_FIXER_COPY.to_owned())];
|
||||
let (command, container) = php.command(&cwd, &volumes, &args)?;
|
||||
if let Err(error) = formatter::run_php_cs_fixer(command, &Default::default()) {
|
||||
// A run that timed out left its container behind.
|
||||
php.remove(&container);
|
||||
return Err(error);
|
||||
}
|
||||
fixed_edits(unsaved, &std::fs::read_to_string(©)?)
|
||||
}
|
||||
|
||||
/// The edits that turn `unsaved` into `formatted`.
|
||||
fn fixed_edits(unsaved: &str, formatted: &str) -> IdeResult<Vec<TextEdit>> {
|
||||
let text = ide_text::Document::new(unsaved);
|
||||
Ok(text
|
||||
.diff(&formatted)
|
||||
.diff(formatted)
|
||||
.changes
|
||||
.into_iter()
|
||||
.map(|c| TextEdit {
|
||||
@@ -745,8 +847,11 @@ async fn provider_edits(
|
||||
}
|
||||
let php = ide_sdk::apply::setting_path(&project.root, &settings.languages.php.interpreter);
|
||||
let tools = Tools::new(&host.local_data_dir);
|
||||
let edits = tokio::task::spawn_blocking(move || {
|
||||
php_cs_fixer_edits(&tools, php.as_deref(), &fixer, &snap.path, &snap.text)
|
||||
let container = crate::ops::run::container::php_target(&settings);
|
||||
let (data_dir, root) = (host.data_dir.clone(), project.root.clone());
|
||||
let edits = tokio::task::spawn_blocking(move || match container {
|
||||
Some(target) => php_cs_fixer_container_edits(&data_dir, &root, &target, &fixer, &snap.path, &snap.text),
|
||||
None => php_cs_fixer_edits(&tools, php.as_deref(), &fixer, &snap.path, &snap.text),
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
@@ -759,6 +864,39 @@ async fn provider_edits(
|
||||
}
|
||||
return Ok(Some(edits));
|
||||
}
|
||||
// CSharpier takes over Reformat Code for C# in projects that use it. It formats whole files
|
||||
// only, so ranges (a selection, generated code) stay with the language server, as in Rider.
|
||||
// It runs the project's tool, so Restricted Mode keeps the server too.
|
||||
if options.tool.is_none()
|
||||
&& range.is_none()
|
||||
&& project.require_trust().is_ok()
|
||||
&& let Some(command) = csharpier_for(&Tools::new(&host.local_data_dir), &snap.path, &project.root)
|
||||
{
|
||||
if options.on_save && !settings.editor.format_on_save {
|
||||
return Ok(None);
|
||||
}
|
||||
if snap.read_only {
|
||||
return Err(IdeError::invalid("The file is read-only"));
|
||||
}
|
||||
let command = command?;
|
||||
let (edits, excluded) = tokio::task::spawn_blocking(move || {
|
||||
let formatted = formatter::run_csharpier(command, &snap.text, &Default::default())?;
|
||||
if excluded_output(&snap.text, &formatted) {
|
||||
return Ok((Vec::new(), true));
|
||||
}
|
||||
Ok::<_, IdeError>((diff_edits(&ide_text::Document::new(&snap.text), &formatted), false))
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??;
|
||||
if excluded && !options.on_save {
|
||||
project.sink.emit(IdeEvent::Notify {
|
||||
level: NotifyLevel::Info,
|
||||
title: "CSharpier".into(),
|
||||
body: Some("CSharpier left the file unchanged: its configuration excludes it".into()),
|
||||
});
|
||||
}
|
||||
return Ok(Some(edits));
|
||||
}
|
||||
// dprint formats what its configuration covers, before the language's own formatters.
|
||||
let dprint = &settings.languages.dprint;
|
||||
let forced_dprint = options.tool == Some(ExternalFormatter::Dprint);
|
||||
@@ -952,7 +1090,7 @@ async fn provider_edits(
|
||||
}
|
||||
|
||||
/// The edits that turn `text` into `formatted`, one per changed region.
|
||||
fn diff_edits(text: &ide_text::Document, formatted: &str) -> Vec<TextEdit> {
|
||||
pub(crate) fn diff_edits(text: &ide_text::Document, formatted: &str) -> Vec<TextEdit> {
|
||||
text.diff(formatted)
|
||||
.changes
|
||||
.into_iter()
|
||||
@@ -1048,6 +1186,54 @@ mod tests {
|
||||
assert_eq!(external_tool(None, None, file, &settings).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csharpier_is_found_in_the_projects_tool_manifest() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("repo");
|
||||
let file = root.join("src/App/A.cs");
|
||||
let write = |path: &str, text: &str| {
|
||||
let path = dir.path().join(path);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
};
|
||||
let manifest = |name: &str, version: &str, is_root: bool| {
|
||||
format!(r#"{{"isRoot":{is_root},"tools":{{"{name}":{{"version":"{version}"}}}}}}"#)
|
||||
};
|
||||
// Outside the project it is not the project's.
|
||||
write("dotnet-tools.json", &manifest("csharpier", "1.0.0", true));
|
||||
assert_eq!(local_csharpier(&file, &root), None);
|
||||
// .NET 10 writes the manifest at the root; names are case-insensitive, a BOM is fine.
|
||||
write("repo/dotnet-tools.json", &format!("\u{feff}{}", manifest("CSharpier", "1.4.2", true)));
|
||||
assert_eq!(local_csharpier(&file, &root).as_deref(), Some("1.4.2"));
|
||||
// A nearer manifest without it passes the search on, unless it is the root one.
|
||||
write("repo/src/.config/dotnet-tools.json", &manifest("dotnet-ef", "10.0.0", false));
|
||||
assert_eq!(local_csharpier(&file, &root).as_deref(), Some("1.4.2"));
|
||||
write("repo/src/.config/dotnet-tools.json", &manifest("dotnet-ef", "10.0.0", true));
|
||||
assert_eq!(local_csharpier(&file, &root), None);
|
||||
write("repo/src/.config/dotnet-tools.json", "not json");
|
||||
assert_eq!(local_csharpier(&file, &root).as_deref(), Some("1.4.2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_csharp_files_of_csharpier_projects_leave_the_language_server() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let tools = Tools::new(&root.join("data"));
|
||||
let uses = |file: &str| csharpier_for(&tools, &root.join(file), root).is_some();
|
||||
assert!(!uses("A.cs"));
|
||||
// A configuration alone takes over only with a CSharpier installed (none on CI), else the
|
||||
// language server keeps formatting.
|
||||
std::fs::write(root.join(".csharpierrc"), "").unwrap();
|
||||
assert_eq!(uses("A.cs"), tools.formatter_command("csharpier", &root.join("A.cs"), None).is_ok());
|
||||
std::fs::write(root.join("dotnet-tools.json"), r#"{"tools":{"csharpier":{"version":"1.4.2"}}}"#).unwrap();
|
||||
// `.csx`, project files and other languages keep their formatter.
|
||||
for other in ["A.csx", "App.csproj", "a.fs"] {
|
||||
assert!(!uses(other), "{other}");
|
||||
}
|
||||
// Without `dotnet` this is the "SDK is not installed" error, still CSharpier's.
|
||||
assert!(uses("A.cs") && uses("B.CS"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ruff_is_the_python_external_formatter_and_is_opt_out() {
|
||||
let file = Path::new("/project/src/example.py");
|
||||
@@ -1214,6 +1400,27 @@ mod tests {
|
||||
assert_eq!(tool(None, "python", &svc, &settings).unwrap(), Some(Ruff));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_explicit_formatter_choice_beats_the_other_tools_configuration() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
let file = root.join("src/main.py");
|
||||
let mut settings = LanguagesSettings::default();
|
||||
std::fs::write(root.join("pyproject.toml"), "[tool.black]\nline-length = 100\n").unwrap();
|
||||
assert_eq!(tool(None, "python", &file, &settings).unwrap(), Some(Black));
|
||||
// Ruff selected on its page: it formats even below [tool.black].
|
||||
settings.ruff.prefer = true;
|
||||
assert_eq!(tool(None, "python", &file, &settings).unwrap(), Some(Ruff));
|
||||
// Both pages explicit falls back to the automatic answer (Black here).
|
||||
settings.black.prefer = true;
|
||||
assert_eq!(tool(None, "python", &file, &settings).unwrap(), Some(Black));
|
||||
// Black selected without any [tool.black]: Black still formats.
|
||||
settings.ruff.prefer = false;
|
||||
std::fs::remove_file(root.join("pyproject.toml")).unwrap();
|
||||
assert_eq!(tool(None, "python", &file, &settings).unwrap(), Some(Black));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn black_finds_its_configuration_like_black_does() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@@ -1523,6 +1730,51 @@ mod tests {
|
||||
assert_eq!(formatter::php_cs_fixer(&file).unwrap().config, root.join("src/.php-cs-fixer.dist.php"));
|
||||
}
|
||||
|
||||
/// With a real Docker daemon:
|
||||
/// `cargo test -p ide-host --lib formatter::tests::php_cs_fixer_fixes_the_copy_in -- --ignored`.
|
||||
#[test]
|
||||
#[ignore = "requires a Docker daemon and the php:8.3-cli image"]
|
||||
fn php_cs_fixer_fixes_the_copy_in_a_container_run_target() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join("vendor/bin")).unwrap();
|
||||
std::fs::create_dir_all(root.join("src")).unwrap();
|
||||
std::fs::write(root.join(".php-cs-fixer.dist.php"), "<?php").unwrap();
|
||||
// Stands in for PHP-CS-Fixer: it needs the configuration, runs beside it, and indents
|
||||
// the file it is given.
|
||||
let stand_in = r#"<?php
|
||||
$file = end($argv);
|
||||
if ($argv[1] !== 'fix' || !is_file($argv[3]) || getcwd() !== dirname($argv[3]) || getenv('XDEBUG_MODE') !== 'off') {
|
||||
fwrite(STDERR, 'unexpected run: ' . getcwd() . ' ' . implode(' ', $argv));
|
||||
exit(16);
|
||||
}
|
||||
file_put_contents($file, str_replace(' echo', ' echo', file_get_contents($file)));
|
||||
"#;
|
||||
std::fs::write(root.join("vendor/bin/php-cs-fixer"), stand_in).unwrap();
|
||||
let file = root.join("src").join("Kernel.php");
|
||||
let fixer = formatter::php_cs_fixer(&file).unwrap();
|
||||
let target = ide_core::remote_settings::RunTarget {
|
||||
kind: ide_core::remote_settings::RunTargetKind::Docker,
|
||||
id: "php".into(),
|
||||
name: "PHP".into(),
|
||||
image: "php:8.3-cli".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let data = root.join("data");
|
||||
let edits = php_cs_fixer_container_edits(&data, &root, &target, &fixer, &file, "<?php\n echo 1;\n").unwrap();
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].new_text, " ");
|
||||
assert!(!file.exists(), "the file on disk is left alone");
|
||||
|
||||
std::fs::write(
|
||||
root.join("vendor/bin/php-cs-fixer"),
|
||||
"<?php fwrite(STDERR, 'Configuration file is invalid'); exit(16);",
|
||||
)
|
||||
.unwrap();
|
||||
let err = php_cs_fixer_container_edits(&data, &root, &target, &fixer, &file, "<?php\n").unwrap_err();
|
||||
assert!(err.message.contains("Configuration file is invalid"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn php_cs_fixer_fixes_a_copy_of_the_unsaved_text() {
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
use ide_build::kotlin_bridge::{self, Outcome, ProjectLibraries};
|
||||
use ide_core::event::NotifyLevel;
|
||||
use ide_core::{CancellationToken, Diagnostic, IdeEvent, Pos, Range, Severity, SharedSink, TaskId};
|
||||
use ide_core::{
|
||||
CancellationToken, Diagnostic, IdeError, IdeEvent, IdeResult, Pos, Range, Severity, SharedSink, TaskId,
|
||||
};
|
||||
use ide_lsp::LspManager;
|
||||
use ide_workspace::SettingsStore;
|
||||
use ide_workspace::documents::DocumentObserver;
|
||||
@@ -20,6 +22,10 @@ use tokio::sync::Notify;
|
||||
const DELAY: Duration = Duration::from_millis(750);
|
||||
const SOURCE: &str = "kotlin-bridge";
|
||||
const COMMAND: &str = "openidea.kotlin.replace";
|
||||
/// How long a snapshot waits for jdtls to import the project, before it is sent regardless.
|
||||
const IMPORT_WAIT: Duration = Duration::from_secs(30 * 60);
|
||||
/// The pauses before a snapshot jdtls did not take is sent again.
|
||||
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(5), Duration::from_secs(15), Duration::from_secs(45)];
|
||||
|
||||
#[derive(Default)]
|
||||
struct Revision {
|
||||
@@ -133,13 +139,50 @@ impl KotlinBridge {
|
||||
self.revision.lock().cancel.cancel();
|
||||
}
|
||||
|
||||
async fn replace(&self, projects: &[ProjectLibraries], cancel: &CancellationToken) -> ide_core::IdeResult<()> {
|
||||
let snapshot = serde_json::to_value(projects).map_err(|e| ide_core::IdeError::internal(e.to_string()))?;
|
||||
/// Hands `projects` to jdtls once it imported the project, again after a pause when it
|
||||
/// timed out, refused or went away. A jdtls that was stopped is not started again.
|
||||
async fn replace(&self, projects: &[ProjectLibraries], cancel: &CancellationToken) -> IdeResult<()> {
|
||||
let deadline = tokio::time::Instant::now() + IMPORT_WAIT;
|
||||
let mut delays = RETRY_DELAYS.iter();
|
||||
loop {
|
||||
let Err(error) = self.try_replace(projects, deadline, cancel).await else { return Ok(()) };
|
||||
let Some(delay) = delays.next() else { return Err(error) };
|
||||
if cancel.is_cancelled() || self.lsp.jdtls_stopped(&self.root) {
|
||||
return Err(error);
|
||||
}
|
||||
tracing::info!("Kotlin libraries: {error}; trying again in {} s", delay.as_secs());
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return Err(IdeError::cancelled()),
|
||||
_ = tokio::time::sleep(*delay) => {}
|
||||
}
|
||||
if self.lsp.jdtls_stopped(&self.root) {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`replace`](Self::replace), with a background task while it waits for the import.
|
||||
async fn publish(&self, projects: &[ProjectLibraries], cancel: &CancellationToken) -> IdeResult<()> {
|
||||
let _waiting = (!self.lsp.jdtls_imported(&self.root)).then(|| {
|
||||
let task = BuildTask::start(self.sink.clone(), cancel);
|
||||
task.emit(Some("Waiting for jdtls to import the project".into()), None, false);
|
||||
task
|
||||
});
|
||||
self.replace(projects, cancel).await
|
||||
}
|
||||
|
||||
async fn try_replace(
|
||||
&self,
|
||||
projects: &[ProjectLibraries],
|
||||
deadline: tokio::time::Instant,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<()> {
|
||||
let snapshot = serde_json::to_value(projects).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
self.lsp.wait_jdtls_imported(&self.root, deadline, cancel).await?;
|
||||
let response = self.lsp.jdtls_command_cancellable(&self.root, COMMAND, vec![snapshot], cancel).await?;
|
||||
if response.as_u64().is_none() {
|
||||
return Err(ide_core::IdeError::unavailable(
|
||||
"Kotlin bridge command did not acknowledge its library snapshot",
|
||||
));
|
||||
return Err(IdeError::unavailable("Kotlin bridge command did not acknowledge its library snapshot"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -211,7 +254,7 @@ impl KotlinBridge {
|
||||
};
|
||||
// Clear entries persisted by an earlier incarnation only before our first build.
|
||||
if !initialized {
|
||||
if let Err(error) = self.replace(&[], &cancel).await {
|
||||
if let Err(error) = self.publish(&[], &cancel).await {
|
||||
if !cancel.is_cancelled() {
|
||||
self.failure(error.message, &mut diagnostics, &mut last_failure);
|
||||
}
|
||||
@@ -238,7 +281,7 @@ impl KotlinBridge {
|
||||
}
|
||||
match result {
|
||||
Ok(Ok(Outcome { success: true, projects, .. })) => {
|
||||
match self.replace(&projects, &cancel).await {
|
||||
match self.publish(&projects, &cancel).await {
|
||||
Ok(()) => {
|
||||
for old in published.drain(..) {
|
||||
remove_directory(old).await;
|
||||
@@ -423,6 +466,9 @@ impl DocumentObserver for KotlinBridge {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod replace_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
//! The bridge against an in-memory jdtls that is still importing, refuses a snapshot or goes
|
||||
//! away (#7726). Maven is a fake `mvnw` that reports a build without modules.
|
||||
|
||||
use super::*;
|
||||
use ide_jsonrpc::{Handler, Peer};
|
||||
use ide_language::{LanguageRegistry, LanguageServerConfig};
|
||||
use ide_lsp::{LaunchError, Launcher};
|
||||
use serde_json::{Value, json};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::time::Instant;
|
||||
|
||||
/// Longer than the time a command may take once it was sent.
|
||||
const LONG_IMPORT: Duration = Duration::from_secs(300);
|
||||
const PAST_RETRY: Duration = Duration::from_secs(60);
|
||||
|
||||
#[derive(Default)]
|
||||
struct Jdtls {
|
||||
launches: AtomicUsize,
|
||||
/// Whether each snapshot arrived after the running instance's `ServiceReady`.
|
||||
replaces: Mutex<Vec<bool>>,
|
||||
/// The snapshots refused from now on, by their position among all.
|
||||
refused: Mutex<Vec<usize>>,
|
||||
/// Requests are not answered while set.
|
||||
stuck: AtomicBool,
|
||||
importing: AtomicBool,
|
||||
ready: AtomicBool,
|
||||
peer: Mutex<Option<Peer>>,
|
||||
}
|
||||
|
||||
impl Jdtls {
|
||||
fn finish_import(&self) {
|
||||
self.ready.store(true, Ordering::SeqCst);
|
||||
let peer = self.peer.lock().clone().unwrap();
|
||||
peer.notify("language/status", json!({ "type": "ServiceReady", "message": "ServiceReady" })).unwrap();
|
||||
}
|
||||
|
||||
fn replaces(&self) -> Vec<bool> {
|
||||
self.replaces.lock().clone()
|
||||
}
|
||||
}
|
||||
|
||||
struct Server(Arc<Jdtls>);
|
||||
|
||||
impl Handler for Server {
|
||||
fn on_notification(&self, method: &str, _: Value) {
|
||||
if method == "initialized" && !self.0.importing.load(Ordering::SeqCst) {
|
||||
self.0.finish_import();
|
||||
}
|
||||
}
|
||||
|
||||
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
|
||||
match method {
|
||||
"initialize" => Ok(json!({ "capabilities": {} })),
|
||||
"workspace/executeCommand" if params["command"] == COMMAND => {
|
||||
let position = {
|
||||
let mut replaces = self.0.replaces.lock();
|
||||
replaces.push(self.0.ready.load(Ordering::SeqCst));
|
||||
replaces.len() - 1
|
||||
};
|
||||
while self.0.stuck.load(Ordering::SeqCst) {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
if self.0.refused.lock().contains(&position) {
|
||||
return Err((-32603, "Workspace is locked".into()));
|
||||
}
|
||||
Ok(json!(0))
|
||||
}
|
||||
_ => Ok(Value::Null),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Launch(Arc<Jdtls>);
|
||||
|
||||
impl Launcher for Launch {
|
||||
fn launch(
|
||||
&self,
|
||||
config: &LanguageServerConfig,
|
||||
_: &Path,
|
||||
handler: Arc<dyn Handler>,
|
||||
_: Box<dyn Fn(String) + Send + Sync>,
|
||||
) -> Result<Peer, LaunchError> {
|
||||
if config.name != "jdtls" {
|
||||
return Err(LaunchError::Missing);
|
||||
}
|
||||
self.0.launches.fetch_add(1, Ordering::SeqCst);
|
||||
self.0.ready.store(false, Ordering::SeqCst);
|
||||
let (client, server) = tokio::io::duplex(1 << 20);
|
||||
let (r, w) = tokio::io::split(server);
|
||||
*self.0.peer.lock() = Some(Peer::connect(r, w, Arc::new(Server(self.0.clone()))));
|
||||
let (r, w) = tokio::io::split(client);
|
||||
Ok(Peer::connect(r, w, handler))
|
||||
}
|
||||
}
|
||||
|
||||
/// A background task's message (`None` when it starts or ends) and whether it is done.
|
||||
type TaskUpdate = (Option<String>, bool);
|
||||
|
||||
struct Fixture {
|
||||
_tmp: tempfile::TempDir,
|
||||
jdtls: Arc<Jdtls>,
|
||||
lsp: Arc<LspManager>,
|
||||
bridge: Arc<KotlinBridge>,
|
||||
tasks: Arc<Mutex<Vec<TaskUpdate>>>,
|
||||
failures: Arc<Mutex<Vec<String>>>,
|
||||
}
|
||||
|
||||
fn start(importing: bool, refused: &[usize]) -> Fixture {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let root = base.join("p");
|
||||
std::fs::create_dir_all(root.join("src/main/kotlin")).unwrap();
|
||||
std::fs::write(
|
||||
root.join("pom.xml"),
|
||||
"<project><groupId>g</groupId><artifactId>a</artifactId><version>1</version></project>",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(root.join("src/main/kotlin/K.kt"), "class K\n").unwrap();
|
||||
std::fs::write(
|
||||
root.join("mvnw"),
|
||||
"#!/bin/sh\nfor a; do case \"$a\" in -Dopenidea.kotlin.staging=*) echo '[]' > \"$(dirname \"${a#*=}\")/modules.json\";; esac; done\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(root.join("mvnw"), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let jdtls = Arc::new(Jdtls::default());
|
||||
jdtls.importing.store(importing, Ordering::SeqCst);
|
||||
*jdtls.refused.lock() = refused.to_vec();
|
||||
let tasks: Arc<Mutex<Vec<_>>> = Arc::default();
|
||||
let failures: Arc<Mutex<Vec<String>>> = Arc::default();
|
||||
let sink: SharedSink = Arc::new({
|
||||
let (tasks, failures) = (tasks.clone(), failures.clone());
|
||||
move |e: IdeEvent| match e {
|
||||
IdeEvent::Task { title, message, done, .. } if title == BuildTask::TITLE => {
|
||||
tasks.lock().push((message, done))
|
||||
}
|
||||
IdeEvent::Notify { body, .. } => failures.lock().push(body.unwrap_or_default()),
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
let languages = Arc::new(LanguageRegistry::load(None).unwrap());
|
||||
let lsp = LspManager::with_launcher(root.clone(), languages, sink.clone(), Arc::new(Launch(jdtls.clone())));
|
||||
let bridge = KotlinBridge::new(
|
||||
root,
|
||||
base.join("cache"),
|
||||
&base.join("data"),
|
||||
Arc::new(SettingsStore::load(&base.join("config"), None)),
|
||||
lsp.clone(),
|
||||
sink,
|
||||
Arc::new(AtomicBool::new(true)),
|
||||
);
|
||||
bridge.start(&tokio::runtime::Handle::current());
|
||||
Fixture { _tmp: tmp, jdtls, lsp, bridge, tasks, failures }
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
self.jdtls.stuck.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
/// The bridge asked for jdtls and it was told `initialized`.
|
||||
async fn until_running(&self) {
|
||||
until("jdtls to run", || self.lsp.servers().iter().any(|s| s.name == "jdtls" && is_up(s.status))).await;
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
|
||||
async fn until_published(&self, replaces: usize) {
|
||||
until("the libraries to be published", || self.jdtls.replaces().len() == replaces).await;
|
||||
until("the task to end", || self.tasks.lock().last().is_some_and(|(_, done)| *done)).await;
|
||||
}
|
||||
|
||||
fn jdtls_id(&self) -> ide_core::ServerId {
|
||||
self.lsp.servers().iter().find(|s| s.name == "jdtls").unwrap().id
|
||||
}
|
||||
}
|
||||
|
||||
fn is_up(status: ide_core::event::ServerStatus) -> bool {
|
||||
matches!(status, ide_core::event::ServerStatus::Ready | ide_core::event::ServerStatus::Busy)
|
||||
}
|
||||
|
||||
async fn until(what: &str, done: impl Fn() -> bool) {
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while !done() {
|
||||
assert!(Instant::now() < deadline, "timed out waiting for {what}");
|
||||
tokio::time::sleep(Duration::from_millis(20)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves every timer on by `time` and lets what it wakes run.
|
||||
async fn skip(time: Duration) {
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(time).await;
|
||||
tokio::time::resume();
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_snapshot_waits_for_an_import_longer_than_the_command_timeout() {
|
||||
let f = start(true, &[]);
|
||||
f.until_running().await;
|
||||
skip(LONG_IMPORT).await;
|
||||
assert_eq!((f.jdtls.replaces(), f.failures.lock().clone()), (vec![], vec![]));
|
||||
let waiting = f.tasks.lock().last().cloned().unwrap();
|
||||
assert!(waiting.0.is_some_and(|m| m.contains("import")) && !waiting.1, "the wait shows in the status bar");
|
||||
f.jdtls.finish_import();
|
||||
f.until_published(2).await;
|
||||
assert_eq!(f.jdtls.replaces(), [true, true], "only after ServiceReady");
|
||||
assert!(f.failures.lock().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refused_snapshots_are_sent_again() {
|
||||
// The first snapshot clears earlier libraries, the third publishes the built ones.
|
||||
let f = start(false, &[0, 2]);
|
||||
until("the first snapshot", || f.jdtls.replaces().len() == 1).await;
|
||||
skip(PAST_RETRY).await;
|
||||
until("the built snapshot", || f.jdtls.replaces().len() == 3).await;
|
||||
skip(PAST_RETRY).await;
|
||||
f.until_published(4).await;
|
||||
assert!(f.failures.lock().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_snapshot_that_times_out_is_sent_again() {
|
||||
let f = start(false, &[]);
|
||||
f.jdtls.stuck.store(true, Ordering::SeqCst);
|
||||
until("the first snapshot", || f.jdtls.replaces().len() == 1).await;
|
||||
skip(LONG_IMPORT).await;
|
||||
f.jdtls.stuck.store(false, Ordering::SeqCst);
|
||||
skip(PAST_RETRY).await;
|
||||
f.until_published(3).await;
|
||||
assert!(f.failures.lock().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_snapshot_refused_every_time_is_reported_once_and_dropped() {
|
||||
let f = start(false, &[0, 1, 2, 3, 4, 5, 6, 7]);
|
||||
for attempt in 1..=1 + RETRY_DELAYS.len() {
|
||||
until("the next attempt", || f.jdtls.replaces().len() == attempt).await;
|
||||
skip(PAST_RETRY).await;
|
||||
}
|
||||
until("the failure", || !f.failures.lock().is_empty()).await;
|
||||
skip(LONG_IMPORT).await;
|
||||
assert_eq!(f.jdtls.replaces().len(), 1 + RETRY_DELAYS.len());
|
||||
assert!(matches!(&f.failures.lock()[..], [text] if text.contains("Workspace is locked")));
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_restart_during_the_import_waits_for_the_new_instance() {
|
||||
let f = start(true, &[]);
|
||||
f.until_running().await;
|
||||
f.lsp.restart(f.jdtls_id()).await.unwrap();
|
||||
skip(LONG_IMPORT).await;
|
||||
assert_eq!(f.jdtls.launches.load(Ordering::SeqCst), 2);
|
||||
f.jdtls.finish_import();
|
||||
f.until_published(2).await;
|
||||
assert_eq!(f.jdtls.replaces(), [true, true]);
|
||||
assert!(f.failures.lock().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_server_lost_during_the_import_is_waited_for_again() {
|
||||
let f = start(true, &[]);
|
||||
f.until_running().await;
|
||||
f.jdtls.peer.lock().take().unwrap().kill();
|
||||
until("the restart after the crash", || f.jdtls.launches.load(Ordering::SeqCst) == 2).await;
|
||||
f.until_running().await;
|
||||
f.jdtls.finish_import();
|
||||
skip(PAST_RETRY).await;
|
||||
f.until_published(2).await;
|
||||
assert_eq!(f.jdtls.replaces(), [true, true]);
|
||||
assert!(f.failures.lock().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stopping_jdtls_ends_the_wait_and_does_not_start_it_again() {
|
||||
let f = start(true, &[]);
|
||||
f.until_running().await;
|
||||
f.lsp.stop(f.jdtls_id()).await.unwrap();
|
||||
until("the failure", || !f.failures.lock().is_empty()).await;
|
||||
skip(LONG_IMPORT).await;
|
||||
assert_eq!(f.jdtls.launches.load(Ordering::SeqCst), 1);
|
||||
assert!(f.jdtls.replaces().is_empty());
|
||||
f.bridge.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_the_project_ends_the_wait_at_once() {
|
||||
let f = start(true, &[]);
|
||||
f.until_running().await;
|
||||
let closing = Instant::now();
|
||||
f.bridge.shutdown().await;
|
||||
assert!(closing.elapsed() < Duration::from_secs(5), "{:?}", closing.elapsed());
|
||||
assert!(f.jdtls.replaces().is_empty());
|
||||
assert!(f.failures.lock().is_empty());
|
||||
assert!(f.tasks.lock().last().is_some_and(|(_, done)| *done), "the status bar task ends");
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub mod catalogue;
|
||||
#[cfg(unix)]
|
||||
pub mod daemon;
|
||||
pub mod data_dirs;
|
||||
pub mod devcontainer;
|
||||
pub mod diagnostics_store;
|
||||
mod direnv;
|
||||
pub mod environment;
|
||||
@@ -24,6 +25,8 @@ mod phpstan;
|
||||
pub mod plugins;
|
||||
mod project;
|
||||
mod proxy;
|
||||
mod python_move;
|
||||
mod python_signature;
|
||||
pub mod relay;
|
||||
mod requests;
|
||||
pub mod rpc;
|
||||
@@ -91,6 +94,7 @@ impl HostConfig {
|
||||
}
|
||||
|
||||
pub struct Host {
|
||||
pub(crate) local_desktop: bool,
|
||||
local_database_tunnels: bool,
|
||||
/// Finders of non-Git working copies ([`Host::with_vcs_provider`]); Git is built in.
|
||||
pub(crate) vcs_providers: Vec<Arc<dyn ide_vcs::BackendProvider>>,
|
||||
@@ -106,6 +110,8 @@ pub struct Host {
|
||||
pub mcp_requests: mcp::Requests,
|
||||
/// Commands agents run in the Run tool window (`run_command`).
|
||||
pub mcp_agent_runs: mcp::AgentRuns,
|
||||
/// Dev containers a window is attached to; the MCP tools leave them alone.
|
||||
pub dev_containers_attached: Arc<devcontainer::AttachedContainers>,
|
||||
/// Projects the MCP server serves without a window.
|
||||
pub mcp_background: mcp::BackgroundProjects,
|
||||
/// Host-owned scheduled agent automations and in-session follow-up timers.
|
||||
@@ -212,6 +218,12 @@ impl Host {
|
||||
windows
|
||||
}
|
||||
|
||||
/// Enables tools that control services on the local desktop.
|
||||
pub fn with_local_desktop(mut self) -> Self {
|
||||
self.local_desktop = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Enables user-approved database helper processes on the local desktop.
|
||||
pub fn with_local_database_tunnels(mut self) -> Self {
|
||||
self.local_database_tunnels = true;
|
||||
@@ -262,6 +274,7 @@ impl Host {
|
||||
let automations = automations::AutomationService::new(&data_dir, boot_override);
|
||||
let host = Self {
|
||||
plugin_host: RwLock::default(),
|
||||
local_desktop: false,
|
||||
local_database_tunnels: false,
|
||||
vcs_providers: Vec::new(),
|
||||
subversion: None,
|
||||
@@ -271,6 +284,7 @@ impl Host {
|
||||
mcp_reports: Default::default(),
|
||||
mcp_requests: Default::default(),
|
||||
mcp_agent_runs: Default::default(),
|
||||
dev_containers_attached: Default::default(),
|
||||
mcp_background: Default::default(),
|
||||
automations,
|
||||
agent_catalogs: Arc::default(),
|
||||
@@ -502,7 +516,6 @@ impl Host {
|
||||
watch.stop();
|
||||
}
|
||||
project.documents.clear_workspace_edit_history();
|
||||
project.agents.detach_sinks();
|
||||
project.flutter.stop();
|
||||
project.devtools.stop();
|
||||
project.widget_preview.stop();
|
||||
@@ -515,8 +528,11 @@ impl Host {
|
||||
let shutdown_agents = if !project.light
|
||||
&& self.automations.retain_on_window_close(self, &project.root, &project.agents, agent_reason)
|
||||
{
|
||||
// Keep internal automation watchers/peer bridges subscribed while dropping UI sinks.
|
||||
project.agents.detach_ui_sinks();
|
||||
Vec::new()
|
||||
} else {
|
||||
project.agents.detach_sinks();
|
||||
vec![project.agents.clone()]
|
||||
};
|
||||
let handle = self.spawn_project_shutdown(ShutdownWork {
|
||||
|
||||
@@ -0,0 +1,979 @@
|
||||
//! Built-in MCP tools for inspecting, previewing, configuring, and controlling
|
||||
//! Agent Automations (`list_automations`, `preview_automation_schedule`,
|
||||
//! `save_automation`, `control_automation`, and `schedule_next_run`).
|
||||
//!
|
||||
//! Safety invariants:
|
||||
//! - Read-only tools (`list_automations`, `preview_automation_schedule`) are strictly scoped
|
||||
//! to the target project (`call.root()`), never exposing `ChatOnly` or other projects' data.
|
||||
//! - Project mutating tools (`save_automation`, `control_automation`) refuse recursive invocations
|
||||
//! from unattended scheduled agent turns, never modify host-level login-service or
|
||||
//! approval-ceiling settings, and always ask for interactive confirmation in an open trusted
|
||||
//! project window (even when MCP brave mode is enabled).
|
||||
//! - Self-chaining (`schedule_next_run`) requires zero human confirmation ONLY when the calling
|
||||
//! session belongs to an automation whose user-configured `allowAgentSchedule` flag is `true`,
|
||||
//! updates ONLY that single automation's next firing time and prompt (never creating additional
|
||||
//! automations or widening workspace/permission boundaries), enforces a 60s minimum delay, and
|
||||
//! respects `maxRuns` and `disableAfterMs` stop limits.
|
||||
|
||||
use crate::Host;
|
||||
use crate::automations::SelfScheduleTime;
|
||||
use crate::mcp::page::{OFFSET, Page};
|
||||
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
|
||||
use ide_agent::{
|
||||
AgentAutomation, AgentConfigChoice, AgentPrompt, AutomationContinuity, AutomationPermissionMode, AutomationTrigger,
|
||||
AutomationWorkspace, Isolation, SaveAutomationInput, export_markdown, format_trigger_timestamp,
|
||||
parse_iso_timestamp_ms, parse_markdown,
|
||||
};
|
||||
use ide_core::settings::{AutomationMisfirePolicy, NewTaskApprovals};
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
const DEFAULT_AUTOMATIONS_LIMIT: usize = 100;
|
||||
const DEFAULT_RUNS_LIMIT: u32 = 20;
|
||||
const MAX_RUNS_LIMIT: u32 = 200;
|
||||
const PROMPT_PREVIEW_CHARS: usize = 400;
|
||||
|
||||
pub fn tools() -> Vec<Tool> {
|
||||
vec![
|
||||
list_automations(),
|
||||
preview_automation_schedule(),
|
||||
save_automation(),
|
||||
control_automation(),
|
||||
schedule_next_run(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Standalone tools exposed to an internal automation `caller_task` even when its working folder
|
||||
/// is not an open project window (e.g. `ChatOnly` or headless `--scheduler` runs).
|
||||
pub(super) fn standalone_task_tools() -> Vec<ide_mcp::Tool> {
|
||||
vec![schedule_next_run().metadata, preview_automation_schedule().metadata]
|
||||
}
|
||||
|
||||
fn trigger_schema(description: &'static str) -> Value {
|
||||
json!({
|
||||
"type": "object",
|
||||
"description": description,
|
||||
"properties": {
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"enum": ["manual", "hourly", "daily", "weekdays", "weekly", "cron", "oneShot"],
|
||||
"description": "Schedule kind"
|
||||
},
|
||||
"minute": {
|
||||
"type": "integer",
|
||||
"description": "Minute of the hour (0..=59) for `hourly`, `daily`, `weekdays`, and `weekly`"
|
||||
},
|
||||
"hour": {
|
||||
"type": "integer",
|
||||
"description": "Hour of the day in 24-hour time (0..=23) for `daily`, `weekdays`, and `weekly`"
|
||||
},
|
||||
"days": {
|
||||
"type": "array",
|
||||
"items": { "type": "integer" },
|
||||
"description": "Weekdays (0 = Sunday .. 6 = Saturday) for `weekly`"
|
||||
},
|
||||
"expression": {
|
||||
"type": "string",
|
||||
"description": "5-field cron expression (`minute hour day-of-month month day-of-week`) for `cron`"
|
||||
},
|
||||
"timeZone": {
|
||||
"type": "string",
|
||||
"description": "IANA timezone name (for example `America/Los_Angeles` or `UTC`), or `local` (default)"
|
||||
},
|
||||
"runAtMs": {
|
||||
"type": "number",
|
||||
"description": "Epoch timestamp in milliseconds for `oneShot`"
|
||||
}
|
||||
},
|
||||
"required": ["kind"]
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_trigger_value(raw: &Value) -> IdeResult<AutomationTrigger> {
|
||||
let mut normalized = raw.clone();
|
||||
if let Some(obj) = normalized.as_object_mut() {
|
||||
let needs_tz = matches!(
|
||||
obj.get("kind").and_then(Value::as_str),
|
||||
Some("hourly" | "daily" | "weekdays" | "weekly" | "cron")
|
||||
);
|
||||
if needs_tz && !obj.contains_key("timeZone") {
|
||||
obj.insert("timeZone".into(), Value::String("local".into()));
|
||||
}
|
||||
}
|
||||
serde_json::from_value::<AutomationTrigger>(normalized)
|
||||
.map_err(|e| IdeError::invalid(format!("invalid `trigger`: {e}")))
|
||||
}
|
||||
|
||||
fn ensure_not_scheduled_caller(call: &Call) -> IdeResult<()> {
|
||||
if call.caller_session.as_ref().is_some_and(|c| c.in_scheduled_turn) {
|
||||
return Err(IdeError::invalid(
|
||||
"Unattended scheduled runs cannot create, modify, enable, delete, or trigger automations; use schedule_next_run if self-scheduling is enabled on this automation",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_project_owns_automation(host: &Host, project_root: &Path, id: &str) -> IdeResult<AgentAutomation> {
|
||||
let canon_project = dunce::canonicalize(project_root).unwrap_or_else(|_| project_root.to_path_buf());
|
||||
let Some(auto) = host.automations.get(id) else {
|
||||
return Err(IdeError::not_found(format!("unknown automation '{id}'")));
|
||||
};
|
||||
match &auto.workspace {
|
||||
AutomationWorkspace::Project { root, .. } => {
|
||||
let canon_auto = dunce::canonicalize(&root.0).unwrap_or_else(|_| root.0.clone());
|
||||
if canon_auto != canon_project {
|
||||
return Err(IdeError::not_found(format!("unknown automation '{id}'")));
|
||||
}
|
||||
}
|
||||
AutomationWorkspace::ChatOnly => {
|
||||
return Err(IdeError::not_found(format!("unknown automation '{id}'")));
|
||||
}
|
||||
}
|
||||
Ok(auto)
|
||||
}
|
||||
|
||||
fn format_automation_json(auto: &AgentAutomation, include_markdown: bool) -> IdeResult<Value> {
|
||||
let mut val = serde_json::to_value(auto).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
if let Some(obj) = val.as_object_mut() {
|
||||
obj.insert("triggerSummary".into(), Value::String(auto.trigger.summary()));
|
||||
if let Some(next_ms) = auto.next_run_ms
|
||||
&& let Some(iso) = format_trigger_timestamp(&auto.trigger, next_ms)
|
||||
{
|
||||
obj.insert("nextRunIso".into(), Value::String(iso));
|
||||
}
|
||||
if let Some(ov_ms) = auto.next_run_override_ms
|
||||
&& let Some(iso) = format_trigger_timestamp(&auto.trigger, ov_ms)
|
||||
{
|
||||
obj.insert("nextRunOverrideIso".into(), Value::String(iso));
|
||||
}
|
||||
if include_markdown {
|
||||
obj.insert("markdown".into(), Value::String(export_markdown(auto)?));
|
||||
}
|
||||
}
|
||||
Ok(val)
|
||||
}
|
||||
|
||||
fn truncate_preview(text: &str, max_chars: usize) -> String {
|
||||
let trimmed = text.trim();
|
||||
let count = trimmed.chars().count();
|
||||
if count <= max_chars {
|
||||
trimmed.to_owned()
|
||||
} else {
|
||||
let mut head: String = trimmed.chars().take(max_chars).collect();
|
||||
head.push('…');
|
||||
head
|
||||
}
|
||||
}
|
||||
|
||||
fn describe_effective_permissions(host: &Host, requested: AutomationPermissionMode) -> String {
|
||||
let ceiling = host.global_settings.effective().agents.new_task_approvals;
|
||||
let req_label = match requested {
|
||||
AutomationPermissionMode::Default => "default (ask before edits and commands)",
|
||||
AutomationPermissionMode::Assisted => "assisted (auto-accept workspace edits, ask before commands)",
|
||||
AutomationPermissionMode::AllowAll => "allowAll (auto-approve within command policy)",
|
||||
};
|
||||
match (requested, ceiling) {
|
||||
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Ask)
|
||||
| (AutomationPermissionMode::Assisted, NewTaskApprovals::Ask) => {
|
||||
format!("{req_label} — capped at runtime to `ask` by Settings › Agents › New task approvals")
|
||||
}
|
||||
_ => req_label.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
fn prepend_brave_mode_note(host: &Host, detail: String) -> String {
|
||||
if host.global_settings.effective().mcp_server.run_without_confirmation {
|
||||
format!(
|
||||
"Note: automation schedules always ask first, even with \"Run tools without confirmation\" (brave mode) on.\n\n{detail}"
|
||||
)
|
||||
} else {
|
||||
detail
|
||||
}
|
||||
}
|
||||
|
||||
fn list_automations() -> Tool {
|
||||
Tool::new(
|
||||
"list_automations",
|
||||
"Lists the project's Agent Automations, recent run history, active in-session schedules (`Send Later` / `/loop`), and scheduler status.
|
||||
Scoped strictly to the target project. Pass `automationId` to inspect one automation (and its runs), or `includeMarkdown=true` to include portable `.automation.md` definitions.",
|
||||
|call| async move {
|
||||
let page = Page::of(&call, DEFAULT_AUTOMATIONS_LIMIT)?;
|
||||
let filter_id = call.opt_str("automationId")?;
|
||||
let include_runs = call.flag("includeRuns", true)?;
|
||||
let include_markdown = call.flag("includeMarkdown", false)?;
|
||||
let runs_limit = match call.opt_i64("runsLimit")? {
|
||||
None => DEFAULT_RUNS_LIMIT,
|
||||
Some(n) if n <= 0 => return Err(IdeError::invalid("runsLimit must be > 0")),
|
||||
Some(n) => (n as u32).min(MAX_RUNS_LIMIT),
|
||||
};
|
||||
let host = call.host();
|
||||
let h = host.clone();
|
||||
let project_agents = call.project.agents.clone();
|
||||
let root = dunce::canonicalize(call.root()).unwrap_or_else(|_| call.root().to_path_buf());
|
||||
host.blocking(move || {
|
||||
let roots = [root];
|
||||
let automations = if let Some(ref id) = filter_id {
|
||||
vec![ensure_project_owns_automation(&h, &roots[0], id)?]
|
||||
} else {
|
||||
h.automations.list_scoped(Some(&roots), false)
|
||||
};
|
||||
let mut out = Map::new();
|
||||
let paged = page.take(automations, &mut out);
|
||||
let items: Vec<Value> = paged
|
||||
.iter()
|
||||
.map(|a| format_automation_json(a, include_markdown))
|
||||
.collect::<IdeResult<_>>()?;
|
||||
out.insert("automations".into(), Value::Array(items));
|
||||
out.insert("availableProviders".into(), json!(project_agents.known_provider_ids()));
|
||||
|
||||
if include_runs {
|
||||
let runs_page = h.automations.runs_scoped(
|
||||
Some(&roots),
|
||||
false,
|
||||
filter_id.as_deref(),
|
||||
None,
|
||||
Some(runs_limit),
|
||||
);
|
||||
out.insert(
|
||||
"runs".into(),
|
||||
serde_json::to_value(runs_page.runs).map_err(|e| IdeError::internal(e.to_string()))?,
|
||||
);
|
||||
}
|
||||
|
||||
let session_schedules = h.automations.list_session_schedules_scoped(Some(&roots), None);
|
||||
out.insert(
|
||||
"sessionSchedules".into(),
|
||||
serde_json::to_value(session_schedules).map_err(|e| IdeError::internal(e.to_string()))?,
|
||||
);
|
||||
|
||||
let status = h.automations.host_status(&h, false, String::new());
|
||||
let auto_start_enabled = h.global_settings.effective().agents.automations.auto_start_service;
|
||||
out.insert(
|
||||
"scheduler".into(),
|
||||
json!({
|
||||
"activeSchedules": status.active_schedules,
|
||||
"runningRuns": status.running_runs,
|
||||
"needsInputRuns": status.needs_input_runs,
|
||||
"unreadRuns": status.unread_runs,
|
||||
"nextRunMs": status.next_run_ms,
|
||||
"autoStartServiceEnabled": auto_start_enabled,
|
||||
"bootServiceKind": status.boot_service_kind,
|
||||
"bootServiceRegistered": status.boot_service_registered,
|
||||
}),
|
||||
);
|
||||
Output::json(Value::Object(out))
|
||||
})
|
||||
.await
|
||||
},
|
||||
)
|
||||
.param(Param::optional("automationId", ParamType::String, "Optional automation ID in this project to inspect"))
|
||||
.param(Param::optional("includeRuns", ParamType::Boolean, "Include recent run history (default true)"))
|
||||
.param(Param::optional(
|
||||
"runsLimit",
|
||||
ParamType::Integer,
|
||||
"Recent runs to return at most when `includeRuns` is true (default 20, max 200)",
|
||||
))
|
||||
.param(Param::optional(
|
||||
"includeMarkdown",
|
||||
ParamType::Boolean,
|
||||
"Include portable `.automation.md` text on each automation (default false)",
|
||||
))
|
||||
.param(Param::optional("limit", ParamType::Integer, "Automations to return at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
}
|
||||
|
||||
pub(super) fn run_preview_schedule_sync(host: &Host, args: &Value) -> IdeResult<Output> {
|
||||
let raw_trigger =
|
||||
args.get("trigger").ok_or_else(|| IdeError::invalid("missing or invalid argument `trigger`"))?.clone();
|
||||
let trigger = parse_trigger_value(&raw_trigger)?;
|
||||
let count = match args.get("count").filter(|v| !v.is_null()) {
|
||||
None => 5u32,
|
||||
Some(v) => {
|
||||
let n = v.as_i64().ok_or_else(|| IdeError::invalid("count must be an integer"))?;
|
||||
if !(1..=20).contains(&n) {
|
||||
return Err(IdeError::invalid("count must be between 1 and 20"));
|
||||
}
|
||||
n as u32
|
||||
}
|
||||
};
|
||||
let next_runs_ms = host.automations.preview_schedule_capped(&trigger, count, 20)?;
|
||||
let next_runs_iso: Vec<String> =
|
||||
next_runs_ms.iter().filter_map(|&ms| format_trigger_timestamp(&trigger, ms)).collect();
|
||||
let mut out = json!({
|
||||
"summary": trigger.summary(),
|
||||
"nextRunsMs": next_runs_ms,
|
||||
"nextRunsIso": next_runs_iso,
|
||||
});
|
||||
if let Some((expr, tz)) = trigger.to_cron()?
|
||||
&& let Some(obj) = out.as_object_mut()
|
||||
{
|
||||
obj.insert("cronExpression".into(), Value::String(expr));
|
||||
obj.insert("timeZone".into(), Value::String(tz));
|
||||
}
|
||||
Output::json(out)
|
||||
}
|
||||
|
||||
fn preview_automation_schedule() -> Tool {
|
||||
Tool::new(
|
||||
"preview_automation_schedule",
|
||||
"Validates an automation schedule `trigger` (5-field cron, preset schedule, or one-shot timestamp) and previews the next `count` firing times in both epoch milliseconds and zoned ISO-8601 timestamps.
|
||||
Call this before `save_automation` to verify cron syntax and timezone behavior.",
|
||||
|call| async move {
|
||||
let host = call.host();
|
||||
let h = host.clone();
|
||||
let args = call.args.clone();
|
||||
host.blocking(move || run_preview_schedule_sync(&h, &args)).await
|
||||
},
|
||||
)
|
||||
.schema_param(
|
||||
"trigger",
|
||||
true,
|
||||
trigger_schema("Schedule trigger to validate and preview (`manual`, `hourly`, `daily`, `weekdays`, `weekly`, `cron`, or `oneShot`)."),
|
||||
)
|
||||
.param(Param::optional("count", ParamType::Integer, "Upcoming firing times to preview (1..=20, default 5)"))
|
||||
}
|
||||
|
||||
fn parse_isolation(raw: Option<&str>, fallback: Isolation) -> IdeResult<Isolation> {
|
||||
match raw {
|
||||
None => Ok(fallback),
|
||||
Some("local") => Ok(Isolation::Local),
|
||||
Some("worktree") => Ok(Isolation::Worktree),
|
||||
Some(other) => Err(IdeError::invalid(format!("invalid `isolation` '{other}'; expected `local` or `worktree`"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_continuity(raw: Option<&str>, fallback: AutomationContinuity) -> IdeResult<AutomationContinuity> {
|
||||
match raw {
|
||||
None => Ok(fallback),
|
||||
Some("newTask") => Ok(AutomationContinuity::NewTask),
|
||||
Some("sameTask") => Ok(AutomationContinuity::SameTask),
|
||||
Some(other) => {
|
||||
Err(IdeError::invalid(format!("invalid `continuity` '{other}'; expected `newTask` or `sameTask`")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_permissions(raw: Option<&str>, fallback: AutomationPermissionMode) -> IdeResult<AutomationPermissionMode> {
|
||||
match raw {
|
||||
None => Ok(fallback),
|
||||
Some("default") => Ok(AutomationPermissionMode::Default),
|
||||
Some("assisted") => Ok(AutomationPermissionMode::Assisted),
|
||||
Some("allowAll") => Ok(AutomationPermissionMode::AllowAll),
|
||||
Some(other) => Err(IdeError::invalid(format!(
|
||||
"invalid `permissions` '{other}'; expected `default`, `assisted`, or `allowAll`"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_misfire_policy(
|
||||
raw: Option<&str>,
|
||||
present: bool,
|
||||
fallback: Option<AutomationMisfirePolicy>,
|
||||
) -> IdeResult<Option<AutomationMisfirePolicy>> {
|
||||
if !present {
|
||||
return Ok(fallback);
|
||||
}
|
||||
match raw {
|
||||
None | Some("inherit") => Ok(None),
|
||||
Some("runOnce") => Ok(Some(AutomationMisfirePolicy::RunOnce)),
|
||||
Some("skip") => Ok(Some(AutomationMisfirePolicy::Skip)),
|
||||
Some(other) => Err(IdeError::invalid(format!(
|
||||
"invalid `misfirePolicy` '{other}'; expected `runOnce`, `skip`, or `inherit`"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_config_choices(raw: Option<&Value>, fallback: Vec<AgentConfigChoice>) -> IdeResult<Vec<AgentConfigChoice>> {
|
||||
let Some(val) = raw.filter(|v| !v.is_null()) else {
|
||||
return Ok(fallback);
|
||||
};
|
||||
serde_json::from_value::<Vec<AgentConfigChoice>>(val.clone())
|
||||
.map_err(|e| IdeError::invalid(format!("invalid `config`: {e}")))
|
||||
}
|
||||
|
||||
fn save_automation() -> Tool {
|
||||
Tool::new(
|
||||
"save_automation",
|
||||
"Creates or updates a project-scoped Agent Automation in the target project (or imports a portable `.automation.md` template via `markdown`).
|
||||
Validates the trigger, workspace trust, and provider first, then always asks the user for confirmation in an open project window (even in MCP brave mode).
|
||||
Never modifies OS login-service settings (`autoStartService`) or global approval ceilings, and refuses calls from unattended scheduled runs.",
|
||||
|call| async move {
|
||||
ensure_not_scheduled_caller(&call)?;
|
||||
call.project.require_trust()?;
|
||||
|
||||
let host = call.host();
|
||||
let root = dunce::canonicalize(call.root()).unwrap_or_else(|_| call.root().to_path_buf());
|
||||
let id = call.opt_str("id")?;
|
||||
let existing = match id.as_deref() {
|
||||
Some(existing_id) => Some(ensure_project_owns_automation(&host, &root, existing_id)?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let parsed_md = match call.opt_str("markdown")? {
|
||||
Some(md) => Some(parse_markdown(&md)?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let name = call
|
||||
.opt_str("name")?
|
||||
.or_else(|| parsed_md.as_ref().map(|p| p.name.clone()))
|
||||
.or_else(|| existing.as_ref().map(|e| e.name.clone()))
|
||||
.map(|s| s.trim().to_owned())
|
||||
.filter(|s| !s.is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("missing or empty `name`"))?;
|
||||
|
||||
let prompt_text = call
|
||||
.opt_str("prompt")?
|
||||
.or_else(|| parsed_md.as_ref().map(|p| p.prompt.clone()))
|
||||
.or_else(|| existing.as_ref().map(|e| e.prompt.text.clone()))
|
||||
.map(|s| s.trim().to_owned())
|
||||
.filter(|s| !s.is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("missing or empty `prompt`"))?;
|
||||
|
||||
let provider = call
|
||||
.opt_str("provider")?
|
||||
.or_else(|| existing.as_ref().map(|e| e.provider.clone()))
|
||||
.map(|s| s.trim().to_owned())
|
||||
.filter(|s| !s.is_empty())
|
||||
.ok_or_else(|| {
|
||||
IdeError::invalid("missing or empty `provider` (for example `claude`, `codex`, or `copilot`)")
|
||||
})?;
|
||||
{
|
||||
let agents = call.project.agents.clone();
|
||||
let candidate = provider.clone();
|
||||
let ok = host.blocking(move || Ok(agents.has_provider(&candidate))).await?;
|
||||
if !ok {
|
||||
let known = call.project.agents.known_provider_ids().join(", ");
|
||||
return Err(IdeError::invalid(format!(
|
||||
"unknown `provider` '{provider}'; available providers: {known}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
let trigger = match call.args.get("trigger").filter(|v| !v.is_null()) {
|
||||
Some(raw) => parse_trigger_value(raw)?,
|
||||
None => parsed_md
|
||||
.as_ref()
|
||||
.map(|p| p.trigger.clone())
|
||||
.or_else(|| existing.as_ref().map(|e| e.trigger.clone()))
|
||||
.unwrap_or(AutomationTrigger::Manual),
|
||||
};
|
||||
|
||||
let default_enabled = if parsed_md.is_some() || matches!(trigger, AutomationTrigger::Manual) {
|
||||
false
|
||||
} else {
|
||||
existing.as_ref().is_none_or(|e| e.enabled)
|
||||
};
|
||||
let enabled = call.flag("enabled", default_enabled)?;
|
||||
|
||||
let (existing_isolation, existing_base, existing_auto_clean) = match existing.as_ref().map(|e| &e.workspace)
|
||||
{
|
||||
Some(AutomationWorkspace::Project { isolation, base, auto_clean_worktree, .. }) => {
|
||||
(*isolation, base.clone(), *auto_clean_worktree)
|
||||
}
|
||||
_ => (Isolation::Local, None, true),
|
||||
};
|
||||
let isolation = parse_isolation(call.opt_str("isolation")?.as_deref(), existing_isolation)?;
|
||||
let base = if call.args.get("base").is_some() {
|
||||
call.opt_str("base")?.map(|b| b.trim().to_owned()).filter(|b| !b.is_empty())
|
||||
} else {
|
||||
existing_base
|
||||
};
|
||||
let auto_clean_worktree = call.flag("autoCleanWorktree", existing_auto_clean)?;
|
||||
let continuity = parse_continuity(
|
||||
call.opt_str("continuity")?.as_deref(),
|
||||
existing.as_ref().map_or(AutomationContinuity::NewTask, |e| e.continuity),
|
||||
)?;
|
||||
let permissions = parse_permissions(
|
||||
call.opt_str("permissions")?.as_deref(),
|
||||
existing.as_ref().map_or(AutomationPermissionMode::Assisted, |e| e.permissions),
|
||||
)?;
|
||||
let config = parse_config_choices(
|
||||
call.args.get("config"),
|
||||
existing.as_ref().map(|e| e.config.clone()).unwrap_or_default(),
|
||||
)?;
|
||||
let misfire_policy = parse_misfire_policy(
|
||||
call.opt_str("misfirePolicy")?.as_deref(),
|
||||
call.args.get("misfirePolicy").is_some(),
|
||||
existing.as_ref().and_then(|e| e.misfire_policy),
|
||||
)?;
|
||||
|
||||
let disable_after_ms = match call.args.get("disableAfterMs") {
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => {
|
||||
let n = v.as_f64().ok_or_else(|| IdeError::invalid("disableAfterMs must be a number"))?;
|
||||
if !n.is_finite() || n < 0.0 {
|
||||
return Err(IdeError::invalid("disableAfterMs must be >= 0"));
|
||||
}
|
||||
(n > 0.0).then_some(n)
|
||||
}
|
||||
None => {
|
||||
parsed_md.as_ref().and_then(|p| p.disable_after_ms).or(existing.as_ref().and_then(|e| e.disable_after_ms))
|
||||
}
|
||||
};
|
||||
|
||||
let max_runs = match call.opt_i64("maxRuns")? {
|
||||
Some(n) if n < 0 => return Err(IdeError::invalid("maxRuns must be >= 0")),
|
||||
Some(0) => None,
|
||||
Some(n) => Some(n as u32),
|
||||
None if call.args.get("maxRuns").is_some_and(Value::is_null) => None,
|
||||
None => parsed_md.as_ref().and_then(|p| p.max_runs).or(existing.as_ref().and_then(|e| e.max_runs)),
|
||||
};
|
||||
|
||||
let default_allow_self_schedule = parsed_md
|
||||
.as_ref()
|
||||
.map(|p| p.allow_agent_schedule)
|
||||
.or_else(|| existing.as_ref().map(|e| e.allow_agent_schedule))
|
||||
.unwrap_or(false);
|
||||
let allow_agent_schedule = call.flag("allowAgentSchedule", default_allow_self_schedule)?;
|
||||
let clear_override = call.flag("clearOverride", false)?;
|
||||
|
||||
let workspace = AutomationWorkspace::Project {
|
||||
root: IpcPath(root),
|
||||
isolation,
|
||||
base: base.clone(),
|
||||
auto_clean_worktree,
|
||||
};
|
||||
|
||||
// Pre-validate workspace trust (including parent Git repository trust for worktrees)
|
||||
// and trigger syntax BEFORE showing the UI confirmation dialog.
|
||||
crate::automations::check_workspace_trust(&host, &workspace).map_err(IdeError::invalid)?;
|
||||
let now = host.automations.now_ms();
|
||||
let next_ms = trigger.next_run_after(now)?;
|
||||
let preserves_future_override = existing.as_ref().is_some_and(|e| {
|
||||
enabled
|
||||
&& allow_agent_schedule
|
||||
&& !clear_override
|
||||
&& e.trigger == trigger
|
||||
&& max_runs.is_none_or(|max| e.run_count < max)
|
||||
&& e.next_run_override_ms.is_some_and(|ms| ms > now && disable_after_ms.is_none_or(|exp| ms < exp))
|
||||
});
|
||||
if enabled && matches!(trigger, AutomationTrigger::OneShot { .. }) && next_ms.is_none() && !preserves_future_override {
|
||||
return Err(IdeError::invalid("one-shot timestamp must be in the future when enabled"));
|
||||
}
|
||||
|
||||
let subject = match &existing {
|
||||
Some(_) => format!("update automation `{name}`"),
|
||||
None => format!("create automation `{name}`"),
|
||||
};
|
||||
let isolation_desc = match (&isolation, &base) {
|
||||
(Isolation::Worktree, Some(b)) => format!("worktree (base: {b})"),
|
||||
(Isolation::Worktree, None) => "worktree".to_owned(),
|
||||
(Isolation::Local, _) => "local checkout".to_owned(),
|
||||
};
|
||||
let continuity_desc = match continuity {
|
||||
AutomationContinuity::NewTask => "newTask",
|
||||
AutomationContinuity::SameTask => "sameTask",
|
||||
};
|
||||
let self_sched_line = if allow_agent_schedule {
|
||||
"\nSelf-scheduling: ALLOWED (runs can call schedule_next_run without confirmation)"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let mut detail = format!(
|
||||
"Name: {name}\nSchedule: {} (enabled: {enabled}){self_sched_line}\nProvider: {provider}\nIsolation: {isolation_desc}\nContinuity: {continuity_desc}\nPermissions: {}\nPrompt:\n{}",
|
||||
trigger.summary(),
|
||||
describe_effective_permissions(&host, permissions),
|
||||
truncate_preview(&prompt_text, PROMPT_PREVIEW_CHARS),
|
||||
);
|
||||
if let Some(existing) = &existing {
|
||||
detail = format!("ID: {}\n{detail}", existing.id);
|
||||
}
|
||||
let detail = prepend_brave_mode_note(&host, detail);
|
||||
call.confirm_always(&subject, Some(detail)).await?;
|
||||
|
||||
let prompt = AgentPrompt {
|
||||
text: prompt_text,
|
||||
files: existing.as_ref().map(|e| e.prompt.files.clone()).unwrap_or_default(),
|
||||
images: existing.as_ref().map(|e| e.prompt.images.clone()).unwrap_or_default(),
|
||||
};
|
||||
let input = SaveAutomationInput {
|
||||
id,
|
||||
name,
|
||||
enabled,
|
||||
prompt,
|
||||
workspace,
|
||||
continuity,
|
||||
provider,
|
||||
config,
|
||||
permissions,
|
||||
mcp_overrides: existing.as_ref().map(|e| e.mcp_overrides.clone()).unwrap_or_default(),
|
||||
skill_overrides: existing.as_ref().map(|e| e.skill_overrides.clone()).unwrap_or_default(),
|
||||
memory_overrides: existing.as_ref().and_then(|e| e.memory_overrides.clone()),
|
||||
trigger,
|
||||
allow_agent_schedule,
|
||||
clear_override,
|
||||
misfire_policy,
|
||||
disable_after_ms,
|
||||
max_runs,
|
||||
};
|
||||
|
||||
let h = host.clone();
|
||||
let saved = host.blocking(move || h.automations.save(&h, input)).await?;
|
||||
Output::json(json!({ "automation": format_automation_json(&saved, false)? }))
|
||||
},
|
||||
)
|
||||
.write()
|
||||
.param(Param::optional("id", ParamType::String, "Existing automation ID in this project to update; omit to create"))
|
||||
.param(Param::optional(
|
||||
"markdown",
|
||||
ParamType::String,
|
||||
"Optional `.automation.md` template (YAML frontmatter + prompt body); explicit fields override parsed values",
|
||||
))
|
||||
.param(Param::optional("name", ParamType::String, "Automation name (required when creating without `markdown`)"))
|
||||
.param(Param::optional("prompt", ParamType::String, "Prompt sent to the agent on each run"))
|
||||
.param(Param::optional(
|
||||
"provider",
|
||||
ParamType::String,
|
||||
"Agent provider ID (for example `claude`, `codex`, `copilot`, `cursor`, or a custom ACP agent ID)",
|
||||
))
|
||||
.schema_param(
|
||||
"trigger",
|
||||
false,
|
||||
trigger_schema("Schedule trigger (`manual`, `hourly`, `daily`, `weekdays`, `weekly`, `cron`, or `oneShot`). Defaults to `manual` on create."),
|
||||
)
|
||||
.param(Param::optional(
|
||||
"enabled",
|
||||
ParamType::Boolean,
|
||||
"Whether the schedule is active (defaults to false for `manual` and `markdown` imports, true for new schedules)",
|
||||
))
|
||||
.param(Param::optional(
|
||||
"allowAgentSchedule",
|
||||
ParamType::Boolean,
|
||||
"Allow runs of this automation to call `schedule_next_run` to set their own next firing time and prompt without interactive confirmation (default false)",
|
||||
))
|
||||
.param(Param::optional(
|
||||
"clearOverride",
|
||||
ParamType::Boolean,
|
||||
"On updates, explicitly clear any pending agent-scheduled `nextRunOverrideMs` and `nextPromptOverride` (default false; non-schedule edits otherwise preserve a valid future override)",
|
||||
))
|
||||
.schema_param(
|
||||
"isolation",
|
||||
false,
|
||||
json!({
|
||||
"type": "string",
|
||||
"enum": ["local", "worktree"],
|
||||
"description": "Where runs execute: `local` (project checkout, default) or `worktree` (fresh Git worktree; recommended for unattended code edits)"
|
||||
}),
|
||||
)
|
||||
.param(Param::optional("base", ParamType::String, "Optional base Git branch/ref when `isolation` is `worktree`"))
|
||||
.param(Param::optional(
|
||||
"autoCleanWorktree",
|
||||
ParamType::Boolean,
|
||||
"Automatically remove zero-diff worktrees after `newTask` worktree runs (default true)",
|
||||
))
|
||||
.schema_param(
|
||||
"continuity",
|
||||
false,
|
||||
json!({
|
||||
"type": "string",
|
||||
"enum": ["newTask", "sameTask"],
|
||||
"description": "`newTask` starts a fresh session each run (default); `sameTask` continues the previous session"
|
||||
}),
|
||||
)
|
||||
.schema_param(
|
||||
"permissions",
|
||||
false,
|
||||
json!({
|
||||
"type": "string",
|
||||
"enum": ["default", "assisted", "allowAll"],
|
||||
"description": "Unattended approval level (`assisted` default); capped at runtime by Settings › Agents › New task approvals"
|
||||
}),
|
||||
)
|
||||
.schema_param(
|
||||
"config",
|
||||
false,
|
||||
json!({
|
||||
"type": "array",
|
||||
"description": "Optional session configuration choices (for example model, reasoning effort, or context window)",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": { "type": "string" },
|
||||
"value": { "type": "string" }
|
||||
},
|
||||
"required": ["id", "value"]
|
||||
}
|
||||
}),
|
||||
)
|
||||
.schema_param(
|
||||
"misfirePolicy",
|
||||
false,
|
||||
json!({
|
||||
"type": "string",
|
||||
"enum": ["runOnce", "skip", "inherit"],
|
||||
"description": "Behavior after missed scheduled windows while asleep (`runOnce`, `skip`, or `inherit` host default)"
|
||||
}),
|
||||
)
|
||||
.schema_param(
|
||||
"disableAfterMs",
|
||||
false,
|
||||
json!({
|
||||
"type": ["number", "null"],
|
||||
"description": "Optional epoch timestamp (ms) after which the schedule disables automatically (`0` or `null` clears)"
|
||||
}),
|
||||
)
|
||||
.param(Param::optional(
|
||||
"maxRuns",
|
||||
ParamType::Integer,
|
||||
"Optional maximum run count before the schedule disables automatically (`0` clears)",
|
||||
))
|
||||
}
|
||||
|
||||
fn control_automation() -> Tool {
|
||||
Tool::new(
|
||||
"control_automation",
|
||||
"Enables, pauses, runs immediately, or deletes an Agent Automation of the target project, or pauses all active schedules of the target project (`pause_all`).
|
||||
Always asks for confirmation in an open project window first (even in MCP brave mode), and refuses calls from unattended scheduled runs.",
|
||||
|call| async move {
|
||||
ensure_not_scheduled_caller(&call)?;
|
||||
call.project.require_trust()?;
|
||||
|
||||
let action = call.str("action")?;
|
||||
let host = call.host();
|
||||
let root = dunce::canonicalize(call.root()).unwrap_or_else(|_| call.root().to_path_buf());
|
||||
|
||||
match action.as_str() {
|
||||
"pause_all" => {
|
||||
let detail = prepend_brave_mode_note(
|
||||
&host,
|
||||
format!("Pause all enabled automations and session schedules in {}", root.display()),
|
||||
);
|
||||
call.confirm_always("pause all project automations", Some(detail)).await?;
|
||||
let h = host.clone();
|
||||
let roots = vec![root];
|
||||
let paused_count =
|
||||
host.blocking(move || h.automations.pause_all_scoped(&h, Some(&roots), false)).await?;
|
||||
Output::json(json!({
|
||||
"action": "pause_all",
|
||||
"pausedCount": paused_count,
|
||||
}))
|
||||
}
|
||||
"enable" | "pause" | "run_now" | "delete" => {
|
||||
let id = call.str("id")?;
|
||||
let auto = ensure_project_owns_automation(&host, &root, &id)?;
|
||||
if matches!(action.as_str(), "enable" | "run_now") {
|
||||
crate::automations::check_workspace_trust(&host, &auto.workspace)
|
||||
.map_err(IdeError::invalid)?;
|
||||
}
|
||||
if action == "enable" {
|
||||
let now = host.automations.now_ms();
|
||||
let next = auto.trigger.next_run_after(now)?;
|
||||
let has_future_override = auto.next_run_override_ms.is_some_and(|ms| ms > now);
|
||||
if matches!(auto.trigger, AutomationTrigger::OneShot { .. })
|
||||
&& next.is_none()
|
||||
&& !has_future_override
|
||||
{
|
||||
return Err(IdeError::invalid(
|
||||
"one-shot timestamp is in the past; update its schedule before enabling",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let verb = match action.as_str() {
|
||||
"enable" => "enable",
|
||||
"pause" => "pause",
|
||||
"run_now" => "run now",
|
||||
"delete" => "delete",
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let subject = format!("{verb} automation `{}`", auto.name);
|
||||
let detail = prepend_brave_mode_note(
|
||||
&host,
|
||||
format!(
|
||||
"Action: {action}\nID: {}\nName: {}\nSchedule: {}\nProvider: {}\nPrompt:\n{}",
|
||||
auto.id,
|
||||
auto.name,
|
||||
auto.trigger.summary(),
|
||||
auto.provider,
|
||||
truncate_preview(&auto.prompt.text, PROMPT_PREVIEW_CHARS),
|
||||
),
|
||||
);
|
||||
call.confirm_always(&subject, Some(detail)).await?;
|
||||
|
||||
match action.as_str() {
|
||||
"enable" | "pause" => {
|
||||
let enabled = action == "enable";
|
||||
let h = host.clone();
|
||||
let updated = host.blocking(move || h.automations.set_enabled(&h, &id, enabled)).await?;
|
||||
Output::json(json!({
|
||||
"action": action,
|
||||
"automation": format_automation_json(&updated, false)?,
|
||||
}))
|
||||
}
|
||||
"run_now" => {
|
||||
let run = host.automations.clone().run_now(&host, &id).await?;
|
||||
Output::json(json!({
|
||||
"action": "run_now",
|
||||
"run": run,
|
||||
}))
|
||||
}
|
||||
"delete" => {
|
||||
let h = host.clone();
|
||||
let target_id = id.clone();
|
||||
host.blocking(move || h.automations.delete(&h, &target_id)).await?;
|
||||
Output::json(json!({
|
||||
"action": "delete",
|
||||
"deletedId": id,
|
||||
}))
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
other => Err(IdeError::invalid(format!(
|
||||
"invalid `action` '{other}'; expected `enable`, `pause`, `pause_all`, `run_now`, or `delete`"
|
||||
))),
|
||||
}
|
||||
},
|
||||
)
|
||||
.write()
|
||||
.schema_param(
|
||||
"action",
|
||||
true,
|
||||
json!({
|
||||
"type": "string",
|
||||
"enum": ["enable", "pause", "pause_all", "run_now", "delete"],
|
||||
"description": "Action to perform on this project's automations"
|
||||
}),
|
||||
)
|
||||
.param(Param::optional(
|
||||
"id",
|
||||
ParamType::String,
|
||||
"Automation ID in this project (required for `enable`, `pause`, `run_now`, and `delete`)",
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn run_schedule_next_run_sync(
|
||||
host: &Arc<Host>,
|
||||
caller_session: Option<&ide_agent::McpCallerSession>,
|
||||
args: &Value,
|
||||
) -> IdeResult<Output> {
|
||||
let Some(caller) = caller_session else {
|
||||
return Err(IdeError::invalid(
|
||||
"schedule_next_run can only be called from an active Agent Automation run inside OpenIDEA; use save_automation to create a new automation",
|
||||
));
|
||||
};
|
||||
|
||||
let done = match args.get("done").filter(|v| !v.is_null()) {
|
||||
Some(v) => v.as_bool().ok_or_else(|| IdeError::invalid("done must be a boolean"))?,
|
||||
None => false,
|
||||
};
|
||||
|
||||
let prompt = match args.get("prompt").filter(|v| !v.is_null()) {
|
||||
Some(v) => Some(v.as_str().map(str::to_owned).ok_or_else(|| IdeError::invalid("prompt must be a string"))?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let opt_f64 = |key: &str| -> IdeResult<Option<f64>> {
|
||||
match args.get(key).filter(|v| !v.is_null()) {
|
||||
None => Ok(None),
|
||||
Some(v) => {
|
||||
let n = v.as_f64().ok_or_else(|| IdeError::invalid(format!("{key} must be a number")))?;
|
||||
if !n.is_finite() || n <= 0.0 {
|
||||
return Err(IdeError::invalid(format!("{key} must be > 0")));
|
||||
}
|
||||
Ok(Some(n))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let delay_minutes = opt_f64("delayMinutes")?;
|
||||
let delay_seconds = opt_f64("delaySeconds")?;
|
||||
let run_at_ms = opt_f64("runAtMs")?;
|
||||
let run_at_iso = match args.get("runAtIso").filter(|v| !v.is_null()) {
|
||||
None => None,
|
||||
Some(v) => {
|
||||
let s = v.as_str().ok_or_else(|| IdeError::invalid("runAtIso must be a string"))?;
|
||||
Some(parse_iso_timestamp_ms(s)?)
|
||||
}
|
||||
};
|
||||
|
||||
let provided_timing = [delay_minutes.is_some(), delay_seconds.is_some(), run_at_ms.is_some(), run_at_iso.is_some()]
|
||||
.into_iter()
|
||||
.filter(|&b| b)
|
||||
.count();
|
||||
|
||||
if done && (provided_timing > 0 || prompt.is_some()) {
|
||||
return Err(IdeError::invalid(
|
||||
"cannot combine `done: true` with `prompt`, `delayMinutes`, `delaySeconds`, `runAtIso`, or `runAtMs`",
|
||||
));
|
||||
}
|
||||
if !done && provided_timing != 1 {
|
||||
return Err(IdeError::invalid(
|
||||
"specify exactly one of `delayMinutes`, `delaySeconds`, `runAtIso`, or `runAtMs` (or `done: true` to clear override)",
|
||||
));
|
||||
}
|
||||
|
||||
let schedule = delay_minutes
|
||||
.map(|mins| SelfScheduleTime::After(mins * 60_000.0))
|
||||
.or_else(|| delay_seconds.map(|secs| SelfScheduleTime::After(secs * 1_000.0)))
|
||||
.or_else(|| run_at_ms.or(run_at_iso).map(SelfScheduleTime::At));
|
||||
|
||||
let updated = host.automations.schedule_next_run_from_agent(host, caller, schedule, prompt)?;
|
||||
let next_iso = updated.next_run_ms.and_then(|ms| format_trigger_timestamp(&updated.trigger, ms));
|
||||
Output::json(json!({
|
||||
"scheduled": !done,
|
||||
"nextRunMs": updated.next_run_ms,
|
||||
"nextRunIso": next_iso,
|
||||
"nextRunOverrideMs": updated.next_run_override_ms,
|
||||
"nextPromptOverride": updated.next_prompt_override,
|
||||
"automation": format_automation_json(&updated, false)?,
|
||||
}))
|
||||
}
|
||||
|
||||
fn schedule_next_run() -> Tool {
|
||||
Tool::new(
|
||||
"schedule_next_run",
|
||||
"Schedules a one-time next-run override (`nextRunOverrideMs` and optional `nextPromptOverride`) for the currently executing Agent Automation without human confirmation, or clears any pending override (`done: true`) so the regular schedule continues (leaving `manual` automations idle and disabling elapsed `oneShot` automations).
|
||||
Keeps the automation's configured `trigger` and base `prompt` intact, works only during an active scheduled run of an automation with `allowAgentSchedule` enabled (including `oneShot` seed runs, which auto-disable once a run completes without scheduling a follow-up), enforces a 60-second minimum delay, and respects `maxRuns` and `disableAfterMs` limits.",
|
||||
|call| async move {
|
||||
let host = call.host();
|
||||
let h = host.clone();
|
||||
let caller_session = call.caller_session.clone();
|
||||
let args = call.args.clone();
|
||||
host.blocking(move || run_schedule_next_run_sync(&h, caller_session.as_ref(), &args)).await
|
||||
},
|
||||
)
|
||||
.write()
|
||||
.schema_param(
|
||||
"delayMinutes",
|
||||
false,
|
||||
json!({
|
||||
"type": "number",
|
||||
"description": "Minutes from now until the next run (>= 1; supports fractional minutes)"
|
||||
}),
|
||||
)
|
||||
.schema_param(
|
||||
"delaySeconds",
|
||||
false,
|
||||
json!({
|
||||
"type": "number",
|
||||
"description": "Seconds from now until the next run (>= 60)"
|
||||
}),
|
||||
)
|
||||
.param(Param::optional(
|
||||
"runAtIso",
|
||||
ParamType::String,
|
||||
"ISO-8601 / RFC-3339 timestamp with timezone offset for the next run (for example `2026-12-01T23:30:00-08:00`)",
|
||||
))
|
||||
.schema_param(
|
||||
"runAtMs",
|
||||
false,
|
||||
json!({
|
||||
"type": "number",
|
||||
"description": "Epoch timestamp in milliseconds for the next run"
|
||||
}),
|
||||
)
|
||||
.param(Param::optional(
|
||||
"prompt",
|
||||
ParamType::String,
|
||||
"Optional updated prompt instructions for the next run; omit to keep the automation's current prompt",
|
||||
))
|
||||
.param(Param::optional(
|
||||
"done",
|
||||
ParamType::Boolean,
|
||||
"Set `true` to clear the pending override and resume the configured schedule",
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,930 @@
|
||||
//! `devcontainer_*`: the project's dev container for agents. Which container is the project's
|
||||
//! is decided by the labels the Dev Containers CLI puts on it (folder and configuration file);
|
||||
//! nothing else is ever touched. Starting and running go through the CLI, listing, logs and
|
||||
//! stopping through `ops::docker`.
|
||||
|
||||
use super::run::agent::{Execution, tab_name};
|
||||
use super::run::agent_tools::{
|
||||
INTERVENTIONS, MAX_LINES, NAME, OUTPUT, SEQUENCE, TRUNCATE_MODE, Tab, busy, start_in_tab,
|
||||
};
|
||||
use super::run::timeout;
|
||||
use super::tool::{Call, Output, Param, ParamType, Tool, ensure_inside};
|
||||
use crate::Host;
|
||||
use crate::ops::docker as ops;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_docker::{DockerAvailability, DockerContainer, DockerEndpoint, DockerObject};
|
||||
use ide_remote::devcontainer::{CONFIG_LABEL, FOLDER_LABEL, Target, UP_TIMEOUT, label_value};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const EXEC_TIMEOUT_MS: usize = 120_000;
|
||||
const DEFAULT_TAIL: i64 = 200;
|
||||
const MAX_TAIL: i64 = 5000;
|
||||
const COMPOSE_PROJECT: &str = "com.docker.compose.project";
|
||||
const CONFIG_NAMES: [&str; 2] = ["devcontainer.json", ".devcontainer.json"];
|
||||
|
||||
const CONFIG: &str = "Which configuration file to use: a path inside the project to a `devcontainer.json` or \
|
||||
`.devcontainer.json`. Default: `.devcontainer/devcontainer.json`, else `.devcontainer.json` (`devcontainer_status` \
|
||||
lists the others)";
|
||||
const WHICH: &str = "The project's container is the one the Dev Containers CLI started for the project folder and \
|
||||
configuration file (its `devcontainer.local_folder` and `devcontainer.config_file` labels), plus the other containers \
|
||||
of its Docker Compose project; no other container is ever touched. Needs Docker on this machine.";
|
||||
|
||||
pub fn tools() -> Vec<Tool> {
|
||||
vec![status(), logs(), up(), exec(), stop()]
|
||||
}
|
||||
|
||||
// ---- which container is the project's ----
|
||||
|
||||
/// Containers with both project labels, running before stopped, then newest.
|
||||
fn project_containers(mut candidates: Vec<DockerContainer>, target: &Target) -> Vec<DockerContainer> {
|
||||
let Some(config) = target.config_label() else { return Vec::new() };
|
||||
let folder = target.folder_label();
|
||||
candidates.retain(|c| {
|
||||
let label = |key: &str| c.labels.get(key).map(|value| label_value(value));
|
||||
label(FOLDER_LABEL).as_deref() == Some(&folder) && label(CONFIG_LABEL).as_deref() == Some(&config)
|
||||
});
|
||||
// `created_at` is docker's `2026-01-02 03:04:05 +0000 UTC`: newest sorts last as text.
|
||||
candidates.sort_by(|a, b| b.running().cmp(&a.running()).then_with(|| b.created_at.cmp(&a.created_at)));
|
||||
candidates
|
||||
}
|
||||
|
||||
/// The project's containers.
|
||||
#[derive(Default)]
|
||||
struct Found {
|
||||
primary: Option<DockerContainer>,
|
||||
/// Other containers with the project's labels, such as one left from before a rebuild.
|
||||
stale: Vec<DockerContainer>,
|
||||
/// The other containers of the primary's Compose project.
|
||||
siblings: Vec<DockerContainer>,
|
||||
}
|
||||
|
||||
impl Found {
|
||||
fn primary_id(&self) -> Option<&str> {
|
||||
self.primary.as_ref().map(|c| c.id.as_str())
|
||||
}
|
||||
|
||||
fn all(&self) -> impl Iterator<Item = &DockerContainer> {
|
||||
self.primary.iter().chain(&self.stale).chain(&self.siblings)
|
||||
}
|
||||
|
||||
/// What `stop` acts on: the primary and its Compose project.
|
||||
fn running_group(&self) -> Vec<&DockerContainer> {
|
||||
self.primary.iter().chain(&self.siblings).filter(|c| c.running()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
async fn find(host: &Host, target: &Target) -> IdeResult<Found> {
|
||||
if target.config().is_none() {
|
||||
return Ok(Found::default());
|
||||
}
|
||||
let ep = || DockerEndpoint::Default;
|
||||
let folder =
|
||||
ops::containers_with_labels(host, ep(), vec![format!("{FOLDER_LABEL}={}", target.folder_label())]).await?;
|
||||
let mut matching = project_containers(folder, target).into_iter();
|
||||
let primary = matching.next();
|
||||
let stale: Vec<DockerContainer> = matching.collect();
|
||||
let mut siblings = Vec::new();
|
||||
if let Some(project) = primary.as_ref().and_then(|p| p.compose_project.clone()) {
|
||||
let members = ops::containers_with_labels(host, ep(), vec![format!("{COMPOSE_PROJECT}={project}")]).await?;
|
||||
siblings = siblings_of(primary.as_ref().unwrap(), members);
|
||||
}
|
||||
Ok(Found { primary, stale, siblings })
|
||||
}
|
||||
|
||||
/// The other containers of `primary`'s Compose project. Another checkout may give its project the
|
||||
/// same name, so only those of the same working directory, which the primary has to have.
|
||||
fn siblings_of(primary: &DockerContainer, members: Vec<DockerContainer>) -> Vec<DockerContainer> {
|
||||
let dir = primary.compose_working_dir.as_deref();
|
||||
let same = |c: &DockerContainer| dir.is_some() && c.compose_working_dir.as_deref() == dir;
|
||||
members
|
||||
.into_iter()
|
||||
.filter(|c| {
|
||||
same(c)
|
||||
&& c.id != primary.id
|
||||
&& !c.labels.contains_key(FOLDER_LABEL)
|
||||
&& !c.labels.contains_key(CONFIG_LABEL)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The container `containerId` names, among the project's containers: the primary without one.
|
||||
fn choose<'a>(found: &'a Found, wanted: Option<&str>) -> IdeResult<&'a DockerContainer> {
|
||||
let Some(wanted) = wanted.map(str::trim).filter(|w| !w.is_empty()) else {
|
||||
return found.primary.as_ref().ok_or_else(|| {
|
||||
IdeError::not_found("this project has no dev container yet; start it with devcontainer_up")
|
||||
});
|
||||
};
|
||||
let wanted = wanted.to_ascii_lowercase();
|
||||
let mut hits = found.all().filter(|c| wanted.len() >= 12 && c.id.to_ascii_lowercase().starts_with(&wanted));
|
||||
match (hits.next(), hits.next()) {
|
||||
(Some(container), None) => Ok(container),
|
||||
_ => Err(IdeError::invalid(format!("container {wanted} does not belong to this project's dev container"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn describe(container: &DockerContainer) -> String {
|
||||
format!("{} ({})", container.name, ide_docker::short_id(&container.id))
|
||||
}
|
||||
|
||||
// ---- docker, the CLI and the arguments ----
|
||||
|
||||
/// Docker is installed, its daemon answers and is on this machine (the project folder is
|
||||
/// bind-mounted, and its labels name this machine's folders).
|
||||
fn daemon() -> IdeResult<()> {
|
||||
match ide_docker::availability(&DockerEndpoint::Default) {
|
||||
DockerAvailability::Ready { .. } => {}
|
||||
DockerAvailability::NotInstalled => return Err(IdeError::unavailable("Docker is not installed")),
|
||||
DockerAvailability::DaemonDown { message, .. } => return Err(IdeError::unavailable(message)),
|
||||
}
|
||||
if ide_docker::endpoint_is_local(&DockerEndpoint::Default)? {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::unavailable(
|
||||
"The Docker daemon of the current context is not on this machine; dev containers need a local one.",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
async fn docker_ready(host: &Host) -> IdeResult<()> {
|
||||
host.blocking(daemon).await
|
||||
}
|
||||
|
||||
fn is_config_file(path: &Path) -> bool {
|
||||
path.file_name().and_then(|n| n.to_str()).is_some_and(|n| CONFIG_NAMES.contains(&n))
|
||||
}
|
||||
|
||||
/// The folder and configuration the call is about: the project root as opened, and `config`
|
||||
/// (or the default one) joined to it, as the CLI is given them and labels the container.
|
||||
fn target(call: &Call) -> IdeResult<Target> {
|
||||
let root = call.root();
|
||||
let config = match call.opt_str("config")?.map(|c| c.trim().to_owned()).filter(|c| !c.is_empty()) {
|
||||
Some(raw) => {
|
||||
let real = call.resolve_inside(&raw)?;
|
||||
if !is_config_file(&real) {
|
||||
return Err(IdeError::invalid("config must be a devcontainer.json or .devcontainer.json file"));
|
||||
}
|
||||
if !real.is_file() {
|
||||
return Err(IdeError::not_found(format!("config {raw} does not exist")));
|
||||
}
|
||||
let base = dunce::canonicalize(root)?;
|
||||
let inside =
|
||||
real.strip_prefix(&base).map_err(|_| IdeError::invalid("config must be inside the project"))?;
|
||||
Some(root.join(inside))
|
||||
}
|
||||
None => {
|
||||
let config = ide_workspace::devcontainer::find(root);
|
||||
if let Some(config) = &config {
|
||||
ensure_inside(root, config)?;
|
||||
}
|
||||
config
|
||||
}
|
||||
};
|
||||
Ok(Target::new(root, config))
|
||||
}
|
||||
|
||||
/// Every configuration file of the project the CLI can be pointed at.
|
||||
fn config_files(root: &Path) -> Vec<PathBuf> {
|
||||
let dir = root.join(".devcontainer");
|
||||
let mut files = vec![dir.join("devcontainer.json"), root.join(".devcontainer.json")];
|
||||
if ensure_inside(root, &dir).is_ok() {
|
||||
let mut named: Vec<PathBuf> = std::fs::read_dir(&dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path().join("devcontainer.json"))
|
||||
.collect();
|
||||
named.sort();
|
||||
files.extend(named);
|
||||
}
|
||||
files.retain(|f| f.is_file() && ensure_inside(root, f).is_ok());
|
||||
files
|
||||
}
|
||||
|
||||
/// The error of a project without a configuration the tools can use by default.
|
||||
fn no_config(call: &Call) -> IdeError {
|
||||
let root = call.root().display();
|
||||
let others: Vec<String> = config_files(call.root()).iter().map(|f| call.display(f)).collect();
|
||||
if others.is_empty() {
|
||||
return IdeError::not_found(format!("{root} has no devcontainer.json"));
|
||||
}
|
||||
IdeError::not_found(format!(
|
||||
"{root} has no .devcontainer/devcontainer.json or .devcontainer.json: pass `config` with one of {}",
|
||||
others.join(", ")
|
||||
))
|
||||
}
|
||||
|
||||
/// `timeout` in milliseconds for a start: a positive number.
|
||||
fn start_timeout(call: &Call) -> IdeResult<std::time::Duration> {
|
||||
if call.opt_i64("timeout")?.is_some_and(|n| n <= 0) {
|
||||
return Err(IdeError::invalid("timeout must be positive"));
|
||||
}
|
||||
timeout(call, UP_TIMEOUT.as_millis() as usize)
|
||||
}
|
||||
|
||||
fn tail_of(tail: Option<i64>) -> IdeResult<u32> {
|
||||
match tail.unwrap_or(DEFAULT_TAIL) {
|
||||
n @ 1..=MAX_TAIL => Ok(n as u32),
|
||||
_ => Err(IdeError::invalid(format!("tail must be between 1 and {MAX_TAIL}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `envs` as `(name, value)`: names a shell accepts.
|
||||
fn envs_of(call: &Call) -> IdeResult<Vec<(String, String)>> {
|
||||
let Some(value) = call.args.get("envs").filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
|
||||
if !value.is_object() {
|
||||
return Err(IdeError::invalid("envs must be an object"));
|
||||
}
|
||||
let envs = call.str_map("envs")?;
|
||||
for (name, value) in &envs {
|
||||
let valid = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|
||||
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
|
||||
if !valid {
|
||||
return Err(IdeError::invalid(format!("envs: `{name}` is not a valid variable name")));
|
||||
}
|
||||
if value.contains('\0') {
|
||||
return Err(IdeError::invalid(format!("envs: the value of {name} contains a NUL character")));
|
||||
}
|
||||
}
|
||||
Ok(envs)
|
||||
}
|
||||
|
||||
/// Pass the full approved ID to the CLI, including when the Run tab reruns this command.
|
||||
fn exec_argv(
|
||||
cli: &Path,
|
||||
docker: &Path,
|
||||
target: &Target,
|
||||
container_id: &str,
|
||||
envs: &[(String, String)],
|
||||
command: &str,
|
||||
) -> Vec<String> {
|
||||
let lossy = |p: &std::ffi::OsStr| p.to_string_lossy().into_owned();
|
||||
let mut argv = vec![lossy(cli.as_os_str()), "exec".to_owned()];
|
||||
argv.extend(target.args().iter().map(|a| lossy(a)));
|
||||
argv.extend(["--container-id".to_owned(), container_id.to_owned()]);
|
||||
argv.extend(["--docker-path".to_owned(), lossy(docker.as_os_str())]);
|
||||
argv.extend(envs.iter().map(|(k, v)| format!("--remote-env={k}={v}")));
|
||||
argv.extend(["sh".to_owned(), "-c".to_owned(), command.to_owned()]);
|
||||
argv
|
||||
}
|
||||
|
||||
/// A command line for people: the arguments that need it in quotes.
|
||||
fn shown(argv: &[String]) -> String {
|
||||
let word = |a: &String| {
|
||||
if !a.is_empty() && a.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=:@%+,".contains(c)) {
|
||||
a.clone()
|
||||
} else {
|
||||
format!("'{}'", a.replace('\'', r"'\''"))
|
||||
}
|
||||
};
|
||||
argv.iter().map(word).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// Refuses to change a container a window is open in.
|
||||
fn not_attached(call: &Call, containers: &[&DockerContainer], what: &str) -> IdeResult<()> {
|
||||
let attached = &call.host.dev_containers_attached;
|
||||
match containers.iter().find(|c| attached.contains(&c.id)) {
|
||||
Some(c) => Err(IdeError::invalid(format!(
|
||||
"cannot {what}: {} is open in a window (Reopen in Container). Close that window or use Rebuild Container in it.",
|
||||
describe(c)
|
||||
))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the tools ----
|
||||
|
||||
fn status() -> Tool {
|
||||
Tool::new(
|
||||
"devcontainer_status",
|
||||
&format!(
|
||||
"Reports the project's dev container: `configFile` (the configuration in use, relative to the project, \
|
||||
or null), `configFiles` (every configuration the project has, including `.devcontainer/<name>/devcontainer.json`), \
|
||||
`forwardPorts` of the configuration, the project's `containers` (`id`, `name`, `state`, `status`, `image`, `ports`, \
|
||||
`service` for Docker Compose, `primary`: the one the other tools act on; none when it was never started), `resources` \
|
||||
(the primary container's limits, usage and OOM status, plus host requirements when Docker is ready), `docker` \
|
||||
(`ready`, or why Docker cannot be used), `dockerLocal` (the Docker daemon is on this machine) and `cliInstalled` \
|
||||
(the Dev Containers CLI that starts it). Starts nothing. {WHICH}"
|
||||
),
|
||||
|call| async move {
|
||||
let target = target(&call)?;
|
||||
let data_dir = call.host.local_data_dir.clone();
|
||||
let cli = call.host.blocking(move || Ok(crate::devcontainer::cli(&data_dir).is_ok())).await?;
|
||||
let (docker, local, found) = match docker_ready(&call.host).await {
|
||||
Ok(()) => match find(&call.host, &target).await {
|
||||
Ok(found) => ("ready".to_owned(), true, found),
|
||||
Err(e) => (format!("cannot list the containers: {}", e.message), true, Found::default()),
|
||||
},
|
||||
// Not usable: say why, and whether the fault is only that it is not local.
|
||||
Err(e) => {
|
||||
let local = call
|
||||
.host
|
||||
.blocking(|| Ok(ide_docker::endpoint_is_local(&DockerEndpoint::Default).unwrap_or(false)))
|
||||
.await?;
|
||||
(e.message, local, Found::default())
|
||||
}
|
||||
};
|
||||
let root = call.root();
|
||||
let primary = found.primary.as_ref().map(|p| p.id.clone());
|
||||
let containers: Vec<Value> = found
|
||||
.all()
|
||||
.map(|c| {
|
||||
let mut v = json!({
|
||||
"id": c.id, "name": c.name, "state": c.state, "status": c.status,
|
||||
"image": c.image, "ports": c.ports, "primary": Some(&c.id) == primary.as_ref(),
|
||||
});
|
||||
if let Some(service) = &c.compose_service {
|
||||
v["service"] = service.clone().into();
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
let mut out = Map::new();
|
||||
out.insert("configFile".into(), target.config().map(|c| call.display(c)).into());
|
||||
let files: Vec<String> = config_files(root).iter().map(|f| call.display(f)).collect();
|
||||
out.insert("configFiles".into(), files.into());
|
||||
let mut ports: Vec<Value> = Vec::new();
|
||||
if let Some(config) = target.config() {
|
||||
match ide_workspace::devcontainer::load_file(config) {
|
||||
Ok(c) => {
|
||||
ports.extend(c.forward_ports.iter().map(|p| Value::from(*p)));
|
||||
ports.extend(c.forward_host_ports.iter().map(|(h, p)| Value::from(format!("{h}:{p}"))));
|
||||
}
|
||||
Err(e) => {
|
||||
out.insert("configError".into(), e.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
out.insert("forwardPorts".into(), ports.into());
|
||||
out.insert("containers".into(), containers.into());
|
||||
if docker == "ready"
|
||||
&& let Some(config) = target.config()
|
||||
{
|
||||
let folder = target.folder().to_path_buf();
|
||||
let config = ide_core::ipc_path::to_ipc(config);
|
||||
let resources = call
|
||||
.host
|
||||
.blocking(move || {
|
||||
crate::ops::devcontainer::inspect_status(
|
||||
&DockerEndpoint::Default,
|
||||
&folder,
|
||||
&config,
|
||||
primary.as_deref(),
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
out.insert(
|
||||
"resources".into(),
|
||||
serde_json::to_value(resources).map_err(|e| IdeError::internal(e.to_string()))?,
|
||||
);
|
||||
}
|
||||
out.insert("docker".into(), docker.into());
|
||||
out.insert("dockerLocal".into(), local.into());
|
||||
out.insert("cliInstalled".into(), cli.into());
|
||||
Output::json(Value::Object(out))
|
||||
},
|
||||
)
|
||||
.param(Param::optional("config", ParamType::String, CONFIG))
|
||||
}
|
||||
|
||||
fn logs() -> Tool {
|
||||
Tool::new(
|
||||
"devcontainer_logs",
|
||||
&format!(
|
||||
"Reads the end of a container's log (`docker logs`): the last `tail` lines (default {DEFAULT_TAIL}, at \
|
||||
most {MAX_TAIL}) of the project's dev container, or of `containerId`, which must be one of the containers \
|
||||
`devcontainer_status` lists (a Compose service's, for example). Returns `containerId`, `lines` (`text`, and `stderr` \
|
||||
for what the container wrote to its error output) and `truncated` (the log may go on before them). Works on a \
|
||||
stopped container. {WHICH}"
|
||||
),
|
||||
|call| async move {
|
||||
let tail = tail_of(call.opt_i64("tail")?)?;
|
||||
let timestamps = call.flag("timestamps", false)?;
|
||||
let wanted = call.opt_str("containerId")?;
|
||||
let target = target(&call)?;
|
||||
docker_ready(&call.host).await?;
|
||||
let found = find(&call.host, &target).await?;
|
||||
let id = choose(&found, wanted.as_deref())?.id.clone();
|
||||
let lines =
|
||||
ops::log_tail(&call.host, DockerEndpoint::Default, id.clone(), tail, timestamps, call.cancel.clone())
|
||||
.await?;
|
||||
let truncated = lines.len() >= tail as usize;
|
||||
let lines: Vec<Value> = lines.iter().map(|l| json!({ "text": l.text, "stderr": l.stderr })).collect();
|
||||
Output::json(json!({ "containerId": id, "lines": lines, "truncated": truncated }))
|
||||
},
|
||||
)
|
||||
.param(Param::optional("config", ParamType::String, CONFIG))
|
||||
.param(Param::optional(
|
||||
"containerId",
|
||||
ParamType::String,
|
||||
"A container of the project (at least 12 characters of its id, from `devcontainer_status`); default: the \
|
||||
primary one",
|
||||
))
|
||||
.param(Param::optional("tail", ParamType::Integer, "Lines from the end of the log (1 to 5000, default 200)"))
|
||||
.param(Param::optional("timestamps", ParamType::Boolean, "Prefix every line with its time (default false)"))
|
||||
}
|
||||
|
||||
async fn start(call: Call) -> IdeResult<Output> {
|
||||
let rebuild = call.flag("rebuild", false)?;
|
||||
let target = target(&call)?;
|
||||
let config = target.config().ok_or_else(|| no_config(&call))?;
|
||||
let limit = start_timeout(&call)?;
|
||||
let no_cache = call.flag("noCache", false)?;
|
||||
if no_cache && !rebuild {
|
||||
return Err(IdeError::invalid("noCache needs rebuild: true"));
|
||||
}
|
||||
let data_dir = call.host.local_data_dir.clone();
|
||||
let (cli, docker) = call
|
||||
.host
|
||||
.blocking(move || {
|
||||
daemon()?;
|
||||
let docker =
|
||||
ide_docker::docker_executable().ok_or_else(|| IdeError::unavailable("Docker is not installed"))?;
|
||||
Ok((crate::devcontainer::cli(&data_dir)?, docker))
|
||||
})
|
||||
.await?;
|
||||
let found = find(&call.host, &target).await?;
|
||||
if !found.stale.is_empty() {
|
||||
return Err(IdeError::unavailable("multiple dev containers match this configuration; see devcontainer_status"));
|
||||
}
|
||||
// Held until the start ends; a second one for the folder is refused, not queued.
|
||||
let _busy = ide_remote::devcontainer::Busy::take(target.folder())?;
|
||||
// Explicit labels disable the CLI's fallback to containers with the folder label alone.
|
||||
let mut extra = vec![
|
||||
"--id-label".to_owned(),
|
||||
format!("{FOLDER_LABEL}={}", target.folder_label()),
|
||||
"--id-label".to_owned(),
|
||||
format!("{CONFIG_LABEL}={}", label_value(&config.to_string_lossy())),
|
||||
];
|
||||
if rebuild {
|
||||
not_attached(&call, &found.primary.iter().collect::<Vec<_>>(), "rebuild it")?;
|
||||
}
|
||||
if no_cache {
|
||||
extra.push("--build-no-cache".to_owned());
|
||||
}
|
||||
let mut command = vec!["devcontainer".to_owned(), "up".to_owned()];
|
||||
command.extend(target.args().iter().map(|a| a.to_string_lossy().into_owned()));
|
||||
command.extend(extra.iter().cloned());
|
||||
let removed = found.primary_id().filter(|_| rebuild);
|
||||
let command = match removed {
|
||||
Some(id) => format!("docker container rm --force {id}\n{}", shown(&command)),
|
||||
None => shown(&command),
|
||||
};
|
||||
let existing = found.primary.as_ref().map(describe);
|
||||
let mut detail = format!(
|
||||
"{}\n\nContainer: {}",
|
||||
command,
|
||||
match (&existing, rebuild) {
|
||||
(Some(c), true) => format!("{c}, removed first"),
|
||||
(Some(c), false) => c.clone(),
|
||||
(None, _) => "none yet".to_owned(),
|
||||
}
|
||||
);
|
||||
let folder = target.folder().to_path_buf();
|
||||
let config_path = ide_core::ipc_path::to_ipc(config);
|
||||
let requirements = call
|
||||
.host
|
||||
.blocking(move || crate::ops::devcontainer::check_requirements(&folder, &config_path, &DockerEndpoint::Default))
|
||||
.await?;
|
||||
for shortfall in requirements.shortfalls {
|
||||
detail.push('\n');
|
||||
detail.push_str(&shortfall.message);
|
||||
}
|
||||
call.confirm(if rebuild { "Rebuild dev container" } else { "Start dev container" }, Some(detail)).await?;
|
||||
docker_ready(&call.host).await?;
|
||||
let current = find(&call.host, &target).await?;
|
||||
if found.primary_id() != current.primary_id() || !current.stale.is_empty() {
|
||||
return Err(IdeError::unavailable(
|
||||
"the dev container changed while awaiting approval; call devcontainer_up again",
|
||||
));
|
||||
}
|
||||
if rebuild {
|
||||
not_attached(&call, ¤t.primary.iter().collect::<Vec<_>>(), "rebuild it")?;
|
||||
}
|
||||
ensure_inside(call.root(), config)?;
|
||||
if let Some(id) = removed {
|
||||
ide_workspace::devcontainer::load_file(config).map_err(IdeError::invalid)?;
|
||||
if call.cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
call.project.require_trust()?;
|
||||
// The CLI's rebuild flag resolves labels again. Remove only the ID shown for approval.
|
||||
ops::docker_remove(&call.host, DockerEndpoint::Default, DockerObject::Container, vec![id.to_owned()], true)
|
||||
.await?;
|
||||
if find(&call.host, &target).await?.primary.is_some() {
|
||||
return Err(IdeError::unavailable("a replacement dev container appeared; call devcontainer_up again"));
|
||||
}
|
||||
}
|
||||
let removed = removed.map(str::to_owned);
|
||||
let cancel = call.cancel.clone();
|
||||
let up = call
|
||||
.host
|
||||
.blocking(move || {
|
||||
if let Some(config) = target.config() {
|
||||
ensure_inside(target.folder(), config)?;
|
||||
}
|
||||
let extra: Vec<&str> = extra.iter().map(String::as_str).collect();
|
||||
ide_remote::devcontainer::up(
|
||||
&cli,
|
||||
&docker,
|
||||
&target,
|
||||
&extra,
|
||||
limit,
|
||||
&mut |line| tracing::debug!(target: "devcontainer", "{line}"),
|
||||
&cancel,
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
let mut out = json!({
|
||||
"containerId": up.container, "remoteUser": up.user, "remoteWorkspaceFolder": up.folder, "outcome": "success",
|
||||
});
|
||||
if rebuild {
|
||||
out["removed"] = removed.into();
|
||||
}
|
||||
Output::json(out)
|
||||
}
|
||||
|
||||
fn up() -> Tool {
|
||||
Tool::new(
|
||||
"devcontainer_up",
|
||||
&format!(
|
||||
"Starts the project's dev container with the Dev Containers CLI (`devcontainer up`): builds the image \
|
||||
when needed, creates or starts the container and runs the lifecycle commands of its configuration, which run the \
|
||||
project's code on this machine and in the container; the user is asked first (unless the IDE runs tools without \
|
||||
confirmation). With `rebuild` it removes the project's approved container first and builds \
|
||||
and starts it again, to pick up a changed `devcontainer.json`, Dockerfile or features; files in the container that \
|
||||
are not in the project folder or a volume are lost, and a container a window is open in is refused (use Rebuild \
|
||||
Container in that window). Waits for it to finish, up to `timeout` milliseconds (default 30 minutes; the CLI is \
|
||||
stopped when it passes), and returns `containerId`, `remoteUser`, `remoteWorkspaceFolder` and `outcome`, and with \
|
||||
`rebuild` `removed`, the id of the container it replaced (null when there was none). An error carries the end of \
|
||||
the CLI's log. One start per project folder runs at a time. {WHICH}"
|
||||
),
|
||||
start,
|
||||
)
|
||||
.write()
|
||||
.param(Param::optional("config", ParamType::String, CONFIG))
|
||||
.param(Param::optional(
|
||||
"rebuild",
|
||||
ParamType::Boolean,
|
||||
"Remove the existing container and build it again (default false)",
|
||||
))
|
||||
.param(Param::optional(
|
||||
"noCache",
|
||||
ParamType::Boolean,
|
||||
"With `rebuild`: build the image without Docker's cache (default false); refused without `rebuild`",
|
||||
))
|
||||
.param(Param::optional(
|
||||
"timeout",
|
||||
ParamType::Integer,
|
||||
"Milliseconds to wait at most, more than 0 (default 1800000); the CLI is stopped when it passes",
|
||||
))
|
||||
}
|
||||
|
||||
fn exec() -> Tool {
|
||||
Tool::new(
|
||||
"devcontainer_exec",
|
||||
&format!(
|
||||
"Runs a shell command line in the project's running dev container (`devcontainer exec`: as the \
|
||||
configuration's `remoteUser`, with its `remoteEnv`, in the project folder of the container), in a new or reused \
|
||||
tab of OpenIDEA's Run tool window, as `run_command` does in the shell of this machine: the user is asked first \
|
||||
(unless the IDE runs tools without confirmation), and the call returns when the command finishes, its output \
|
||||
matches `pattern` or `timeout` milliseconds (default {EXEC_TIMEOUT_MS}) pass, with the same result (`state`, \
|
||||
`exitCode`, `output`, `waitEnded`…) plus `containerId`; `wait_for_run`, `read_run_output`, `get_run_status`, \
|
||||
`send_run_input` and `stop_run` follow it up by name. Stopping the tab ends the CLI on this machine; a process it \
|
||||
started in the container may keep running there. The container must be running (see `devcontainer_status`, \
|
||||
`devcontainer_up`). {WHICH}{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
|
||||
),
|
||||
|call| async move {
|
||||
call.needs_window()?;
|
||||
let name = tab_name(&call.str("name")?)?;
|
||||
let command = call.str("command")?;
|
||||
if command.trim().is_empty() {
|
||||
return Err(IdeError::invalid("command must not be empty"));
|
||||
}
|
||||
let envs = envs_of(&call)?;
|
||||
let target = target(&call)?;
|
||||
let config = target.config().ok_or_else(|| no_config(&call))?.to_path_buf();
|
||||
if let Some(run) = call.host.mcp_agent_runs.get(call.root(), &name).filter(|r| r.running()) {
|
||||
return Err(busy(&run));
|
||||
}
|
||||
let data_dir = call.host.local_data_dir.clone();
|
||||
let (cli, docker) = call
|
||||
.host
|
||||
.blocking(move || {
|
||||
daemon()?;
|
||||
let docker = ide_docker::docker_executable()
|
||||
.ok_or_else(|| IdeError::unavailable("Docker is not installed"))?;
|
||||
Ok((crate::devcontainer::cli(&data_dir)?, docker))
|
||||
})
|
||||
.await?;
|
||||
let found = find(&call.host, &target).await?;
|
||||
let container = found.primary.filter(DockerContainer::running).ok_or_else(|| {
|
||||
IdeError::unavailable("the dev container is not running; start it with devcontainer_up")
|
||||
})?;
|
||||
let argv = exec_argv(&cli, &docker, &target, &container.id, &envs, &command);
|
||||
let mut detail = format!(
|
||||
"{command}\n\nTab: {name}\nContainer: {}\nCommand line: {}",
|
||||
describe(&container),
|
||||
shown(&argv)
|
||||
);
|
||||
for (key, value) in &envs {
|
||||
detail.push_str(&format!("\n{key}={value}"));
|
||||
}
|
||||
let mut extra = Map::new();
|
||||
extra.insert("containerId".into(), container.id.clone().into());
|
||||
let tab = Tab {
|
||||
subject: "Run in dev container".into(),
|
||||
command: format!("in dev container {}: {command}", container.name),
|
||||
name,
|
||||
detail,
|
||||
cwd: call.root().to_path_buf(),
|
||||
env: Vec::new(),
|
||||
execution: Execution::Container { id: container.id, config, argv },
|
||||
extra,
|
||||
};
|
||||
start_in_tab(&call, tab, EXEC_TIMEOUT_MS).await
|
||||
},
|
||||
)
|
||||
.write()
|
||||
.param(Param::required("name", ParamType::String, NAME))
|
||||
.param(Param::required(
|
||||
"command",
|
||||
ParamType::String,
|
||||
"Shell command line to run in the container with `sh -c`, e.g. `npm test` or `pytest -x`",
|
||||
))
|
||||
.param(Param::optional("config", ParamType::String, CONFIG))
|
||||
.param(Param::optional(
|
||||
"envs",
|
||||
ParamType::StringMap,
|
||||
"Environment variables added for this command (names of letters, digits and `_`)",
|
||||
))
|
||||
.param(Param::optional(
|
||||
"timeout",
|
||||
ParamType::Integer,
|
||||
"Milliseconds to wait for the command to finish before returning (0 returns once it started); the command \
|
||||
keeps running after it",
|
||||
))
|
||||
.param(Param::optional(
|
||||
"pattern",
|
||||
ParamType::String,
|
||||
"Regular expression that ends the wait when the command's output matches it. `waitEnded` is then `matched`",
|
||||
))
|
||||
.param(Param::optional("maxLinesCount", ParamType::Integer, MAX_LINES))
|
||||
.param(Param::optional("truncateMode", ParamType::String, TRUNCATE_MODE))
|
||||
}
|
||||
|
||||
fn stop() -> Tool {
|
||||
Tool::new(
|
||||
"devcontainer_stop",
|
||||
&format!(
|
||||
"Stops the project's dev container and the other containers of its Docker Compose project \
|
||||
(`docker container stop`); nothing is removed, and `devcontainer_up` starts it again. Refused for a container a \
|
||||
window is open in. The user is asked first (unless the IDE runs tools without confirmation). Returns `stopped`, \
|
||||
the ids of the containers that were running (none when nothing was). {WHICH}"
|
||||
),
|
||||
|call| async move {
|
||||
let target = target(&call)?;
|
||||
docker_ready(&call.host).await?;
|
||||
let found = find(&call.host, &target).await?;
|
||||
let running = found.running_group();
|
||||
if running.is_empty() {
|
||||
return Output::json(json!({ "stopped": [] }));
|
||||
}
|
||||
not_attached(&call, &running, "stop it")?;
|
||||
let ids: Vec<String> = running.iter().map(|c| c.id.clone()).collect();
|
||||
let names: Vec<String> = running.iter().map(|c| describe(c)).collect();
|
||||
let mut command = vec!["docker".to_owned(), "container".to_owned(), "stop".to_owned()];
|
||||
command.extend(ids.iter().cloned());
|
||||
call.confirm(
|
||||
"Stop dev container",
|
||||
Some(format!("{}\n\nContainers: {}", shown(&command), names.join(", "))),
|
||||
)
|
||||
.await?;
|
||||
ops::stop_containers(&call.host, DockerEndpoint::Default, ids.clone()).await?;
|
||||
Output::json(json!({ "stopped": ids }))
|
||||
},
|
||||
)
|
||||
.write()
|
||||
.param(Param::optional("config", ParamType::String, CONFIG))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ROOT: &str = if cfg!(windows) { r"C:\work\app" } else { "/work/app" };
|
||||
const CONFIG_FILE: &str = if cfg!(windows) {
|
||||
r"C:\work\app\.devcontainer\devcontainer.json"
|
||||
} else {
|
||||
"/work/app/.devcontainer/devcontainer.json"
|
||||
};
|
||||
|
||||
fn container(id: &str, labels: &[(&str, &str)]) -> DockerContainer {
|
||||
DockerContainer {
|
||||
id: id.repeat(64 / id.len()),
|
||||
name: format!("name-{id}"),
|
||||
image: "img".into(),
|
||||
command: String::new(),
|
||||
state: "running".into(),
|
||||
status: "Up".into(),
|
||||
ports: String::new(),
|
||||
created_at: "2026-01-01 10:00:00 +0000 UTC".into(),
|
||||
compose_project: None,
|
||||
compose_service: None,
|
||||
compose_working_dir: None,
|
||||
compose_files: Vec::new(),
|
||||
mounts: Vec::new(),
|
||||
networks: Vec::new(),
|
||||
labels: labels.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn target() -> Target {
|
||||
Target::new(ROOT, Some(PathBuf::from(CONFIG_FILE)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn labels_decide_which_container_is_the_projects() {
|
||||
let both = container("a", &[(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)]);
|
||||
let legacy = container("b", &[(FOLDER_LABEL, ROOT)]);
|
||||
let other_folder = container("c", &[(FOLDER_LABEL, "/work/other"), (CONFIG_LABEL, CONFIG_FILE)]);
|
||||
let other_config =
|
||||
container("d", &[(FOLDER_LABEL, ROOT), (CONFIG_LABEL, "/work/app/.devcontainer/b/devcontainer.json")]);
|
||||
let unlabelled = container("e", &[("com.docker.compose.project", "app")]);
|
||||
let t = target();
|
||||
let config_only = container("f", &[(CONFIG_LABEL, CONFIG_FILE)]);
|
||||
assert!(project_containers(vec![legacy.clone()], &t).is_empty());
|
||||
let matches =
|
||||
project_containers(vec![both.clone(), legacy, other_folder, other_config, unlabelled, config_only], &t);
|
||||
assert_eq!(matches.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), [both.id.as_str()]);
|
||||
assert!(project_containers(vec![both], &Target::new(ROOT, None)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_windows_drive_letter_is_matched_in_lower_case() {
|
||||
let root = r"C:\Users\me\app";
|
||||
let config = r"C:\Users\me\app\.devcontainer\devcontainer.json";
|
||||
let t = Target::new(root, Some(PathBuf::from(config)));
|
||||
let written = container("a", &[(FOLDER_LABEL, r"c:\Users\me\app"), (CONFIG_LABEL, config)]);
|
||||
assert_eq!(project_containers(vec![written], &t).len(), 1);
|
||||
assert_eq!(t.folder_label(), r"c:\Users\me\app");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_primary_is_running_before_stopped_and_new_before_old() {
|
||||
let labels = [(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)];
|
||||
let mut old_running = container("a", &labels);
|
||||
old_running.created_at = "2026-01-01 10:00:00 +0000 UTC".into();
|
||||
let mut new_running = container("b", &labels);
|
||||
new_running.created_at = "2026-02-01 10:00:00 +0000 UTC".into();
|
||||
let mut newest_stopped = container("c", &labels);
|
||||
newest_stopped.created_at = "2026-03-01 10:00:00 +0000 UTC".into();
|
||||
newest_stopped.state = "exited".into();
|
||||
let order: Vec<String> = project_containers(vec![old_running, newest_stopped, new_running], &target())
|
||||
.into_iter()
|
||||
.map(|c| c.name)
|
||||
.collect();
|
||||
assert_eq!(order, ["name-b", "name-a", "name-c"]);
|
||||
}
|
||||
|
||||
fn found() -> Found {
|
||||
let labels = [(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)];
|
||||
let mut sibling = container("d", &[("com.docker.compose.project", "app")]);
|
||||
sibling.compose_service = Some("db".into());
|
||||
Found { primary: Some(container("a", &labels)), stale: vec![container("b", &labels)], siblings: vec![sibling] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compose_siblings_share_the_working_directory_of_a_primary_that_has_one() {
|
||||
let labels = [(FOLDER_LABEL, ROOT), (CONFIG_LABEL, CONFIG_FILE)];
|
||||
let mut primary = container("a", &labels);
|
||||
let (mut mine, mut foreign, mut unlabelled) = (container("d", &[]), container("e", &[]), container("f", &[]));
|
||||
primary.compose_working_dir = Some("/work/app/.devcontainer".into());
|
||||
mine.compose_working_dir = primary.compose_working_dir.clone();
|
||||
foreign.compose_working_dir = Some("/other/app/.devcontainer".into());
|
||||
let mut legacy = container("b", &[(FOLDER_LABEL, ROOT)]);
|
||||
legacy.compose_working_dir = primary.compose_working_dir.clone();
|
||||
let members = vec![primary.clone(), mine.clone(), foreign.clone(), unlabelled.clone(), legacy];
|
||||
let ids: Vec<String> = siblings_of(&primary, members.clone()).into_iter().map(|c| c.id).collect();
|
||||
assert_eq!(ids, [mine.id.clone()]);
|
||||
// A primary without a working directory matches nobody, not even containers without one.
|
||||
primary.compose_working_dir = None;
|
||||
unlabelled.compose_working_dir = None;
|
||||
assert!(siblings_of(&primary, members).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_container_id_must_name_one_of_the_projects_containers() {
|
||||
let found = found();
|
||||
let id = |c: &DockerContainer| c.id.clone();
|
||||
let primary = id(found.primary.as_ref().unwrap());
|
||||
assert_eq!(choose(&found, None).unwrap().id, primary);
|
||||
assert_eq!(choose(&found, Some(&primary)).unwrap().id, primary);
|
||||
assert_eq!(choose(&found, Some(&primary[..12].to_uppercase())).unwrap().id, primary);
|
||||
assert_eq!(choose(&found, Some(&id(&found.siblings[0]))).unwrap().name, "name-d");
|
||||
for foreign in ["e".repeat(64).as_str(), "ffffffffffff", &primary[..11], "", "--all", "name-a"] {
|
||||
let refused = choose(&found, Some(foreign)).map(|c| c.id.clone());
|
||||
if foreign.trim().is_empty() {
|
||||
assert_eq!(refused.unwrap(), primary);
|
||||
continue;
|
||||
}
|
||||
let message = refused.unwrap_err().message;
|
||||
assert!(message.ends_with("does not belong to this project's dev container"), "{foreign}: {message}");
|
||||
}
|
||||
let none = Found { primary: None, stale: Vec::new(), siblings: Vec::new() };
|
||||
assert!(choose(&none, None).unwrap_err().message.contains("devcontainer_up"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_acts_on_the_primary_and_its_compose_project_only() {
|
||||
let mut found = found();
|
||||
found.stale[0].state = "running".into();
|
||||
let names: Vec<&str> = found.running_group().into_iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(names, ["name-a", "name-d"]);
|
||||
found.siblings[0].state = "exited".into();
|
||||
assert_eq!(found.running_group().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tail_is_one_to_five_thousand() {
|
||||
assert_eq!(tail_of(None).unwrap(), 200);
|
||||
assert_eq!(tail_of(Some(1)).unwrap(), 1);
|
||||
assert_eq!(tail_of(Some(5000)).unwrap(), 5000);
|
||||
for bad in [0, -1, 5001] {
|
||||
assert!(tail_of(Some(bad)).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_devcontainer_json_files_are_configurations() {
|
||||
assert!(is_config_file(Path::new("/p/.devcontainer/devcontainer.json")));
|
||||
assert!(is_config_file(Path::new("/p/.devcontainer.json")));
|
||||
assert!(!is_config_file(Path::new("/p/package.json")));
|
||||
assert!(!is_config_file(Path::new("/p/.devcontainer/Dockerfile")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_configuration_of_the_project_is_listed() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
for f in [".devcontainer/devcontainer.json", ".devcontainer/py/devcontainer.json", ".devcontainer.json"] {
|
||||
std::fs::create_dir_all(root.join(f).parent().unwrap()).unwrap();
|
||||
std::fs::write(root.join(f), "{}").unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(root.join(".devcontainer/empty")).unwrap();
|
||||
let found: Vec<String> = config_files(root)
|
||||
.iter()
|
||||
.map(|f| f.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/"))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
found,
|
||||
[".devcontainer/devcontainer.json", ".devcontainer.json", ".devcontainer/py/devcontainer.json"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_line_for_people_quotes_what_needs_it() {
|
||||
let argv = ["devcontainer", "exec", "--remote-env=A=b c", "sh", "-c", "echo 'x' && ls"].map(String::from);
|
||||
assert_eq!(shown(&argv), r#"devcontainer exec '--remote-env=A=b c' sh -c 'echo '\''x'\'' && ls'"#);
|
||||
}
|
||||
|
||||
/// A stand-in for the Dev Containers CLI that checks where `exec` and `sh -c` are.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn exec_pins_the_approved_id_even_when_a_replacement_matches() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cli = dir.path().join("devcontainer");
|
||||
let approved = "a".repeat(64);
|
||||
let replacement = "b".repeat(64);
|
||||
let script = format!(
|
||||
r#"#!/bin/sh
|
||||
[ "$1" = exec ] || {{ echo "exec is not first: $*" >&2; exit 2; }}
|
||||
[ "$2 $3" = "--workspace-folder {ROOT}" ] || {{ echo "no folder: $*" >&2; exit 2; }}
|
||||
[ "$4 $5" = "--config {CONFIG_FILE}" ] || {{ echo "no config: $*" >&2; exit 2; }}
|
||||
[ "$6" = "--container-id" ] || {{ echo "no approved id: $*" >&2; exit 2; }}
|
||||
[ "$7" = "$MATCHING_CONTAINER" ] || {{ echo "pinned container unavailable" >&2; exit 3; }}
|
||||
[ "$8 $9" = "--docker-path /usr/bin/docker" ] || {{ echo "no docker: $*" >&2; exit 2; }}
|
||||
shift 9
|
||||
[ "$1" = "--remote-env=A=1 2" ] && [ "$2" = "--remote-env=B_=" ] || {{ echo "no env: $*" >&2; exit 2; }}
|
||||
[ $# -eq 5 ] && [ "$3 $4" = "sh -c" ] || {{ echo "sh -c is not last: $*" >&2; exit 2; }}
|
||||
printf '%s' "$5"
|
||||
"#,
|
||||
);
|
||||
std::fs::write(&cli, script).unwrap();
|
||||
std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let command = "echo \"$A\" && ls -- 'x y'; exit 3";
|
||||
let envs = vec![("A".to_owned(), "1 2".to_owned()), ("B_".to_owned(), String::new())];
|
||||
let argv = exec_argv(&cli, Path::new("/usr/bin/docker"), &target(), &approved, &envs, command);
|
||||
assert_eq!(argv[1], "exec");
|
||||
assert_eq!(&argv[argv.len() - 3..], ["sh", "-c", command]);
|
||||
let invoke =
|
||||
|id| std::process::Command::new(&argv[0]).args(&argv[1..]).env("MATCHING_CONTAINER", id).output().unwrap();
|
||||
let out = invoke(&approved);
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
assert_eq!(String::from_utf8_lossy(&out.stdout), command);
|
||||
let out = invoke(&replacement);
|
||||
assert_eq!(out.status.code(), Some(3));
|
||||
assert!(out.stdout.is_empty());
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1710 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача