дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 09:11:10 +02:00
Порівняти коміти
218
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
f53b89b6e9 | ||
|
|
bc63e8e029 | ||
|
|
a579d81694 | ||
|
|
6eb1f0713d | ||
|
|
95d4a41b62 | ||
|
|
18ac414b52 | ||
|
|
10e399cbec | ||
|
|
ce4b2f9655 | ||
|
|
65686e246e | ||
|
|
3078674a86 | ||
|
|
82d8a6ea19 | ||
|
|
3785b75582 | ||
|
|
15b55c66ca | ||
|
|
d6d6fd0909 | ||
|
|
7bfad25bb5 | ||
|
|
5c31ccfe70 | ||
|
|
304674d0fe | ||
|
|
aa003541a3 | ||
|
|
d2699c430e | ||
|
|
f404a33e7a | ||
|
|
05e7db4be6 | ||
|
|
8ad3fc4faf | ||
|
|
3f7b83e8fd | ||
|
|
7fa280e9e0 | ||
|
|
3c8acf8ee3 | ||
|
|
0d94a8973e | ||
|
|
18f28cd804 | ||
|
|
37f2dd3ced | ||
|
|
ba5eb92c70 | ||
|
|
bbbcf23c77 | ||
|
|
ac9f745dcf | ||
|
|
86cfabfbe4 | ||
|
|
6b038245fd | ||
|
|
e985322f3a | ||
|
|
1f329cbc87 | ||
|
|
0f0cdd4672 | ||
|
|
875b17938e | ||
|
|
6820d27af5 | ||
|
|
02aa916a26 | ||
|
|
a7b9529109 | ||
|
|
0303a513cd | ||
|
|
a2bf7fb0c4 | ||
|
|
17dd723a3d | ||
|
|
f1097831d7 | ||
|
|
ad0a755f07 | ||
|
|
099bb57abd | ||
|
|
1ba2ce55bb | ||
|
|
24588b0975 | ||
|
|
8dc1fecc0e | ||
|
|
cb7668d4f0 | ||
|
|
90377204aa | ||
|
|
1d3de3c366 | ||
|
|
4466a059b3 | ||
|
|
b7bacc8ff5 | ||
|
|
50508b0af0 | ||
|
|
ef4458c04c | ||
|
|
0666f9ea5a | ||
|
|
3fe4e12252 | ||
|
|
9ecb664036 | ||
|
|
e6c8d6d9ac | ||
|
|
a68ebc1293 | ||
|
|
8b267c6307 | ||
|
|
67460f1275 | ||
|
|
4a620287c8 | ||
|
|
607812d8fa | ||
|
|
90f9d4ffd0 | ||
|
|
0f359ddf3b | ||
|
|
51a6b40314 | ||
|
|
bd5af356f4 | ||
|
|
d3cb8513be | ||
|
|
29d1a52d91 | ||
|
|
5b24b61b49 | ||
|
|
1dd8ea9b3b | ||
|
|
2221afad01 | ||
|
|
471bce2bb1 | ||
|
|
b630dfad55 | ||
|
|
74b50f7592 | ||
|
|
95bc3622ab | ||
|
|
b911366115 | ||
|
|
b2a9d105e2 | ||
|
|
b83c2cf11a | ||
|
|
6648f502f1 | ||
|
|
115003f0b6 | ||
|
|
02d912d72a | ||
|
|
70fe0e6653 | ||
|
|
950bf986d6 | ||
|
|
310d923480 | ||
|
|
0c506fa479 | ||
|
|
bc86836492 | ||
|
|
dead55af21 | ||
|
|
c7a4201ce9 | ||
|
|
91cf66e72e | ||
|
|
4a87022e58 | ||
|
|
c92bd0999b | ||
|
|
880835f0ac | ||
|
|
ce938df81b | ||
|
|
9abe3d7e3c | ||
|
|
4e5ae49aa9 | ||
|
|
9443517d1c | ||
|
|
29f6131f9d | ||
|
|
4027b8341f | ||
|
|
ddc483fd2a | ||
|
|
23d81a2b3d | ||
|
|
74f61a3540 | ||
|
|
c287ce0ee3 | ||
|
|
607e4e095d | ||
|
|
e7da5e0937 | ||
|
|
ae4a90b23a | ||
|
|
04006f2ea7 | ||
|
|
7f20fc0c54 | ||
|
|
a8db175c25 | ||
|
|
8aacedf5ad | ||
|
|
1425bfe8ae | ||
|
|
75ec6c51a3 | ||
|
|
b20e7c0817 | ||
|
|
adf5701e16 | ||
|
|
5debc5297b | ||
|
|
5db70297cb | ||
|
|
0f78b845e6 | ||
|
|
c319656529 | ||
|
|
4ebc769042 | ||
|
|
300424658a | ||
|
|
44ccaaef26 | ||
|
|
befb4792ce | ||
|
|
34741f56c4 | ||
|
|
2907832e37 | ||
|
|
ff4e916561 | ||
|
|
2f799aede9 | ||
|
|
f853ccf544 | ||
|
|
8b4de98664 | ||
|
|
a36516d463 | ||
|
|
b7c2d4eacb | ||
|
|
abc5b2b2c6 | ||
|
|
cb10ba7207 | ||
|
|
0fe39535d6 | ||
|
|
0c9ffe1e41 | ||
|
|
cda99d5495 | ||
|
|
d979e102f9 | ||
|
|
67d68f7f4e | ||
|
|
2b73ef73f1 | ||
|
|
de41651a5e | ||
|
|
6bd2d5f843 | ||
|
|
93c15547ef | ||
|
|
90d98f3edd | ||
|
|
b7ef68df71 | ||
|
|
fdc4df4752 | ||
|
|
54ce048ec9 | ||
|
|
a372385788 | ||
|
|
7ff8d472f7 | ||
|
|
4de01a91c5 | ||
|
|
657d49e30a | ||
|
|
2a7975a077 | ||
|
|
71d88d0b55 | ||
|
|
c6faf280db | ||
|
|
fba7705acf | ||
|
|
f87fb35be5 | ||
|
|
f4236a0ea1 | ||
|
|
1eece0ae51 | ||
|
|
7361707b63 | ||
|
|
8e56d3b73e | ||
|
|
e5453a8a97 | ||
|
|
27689f09d3 | ||
|
|
9b468b0873 | ||
|
|
cb887dad80 | ||
|
|
3cfbf80e26 | ||
|
|
97add1f448 | ||
|
|
35a6bec1c2 | ||
|
|
f8ba067e1d | ||
|
|
85cbc6bacd | ||
|
|
3f490684d6 | ||
|
|
8f6200c3fa | ||
|
|
0aa64c2c6e | ||
|
|
8d4e016cb0 | ||
|
|
a1ef8ca749 | ||
|
|
669462c4de | ||
|
|
90eb6bac1b | ||
|
|
674e925c9a | ||
|
|
ddd27a6e50 | ||
|
|
d4791ea0c2 | ||
|
|
baea2733f8 | ||
|
|
0d2401705e | ||
|
|
6c96b79538 | ||
|
|
878e86e10c | ||
|
|
6c36723a7d | ||
|
|
ed58f1aba0 | ||
|
|
adda2cbb93 | ||
|
|
132259242a | ||
|
|
1a400d3405 | ||
|
|
aa1711194c | ||
|
|
83dcdc8eca | ||
|
|
783daaa041 | ||
|
|
dc74595bca | ||
|
|
aa596f1125 | ||
|
|
6927b787b2 | ||
|
|
e1e9ede2d6 | ||
|
|
839292fb30 | ||
|
|
2a4bf1f848 | ||
|
|
3e41c93a95 | ||
|
|
b85027dc47 | ||
|
|
63c2ced086 | ||
|
|
d73b8d8ec1 | ||
|
|
74b90a114a | ||
|
|
e70b516ca0 | ||
|
|
7d15681313 | ||
|
|
2ecaefe859 | ||
|
|
895e5bd56e | ||
|
|
2dc577614b | ||
|
|
a9e92d0665 | ||
|
|
fa0be07436 | ||
|
|
fea27f5608 | ||
|
|
a4d172ac83 | ||
|
|
c40d06c702 | ||
|
|
619ae7f727 | ||
|
|
c725b1629d | ||
|
|
b0033a869d | ||
|
|
4ed4ced5b1 | ||
|
|
7668e4a5ba | ||
|
|
4a6e0dfac1 |
No files matched your search
@@ -0,0 +1,129 @@
|
||||
---
|
||||
name: pr
|
||||
description: Prepare and open an OpenIDEA pull request that a maintainer can accept from its description — scope check, the checks CI runs, evidence chosen by the kind of change, UX consistency review, and a filled-in template. Use before opening or updating a PR ("提 pr", "open a PR", "写 PR 描述", "准备验收证据").
|
||||
---
|
||||
|
||||
# Open a pull request with evidence
|
||||
|
||||
A reviewer should be able to accept the PR from its description: what changed, why, and proof
|
||||
that it works and didn't break its neighbours. Evidence is the part people skip; it is required.
|
||||
|
||||
## 1. Scope
|
||||
|
||||
- One problem per PR. If the description needs more than 2–4 sentences, split it.
|
||||
- `Closes #<n>` when it resolves an issue. Read the issue's comments first: a maintainer may
|
||||
already have decided how it should behave.
|
||||
- The diff contains only what the problem needs: no drive-by refactors, formatting of untouched
|
||||
files, generated files you didn't need to regenerate, or local IDE state (`.openidea/`).
|
||||
- A product decision you can't make (layout or navigation restructure, a changed default, an
|
||||
unclear expected behaviour) → ask in the issue, label `needs-decision`, stop.
|
||||
- Title in Conventional Commits, written as the commit you want on `main`:
|
||||
`fix(editor): keep the caret visible after folding`. It describes the change, not the
|
||||
process; no references to screenshots, other products or "parity".
|
||||
|
||||
## 2. Checks
|
||||
|
||||
Run what CI runs for the parts you touched (`AGENTS.md` § Before opening a PR). Run long checks
|
||||
one at a time. Paste the command and its result line (`test result: ok. 412 passed`,
|
||||
`Tests 87 passed`), not "tests pass".
|
||||
|
||||
Easy to miss:
|
||||
|
||||
| You touched | Also run |
|
||||
| --------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
|
||||
| Any `.ts`/`.tsx`, including tests | `pnpm typecheck` |
|
||||
| A feature's UI | every spec under `e2e/` whose name contains the feature |
|
||||
| New regex in frontend code | `pnpm vitest run src/platform/webkitCompatibility.test.ts` |
|
||||
| Text catalog keys | `pnpm vitest run src/platform/locales/textCatalog.test.ts src/platform/i18n.test.ts` |
|
||||
| `tokens.css` | `pnpm gen:theme-docs`, then the full `pnpm test` |
|
||||
| Moved or removed exports | `pnpm knip` |
|
||||
| A `pub fn` signature | `cargo test -p <crate>` (all targets), or workspace clippy |
|
||||
| A new crate dependency, or imports in files the smoke runs load | `pnpm vitest run scripts/smoke-paths.test.ts` |
|
||||
| IPC types | `pnpm gen:bindings`, commit `src/bindings.ts` |
|
||||
| `wit/` or the plugin SDK | `plugins/build.sh`, commit the rebuilt `dist/` |
|
||||
|
||||
## 3. Evidence
|
||||
|
||||
Pick every row that applies. Evidence must come from the final commit of the branch; re-take it
|
||||
after review changes that affect it.
|
||||
|
||||
| Change | Evidence |
|
||||
| ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Bug fix | A test that fails on `main` and passes on the branch (name it), or exact steps from a fresh start with the before/after result |
|
||||
| Visible UI | `before.png` / `after.png` at the same state and window size. Every theme the change touches (at least Islands Light and Islands Dark when colours, borders or icons change). The narrow case when width matters |
|
||||
| Interaction: multi-step, drag and drop, keyboard, focus, animation | A short recording (GIF/MP4), or numbered screenshots of each step |
|
||||
| Keyboard shortcut or action | Where it appears (Find Action, menu, keymap settings) and that it doesn't clash in the default keymaps |
|
||||
| Code intelligence / language support | Which `fixtures/` project, `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` output; for Java, `pnpm eval --only <id>` numbers before/after |
|
||||
| Run / debug | `pnpm smoke smoke/run.test.ts -t <language>` or `smoke/debug.test.ts`, plus a screenshot of the Run/Debug tool window |
|
||||
| Performance | Before/after numbers on the same machine and build type (`pnpm perf`, `pnpm perf:rust`, or the exact measurement), and evidence the results are identical: a fast path must return the same results or fall back |
|
||||
| Windows / Linux only | The platform's CI job, and a screenshot or log from a real machine. Say plainly if you couldn't run it on that platform |
|
||||
| Backend / IPC | Test output; logs for behaviour tests can't reach |
|
||||
| Remote development / containers / WSL | The flow against a real `openidea-server` host or container, with a screenshot or log |
|
||||
| Plugin API / `wit/` | A sample plugin exercising the change, and the rebuilt `dist/` |
|
||||
| Settings / persisted data / migrations | Start from data written by the previous release and show it still loads and behaves the same |
|
||||
| Security fix | A test for the attack case. Describe the class of problem only; follow `SECURITY.md` for anything not yet public |
|
||||
| Copy, docs, pure refactor | The commands run, and "No visible change" / "no behaviour change" stated |
|
||||
|
||||
Also state what else the change could affect (other languages, platforms, entry points such as
|
||||
menu / context menu / shortcut, other themes) and how you checked each.
|
||||
|
||||
How to capture:
|
||||
|
||||
- Use the `verify` skill to drive the app and take screenshots. Before: on `main` (or with the
|
||||
fix reverted). After: on the branch, same state and window size.
|
||||
- Crop to the relevant area when the window is large, but keep enough context to locate it.
|
||||
- Drag screenshots and recordings into the PR description on GitHub. Never commit them.
|
||||
- No real credentials, tokens, private repository names or personal paths in screenshots or logs.
|
||||
|
||||
## 4. UX consistency
|
||||
|
||||
For any change users can see, review it against `DESIGN.md`, `PRODUCT.md` and
|
||||
`docs/en/contribute/guidelines/ui.mdx` before taking the "after" screenshots:
|
||||
|
||||
- Tokens only; spacing on the `--space-*` scale; icons from `src/ui/icons.tsx`; no emoji.
|
||||
- Built from `src/ui/` primitives and workbench contributions; it looks like its neighbours
|
||||
(same row height, font size, padding, hover/selection, empty state) rather than new.
|
||||
- Same action, same name, place and shortcut as elsewhere in the IDE.
|
||||
- Keyboard reachable, visible focus, focus returns sensibly; `aria-label` on icon buttons.
|
||||
- Every new string in `en.json` and `zh.json`; long translations don't break the layout.
|
||||
- Light and dark, default and narrow widths all look right.
|
||||
- The Impeccable design skills can help critique and polish; they read `DESIGN.md`,
|
||||
`PRODUCT.md` and `.impeccable/`.
|
||||
|
||||
A layout or navigation restructure needs a maintainer decision first (§ 1).
|
||||
|
||||
## 5. Description
|
||||
|
||||
Fill in `.github/pull_request_template.md`; keep it short and plain:
|
||||
|
||||
```markdown
|
||||
Closes #123
|
||||
|
||||
## What and why
|
||||
|
||||
<The change a user notices, and the root cause. 2–4 sentences.>
|
||||
|
||||
## How it was verified
|
||||
|
||||
- [x] Bug fix: `pnpm vitest run src/features/editor/folding.test.ts` — the new
|
||||
`keeps caret visible after fold` fails on main, passes here (12 passed)
|
||||
- [x] Visible UI: before / after (Islands Light, Islands Dark)
|
||||
<screenshots>
|
||||
- `pnpm typecheck`, `pnpm lint`, `pnpm e2e e2e/editor-folding.spec.ts` — all pass
|
||||
- Also affected: folding from the gutter and from ⌘- — both checked in the app
|
||||
|
||||
## Review focus
|
||||
|
||||
<Optional.>
|
||||
```
|
||||
|
||||
The `PR check` workflow labels the PR `needs-info` when **How it was verified** is empty, or when
|
||||
the PR changes UI files and the section has no screenshot or recording and doesn't say
|
||||
"No visible change".
|
||||
|
||||
## 6. Before you push
|
||||
|
||||
- Re-read the diff as the reviewer: anything unrelated, debug output, commented-out code,
|
||||
leftover TODOs?
|
||||
- Rebased on current `main`; checks re-run if the rebase changed anything they cover.
|
||||
- Open as draft while evidence is missing; mark ready once it's in.
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
name: verify
|
||||
description: Build, launch and drive the OpenIDEA desktop app through the Tauri MCP bridge to verify a change at runtime.
|
||||
---
|
||||
|
||||
# Verify OpenIDEA in the running app
|
||||
|
||||
## Launch
|
||||
|
||||
- Run the app from the worktree that holds the change: `pnpm tauri dev` in the background, logging
|
||||
into your task's scratch subdirectory. Use `pnpm dev:app` instead when your checks call
|
||||
`window.__TAURI__` from `execute_js`. The wrapper gives each worktree its own app identity, data,
|
||||
settings and Vite port, so other worktrees and the installed app don't interfere. If it reports a
|
||||
session already running for this worktree, reuse that one.
|
||||
- Once the app is up, `pnpm dev:status` lists this worktree's MCP bridges. Pass the reported
|
||||
`appIdentifier` (the port) on every `mcp__tauri__*` call. The MCP server is shared between
|
||||
sessions: never `driver_session stop` without an `appIdentifier`, and re-check `document.title` /
|
||||
`location.href` before acting if anything looks off.
|
||||
- Make sure the binary contains the change: a session already running for this worktree may be an
|
||||
older build. Restart it after Rust changes; frontend changes reload through Vite.
|
||||
- After the app restarts, `driver_session start` again for your port (a stale session says "Already connected").
|
||||
- If the `pnpm tauri dev` process exits while the app window stays open, Vite is gone and any webview
|
||||
reload shows an empty `#root`. Stop that app and start the session again.
|
||||
- Stop everything you started when done and nothing else; never use process-name kills.
|
||||
|
||||
## Driving
|
||||
|
||||
- `manage_window focus` before screenshots / timing-sensitive steps: a background window throttles timers
|
||||
(debounced LSP / VCS refreshes stall, `setTimeout` promises in `execute_js` time out) and native
|
||||
screenshots come back black.
|
||||
- Settings is a separate native window `settings-main`; pass `windowId`, focus it before screenshotting.
|
||||
- CodeMirror / xterm ignore MCP `type`. Focus the element, then `document.execCommand('insertText', false, text)`.
|
||||
For xterm Enter, dispatch a `keydown` (`key: 'Enter', keyCode: 13`) on `.xterm-helper-textarea`.
|
||||
- MCP clicks arrive with `event.detail === 0`; CodeMirror treats them as line-select clicks. Set the caret
|
||||
through the view instead: `document.querySelector('.cm-content').cmTile.view`.
|
||||
- MCP `text` strategy can resolve to a hidden node; prefer coordinates (CSS px = image px × 0.9) or CSS selectors.
|
||||
- CSS-module edits often trigger a full page reload in dev: dialogs close, Run sessions and terminal
|
||||
scrollback reset, and each reload spawns a fresh shell. Re-open what you were testing.
|
||||
|
||||
## Evidence
|
||||
|
||||
- For UI or interaction changes, capture `before.png` (on `main` or with the fix reverted) and
|
||||
`after.png` at the same state and window size, into your task's scratch subdirectory. Multi-step
|
||||
flows: a numbered series (`after-1.png`, `after-2.png`, ...). When colours, borders or icons
|
||||
change, take each in Islands Light and Islands Dark. The `pr` skill lists what evidence each
|
||||
kind of change needs.
|
||||
- Report the absolute paths; they go into the PR's **How it was verified** section and the triage
|
||||
acceptance entry. Never commit screenshots to the feature branch.
|
||||
|
||||
## Fixture
|
||||
|
||||
`fixtures/` has sample projects (go-app, rust-app, ts-app, kotlin-gradle, polyglot). Copy one into
|
||||
your scratch directory before editing it, and don't commit the IDE state it creates (`.openidea/`).
|
||||
|
||||
## Flows worth driving
|
||||
|
||||
⌘⇧O Goto File · ⌘⇧F Find in Files (preview scroll + highlight) · ⌘⇧A Find Action · editor edit/undo/autosave ·
|
||||
Terminal (Unicode, venv) · Commit view at the default narrow width · Problems · Run → Stop · Project view
|
||||
New / Delete (nested `a/b.txt` names) · ⌘, Settings search (+ Keymap filter) · Git Log on a repo without commits.
|
||||
Symlink
@@ -0,0 +1 @@
|
||||
../../.agents/skills/pr
|
||||
Symlink
@@ -0,0 +1 @@
|
||||
../../.agents/skills/verify
|
||||
@@ -11,3 +11,10 @@ package(=ide-clipboard) & (
|
||||
)
|
||||
'''
|
||||
test-group = "windows-clipboard"
|
||||
|
||||
# The Subversion tests run svn against throwaway servers: none should take minutes. A test
|
||||
# that hangs (a server left stopped) is ended after 5 minutes instead of waiting for svn's own
|
||||
# timeout.
|
||||
[[profile.default.overrides]]
|
||||
filter = 'package(=ide-svn) | (package(=ide-host) & (binary(=svn) | binary(=ij_svn_roots)))'
|
||||
slow-timeout = { period = "60s", terminate-after = 5 }
|
||||
Бінарний файл не відображається.
|
До Ширина: | Висота: | Розмір: 169 KiB Після Ширина: | Висота: | Розмір: 192 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
|
||||
|
||||
|
||||
@@ -150,8 +150,18 @@ jobs:
|
||||
- name: Linux deps
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
|
||||
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf subversion sqlite3)
|
||||
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
|
||||
# The Subversion tests run the real svn, svnadmin and svnserve (and sqlite3, to write a
|
||||
# working copy's database); with CI set they fail instead of skipping when these are
|
||||
# missing. Linux gets them with the deps above; macOS has sqlite3. Windows runners skip them.
|
||||
- name: Subversion (macOS)
|
||||
if: runner.os == 'macOS'
|
||||
run: command -v svnadmin >/dev/null || brew install subversion
|
||||
- name: Subversion version
|
||||
if: runner.os != 'Windows'
|
||||
shell: bash
|
||||
run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version
|
||||
# tauri-build checks that frontendDist exists.
|
||||
- run: pnpm install --frozen-lockfile && mkdir -p dist
|
||||
shell: bash
|
||||
@@ -360,6 +370,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
|
||||
|
||||
@@ -36,6 +36,7 @@ on:
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/core/cm/inlineBg.ts"
|
||||
- "src/editor/core/cm/localAppearance.ts"
|
||||
- "src/editor/core/cm/lineNumberOptions.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
- "src/editor/lsp/files.ts"
|
||||
@@ -110,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|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-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
name: PR check
|
||||
on:
|
||||
# pull_request_target so the check can label PRs from forks. It never checks out
|
||||
# or runs PR code: it only reads the PR title and description.
|
||||
# or runs PR code: it only reads the PR title, description and changed file names.
|
||||
pull_request_target:
|
||||
types: [opened, edited, reopened, ready_for_review]
|
||||
types: [opened, edited, reopened, ready_for_review, synchronize]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
@@ -34,6 +34,24 @@ jobs:
|
||||
|
||||
const { owner, repo } = context.repo;
|
||||
const issue_number = pr.number;
|
||||
|
||||
if (verified && verified[1].trim()) {
|
||||
const section = verified[1];
|
||||
const hasMedia =
|
||||
/!\[[^\]]*\]\(|<img\b|<video\b|github\.com\/user-attachments\/|https?:\/\/\S+\.(png|jpe?g|gif|webp|mp4|mov|webm)\b/i.test(section);
|
||||
const optedOut = /no visible change/i.test(section);
|
||||
if (!hasMedia && !optedOut) {
|
||||
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: issue_number, per_page: 100 });
|
||||
const ui = files
|
||||
.filter(f => f.status !== 'removed')
|
||||
.map(f => f.filename)
|
||||
.filter(name => /^src\/.*\.(tsx|css)$/.test(name) && !/\.(test|spec)\.tsx$/.test(name));
|
||||
if (ui.length) {
|
||||
const shown = ui.slice(0, 3).map(n => `\`${n}\``).join(', ') + (ui.length > 3 ? ', …' : '');
|
||||
problems.push(`This PR changes UI files (${shown}). Add before/after screenshots, or a recording for interactions, to **How it was verified**; if nothing users see changed, write "No visible change" and say what you checked.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
|
||||
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes(MARKER));
|
||||
const labeled = pr.labels.some(l => l.name === LABEL);
|
||||
|
||||
@@ -284,6 +284,8 @@ jobs:
|
||||
return;
|
||||
}
|
||||
// Bundle suffix → updater platform keys, as tauri-action names them.
|
||||
// Nightly builds skip RPM because RPM rejects `-` in SemVer prerelease versions.
|
||||
const nightly = tag.includes("-nightly.");
|
||||
const windows = (arch, msi, nsis) => [
|
||||
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
|
||||
[nsis, [`windows-${arch}-nsis`]],
|
||||
@@ -291,10 +293,10 @@ jobs:
|
||||
const kinds = [
|
||||
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
|
||||
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
|
||||
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
|
||||
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
|
||||
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
|
||||
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
|
||||
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
|
||||
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
|
||||
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
|
||||
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
|
||||
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
|
||||
|
||||
+6
-5
@@ -33,12 +33,13 @@ target/
|
||||
test-results/
|
||||
playwright-report/
|
||||
|
||||
# Local AI agent files
|
||||
AGENTS.md
|
||||
CLAUDE.md
|
||||
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
|
||||
CLAUDE.local.md
|
||||
.agents/
|
||||
.claude/
|
||||
.claude/*
|
||||
!.claude/skills/
|
||||
.claude/skills/*
|
||||
!.claude/skills/pr
|
||||
!.claude/skills/verify
|
||||
|
||||
# Local reference screenshots
|
||||
pycharm-screenshots/
|
||||
@@ -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.
|
||||
Створено
+249
-362
File diff suppressed because it is too large.
Load diff
+9
-1
@@ -2,7 +2,7 @@
|
||||
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"
|
||||
@@ -24,6 +24,7 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
|
||||
ide-lsp = { path = "crates/ide-lsp" }
|
||||
ide-dap = { path = "crates/ide-dap" }
|
||||
ide-vcs = { path = "crates/ide-vcs" }
|
||||
ide-svn = { path = "crates/ide-svn" }
|
||||
ide-github = { path = "crates/ide-github" }
|
||||
ide-terminal = { path = "crates/ide-terminal" }
|
||||
ide-run = { path = "crates/ide-run" }
|
||||
@@ -90,6 +91,7 @@ trash = "5"
|
||||
blake3 = "1"
|
||||
dunce = "1"
|
||||
dirs = "6"
|
||||
jiff = "0.2"
|
||||
memmap2 = "0.9"
|
||||
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
|
||||
flate2 = "1"
|
||||
@@ -99,6 +101,7 @@ tar = "0.4"
|
||||
grep-searcher = "0.1"
|
||||
grep-regex = "0.1"
|
||||
regex-syntax = "0.8"
|
||||
regex = "1"
|
||||
grep-matcher = "0.1"
|
||||
nucleo-matcher = "0.3"
|
||||
redb = "4"
|
||||
@@ -158,3 +161,8 @@ opt-level = 3
|
||||
panic = "unwind"
|
||||
# Keep the symbol table: crash reports and logged backtraces name functions.
|
||||
strip = "debuginfo"
|
||||
|
||||
# tauri-plugin-mcp-bridge 0.13.2 (debug-only E2E bridge) pins `tauri ~2.12`; this copy only widens
|
||||
# that requirement to 2.13. Drop it once a release supporting tauri 2.13 is published.
|
||||
[patch.crates-io]
|
||||
tauri-plugin-mcp-bridge = { path = "vendor/tauri-plugin-mcp-bridge" }
|
||||
@@ -6,6 +6,11 @@ contributors as part of the IntelliJ Platform (https://github.com/JetBrains/inte
|
||||
https://github.com/JetBrains/intellij-plugins), licensed under the Apache License 2.0.
|
||||
Copyright 2000-2026 JetBrains s.r.o. and contributors.
|
||||
|
||||
The Subversion tests (crates/ide-svn/tests/matrix.rs) take the tree-conflict scenarios,
|
||||
their names and file contents from IntelliJ's svn4idea TreeConflictData
|
||||
(plugins/svn4idea/testSource/org/jetbrains/idea/svn/), Apache License 2.0, Copyright
|
||||
2000-2026 JetBrains s.r.o. and contributors.
|
||||
|
||||
Some Simplified Chinese UI terms follow the Visual Studio Code Simplified Chinese
|
||||
language pack (https://github.com/microsoft/vscode-loc), Copyright (c) Microsoft
|
||||
Corporation, licensed under the MIT License.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
`src/ui/brands/*.svg` use the unmodified logo paths from
|
||||
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:xcode`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
|
||||
|
||||
## DuckDB symbol
|
||||
|
||||
|
||||
@@ -21,12 +21,13 @@ specta.workspace = true
|
||||
sqlx.workspace = true
|
||||
tokio.workspace = true
|
||||
toml.workspace = true
|
||||
toml_edit.workspace = true
|
||||
tracing.workspace = true
|
||||
parking_lot.workspace = true
|
||||
dunce.workspace = true
|
||||
jiff.workspace = true
|
||||
uuid.workspace = true
|
||||
tempfile.workspace = true
|
||||
which = "8"
|
||||
semver = "1"
|
||||
sha1 = "0.10"
|
||||
|
||||
|
||||
@@ -53,6 +53,24 @@ pub(crate) fn auth_required(code: i64, message: &str) -> bool {
|
||||
.any(|w| w == ["logged", "out"] || w == ["sign", "in"] || w == ["log", "in"] || w == ["login", "required"])
|
||||
}
|
||||
|
||||
/// Whether a failed request only means the agent hasn't finished starting up: OpenCode
|
||||
/// rejects session opens until the location's plugins and MCP servers finish activating
|
||||
/// (`ServiceUnavailableError`, "Location plugins did not finish activating") and reports
|
||||
/// an unavailable server as `ServerUnavailable`. Both arrive as internal errors naming
|
||||
/// the cause in `data.errorName`; retrying them once activation completes succeeds.
|
||||
pub(crate) fn service_warming_up(error: &RpcError) -> bool {
|
||||
let RpcError::Server { code: codes::INTERNAL_ERROR, message, data } = error else {
|
||||
return false;
|
||||
};
|
||||
if let Some(name) = data.as_ref().and_then(|d| d.get("errorName")).and_then(Value::as_str)
|
||||
&& matches!(name, "ServiceUnavailableError" | "ServerUnavailable")
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let lower = message.to_lowercase();
|
||||
lower.contains("did not finish activating") || lower.contains("opencode server is unavailable")
|
||||
}
|
||||
|
||||
/// The capabilities this client offers, in v1 form.
|
||||
fn client_capabilities() -> Value {
|
||||
json!({
|
||||
|
||||
@@ -52,6 +52,40 @@ fn auth_required_matches_authentication_words_and_sign_in_phrases() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_warming_up_matches_opencode_startup_races_only() {
|
||||
for (code, message, data, expected) in [
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure",
|
||||
Some(json!({"errorName": "ServiceUnavailableError"})),
|
||||
true,
|
||||
),
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: OpenCode server is unavailable",
|
||||
Some(json!({"errorName": "ServerUnavailable"})),
|
||||
true,
|
||||
),
|
||||
(codes::INTERNAL_ERROR, "Location plugins did not finish activating", None, true),
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure",
|
||||
Some(json!({"errorName": "SQLiteError"})),
|
||||
false,
|
||||
),
|
||||
(codes::INTERNAL_ERROR, "Internal error: Internal service failure", None, false),
|
||||
(codes::INTERNAL_ERROR, "boom", None, false),
|
||||
(AUTH_REQUIRED, "Authentication required", None, false),
|
||||
] {
|
||||
assert_eq!(
|
||||
service_warming_up(&RpcError::Server { code, message: message.into(), data: data.clone() }),
|
||||
expected,
|
||||
"code={code}, message={message:?}, data={data:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The messages of a fixture going `dir` (`in` or `out`).
|
||||
pub(crate) fn frames(fixture: &str, dir: &str) -> Vec<Value> {
|
||||
fixture
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -58,7 +58,9 @@ impl AgentManager {
|
||||
if spec.source != AgentSource::Builtin {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
}
|
||||
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
|
||||
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
|
||||
return Ok(AgentCliUpdateResult::Unmanaged);
|
||||
};
|
||||
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
|
||||
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
|
||||
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
|
||||
|
||||
@@ -131,7 +131,263 @@ fn is_bypass_mode(mode: &str) -> bool {
|
||||
let lower = mode.to_lowercase();
|
||||
let m: String =
|
||||
lower.rsplit(['#', '/']).next().unwrap_or_default().chars().filter(char::is_ascii_lowercase).collect();
|
||||
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous"
|
||||
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous" || m == "autopilot"
|
||||
}
|
||||
|
||||
fn upsert_choice(wanted: &mut Vec<crate::model::AgentConfigChoice>, id: &str, value: &str) {
|
||||
if let Some(existing) = wanted.iter_mut().find(|c| c.id == id) {
|
||||
existing.value = value.to_owned();
|
||||
} else {
|
||||
wanted.push(crate::model::AgentConfigChoice { id: id.to_owned(), value: value.to_owned() });
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
|
||||
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
|
||||
}
|
||||
|
||||
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
|
||||
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
|
||||
}
|
||||
|
||||
/// Applies an automation's permission policy (`mode`) to `config` and `wanted`, enforcing the
|
||||
/// user's interactive approval setting (`interactive`) as a strict ceiling. When `mode` is `None`
|
||||
/// (an in-session `/loop` or `Send Later` turn), clamps any bypass options down when `interactive`
|
||||
/// is [`ide_core::settings::NewTaskApprovals::Ask`].
|
||||
pub(crate) fn clamp_automation_permissions(
|
||||
provider: &str,
|
||||
mode: Option<crate::automation::AutomationPermissionMode>,
|
||||
interactive: ide_core::settings::NewTaskApprovals,
|
||||
config: &mut [AgentConfigOption],
|
||||
wanted: &mut Vec<crate::model::AgentConfigChoice>,
|
||||
) {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
|
||||
return;
|
||||
}
|
||||
|
||||
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
|
||||
|
||||
if !allow_bypass {
|
||||
// Strip any explicit bypass choices from `wanted` first so they cannot re-elevate later.
|
||||
wanted.retain(|c| match c.id.as_str() {
|
||||
"mode" => !is_bypass_mode(&c.value),
|
||||
"allow_all" | "permissions" => !matches!(c.value.to_ascii_lowercase().as_str(), "on" | "true"),
|
||||
"approval" | CURSOR_APPROVAL => !c.value.eq_ignore_ascii_case("bypass"),
|
||||
"approval_policy" => !c.value.eq_ignore_ascii_case("never"),
|
||||
_ => true,
|
||||
});
|
||||
ask_for_approvals(config);
|
||||
}
|
||||
|
||||
match provider {
|
||||
"claude" | "claude-acp" => {
|
||||
let cur_wanted = wanted_val(wanted, "mode");
|
||||
let target = if allow_bypass {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("default" | "plan" | "acceptEdits") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "bypassPermissions".to_owned(),
|
||||
}
|
||||
} else if interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::Assisted) {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("default" | "plan") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "acceptEdits".to_owned(),
|
||||
}
|
||||
} else {
|
||||
// Either Default mode or interactive policy is Ask (where interactive Claude starts in `default`).
|
||||
match cur_wanted.as_deref() {
|
||||
Some("plan") => "plan".to_owned(),
|
||||
_ => "default".to_owned(),
|
||||
}
|
||||
};
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
&& opt.values.iter().any(|v| v.value == target)
|
||||
{
|
||||
let id = opt.id.clone();
|
||||
opt.current = Some(target.clone());
|
||||
upsert_choice(wanted, &id, &target);
|
||||
} else if mode.is_some() || cur_wanted.is_some() {
|
||||
upsert_choice(wanted, "mode", &target);
|
||||
}
|
||||
}
|
||||
"codex" | "codex-acp" => {
|
||||
let cur_wanted = wanted_val(wanted, "mode");
|
||||
let target = if allow_bypass {
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "full-access".to_owned(),
|
||||
}
|
||||
} else if mode == Some(AutomationPermissionMode::Default) {
|
||||
"read-only".to_owned()
|
||||
} else if mode.is_some() {
|
||||
// Assisted, or AllowAll clamped by interactive Ask (`ask_for_approvals` maps full-access -> ask).
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only") => "read-only".to_owned(),
|
||||
_ => "ask".to_owned(),
|
||||
}
|
||||
} else {
|
||||
// Scheduled /loop or Send Later under interactive Ask: never full-access.
|
||||
match cur_wanted.as_deref() {
|
||||
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
|
||||
_ => "ask".to_owned(),
|
||||
}
|
||||
};
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
&& opt.values.iter().any(|v| v.value == target)
|
||||
{
|
||||
let id = opt.id.clone();
|
||||
opt.current = Some(target.clone());
|
||||
upsert_choice(wanted, &id, &target);
|
||||
} else if mode.is_some() || cur_wanted.is_some() {
|
||||
upsert_choice(wanted, "mode", &target);
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
if allow_bypass {
|
||||
if !matches!(wanted_val(wanted, "allow_all").as_deref(), Some("off" | "false")) {
|
||||
upsert_choice(wanted, "allow_all", "on");
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
|
||||
opt.current = Some("on".into());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
upsert_choice(wanted, "allow_all", "off");
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
|
||||
opt.current = Some("off".into());
|
||||
}
|
||||
let non_auto = match wanted_val(wanted, "mode").as_deref() {
|
||||
Some("plan") => "plan",
|
||||
_ => "agent",
|
||||
};
|
||||
if mode.is_some() || config.iter().any(|o| o.id == "mode" && o.current.as_deref() == Some("autopilot"))
|
||||
{
|
||||
upsert_choice(wanted, "mode", non_auto);
|
||||
}
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode")
|
||||
&& (mode.is_some() || opt.current.as_deref() == Some("autopilot"))
|
||||
&& opt.values.iter().any(|v| v.value == non_auto)
|
||||
{
|
||||
opt.current = Some(non_auto.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
"cursor" => {
|
||||
let target = if allow_bypass && wanted_val(wanted, CURSOR_APPROVAL).as_deref() != Some("ask") {
|
||||
"bypass"
|
||||
} else {
|
||||
"ask"
|
||||
};
|
||||
upsert_choice(wanted, CURSOR_APPROVAL, target);
|
||||
if let Some(opt) = config.iter_mut().find(|o| o.id == CURSOR_APPROVAL) {
|
||||
opt.current = Some(target.into());
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if allow_bypass {
|
||||
let user_chose_non_bypass = config.iter().any(|o| {
|
||||
is_approval_option(o)
|
||||
&& wanted.iter().any(|c| {
|
||||
c.id == o.id && o.category.as_deref().and_then(bypass_value).is_some_and(|b| !b(&c.value))
|
||||
})
|
||||
});
|
||||
if !user_chose_non_bypass {
|
||||
apply_bypass_approvals(config);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure every approval-bearing option in `config` has its enforced value mirrored in `wanted`
|
||||
// so `open_session` actively configures the live session even if the CLI's own config differs.
|
||||
for opt in config.iter().filter(|o| is_approval_option(o)) {
|
||||
if let Some(cur) = opt.current.as_deref() {
|
||||
upsert_choice(wanted, &opt.id, cur);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Verifies that the session's reported `config` options do not exceed the required automation
|
||||
/// permission ceiling (`min(mode, interactive)`). Returns `Err(reason)` if the provider remained
|
||||
/// in a more permissive mode than allowed.
|
||||
pub(crate) fn verify_automation_ceiling(
|
||||
provider: &str,
|
||||
mode: Option<crate::automation::AutomationPermissionMode>,
|
||||
interactive: ide_core::settings::NewTaskApprovals,
|
||||
config: &[AgentConfigOption],
|
||||
) -> Result<(), String> {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
|
||||
if !allow_bypass && bypass_approvals(config) {
|
||||
return Err("Agent did not confirm the required approval ceiling (session remained in bypass mode).".into());
|
||||
}
|
||||
|
||||
let cur_of = |id: &str| config.iter().find(|o| o.id == id).and_then(|o| o.current.as_deref());
|
||||
let mode_cur = config
|
||||
.iter()
|
||||
.find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
|
||||
.and_then(|o| o.current.as_deref());
|
||||
|
||||
if !allow_bypass {
|
||||
match provider {
|
||||
"claude" | "claude-acp" => {
|
||||
if let Some(cur) = mode_cur {
|
||||
let allowed = if interactive == NewTaskApprovals::Bypass
|
||||
&& mode == Some(AutomationPermissionMode::Assisted)
|
||||
{
|
||||
matches!(cur, "default" | "plan" | "acceptEdits")
|
||||
} else {
|
||||
matches!(cur, "default" | "plan")
|
||||
};
|
||||
if !allowed {
|
||||
return Err(format!(
|
||||
"Claude session remained in mode '{cur}', exceeding the required approval ceiling."
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
"codex" | "codex-acp" => {
|
||||
if let Some(cur) = mode_cur {
|
||||
let allowed = if mode == Some(AutomationPermissionMode::Default) {
|
||||
cur == "read-only"
|
||||
} else if mode.is_some() {
|
||||
matches!(cur, "read-only" | "ask")
|
||||
} else {
|
||||
matches!(cur, "read-only" | "ask" | "auto")
|
||||
};
|
||||
if !allowed {
|
||||
return Err(format!(
|
||||
"Codex session remained in mode '{cur}', exceeding the required approval ceiling."
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
"copilot" => {
|
||||
if let Some(cur) = cur_of("allow_all")
|
||||
&& matches!(cur.to_ascii_lowercase().as_str(), "on" | "true")
|
||||
{
|
||||
return Err("Copilot session kept allow_all enabled above the approval ceiling.".into());
|
||||
}
|
||||
if let Some(cur) = mode_cur
|
||||
&& cur.eq_ignore_ascii_case("autopilot")
|
||||
{
|
||||
return Err("Copilot session remained in autopilot mode above the approval ceiling.".into());
|
||||
}
|
||||
}
|
||||
"cursor" if cur_of(CURSOR_APPROVAL).is_some_and(|cur| cur.eq_ignore_ascii_case("bypass")) => {
|
||||
return Err("Cursor session remained in bypass mode above the approval ceiling.".into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
|
||||
@@ -669,6 +925,87 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_permissions_respect_interactive_approval_ceiling() {
|
||||
use crate::automation::AutomationPermissionMode;
|
||||
use crate::model::AgentConfigChoice;
|
||||
use ide_core::settings::NewTaskApprovals;
|
||||
|
||||
let claude_opts = || {
|
||||
options_of(&json!({"configOptions": [{
|
||||
"id": "mode", "category": "mode", "type": "select", "currentValue": "bypassPermissions",
|
||||
"defaultValue": "default",
|
||||
"options": [
|
||||
{"value": "default"}, {"value": "acceptEdits"}, {"value": "plan"}, {"value": "bypassPermissions"}
|
||||
]
|
||||
}]}))
|
||||
};
|
||||
|
||||
// Claude Assisted under interactive Bypass -> acceptEdits; under interactive Ask -> default!
|
||||
let mut c = claude_opts();
|
||||
let mut wanted = Vec::new();
|
||||
clamp_automation_permissions(
|
||||
"claude",
|
||||
Some(AutomationPermissionMode::Assisted),
|
||||
NewTaskApprovals::Bypass,
|
||||
&mut c,
|
||||
&mut wanted,
|
||||
);
|
||||
assert_eq!(c[0].current.as_deref(), Some("acceptEdits"));
|
||||
assert!(wanted.iter().any(|w| w.id == "mode" && w.value == "acceptEdits"));
|
||||
|
||||
let mut c_ask = claude_opts();
|
||||
let mut wanted_ask = vec![AgentConfigChoice { id: "mode".into(), value: "bypassPermissions".into() }];
|
||||
clamp_automation_permissions(
|
||||
"claude",
|
||||
Some(AutomationPermissionMode::AllowAll),
|
||||
NewTaskApprovals::Ask,
|
||||
&mut c_ask,
|
||||
&mut wanted_ask,
|
||||
);
|
||||
assert_eq!(c_ask[0].current.as_deref(), Some("default"));
|
||||
assert_eq!(wanted_ask, vec![AgentConfigChoice { id: "mode".into(), value: "default".into() }]);
|
||||
|
||||
// Copilot AllowAll under interactive Ask clamps allow_all -> off and autopilot -> agent.
|
||||
let mut copilot = options_of(&json!({"configOptions": [
|
||||
{"id": "mode", "category": "mode", "type": "select", "currentValue": "autopilot",
|
||||
"options": [{"value": "agent"}, {"value": "plan"}, {"value": "autopilot"}]},
|
||||
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "on",
|
||||
"options": [{"value": "off"}, {"value": "on"}]}
|
||||
]}));
|
||||
let mut copilot_wanted = vec![AgentConfigChoice { id: "allow_all".into(), value: "on".into() }];
|
||||
clamp_automation_permissions(
|
||||
"copilot",
|
||||
Some(AutomationPermissionMode::AllowAll),
|
||||
NewTaskApprovals::Ask,
|
||||
&mut copilot,
|
||||
&mut copilot_wanted,
|
||||
);
|
||||
assert_eq!(ids(&copilot), [("mode", Some("agent")), ("allow_all", Some("off"))]);
|
||||
assert!(!bypass_approvals(&copilot));
|
||||
|
||||
// Codex Default -> read-only, Assisted -> ask, AllowAll + Ask -> ask, AllowAll + Bypass -> full-access.
|
||||
let codex_opts = || {
|
||||
options_of(&json!({"configOptions": [{
|
||||
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
|
||||
"defaultValue": "ask",
|
||||
"options": [{"value": "read-only"}, {"value": "ask"}, {"value": "auto"}, {"value": "full-access"}]
|
||||
}]}))
|
||||
};
|
||||
for (perm, interactive, expected) in [
|
||||
(AutomationPermissionMode::Default, NewTaskApprovals::Bypass, "read-only"),
|
||||
(AutomationPermissionMode::Assisted, NewTaskApprovals::Bypass, "ask"),
|
||||
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Ask, "ask"),
|
||||
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Bypass, "full-access"),
|
||||
] {
|
||||
let mut opts = codex_opts();
|
||||
let mut w = Vec::new();
|
||||
clamp_automation_permissions("codex", Some(perm), interactive, &mut opts, &mut w);
|
||||
assert_eq!(opts[0].current.as_deref(), Some(expected), "{perm:?} + {interactive:?}");
|
||||
assert!(w.iter().any(|c| c.id == "mode" && c.value == expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_sources_in_updates_and_stored_tasks() {
|
||||
let update = json!({"availableCommands": [
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! ACP elicitation in form mode: the agent's restricted JSON Schema as form fields, and the
|
||||
//! user's answer as the `elicitation/create` response.
|
||||
|
||||
use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption};
|
||||
use crate::model::{
|
||||
AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption, AgentQuestion,
|
||||
AgentQuestionOption,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -10,6 +13,9 @@ use serde_json::{Map, Value, json};
|
||||
/// anything else cancels it.
|
||||
const DECLINE: &str = "decline";
|
||||
|
||||
/// What the question card sends for Skip.
|
||||
const SKIP: &str = "reject";
|
||||
|
||||
/// The form `elicitation/create` asks for; `Err` when it asks for something else.
|
||||
pub(crate) fn form_of(params: &Value) -> Result<AgentForm, String> {
|
||||
if params.get("mode").and_then(Value::as_str) != Some("form") {
|
||||
@@ -148,6 +154,97 @@ fn scalar(value: &Value) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The questions a form asks when it is an agent's question tool in form shape: every field
|
||||
/// a choice, each followed by its own text field for a typed answer, named after it
|
||||
/// (`question_0` + `question_0_custom` from claude-agent-acp's `AskUserQuestion`, `q0` +
|
||||
/// `q0__other` from OMP's `ask`). They are shown and answered as the agent's questions, one
|
||||
/// at a time like a native `AskUserQuestion` (#7359); [`answer_questions`] turns the answers
|
||||
/// back into the form's values. `None` for any other form.
|
||||
pub(crate) fn questions_of(form: &AgentForm, params: &Value, message: &str) -> Option<Vec<AgentQuestion>> {
|
||||
let choices = form.fields.len() / 2;
|
||||
if choices == 0 || form.fields.len() % 2 == 1 {
|
||||
return None;
|
||||
}
|
||||
let properties = params.pointer("/requestedSchema/properties");
|
||||
form.fields
|
||||
.chunks(2)
|
||||
.map(|pair| {
|
||||
let [choice, text] = pair else { return None };
|
||||
let asks = matches!(choice.kind, AgentFormFieldKind::Choice | AgentFormFieldKind::Choices)
|
||||
&& !choice.options.is_empty()
|
||||
&& text.kind == AgentFormFieldKind::Text
|
||||
&& text.name.len() > choice.name.len()
|
||||
&& text.name.starts_with(&choice.name);
|
||||
if !asks {
|
||||
return None;
|
||||
}
|
||||
let (title, description) = (choice.title.trim(), choice.description.trim());
|
||||
let (header, question) = if choices == 1 && !message.is_empty() {
|
||||
(if title == message || title == choice.name { "" } else { title }, message)
|
||||
} else if description.is_empty() {
|
||||
("", title)
|
||||
} else {
|
||||
(if title == choice.name { "" } else { title }, description)
|
||||
};
|
||||
let schema = properties.and_then(|p| p.get(&choice.name));
|
||||
let options = choice
|
||||
.options
|
||||
.iter()
|
||||
.map(|option| AgentQuestionOption {
|
||||
label: option.label.clone(),
|
||||
description: option.description.clone(),
|
||||
preview: schema.and_then(|s| option_preview(s, &option.value)),
|
||||
})
|
||||
.collect();
|
||||
Some(AgentQuestion {
|
||||
answer_key: Some(choice.name.clone()),
|
||||
header: header.to_owned(),
|
||||
question: question.to_owned(),
|
||||
multi_select: choice.kind == AgentFormFieldKind::Choices,
|
||||
options,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The preview claude-agent-acp forwards beside an option (`_meta["_claude/askUserQuestionOption"]`).
|
||||
fn option_preview(schema: &Value, value: &str) -> Option<String> {
|
||||
let listed = schema.get("oneOf").or_else(|| schema.get("anyOf")).or_else(|| schema.pointer("/items/anyOf"));
|
||||
listed?
|
||||
.as_array()?
|
||||
.iter()
|
||||
.find(|o| o.get("const").and_then(Value::as_str) == Some(value))?
|
||||
.pointer("/_meta/_claude~1askUserQuestionOption/preview")?
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// The form reply to the answers of [`questions_of`]'s questions (question key to the picked
|
||||
/// labels and the typed text): picked options as the choice's values, the text in the field
|
||||
/// beside it. The question card's Skip declines the form; nothing passes through.
|
||||
pub(crate) fn answer_questions(form: &AgentForm, reply: Option<&str>) -> Option<String> {
|
||||
let reply = reply?;
|
||||
if reply == SKIP {
|
||||
return Some(DECLINE.to_owned());
|
||||
}
|
||||
let Ok(answers) = serde_json::from_str::<Map<String, Value>>(reply) else { return Some(reply.to_owned()) };
|
||||
let mut values = Map::new();
|
||||
for pair in form.fields.chunks(2) {
|
||||
let [choice, text] = pair else { continue };
|
||||
let items = answers.get(&choice.name).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
|
||||
let (mut picked, mut typed) = (Vec::new(), Vec::new());
|
||||
for item in items {
|
||||
match choice.options.iter().find(|o| o.label == item) {
|
||||
Some(option) => picked.push(json!(option.value)),
|
||||
None => typed.push(item),
|
||||
}
|
||||
}
|
||||
values.insert(choice.name.clone(), Value::Array(picked));
|
||||
values.insert(text.name.clone(), json!([typed.join("\n")]));
|
||||
}
|
||||
Some(Value::Object(values).to_string())
|
||||
}
|
||||
|
||||
/// A form is submitted from its own card; this option only names a declined form.
|
||||
pub(crate) fn options() -> Vec<AgentPermissionOption> {
|
||||
vec![AgentPermissionOption { id: DECLINE.to_owned(), name: "Decline".to_owned(), kind: "reject_once".to_owned() }]
|
||||
@@ -295,6 +392,90 @@ mod tests {
|
||||
assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b");
|
||||
}
|
||||
|
||||
/// What claude-agent-acp sends for `AskUserQuestion` with two questions.
|
||||
fn claude_questions() -> Value {
|
||||
json!({
|
||||
"sessionId": "s", "mode": "form", "message": "Please answer the following questions.",
|
||||
"requestedSchema": { "type": "object", "properties": {
|
||||
"question_0": { "type": "string", "title": "Delivery", "description": "How should it ship?",
|
||||
"oneOf": [{ "const": "Util + table (Recommended)", "title": "Util + table (Recommended)",
|
||||
"description": "Tracks tasks",
|
||||
"_meta": { "_claude/askUserQuestionOption": { "preview": "```\nUtil\n```" } } },
|
||||
{ "const": "Util only", "title": "Util only" }] },
|
||||
"question_0_custom": { "type": "string", "title": "Other" },
|
||||
"question_1": { "type": "array", "title": "Targets", "description": "Who receives it?",
|
||||
"items": { "anyOf": [{ "const": "Members", "title": "Members" },
|
||||
{ "const": "Tags", "title": "Tags" }] } },
|
||||
"question_1_custom": { "type": "string", "title": "Other" }
|
||||
} }
|
||||
})
|
||||
}
|
||||
|
||||
fn in_order(params: &Value, names: &[&str]) -> AgentForm {
|
||||
let mut form = form_of(params).unwrap();
|
||||
form.fields.sort_by_key(|f| names.iter().position(|n| *n == f.name));
|
||||
form
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_question_tool_form_is_asked_as_questions() {
|
||||
let params = claude_questions();
|
||||
let form = in_order(¶ms, &["question_0", "question_0_custom", "question_1", "question_1_custom"]);
|
||||
let questions = questions_of(&form, ¶ms, "Please answer the following questions.").unwrap();
|
||||
let [delivery, targets] = questions.as_slice() else { panic!("{questions:?}") };
|
||||
assert_eq!(
|
||||
(
|
||||
delivery.answer_key.as_deref(),
|
||||
delivery.header.as_str(),
|
||||
delivery.question.as_str(),
|
||||
delivery.multi_select
|
||||
),
|
||||
(Some("question_0"), "Delivery", "How should it ship?", false)
|
||||
);
|
||||
assert_eq!(delivery.options[0].description, "Tracks tasks");
|
||||
assert_eq!(delivery.options[0].preview.as_deref(), Some("```\nUtil\n```"));
|
||||
assert_eq!(delivery.options[1].preview, None);
|
||||
assert_eq!((targets.question.as_str(), targets.multi_select), ("Who receives it?", true));
|
||||
|
||||
let reply = json!({ "question_0": ["Util only", "keep it small"], "question_1": ["Members", "Tags"] });
|
||||
let reply = answer_questions(&form, Some(&reply.to_string()));
|
||||
let (response, chosen) = answer(&form, reply.as_deref());
|
||||
assert_eq!(
|
||||
response,
|
||||
json!({ "action": "accept", "content": {
|
||||
"question_0": "Util only", "question_0_custom": "keep it small", "question_1": ["Members", "Tags"]
|
||||
} })
|
||||
);
|
||||
assert_eq!(chosen, "Delivery: Util only; Other: keep it small; Targets: Members, Tags");
|
||||
assert_eq!(answer_questions(&form, Some(SKIP)).as_deref(), Some(DECLINE));
|
||||
assert_eq!(answer_questions(&form, None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_question_reads_from_the_message() {
|
||||
let params = ask();
|
||||
let form = in_order(¶ms, &["q0", "q0__other"]);
|
||||
let questions = questions_of(&form, ¶ms, "Which database?").unwrap();
|
||||
assert_eq!((questions[0].header.as_str(), questions[0].question.as_str()), ("", "Which database?"));
|
||||
assert_eq!(questions[0].options[0].label, "Postgres");
|
||||
let reply = answer_questions(&form, Some(&json!({ "q0": ["SQLite"] }).to_string()));
|
||||
assert_eq!(answer(&form, reply.as_deref()).0, json!({ "action": "accept", "content": { "q0": "sqlite" } }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_forms_stay_forms() {
|
||||
let only_choices = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
|
||||
"size": { "type": "string", "enum": ["s", "l"] }, "env": { "type": "string", "enum": ["dev"] }
|
||||
} } }))
|
||||
.unwrap();
|
||||
assert_eq!(questions_of(&only_choices, &json!({}), "Pick"), None);
|
||||
let unrelated_text = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
|
||||
"size": { "type": "string", "enum": ["s", "l"] }, "note": { "type": "string" }
|
||||
} } }))
|
||||
.unwrap();
|
||||
assert_eq!(questions_of(&unrelated_text, &json!({}), "Pick"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declining_and_dismissing_send_no_content() {
|
||||
let form = form_of(&ask()).unwrap();
|
||||
|
||||
@@ -16,14 +16,19 @@ pub(crate) fn from_content(content: &Value) -> Option<AgentImage> {
|
||||
if let (Some(data), Some(mime)) = (str_of(content, "data"), str_of(content, "mimeType"))
|
||||
&& mime.starts_with("image/")
|
||||
{
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None });
|
||||
return Some(AgentImage { mime_type: mime.into(), data: data.into(), name: None, inline_number: None });
|
||||
}
|
||||
from_uri(str_of(content, "uri")?)
|
||||
}
|
||||
"resource" => {
|
||||
let resource = content.get("resource")?;
|
||||
let (data, mime) = (str_of(resource, "blob")?, str_of(resource, "mimeType")?);
|
||||
mime.starts_with("image/").then(|| AgentImage { mime_type: mime.into(), data: data.into(), name: None })
|
||||
mime.starts_with("image/").then(|| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
})
|
||||
}
|
||||
"resource_link" => {
|
||||
let uri = str_of(content, "uri")?;
|
||||
@@ -51,6 +56,7 @@ pub(crate) fn from_uri(uri: &str) -> Option<AgentImage> {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
});
|
||||
}
|
||||
uri.starts_with("file://").then(|| from_file(Path::new(&uri_path(uri))))?
|
||||
@@ -67,6 +73,7 @@ pub(crate) fn from_file(path: &Path) -> Option<AgentImage> {
|
||||
mime_type: mime.into(),
|
||||
data: base64::engine::general_purpose::STANDARD.encode(bytes),
|
||||
name: path.file_name().and_then(|n| n.to_str()).map(str::to_owned),
|
||||
inline_number: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+753
-102
File diff suppressed because it is too large.
Load diff
@@ -68,9 +68,25 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
|
||||
headers: cfg.headers.iter().map(|(k, v)| McpKeyValue { name: k.clone(), value: v.clone() }).collect(),
|
||||
agents: cfg.agents.clone(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Merges `projected` MCP servers from enabled agent plugins behind `configured` User and
|
||||
/// Workspace servers so standalone settings entries always take precedence on name clashes.
|
||||
pub fn merge_projected_servers(mut configured: Vec<McpServer>, projected: Vec<McpServer>) -> Vec<McpServer> {
|
||||
let existing: HashSet<String> = configured.iter().map(|s| s.name.clone()).collect();
|
||||
// Same-named servers from different bundles are distinct rows (ids are `plugin:<bundle>:<server>`).
|
||||
let mut seen_projected: HashSet<String> = HashSet::new();
|
||||
for srv in projected {
|
||||
if !existing.contains(&srv.name) && seen_projected.insert(srv.id.clone()) {
|
||||
configured.push(srv);
|
||||
}
|
||||
}
|
||||
configured
|
||||
}
|
||||
|
||||
fn normalize_provider(id: &str) -> &str {
|
||||
id.strip_suffix("-acp").unwrap_or(id)
|
||||
}
|
||||
@@ -399,13 +415,8 @@ pub fn apply_save_json(
|
||||
Ok(saved_names)
|
||||
}
|
||||
|
||||
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
|
||||
".github/plugin/plugin.json",
|
||||
".plugin/plugin.json",
|
||||
".claude-plugin/plugin.json",
|
||||
".cursor-plugin/plugin.json",
|
||||
"plugin.json",
|
||||
];
|
||||
const COPILOT_PLUGIN_MANIFESTS: &[&str] =
|
||||
&[".github/plugin/plugin.json", ".plugin/plugin.json", ".claude-plugin/plugin.json", "plugin.json"];
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
enum SourceFormat {
|
||||
@@ -1051,6 +1062,14 @@ fn extract_servers_from_root(root: &Value, fallback_name: Option<&str>) -> BTree
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn read_external_mcp_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
|
||||
read_external_file(path)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_mcp_value(root: &Value) -> Result<BTreeMap<String, AgentMcpServer>, String> {
|
||||
Ok(extract_servers_from_root(root, None))
|
||||
}
|
||||
|
||||
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return BTreeMap::new();
|
||||
@@ -1088,15 +1107,7 @@ pub async fn probe_stdio_server(server: &AgentMcpServer, cwd: &Path) -> McpProbe
|
||||
env.push((k.clone(), v.clone()));
|
||||
}
|
||||
}
|
||||
let search_path = env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
let program = ide_core::process::find_executable(raw_cmd, &search_path)
|
||||
.map(|p| p.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| raw_cmd.to_owned());
|
||||
let program = ide_jsonrpc::resolve_spawn_program(raw_cmd, &env).to_string_lossy().into_owned();
|
||||
|
||||
let stderr_lines = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
|
||||
let stderr_capture = stderr_lines.clone();
|
||||
@@ -1259,6 +1270,8 @@ mod tests {
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -453,6 +453,26 @@ pub fn discover_memories(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Age
|
||||
out
|
||||
}
|
||||
|
||||
/// Discovers all standalone memory entries across `workspaces` and `home`, then appends
|
||||
/// projected rule/context entries from enabled agent plugins (deduplicated by canonical path).
|
||||
pub fn discover_memories_with_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
projected: Vec<AgentMemoryEntry>,
|
||||
) -> Vec<AgentMemoryEntry> {
|
||||
let mut out = discover_memories(workspaces, home);
|
||||
let mut seen: HashSet<PathBuf> =
|
||||
out.iter().map(|e| dunce::canonicalize(&e.path.0).unwrap_or_else(|_| e.path.0.clone())).collect();
|
||||
for mut entry in projected {
|
||||
let canon = dunce::canonicalize(&entry.path.0).unwrap_or_else(|_| entry.path.0.clone());
|
||||
entry.path = canon.clone().into();
|
||||
if seen.insert(canon) {
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
|
||||
/// against `policy` and optional per-session `session_overrides`.
|
||||
pub fn resolve_catalog(
|
||||
@@ -1412,6 +1432,8 @@ fn parse_cursor_mdc(path: &Path, rel: &str) -> Option<AgentMemoryEntry> {
|
||||
writable: false,
|
||||
valid: true,
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1482,6 +1504,8 @@ fn parse_entry(
|
||||
writable,
|
||||
valid: true,
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ pub enum InterruptionReason {
|
||||
BackendStop,
|
||||
UnexpectedExit,
|
||||
NetworkTimeout,
|
||||
CursorCapacity,
|
||||
}
|
||||
|
||||
impl From<AgentShutdownReason> for InterruptionReason {
|
||||
@@ -199,6 +200,10 @@ pub struct AgentTask {
|
||||
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recovery_window_mins: Option<u32>,
|
||||
/// Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`].
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -427,6 +432,9 @@ pub struct AgentImage {
|
||||
/// Base64, without a `data:` prefix.
|
||||
pub data: String,
|
||||
pub name: Option<String>,
|
||||
/// The `[Image #n]` label in the prompt text for an inline attachment.
|
||||
#[specta(optional)]
|
||||
pub inline_number: Option<u32>,
|
||||
}
|
||||
|
||||
impl AgentImage {
|
||||
@@ -454,11 +462,29 @@ pub struct AgentPrompt {
|
||||
pub images: Vec<AgentImage>,
|
||||
}
|
||||
|
||||
/// Provenance carried with a scheduled turn (`SameTask`, `Send Later`, or `/loop`), including
|
||||
/// while queued behind a busy turn, so trust and approval ceilings are re-checked at dispatch.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ScheduledTurnMeta {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub permissions: Option<crate::automation::AutomationPermissionMode>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub extra_choices: Vec<AgentConfigChoice>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub automation_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub session_schedule_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentQueued {
|
||||
pub id: String,
|
||||
pub prompt: AgentPrompt,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(skip)]
|
||||
pub scheduled: Option<ScheduledTurnMeta>,
|
||||
}
|
||||
|
||||
/// A setting chosen for a new task, by [`AgentConfigOption::id`].
|
||||
@@ -616,6 +642,9 @@ pub enum AgentEntry {
|
||||
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
|
||||
#[serde(default)]
|
||||
recovery: Option<InterruptionReason>,
|
||||
/// One-based automatic retry number for this continuation.
|
||||
#[serde(default)]
|
||||
retry_attempt: Option<u32>,
|
||||
},
|
||||
Agent {
|
||||
text: String,
|
||||
@@ -920,7 +949,7 @@ pub struct AgentModelCatalog {
|
||||
}
|
||||
|
||||
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
|
||||
#[derive(Clone, Debug, Serialize, Type)]
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
pub enum AgentEvent {
|
||||
/// A task was created or its metadata changed.
|
||||
@@ -1018,6 +1047,14 @@ pub struct McpServer {
|
||||
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
|
||||
#[serde(default)]
|
||||
pub unapproved: bool,
|
||||
/// Parent agent plugin ID when this server is live-projected from an enabled agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// Payload for creating or updating a user or workspace MCP server.
|
||||
@@ -1051,8 +1088,8 @@ fn default_true() -> bool {
|
||||
}
|
||||
|
||||
pub use ide_core::settings::{
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentProviderMemoryPolicy, AgentSkillMode,
|
||||
AgentSkillPolicy, AutoMemoryMode,
|
||||
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
|
||||
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
|
||||
};
|
||||
|
||||
/// Kind of discovered agent memory entry.
|
||||
@@ -1165,6 +1202,14 @@ pub struct AgentMemoryEntry {
|
||||
pub valid: bool,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
/// Parent agent plugin ID when this rule/instruction is live-projected from an enabled agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
|
||||
@@ -1337,6 +1382,14 @@ pub struct AgentSkill {
|
||||
pub valid: bool,
|
||||
/// What validation found (`name` mismatch, missing or over-long description…).
|
||||
pub warnings: Vec<String>,
|
||||
/// Parent agent plugin ID when this skill comes from an agent plugin bundle.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_id: Option<String>,
|
||||
/// Display name of the parent agent plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub plugin_name: Option<String>,
|
||||
}
|
||||
|
||||
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
|
||||
@@ -1398,6 +1451,371 @@ pub struct McpDiscoveredServer {
|
||||
pub header_keys: Vec<String>,
|
||||
}
|
||||
|
||||
/// Which workspace, user, or CLI store an agent plugin bundle was discovered in.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginSource {
|
||||
/// `~/.copilot/installed-plugins/{<marketplace>,_direct}/*`.
|
||||
#[default]
|
||||
CopilotUser,
|
||||
/// `~/.claude/plugins/installed_plugins.json` & `~/.claude/plugins/cache/*`.
|
||||
ClaudeUser,
|
||||
/// `~/.codex/plugins/cache/*`.
|
||||
CodexUser,
|
||||
/// `~/.gemini/extensions/*`.
|
||||
GeminiUser,
|
||||
}
|
||||
|
||||
/// Manifest format(s) recognized inside an agent plugin directory.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginFormat {
|
||||
/// Vendor-neutral Agent Plugins 1.0 / 1.1 (`plugin.json` with `$schema`).
|
||||
#[default]
|
||||
AgentPluginsV1,
|
||||
/// `.openidea/plugin.json`.
|
||||
OpenIdea,
|
||||
/// `.claude-plugin/plugin.json`.
|
||||
Claude,
|
||||
/// `.plugin/plugin.json`, `.github/plugin/plugin.json`, or legacy root `plugin.json`.
|
||||
Copilot,
|
||||
/// `.codex-plugin/plugin.json`.
|
||||
Codex,
|
||||
/// `gemini-extension.json`.
|
||||
GeminiExtension,
|
||||
}
|
||||
|
||||
/// Which policy layer decided an [`AgentPluginState::enabled`] status.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginOrigin {
|
||||
/// Native harness configuration owns the enabled state.
|
||||
#[default]
|
||||
None,
|
||||
/// Locked `Off` because the workspace is untrusted.
|
||||
Trust,
|
||||
/// Locked `Off` until executable capabilities (stdio MCP / lifecycle hooks) are approved.
|
||||
Consent,
|
||||
}
|
||||
|
||||
/// Data type of a plugin `userConfig` / `variables` / `settings` option.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AgentPluginConfigFieldKind {
|
||||
#[default]
|
||||
String,
|
||||
Number,
|
||||
Boolean,
|
||||
Secret,
|
||||
}
|
||||
|
||||
/// One configurable option declared by an agent plugin (`userConfig`, `variables`, or Gemini `settings`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginConfigField {
|
||||
pub key: String,
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
pub kind: AgentPluginConfigFieldKind,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub default_value: Option<String>,
|
||||
#[serde(default)]
|
||||
pub required: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub env_var: Option<String>,
|
||||
/// Current non-sensitive value (always empty when `kind == Secret`).
|
||||
#[serde(default)]
|
||||
pub value: String,
|
||||
/// True when a secret is stored in OS Keychain for this field.
|
||||
#[serde(default)]
|
||||
pub has_secret: bool,
|
||||
}
|
||||
|
||||
/// Summary of components and executable capabilities bundled inside an agent plugin.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginCapabilities {
|
||||
pub skill_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub skill_names: Vec<String>,
|
||||
pub mcp_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub mcp_names: Vec<String>,
|
||||
pub rule_count: u32,
|
||||
pub subagent_count: u32,
|
||||
pub command_count: u32,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub hook_files: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub stdio_commands: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub has_lsp: bool,
|
||||
#[serde(default)]
|
||||
pub has_canvas_or_app: bool,
|
||||
/// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub native_harnesses: Vec<String>,
|
||||
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub capability_hash: Option<String>,
|
||||
#[serde(default)]
|
||||
pub requires_consent: bool,
|
||||
}
|
||||
|
||||
/// One discovered agent plugin bundle on disk (or built-in).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPlugin {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub author: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub homepage: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repository: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub license: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
pub source: AgentPluginSource,
|
||||
/// Scope this bundle is installed in. Native plugin folders and enablement config are
|
||||
/// resolved relative to this scope.
|
||||
pub scope: McpScope,
|
||||
/// Workspace whose native configuration owns this row's enablement (workspace scope only).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub workspace_root: Option<IpcPath>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub also_in: Vec<AgentPluginSource>,
|
||||
pub formats: Vec<AgentPluginFormat>,
|
||||
pub root_path: IpcPath,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub manifest_path: Option<IpcPath>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub readme_path: Option<IpcPath>,
|
||||
pub default_enabled: bool,
|
||||
pub approx_tokens: u32,
|
||||
pub capabilities: AgentPluginCapabilities,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub config_fields: Vec<AgentPluginConfigField>,
|
||||
pub valid: bool,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Resolved agent plugin state paired with its policy origin and consent status.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginState {
|
||||
pub plugin: AgentPlugin,
|
||||
pub enabled: bool,
|
||||
pub origin: AgentPluginOrigin,
|
||||
/// True when executable stdio MCP / hook capabilities require user approval before enabling.
|
||||
pub consent_required: bool,
|
||||
}
|
||||
|
||||
/// Summary of a configured or repository-discovered plugin marketplace.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceInfo {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub source: String,
|
||||
pub scope: McpScope,
|
||||
/// True when discovered from a harness-native marketplace/configuration file.
|
||||
pub discovered: bool,
|
||||
}
|
||||
|
||||
/// Full catalog returned to Settings › Agents › Plugins.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginCatalog {
|
||||
pub plugins: Vec<AgentPluginState>,
|
||||
pub marketplaces: Vec<AgentMarketplaceInfo>,
|
||||
pub projected_skills: u32,
|
||||
pub projected_mcp_servers: u32,
|
||||
pub projected_rules: u32,
|
||||
}
|
||||
|
||||
/// One installable plugin entry listed inside a marketplace or repository.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceCandidate {
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub author: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
|
||||
pub source_spec: String,
|
||||
pub subpath: String,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub keywords: Vec<String>,
|
||||
pub already_installed_user: bool,
|
||||
pub already_installed_workspace: bool,
|
||||
}
|
||||
|
||||
/// Result of browsing a marketplace (`owner/repo`, local marketplace path, or direct plugin repo).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentMarketplaceBrowseResult {
|
||||
pub source: String,
|
||||
pub marketplace_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
pub candidates: Vec<AgentMarketplaceCandidate>,
|
||||
}
|
||||
|
||||
/// Whether a previewed plugin can be installed for one harness, and where it is already installed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginInstallTarget {
|
||||
pub harness: String,
|
||||
pub supported: bool,
|
||||
/// Why the harness cannot install this plugin.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub reason: Option<String>,
|
||||
/// Whether this harness can enable the plugin for just one workspace.
|
||||
pub workspace_supported: bool,
|
||||
/// This harness already records the plugin for the user / for the current workspace.
|
||||
pub installed_user: bool,
|
||||
pub installed_workspace: bool,
|
||||
/// The harness store already holds this plugin version's folder, so installing replaces it.
|
||||
pub overwrite_required: bool,
|
||||
}
|
||||
|
||||
/// Security and capability preview of an agent plugin bundle before installation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AgentPluginPreview {
|
||||
/// `"github"` or `"local"`.
|
||||
pub source_kind: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
/// Pinned commit SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub commit_sha: Option<String>,
|
||||
#[serde(default)]
|
||||
pub subpath: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub local_path: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub marketplace_source: Option<String>,
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub version: Option<String>,
|
||||
pub description: String,
|
||||
pub formats: Vec<AgentPluginFormat>,
|
||||
pub capabilities: AgentPluginCapabilities,
|
||||
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
|
||||
pub scan_warnings: Vec<crate::skill_installer::SkillScanWarning>,
|
||||
/// Per-harness install eligibility and existing installs for this plugin and marketplace.
|
||||
pub targets: Vec<AgentPluginInstallTarget>,
|
||||
}
|
||||
|
||||
/// Request payload to install a previewed agent plugin into a selected harness's native plugin directory.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InstallAgentPluginRequest {
|
||||
/// `"github"` or `"local"`.
|
||||
pub source_kind: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub owner: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub repo: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub git_ref: Option<String>,
|
||||
/// Pinned root tree SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub tree_sha: Option<String>,
|
||||
/// Pinned commit SHA from preview when `source_kind == "github"`.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub commit_sha: Option<String>,
|
||||
#[serde(default)]
|
||||
pub subpath: String,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub local_path: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub marketplace: Option<String>,
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub marketplace_source: Option<String>,
|
||||
pub scope: McpScope,
|
||||
/// Native harness the plugin is installed for (`claude`, `copilot`, `codex`, or `gemini`).
|
||||
pub harness: String,
|
||||
#[serde(default)]
|
||||
pub approve_capabilities: bool,
|
||||
/// The preview's `capabilityHash` the user approved; the install is refused if the installed
|
||||
/// folder resolves to different executable capabilities.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub approved_capability_hash: Option<String>,
|
||||
#[serde(default)]
|
||||
pub confirm_warnings: bool,
|
||||
#[serde(default)]
|
||||
pub overwrite: bool,
|
||||
}
|
||||
|
||||
/// Selection of one server from an external MCP configuration source to import.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -1484,3 +1484,34 @@ async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env()
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
|
||||
let cli = replay_cli(load_fixture("simple"));
|
||||
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
|
||||
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
|
||||
let h =
|
||||
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
|
||||
let params = json!({
|
||||
"cwd": h.cwd,
|
||||
"mcpServers": [],
|
||||
"_meta": {
|
||||
"openidea": {
|
||||
"memory": {
|
||||
"claudeInstructionFiles": "claude-md-and-agents-md"
|
||||
},
|
||||
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
|
||||
}
|
||||
}
|
||||
});
|
||||
h.request("session/new", params).await.unwrap();
|
||||
let args = cli.launched.lock()[0].clone();
|
||||
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
|
||||
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
|
||||
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
|
||||
assert_eq!(
|
||||
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
|
||||
"claude-md-and-agents-md"
|
||||
);
|
||||
assert!(parsed["pluginConfigs"]["azure"].is_null());
|
||||
}
|
||||
@@ -553,7 +553,12 @@ fn image_content(image: &crate::model::AgentImage) -> Value {
|
||||
/// A generated image: inline (base64 PNG) or, when codex saved it, the file.
|
||||
fn generated_image(item: &Value) -> Option<crate::model::AgentImage> {
|
||||
if let Some(data) = item.get("result").and_then(Value::as_str).filter(|d| !d.is_empty()) {
|
||||
let image = crate::model::AgentImage { mime_type: "image/png".into(), data: data.into(), name: None };
|
||||
let image = crate::model::AgentImage {
|
||||
mime_type: "image/png".into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
};
|
||||
return Some(crate::model::AgentImage { mime_type: image.media_type().into(), ..image });
|
||||
}
|
||||
crate::images::from_file(std::path::Path::new(item.get("savedPath")?.as_str()?))
|
||||
|
||||
@@ -1372,6 +1372,10 @@ fn build_prompt_payload(session_id: &str, blocks: &[Value]) -> (String, Vec<Valu
|
||||
{
|
||||
let path_str = saved.to_string_lossy().into_owned();
|
||||
let name = saved.file_name().and_then(|n| n.to_str()).unwrap_or("image").to_owned();
|
||||
// Copilot takes one text prompt and a separate attachments array.
|
||||
if let Some(number) = block.pointer("/_meta/openideaImageNumber").and_then(Value::as_u64) {
|
||||
text_parts.push(format!("[Image #{number}: {name}]"));
|
||||
}
|
||||
attachments.push(json!({ "type": "file", "path": path_str, "displayName": name }));
|
||||
temp_files.push(saved);
|
||||
}
|
||||
|
||||
@@ -25,11 +25,7 @@ use std::sync::Arc;
|
||||
/// A path, or a name not found on `PATH`, is used as it is; a single match returns its
|
||||
/// resolved path so Windows `PATHEXT` shims (`claude.cmd`, `codex.cmd`) start.
|
||||
pub(crate) fn newest_install(command: &str) -> String {
|
||||
let path = ide_core::process::host_var_os("PATH")
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| *k == "PATH").map(|(_, v)| v.to_owned()))
|
||||
.unwrap_or_default();
|
||||
// Windows: read afresh, so a tool the user installed since the IDE started is found too.
|
||||
newest_install_in(command, &ide_core::process::with_user_path(&path))
|
||||
newest_install_in(command, &ide_core::tool_path::search_path())
|
||||
}
|
||||
|
||||
fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -114,7 +114,7 @@ impl ProviderSpec {
|
||||
if !program.is_absolute() {
|
||||
return self.login_hint.clone();
|
||||
}
|
||||
let search = ide_core::process::host_var_os("PATH").unwrap_or_default();
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let builtin = builtin_spec(&self.id);
|
||||
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
|
||||
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
|
||||
@@ -623,7 +623,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
installed: installed_with_env(&spec.command, &spec.env),
|
||||
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(),
|
||||
@@ -1057,19 +1057,23 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
|
||||
specs
|
||||
}
|
||||
|
||||
/// Whether `command` resolves to an executable (a path, or a name on `PATH`).
|
||||
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn installed(command: &str) -> bool {
|
||||
installed_with_env(command, &[])
|
||||
}
|
||||
|
||||
pub(crate) fn installed_with_env(command: &str, env: &[(String, String)]) -> bool {
|
||||
let p = Path::new(command);
|
||||
if p.components().count() > 1 {
|
||||
if p.components().count() > 1 || p.is_absolute() {
|
||||
return is_executable(p);
|
||||
}
|
||||
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[] };
|
||||
std::env::var_os("PATH").is_some_and(|path| {
|
||||
std::env::split_paths(&path).any(|dir| {
|
||||
let c = dir.join(command);
|
||||
is_executable(&c) || exts.iter().any(|e| is_executable(&c.with_extension(e)))
|
||||
})
|
||||
})
|
||||
if let Some((_, path)) = env.iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
&& ide_core::process::find_executable(command, std::ffi::OsStr::new(path)).is_some()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
|
||||
}
|
||||
|
||||
fn is_executable(p: &Path) -> bool {
|
||||
@@ -1326,6 +1330,22 @@ mod tests {
|
||||
assert!(installed("sh"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_with_env_resolves_executables_on_provider_path() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let name = if cfg!(windows) { "fake-agent.cmd" } else { "fake-agent" };
|
||||
let exe = dir.path().join(name);
|
||||
std::fs::write(&exe, "").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert!(!installed("fake-agent"));
|
||||
let env = vec![("PATH".to_owned(), dir.path().to_string_lossy().into_owned())];
|
||||
assert!(installed_with_env("fake-agent", &env));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_builtin_env_writes_and_clears_the_environment() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -320,7 +320,7 @@ fn is_builtin(id: &str) -> bool {
|
||||
}
|
||||
|
||||
fn on_path(command: &str) -> bool {
|
||||
which::which(command).is_ok()
|
||||
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
|
||||
}
|
||||
|
||||
/// `1.10.0` > `1.9.2`; a release is newer than its pre-releases.
|
||||
@@ -708,7 +708,8 @@ fn install_npm(
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
let npm = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path())
|
||||
.ok_or_else(|| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
@@ -789,7 +790,8 @@ fn install_uv(
|
||||
_ => format!("{name}=={}", entry.version),
|
||||
};
|
||||
check_spec(&spec)?;
|
||||
let uv = which::which("uv").map_err(|_| IdeError::unavailable(format!("uv is required to install {name}")))?;
|
||||
let uv = ide_core::process::find_executable("uv", &ide_core::tool_path::search_path())
|
||||
.ok_or_else(|| IdeError::unavailable(format!("uv is required to install {name}")))?;
|
||||
let bin = dir.join("bin");
|
||||
let mut cmd = Command::new(uv);
|
||||
cmd.args(["tool", "install", "--force"])
|
||||
|
||||
@@ -185,22 +185,7 @@ pub(crate) fn recorder(out: PathBuf) -> Connector {
|
||||
let file = Arc::new(Mutex::new(String::new()));
|
||||
let connections = Arc::new(Mutex::new(0u32));
|
||||
Arc::new(move |spec, cwd, client, on_stderr| {
|
||||
let program = {
|
||||
let path = Path::new(&spec.command);
|
||||
if path.components().count() > 1 || path.is_absolute() {
|
||||
path.to_path_buf()
|
||||
} else {
|
||||
let search = spec
|
||||
.env
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
|
||||
.map(|(_, v)| std::ffi::OsString::from(v))
|
||||
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"))
|
||||
.unwrap_or_default();
|
||||
ide_core::process::find_executable(&spec.command, &search).unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
};
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env);
|
||||
let mut cmd = tokio::process::Command::new(&program);
|
||||
ide_core::process::prepare(cmd.as_std_mut());
|
||||
let mut child = cmd
|
||||
|
||||
@@ -163,6 +163,15 @@ pub struct RepoRef<'a> {
|
||||
|
||||
pub trait SkillSourceFetcher: Send + Sync {
|
||||
fn default_branch(&self, owner: &str, repo: &str, cancel: &CancellationToken) -> IdeResult<String>;
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String>;
|
||||
/// The root tree SHA recorded in commit `commit_sha`.
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
commit_sha: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String>;
|
||||
fn git_tree(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<GitTree>;
|
||||
fn read_blob(
|
||||
&self,
|
||||
@@ -238,6 +247,63 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
|
||||
.map_err(|e| IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid Git tree: {e}")))
|
||||
}
|
||||
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct CommitMeta {
|
||||
sha: String,
|
||||
}
|
||||
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
validate_git_ref(git_ref)?;
|
||||
let encoded_ref = encode_url_segment(git_ref);
|
||||
let url = format!("https://api.github.com/repos/{owner}/{repo}/commits/{encoded_ref}");
|
||||
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
|
||||
let meta: CommitMeta = serde_json::from_str(&body).map_err(|e| {
|
||||
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid GitHub commit: {e}"))
|
||||
})?;
|
||||
if !is_git_object_id(&meta.sha) {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Protocol,
|
||||
format!("{owner}/{repo}@{git_ref}: invalid GitHub commit SHA"),
|
||||
));
|
||||
}
|
||||
Ok(meta.sha)
|
||||
}
|
||||
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
owner: &str,
|
||||
repo: &str,
|
||||
commit_sha: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct TreeRef {
|
||||
sha: String,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct GitCommit {
|
||||
tree: TreeRef,
|
||||
}
|
||||
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
if !is_git_object_id(commit_sha) {
|
||||
return Err(IdeError::invalid("Invalid commit SHA"));
|
||||
}
|
||||
let url = format!("https://api.github.com/repos/{owner}/{repo}/git/commits/{commit_sha}");
|
||||
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
|
||||
let commit: GitCommit = serde_json::from_str(&body).map_err(|e| {
|
||||
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid Git commit: {e}"))
|
||||
})?;
|
||||
if !is_git_object_id(&commit.tree.sha) {
|
||||
return Err(IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid tree SHA")));
|
||||
}
|
||||
Ok(commit.tree.sha)
|
||||
}
|
||||
|
||||
fn read_blob(
|
||||
&self,
|
||||
target: RepoRef<'_>,
|
||||
@@ -616,6 +682,17 @@ fn sanitize_repo_as_skill_name(repo: &str) -> String {
|
||||
out.trim_matches('-').to_owned()
|
||||
}
|
||||
|
||||
pub(crate) struct FetchedSubtree {
|
||||
pub tree_sha: String,
|
||||
pub normalized_subpath: String,
|
||||
pub files: Vec<RemoteSkillFile>,
|
||||
pub scan_warnings: Vec<SkillScanWarning>,
|
||||
/// `(relative_path, bytes, executable)` for safe non-symlink files to write on disk.
|
||||
pub regular_files: Vec<(PathBuf, Vec<u8>, bool)>,
|
||||
/// `(relative_path, relative_target)` for safe internal symlinks.
|
||||
pub in_root_symlinks: Vec<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
struct PreparedSkillBundle {
|
||||
tree_sha: String,
|
||||
skill_name: String,
|
||||
@@ -629,14 +706,19 @@ struct PreparedSkillBundle {
|
||||
in_root_symlinks: Vec<(PathBuf, PathBuf)>,
|
||||
}
|
||||
|
||||
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
|
||||
fn fetch_and_scan_bundle(
|
||||
/// Fetches `target`'s tree (or exactly `pinned_tree_sha` when set) and scans `subpath` with hardened
|
||||
/// symlink-graph, executable-script, and hidden-Unicode checks.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn fetch_and_scan_subtree(
|
||||
fetcher: &dyn SkillSourceFetcher,
|
||||
target: RepoRef<'_>,
|
||||
subpath: &str,
|
||||
pinned_tree_sha: Option<&str>,
|
||||
max_files: usize,
|
||||
max_subtree_bytes: u64,
|
||||
noun: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PreparedSkillBundle> {
|
||||
) -> IdeResult<FetchedSubtree> {
|
||||
let RepoRef { owner, repo, git_ref } = target;
|
||||
validate_repo_coord(owner, "owner")?;
|
||||
validate_repo_coord(repo, "repository")?;
|
||||
@@ -646,9 +728,8 @@ fn fetch_and_scan_bundle(
|
||||
let tree = match pinned_tree_sha {
|
||||
Some(sha) => {
|
||||
if !is_git_object_id(sha) {
|
||||
return Err(IdeError::invalid("Preview the skill again before installing it"));
|
||||
return Err(IdeError::invalid(format!("Preview the {noun} again before installing it")));
|
||||
}
|
||||
// The Git trees API accepts a tree SHA in place of a ref.
|
||||
let tree = fetcher.git_tree(RepoRef { owner, repo, git_ref: sha }, cancel)?;
|
||||
if !tree.sha.eq_ignore_ascii_case(sha) {
|
||||
return Err(IdeError::new(
|
||||
@@ -660,6 +741,14 @@ fn fetch_and_scan_bundle(
|
||||
}
|
||||
None => fetcher.git_tree(target, cancel)?,
|
||||
};
|
||||
if tree.truncated {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::Protocol,
|
||||
format!(
|
||||
"{owner}/{repo}@{git_ref}: GitHub returned a truncated file listing; the {noun} cannot be verified"
|
||||
),
|
||||
));
|
||||
}
|
||||
let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") };
|
||||
|
||||
let subtree_entries: Vec<&GitTreeEntry> = tree
|
||||
@@ -672,27 +761,32 @@ fn fetch_and_scan_bundle(
|
||||
|
||||
if subtree_entries.is_empty() {
|
||||
return Err(IdeError::not_found(format!(
|
||||
"Skill path {:?} was not found in {owner}/{repo}@{git_ref}",
|
||||
"{} path {:?} was not found in {owner}/{repo}@{git_ref}",
|
||||
capitalize(noun),
|
||||
normalized_subpath
|
||||
)));
|
||||
}
|
||||
if subtree_entries.len() > MAX_SKILL_FILES {
|
||||
if subtree_entries.len() > max_files {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Skill exceeds maximum of {MAX_SKILL_FILES} files ({} found)",
|
||||
"{} exceeds maximum of {max_files} files ({} found)",
|
||||
capitalize(noun),
|
||||
subtree_entries.len()
|
||||
)));
|
||||
}
|
||||
|
||||
let declared_total: u64 = subtree_entries.iter().map(|e| e.size.unwrap_or(0)).sum();
|
||||
if declared_total > MAX_SKILL_SUBTREE_BYTES {
|
||||
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
|
||||
if declared_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
}
|
||||
|
||||
let mut files = Vec::with_capacity(subtree_entries.len());
|
||||
let mut scan_warnings = Vec::new();
|
||||
let mut regular_files = Vec::new();
|
||||
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
|
||||
let mut skill_markdown: Option<String> = None;
|
||||
let mut actual_total = 0u64;
|
||||
|
||||
for entry in subtree_entries {
|
||||
@@ -709,12 +803,16 @@ fn fetch_and_scan_bundle(
|
||||
target,
|
||||
&entry.path,
|
||||
&entry.sha,
|
||||
MAX_SINGLE_BLOB_BYTES.min(MAX_SKILL_SUBTREE_BYTES - actual_total),
|
||||
MAX_SINGLE_BLOB_BYTES.min(max_subtree_bytes - actual_total),
|
||||
cancel,
|
||||
)?;
|
||||
actual_total = actual_total.saturating_add(bytes.len() as u64);
|
||||
if actual_total > MAX_SKILL_SUBTREE_BYTES {
|
||||
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
|
||||
if actual_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
}
|
||||
|
||||
if is_symlink {
|
||||
@@ -748,11 +846,15 @@ fn fetch_and_scan_bundle(
|
||||
|
||||
if let Ok(text) = std::str::from_utf8(&bytes) {
|
||||
scan_hidden_unicode(rel_str, text, &mut scan_warnings);
|
||||
if rel_str == "SKILL.md" {
|
||||
skill_markdown = Some(text.to_owned());
|
||||
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
|
||||
for tool in frontmatter_shell_tools(text) {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: rel_str.to_owned(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if rel_str == "SKILL.md" {
|
||||
return Err(IdeError::invalid("SKILL.md is not valid UTF-8 text"));
|
||||
}
|
||||
|
||||
files.push(RemoteSkillFile {
|
||||
@@ -767,13 +869,12 @@ fn fetch_and_scan_bundle(
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
// Symlinks are judged together: one link may point through another, and an entry placed beneath
|
||||
// a symlink would be written wherever that link points.
|
||||
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
|
||||
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
|
||||
if let Some(link) = graph.symlink_ancestor(path) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Skill entry {:?} is inside symlink {link:?}; the repository tree is malformed",
|
||||
"{} entry {:?} is inside symlink {link:?}; the repository tree is malformed",
|
||||
capitalize(noun),
|
||||
path.display().to_string()
|
||||
)));
|
||||
}
|
||||
@@ -786,26 +887,65 @@ fn fetch_and_scan_bundle(
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::OutOfRootSymlink,
|
||||
file: rel_str,
|
||||
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
|
||||
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
in_root_symlinks.sort();
|
||||
|
||||
let Some(skill_markdown) = skill_markdown else {
|
||||
return Err(IdeError::invalid("Selected folder does not contain a regular SKILL.md file"));
|
||||
};
|
||||
Ok(FetchedSubtree { tree_sha: tree.sha, normalized_subpath, files, scan_warnings, regular_files, in_root_symlinks })
|
||||
}
|
||||
|
||||
let folder_hint = normalized_subpath
|
||||
fn capitalize(s: &str) -> String {
|
||||
let mut c = s.chars();
|
||||
match c.next() {
|
||||
None => String::new(),
|
||||
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
|
||||
fn fetch_and_scan_bundle(
|
||||
fetcher: &dyn SkillSourceFetcher,
|
||||
target: RepoRef<'_>,
|
||||
subpath: &str,
|
||||
pinned_tree_sha: Option<&str>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PreparedSkillBundle> {
|
||||
let RepoRef { repo, .. } = target;
|
||||
let mut sub = fetch_and_scan_subtree(
|
||||
fetcher,
|
||||
target,
|
||||
subpath,
|
||||
pinned_tree_sha,
|
||||
MAX_SKILL_FILES,
|
||||
MAX_SKILL_SUBTREE_BYTES,
|
||||
"skill",
|
||||
cancel,
|
||||
)?;
|
||||
|
||||
let skill_bytes = sub
|
||||
.regular_files
|
||||
.iter()
|
||||
.find(|(p, _, _)| p == Path::new("SKILL.md"))
|
||||
.map(|(_, b, _)| b.as_slice())
|
||||
.ok_or_else(|| IdeError::invalid("Selected folder does not contain a regular SKILL.md file"))?;
|
||||
let skill_markdown =
|
||||
std::str::from_utf8(skill_bytes).map_err(|_| IdeError::invalid("SKILL.md is not valid UTF-8 text"))?.to_owned();
|
||||
|
||||
let folder_hint = sub
|
||||
.normalized_subpath
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(|| sanitize_repo_as_skill_name(repo));
|
||||
|
||||
// Strip any `SKILL.md` shell-tool warnings already collected so `parse_skill_markdown_metadata` emits them in order.
|
||||
sub.scan_warnings.retain(|w| !(w.kind == SkillScanWarningKind::AllowedToolsShell && w.file == "SKILL.md"));
|
||||
let parsed_meta = parse_skill_markdown_metadata(&folder_hint, &skill_markdown)?;
|
||||
for tool in &parsed_meta.shell_tools {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
sub.scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: "SKILL.md".into(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
@@ -813,14 +953,14 @@ fn fetch_and_scan_bundle(
|
||||
}
|
||||
|
||||
Ok(PreparedSkillBundle {
|
||||
tree_sha: tree.sha,
|
||||
tree_sha: sub.tree_sha,
|
||||
skill_name: parsed_meta.name,
|
||||
description: parsed_meta.description,
|
||||
skill_markdown,
|
||||
files,
|
||||
scan_warnings,
|
||||
regular_files,
|
||||
in_root_symlinks,
|
||||
files: sub.files,
|
||||
scan_warnings: sub.scan_warnings,
|
||||
regular_files: sub.regular_files,
|
||||
in_root_symlinks: sub.in_root_symlinks,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1140,6 +1280,33 @@ fn create_parent_dirs_no_follow(root: &Path, rel: &Path) -> IdeResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates `target` below the existing `anchor` (the home or project folder) without following a
|
||||
/// symlink in any directory between them, the harness store root included.
|
||||
fn create_dirs_below_anchor(anchor: &Path, target: &Path) -> IdeResult<()> {
|
||||
if !anchor.is_dir() {
|
||||
return Err(IdeError::not_found(format!("{} does not exist", anchor.display())));
|
||||
}
|
||||
let rel = target
|
||||
.strip_prefix(anchor)
|
||||
.map_err(|_| IdeError::invalid(format!("{} is outside {}", target.display(), anchor.display())))?;
|
||||
let mut dir = anchor.to_path_buf();
|
||||
for component in rel.components() {
|
||||
if !matches!(component, Component::Normal(_)) {
|
||||
return Err(IdeError::invalid(format!("{} is not a plain path below the store", target.display())));
|
||||
}
|
||||
dir.push(component);
|
||||
match std::fs::symlink_metadata(&dir) {
|
||||
Ok(meta) if meta.is_dir() => {}
|
||||
Ok(_) => {
|
||||
return Err(IdeError::invalid(format!("{} passes through a symlink or file", dir.display())));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => std::fs::create_dir(&dir)?,
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the symlink at `link` resolves strictly inside `root` (canonical), following links on disk.
|
||||
/// Components that do not exist are resolved lexically.
|
||||
#[cfg(unix)]
|
||||
@@ -1220,15 +1387,16 @@ pub fn install_skill(
|
||||
workspace_root: Option<&Path>,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let target_root = match req.scope {
|
||||
// Anchored at the home or project folder: nothing below it may be a symlink, store included.
|
||||
let (anchor, target_root) = match req.scope {
|
||||
McpScope::User => {
|
||||
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
|
||||
home.join(".agents").join("skills")
|
||||
(home.to_path_buf(), home.join(".agents").join("skills"))
|
||||
}
|
||||
McpScope::Workspace => {
|
||||
let ws = workspace_root
|
||||
.ok_or_else(|| IdeError::invalid("Open a trusted project to install workspace skills"))?;
|
||||
ws.join(".agents").join("skills")
|
||||
(ws.to_path_buf(), ws.join(".agents").join("skills"))
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1245,20 +1413,60 @@ pub fn install_skill(
|
||||
));
|
||||
}
|
||||
|
||||
std::fs::create_dir_all(&target_root)?;
|
||||
let final_dir = target_root.join(&bundle.skill_name);
|
||||
if final_dir.exists() && !req.overwrite {
|
||||
write_staged_subtree(
|
||||
&anchor,
|
||||
&target_root,
|
||||
&bundle.skill_name,
|
||||
req.overwrite,
|
||||
"Skill",
|
||||
&bundle.regular_files,
|
||||
&bundle.in_root_symlinks,
|
||||
&[],
|
||||
)
|
||||
}
|
||||
|
||||
/// Atomically writes `regular_files`, `in_root_symlinks`, and `extra_files` into a staging folder
|
||||
/// under `target_root`, verifies created symlinks stay inside the folder, and swaps into `<target_root>/<folder_name>`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn write_staged_subtree(
|
||||
anchor: &Path,
|
||||
target_root: &Path,
|
||||
folder_name: &str,
|
||||
overwrite: bool,
|
||||
noun_cap: &str,
|
||||
regular_files: &[(PathBuf, Vec<u8>, bool)],
|
||||
in_root_symlinks: &[(PathBuf, PathBuf)],
|
||||
extra_files: &[(&str, &[u8])],
|
||||
) -> IdeResult<PathBuf> {
|
||||
create_dirs_below_anchor(anchor, target_root)?;
|
||||
if folder_name.is_empty() || !Path::new(folder_name).components().all(|c| matches!(c, Component::Normal(_))) {
|
||||
return Err(IdeError::invalid(format!("Invalid {} folder name", noun_cap.to_ascii_lowercase())));
|
||||
}
|
||||
let final_dir = target_root.join(folder_name);
|
||||
let existing = match std::fs::symlink_metadata(&final_dir) {
|
||||
Ok(meta) if meta.is_dir() => true,
|
||||
Ok(_) => {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} is a symlink or file, not a {} folder",
|
||||
final_dir.display(),
|
||||
noun_cap.to_ascii_lowercase()
|
||||
)));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
if existing && !overwrite {
|
||||
return Err(IdeError::new(
|
||||
ErrorKind::AlreadyExists,
|
||||
format!("Skill `{}` is already installed in {}", bundle.skill_name, target_root.display()),
|
||||
format!("{noun_cap} `{folder_name}` is already installed in {}", target_root.display()),
|
||||
));
|
||||
}
|
||||
|
||||
let nonce = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
|
||||
let staging = target_root.join(format!(".staging-{}-{nonce}-{}", bundle.skill_name, std::process::id()));
|
||||
let staging = target_root.join(format!(".staging-{folder_name}-{nonce}-{}", std::process::id()));
|
||||
let write_res = (|| -> IdeResult<()> {
|
||||
std::fs::create_dir_all(&staging)?;
|
||||
for (rel_path, bytes, is_exec) in &bundle.regular_files {
|
||||
for (rel_path, bytes, is_exec) in regular_files {
|
||||
create_parent_dirs_no_follow(&staging, rel_path)?;
|
||||
let dest = staging.join(rel_path);
|
||||
std::fs::write(&dest, bytes)?;
|
||||
@@ -1270,7 +1478,12 @@ pub fn install_skill(
|
||||
#[cfg(not(unix))]
|
||||
let _ = is_exec;
|
||||
}
|
||||
for (rel_link, target) in &bundle.in_root_symlinks {
|
||||
for (rel_str, bytes) in extra_files {
|
||||
let rel_path = validate_rel_skill_file(rel_str)?;
|
||||
create_parent_dirs_no_follow(&staging, &rel_path)?;
|
||||
std::fs::write(staging.join(&rel_path), bytes)?;
|
||||
}
|
||||
for (rel_link, target) in in_root_symlinks {
|
||||
create_parent_dirs_no_follow(&staging, rel_link)?;
|
||||
let dest = staging.join(rel_link);
|
||||
#[cfg(unix)]
|
||||
@@ -1288,17 +1501,18 @@ pub fn install_skill(
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let root = std::fs::canonicalize(&staging)?;
|
||||
for (rel_link, _) in &bundle.in_root_symlinks {
|
||||
for (rel_link, _) in in_root_symlinks {
|
||||
if !link_resolves_inside(&root, &staging.join(rel_link)) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"Symlink {:?} leaves the skill folder",
|
||||
rel_link.display().to_string()
|
||||
"Symlink {:?} leaves the {} folder",
|
||||
rel_link.display().to_string(),
|
||||
noun_cap.to_ascii_lowercase()
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let backup = if final_dir.exists() {
|
||||
let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name));
|
||||
let backup = if existing {
|
||||
let bak = target_root.join(format!(".old-{folder_name}-{nonce}"));
|
||||
std::fs::rename(&final_dir, &bak)?;
|
||||
Some(bak)
|
||||
} else {
|
||||
@@ -1323,6 +1537,179 @@ pub fn install_skill(
|
||||
Ok(final_dir)
|
||||
}
|
||||
|
||||
/// Scans a local directory on disk with the same symlink-graph, executable-script, and hidden-Unicode
|
||||
/// checks used for remote GitHub subtrees.
|
||||
/// Content digest of a scanned local folder, used to pin a local preview to its install.
|
||||
fn local_subtree_digest(regular_files: &[(PathBuf, Vec<u8>, bool)], symlinks: &[(PathBuf, PathBuf)]) -> String {
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
hasher.update(b"openidea-local-subtree-v1\0");
|
||||
for (path, bytes, executable) in regular_files {
|
||||
hasher.update(b"f\0");
|
||||
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(&[0, u8::from(*executable)]);
|
||||
hasher.update(&(bytes.len() as u64).to_le_bytes());
|
||||
hasher.update(bytes);
|
||||
}
|
||||
for (path, target) in symlinks {
|
||||
hasher.update(b"l\0");
|
||||
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(b"\0");
|
||||
hasher.update(target.to_string_lossy().replace('\\', "/").as_bytes());
|
||||
hasher.update(b"\0");
|
||||
}
|
||||
format!("local-blake3:{}", hasher.finalize().to_hex())
|
||||
}
|
||||
|
||||
pub(crate) fn scan_local_subtree(
|
||||
dir: &Path,
|
||||
max_files: usize,
|
||||
max_subtree_bytes: u64,
|
||||
noun: &str,
|
||||
) -> IdeResult<FetchedSubtree> {
|
||||
if !dir.is_dir() {
|
||||
return Err(IdeError::not_found(format!("Directory {} does not exist", dir.display())));
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
let mut scan_warnings = Vec::new();
|
||||
let mut regular_files = Vec::new();
|
||||
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
|
||||
let mut actual_total = 0u64;
|
||||
|
||||
let mut stack = vec![(dir.to_path_buf(), String::new())];
|
||||
while let Some((cur_dir, rel_prefix)) = stack.pop() {
|
||||
let mut entries: Vec<_> = std::fs::read_dir(&cur_dir)?.filter_map(Result::ok).collect();
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
for entry in entries {
|
||||
let name = entry.file_name();
|
||||
let Some(name_str) = name.to_str() else {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} contains a file name that is not valid UTF-8: {}",
|
||||
capitalize(noun),
|
||||
entry.path().display()
|
||||
)));
|
||||
};
|
||||
if name_str == ".git" || name_str == "node_modules" || name_str == "target" {
|
||||
continue;
|
||||
}
|
||||
let rel_str = if rel_prefix.is_empty() { name_str.to_owned() } else { format!("{rel_prefix}/{name_str}") };
|
||||
let rel_path = validate_rel_skill_file(&rel_str)?;
|
||||
let full = entry.path();
|
||||
let meta = std::fs::symlink_metadata(&full)?;
|
||||
if (meta.file_type().is_symlink() || meta.file_type().is_file())
|
||||
&& regular_files.len() + symlinks.len() >= max_files
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{} exceeds maximum of {max_files} files", capitalize(noun))));
|
||||
}
|
||||
if meta.file_type().is_symlink() {
|
||||
let target_raw = std::fs::read_link(&full)?.to_string_lossy().replace('\\', "/");
|
||||
symlinks.push((rel_path, rel_str.clone(), target_raw));
|
||||
files.push(RemoteSkillFile { path: rel_str, size: 0, executable: false, symlink: true });
|
||||
continue;
|
||||
}
|
||||
if meta.file_type().is_dir() {
|
||||
stack.push((full, rel_str));
|
||||
continue;
|
||||
}
|
||||
if !meta.file_type().is_file() {
|
||||
continue;
|
||||
}
|
||||
if meta.len() > MAX_SINGLE_BLOB_BYTES {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"File {rel_str:?} exceeds {} MiB size cap",
|
||||
MAX_SINGLE_BLOB_BYTES >> 20
|
||||
)));
|
||||
}
|
||||
let bytes = std::fs::read(&full)?;
|
||||
actual_total = actual_total.saturating_add(bytes.len() as u64);
|
||||
if actual_total > max_subtree_bytes {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} exceeds {} MiB size cap",
|
||||
capitalize(noun),
|
||||
max_subtree_bytes >> 20
|
||||
)));
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let is_exec_mode = {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
meta.permissions().mode() & 0o111 != 0
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let is_exec_mode = false;
|
||||
let has_shebang = bytes.starts_with(b"#!");
|
||||
let is_script_path = is_executable_or_script_path(&rel_path);
|
||||
if is_exec_mode || has_shebang || is_script_path {
|
||||
let reason = if is_exec_mode {
|
||||
"executable file mode"
|
||||
} else if has_shebang {
|
||||
"script with `#!` interpreter header"
|
||||
} else {
|
||||
"bundled script or native binary"
|
||||
};
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::ExecutableScript,
|
||||
file: rel_str.clone(),
|
||||
message: format!("Contains {reason}"),
|
||||
});
|
||||
}
|
||||
if let Ok(text) = std::str::from_utf8(&bytes) {
|
||||
scan_hidden_unicode(&rel_str, text, &mut scan_warnings);
|
||||
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
|
||||
for tool in frontmatter_shell_tools(text) {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::AllowedToolsShell,
|
||||
file: rel_str.clone(),
|
||||
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
files.push(RemoteSkillFile {
|
||||
path: rel_str,
|
||||
size: bytes.len() as u64,
|
||||
executable: is_exec_mode || has_shebang,
|
||||
symlink: false,
|
||||
});
|
||||
regular_files.push((rel_path, bytes, is_exec_mode));
|
||||
}
|
||||
}
|
||||
|
||||
files.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
|
||||
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
|
||||
if let Some(link) = graph.symlink_ancestor(path) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{} entry {:?} is inside symlink {link:?}",
|
||||
capitalize(noun),
|
||||
path.display().to_string()
|
||||
)));
|
||||
}
|
||||
}
|
||||
let mut in_root_symlinks = Vec::new();
|
||||
for (rel_path, rel_str, target_raw) in symlinks {
|
||||
if graph.stays_inside(&rel_path, &target_raw) {
|
||||
in_root_symlinks.push((rel_path, PathBuf::from(target_raw)));
|
||||
} else {
|
||||
scan_warnings.push(SkillScanWarning {
|
||||
kind: SkillScanWarningKind::OutOfRootSymlink,
|
||||
file: rel_str,
|
||||
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
|
||||
});
|
||||
}
|
||||
}
|
||||
in_root_symlinks.sort();
|
||||
|
||||
Ok(FetchedSubtree {
|
||||
tree_sha: local_subtree_digest(®ular_files, &in_root_symlinks),
|
||||
normalized_subpath: String::new(),
|
||||
files,
|
||||
scan_warnings,
|
||||
regular_files,
|
||||
in_root_symlinks,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1374,6 +1761,25 @@ mod tests {
|
||||
.cloned()
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
|
||||
}
|
||||
fn git_commit_sha(&self, target: RepoRef<'_>, _cancel: &CancellationToken) -> IdeResult<String> {
|
||||
self.trees
|
||||
.get(target.git_ref)
|
||||
.map(|_| git_blob_id(format!("commit:{}", target.git_ref).as_bytes()))
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
|
||||
}
|
||||
fn git_commit_tree_sha(
|
||||
&self,
|
||||
_owner: &str,
|
||||
_repo: &str,
|
||||
commit_sha: &str,
|
||||
_cancel: &CancellationToken,
|
||||
) -> IdeResult<String> {
|
||||
self.trees
|
||||
.iter()
|
||||
.find(|(git_ref, _)| git_blob_id(format!("commit:{git_ref}").as_bytes()) == commit_sha)
|
||||
.map(|(_, tree)| tree.sha.clone())
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown commit {commit_sha}")))
|
||||
}
|
||||
|
||||
fn read_blob(
|
||||
&self,
|
||||
@@ -1440,7 +1846,9 @@ mod tests {
|
||||
let cancel = CancellationToken::new();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let home = tmp.path().join("home");
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let ws = tmp.path().join("ws");
|
||||
std::fs::create_dir_all(&ws).unwrap();
|
||||
|
||||
// Bare `owner/repo` lists both skills; `owner/repo@clean-skill` falls back from ref lookup to skill filter!
|
||||
let all = browse_skills(&fetcher, "acme/skills", &cancel).unwrap();
|
||||
@@ -1796,4 +2204,66 @@ mod tests {
|
||||
.unwrap();
|
||||
assert!(dest.join("SKILL.md").is_file());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn local_scan_counts_symlinks_toward_the_file_cap() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::write(tmp.path().join("SKILL.md"), "x").unwrap();
|
||||
for i in 0..3 {
|
||||
std::os::unix::fs::symlink("SKILL.md", tmp.path().join(format!("link-{i}"))).unwrap();
|
||||
}
|
||||
let Err(err) = scan_local_subtree(tmp.path(), 3, 1 << 20, "plugin") else { panic!("symlinks must count") };
|
||||
assert!(err.to_string().contains("maximum of 3 files"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_tree_listings_are_rejected() {
|
||||
let mut fetcher = FakeFetcher::new();
|
||||
fetcher.add_tree("main", vec![("skills/a/SKILL.md", "100644", b"---\nname: a\ndescription: a\n---\n")]);
|
||||
fetcher.trees.get_mut("main").unwrap().truncated = true;
|
||||
let cancel = CancellationToken::new();
|
||||
let target = RepoRef { owner: "o", repo: "r", git_ref: "main" };
|
||||
let Err(err) = fetch_and_scan_subtree(&fetcher, target, "skills/a", None, 10, 1 << 20, "skill", &cancel) else {
|
||||
panic!("a truncated listing cannot be verified")
|
||||
};
|
||||
assert!(err.to_string().contains("truncated"), "{err}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn staged_installs_do_not_follow_symlinks_below_the_store() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let store = tmp.path().join("store");
|
||||
let outside = tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&store).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, store.join("mkt")).unwrap();
|
||||
let files = vec![(PathBuf::from("plugin.json"), b"{}".to_vec(), false)];
|
||||
let Err(err) = write_staged_subtree(&store, &store.join("mkt"), "plugin", false, "Plugin", &files, &[], &[])
|
||||
else {
|
||||
panic!("a symlinked marketplace folder must not be written through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the store");
|
||||
|
||||
// The store root itself (`<home>/.claude/plugins` → elsewhere) is checked as well.
|
||||
let home = tmp.path().join("home");
|
||||
std::fs::create_dir_all(home.join(".claude")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, home.join(".claude/plugins")).unwrap();
|
||||
let store_root = home.join(".claude/plugins/cache/mkt");
|
||||
let Err(err) = write_staged_subtree(&home, &store_root, "plugin", false, "Plugin", &files, &[], &[]) else {
|
||||
panic!("a symlinked store root must not be written through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
assert!(std::fs::read_dir(&outside).unwrap().next().is_none());
|
||||
|
||||
std::fs::create_dir_all(store.join("real")).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, store.join("real/plugin")).unwrap();
|
||||
let Err(err) = write_staged_subtree(&store, &store.join("real"), "plugin", true, "Plugin", &files, &[], &[])
|
||||
else {
|
||||
panic!("an existing symlinked plugin folder must not be replaced through")
|
||||
};
|
||||
assert!(err.to_string().contains("symlink"), "{err}");
|
||||
}
|
||||
}
|
||||
@@ -275,12 +275,27 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Ag
|
||||
}
|
||||
|
||||
/// [`discover_skills_in`] plus the `<dir>` skill folders contributed by enabled OpenIDEA
|
||||
/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name
|
||||
/// clash; a plugin skill is never silently renamed.
|
||||
/// plugins (`[[contributes.skills]]`) and unified agent plugin bundles (`plugins.rs`).
|
||||
/// Workspace and user skills take precedence on a name clash; a plugin skill is never silently renamed.
|
||||
pub fn discover_skills_with_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
) -> Vec<AgentSkill> {
|
||||
let default_policy = crate::plugins::PluginsPolicy { workspace_roots: workspaces.to_vec(), ..Default::default() };
|
||||
let states =
|
||||
crate::plugins::resolve_plugins(crate::plugins::discover_plugins(workspaces, home), &default_policy, None);
|
||||
let projected = crate::plugins::projected_skill_roots(&states, None);
|
||||
discover_skills_with_agent_plugins(workspaces, home, plugin_skill_dirs, &projected)
|
||||
}
|
||||
|
||||
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
|
||||
/// and resolved agent plugin bundle roots (`agent_plugin_roots`).
|
||||
pub fn discover_skills_with_agent_plugins(
|
||||
workspaces: &[PathBuf],
|
||||
home: Option<&Path>,
|
||||
plugin_skill_dirs: &[PathBuf],
|
||||
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
|
||||
) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
|
||||
@@ -338,9 +353,19 @@ pub fn discover_skills_with_plugins(
|
||||
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
|
||||
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
|
||||
}
|
||||
if let Some(home) = home {
|
||||
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
|
||||
for skill in skills_of(&root, source) {
|
||||
for proj in agent_plugin_roots {
|
||||
if proj.dir.join("SKILL.md").is_file() && proj.dir.file_name().and_then(|s| s.to_str()) != Some("skills") {
|
||||
let Some(folder) = file_name(&proj.dir) else { continue };
|
||||
if let Ok(text) = std::fs::read_to_string(proj.dir.join("SKILL.md")) {
|
||||
let mut skill = parse_skill_file(&proj.dir, &folder, &text, proj.source);
|
||||
skill.plugin_id = Some(proj.plugin_id.clone());
|
||||
skill.plugin_name = Some(proj.plugin_name.clone());
|
||||
push_skill(skill);
|
||||
}
|
||||
} else {
|
||||
for mut skill in skills_of(&proj.dir, proj.source) {
|
||||
skill.plugin_id = Some(proj.plugin_id.clone());
|
||||
skill.plugin_name = Some(proj.plugin_name.clone());
|
||||
push_skill(skill);
|
||||
}
|
||||
}
|
||||
@@ -388,83 +413,6 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Discovers skill roots inside `~/.copilot/installed-plugins`, supporting both Copilot CLI's
|
||||
/// 2-level `<marketplace-or-_direct>/<plugin>` layout (and `config.json` `installedPlugins`
|
||||
/// enablement) and flat 1-level `<plugin>` folders.
|
||||
fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkillSource)> {
|
||||
let mut disabled_paths: HashSet<PathBuf> = HashSet::new();
|
||||
let mut plugin_dirs: Vec<PathBuf> = Vec::new();
|
||||
let mut seen_dirs: HashSet<PathBuf> = HashSet::new();
|
||||
let mut push_plugin = |dir: PathBuf, disabled: &HashSet<PathBuf>| {
|
||||
if !dir.is_dir() {
|
||||
return;
|
||||
}
|
||||
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
||||
if disabled.contains(&canon) || !seen_dirs.insert(canon) {
|
||||
return;
|
||||
}
|
||||
plugin_dirs.push(dir);
|
||||
};
|
||||
|
||||
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
|
||||
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
|
||||
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
|
||||
{
|
||||
for entry in installed {
|
||||
let Some(raw_cache) = entry.get("cache_path").and_then(serde_json::Value::as_str).map(str::trim) else {
|
||||
continue;
|
||||
};
|
||||
if raw_cache.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let dir =
|
||||
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
|
||||
if entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(false) {
|
||||
disabled_paths.insert(dunce::canonicalize(&dir).unwrap_or(dir));
|
||||
} else {
|
||||
push_plugin(dir, &disabled_paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let plugins_root = copilot_dir.join("installed-plugins");
|
||||
for entry in sorted(&plugins_root) {
|
||||
if !entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
if looks_like_plugin_dir(&entry) {
|
||||
push_plugin(entry, &disabled_paths);
|
||||
} else {
|
||||
// 2-level `<marketplace>/<plugin>` or `_direct/<plugin>`.
|
||||
for sub in sorted(&entry) {
|
||||
if sub.is_dir() {
|
||||
push_plugin(sub, &disabled_paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut roots = Vec::new();
|
||||
for plugin in plugin_dirs {
|
||||
let skills_sub = plugin.join("skills");
|
||||
if skills_sub.is_dir() {
|
||||
roots.push((skills_sub, AgentSkillSource::CopilotUser));
|
||||
} else {
|
||||
roots.push((plugin, AgentSkillSource::CopilotUser));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn looks_like_plugin_dir(dir: &Path) -> bool {
|
||||
dir.join("skills").is_dir()
|
||||
|| dir.join("plugin.json").is_file()
|
||||
|| dir.join(".plugin").is_dir()
|
||||
|| dir.join(".claude-plugin").is_dir()
|
||||
|| dir.join(".cursor-plugin").is_dir()
|
||||
|| dir.join("SKILL.md").is_file()
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
@@ -544,6 +492,8 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
|
||||
paths,
|
||||
valid: warnings.is_empty(),
|
||||
warnings,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1070,6 +1020,8 @@ mod tests {
|
||||
paths: Vec::new(),
|
||||
valid: true,
|
||||
warnings: Vec::new(),
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -69,6 +69,10 @@ struct FakeAgent {
|
||||
prompts: Mutex<Vec<Value>>,
|
||||
/// Queued errors returned on the next `session/prompt` calls before succeeding.
|
||||
prompt_errors: Mutex<VecDeque<(i64, String)>>,
|
||||
/// Number of prompts that stream Cursor's capacity diagnostic before returning end_turn.
|
||||
capacity_errors: Mutex<u32>,
|
||||
/// Queued errors returned on the next session-open calls before succeeding.
|
||||
open_errors: Mutex<VecDeque<(i64, String, Option<Value>)>>,
|
||||
/// Recorded `(method, _meta.openidea.memory)` payloads across `session/new`, `session/load`, and `session/fork`.
|
||||
memory_calls: Mutex<Vec<(String, Option<Value>)>>,
|
||||
}
|
||||
@@ -150,6 +154,12 @@ impl Handler for FakeAgent {
|
||||
let data = json!({"openidea": {"usageLimit": {"resetsAtMs": 1234.0}}});
|
||||
return Err((codes::INTERNAL_ERROR, "You've hit your usage limit".into(), Some(data)));
|
||||
}
|
||||
if matches!(method, "session/new" | "session/load" | "session/fork")
|
||||
&& let Some(err) = self.open_errors.lock().pop_front()
|
||||
{
|
||||
self.calls.lock().push(method.to_owned());
|
||||
return Err(err);
|
||||
}
|
||||
self.on_request(method, params).map_err(|(code, message)| (code, message, None))
|
||||
}
|
||||
|
||||
@@ -289,6 +299,22 @@ impl Handler for FakeAgent {
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_owned();
|
||||
{
|
||||
let mut remaining = self.capacity_errors.lock();
|
||||
if *remaining > 0 {
|
||||
*remaining -= 1;
|
||||
if text == "edit once" {
|
||||
self.update(
|
||||
&session,
|
||||
json!({"sessionUpdate": "tool_call", "toolCallId": "edit",
|
||||
"title": "Edit file", "kind": "edit", "status": "completed"}),
|
||||
);
|
||||
}
|
||||
self.say(&session, "\n\nError: RetriableError: ");
|
||||
self.say(&session, "[resource_exhausted] Error");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
}
|
||||
}
|
||||
if text.starts_with("The previous turn was interrupted because ") {
|
||||
self.say(&session, "resumed cleanly");
|
||||
return Ok(json!({"stopReason": "end_turn"}));
|
||||
@@ -426,6 +452,28 @@ impl Handler for FakeAgent {
|
||||
self.say(&session, &format!("form {answer}"));
|
||||
return Ok(json!({ "stopReason": "end_turn" }));
|
||||
}
|
||||
if text == "question form" {
|
||||
// claude-agent-acp's `AskUserQuestion`, sent as a form.
|
||||
let peer = self.latest();
|
||||
let answer: Value = tokio::runtime::Handle::current()
|
||||
.block_on(peer.request(
|
||||
"elicitation/create",
|
||||
json!({"sessionId": session, "mode": "form",
|
||||
"message": "Please answer the following questions.",
|
||||
"requestedSchema": {"type": "object", "properties": {
|
||||
"question_0": {"type": "string", "title": "Layout", "description": "Which layout?",
|
||||
"oneOf": [{"const": "List", "title": "List"}, {"const": "Grid", "title": "Grid"}]},
|
||||
"question_0_custom": {"type": "string", "title": "Other"},
|
||||
"question_1": {"type": "array", "title": "Checks", "description": "Which checks?",
|
||||
"items": {"anyOf": [{"const": "Disk", "title": "Disk"},
|
||||
{"const": "GPU", "title": "GPU"}]}},
|
||||
"question_1_custom": {"type": "string", "title": "Other"}}}}),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
self.say(&session, &format!("form {answer}"));
|
||||
return Ok(json!({ "stopReason": "end_turn" }));
|
||||
}
|
||||
if text == "ask" {
|
||||
let peer = self.latest();
|
||||
let answer: Value = tokio::runtime::Handle::current()
|
||||
@@ -2226,6 +2274,175 @@ async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn warming_up_error() -> (i64, String, Option<Value>) {
|
||||
(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure".to_owned(),
|
||||
Some(json!({"errorName": "ServiceUnavailableError"})),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_open_retries_while_the_agent_finishes_starting_up() {
|
||||
// OpenCode rejects session opens until its plugins and MCP servers finish activating.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent =
|
||||
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 2, "retried the startup race");
|
||||
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().expect("a session");
|
||||
mgr.shutdown();
|
||||
|
||||
// The same race when reopening a saved session.
|
||||
let agent =
|
||||
Arc::new(FakeAgent { open_errors: Mutex::new(VecDeque::from([warming_up_error()])), ..Default::default() });
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/load").count(), 2, "retried the startup race");
|
||||
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(saved.as_str()));
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
async fn wait_for_session_open_attempts(agent: &FakeAgent, method: &str, attempts: usize) {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while agent.calls.lock().iter().filter(|call| call.as_str() == method).count() < attempts {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("agent received the session-open requests");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retry_after_warmup_expires_loads_the_saved_session_again() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let saved = mgr.task(&task.id).unwrap().state.lock().session_id.clone().unwrap();
|
||||
mgr.shutdown();
|
||||
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(std::iter::repeat_with(warming_up_error).take(16).collect()),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for_session_open_attempts(&agent, "session/load", 2).await;
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(WARMUP_WINDOW - WARMUP_DELAY * 2).await;
|
||||
tokio::time::resume();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
|
||||
entry, AgentEntry::Error { message } if message.contains("Try again") && !message.contains("new session")
|
||||
)));
|
||||
|
||||
agent.open_errors.lock().clear();
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert!(!agent.calls.lock().iter().any(|call| call == "session/new"));
|
||||
let handle = mgr.task(&task.id).unwrap();
|
||||
assert_eq!(handle.live.lock().as_ref().unwrap().session, saved);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_stalled_warmup_retry_times_out_and_closes_the_connection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
|
||||
hold_session_new: AtomicBool::new(true),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for_session_open_attempts(&agent, "session/new", 2).await;
|
||||
tokio::time::pause();
|
||||
tokio::time::advance(WARMUP_WINDOW).await;
|
||||
tokio::time::resume();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
assert!(mgr.entries(&task.id, None).unwrap().iter().any(|entry| matches!(
|
||||
entry, AgentEntry::Error { message } if message.contains("timed out")
|
||||
)));
|
||||
tokio::time::timeout(Duration::from_secs(5), agent.latest().closed())
|
||||
.await
|
||||
.expect("the timed-out connection closes");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_open_authenticates_after_a_warmup_reply() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(VecDeque::from([warming_up_error()])),
|
||||
auth_on_new: true,
|
||||
authenticate_method: Some("agent_login".into()),
|
||||
auth_methods: vec![json!({"id": "agent_login", "name": "Sign in"})],
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask { prompt: text("again"), provider: "claude".into(), ..Default::default() })
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let calls = agent.calls.lock();
|
||||
let setup: Vec<_> = calls
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.filter(|call| call.starts_with("session/") || call.starts_with("authenticate"))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
setup,
|
||||
["session/new", "session/new", "authenticate", "authenticate agent_login", "session/new", "session/prompt"]
|
||||
);
|
||||
drop(calls);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn session_open_does_not_retry_unrelated_internal_errors() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let agent = Arc::new(FakeAgent {
|
||||
open_errors: Mutex::new(VecDeque::from([(
|
||||
codes::INTERNAL_ERROR,
|
||||
"Internal error: Internal service failure".into(),
|
||||
Some(json!({"errorName": "SQLiteError"})),
|
||||
)])),
|
||||
..Default::default()
|
||||
});
|
||||
let mgr = manager(tmp.path(), agent.clone());
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
isolation: Isolation::Local,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Failed).await;
|
||||
assert_eq!(agent.calls.lock().iter().filter(|c| *c == "session/new").count(), 1, "no retry on a real failure");
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn text(t: &str) -> AgentPrompt {
|
||||
AgentPrompt { text: t.into(), ..AgentPrompt::default() }
|
||||
}
|
||||
@@ -2606,7 +2823,12 @@ async fn subagents_get_their_own_conversation() {
|
||||
|
||||
#[test]
|
||||
fn image_blocks_declare_the_type_of_their_bytes() {
|
||||
let image = |mime: &str, data: &str| AgentImage { mime_type: mime.into(), data: data.into(), name: None };
|
||||
let image = |mime: &str, data: &str| AgentImage {
|
||||
mime_type: mime.into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: None,
|
||||
};
|
||||
let cases = [
|
||||
// A browser's JPEG pasted as PNG.
|
||||
(image("image/png", "/9j/4AAQSkZJRgABAQ"), "image/jpeg"),
|
||||
@@ -2628,7 +2850,7 @@ fn prompts_become_acp_content_blocks() {
|
||||
let p = AgentPrompt {
|
||||
text: "look".into(),
|
||||
files: vec![IpcPath(PathBuf::from("/p/my file.rs"))],
|
||||
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None }],
|
||||
images: vec![AgentImage { mime_type: "image/png".into(), data: "AAA".into(), name: None, inline_number: None }],
|
||||
};
|
||||
assert_eq!(
|
||||
blocks(&p, &[]),
|
||||
@@ -2660,6 +2882,32 @@ fn prompts_become_acp_content_blocks() {
|
||||
assert!(clean(text(" ")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_images_are_distinct_content_blocks_in_text_order() {
|
||||
let older: AgentImage = serde_json::from_value(json!({"mimeType":"image/png", "data":"AAA", "name":null})).unwrap();
|
||||
assert!(older.inline_number.is_none());
|
||||
let image = |number, data: &str| AgentImage {
|
||||
mime_type: "image/png".into(),
|
||||
data: data.into(),
|
||||
name: None,
|
||||
inline_number: Some(number),
|
||||
};
|
||||
let prompt = AgentPrompt {
|
||||
text: "😀 [Image #2] then [Image #1] and [Image #99]".into(),
|
||||
images: vec![image(1, "AAA"), image(2, "BBB"), image(3, "CCC")],
|
||||
..Default::default()
|
||||
};
|
||||
let content = blocks(&prompt, &[]);
|
||||
assert_eq!(content.len(), 5);
|
||||
assert_eq!(content[0], json!({"type": "text", "text": "😀 "}));
|
||||
assert_eq!(content[1]["type"], "image");
|
||||
assert_eq!(content[1]["data"], "BBB");
|
||||
assert_eq!(content[2], json!({"type": "text", "text": " then "}));
|
||||
assert_eq!(content[3]["type"], "image");
|
||||
assert_eq!(content[3]["data"], "AAA");
|
||||
assert_eq!(content[4], json!({"type": "text", "text": " and [Image #99]"}));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn claude_questions_keep_the_answer_object_as_the_option_id() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -3930,6 +4178,54 @@ async fn an_agent_form_is_answered_declined_or_cancelled_even_when_approvals_are
|
||||
}
|
||||
}
|
||||
|
||||
/// claude-agent-acp asks `AskUserQuestion` as a form: it is shown as the question card, one
|
||||
/// question at a time, and the card's answers fill the form (#7359).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_question_tool_form_is_asked_as_questions() {
|
||||
let answers = json!({"question_0": ["Grid", "with thumbnails"], "question_1": ["Disk", "GPU"]}).to_string();
|
||||
for (reply, said) in [
|
||||
(
|
||||
answers.as_str(),
|
||||
r#"form {"action":"accept","content":{"question_0":"Grid","question_0_custom":"with thumbnails","question_1":["Disk","GPU"]}}"#,
|
||||
),
|
||||
("reject", r#"form {"action":"decline"}"#),
|
||||
] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("question form"),
|
||||
provider: "cursor".into(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
|
||||
let (id, questions) = mgr
|
||||
.entries(&task.id, None)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.find_map(|entry| match entry {
|
||||
AgentEntry::Permission { id, questions, form: None, chosen: None, .. } if !questions.is_empty() => {
|
||||
Some((id, questions))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let asked: Vec<_> =
|
||||
questions.iter().map(|q| (q.answer_key.as_deref(), q.question.as_str(), q.multi_select)).collect();
|
||||
assert_eq!(asked, [(Some("question_0"), "Which layout?", false), (Some("question_1"), "Which checks?", true)]);
|
||||
mgr.respond(&task.id, id, Some(reply.to_owned())).unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
let entries = mgr.entries(&task.id, None).unwrap();
|
||||
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == said)), "{entries:?}");
|
||||
mgr.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cursor_approval_choice_applies_before_first_prompt() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -4882,7 +5178,7 @@ fn a_running_tools_output_is_sent_as_appends() {
|
||||
// An image the tool returned is not part of the appended text: it goes with the whole entry.
|
||||
let mut shown = titled.clone();
|
||||
if let AgentEntry::Tool { images, output, .. } = &mut shown {
|
||||
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None });
|
||||
images.push(AgentImage { mime_type: "image/png".into(), data: "AAAA".into(), name: None, inline_number: None });
|
||||
output.as_mut().unwrap().push('!');
|
||||
}
|
||||
let imaged = event(&mut streamed, None, 2, &shown).unwrap();
|
||||
@@ -6056,6 +6352,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
},
|
||||
McpServer {
|
||||
id: "user::slack".into(),
|
||||
@@ -6070,6 +6368,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
headers: Vec::new(),
|
||||
agents: Vec::new(),
|
||||
unapproved: false,
|
||||
plugin_id: None,
|
||||
plugin_name: None,
|
||||
},
|
||||
]
|
||||
}));
|
||||
@@ -6981,6 +7281,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};
|
||||
|
||||
@@ -523,7 +523,7 @@ mod tests {
|
||||
t.apply(&update);
|
||||
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "preview", "status": "completed"}));
|
||||
let AgentEntry::Tool { images, output, status, .. } = &t.entries[0] else { panic!() };
|
||||
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None }]);
|
||||
assert_eq!(images, &vec![AgentImage { mime_type: "image/png".into(), data, name: None, inline_number: None }]);
|
||||
assert!(output.as_ref().unwrap().len() < MAX_OUTPUT + 100);
|
||||
assert_eq!(*status, AgentToolStatus::Completed);
|
||||
let saved = serde_json::to_string(&t.entries[0]).unwrap();
|
||||
@@ -646,6 +646,7 @@ mod tests {
|
||||
done_ms: None,
|
||||
steered: false,
|
||||
recovery: None,
|
||||
retry_attempt: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0));
|
||||
@@ -668,6 +669,7 @@ mod tests {
|
||||
done_ms: None,
|
||||
steered,
|
||||
recovery: None,
|
||||
retry_attempt: None,
|
||||
};
|
||||
let mut t = Timeline::default();
|
||||
t.push(user(1.0, false));
|
||||
|
||||
@@ -9,12 +9,34 @@ use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
|
||||
pub(crate) struct Created {
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub path: PathBuf,
|
||||
pub cwd: PathBuf,
|
||||
pub branch: String,
|
||||
pub base: String,
|
||||
pub base_commit: String,
|
||||
}
|
||||
|
||||
const OWNERSHIP_MARKER: &str = "openidea-worktree.json";
|
||||
const OWNERSHIP_TAG: &str = "openidea-agent";
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct WorktreeOwnership {
|
||||
owner: String,
|
||||
task_id: String,
|
||||
worktree_root: PathBuf,
|
||||
repo_root: PathBuf,
|
||||
}
|
||||
|
||||
/// Returns the canonical root of the Git repository containing `project_root`, if any.
|
||||
pub fn canonical_repo_root(project_root: &Path) -> IdeResult<Option<PathBuf>> {
|
||||
match Repo::discover(project_root)? {
|
||||
Some(repo) => Ok(Some(dunce::canonicalize(repo.root())?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The repository of `path`, free to execute: the host runs every agent command that
|
||||
/// reaches a repository only in a trusted project.
|
||||
fn discover(path: &Path) -> IdeResult<Option<Repo>> {
|
||||
@@ -157,9 +179,38 @@ pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
|
||||
create_for_task(project_root, worktrees_dir, "", title, base)
|
||||
}
|
||||
|
||||
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
|
||||
/// Records an ownership marker in the linked worktree's private `git_dir` and preserves any
|
||||
/// project-relative subdirectory inside `project_root` when `project_root` is below `repo.root()`.
|
||||
pub(crate) fn create_for_task(
|
||||
project_root: &Path,
|
||||
worktrees_dir: &Path,
|
||||
task_id: &str,
|
||||
title: &str,
|
||||
base: Option<&str>,
|
||||
) -> IdeResult<Created> {
|
||||
let repo = repo_at(project_root)?;
|
||||
let canon_repo = dunce::canonicalize(repo.root())?;
|
||||
let canon_proj = dunce::canonicalize(project_root)?;
|
||||
let rel_subdir = if canon_proj != canon_repo {
|
||||
canon_proj
|
||||
.strip_prefix(&canon_repo)
|
||||
.map_err(|_| {
|
||||
IdeError::invalid(format!(
|
||||
"{} is outside git repository {}",
|
||||
canon_proj.display(),
|
||||
canon_repo.display()
|
||||
))
|
||||
})?
|
||||
.to_path_buf()
|
||||
} else {
|
||||
PathBuf::new()
|
||||
};
|
||||
let (base, base_commit) = match base.map(str::trim).filter(|b| !b.is_empty()) {
|
||||
Some(b) => {
|
||||
let commit =
|
||||
@@ -177,7 +228,125 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
|
||||
let path = worktrees_dir.join(&slug);
|
||||
let branch = format!("agent/{slug}");
|
||||
repo.add_worktree(&path, &base_commit, Some(&branch))?;
|
||||
Ok(Created { path, branch, base, base_commit })
|
||||
|
||||
let canon_wt = match dunce::canonicalize(&path) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e.into());
|
||||
}
|
||||
};
|
||||
let wt_repo = match repo_at(&canon_wt) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let [git_dir, common_dir] = match wt_repo.metadata_dirs() {
|
||||
Ok(dirs) => dirs,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
if dunce::canonicalize(&git_dir).ok() == dunce::canonicalize(&common_dir).ok() {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(IdeError::internal("linked worktree did not receive a separate git metadata directory"));
|
||||
}
|
||||
let marker = WorktreeOwnership {
|
||||
owner: OWNERSHIP_TAG.to_owned(),
|
||||
task_id: task_id.to_owned(),
|
||||
worktree_root: canon_wt.clone(),
|
||||
repo_root: canon_repo,
|
||||
};
|
||||
if let Err(e) = serde_json::to_vec_pretty(&marker)
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
.and_then(|bytes| ide_vfs::write_atomic(&git_dir.join(OWNERSHIP_MARKER), &bytes))
|
||||
{
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let raw_cwd = if rel_subdir.as_os_str().is_empty() { canon_wt.clone() } else { canon_wt.join(&rel_subdir) };
|
||||
if !raw_cwd.is_dir() {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(IdeError::invalid(format!(
|
||||
"project folder {} does not exist in base revision {}",
|
||||
rel_subdir.display(),
|
||||
base
|
||||
)));
|
||||
}
|
||||
let canon_cwd = match verify_confined_worktree_subdir(&canon_wt, &raw_cwd) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
let _ = repo.remove_worktree(&path, false);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
|
||||
}
|
||||
|
||||
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
|
||||
let canon_cwd = dunce::canonicalize(target_cwd)?;
|
||||
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
|
||||
let real_cwd = ide_core::real_path::resolve_real(target_cwd);
|
||||
if !canon_cwd.starts_with(canon_wt_root)
|
||||
|| !real_cwd.starts_with(&real_wt)
|
||||
|| ide_core::real_path::reaches_git_dir(&real_wt, &real_cwd)
|
||||
{
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree working directory {} resolves outside worktree {}",
|
||||
target_cwd.display(),
|
||||
canon_wt_root.display()
|
||||
)));
|
||||
}
|
||||
Ok(canon_cwd)
|
||||
}
|
||||
|
||||
/// Canonicalizes `cwd` of an existing `Isolation::Worktree` task and verifies that it still
|
||||
/// resolves strictly inside its own worktree checkout root under `worktrees_dir` (preventing
|
||||
/// symlink escapes on reused sessions/turns).
|
||||
pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) -> IdeResult<PathBuf> {
|
||||
let (wt_root, wt_base) = worktree_checkout_root(worktrees_dir, cwd);
|
||||
if !wt_root.starts_with(&wt_base) || wt_root == wt_base {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"worktree working directory {} is outside managed worktrees directory {}",
|
||||
cwd.display(),
|
||||
worktrees_dir.display()
|
||||
)));
|
||||
}
|
||||
let canon_wt_root = dunce::canonicalize(&wt_root)?;
|
||||
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
|
||||
if !canon_wt_root.starts_with(&canon_wt_dir)
|
||||
|| canon_wt_root == canon_wt_dir
|
||||
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
|
||||
{
|
||||
return Err(IdeError::invalid("worktree checkout root escaped managed worktrees directory"));
|
||||
}
|
||||
verify_confined_worktree_subdir(&canon_wt_root, cwd)
|
||||
}
|
||||
|
||||
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
|
||||
if let Ok(rel) = path.strip_prefix(worktrees_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
|
||||
}
|
||||
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
|
||||
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
}
|
||||
if let Ok(canon_path) = dunce::canonicalize(path)
|
||||
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
|
||||
&& let Some(first) = rel.components().next()
|
||||
{
|
||||
return (canon_wt_dir.join(first), canon_wt_dir);
|
||||
}
|
||||
}
|
||||
(path.to_path_buf(), worktrees_dir.to_path_buf())
|
||||
}
|
||||
|
||||
/// `git worktree remove --force -- <path>`. When git no longer recognizes the
|
||||
@@ -186,19 +355,94 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
|
||||
/// ours, so it is removed directly to keep the task deletable (a stale
|
||||
/// registration prunes later); anything else keeps git's error.
|
||||
pub(crate) fn remove(project_root: &Path, worktrees_dir: &Path, path: &Path) -> IdeResult<()> {
|
||||
let (target, wt_base) = worktree_checkout_root(worktrees_dir, path);
|
||||
let repo = repo_at(project_root)?;
|
||||
let err = match repo.remove_worktree(path, true) {
|
||||
let err = match repo.remove_worktree(&target, true) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(e) => e,
|
||||
};
|
||||
if !path.exists() {
|
||||
if !target.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
if !path.starts_with(worktrees_dir) || path == worktrees_dir {
|
||||
if !target.starts_with(&wt_base) || target == wt_base {
|
||||
return Err(err);
|
||||
}
|
||||
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(path))
|
||||
.map_err(|e| IdeError::internal(format!("{}: {e}", path.display())))
|
||||
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(&target))
|
||||
.map_err(|e| IdeError::internal(format!("{}: {e}", target.display())))
|
||||
}
|
||||
|
||||
/// Safely removes an automation worktree ONLY after verifying its private `git_dir` ownership
|
||||
/// marker (`openidea-worktree.json`) matches `task_id` and `worktrees_dir`.
|
||||
///
|
||||
/// - When `require_clean` is `true` (zero-diff GC): verifies `HEAD == base_commit` and both the
|
||||
/// Git index (staged) and working tree (unstaged + untracked) are completely clean right before
|
||||
/// running **non-forced** `git worktree remove` (`force = false`). Returns `Ok(false)` without
|
||||
/// modifying disk if the worktree has any commits, staged changes, unstaged edits, or untracked
|
||||
/// files.
|
||||
/// - Never falls back to `remove_dir_all` on any ownership or Git error: any error keeps the
|
||||
/// checkout intact.
|
||||
pub(crate) fn remove_owned_automation_worktree(
|
||||
project_root: &Path,
|
||||
worktrees_dir: &Path,
|
||||
cwd: &Path,
|
||||
task_id: &str,
|
||||
base_commit: Option<&str>,
|
||||
require_clean: bool,
|
||||
) -> IdeResult<bool> {
|
||||
if !cwd.exists() || !worktrees_dir.exists() {
|
||||
return Ok(false);
|
||||
}
|
||||
let canon_worktrees = dunce::canonicalize(worktrees_dir)?;
|
||||
let canon_cwd = dunce::canonicalize(cwd)?;
|
||||
if !canon_cwd.starts_with(&canon_worktrees) || canon_cwd == canon_worktrees {
|
||||
return Err(IdeError::invalid("refusing to clean worktree outside managed worktrees directory"));
|
||||
}
|
||||
let main_repo = repo_at(project_root)?;
|
||||
let wt_repo = repo_at(&canon_cwd)?;
|
||||
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
|
||||
if !canon_wt_root.starts_with(&canon_worktrees)
|
||||
|| canon_wt_root == canon_worktrees
|
||||
|| canon_wt_root.parent() != Some(canon_worktrees.as_path())
|
||||
{
|
||||
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
|
||||
}
|
||||
let [git_dir, wt_common] = wt_repo.metadata_dirs()?;
|
||||
let [_, main_common] = main_repo.metadata_dirs()?;
|
||||
let canon_git_dir = dunce::canonicalize(&git_dir)?;
|
||||
let canon_wt_common = dunce::canonicalize(&wt_common)?;
|
||||
let canon_main_common = dunce::canonicalize(&main_common)?;
|
||||
if canon_git_dir == canon_wt_common || canon_wt_common != canon_main_common {
|
||||
return Err(IdeError::invalid("target checkout is not a linked worktree of this repository"));
|
||||
}
|
||||
let marker_bytes = std::fs::read(canon_git_dir.join(OWNERSHIP_MARKER))
|
||||
.map_err(|_| IdeError::invalid("refusing to remove worktree without OpenIDEA ownership marker"))?;
|
||||
let marker: WorktreeOwnership = serde_json::from_slice(&marker_bytes)
|
||||
.map_err(|_| IdeError::invalid("corrupt OpenIDEA worktree ownership marker"))?;
|
||||
let marker_root = dunce::canonicalize(&marker.worktree_root).unwrap_or(marker.worktree_root);
|
||||
if marker.owner != OWNERSHIP_TAG || marker.task_id != task_id || marker_root != canon_wt_root {
|
||||
return Err(IdeError::invalid("worktree ownership marker does not match task"));
|
||||
}
|
||||
|
||||
if require_clean {
|
||||
let Some(base) = base_commit else {
|
||||
return Ok(false);
|
||||
};
|
||||
if wt_repo.head()?.1.as_deref() != Some(base) {
|
||||
return Ok(false);
|
||||
}
|
||||
// `status()` checks BOTH HEAD↔index (staged) and index↔worktree (unstaged + untracked).
|
||||
if !wt_repo.status()?.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
if !wt_repo.diff_with_worktree(base)?.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
main_repo.remove_worktree(&canon_wt_root, false)?;
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
main_repo.remove_worktree(&canon_wt_root, true)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// On Windows a folder can't be deleted while a process still has a file in it open
|
||||
@@ -1944,4 +2188,130 @@ mod tests {
|
||||
changed.sort();
|
||||
assert_eq!(changed, ["edited", "new", "reverted"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_worktree_cleanup_preserves_subproject_cwd_catches_staged_changes_and_verifies_ownership() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let repo = tmp.path().join("repo");
|
||||
let sub = repo.join("packages").join("subapp");
|
||||
std::fs::create_dir_all(&sub).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
git(&repo, &["config", "core.autocrlf", "false"]);
|
||||
std::fs::write(repo.join("root.txt"), "root\n").unwrap();
|
||||
std::fs::write(sub.join("index.ts"), "export const x = 1;\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "init"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
let created = create_for_task(&sub, &wt_dir, "task-1", "Sub Audit", None).unwrap();
|
||||
assert_eq!(
|
||||
dunce::canonicalize(&created.cwd).unwrap(),
|
||||
dunce::canonicalize(&created.path).unwrap().join("packages").join("subapp"),
|
||||
"project-relative cwd inside parent repo must be preserved inside worktree"
|
||||
);
|
||||
|
||||
// Wrong task_id is refused and keeps the checkout untouched.
|
||||
assert!(
|
||||
remove_owned_automation_worktree(
|
||||
&sub,
|
||||
&wt_dir,
|
||||
&created.cwd,
|
||||
"wrong-task",
|
||||
Some(&created.base_commit),
|
||||
true,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(created.path.exists());
|
||||
|
||||
// Staged-only change (index differs from HEAD while working tree matches HEAD!) is NOT clean!
|
||||
std::fs::write(created.cwd.join("index.ts"), "export const x = 2;\n").unwrap();
|
||||
git(&created.path, &["add", "packages/subapp/index.ts"]);
|
||||
std::fs::write(created.cwd.join("index.ts"), "export const x = 1;\n").unwrap();
|
||||
let removed_staged =
|
||||
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
|
||||
.unwrap();
|
||||
assert!(!removed_staged, "staged-only index change must prevent zero-diff worktree GC");
|
||||
assert!(created.path.exists());
|
||||
|
||||
// Reset index back to HEAD -> zero-diff GC removes the worktree via non-forced `git worktree remove`.
|
||||
git(&created.path, &["reset", "-q", "HEAD", "--", "packages/subapp/index.ts"]);
|
||||
let removed_clean =
|
||||
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
|
||||
.unwrap();
|
||||
assert!(removed_clean);
|
||||
assert!(!created.path.exists());
|
||||
|
||||
// Foreign / manually created git worktree inside `wt_dir` without ownership marker is NEVER deleted.
|
||||
let manual_wt = wt_dir.join("foreign");
|
||||
git(&repo, &["worktree", "add", "-q", "-b", "manual-branch", manual_wt.to_str().unwrap(), "HEAD"]);
|
||||
assert!(
|
||||
remove_owned_automation_worktree(&repo, &wt_dir, &manual_wt, "task-2", Some(&created.base_commit), false,)
|
||||
.is_err()
|
||||
);
|
||||
assert!(manual_wt.exists(), "worktree without OpenIDEA ownership marker must never be deleted");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn symlinked_subproject_cwd_escaping_worktree_is_rejected_on_create_and_reuse() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let outside = tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(outside.join("secret.txt"), "nope\n").unwrap();
|
||||
|
||||
let repo = tmp.path().join("repo");
|
||||
let packages = repo.join("packages");
|
||||
std::fs::create_dir_all(&packages).unwrap();
|
||||
git(&repo, &["init", "-q", "-b", "main"]);
|
||||
git(&repo, &["config", "core.autocrlf", "false"]);
|
||||
|
||||
// 1a. Direct symlink pointing outside git is rejected immediately.
|
||||
let escape_link = packages.join("escape");
|
||||
std::os::unix::fs::symlink(&outside, &escape_link).unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "symlink escape"]);
|
||||
|
||||
let wt_dir = tmp.path().join("wt");
|
||||
assert!(create_for_task(&escape_link, &wt_dir, "task-escape-direct", "Escape", None).is_err());
|
||||
|
||||
// 1b. Committed symlink in `HEAD` (`packages/tricky -> ../../outside`) while the main
|
||||
// checkout temporarily has a real directory at `packages/tricky`: `git worktree add`
|
||||
// checks out `HEAD`'s symlink inside the worktree, and `verify_confined_worktree_subdir`
|
||||
// must catch the escape and clean up the worktree!
|
||||
let tricky = packages.join("tricky");
|
||||
std::os::unix::fs::symlink(&outside, &tricky).unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "committed tricky symlink"]);
|
||||
std::fs::remove_file(&tricky).unwrap();
|
||||
std::fs::create_dir_all(&tricky).unwrap();
|
||||
|
||||
let Err(err) = create_for_task(&tricky, &wt_dir, "task-escape-head", "Tricky", None) else {
|
||||
panic!("expected committed symlink escaping worktree root to be rejected");
|
||||
};
|
||||
assert!(
|
||||
err.to_string().contains("outside worktree") || err.to_string().contains("escapes worktree root"),
|
||||
"unexpected error for committed symlink cwd: {err}"
|
||||
);
|
||||
|
||||
// 2. Normal directory at creation time, later replaced with an escaping symlink before reuse,
|
||||
// must be rejected by `verify_confined_worktree_cwd`!
|
||||
let legit_sub = packages.join("legit");
|
||||
std::fs::create_dir_all(&legit_sub).unwrap();
|
||||
std::fs::write(legit_sub.join("ok.txt"), "ok\n").unwrap();
|
||||
git(&repo, &["add", "."]);
|
||||
git(&repo, &["commit", "-q", "-m", "legit sub"]);
|
||||
|
||||
let created = create_for_task(&legit_sub, &wt_dir, "task-reuse", "Legit", None).unwrap();
|
||||
let verified = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap();
|
||||
assert!(verified.starts_with(dunce::canonicalize(&created.path).unwrap()));
|
||||
|
||||
std::fs::remove_dir_all(&created.cwd).unwrap();
|
||||
std::os::unix::fs::symlink(&outside, &created.cwd).unwrap();
|
||||
let reuse_err = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap_err();
|
||||
assert!(
|
||||
reuse_err.to_string().contains("outside worktree") || reuse_err.to_string().contains("escapes"),
|
||||
"symlink swap on worktree reuse must be rejected: {reuse_err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"version": 2,
|
||||
"plugins": {
|
||||
"evidence-plugin@evidence-mkt": [
|
||||
{
|
||||
"scope": "user",
|
||||
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
|
||||
"version": "1.2.3",
|
||||
"installedAt": "2026-11-30T21:50:25.665Z",
|
||||
"lastUpdated": "2026-11-30T21:50:25.665Z",
|
||||
"gitCommitSha": "1111111111111111111111111111111111111111"
|
||||
},
|
||||
{
|
||||
"scope": "project",
|
||||
"projectPath": "$WORKSPACE",
|
||||
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
|
||||
"version": "1.2.3",
|
||||
"installedAt": "2026-11-30T21:50:25.665Z",
|
||||
"lastUpdated": "2026-11-30T21:50:25.665Z",
|
||||
"gitCommitSha": "1111111111111111111111111111111111111111"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
[marketplaces.evidence-mkt]
|
||||
source_type = "local"
|
||||
source = "$HOME/.codex/.tmp/marketplaces/evidence-mkt"
|
||||
|
||||
[plugins."evidence-plugin@evidence-mkt"]
|
||||
enabled = false
|
||||
@@ -0,0 +1,19 @@
|
||||
// This file is managed automatically.
|
||||
{
|
||||
"installedPlugins": [
|
||||
{
|
||||
"name": "evidence-plugin",
|
||||
"marketplace": "evidence-mkt",
|
||||
"installed_at": "2026-11-30T21:50:25.665Z",
|
||||
"enabled": true,
|
||||
"version": "1.2.3",
|
||||
"cache_path": "$HOME/.copilot/installed-plugins/evidence-mkt/evidence-plugin",
|
||||
"source": {
|
||||
"source": "github",
|
||||
"repo": "acme/plugins",
|
||||
"sha": "1111111111111111111111111111111111111111",
|
||||
"path": "plugins/evidence-plugin"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"evidence-extension": {
|
||||
"overrides": [
|
||||
"$HOME/*",
|
||||
"!$WORKSPACE/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,7 @@ pub(crate) fn stream_batched<T>(
|
||||
}
|
||||
}
|
||||
flush(&mut batch, on_batch);
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
Ok((lines.finish(cancel)?.success(), stderr_tail))
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
|
||||
@@ -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};
|
||||
@@ -421,13 +422,14 @@ fn cargo_steps(dir: &Path, kind: BuildKind) -> Vec<BuildStep> {
|
||||
}
|
||||
|
||||
/// CLion's Build Project for a CMake project: configures the build directory when it has no
|
||||
/// `CMakeCache.txt` yet, then `cmake --build` (`--clean-first` to rebuild), one job per
|
||||
/// `CMakeCache.txt` or no File API reply yet, then `cmake --build` (`--clean-first` to rebuild), one job per
|
||||
/// logical CPU unless the profile's build arguments choose a count. The directory and
|
||||
/// options come from the CMake profile; without one, a configured directory of the project
|
||||
/// (the first by name), else `build`, as the generated run configurations use.
|
||||
fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> Vec<BuildStep> {
|
||||
let build_dir = match profile {
|
||||
Some(p) if !p.build_dir.trim().is_empty() => p.build_dir.trim().to_owned(),
|
||||
Some(p) if p.build_type.is_empty() => "cmake-build-default".into(),
|
||||
Some(p) => format!("cmake-build-{}", p.build_type.to_lowercase()),
|
||||
None => {
|
||||
let mut configured: Vec<String> = std::fs::read_dir(dir)
|
||||
@@ -444,18 +446,49 @@ fn cmake_steps(dir: &Path, kind: BuildKind, profile: Option<&CMakeProfile>) -> V
|
||||
let build_type = profile.map_or("Debug", |p| p.build_type.as_str());
|
||||
let env = profile.map(|p| p.env.clone()).unwrap_or_default();
|
||||
let mut steps = Vec::new();
|
||||
if !dir.join(&build_dir).join("CMakeCache.txt").is_file() {
|
||||
let mut configure = BuildStep::new("cmake", &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
|
||||
if let Some(p) = profile.filter(|p| !p.generator.trim().is_empty()) {
|
||||
configure.args.extend(["-G".into(), p.generator.clone()]);
|
||||
}
|
||||
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
|
||||
let preset = profile.and_then(|p| p.preset.as_ref());
|
||||
// The profile's toolchain may bring its own cmake.
|
||||
let cmake = profile.and_then(|p| p.cmake_program.as_ref()).map_or("cmake".into(), |c| c.to_string_lossy());
|
||||
let cmake = cmake.as_ref();
|
||||
let build_path = dir.join(&build_dir);
|
||||
// Configured without the File API queries (by another tool, or before they were written):
|
||||
// configure again so the targets, and their run configurations, become known.
|
||||
let fresh = !build_path.join("CMakeCache.txt").is_file();
|
||||
if fresh || !build_path.join(ide_core::cmake_file_api::REPLY).is_dir() {
|
||||
// Best effort: without the queries the build still runs, only the targets stay unknown.
|
||||
let _ = ide_core::cmake_file_api::write_queries(&build_path);
|
||||
let mut configure = match preset {
|
||||
// The preset sets the generator and cache variables.
|
||||
Some(preset) => BuildStep::new(cmake, &["--preset", &preset.configure], dir, Format::Gcc),
|
||||
None => {
|
||||
let mut configure = BuildStep::new(cmake, &["-S", ".", "-B", &build_dir], dir, Format::Gcc);
|
||||
// A configured directory keeps its generator (CMake refuses another one) and,
|
||||
// without a profile, its build type.
|
||||
if let Some(p) = profile.filter(|p| fresh && !p.generator.trim().is_empty()) {
|
||||
configure.args.extend(["-G".into(), p.generator.clone()]);
|
||||
}
|
||||
if fresh || profile.is_some() {
|
||||
configure.args.push(format!("-DCMAKE_BUILD_TYPE={build_type}"));
|
||||
}
|
||||
configure
|
||||
}
|
||||
};
|
||||
configure.args.push("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".into());
|
||||
configure.args.extend(profile.map(|p| p.cmake_args.clone()).unwrap_or_default());
|
||||
configure.env = env.clone();
|
||||
steps.push(configure);
|
||||
}
|
||||
let mut build = BuildStep::new("cmake", &["--build", &build_dir, "--config", build_type], dir, Format::Gcc);
|
||||
let mut build = match preset.and_then(|p| p.build.as_deref()) {
|
||||
Some(build) => BuildStep::new(cmake, &["--build", "--preset", build], dir, Format::Gcc),
|
||||
None => {
|
||||
let mut build = BuildStep::new(cmake, &["--build", &build_dir], dir, Format::Gcc);
|
||||
// CLion's "Default" build type: no configuration at all.
|
||||
if !build_type.is_empty() {
|
||||
build.args.extend(["--config".into(), build_type.into()]);
|
||||
}
|
||||
build
|
||||
}
|
||||
};
|
||||
if kind == BuildKind::Rebuild {
|
||||
build.args.push("--clean-first".into());
|
||||
}
|
||||
@@ -1659,6 +1692,15 @@ mod tests {
|
||||
"an unconfigured project is configured first"
|
||||
);
|
||||
write(&cm, "cmake-build-release/CMakeCache.txt", "");
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
p.steps[0].args,
|
||||
["-S", ".", "-B", "cmake-build-release", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"],
|
||||
"configured again, as it was, when it has no File API reply"
|
||||
);
|
||||
assert!(cm.join("cmake-build-release/.cmake/api/v1/query/client-openidea/codemodel-v2").is_file());
|
||||
std::fs::create_dir_all(cm.join("cmake-build-release").join(ide_core::cmake_file_api::REPLY)).unwrap();
|
||||
let p =
|
||||
plan(&cm, &BuildModel::default(), BuildKind::Rebuild, None, None, None, &CancellationToken::new()).unwrap();
|
||||
assert_eq!(
|
||||
@@ -1694,6 +1736,33 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(p.steps[0].args[..4], ["-S", ".", "-B", "cmake-build-debug"]);
|
||||
let preset = CMakeProfile {
|
||||
build_dir: "out/dev".into(),
|
||||
preset: Some(ide_core::settings::CMakePresetRef {
|
||||
configure: "dev".into(),
|
||||
build: Some("dev-build".into()),
|
||||
..Default::default()
|
||||
}),
|
||||
..CMakeProfile::default()
|
||||
};
|
||||
let p = plan(
|
||||
&cm,
|
||||
&BuildModel::default(),
|
||||
BuildKind::Build,
|
||||
None,
|
||||
Some(std::slice::from_ref(&preset)),
|
||||
None,
|
||||
&CancellationToken::new(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
args(&p),
|
||||
[
|
||||
"--preset dev -DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned(),
|
||||
format!("--build --preset dev-build {jobs}")
|
||||
],
|
||||
"a preset profile configures and builds with its presets"
|
||||
);
|
||||
|
||||
let siblings = tmp.path().join("siblings");
|
||||
write(&siblings, "core/pom.xml", "<project><artifactId>core</artifactId></project>");
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -234,9 +234,7 @@ fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Ve
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
fn read_pool(r: &mut Bytes<'_>) -> Option<Pool> {
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
@@ -283,11 +281,28 @@ pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
entries.push(entry);
|
||||
i += 1;
|
||||
if wide {
|
||||
if i == count {
|
||||
return None;
|
||||
}
|
||||
entries.push(Entry::Empty);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let pool = Pool(entries);
|
||||
Some(Pool(entries))
|
||||
}
|
||||
|
||||
/// Reads the internal class name (e.g. `com/acme/Order$Line`) from `this_class`.
|
||||
pub fn class_file_name(data: &[u8]) -> Option<String> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
r.u2()?; // access_flags
|
||||
Some(pool.class(r.u2()?)?.to_owned())
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
let pool = read_pool(&mut r)?;
|
||||
let mut refs = BTreeSet::new();
|
||||
for entry in &pool.0 {
|
||||
match entry {
|
||||
|
||||
@@ -22,7 +22,7 @@ mod incremental;
|
||||
mod javac;
|
||||
mod model;
|
||||
|
||||
pub use classfile::ClassFile;
|
||||
pub use classfile::{ClassFile, class_file_name};
|
||||
pub use javac::{JavacPool, Reply, ServerKey};
|
||||
|
||||
use incremental::{ClassRecord, SetStamp, SetState};
|
||||
@@ -64,9 +64,300 @@ pub struct JavaBuildService {
|
||||
}
|
||||
|
||||
impl JavaBuildService {
|
||||
fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
|
||||
pub(crate) fn lock(&self, dir: &Path) -> Arc<Mutex<()>> {
|
||||
self.locks.lock().unwrap().entry(dir.to_path_buf()).or_default().clone()
|
||||
}
|
||||
|
||||
/// Compiles what changed in one source set (see [`incremental`]).
|
||||
pub fn compile_incremental(
|
||||
&self,
|
||||
set: &IncrementalSet<'_>,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
messages: &mut Vec<BuildMessage>,
|
||||
) -> IdeResult<IncrementalOutcome> {
|
||||
if set.clean {
|
||||
remove_classes(&set.output);
|
||||
let _ = std::fs::remove_dir_all(&set.generated_dir);
|
||||
let _ = std::fs::remove_file(&set.state_file);
|
||||
}
|
||||
let source_stamps: BTreeMap<PathBuf, FileStamp> =
|
||||
set.sources.iter().filter_map(|s| Some((s.clone(), file_stamp(s)?))).collect();
|
||||
let previous = incremental::load_state(&set.state_file);
|
||||
let reactor: Vec<PathBuf> = set.upstream_states.iter().map(|(o, _)| o.clone()).collect();
|
||||
let stamp = SetStamp {
|
||||
options: set.options.clone(),
|
||||
libraries: set.libraries.iter().map(|e| (e.clone(), file_stamp(e))).collect(),
|
||||
reactor,
|
||||
processor_path: set.processor_path.iter().map(|p| (p.clone(), file_stamp(p))).collect(),
|
||||
java_home: set.java_home.clone(),
|
||||
};
|
||||
|
||||
// What the upstream outputs it compiles against changed since it last compiled.
|
||||
let mut upstream = BTreeMap::new();
|
||||
let mut upstream_changed = BTreeSet::new();
|
||||
let mut upstream_all = false;
|
||||
for (entry, up_state_file) in &set.upstream_states {
|
||||
let state = incremental::load_state(up_state_file);
|
||||
let generation = state.as_ref().map_or(0, |s| s.generation);
|
||||
upstream.insert(entry.clone(), generation);
|
||||
let recorded = previous.as_ref().and_then(|p| p.upstream.get(entry)).copied();
|
||||
if recorded == Some(generation) {
|
||||
continue;
|
||||
}
|
||||
match (recorded, state.and_then(|s| s.changes_since(recorded?))) {
|
||||
(Some(_), Some(changed)) => upstream_changed.extend(changed),
|
||||
_ => upstream_all = true,
|
||||
}
|
||||
}
|
||||
|
||||
let had_state = previous.is_some();
|
||||
let previous = previous.unwrap_or_default();
|
||||
let mut changed: BTreeSet<PathBuf> = source_stamps
|
||||
.iter()
|
||||
.filter(|(path, stamp)| {
|
||||
previous.sources.get(*path) != Some(*stamp)
|
||||
|| previous.dirty.contains(*path)
|
||||
|| set.force.contains(*path)
|
||||
})
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect();
|
||||
let removed: BTreeSet<PathBuf> =
|
||||
previous.sources.keys().filter(|p| !source_stamps.contains_key(*p)).cloned().collect();
|
||||
let mut from_scratch = !had_state
|
||||
|| previous.stamp != stamp
|
||||
|| upstream_all
|
||||
|| !set.output.is_dir()
|
||||
|| (!previous.success && previous.dirty.is_empty());
|
||||
if had_state && !from_scratch {
|
||||
for record in previous.classes.values() {
|
||||
if !record.file.is_file() {
|
||||
match &record.source {
|
||||
Some(src) if source_stamps.contains_key(src) => {
|
||||
changed.insert(src.clone());
|
||||
}
|
||||
Some(src) if removed.contains(src) => {}
|
||||
_ => {
|
||||
from_scratch = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !from_scratch && changed.is_empty() && removed.is_empty() && upstream_changed.is_empty() {
|
||||
return Ok(IncrementalOutcome { failed: false, compiled_files: 0, outputs_changed: false });
|
||||
}
|
||||
// Processors that aggregate (or name no originating source) can't be followed class by class.
|
||||
let has_changes = !changed.is_empty() || !removed.is_empty() || !upstream_changed.is_empty();
|
||||
let from_scratch =
|
||||
from_scratch || ((!previous.generated.is_empty() || !previous.unowned.is_empty()) && has_changes);
|
||||
|
||||
let mut state = SetState {
|
||||
stamp,
|
||||
sources: source_stamps.clone(),
|
||||
generation: previous.generation,
|
||||
upstream,
|
||||
classes: previous.classes,
|
||||
changes: previous.changes,
|
||||
..Default::default()
|
||||
};
|
||||
let mut api_changed = BTreeSet::new();
|
||||
let mut constants_changed = false;
|
||||
// Classes of removed sources go first, and count as changed.
|
||||
let gone: Vec<String> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| removed.contains(s)))
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect();
|
||||
let gone_empty = gone.is_empty();
|
||||
for name in gone {
|
||||
let record = state.classes.remove(&name).expect("listed");
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
constants_changed |= record.constants != incremental::NO_CONSTANTS;
|
||||
api_changed.insert(name);
|
||||
}
|
||||
let mut to_compile: BTreeSet<PathBuf> = if from_scratch || constants_changed {
|
||||
remove_classes(&set.output);
|
||||
for file in previous.generated.iter().chain(&previous.unowned) {
|
||||
let _ = std::fs::remove_file(file);
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&set.generated_dir);
|
||||
state.classes.retain(|_, r| r.source.is_some());
|
||||
source_stamps.keys().cloned().collect()
|
||||
} else {
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &upstream_changed.union(&api_changed).cloned().collect());
|
||||
changed.iter().cloned().chain(incremental::dependent_sources(&state.classes, &affected)).collect()
|
||||
};
|
||||
std::fs::create_dir_all(&set.output)?;
|
||||
std::fs::create_dir_all(&set.generated_dir)?;
|
||||
|
||||
let total = source_stamps.len();
|
||||
let mut compiled: BTreeSet<PathBuf> = BTreeSet::new();
|
||||
let mut server = None;
|
||||
loop {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let batch: BTreeSet<PathBuf> = to_compile
|
||||
.iter()
|
||||
.filter(|s| !compiled.contains(*s) && source_stamps.contains_key(*s))
|
||||
.cloned()
|
||||
.collect();
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
// The classes the batch replaces: their files go first, so nothing stale is left.
|
||||
let replaced: BTreeMap<String, ClassRecord> = state
|
||||
.classes
|
||||
.iter()
|
||||
.filter(|(_, r)| r.source.as_ref().is_some_and(|s| batch.contains(s)))
|
||||
.map(|(n, r)| (n.clone(), r.clone()))
|
||||
.collect();
|
||||
for (name, record) in &replaced {
|
||||
let _ = std::fs::remove_file(&record.file);
|
||||
state.classes.remove(name);
|
||||
}
|
||||
let files: Vec<PathBuf> = batch.iter().cloned().collect();
|
||||
let noun = if total == 1 { "file" } else { "files" };
|
||||
let count = if files.len() == total {
|
||||
format!("{total} {noun}")
|
||||
} else {
|
||||
format!("{} of {total} {noun}", files.len())
|
||||
};
|
||||
on_event(BuildEvent::Step {
|
||||
command: format!("javac {} ({}, {count})", set.module_name, set.set_name),
|
||||
cwd: set.cwd.clone().into(),
|
||||
});
|
||||
if server.is_none() {
|
||||
let key = ServerKey { java_home: set.java_home.clone(), jvm_args: set.jvm_args.clone() };
|
||||
server = Some(self.servers.server(set.jar, &key)?);
|
||||
}
|
||||
let mut written: Vec<(PathBuf, Option<PathBuf>)> = Vec::new();
|
||||
let result =
|
||||
server.as_ref().expect("started").compile(&set.options, &files, set.encoding, cancel, |reply| {
|
||||
match reply {
|
||||
Reply::Output { path, source } => written.push((path.clone(), source.clone())),
|
||||
Reply::Generated { path, .. } => state.generated.push(path.clone()),
|
||||
Reply::OutputText { text } => {
|
||||
on_event(BuildEvent::Output { text: text.clone(), stderr: false })
|
||||
}
|
||||
Reply::Diagnostic { .. } => {
|
||||
if let Some(m) = diagnostic(reply) {
|
||||
on_event(BuildEvent::Output {
|
||||
text: message_text(&m),
|
||||
stderr: m.severity == Severity::Error,
|
||||
});
|
||||
on_event(BuildEvent::Message { message: m.clone() });
|
||||
messages.push(m);
|
||||
}
|
||||
}
|
||||
Reply::Done { .. } => {}
|
||||
}
|
||||
});
|
||||
if !matches!(result, Ok(true)) {
|
||||
for (path, _) in &written {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
// The next build starts from the state this one started from, with whatever this
|
||||
// one had to compile still to compile. Its earlier rounds' classes are not the
|
||||
// baseline: compared with them, the API and constant changes those rounds found
|
||||
// would never reach this set's dependents or the sets compiled against it.
|
||||
let mut retry = incremental::load_state(&set.state_file).unwrap_or_default();
|
||||
retry.dirty.extend(to_compile.union(&compiled).filter(|s| source_stamps.contains_key(*s)).cloned());
|
||||
retry.success = false;
|
||||
let _ = model::write_json(&set.state_file, &retry);
|
||||
return result.map(|_| IncrementalOutcome {
|
||||
failed: true,
|
||||
compiled_files: compiled.len(),
|
||||
outputs_changed: false,
|
||||
});
|
||||
}
|
||||
// javac names sources as they were passed; other spellings are matched canonically,
|
||||
// and classes of sources outside the set (processors' output) are unowned.
|
||||
let canonical: HashMap<PathBuf, &PathBuf> =
|
||||
batch.iter().filter_map(|s| Some((dunce::canonicalize(s).ok()?, s))).collect();
|
||||
let own = |source: PathBuf| -> Option<PathBuf> {
|
||||
if source_stamps.contains_key(&source) {
|
||||
return Some(source);
|
||||
}
|
||||
canonical.get(&dunce::canonicalize(&source).ok()?).map(|s| (*s).clone())
|
||||
};
|
||||
let mut fresh = BTreeMap::new();
|
||||
for (path, source) in written {
|
||||
let source = source.and_then(own);
|
||||
let class = (path.extension().is_some_and(|e| e == "class"))
|
||||
.then(|| std::fs::read(&path).ok())
|
||||
.flatten()
|
||||
.and_then(|bytes| classfile::parse(&bytes));
|
||||
match (class, source) {
|
||||
(Some(class), Some(source)) => {
|
||||
let (name, record) = ClassRecord::new(class, path, Some(source));
|
||||
fresh.insert(name, record);
|
||||
}
|
||||
_ => state.unowned.push(path),
|
||||
}
|
||||
}
|
||||
let round = incremental::diff(&replaced, &fresh);
|
||||
constants_changed |= round.constants;
|
||||
api_changed.extend(round.api.iter().cloned());
|
||||
state.classes.extend(fresh);
|
||||
compiled.extend(batch);
|
||||
if constants_changed {
|
||||
// Constants are copied into the classes that use them: compile the rest too.
|
||||
to_compile.extend(source_stamps.keys().cloned());
|
||||
continue;
|
||||
}
|
||||
let affected =
|
||||
incremental::with_subclasses(&state.classes, &round.api.union(&upstream_changed).cloned().collect());
|
||||
to_compile.extend(incremental::dependent_sources(&state.classes, &affected));
|
||||
to_compile.extend(incremental::shadowed_sources(&state.classes, &round.added));
|
||||
}
|
||||
state.success = true;
|
||||
if !compiled.is_empty() || !api_changed.is_empty() {
|
||||
let changed =
|
||||
incremental::with_subclasses(&state.classes, &api_changed.union(&upstream_changed).cloned().collect());
|
||||
state.log(now_generation(), changed, !had_state || constants_changed);
|
||||
}
|
||||
model::write_json(&set.state_file, &state)?;
|
||||
Ok(IncrementalOutcome {
|
||||
failed: false,
|
||||
compiled_files: compiled.len(),
|
||||
outputs_changed: !compiled.is_empty() || !gone_empty,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Inputs for compiling one source set incrementally with the resident `javac` server.
|
||||
pub struct IncrementalSet<'a> {
|
||||
pub module_name: String,
|
||||
pub set_name: &'static str,
|
||||
pub cwd: PathBuf,
|
||||
pub sources: Vec<PathBuf>,
|
||||
pub output: PathBuf,
|
||||
pub options: Vec<String>,
|
||||
pub libraries: Vec<PathBuf>,
|
||||
/// Upstream `(output_dir, state_file)` pairs this set compiles against.
|
||||
pub upstream_states: Vec<(PathBuf, PathBuf)>,
|
||||
pub processor_path: Vec<PathBuf>,
|
||||
pub java_home: PathBuf,
|
||||
pub jvm_args: Vec<String>,
|
||||
pub encoding: Option<&'a str>,
|
||||
pub state_file: PathBuf,
|
||||
pub generated_dir: PathBuf,
|
||||
pub force: &'a BTreeSet<PathBuf>,
|
||||
pub jar: &'a Path,
|
||||
pub clean: bool,
|
||||
}
|
||||
|
||||
/// Result of compiling one source set incrementally.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct IncrementalOutcome {
|
||||
pub failed: bool,
|
||||
pub compiled_files: usize,
|
||||
pub outputs_changed: bool,
|
||||
}
|
||||
|
||||
/// One build of the IDE's Java build service.
|
||||
@@ -79,6 +370,8 @@ pub struct JavaBuild<'a> {
|
||||
/// Changes when the jar does, so models recorded by an older extension are prepared again.
|
||||
pub jar_version: &'a str,
|
||||
pub local_repo: Option<PathBuf>,
|
||||
/// Explicit Maven goals the project's settings allow the IDE to skip in compile phases.
|
||||
pub ignored_maven_compile_goals: &'a [String],
|
||||
pub service: &'a JavaBuildService,
|
||||
/// The JDK home that compiles for a release, when Maven's environment names none.
|
||||
pub jdk: &'a (dyn Fn(Option<u32>) -> Option<PathBuf> + Sync),
|
||||
@@ -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.
|
||||
@@ -702,7 +995,11 @@ impl JavaBuild<'_> {
|
||||
let step = match top {
|
||||
Reactor::Maven(top) => {
|
||||
let selection = maven_project_selection(changed.iter().map(|(p, _, _)| *p));
|
||||
let mut extra = vec!["-q".to_owned(), "-pl".to_owned(), selection];
|
||||
// The resources plugin copies a file only when it is newer than the copy; content
|
||||
// replaced without moving the mtime (a sync tool, PowerShell `Copy-Item`) would stay
|
||||
// stale while its stamp is recorded as processed.
|
||||
let mut extra =
|
||||
vec!["-q".to_owned(), "-pl".to_owned(), selection, "-Dmaven.resources.overwrite=true".to_owned()];
|
||||
extra.push("resources:resources".into());
|
||||
if changed.iter().any(|(_, test, _)| *test) {
|
||||
extra.push("resources:testResources".into());
|
||||
@@ -758,244 +1055,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
|
||||
|
||||
@@ -105,13 +105,26 @@ impl ProjectModel {
|
||||
}
|
||||
|
||||
/// Why the IDE can't compile this project with javac itself, if it can't.
|
||||
pub fn unsupported(&self, test: bool) -> Option<String> {
|
||||
pub fn unsupported(&self, test: bool, ignored_maven_compile_goals: &[String]) -> Option<String> {
|
||||
// What the build tool couldn't resolve or read: the model would be incomplete.
|
||||
if let Some(problem) = self.problems.first() {
|
||||
return Some(format!("{}: {problem}", self.artifact_id));
|
||||
}
|
||||
if !self.other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
|
||||
// Keep the recorded model intact: adding or removing a project override must also
|
||||
// affect an already prepared model. Gradle tasks never use Maven overrides.
|
||||
let other_compilers: Vec<&str> = self
|
||||
.other_compilers
|
||||
.iter()
|
||||
.filter(|execution| {
|
||||
!(self.gradle_path.is_none()
|
||||
&& execution.split_once('@').is_some_and(|(goal, _)| {
|
||||
ignored_maven_compile_goals.iter().any(|ignored| ignored.trim() == goal)
|
||||
}))
|
||||
})
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
if !other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, other_compilers.join(", ")));
|
||||
}
|
||||
if test && !self.test_generators.is_empty() {
|
||||
return Some(format!(
|
||||
|
||||
@@ -55,6 +55,75 @@ fn maven_resources_select_projects_by_coordinates_not_by_basedir() {
|
||||
assert_eq!(maven_project_selection(projects.iter()), "org.starry:cloud,org.starry:organ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_apply_to_cached_models_and_can_be_removed() {
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{goal}@default-jar"), format!("{goal}@extra-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
let cached: ProjectModel = serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap();
|
||||
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
|
||||
assert_eq!(cached.unsupported(false, &[goal.into()]), None);
|
||||
assert_eq!(cached.unsupported(false, &[format!(" {goal} ")]), None);
|
||||
assert!(cached.unsupported(false, &[]).unwrap().contains(goal));
|
||||
assert_eq!(cached.other_compilers, project.other_compilers);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_match_exact_goals_and_keep_other_executions() {
|
||||
let jar = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let kotlin = "org.jetbrains.kotlin:kotlin-maven-plugin:compile";
|
||||
let mut project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{jar}@default-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
for unmatched in [
|
||||
"",
|
||||
"*",
|
||||
"org.apache.maven.plugins:maven-jar-plugin",
|
||||
"maven-jar-plugin:jar",
|
||||
"org.apache.maven.plugins:maven-jar-plugin:test-jar",
|
||||
"org.apache.maven.plugins:*:jar",
|
||||
] {
|
||||
assert!(project.unsupported(false, &[unmatched.into()]).is_some(), "{unmatched}");
|
||||
}
|
||||
project.other_compilers.push(format!("{kotlin}@compile"));
|
||||
let reason = project.unsupported(false, &[jar.into()]).unwrap();
|
||||
assert!(reason.contains(kotlin));
|
||||
assert!(!reason.contains(jar));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maven_compile_goal_overrides_do_not_affect_gradle_or_other_safety_checks() {
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
let ignored = [goal.into()];
|
||||
let mut project = ProjectModel {
|
||||
artifact_id: "app".into(),
|
||||
other_compilers: vec![format!("{goal}@default-jar")],
|
||||
..Default::default()
|
||||
};
|
||||
project.gradle_path = Some(":app".into());
|
||||
assert!(project.unsupported(false, &ignored).is_some());
|
||||
project.gradle_path = None;
|
||||
project.problems.push("unresolved dependency".into());
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("unresolved dependency"));
|
||||
project.problems.clear();
|
||||
project.test_generators.push("org.example:generator:test@tests".into());
|
||||
assert_eq!(project.unsupported(false, &ignored), None);
|
||||
assert!(project.unsupported(true, &ignored).unwrap().contains("generates test sources"));
|
||||
project.test_generators.clear();
|
||||
project.main.compiler = Some(CompilerConfig { compiler_id: Some("eclipse".into()), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("eclipse"));
|
||||
project.main.compiler = Some(CompilerConfig { multi_release_output: Some(true), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("multi-release"));
|
||||
project.main.compiler =
|
||||
Some(CompilerConfig { processor_path_error: Some("missing processor".into()), ..Default::default() });
|
||||
assert!(project.unsupported(false, &ignored).unwrap().contains("missing processor"));
|
||||
}
|
||||
|
||||
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
|
||||
fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
|
||||
@@ -169,6 +238,17 @@ impl Fixture {
|
||||
}
|
||||
|
||||
fn build(&self, target: Target) -> LaunchOutputs {
|
||||
match self.try_build(target, &[]) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn try_build(&self, target: Target, ignored_maven_compile_goals: &[String]) -> IdeResult<Built> {
|
||||
let jdk = |_: Option<u32>| None;
|
||||
let build = JavaBuild {
|
||||
root: &self.root,
|
||||
@@ -177,18 +257,12 @@ impl Fixture {
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
ignored_maven_compile_goals,
|
||||
service: &self.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
let output = build_output_tail(&self.events.lock().unwrap());
|
||||
panic!("unsupported: {reason}\n{output}");
|
||||
}
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event)
|
||||
}
|
||||
|
||||
/// The steps of the launch builds since the last call.
|
||||
@@ -213,6 +287,37 @@ impl Fixture {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_maven_compile_goal_can_be_skipped_with_a_cached_reactor() {
|
||||
let pom = APP_POM.replace(
|
||||
"</build>",
|
||||
concat!(
|
||||
"<plugins><plugin><groupId>org.apache.maven.plugins</groupId>",
|
||||
"<artifactId>maven-jar-plugin</artifactId><version>3.4.1</version>",
|
||||
"<executions><execution><id>early-jar</id><phase>compile</phase>",
|
||||
"<goals><goal>jar</goal></goals></execution></executions></plugin></plugins></build>",
|
||||
),
|
||||
);
|
||||
let Some(f) = Fixture::new(&[
|
||||
("app/pom.xml", &pom),
|
||||
("lib/src/main/java/l/L.java", "package l; public class L {}"),
|
||||
("app/src/main/java/a/A.java", "package a; public class A { l.L dependency; }"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let module = f.root.join("app");
|
||||
let go = |ignored: &[String]| f.try_build(Target::Launch { module: &module, test: false }, ignored).unwrap();
|
||||
let goal = "org.apache.maven.plugins:maven-jar-plugin:jar";
|
||||
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
|
||||
f.steps();
|
||||
let Built::Done(output) = go(&[goal.into()]) else { panic!("expected the configured build to use javac") };
|
||||
assert!(output.failure.is_none(), "{:?}", output.messages);
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
assert!(!f.root.join("app/target/app-1.jar").exists());
|
||||
assert!(f.steps().iter().all(|step| step.starts_with("javac")), "the prepared model was reused");
|
||||
assert!(matches!(go(&[]), Built::Unsupported(reason) if reason.contains(goal)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
@@ -258,6 +363,8 @@ fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl t:app"), "{steps:?}");
|
||||
// #7340: content replaced without a newer mtime is copied too.
|
||||
assert!(steps[0].contains("-Dmaven.resources.overwrite=true"), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
|
||||
|
||||
// A deleted source leaves no class behind.
|
||||
@@ -581,6 +688,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,
|
||||
};
|
||||
|
||||
@@ -1555,7 +1555,9 @@ pub fn load_with_linked_jdk(
|
||||
.as_deref()
|
||||
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
|
||||
let path = i(path);
|
||||
(!path.contains("${") && Path::new(&path).is_absolute()).then(|| PathBuf::from(path))
|
||||
// Rebuilt from its components: `${pom.basedir}/lib/x.jar` on Windows mixes `\\` and `/`.
|
||||
(!path.contains("${") && Path::new(&path).is_absolute())
|
||||
.then(|| Path::new(&path).components().collect::<PathBuf>())
|
||||
})
|
||||
.collect();
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ objc2-app-kit = { version = "0.3", default-features = false, features = ["std",
|
||||
png = "0.18"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
gtk = "0.18"
|
||||
gtk = "0.19"
|
||||
|
||||
[dev-dependencies]
|
||||
png = "0.18"
|
||||
@@ -175,7 +175,7 @@ impl CliTool {
|
||||
Poll::Finished => break,
|
||||
}
|
||||
}
|
||||
Ok((lines.finish(cancel)?, stderr_tail))
|
||||
Ok((lines.finish(cancel)?.success(), stderr_tail))
|
||||
}
|
||||
|
||||
/// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself
|
||||
@@ -301,9 +301,9 @@ impl Lines {
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for the child to exit and returns whether it did so successfully. Fails, after
|
||||
/// killing it, when `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<bool> {
|
||||
/// Waits for the child to exit and returns how it exited. Fails, after killing it, when
|
||||
/// `cancel` fires first.
|
||||
pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult<std::process::ExitStatus> {
|
||||
let status = loop {
|
||||
if let Some(status) = self.child.try_wait()? {
|
||||
break status;
|
||||
@@ -314,6 +314,6 @@ impl Lines {
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
Ok(status.success())
|
||||
Ok(status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! The CMake File API queries the IDE writes into a build directory, shared by the run
|
||||
//! configurations (which read the replies) and Build Project (which configures).
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
/// The objects asked for: targets, cache, toolchains and the CMake files.
|
||||
pub const QUERIES: [&str; 4] = ["codemodel-v2", "cache-v2", "toolchains-v1", "cmakeFiles-v1"];
|
||||
const QUERY: &str = ".cmake/api/v1/query/client-openidea";
|
||||
/// Where CMake writes its replies, relative to the build directory.
|
||||
pub const REPLY: &str = ".cmake/api/v1/reply";
|
||||
|
||||
/// Asks CMake to answer [`QUERIES`] on the next configure of `build`.
|
||||
pub fn write_queries(build: &Path) -> std::io::Result<()> {
|
||||
let query = build.join(QUERY);
|
||||
std::fs::create_dir_all(&query)?;
|
||||
for name in QUERIES {
|
||||
std::fs::write(query.join(name), "")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -401,6 +401,8 @@ impl Default for CodeEditingSettings {
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct InlayHintsSettings {
|
||||
pub types: bool,
|
||||
/// Inferred variable and field types from the JavaScript and TypeScript servers (on, as in WebStorm).
|
||||
pub js_ts_types: bool,
|
||||
pub parameters: bool,
|
||||
/// Hints of other kinds (chaining, closing labels…).
|
||||
pub other: bool,
|
||||
@@ -436,6 +438,7 @@ impl Default for InlayHintsSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
types: true,
|
||||
js_ts_types: true,
|
||||
parameters: true,
|
||||
other: true,
|
||||
closing_labels: true,
|
||||
@@ -710,6 +713,19 @@ mod folding_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod inlay_hints_tests {
|
||||
use super::InlayHintsSettings;
|
||||
|
||||
#[test]
|
||||
fn existing_settings_enable_js_ts_type_hints_by_default() {
|
||||
let settings: InlayHintsSettings = serde_json::from_str(r#"{"parameters":false}"#).unwrap();
|
||||
assert!(settings.types);
|
||||
assert!(settings.js_ts_types);
|
||||
assert!(!settings.parameters);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sticky_lines_tests {
|
||||
use super::CodeEditingSettings;
|
||||
|
||||
@@ -11,6 +11,14 @@ use specta::Type;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The execution target recorded with an MCP agent run.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum McpAgentRunTarget {
|
||||
Host,
|
||||
Container { id: String },
|
||||
}
|
||||
|
||||
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
|
||||
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
|
||||
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
|
||||
@@ -42,6 +50,7 @@ pub enum McpUiRequest {
|
||||
command: String,
|
||||
cwd: crate::IpcPath,
|
||||
env: BTreeMap<String, String>,
|
||||
target: McpAgentRunTarget,
|
||||
},
|
||||
RunConfiguration {
|
||||
#[specta(type = specta_typescript::Unknown)]
|
||||
@@ -99,6 +108,8 @@ pub enum IdeEvent {
|
||||
WindowGroupsChanged,
|
||||
/// A project was loaded or unloaded for the MCP server without a window of its own.
|
||||
McpBackgroundProjectsChanged,
|
||||
/// Agent automations, run history, or session schedules changed on the host.
|
||||
AutomationsChanged,
|
||||
/// A window entered or left full screen, itself or as a member of a full-screen window group.
|
||||
WindowFullscreenChanged,
|
||||
/// This remote window's connection ended or another window took over the session.
|
||||
@@ -106,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,
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
pub mod build_jobs;
|
||||
pub mod cli_process;
|
||||
pub mod cmake_file_api;
|
||||
pub mod editor_settings;
|
||||
pub mod error;
|
||||
pub mod event;
|
||||
|
||||
@@ -83,6 +83,24 @@ pub fn own_group(cmd: &mut Command) -> &mut Command {
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Starts the child as the leader of a session of its own on Unix. Like [`own_group`] it leads
|
||||
/// its process group, so [`kill_tree`] and [`terminate_tree`] reach what it starts; unlike it,
|
||||
/// the child has no controlling terminal, so a tool that would ask on `/dev/tty` (and be
|
||||
/// stopped there as a background job when the app was started from a shell) falls back to
|
||||
/// its pipes. Use it in place of `own_group`: a group leader cannot start a session. A no-op
|
||||
/// elsewhere.
|
||||
pub fn own_session(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
// SAFETY: `setsid` is async-signal-safe and touches none of the parent's memory.
|
||||
unsafe {
|
||||
cmd.pre_exec(|| if libc::setsid() == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) });
|
||||
}
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
/// Kills the child and everything it started, then reaps it.
|
||||
///
|
||||
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
|
||||
@@ -970,6 +988,28 @@ fn append_path_entries(path: &OsStr, extra: &OsStr) -> OsString {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn own_session_leaves_the_controlling_terminal_behind() {
|
||||
// `ps` prints `?` (Linux) or `??` (macOS) for a process without a controlling terminal.
|
||||
let mut cmd = Command::new("sh");
|
||||
cmd.args(["-c", "ps -o tty= -p $$"]);
|
||||
let out = own_session(&mut cmd).output().unwrap();
|
||||
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(String::from_utf8_lossy(&out.stdout).trim().chars().all(|c| c == '?'), "{:?}", out.stdout);
|
||||
// Without a terminal (CI) the line above holds anyway: the child must lead a session
|
||||
// of its own, which only `setsid` makes it.
|
||||
let mut cmd = Command::new("sleep");
|
||||
cmd.arg("5");
|
||||
let mut child = own_session(&mut cmd).spawn().unwrap();
|
||||
let pid = libc::pid_t::try_from(child.id()).unwrap();
|
||||
// SAFETY: plain syscall on a child not reaped yet.
|
||||
let session = unsafe { libc::getsid(pid) };
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
assert_eq!(session, pid, "the child leads its own session");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_alive_tells_live_from_dead_pids() {
|
||||
assert!(process_alive(std::process::id()));
|
||||
|
||||
@@ -5,6 +5,29 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const SEARCH_DEPTH: usize = 3;
|
||||
|
||||
/// Folders that hold dependencies or build output rather than the project's own builds: hidden
|
||||
/// folders (`.build`, `.git`), package checkouts (`node_modules`, `SourcePackages`, `Pods`,
|
||||
/// `Carthage`) and build products (`target`, `build`, `DerivedData`, …).
|
||||
pub fn is_skipped_dir(name: &str) -> bool {
|
||||
name.starts_with('.')
|
||||
|| matches!(
|
||||
name,
|
||||
"node_modules"
|
||||
| "target"
|
||||
| "build"
|
||||
| "dist"
|
||||
| "vendor"
|
||||
| "out"
|
||||
| "bin"
|
||||
| "obj"
|
||||
| "venv"
|
||||
| "SourcePackages"
|
||||
| "Pods"
|
||||
| "Carthage"
|
||||
| "DerivedData"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn children(dir: &Path) -> Vec<PathBuf> {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut dirs: Vec<_> = entries
|
||||
@@ -13,13 +36,7 @@ pub fn children(dir: &Path) -> Vec<PathBuf> {
|
||||
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
return false;
|
||||
}
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
!name.starts_with('.')
|
||||
&& !matches!(
|
||||
name.as_ref(),
|
||||
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
|
||||
)
|
||||
!is_skipped_dir(&entry.file_name().to_string_lossy())
|
||||
})
|
||||
.map(|entry| entry.path())
|
||||
.collect();
|
||||
|
||||
@@ -68,6 +68,8 @@ pub struct Settings {
|
||||
/// Build, Execution, Deployment › Run Targets.
|
||||
pub run_targets: Vec<RunTarget>,
|
||||
pub cmake: CMakeSettings,
|
||||
/// Build, Execution, Deployment › Toolchains; the first is the default.
|
||||
pub toolchains: Vec<Toolchain>,
|
||||
/// Settings › Agents.
|
||||
pub agents: AgentSettings,
|
||||
/// Agents › MCP Server (global only).
|
||||
@@ -170,6 +172,15 @@ pub struct AgentSettings {
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentMemorySettings)]
|
||||
pub memory: AgentMemorySettings,
|
||||
/// Agent plugin bundle policies (`[agents.plugins]`): registered marketplaces and non-sensitive
|
||||
/// config. Enablement lives in each harness's native config; capability consent is stored per machine.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentPluginSettings)]
|
||||
pub plugins: AgentPluginSettings,
|
||||
/// Scheduled agent automations and headless scheduler host policies (`[agents.automations]`).
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AgentAutomationSettings)]
|
||||
pub automations: AgentAutomationSettings,
|
||||
}
|
||||
|
||||
impl Default for AgentSettings {
|
||||
@@ -202,6 +213,8 @@ impl Default for AgentSettings {
|
||||
mcp_servers: BTreeMap::new(),
|
||||
skills: BTreeMap::new(),
|
||||
memory: AgentMemorySettings::default(),
|
||||
plugins: AgentPluginSettings::default(),
|
||||
automations: AgentAutomationSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -358,6 +371,96 @@ pub struct AgentMemorySettings {
|
||||
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
|
||||
}
|
||||
|
||||
/// One agent plugin bundle's policy in Settings › Agents › Plugins
|
||||
/// (`[agents.plugins.entries."<harness>:<plugin>@<marketplace>"]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentPluginEntryPolicy {
|
||||
/// Non-sensitive `userConfig` / `variables` key-value pairs; sensitive values live in OS Keychain.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub config: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// Agent plugin bundle settings (`[agents.plugins]`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentPluginSettings {
|
||||
/// Registered plugin marketplaces (`owner/repo[#ref]`, GitHub URL, or local directory/manifest path).
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub marketplaces: Vec<String>,
|
||||
/// Per-plugin non-sensitive native option hints, keyed by `<harness>:<plugin>@<marketplace>`.
|
||||
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
|
||||
#[specta(type = BTreeMap<String, AgentPluginEntryPolicy>)]
|
||||
pub entries: BTreeMap<String, AgentPluginEntryPolicy>,
|
||||
}
|
||||
|
||||
/// When OpenIDEA holds an OS idle-sleep assertion during active automation turns.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutomationPreventSleep {
|
||||
/// Prevent idle sleep while plugged into AC power.
|
||||
#[default]
|
||||
Ac,
|
||||
/// Prevent idle sleep whenever an automated turn is running.
|
||||
Always,
|
||||
/// Never hold an idle-sleep assertion.
|
||||
Never,
|
||||
}
|
||||
|
||||
/// What the scheduler does when one or more scheduled occurrences fell due while asleep or offline.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AutomationMisfirePolicy {
|
||||
/// Coalesce all missed occurrences into at most one catch-up run once awake and online.
|
||||
#[default]
|
||||
RunOnce,
|
||||
/// Skip missed occurrences and advance to the next future slot.
|
||||
Skip,
|
||||
}
|
||||
|
||||
/// Agent automation and headless scheduler settings (`[agents.automations]`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct AgentAutomationSettings {
|
||||
/// Automatically register the headless login/boot scheduler service while at least one
|
||||
/// automation is enabled, and unregister it when none remain enabled.
|
||||
pub auto_start_service: bool,
|
||||
/// Keep the local OpenIDEA host alive in the background when windows close while local
|
||||
/// automations are enabled.
|
||||
pub keep_alive_in_background: bool,
|
||||
/// Prevent system idle sleep while an automated turn is running.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutomationPreventSleep)]
|
||||
pub prevent_sleep: AutomationPreventSleep,
|
||||
/// Default policy for scheduled occurrences missed during sleep, offline downtime, or reboot.
|
||||
#[serde(deserialize_with = "or_default")]
|
||||
#[specta(type = AutomationMisfirePolicy)]
|
||||
pub misfire_policy: AutomationMisfirePolicy,
|
||||
/// Keep `openidea-server --daemon` alive across disconnects while the remote host has
|
||||
/// enabled scheduled automations.
|
||||
pub keep_remote_daemon_alive: bool,
|
||||
/// Automatically remove temporary automation worktrees when a run finishes with zero diff
|
||||
/// and zero commits.
|
||||
pub auto_clean_worktrees: bool,
|
||||
/// Maximum retained non-clean automation worktrees per automation before pruning oldest
|
||||
/// finished ones.
|
||||
pub max_dirty_worktrees: u32,
|
||||
}
|
||||
|
||||
impl Default for AgentAutomationSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
auto_start_service: false,
|
||||
keep_alive_in_background: true,
|
||||
prevent_sleep: AutomationPreventSleep::Ac,
|
||||
misfire_policy: AutomationMisfirePolicy::RunOnce,
|
||||
keep_remote_daemon_alive: true,
|
||||
auto_clean_worktrees: true,
|
||||
max_dirty_worktrees: 5,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A hand-edited value these settings don't know reads as the default, rather than
|
||||
/// failing the whole settings file.
|
||||
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
|
||||
@@ -602,6 +705,8 @@ pub struct ToolDownloadSettings {
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
/// The managed Vue Language Server release. Empty selects it from the project's Vue dependency.
|
||||
pub vue_language_server_version: String,
|
||||
}
|
||||
|
||||
/// Settings › Settings Sync: the Git repository the IDE settings sync through, and what syncs.
|
||||
@@ -649,9 +754,42 @@ impl Default for SettingsSyncSettings {
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CMakeSettings {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
/// Serialized as `null` when absent, so `cmake.profiles` stays a known settings key.
|
||||
#[specta(optional)]
|
||||
pub profiles: Option<Vec<CMakeProfile>>,
|
||||
/// `true` ignores `CMakePresets.json` / `CMakeUserPresets.json`; otherwise every visible
|
||||
/// configure preset whose condition holds is listed after the explicit profiles.
|
||||
pub ignore_presets: bool,
|
||||
/// Configure presets (by name) enabled as profiles. As in CLion, a preset is listed but
|
||||
/// disabled until enabled here.
|
||||
pub enabled_presets: Vec<String>,
|
||||
/// The profile (by name) that build, run and debug use, as CLion's toolbar switcher;
|
||||
/// empty or unknown = the first enabled one.
|
||||
pub active_profile: String,
|
||||
}
|
||||
|
||||
/// The presets a profile made from `CMakePresets.json` runs with.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct CMakePresetRef {
|
||||
pub configure: String,
|
||||
/// The first build preset of `configure`, used by `cmake --build --preset`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub build: Option<String>,
|
||||
/// The first test preset of `configure`, used by `ctest --preset`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub test: Option<String>,
|
||||
/// Cache variables the resolved preset sets itself, read when presets are loaded (never
|
||||
/// saved): a toolchain does not override them.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub cache_variables: Vec<String>,
|
||||
/// The preset names a toolchain file, which picks the compilers.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub toolchain_file: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
@@ -665,6 +803,23 @@ pub struct CMakeProfile {
|
||||
pub build_dir: String,
|
||||
pub build_args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// `false` keeps the profile listed but unused (CLion's "Enable profile").
|
||||
pub enabled: bool,
|
||||
/// Toolchain name (Settings › Toolchains); empty = the default (first) toolchain.
|
||||
pub toolchain: String,
|
||||
/// Set only on the profiles made from presets: configure with `cmake --preset`, and the
|
||||
/// generator and cache variables come from the preset.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[specta(optional)]
|
||||
pub preset: Option<CMakePresetRef>,
|
||||
/// Resolved from the toolchain when profiles are put to use (never saved): the `cmake`
|
||||
/// to run (`ctest` next to it) and the debugger to prefer.
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub cmake_program: Option<std::path::PathBuf>,
|
||||
#[serde(skip)]
|
||||
#[specta(skip)]
|
||||
pub debugger: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for CMakeProfile {
|
||||
@@ -677,10 +832,44 @@ impl Default for CMakeProfile {
|
||||
build_dir: String::new(),
|
||||
build_args: Vec::new(),
|
||||
env: BTreeMap::new(),
|
||||
enabled: true,
|
||||
toolchain: String::new(),
|
||||
preset: None,
|
||||
cmake_program: None,
|
||||
debugger: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ToolchainKind {
|
||||
/// Tools from the chosen paths, else from `PATH`.
|
||||
#[default]
|
||||
System,
|
||||
/// A MinGW / MSYS2 directory: its `bin` goes first on `PATH`, with gcc, g++,
|
||||
/// mingw32-make and gdb from there.
|
||||
#[serde(rename = "mingw")]
|
||||
MinGw,
|
||||
}
|
||||
|
||||
/// Build, Execution, Deployment › Toolchains (IDE-wide, as in CLion). Empty fields are
|
||||
/// detected: from the MinGW directory, else from `PATH`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Toolchain {
|
||||
pub name: String,
|
||||
pub kind: ToolchainKind,
|
||||
/// The MinGW directory (the one holding `bin`).
|
||||
pub path: String,
|
||||
pub cmake: String,
|
||||
/// `CMAKE_MAKE_PROGRAM`: make, mingw32-make or ninja.
|
||||
pub build_tool: String,
|
||||
pub c_compiler: String,
|
||||
pub cxx_compiler: String,
|
||||
pub debugger: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ToolSettings {
|
||||
@@ -792,6 +981,7 @@ impl Default for Settings {
|
||||
deployment: DeploymentSettings::default(),
|
||||
run_targets: Vec::new(),
|
||||
cmake: CMakeSettings::default(),
|
||||
toolchains: Vec::new(),
|
||||
agents: AgentSettings::default(),
|
||||
mcp_server: McpServerSettings::default(),
|
||||
agent_security: AgentSecuritySettings::default(),
|
||||
@@ -1240,6 +1430,10 @@ pub struct CustomColorScheme {
|
||||
pub struct EditorSettings {
|
||||
pub font_family: String,
|
||||
pub font_size: f32,
|
||||
/// Largest document (in MiB) eligible for syntax analysis and language-server features.
|
||||
#[serde(deserialize_with = "code_insight_limit_mb")]
|
||||
#[specta(type = u8)]
|
||||
pub max_code_insight_file_size_mb: u8,
|
||||
pub line_height: f32,
|
||||
pub tab_size: u32,
|
||||
pub insert_spaces: bool,
|
||||
@@ -1293,11 +1487,23 @@ pub struct EditorSettings {
|
||||
pub encodings: EncodingSettings,
|
||||
}
|
||||
|
||||
pub const DEFAULT_CODE_INSIGHT_LIMIT_MB: u8 = 5;
|
||||
pub const MAX_CODE_INSIGHT_LIMIT_MB: u8 = 50;
|
||||
|
||||
fn code_insight_limit_mb<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u8, D::Error> {
|
||||
Ok(serde_json::Value::deserialize(d)?
|
||||
.as_u64()
|
||||
.and_then(|n| u8::try_from(n).ok())
|
||||
.filter(|n| (1..=MAX_CODE_INSIGHT_LIMIT_MB).contains(n))
|
||||
.unwrap_or(DEFAULT_CODE_INSIGHT_LIMIT_MB))
|
||||
}
|
||||
|
||||
impl Default for EditorSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
font_family: "JetBrains Mono".into(),
|
||||
font_size: 13.0,
|
||||
max_code_insight_file_size_mb: DEFAULT_CODE_INSIGHT_LIMIT_MB,
|
||||
line_height: 22.0,
|
||||
tab_size: 4,
|
||||
insert_spaces: true,
|
||||
@@ -1509,6 +1715,9 @@ pub struct MarkdownSettings {
|
||||
pub preview_layout: MarkdownPreviewLayout,
|
||||
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
|
||||
pub preview_font_size: Option<u32>,
|
||||
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
|
||||
/// trusted projects, or stay in static safe mode.
|
||||
pub mdx_execution: MdxExecutionPolicy,
|
||||
/// "Detect commands that can be run right from Markdown files": gutter run icons on
|
||||
/// shell code blocks and on command lines in code blocks.
|
||||
pub run_commands: bool,
|
||||
@@ -1521,12 +1730,22 @@ impl Default for MarkdownSettings {
|
||||
Self {
|
||||
preview_layout: MarkdownPreviewLayout::default(),
|
||||
preview_font_size: None,
|
||||
mdx_execution: MdxExecutionPolicy::default(),
|
||||
run_commands: true,
|
||||
command_directory: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MdxExecutionPolicy {
|
||||
#[default]
|
||||
Ask,
|
||||
Trusted,
|
||||
Off,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum MarkdownPreviewLayout {
|
||||
@@ -1935,6 +2154,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.
|
||||
|
||||
@@ -296,6 +296,14 @@ pub struct OutlineItem {
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub visibility: Option<Visibility>,
|
||||
/// Rust `impl Trait for Type`: the trait's name in the header (its last path segment, where go-to-definition lands), from the syntax tree.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub implements: Option<Range>,
|
||||
/// Rust `impl [Trait for] Type`: the implementing type's name (its last path segment), from the syntax tree.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub self_type: Option<Range>,
|
||||
}
|
||||
|
||||
/// Fuzzy-match highlight: indices (in chars of the displayed string) that matched.
|
||||
|
||||
@@ -27,6 +27,35 @@ pub struct VcsSettings {
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
/// Settings › Version Control › Subversion.
|
||||
pub svn: SvnSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › Subversion (`vcs.svn`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct SvnSettings {
|
||||
/// Path to the svn executable; empty = auto-detect.
|
||||
pub executable: String,
|
||||
/// Run svn as if in a terminal: its password, passphrase and certificate prompts open
|
||||
/// dialogs. Off, svn runs with `--non-interactive` and a rejected login asks once.
|
||||
pub interactive: bool,
|
||||
/// Pass `--config-dir config_dir` to every svn command.
|
||||
pub use_custom_config_dir: bool,
|
||||
pub config_dir: String,
|
||||
}
|
||||
|
||||
impl Default for SvnSettings {
|
||||
/// Interactive except on Windows: svn there asks on the console, which an IDE's child
|
||||
/// process has hidden, so a prompt could not be answered (not verified on Windows yet).
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
executable: String::new(),
|
||||
interactive: !cfg!(windows),
|
||||
use_custom_config_dir: false,
|
||||
config_dir: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
@@ -80,6 +109,7 @@ impl Default for VcsSettings {
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
svn: SvnSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -447,12 +477,15 @@ pub struct BuildSettings {
|
||||
pub open_tool_window: String,
|
||||
/// When to focus the Build tool window: `always` | `onError` | `never`.
|
||||
pub focus_tool_window: String,
|
||||
/// Build an Xcode project in the background when xcode-build-server has no build log to read
|
||||
/// yet, so cross-file code insight works before the first Run.
|
||||
pub xcode_index_build: bool,
|
||||
}
|
||||
|
||||
impl Default for BuildSettings {
|
||||
fn default() -> Self {
|
||||
// Builds open the tool window without taking focus.
|
||||
Self { open_tool_window: "always".into(), focus_tool_window: "never".into() }
|
||||
Self { open_tool_window: "always".into(), focus_tool_window: "never".into(), xcode_index_build: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -634,7 +667,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,
|
||||
@@ -674,7 +706,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,
|
||||
|
||||
@@ -508,6 +508,11 @@ fn child_name(configuration: &Value, parent: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// LLDB-based adapters, which debug native programs (and Swift on Apple platforms).
|
||||
fn is_native(adapter: &str) -> bool {
|
||||
matches!(adapter, "lldb-dap" | "codelldb")
|
||||
}
|
||||
|
||||
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
|
||||
/// adapter.
|
||||
pub const RUN_LINK: &str = "__openideaRun";
|
||||
@@ -1050,6 +1055,15 @@ impl DebugManager {
|
||||
if let Some(command) = custom_command(&spec.command) {
|
||||
spec.command = command;
|
||||
}
|
||||
// The debugger of the run configuration's toolchain (a MinGW gdb), over every other choice.
|
||||
if let Some(command) = arguments
|
||||
.as_object_mut()
|
||||
.and_then(|o| o.remove(native::ADAPTER_COMMAND))
|
||||
.and_then(|v| v.as_str().map(str::to_owned))
|
||||
{
|
||||
spec.command = command;
|
||||
spec.pinned = None;
|
||||
}
|
||||
// debugpy: run the adapter with the debuggee's interpreter (venvs carry their own debugpy),
|
||||
// or with the launcher's when the debuggee runs through a manager (`uv run python`).
|
||||
if config.adapter == "debugpy" {
|
||||
@@ -1638,11 +1652,16 @@ impl DebugManager {
|
||||
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
|
||||
}
|
||||
if !graceful && (!own_terminate || killed) {
|
||||
// A native attach to a program a run started for the debugger (an Xcode app launched
|
||||
// with `simctl launch --wait-for-debugger`) ends it too: detached, the app can be
|
||||
// left stopped with the SIGTERM the run's Stop sent while it was traced, and the
|
||||
// simulator then holds its launch (and the next one) forever.
|
||||
let ends_debuggee = s.request == "launch" || (terminate && s.run.is_some() && is_native(&s.adapter));
|
||||
let _ = s
|
||||
.conn
|
||||
.request_timeout(
|
||||
"disconnect",
|
||||
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
|
||||
json!({ "restart": false, "terminateDebuggee": ends_debuggee }),
|
||||
SHUTDOWN_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
@@ -1786,7 +1805,8 @@ impl DebugManager {
|
||||
let mut states = self.states.lock();
|
||||
let Some(slot) = states.get_mut(path).and_then(|v| v.get_mut(index)) else { return false };
|
||||
let next = session::state_from(bp, slot.line);
|
||||
let next = BreakpointState { message: next.message.or_else(|| slot.message.clone()), ..next };
|
||||
let kept = slot.message.clone().filter(|m| !(next.verified && m == session::UNBOUND_NATIVE));
|
||||
let next = BreakpointState { message: next.message.or(kept), ..next };
|
||||
let changed = *slot != next;
|
||||
*slot = next;
|
||||
changed
|
||||
|
||||
@@ -8,6 +8,10 @@ use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Launch argument naming the debugger to run (a toolchain's gdb or lldb-dap), which replaces
|
||||
/// the search: lldb-dap if its name says so, else GDB.
|
||||
pub const ADAPTER_COMMAND: &str = "__adapterCommand";
|
||||
|
||||
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
|
||||
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
|
||||
|
||||
@@ -20,7 +24,16 @@ pub async fn choose(
|
||||
if config.adapter != "lldb-dap" || config.request != "launch" {
|
||||
return Ok(config);
|
||||
}
|
||||
let chosen = config
|
||||
.extra_json
|
||||
.as_deref()
|
||||
.and_then(|e| serde_json::from_str::<Value>(e).ok())
|
||||
.and_then(|e| e[ADAPTER_COMMAND].as_str().map(PathBuf::from));
|
||||
let found = tokio::task::spawn_blocking(move || {
|
||||
if let Some(chosen) = chosen {
|
||||
let name = chosen.file_stem().map(|s| s.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
return if name.contains("lldb-dap") { Found::LldbDap } else { Found::Gdb(chosen) };
|
||||
}
|
||||
if lookup("lldb-dap").is_some() {
|
||||
return Found::LldbDap;
|
||||
}
|
||||
@@ -154,6 +167,19 @@ mod tests {
|
||||
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_toolchain_debugger_replaces_the_search() {
|
||||
let mut launch = cmake_launch();
|
||||
launch.extra_json = Some(json!({"env": ["A=1"], ADAPTER_COMMAND: "/opt/mingw/bin/gdb.exe"}).to_string());
|
||||
// lldb-dap is there, but the toolchain names its GDB (an unknown version is left to GDB).
|
||||
let config = choose(launch, only(&["lldb-dap"])).await.unwrap();
|
||||
assert_eq!(config.adapter, "gdb");
|
||||
assert_eq!(extra(&config)[ADAPTER_COMMAND], "/opt/mingw/bin/gdb.exe", "kept for the adapter launch");
|
||||
let mut launch = cmake_launch();
|
||||
launch.extra_json = Some(json!({ADAPTER_COMMAND: "/opt/llvm/bin/lldb-dap"}).to_string());
|
||||
assert_eq!(choose(launch, only(&[])).await.unwrap().adapter, "lldb-dap");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_any_debugger_says_what_to_install() {
|
||||
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
|
||||
|
||||
@@ -293,6 +293,11 @@ impl Suspension {
|
||||
/// symlinked path (`/tmp/game` while the editor has `/private/tmp/game`).
|
||||
const RESOLVES_PATHS: &[&str] = &["godot"];
|
||||
|
||||
/// LLDB answers a breakpoint it can't bind yet with no reason: the code may simply not be loaded.
|
||||
const NATIVE_ADAPTERS: &[&str] = &["lldb-dap", "codelldb"];
|
||||
/// One literal: the UI looks it up in the text catalogs to translate it.
|
||||
pub(crate) const UNBOUND_NATIVE: &str = "No loaded code at this line yet. If it stays unbound after its module loads, the debug info may record this file under another path (through a symlink, or /tmp for /private/tmp): set a source map from that path to this one";
|
||||
|
||||
impl Session {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
@@ -514,6 +519,9 @@ impl Session {
|
||||
ids.insert(id, (path.to_path_buf(), i));
|
||||
}
|
||||
states[i] = state_from(r, breakpoints[i].line);
|
||||
if !states[i].verified && states[i].message.is_none() && NATIVE_ADAPTERS.contains(&self.adapter.as_str()) {
|
||||
states[i].message = Some(UNBOUND_NATIVE.to_owned());
|
||||
}
|
||||
}
|
||||
Ok(states)
|
||||
}
|
||||
|
||||
@@ -138,6 +138,8 @@ struct Script {
|
||||
output_after_terminate: bool,
|
||||
/// Advertise `supportsTerminateRequest` (java-debug does not, so Stop signals the program).
|
||||
supports_terminate: bool,
|
||||
/// Answer `setBreakpoints` with unverified breakpoints and no reason (LLDB before the code loads).
|
||||
unbound_breakpoints: bool,
|
||||
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
|
||||
hold_set_breakpoints: usize,
|
||||
/// Send a `continued` event right after the first `stopped` one.
|
||||
@@ -220,6 +222,7 @@ impl Default for Script {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
run_in_terminal: None,
|
||||
unbound_breakpoints: false,
|
||||
start_debugging: false,
|
||||
child_request: None,
|
||||
ignore_configuration_done: false,
|
||||
@@ -414,7 +417,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
|
||||
.unwrap()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
|
||||
.map(|(i, b)| json!({"id": i + 1, "verified": !script.unbound_breakpoints, "line": b["line"]}))
|
||||
.collect();
|
||||
ok!(msg, json!({"breakpoints": bps}));
|
||||
}
|
||||
@@ -4019,6 +4022,50 @@ async fn stop_detaches_from_an_attached_program() {
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
/// Xcode Debug: lldb-dap attaches to the app a run launched suspended. Stop ends the app through
|
||||
/// the debugger; detaching would leave it stopped with the run's SIGTERM, holding the simulator.
|
||||
#[tokio::test]
|
||||
async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
|
||||
let h = harness(Script::default());
|
||||
let linked = |adapter: &str| LaunchConfig {
|
||||
adapter: adapter.into(),
|
||||
request: "attach".into(),
|
||||
extra_json: Some(json!({ RUN_LINK: 7, "pid": 4242 }).to_string()),
|
||||
..config()
|
||||
};
|
||||
let id = h.start(linked("lldb-dap")).await.unwrap();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], true);
|
||||
|
||||
// Another adapter's attach to a run (a Gradle test worker JVM) still only detaches.
|
||||
let h = harness(Script::default());
|
||||
let id = h.start(linked("debugpy")).await.unwrap();
|
||||
h.manager.stop(id).await.unwrap();
|
||||
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
|
||||
}
|
||||
|
||||
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
|
||||
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
|
||||
#[tokio::test]
|
||||
async fn an_unbound_native_breakpoint_says_why() {
|
||||
for (adapter, hint) in [("lldb-dap", true), ("codelldb", true), ("debugpy", false)] {
|
||||
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
|
||||
h.start(LaunchConfig { adapter: adapter.into(), ..config() }).await.unwrap();
|
||||
let path = PathBuf::from("/private/tmp/app/Counter.swift");
|
||||
let states = h.manager.set_breakpoints(&h.owner.key, path, vec![bp(6)]).await.unwrap();
|
||||
assert!(!states[0].verified);
|
||||
assert_eq!(states[0].message.as_deref() == Some(crate::session::UNBOUND_NATIVE), hint, "{adapter}");
|
||||
}
|
||||
|
||||
// Bound once the module loads (lldb-dap's `breakpoint` event has no message): the hint goes.
|
||||
let path = PathBuf::from("/private/tmp/app/Counter.swift");
|
||||
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
|
||||
h.start(LaunchConfig { adapter: "lldb-dap".into(), ..config() }).await.unwrap();
|
||||
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(6)]).await.unwrap();
|
||||
assert!(h.manager.update_breakpoint_state(&path, 0, &json!({"id": 1, "verified": true, "line": 7})));
|
||||
assert_eq!(h.manager.breakpoint_states(&path)[0].message, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
|
||||
use crate::jvm_memory::test_support::bare_session_of;
|
||||
|
||||
@@ -1355,6 +1355,25 @@ impl DbManager {
|
||||
Self::table_details_on(&pool, Some(catalog), schema, table).await
|
||||
}
|
||||
|
||||
/// Read metadata using an existing connection only. A concurrent disconnect must not
|
||||
/// cause a read-only extension request to reopen a source or prompt for credentials.
|
||||
pub async fn connected_table_details(
|
||||
&self,
|
||||
id: &str,
|
||||
catalog: Option<&str>,
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> IdeResult<TableDetails> {
|
||||
if catalog.is_some() {
|
||||
let source = self.source(id)?;
|
||||
if id != source.id || source.driver != DbDriver::Jdbc || source.vendor != "duckdb" {
|
||||
return Err(IdeError::invalid("Catalog browsing requires a DuckDB data source"));
|
||||
}
|
||||
}
|
||||
let pool = self.connected_pool(id)?;
|
||||
Self::table_details_on(&pool, catalog, schema, table).await
|
||||
}
|
||||
|
||||
pub async fn table_details(&self, id: &str, schema: &str, table: &str) -> IdeResult<TableDetails> {
|
||||
let pool = self.pool(id).await?;
|
||||
Self::table_details_on(&pool, None, schema, table).await
|
||||
@@ -1633,11 +1652,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() {
|
||||
|
||||
@@ -165,6 +165,17 @@ impl DbManager {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Snapshot an existing connection without allocating a slot or opening a route.
|
||||
pub(super) fn connected_pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
|
||||
self.pools
|
||||
.lock()
|
||||
.get(id)
|
||||
.and_then(|slot| slot.value.get())
|
||||
.filter(|connection| !connection.is_closed())
|
||||
.map(|connection| connection.pool.clone())
|
||||
.ok_or_else(|| IdeError::invalid("Connect the data source in the Database tool window first"))
|
||||
}
|
||||
|
||||
pub async fn pool(&self, id: &str) -> IdeResult<Arc<Pool>> {
|
||||
Ok(self.connection(id).await?.pool)
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -24,6 +24,8 @@ pub enum Capability {
|
||||
IdeCommands,
|
||||
/// Manage only its own project database sources and write their credentials.
|
||||
DatabaseSources,
|
||||
/// Read table metadata of connected project sources; never rows or credentials.
|
||||
DatabaseSchema,
|
||||
VcsRead,
|
||||
VcsWrite,
|
||||
/// The Maven / Gradle dependency graph the IDE resolved.
|
||||
@@ -93,6 +95,7 @@ impl Capability {
|
||||
}
|
||||
Self::EditorWrite
|
||||
| Self::DatabaseSources
|
||||
| Self::DatabaseSchema
|
||||
| Self::VcsWrite
|
||||
| Self::Net(_)
|
||||
| Self::NetAsk
|
||||
@@ -130,6 +133,7 @@ impl Capability {
|
||||
Self::EditorWrite => "Change text in the editor".into(),
|
||||
Self::ProjectWrite => "Create and change files in the open project".into(),
|
||||
Self::DatabaseSources => "Manage its own database sources and store their passwords in trusted projects".into(),
|
||||
Self::DatabaseSchema => "Read table structures of connected database sources in trusted projects, without rows or passwords".into(),
|
||||
Self::IdeCommands => "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing".into(),
|
||||
Self::VcsRead => "Read version control state".into(),
|
||||
Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(),
|
||||
@@ -289,6 +293,7 @@ impl fmt::Display for Capability {
|
||||
Self::ProjectWrite => f.write_str("project.write"),
|
||||
Self::IdeCommands => f.write_str("ide.commands"),
|
||||
Self::DatabaseSources => f.write_str("database.sources"),
|
||||
Self::DatabaseSchema => f.write_str("database.schema"),
|
||||
Self::VcsRead => f.write_str("vcs.read"),
|
||||
Self::VcsWrite => f.write_str("vcs.write"),
|
||||
Self::BuildRead => f.write_str("build.read"),
|
||||
@@ -383,6 +388,7 @@ impl FromStr for Capability {
|
||||
"project.write" => Self::ProjectWrite,
|
||||
"ide.commands" => Self::IdeCommands,
|
||||
"database.sources" => Self::DatabaseSources,
|
||||
"database.schema" => Self::DatabaseSchema,
|
||||
"vcs.read" => Self::VcsRead,
|
||||
"vcs.write" => Self::VcsWrite,
|
||||
"build.read" => Self::BuildRead,
|
||||
@@ -677,6 +683,23 @@ mod net_setting_tests {
|
||||
mod database_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn database_schema_is_a_separate_medium_risk_grant_requiring_api20() {
|
||||
let cap: Capability = "database.schema".parse().unwrap();
|
||||
assert_eq!(cap, Capability::DatabaseSchema);
|
||||
assert_eq!(cap.to_string(), "database.schema");
|
||||
assert_eq!(cap.risk(), Risk::Medium);
|
||||
assert!(!cap.auto_migrates());
|
||||
for other in [Capability::ProjectRead, Capability::DatabaseSources] {
|
||||
assert!(!other.covers(&cap));
|
||||
}
|
||||
for (api, valid) in [("^1.19", false), ("^1.20", true)] {
|
||||
let text = format!(
|
||||
"id='schema'\nname='Schema'\nversion='1.0.0'\nengines.openidea='{api}'\n[capabilities]\nrequired=['database.schema']"
|
||||
);
|
||||
assert_eq!(crate::Manifest::parse(&text).is_ok(), valid);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn database_sources_is_a_medium_risk_exact_grant_requiring_api4() {
|
||||
let cap: Capability = "database.sources".parse().unwrap();
|
||||
assert_eq!(cap, Capability::DatabaseSources);
|
||||
|
||||
@@ -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.19.0";
|
||||
pub const ENGINE_VERSION: &str = "1.20.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.
|
||||
@@ -426,6 +426,9 @@ impl Manifest {
|
||||
if matches!(cap, Capability::ClipboardRead) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 11)?;
|
||||
}
|
||||
if matches!(cap, Capability::DatabaseSchema) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 20)?;
|
||||
}
|
||||
if matches!(cap, Capability::Agents) {
|
||||
self.needs_api(&format!("capability `{cap}`"), 18)?;
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ ide-syntax.workspace = true
|
||||
ide-search.workspace = true
|
||||
ide-lsp.workspace = true
|
||||
ide-vcs.workspace = true
|
||||
ide-svn.workspace = true
|
||||
ide-github.workspace = true
|
||||
ide-dap.workspace = true
|
||||
ide-heap.workspace = true
|
||||
|
||||
@@ -111,6 +111,24 @@ impl AgentSecrets {
|
||||
}
|
||||
}
|
||||
|
||||
impl ide_agent::EnvSecrets for AgentSecrets {
|
||||
fn get(&self, key: &str) -> Option<String> {
|
||||
AgentSecrets::get(self, key)
|
||||
}
|
||||
|
||||
fn set(&self, key: &str, value: &str) -> IdeResult<()> {
|
||||
AgentSecrets::set(self, key, value).map(|_| ())
|
||||
}
|
||||
|
||||
fn delete(&self, key: &str) {
|
||||
AgentSecrets::delete(self, key);
|
||||
}
|
||||
|
||||
fn keys(&self, prefix: &str) -> Vec<String> {
|
||||
AgentSecrets::keys(self, prefix)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,775 @@
|
||||
//! Per-user OS login / boot service registration for `openidea-server --scheduler`
|
||||
//! (or `<desktop-exe> --scheduler`).
|
||||
//!
|
||||
//! Off by default (`agents.automations.autoStartService = false`). When the user enables it
|
||||
//! and at least one scheduled automation is active, registers the user login service; when
|
||||
//! disabled or when zero scheduled automations remain (after any in-flight claimed runs finish),
|
||||
//! stops and unregisters the service.
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub const SERVICE_LABEL: &str = "ai.l0ng.openidea.scheduler";
|
||||
pub const SYSTEMD_UNIT_NAME: &str = "openidea-scheduler.service";
|
||||
const WINDOWS_SCRIPT_NAME: &str = "openidea-scheduler.cmd";
|
||||
const OVERRIDE_ENV: &str = "OPENIDEA_BOOT_SERVICE_DIR";
|
||||
const DISABLE_OS_CALLS_ENV: &str = "OPENIDEA_DISABLE_OS_SERVICE_CALLS";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ServicePlatform {
|
||||
Macos,
|
||||
Linux,
|
||||
Windows,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl ServicePlatform {
|
||||
pub fn host() -> Self {
|
||||
if cfg!(target_os = "macos") {
|
||||
Self::Macos
|
||||
} else if cfg!(target_os = "linux") {
|
||||
Self::Linux
|
||||
} else if cfg!(target_os = "windows") {
|
||||
Self::Windows
|
||||
} else {
|
||||
Self::Other
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type CommandRunner = Arc<dyn Fn(&str, &[&str]) -> std::io::Result<(i32, String, String)> + Send + Sync>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct BootServiceManager {
|
||||
sync_lock: Mutex<()>,
|
||||
override_dir: RwLock<Option<PathBuf>>,
|
||||
executable_override: RwLock<Option<PathBuf>>,
|
||||
platform_override: RwLock<Option<ServicePlatform>>,
|
||||
command_runner: RwLock<Option<CommandRunner>>,
|
||||
last_error: Mutex<Option<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BootServiceState {
|
||||
pub kind: String,
|
||||
pub registered: bool,
|
||||
pub path: Option<IpcPath>,
|
||||
pub error: Option<String>,
|
||||
pub linux_linger_enabled: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum OsServicePresence {
|
||||
RegisteredAndActive,
|
||||
RegisteredIdle,
|
||||
ActiveUnregistered,
|
||||
Absent,
|
||||
}
|
||||
|
||||
impl OsServicePresence {
|
||||
fn is_registered(self) -> bool {
|
||||
matches!(self, Self::RegisteredAndActive | Self::RegisteredIdle)
|
||||
}
|
||||
|
||||
fn is_loaded_or_active(self) -> bool {
|
||||
!matches!(self, Self::Absent)
|
||||
}
|
||||
}
|
||||
|
||||
impl BootServiceManager {
|
||||
pub fn with_override_dir(dir: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
sync_lock: Mutex::new(()),
|
||||
override_dir: RwLock::new(dir),
|
||||
executable_override: RwLock::new(None),
|
||||
platform_override: RwLock::new(None),
|
||||
command_runner: RwLock::new(None),
|
||||
last_error: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_override_dir(&self, dir: Option<PathBuf>) {
|
||||
*self.override_dir.write() = dir;
|
||||
}
|
||||
|
||||
pub fn set_executable_override(&self, exe: Option<PathBuf>) {
|
||||
*self.executable_override.write() = exe;
|
||||
}
|
||||
|
||||
pub fn set_command_runner_for_test(&self, platform: ServicePlatform, runner: Option<CommandRunner>) {
|
||||
*self.platform_override.write() = runner.as_ref().map(|_| platform);
|
||||
*self.command_runner.write() = runner;
|
||||
}
|
||||
|
||||
fn effective_platform(&self) -> ServicePlatform {
|
||||
self.platform_override.read().unwrap_or_else(ServicePlatform::host)
|
||||
}
|
||||
|
||||
fn effective_override_dir(&self) -> Option<PathBuf> {
|
||||
self.override_dir
|
||||
.read()
|
||||
.clone()
|
||||
.or_else(|| std::env::var_os(OVERRIDE_ENV).filter(|v| !v.is_empty()).map(PathBuf::from))
|
||||
}
|
||||
|
||||
fn uses_os_commands(&self) -> bool {
|
||||
if self.command_runner.read().is_some() {
|
||||
return true;
|
||||
}
|
||||
self.effective_override_dir().is_none() && std::env::var_os(DISABLE_OS_CALLS_ENV).is_none_or(|v| v != "1")
|
||||
}
|
||||
|
||||
fn run_command(&self, program: &str, args: &[&str]) -> IdeResult<(i32, String, String)> {
|
||||
if let Some(runner) = self.command_runner.read().clone() {
|
||||
return runner(program, args).map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")));
|
||||
}
|
||||
let out = std::process::Command::new(program)
|
||||
.args(args)
|
||||
.output()
|
||||
.map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")))?;
|
||||
let code = out.status.code().unwrap_or(-1);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
|
||||
Ok((code, stdout, stderr))
|
||||
}
|
||||
|
||||
fn run_checked(&self, program: &str, args: &[&str]) -> IdeResult<String> {
|
||||
let (code, stdout, stderr) = self.run_command(program, args)?;
|
||||
if code == 0 {
|
||||
return Ok(stdout);
|
||||
}
|
||||
let detail = stderr.trim();
|
||||
let msg = if detail.is_empty() { stdout.trim() } else { detail };
|
||||
Err(IdeError::internal(format!("{program} {} exited with {code}: {msg}", args.join(" "))))
|
||||
}
|
||||
|
||||
fn scheduler_executable(&self) -> Option<PathBuf> {
|
||||
self.executable_override.read().clone().or_else(|| std::env::current_exe().ok())
|
||||
}
|
||||
|
||||
pub fn service_kind_for(platform: ServicePlatform, remote: bool) -> &'static str {
|
||||
if remote && platform == ServicePlatform::Linux {
|
||||
"systemdUser"
|
||||
} else {
|
||||
match platform {
|
||||
ServicePlatform::Macos => "launchAgent",
|
||||
ServicePlatform::Linux => "systemdUser",
|
||||
ServicePlatform::Windows => "windowsStartup",
|
||||
ServicePlatform::Other => "backgroundHost",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn service_kind(remote: bool) -> &'static str {
|
||||
Self::service_kind_for(ServicePlatform::host(), remote)
|
||||
}
|
||||
|
||||
pub fn service_file_path(&self, home_dir: Option<&Path>) -> Option<PathBuf> {
|
||||
let platform = self.effective_platform();
|
||||
if let Some(dir) = self.effective_override_dir() {
|
||||
let filename = match platform {
|
||||
ServicePlatform::Macos => format!("{SERVICE_LABEL}.plist"),
|
||||
ServicePlatform::Windows => WINDOWS_SCRIPT_NAME.to_owned(),
|
||||
ServicePlatform::Linux | ServicePlatform::Other => SYSTEMD_UNIT_NAME.to_owned(),
|
||||
};
|
||||
return Some(dir.join(filename));
|
||||
}
|
||||
let home = home_dir?;
|
||||
match platform {
|
||||
ServicePlatform::Macos => {
|
||||
Some(home.join("Library").join("LaunchAgents").join(format!("{SERVICE_LABEL}.plist")))
|
||||
}
|
||||
ServicePlatform::Linux => Some(home.join(".config").join("systemd").join("user").join(SYSTEMD_UNIT_NAME)),
|
||||
ServicePlatform::Windows => {
|
||||
let appdata = std::env::var_os("APPDATA")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| home.join("AppData").join("Roaming"));
|
||||
Some(
|
||||
appdata
|
||||
.join("Microsoft")
|
||||
.join("Windows")
|
||||
.join("Start Menu")
|
||||
.join("Programs")
|
||||
.join("Startup")
|
||||
.join(WINDOWS_SCRIPT_NAME),
|
||||
)
|
||||
}
|
||||
ServicePlatform::Other => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn macos_domain() -> String {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
format!("gui/{}", rustix::process::getuid().as_raw())
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
"gui/501".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
/// Queries the OS service manager, distinguishing confirmed `Absent` from `Err(...)` (unknown
|
||||
/// status, e.g. D-Bus / launchd unreachable) so `sync(..., false)` never deletes the service
|
||||
/// file when status cannot be determined.
|
||||
fn query_os_presence(&self, platform: ServicePlatform) -> IdeResult<OsServicePresence> {
|
||||
if !self.uses_os_commands() {
|
||||
return Ok(OsServicePresence::Absent);
|
||||
}
|
||||
match platform {
|
||||
ServicePlatform::Macos => {
|
||||
let job = format!("{}/{SERVICE_LABEL}", Self::macos_domain());
|
||||
let (code, stdout, stderr) = self.run_command("launchctl", &["print", &job])?;
|
||||
if code == 0 {
|
||||
return Ok(OsServicePresence::RegisteredAndActive);
|
||||
}
|
||||
let combined = format!("{stdout}\n{stderr}");
|
||||
if code == 113 || combined.contains("Could not find service") {
|
||||
return Ok(OsServicePresence::Absent);
|
||||
}
|
||||
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
|
||||
Err(IdeError::internal(format!("launchctl print {job} returned unknown status {code}: {detail}")))
|
||||
}
|
||||
ServicePlatform::Linux => {
|
||||
let (en_code, en_out, en_err) =
|
||||
self.run_command("systemctl", &["--user", "is-enabled", SYSTEMD_UNIT_NAME])?;
|
||||
let en_state = en_out.trim();
|
||||
let enabled = if en_code == 0 && matches!(en_state, "enabled" | "enabled-runtime") {
|
||||
true
|
||||
} else if matches!(
|
||||
en_state,
|
||||
"disabled" | "not-found" | "static" | "indirect" | "masked" | "linked" | "generated"
|
||||
) {
|
||||
false
|
||||
} else {
|
||||
let detail = if en_err.trim().is_empty() { en_state } else { en_err.trim() };
|
||||
return Err(IdeError::internal(format!(
|
||||
"systemctl --user is-enabled {SYSTEMD_UNIT_NAME} returned unknown status {en_code}: {detail}"
|
||||
)));
|
||||
};
|
||||
|
||||
let (ac_code, ac_out, ac_err) =
|
||||
self.run_command("systemctl", &["--user", "is-active", SYSTEMD_UNIT_NAME])?;
|
||||
let ac_state = ac_out.trim();
|
||||
let active = if ac_code == 0 && matches!(ac_state, "active" | "activating" | "reloading") {
|
||||
true
|
||||
} else if matches!(ac_state, "inactive" | "failed" | "deactivating") {
|
||||
false
|
||||
} else {
|
||||
let detail = if ac_err.trim().is_empty() { ac_state } else { ac_err.trim() };
|
||||
return Err(IdeError::internal(format!(
|
||||
"systemctl --user is-active {SYSTEMD_UNIT_NAME} returned unknown status {ac_code}: {detail}"
|
||||
)));
|
||||
};
|
||||
|
||||
Ok(match (enabled, active) {
|
||||
(true, true) => OsServicePresence::RegisteredAndActive,
|
||||
(true, false) => OsServicePresence::RegisteredIdle,
|
||||
(false, true) => OsServicePresence::ActiveUnregistered,
|
||||
(false, false) => OsServicePresence::Absent,
|
||||
})
|
||||
}
|
||||
ServicePlatform::Windows | ServicePlatform::Other => Ok(OsServicePresence::Absent),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_os_registered(&self, platform: ServicePlatform, path: &Path) -> bool {
|
||||
if !path.is_file() {
|
||||
return false;
|
||||
}
|
||||
if !self.uses_os_commands() {
|
||||
return true;
|
||||
}
|
||||
match platform {
|
||||
ServicePlatform::Macos | ServicePlatform::Linux => {
|
||||
self.query_os_presence(platform).is_ok_and(OsServicePresence::is_registered)
|
||||
}
|
||||
ServicePlatform::Windows => std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > 0),
|
||||
ServicePlatform::Other => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status(&self, home_dir: Option<&Path>, remote: bool) -> BootServiceState {
|
||||
let platform = self.effective_platform();
|
||||
let path = self.service_file_path(home_dir);
|
||||
let registered = path.as_ref().is_some_and(|p| self.is_os_registered(platform, p));
|
||||
let linux_linger_enabled = if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None };
|
||||
BootServiceState {
|
||||
kind: Self::service_kind_for(platform, remote).to_owned(),
|
||||
registered,
|
||||
path: path.map(IpcPath),
|
||||
error: self.last_error.lock().clone(),
|
||||
linux_linger_enabled,
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronizes the OS user service file and service manager state to match
|
||||
/// `(should_register, base_dir)`. Checks command results, retries activation even when the
|
||||
/// unit/plist file on disk is unchanged, and stops + unloads the worker BEFORE deleting the
|
||||
/// unit/plist file (keeping the file when status is unknown) so failed unregistrations retry.
|
||||
pub fn sync(&self, home_dir: Option<&Path>, base_dir: &Path, should_register: bool) -> IdeResult<BootServiceState> {
|
||||
let _guard = self.sync_lock.lock();
|
||||
let result = self.sync_locked(home_dir, base_dir, should_register);
|
||||
match &result {
|
||||
Ok(_) => *self.last_error.lock() = None,
|
||||
Err(err) => *self.last_error.lock() = Some(err.to_string()),
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn sync_locked(
|
||||
&self,
|
||||
home_dir: Option<&Path>,
|
||||
base_dir: &Path,
|
||||
should_register: bool,
|
||||
) -> IdeResult<BootServiceState> {
|
||||
let platform = self.effective_platform();
|
||||
let Some(target) = self.service_file_path(home_dir) else {
|
||||
return Ok(self.status(home_dir, false));
|
||||
};
|
||||
let use_os = self.uses_os_commands();
|
||||
|
||||
if should_register {
|
||||
let exe = self
|
||||
.scheduler_executable()
|
||||
.ok_or_else(|| IdeError::unavailable("cannot locate OpenIDEA executable for --scheduler"))?;
|
||||
let content = render_service_file_for(platform, &exe, base_dir)?;
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let file_changed = std::fs::read_to_string(&target).ok().as_deref() != Some(content.as_str());
|
||||
if file_changed {
|
||||
ide_vfs::write_atomic(&target, content.as_bytes())?;
|
||||
}
|
||||
if use_os {
|
||||
let already_registered = self.is_os_registered(platform, &target);
|
||||
if file_changed || !already_registered {
|
||||
self.activate_os_service(platform, &target)?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if use_os {
|
||||
// Propagate unknown status BEFORE touching `target` so the file stays for retry!
|
||||
let presence = self.query_os_presence(platform)?;
|
||||
if presence.is_loaded_or_active() || target.exists() {
|
||||
self.deactivate_os_service(platform, presence)?;
|
||||
}
|
||||
}
|
||||
if target.exists() {
|
||||
match std::fs::remove_file(&target) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(BootServiceState {
|
||||
kind: Self::service_kind_for(platform, false).to_owned(),
|
||||
registered: self.is_os_registered(platform, &target),
|
||||
path: Some(IpcPath(target)),
|
||||
error: None,
|
||||
linux_linger_enabled: if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None },
|
||||
})
|
||||
}
|
||||
|
||||
fn activate_os_service(&self, platform: ServicePlatform, path: &Path) -> IdeResult<()> {
|
||||
let path_str = path
|
||||
.to_str()
|
||||
.ok_or_else(|| IdeError::invalid(format!("service file path is not valid UTF-8: {}", path.display())))?;
|
||||
match platform {
|
||||
ServicePlatform::Macos => {
|
||||
let domain = Self::macos_domain();
|
||||
let job = format!("{domain}/{SERVICE_LABEL}");
|
||||
if self.query_os_presence(platform).is_ok_and(OsServicePresence::is_loaded_or_active) {
|
||||
let _ = self.run_command("launchctl", &["bootout", &job]);
|
||||
}
|
||||
self.run_checked("launchctl", &["bootstrap", &domain, path_str])?;
|
||||
Ok(())
|
||||
}
|
||||
ServicePlatform::Linux => {
|
||||
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
|
||||
self.run_checked("systemctl", &["--user", "enable", SYSTEMD_UNIT_NAME])?;
|
||||
Ok(())
|
||||
}
|
||||
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn deactivate_os_service(&self, platform: ServicePlatform, presence: OsServicePresence) -> IdeResult<()> {
|
||||
match platform {
|
||||
ServicePlatform::Macos => {
|
||||
let domain = Self::macos_domain();
|
||||
let job = format!("{domain}/{SERVICE_LABEL}");
|
||||
if presence.is_loaded_or_active() {
|
||||
let (code, stdout, stderr) = self.run_command("launchctl", &["bootout", &job])?;
|
||||
let after = self.query_os_presence(platform)?;
|
||||
if code != 0 && after.is_loaded_or_active() {
|
||||
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
|
||||
return Err(IdeError::internal(format!(
|
||||
"launchctl bootout {job} exited with {code}: {detail}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
ServicePlatform::Linux => {
|
||||
match presence {
|
||||
OsServicePresence::RegisteredAndActive | OsServicePresence::RegisteredIdle => {
|
||||
self.run_checked("systemctl", &["--user", "disable", "--now", SYSTEMD_UNIT_NAME])?;
|
||||
}
|
||||
OsServicePresence::ActiveUnregistered => {
|
||||
self.run_checked("systemctl", &["--user", "stop", SYSTEMD_UNIT_NAME])?;
|
||||
}
|
||||
OsServicePresence::Absent => {}
|
||||
}
|
||||
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
|
||||
Ok(())
|
||||
}
|
||||
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render_service_file(exe: &Path, base_dir: &Path) -> IdeResult<String> {
|
||||
render_service_file_for(ServicePlatform::host(), exe, base_dir)
|
||||
}
|
||||
|
||||
pub fn render_service_file_for(platform: ServicePlatform, exe: &Path, base_dir: &Path) -> IdeResult<String> {
|
||||
match platform {
|
||||
ServicePlatform::Macos => render_macos_plist(exe, base_dir),
|
||||
ServicePlatform::Windows => render_windows_cmd(exe, base_dir),
|
||||
ServicePlatform::Linux | ServicePlatform::Other => render_systemd_unit(exe, base_dir),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_roundtrip_path<'a>(path: &'a Path, label: &str) -> IdeResult<&'a str> {
|
||||
let s = path.to_str().ok_or_else(|| IdeError::invalid(format!("{label} path is not valid UTF-8")))?;
|
||||
if s.is_empty() {
|
||||
return Err(IdeError::invalid(format!("{label} path cannot be empty")));
|
||||
}
|
||||
let has_root = path.is_absolute() || s.starts_with('/') || (s.len() >= 3 && s.as_bytes()[1] == b':');
|
||||
if !has_root {
|
||||
return Err(IdeError::invalid(format!("{label} path must be absolute: {s}")));
|
||||
}
|
||||
if s.chars().any(char::is_control) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"{label} path contains control characters or line breaks that cannot round-trip in a service file"
|
||||
)));
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
pub fn render_macos_plist(exe: &Path, base_dir: &Path) -> IdeResult<String> {
|
||||
let exe_str = validate_roundtrip_path(exe, "scheduler executable")?;
|
||||
let home_str = validate_roundtrip_path(base_dir, "scheduler data")?;
|
||||
let log_path = base_dir.join("logs").join("scheduler.log");
|
||||
let log_str = validate_roundtrip_path(&log_path, "scheduler log")?;
|
||||
let exe_esc = xml_escape(exe_str);
|
||||
let home_esc = xml_escape(home_str);
|
||||
let log_esc = xml_escape(log_str);
|
||||
Ok(format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>{SERVICE_LABEL}</string>
|
||||
<key>AssociatedBundleIdentifiers</key>
|
||||
<array>
|
||||
<string>ai.l0ng.openidea</string>
|
||||
</array>
|
||||
<key>LimitLoadToSessionType</key>
|
||||
<string>Aqua</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>{exe_esc}</string>
|
||||
<string>--scheduler</string>
|
||||
</array>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>OPENIDEA_SERVER_HOME</key>
|
||||
<string>{home_esc}</string>
|
||||
</dict>
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
<key>StandardErrorPath</key>
|
||||
<string>{log_esc}</string>
|
||||
</dict>
|
||||
</plist>
|
||||
"#
|
||||
))
|
||||
}
|
||||
|
||||
pub fn render_systemd_unit(exe: &Path, base_dir: &Path) -> IdeResult<String> {
|
||||
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
|
||||
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
|
||||
// Both `Environment=` and the executable path (`argv[0]`) of `ExecStart=` are resolved before
|
||||
// `$` variable expansion (`systemd.exec(5)`, `systemd.service(5)`), so `$` stays literal!
|
||||
let exe_str = systemd_escape_literal_quoted(exe_raw);
|
||||
let home_str = systemd_escape_literal_quoted(home_raw);
|
||||
Ok(format!(
|
||||
"[Unit]\n\
|
||||
Description=OpenIDEA Headless Agent Automation Scheduler\n\
|
||||
After=network-online.target\n\
|
||||
\n\
|
||||
[Service]\n\
|
||||
Type=simple\n\
|
||||
Environment=\"OPENIDEA_SERVER_HOME={home_str}\"\n\
|
||||
ExecStart=\"{exe_str}\" --scheduler\n\
|
||||
Restart=on-failure\n\
|
||||
RestartSec=10\n\
|
||||
\n\
|
||||
[Install]\n\
|
||||
WantedBy=default.target\n"
|
||||
))
|
||||
}
|
||||
|
||||
pub fn render_windows_cmd(exe: &Path, base_dir: &Path) -> IdeResult<String> {
|
||||
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
|
||||
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
|
||||
if exe_raw.contains('"') || home_raw.contains('"') {
|
||||
return Err(IdeError::invalid("Windows Startup script path cannot contain '\"'"));
|
||||
}
|
||||
let home_esc = cmd_escape(home_raw);
|
||||
let exe_esc = cmd_escape(exe_raw);
|
||||
Ok(format!("@echo off\r\nset \"OPENIDEA_SERVER_HOME={home_esc}\"\r\nstart \"\" /B \"{exe_esc}\" --scheduler\r\n"))
|
||||
}
|
||||
|
||||
/// Escapes a double-quoted systemd value where `$` is literal (`Environment="KEY=VALUE"` and
|
||||
/// `ExecStart="EXECUTABLE"` `argv[0]`): specifiers (`%` -> `%%`) and C escapes (`\` -> `\\`,
|
||||
/// `"` -> `\"`) are interpreted, while `$` must remain literal.
|
||||
fn systemd_escape_literal_quoted(s: &str) -> String {
|
||||
s.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%")
|
||||
}
|
||||
|
||||
fn cmd_escape(s: &str) -> String {
|
||||
s.replace('%', "%%")
|
||||
}
|
||||
|
||||
fn xml_escape(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'")
|
||||
}
|
||||
|
||||
fn check_linux_linger() -> bool {
|
||||
if let Ok(user) = std::env::var("USER").or_else(|_| std::env::var("LOGNAME"))
|
||||
&& !user.is_empty()
|
||||
&& Path::new("/var/lib/systemd/linger").join(user).exists()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
|
||||
fn unescape_systemd_quoted(s: &str, expand_dollars: bool) -> String {
|
||||
let after_specifiers = s.replace("%%", "%");
|
||||
let after_dollars = if expand_dollars { after_specifiers.replace("$$", "$") } else { after_specifiers };
|
||||
let mut out = String::new();
|
||||
let mut chars = after_dollars.chars();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '\\' {
|
||||
if let Some(next) = chars.next() {
|
||||
out.push(next);
|
||||
}
|
||||
} else {
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn systemd_unit_encodes_environment_and_exec_start_with_distinct_rules_and_rejects_bad_paths() {
|
||||
let exe = Path::new("/opt/openidea$bin/with \"quotes\"\\slash/open%idea");
|
||||
let home = Path::new("/home/dev&co/100%data$dir/\"sub\"\\path");
|
||||
|
||||
let plist = render_macos_plist(exe, home).unwrap();
|
||||
assert!(plist.contains("dev&co"));
|
||||
|
||||
let unit = render_systemd_unit(exe, home).unwrap();
|
||||
let env_line = unit.lines().find(|l| l.starts_with("Environment=")).unwrap();
|
||||
let exec_line = unit.lines().find(|l| l.starts_with("ExecStart=")).unwrap();
|
||||
|
||||
// Both Environment= and ExecStart= argv[0] keep `$` literal while escaping `\`, `"`, and `%`.
|
||||
assert!(env_line.contains("100%%data$dir"));
|
||||
assert!(!env_line.contains("data$$dir"));
|
||||
let env_inner =
|
||||
env_line.strip_prefix("Environment=\"OPENIDEA_SERVER_HOME=").unwrap().strip_suffix('"').unwrap();
|
||||
assert_eq!(unescape_systemd_quoted(env_inner, false), home.to_str().unwrap());
|
||||
|
||||
assert!(exec_line.contains("openidea$bin"));
|
||||
assert!(!exec_line.contains("openidea$$bin"));
|
||||
assert!(exec_line.contains("open%%idea"));
|
||||
let exec_inner = exec_line.strip_prefix("ExecStart=\"").unwrap().strip_suffix("\" --scheduler").unwrap();
|
||||
assert_eq!(unescape_systemd_quoted(exec_inner, false), exe.to_str().unwrap());
|
||||
|
||||
// Windows .cmd rejects embedded quotes and round-trips `%` and `$`.
|
||||
assert!(render_windows_cmd(exe, home).is_err());
|
||||
let win_ok = render_windows_cmd(
|
||||
Path::new(r"C:\Program Files\OpenIDEA\open%idea$1.exe"),
|
||||
Path::new(r"C:\Users\dev&co\100%data$dir"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(win_ok.contains("100%%data$dir"));
|
||||
assert!(win_ok.contains("open%%idea$1.exe"));
|
||||
|
||||
// Line breaks, NULs, and relative paths are rejected across all platforms.
|
||||
assert!(render_systemd_unit(Path::new("/opt/openidea\nExecStart=/bin/sh"), home).is_err());
|
||||
assert!(render_systemd_unit(exe, Path::new("/home/user\r\nBad=1")).is_err());
|
||||
assert!(render_systemd_unit(Path::new("relative/openidea"), home).is_err());
|
||||
assert!(render_macos_plist(Path::new("/Applications/OpenIDEA\nBad"), home).is_err());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn systemd_unit_rejects_non_utf8_paths() {
|
||||
use std::ffi::OsStr;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let bad = Path::new(OsStr::from_bytes(b"/tmp/openidea-\xff"));
|
||||
assert!(render_systemd_unit(bad, Path::new("/tmp/home")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boot_service_checks_real_registration_retries_unchanged_file_and_stops_on_disable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = BootServiceManager::with_override_dir(Some(tmp.path().join("units")));
|
||||
mgr.set_executable_override(Some(PathBuf::from("/usr/local/bin/openidea-server")));
|
||||
|
||||
let enabled = Arc::new(AtomicBool::new(false));
|
||||
let active = Arc::new(AtomicBool::new(false));
|
||||
let fail_next_enable = Arc::new(AtomicBool::new(true));
|
||||
let fail_next_disable = Arc::new(AtomicBool::new(true));
|
||||
let disable_now_calls = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let enabled_c = enabled.clone();
|
||||
let active_c = active.clone();
|
||||
let fail_en_c = fail_next_enable.clone();
|
||||
let fail_dis_c = fail_next_disable.clone();
|
||||
let dis_calls_c = disable_now_calls.clone();
|
||||
|
||||
mgr.set_command_runner_for_test(
|
||||
ServicePlatform::Linux,
|
||||
Some(Arc::new(move |prog, args| {
|
||||
assert_eq!(prog, "systemctl");
|
||||
match args {
|
||||
["--user", "is-enabled", u] if *u == SYSTEMD_UNIT_NAME => {
|
||||
if enabled_c.load(Ordering::Acquire) {
|
||||
Ok((0, "enabled\n".into(), String::new()))
|
||||
} else {
|
||||
Ok((1, "disabled\n".into(), String::new()))
|
||||
}
|
||||
}
|
||||
["--user", "is-active", u] if *u == SYSTEMD_UNIT_NAME => {
|
||||
if active_c.load(Ordering::Acquire) {
|
||||
Ok((0, "active\n".into(), String::new()))
|
||||
} else {
|
||||
Ok((3, "inactive\n".into(), String::new()))
|
||||
}
|
||||
}
|
||||
["--user", "daemon-reload"] => Ok((0, String::new(), String::new())),
|
||||
["--user", "enable", u] if *u == SYSTEMD_UNIT_NAME => {
|
||||
if fail_en_c.swap(false, Ordering::AcqRel) {
|
||||
Ok((1, String::new(), "dbus unavailable".into()))
|
||||
} else {
|
||||
enabled_c.store(true, Ordering::Release);
|
||||
active_c.store(true, Ordering::Release);
|
||||
Ok((0, String::new(), String::new()))
|
||||
}
|
||||
}
|
||||
["--user", "disable", "--now", u] if *u == SYSTEMD_UNIT_NAME => {
|
||||
dis_calls_c.fetch_add(1, Ordering::AcqRel);
|
||||
if fail_dis_c.swap(false, Ordering::AcqRel) {
|
||||
Ok((1, String::new(), "unit busy".into()))
|
||||
} else {
|
||||
enabled_c.store(false, Ordering::Release);
|
||||
active_c.store(false, Ordering::Release);
|
||||
Ok((0, String::new(), String::new()))
|
||||
}
|
||||
}
|
||||
other => panic!("unexpected systemctl args: {other:?}"),
|
||||
}
|
||||
})),
|
||||
);
|
||||
|
||||
let home = tmp.path();
|
||||
let data = tmp.path().join("data");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
|
||||
// 1. First sync writes the unit file, `systemctl enable` fails -> returns Err and status is NOT registered
|
||||
// even though the unit file already exists on disk!
|
||||
assert!(mgr.sync(Some(home), &data, true).is_err());
|
||||
let st_failed = mgr.status(Some(home), true);
|
||||
assert!(!st_failed.registered, "file exists alone must not report registered when systemctl failed");
|
||||
assert!(st_failed.error.as_deref().unwrap_or_default().contains("dbus unavailable"));
|
||||
|
||||
// 2. Second sync with identical parameters (unchanged file on disk!) retries `systemctl enable` and succeeds.
|
||||
let st_ok = mgr.sync(Some(home), &data, true).unwrap();
|
||||
assert!(st_ok.registered);
|
||||
assert!(st_ok.error.is_none());
|
||||
|
||||
// 3. Disabling when `systemctl disable --now` fails preserves the unit file and retryability.
|
||||
assert!(mgr.sync(Some(home), &data, false).is_err());
|
||||
assert!(mgr.service_file_path(Some(home)).unwrap().is_file(), "unit file kept so unregister can retry");
|
||||
assert!(mgr.status(Some(home), true).registered);
|
||||
|
||||
// 4. Retrying disable runs `systemctl --user disable --now` (stopping the worker), removes the file, and clears status.
|
||||
let st_off = mgr.sync(Some(home), &data, false).unwrap();
|
||||
assert!(!st_off.registered);
|
||||
assert!(!active.load(Ordering::Acquire), "running worker stopped on disable");
|
||||
assert_eq!(disable_now_calls.load(Ordering::Acquire), 2);
|
||||
assert!(!mgr.service_file_path(Some(home)).unwrap().exists());
|
||||
|
||||
// 5. Unknown OS query status (e.g. D-Bus unreachable) MUST NOT treat worker as absent or delete unit file!
|
||||
let status_unknown = Arc::new(AtomicBool::new(false));
|
||||
let status_unknown_c = status_unknown.clone();
|
||||
let macos_loaded = Arc::new(AtomicBool::new(false));
|
||||
let macos_loaded_c = macos_loaded.clone();
|
||||
mgr.set_command_runner_for_test(
|
||||
ServicePlatform::Macos,
|
||||
Some(Arc::new(move |prog, args| {
|
||||
assert_eq!(prog, "launchctl");
|
||||
match args {
|
||||
["print", _] => {
|
||||
if status_unknown_c.load(Ordering::Acquire) {
|
||||
Ok((1, String::new(), "IPC transport error".into()))
|
||||
} else if macos_loaded_c.load(Ordering::Acquire) {
|
||||
Ok((0, "state = running\n".into(), String::new()))
|
||||
} else {
|
||||
Ok((113, String::new(), "Could not find service\n".into()))
|
||||
}
|
||||
}
|
||||
["bootstrap", _, _] => {
|
||||
macos_loaded_c.store(true, Ordering::Release);
|
||||
Ok((0, String::new(), String::new()))
|
||||
}
|
||||
["bootout", _] => {
|
||||
macos_loaded_c.store(false, Ordering::Release);
|
||||
Ok((0, String::new(), String::new()))
|
||||
}
|
||||
other => panic!("unexpected launchctl args: {other:?}"),
|
||||
}
|
||||
})),
|
||||
);
|
||||
mgr.sync(Some(home), &data, true).unwrap();
|
||||
let plist_path = mgr.service_file_path(Some(home)).unwrap();
|
||||
assert!(plist_path.is_file());
|
||||
|
||||
// Simulate transient launchd query failure on disable -> keeps plist file on disk for retry!
|
||||
status_unknown.store(true, Ordering::Release);
|
||||
assert!(mgr.sync(Some(home), &data, false).is_err());
|
||||
assert!(plist_path.is_file(), "plist must be preserved when OS status is unknown");
|
||||
assert!(macos_loaded.load(Ordering::Acquire));
|
||||
|
||||
// Restore launchd query -> retry succeeds, unloads worker, and deletes plist!
|
||||
status_unknown.store(false, Ordering::Release);
|
||||
mgr.sync(Some(home), &data, false).unwrap();
|
||||
assert!(!macos_loaded.load(Ordering::Acquire));
|
||||
assert!(!plist_path.exists());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,577 @@
|
||||
//! Cross-process owner locks, abandonment detection, and authenticated loopback RPC bridge
|
||||
//! so live runs owned by `openidea --scheduler` (or `ChatOnly` / headless `AgentManager`s)
|
||||
//! stream `AgentEvent`s to open windows and accept permission approvals (`agent_respond`,
|
||||
//! `agent_answer_question`, `agent_cancel`, `agent_entries`, etc.).
|
||||
|
||||
use ide_agent::{AgentEntry, AgentEvent, AgentManager, AgentPrompt, AgentTask};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
const OWNERS_DIR: &str = "owners";
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OwnerEndpoint {
|
||||
pub instance_id: String,
|
||||
pub pid: u32,
|
||||
pub addr: String,
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RoutedAgentEvent {
|
||||
pub project_root: Option<PathBuf>,
|
||||
pub event: AgentEvent,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
enum PeerRequest {
|
||||
Subscribe { token: String, allowed_roots: Vec<PathBuf>, include_chat_only: bool },
|
||||
Entries { token: String, task: String, subagent: Option<String> },
|
||||
Respond { token: String, task: String, permission: u32, option: Option<String> },
|
||||
AnswerQuestion { token: String, task: String, question: String, answer: Option<String> },
|
||||
Cancel { token: String, task: String, subagent: Option<String> },
|
||||
StopBackground { token: String, task: String, background: String },
|
||||
Prompt { token: String, task: String, prompt: AgentPrompt, now: bool },
|
||||
StopIdleWorker { token: String },
|
||||
}
|
||||
|
||||
pub type ResolveManagerFn = Arc<dyn Fn(&str) -> Option<Arc<AgentManager>> + Send + Sync>;
|
||||
pub type ListLiveTasksFn = Arc<dyn Fn(&[PathBuf], bool) -> Vec<AgentTask> + Send + Sync>;
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
|
||||
enum PeerStreamItem {
|
||||
Snapshot { tasks: Vec<AgentTask> },
|
||||
Event { event: Box<AgentEvent> },
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(tag = "status", rename_all = "camelCase")]
|
||||
enum PeerReply<T> {
|
||||
Ok { value: T },
|
||||
Err { error: String },
|
||||
}
|
||||
|
||||
pub fn owners_dir(automations_dir: &Path) -> PathBuf {
|
||||
automations_dir.join(OWNERS_DIR)
|
||||
}
|
||||
|
||||
/// Checks whether `owner_id` holds an active OS lock in `automations_dir/owners/`.
|
||||
/// If the lock can be acquired immediately, that process has exited/crashed and its stale
|
||||
/// lock/endpoint files are cleaned up.
|
||||
pub fn is_owner_alive(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> bool {
|
||||
if owner_id.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if owner_id == self_instance_id {
|
||||
return true;
|
||||
}
|
||||
let dir = owners_dir(automations_dir);
|
||||
let lock_path = dir.join(format!("{owner_id}.lock"));
|
||||
let Ok(file) = std::fs::OpenOptions::new().read(true).write(true).open(&lock_path) else {
|
||||
return false;
|
||||
};
|
||||
if file.try_lock().is_ok() {
|
||||
let _ = file.unlock();
|
||||
drop(file);
|
||||
let _ = std::fs::remove_file(&lock_path);
|
||||
let _ = std::fs::remove_file(dir.join(format!("{owner_id}.json")));
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_live_endpoint(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> Option<OwnerEndpoint> {
|
||||
if !is_owner_alive(automations_dir, self_instance_id, owner_id) {
|
||||
return None;
|
||||
}
|
||||
let path = owners_dir(automations_dir).join(format!("{owner_id}.json"));
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
serde_json::from_slice(&bytes).ok()
|
||||
}
|
||||
|
||||
pub fn list_live_peer_endpoints(automations_dir: &Path, self_instance_id: &str) -> Vec<OwnerEndpoint> {
|
||||
let dir = owners_dir(automations_dir);
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.extension().is_none_or(|e| e != "json") {
|
||||
continue;
|
||||
}
|
||||
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
if stem == self_instance_id {
|
||||
continue;
|
||||
}
|
||||
if let Some(ep) = read_live_endpoint(automations_dir, self_instance_id, stem) {
|
||||
out.push(ep);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub struct OwnerNode {
|
||||
pub instance_id: String,
|
||||
lock_file: Mutex<Option<std::fs::File>>,
|
||||
endpoint_path: Mutex<Option<PathBuf>>,
|
||||
pub events_tx: broadcast::Sender<RoutedAgentEvent>,
|
||||
worker_stop_requested: std::sync::atomic::AtomicBool,
|
||||
subscriptions: Mutex<HashMap<String, CancellationToken>>,
|
||||
}
|
||||
|
||||
impl OwnerNode {
|
||||
pub fn new(instance_id: String) -> Self {
|
||||
let (events_tx, _) = broadcast::channel(512);
|
||||
Self {
|
||||
instance_id,
|
||||
lock_file: Mutex::new(None),
|
||||
endpoint_path: Mutex::new(None),
|
||||
events_tx,
|
||||
worker_stop_requested: std::sync::atomic::AtomicBool::new(false),
|
||||
subscriptions: Mutex::new(HashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn worker_stop_requested(&self) -> bool {
|
||||
self.worker_stop_requested.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Acquires `owners/<instance_id>.lock` (idempotent) so any peer can tell this process is alive.
|
||||
pub fn ensure_lock(&self, automations_dir: &Path) -> IdeResult<()> {
|
||||
let mut guard = self.lock_file.lock();
|
||||
if guard.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let dir = owners_dir(automations_dir);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let lock_path = dir.join(format!("{}.lock", self.instance_id));
|
||||
let file = std::fs::OpenOptions::new().create(true).read(true).write(true).truncate(false).open(&lock_path)?;
|
||||
file.try_lock()
|
||||
.map_err(|e| IdeError::internal(format!("cannot acquire owner lock {}: {e}", lock_path.display())))?;
|
||||
*guard = Some(file);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts the authenticated loopback RPC server for live run events and approvals.
|
||||
pub fn start_server(
|
||||
&self,
|
||||
automations_dir: &Path,
|
||||
runtime: &tokio::runtime::Handle,
|
||||
shutdown: CancellationToken,
|
||||
resolve_mgr: ResolveManagerFn,
|
||||
list_live_tasks: ListLiveTasksFn,
|
||||
node_ref: Arc<OwnerNode>,
|
||||
) {
|
||||
if self.ensure_lock(automations_dir).is_err() {
|
||||
return;
|
||||
}
|
||||
if self.endpoint_path.lock().is_some() {
|
||||
return;
|
||||
}
|
||||
let dir = owners_dir(automations_dir);
|
||||
let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
|
||||
let Ok(std_listener) = std::net::TcpListener::bind("127.0.0.1:0") else {
|
||||
return;
|
||||
};
|
||||
if std_listener.set_nonblocking(true).is_err() {
|
||||
return;
|
||||
}
|
||||
let Ok(local_addr) = std_listener.local_addr() else {
|
||||
return;
|
||||
};
|
||||
let instance_id = self.instance_id.clone();
|
||||
let json_path = dir.join(format!("{instance_id}.json"));
|
||||
let ep = OwnerEndpoint {
|
||||
instance_id: instance_id.clone(),
|
||||
pid: std::process::id(),
|
||||
addr: local_addr.to_string(),
|
||||
token: token.clone(),
|
||||
};
|
||||
if let Ok(bytes) = serde_json::to_vec_pretty(&ep) {
|
||||
let _ = write_private_file(&json_path, &bytes);
|
||||
}
|
||||
*self.endpoint_path.lock() = Some(json_path.clone());
|
||||
|
||||
runtime.spawn(async move {
|
||||
let Ok(listener) = TcpListener::from_std(std_listener) else {
|
||||
let _ = std::fs::remove_file(&json_path);
|
||||
return;
|
||||
};
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => break,
|
||||
accepted = listener.accept() => {
|
||||
let Ok((stream, _)) = accepted else { continue };
|
||||
let token_c = token.clone();
|
||||
let resolve_c = resolve_mgr.clone();
|
||||
let list_c = list_live_tasks.clone();
|
||||
let shutdown_c = shutdown.clone();
|
||||
let node_c = node_ref.clone();
|
||||
tokio::spawn(async move {
|
||||
handle_peer_conn(stream, token_c, resolve_c, list_c, shutdown_c, node_c).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_file(&json_path);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn stop(&self, automations_dir: &Path) {
|
||||
for (_, cancel) in self.subscriptions.lock().drain() {
|
||||
cancel.cancel();
|
||||
}
|
||||
if let Some(ep_path) = self.endpoint_path.lock().take() {
|
||||
let _ = std::fs::remove_file(ep_path);
|
||||
}
|
||||
if let Some(file) = self.lock_file.lock().take() {
|
||||
let _ = file.unlock();
|
||||
}
|
||||
let _ = std::fs::remove_file(owners_dir(automations_dir).join(format!("{}.lock", self.instance_id)));
|
||||
}
|
||||
|
||||
pub fn replace_subscriber(&self, subscriber: &str) -> CancellationToken {
|
||||
let token = CancellationToken::new();
|
||||
if let Some(prev) = self.subscriptions.lock().insert(subscriber.to_owned(), token.clone()) {
|
||||
prev.cancel();
|
||||
}
|
||||
token
|
||||
}
|
||||
|
||||
pub fn unsubscribe(&self, subscriber: &str) {
|
||||
if let Some(prev) = self.subscriptions.lock().remove(subscriber) {
|
||||
prev.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_private_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let mut f = std::fs::OpenOptions::new().create(true).write(true).truncate(true).mode(0o600).open(path)?;
|
||||
f.write_all(bytes)?;
|
||||
f.sync_all()
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
std::fs::write(path, bytes)
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_peer_conn(
|
||||
stream: TcpStream,
|
||||
expected_token: String,
|
||||
resolve_mgr: ResolveManagerFn,
|
||||
list_live_tasks: ListLiveTasksFn,
|
||||
shutdown: CancellationToken,
|
||||
node: Arc<OwnerNode>,
|
||||
) {
|
||||
let (reader, mut writer) = stream.into_split();
|
||||
let mut lines = BufReader::new(reader).lines();
|
||||
let Ok(Some(first_line)) = lines.next_line().await else {
|
||||
return;
|
||||
};
|
||||
let Ok(req) = serde_json::from_str::<PeerRequest>(&first_line) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let req_token = match &req {
|
||||
PeerRequest::Subscribe { token, .. }
|
||||
| PeerRequest::Entries { token, .. }
|
||||
| PeerRequest::Respond { token, .. }
|
||||
| PeerRequest::AnswerQuestion { token, .. }
|
||||
| PeerRequest::Cancel { token, .. }
|
||||
| PeerRequest::StopBackground { token, .. }
|
||||
| PeerRequest::Prompt { token, .. }
|
||||
| PeerRequest::StopIdleWorker { token } => token,
|
||||
};
|
||||
if req_token != &expected_token {
|
||||
let _ = write_json_line(&mut writer, &PeerReply::<()>::err("unauthorized")).await;
|
||||
return;
|
||||
}
|
||||
|
||||
match req {
|
||||
PeerRequest::Subscribe { allowed_roots, include_chat_only, .. } => {
|
||||
let mut rx = node.events_tx.subscribe();
|
||||
let canon_allowed: Vec<PathBuf> =
|
||||
allowed_roots.into_iter().map(|p| dunce::canonicalize(&p).unwrap_or(p)).collect();
|
||||
let initial = list_live_tasks(&canon_allowed, include_chat_only);
|
||||
if write_json_line(&mut writer, &PeerStreamItem::Snapshot { tasks: initial }).await.is_err() {
|
||||
return;
|
||||
}
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.cancelled() => break,
|
||||
recv = rx.recv() => {
|
||||
match recv {
|
||||
Ok(routed) => {
|
||||
let matches = match &routed.project_root {
|
||||
None => include_chat_only,
|
||||
Some(actual) => {
|
||||
let cand = dunce::canonicalize(actual).unwrap_or_else(|_| actual.clone());
|
||||
canon_allowed.iter().any(|w| w == &cand)
|
||||
}
|
||||
};
|
||||
if matches
|
||||
&& write_json_line(
|
||||
&mut writer,
|
||||
&PeerStreamItem::Event { event: Box::new(routed.event) },
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(broadcast::error::RecvError::Closed) => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
PeerRequest::Entries { task, subagent, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => tokio::task::spawn_blocking(move || mgr.entries(&task, subagent))
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))
|
||||
.and_then(|r| r),
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::Respond { task, permission, option, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => mgr.respond(&task, permission, option),
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::AnswerQuestion { task, question, answer, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => mgr.answer_question(&task, &question, answer).await,
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::Cancel { task, subagent, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => mgr.cancel(&task, subagent),
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::StopBackground { task, background, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => mgr.stop_background(&task, &background).await,
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::Prompt { task, prompt, now, .. } => {
|
||||
let res = match resolve_mgr(&task) {
|
||||
Some(mgr) => mgr.prompt(&task, prompt, now).await,
|
||||
None => Err(IdeError::not_found(format!("unknown task {task}"))),
|
||||
};
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
|
||||
}
|
||||
PeerRequest::StopIdleWorker { .. } => {
|
||||
node.worker_stop_requested.store(true, std::sync::atomic::Ordering::Release);
|
||||
let _ = write_json_line(&mut writer, &PeerReply::from_res(Ok(()))).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PeerReply<T> {
|
||||
fn from_res(res: IdeResult<T>) -> Self {
|
||||
match res {
|
||||
Ok(value) => Self::Ok { value },
|
||||
Err(e) => Self::Err { error: e.to_string() },
|
||||
}
|
||||
}
|
||||
|
||||
fn err(msg: &str) -> Self {
|
||||
Self::Err { error: msg.to_owned() }
|
||||
}
|
||||
}
|
||||
|
||||
async fn write_json_line<W: AsyncWriteExt + Unpin, T: Serialize>(writer: &mut W, msg: &T) -> std::io::Result<()> {
|
||||
let mut line = serde_json::to_vec(msg).map_err(std::io::Error::other)?;
|
||||
line.push(b'\n');
|
||||
writer.write_all(&line).await?;
|
||||
writer.flush().await
|
||||
}
|
||||
|
||||
async fn call_peer<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
|
||||
let mut stream = TcpStream::connect(&ep.addr)
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
|
||||
write_json_line(&mut stream, req)
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
|
||||
let mut lines = BufReader::new(stream).lines();
|
||||
let raw = lines
|
||||
.next_line()
|
||||
.await
|
||||
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?
|
||||
.ok_or_else(|| IdeError::unavailable("automation worker closed connection without replying"))?;
|
||||
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
|
||||
PeerReply::Ok { value } => Ok(value),
|
||||
PeerReply::Err { error } => Err(IdeError::internal(error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn call_peer_sync<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
|
||||
use std::io::{BufRead, Write};
|
||||
let addr: std::net::SocketAddr = ep
|
||||
.addr
|
||||
.parse()
|
||||
.map_err(|e| IdeError::internal(format!("invalid automation worker address {}: {e}", ep.addr)))?;
|
||||
let mut stream = std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(3))
|
||||
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
|
||||
let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
|
||||
let _ = stream.set_write_timeout(Some(std::time::Duration::from_secs(5)));
|
||||
let mut line = serde_json::to_vec(req).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
line.push(b'\n');
|
||||
stream
|
||||
.write_all(&line)
|
||||
.and_then(|()| stream.flush())
|
||||
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
|
||||
let mut reader = std::io::BufReader::new(stream);
|
||||
let mut raw = String::new();
|
||||
reader
|
||||
.read_line(&mut raw)
|
||||
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?;
|
||||
if raw.trim().is_empty() {
|
||||
return Err(IdeError::unavailable("automation worker closed connection without replying"));
|
||||
}
|
||||
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
|
||||
PeerReply::Ok { value } => Ok(value),
|
||||
PeerReply::Err { error } => Err(IdeError::internal(error)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn peer_entries(ep: &OwnerEndpoint, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
|
||||
call_peer(ep, &PeerRequest::Entries { token: ep.token.clone(), task, subagent }).await
|
||||
}
|
||||
|
||||
pub fn peer_respond(
|
||||
_runtime: &tokio::runtime::Handle,
|
||||
ep: OwnerEndpoint,
|
||||
task: String,
|
||||
permission: u32,
|
||||
option: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
let token = ep.token.clone();
|
||||
call_peer_sync(&ep, &PeerRequest::Respond { token, task, permission, option })
|
||||
}
|
||||
|
||||
pub async fn peer_answer_question(
|
||||
ep: &OwnerEndpoint,
|
||||
task: String,
|
||||
question: String,
|
||||
answer: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
call_peer(ep, &PeerRequest::AnswerQuestion { token: ep.token.clone(), task, question, answer }).await
|
||||
}
|
||||
|
||||
pub fn peer_cancel(
|
||||
_runtime: &tokio::runtime::Handle,
|
||||
ep: OwnerEndpoint,
|
||||
task: String,
|
||||
subagent: Option<String>,
|
||||
) -> IdeResult<()> {
|
||||
let token = ep.token.clone();
|
||||
call_peer_sync(&ep, &PeerRequest::Cancel { token, task, subagent })
|
||||
}
|
||||
|
||||
pub async fn peer_stop_background(ep: &OwnerEndpoint, task: String, background: String) -> IdeResult<()> {
|
||||
call_peer(ep, &PeerRequest::StopBackground { token: ep.token.clone(), task, background }).await
|
||||
}
|
||||
|
||||
pub async fn peer_prompt(ep: &OwnerEndpoint, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
|
||||
call_peer(ep, &PeerRequest::Prompt { token: ep.token.clone(), task, prompt, now }).await
|
||||
}
|
||||
|
||||
pub fn notify_peers_stop_if_headless(runtime: &tokio::runtime::Handle, endpoints: Vec<OwnerEndpoint>) {
|
||||
for ep in endpoints {
|
||||
runtime.spawn(async move {
|
||||
let token = ep.token.clone();
|
||||
let _: IdeResult<()> = call_peer(&ep, &PeerRequest::StopIdleWorker { token }).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to `ep`, fetches its initial live task snapshot synchronously (with a short timeout),
|
||||
/// and spawns an async forwarder streaming subsequent `AgentEvent`s until `cancel` triggers.
|
||||
pub fn attach_peer_stream(
|
||||
runtime: &tokio::runtime::Handle,
|
||||
ep: OwnerEndpoint,
|
||||
allowed_roots: Vec<PathBuf>,
|
||||
include_chat_only: bool,
|
||||
cancel: CancellationToken,
|
||||
on_event: Arc<dyn Fn(AgentEvent) + Send + Sync>,
|
||||
) -> Vec<AgentTask> {
|
||||
let (snap_tx, snap_rx) = std::sync::mpsc::channel();
|
||||
runtime.spawn(async move {
|
||||
let connect_fut = TcpStream::connect(&ep.addr);
|
||||
let Ok(Ok(mut stream)) = tokio::time::timeout(std::time::Duration::from_secs(2), connect_fut).await else {
|
||||
let _ = snap_tx.send(Vec::new());
|
||||
return;
|
||||
};
|
||||
let req = PeerRequest::Subscribe { token: ep.token.clone(), allowed_roots, include_chat_only };
|
||||
if write_json_line(&mut stream, &req).await.is_err() {
|
||||
let _ = snap_tx.send(Vec::new());
|
||||
return;
|
||||
}
|
||||
let mut lines = BufReader::new(stream).lines();
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(2), lines.next_line()).await {
|
||||
Ok(Ok(Some(first))) => match serde_json::from_str::<PeerStreamItem>(&first) {
|
||||
Ok(PeerStreamItem::Snapshot { tasks }) => {
|
||||
let _ = snap_tx.send(tasks);
|
||||
}
|
||||
_ => {
|
||||
let _ = snap_tx.send(Vec::new());
|
||||
return;
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
let _ = snap_tx.send(Vec::new());
|
||||
return;
|
||||
}
|
||||
}
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => break,
|
||||
next = lines.next_line() => {
|
||||
match next {
|
||||
Ok(Some(line)) => {
|
||||
if let Ok(PeerStreamItem::Event { event }) = serde_json::from_str::<PeerStreamItem>(&line) {
|
||||
on_event(*event);
|
||||
}
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
snap_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap_or_default()
|
||||
}
|
||||
@@ -18,6 +18,7 @@ use std::sync::{Arc, OnceLock};
|
||||
|
||||
enum Mode {
|
||||
Stdio,
|
||||
Scheduler,
|
||||
#[cfg(unix)]
|
||||
Daemon(PathBuf, ide_host::daemon::BuildId),
|
||||
}
|
||||
@@ -29,6 +30,7 @@ usage:
|
||||
openidea-server --web [options] [<project>]
|
||||
openidea-server --stdio
|
||||
openidea-server --attach <project-path>
|
||||
openidea-server --scheduler
|
||||
openidea-server --mcp-stdio [--project <path>]
|
||||
openidea-server --connect <host> <port>
|
||||
openidea-server --version
|
||||
@@ -233,6 +235,7 @@ fn main() {
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
[flag, _] if flag == "--attach" => Mode::Stdio,
|
||||
_ if args.iter().any(|a| a == "--scheduler") => Mode::Scheduler,
|
||||
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
|
||||
_ => {
|
||||
print_usage();
|
||||
@@ -292,17 +295,21 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
|
||||
let peer = Arc::new(OnceLock::new());
|
||||
let sink_peer = peer.clone();
|
||||
let plugins_data = data_dir.clone();
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir,
|
||||
local_data_dir: data_dir.clone(),
|
||||
data_dir,
|
||||
languages,
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: true,
|
||||
}));
|
||||
let host = Arc::new(
|
||||
Host::new(HostConfig {
|
||||
config_dir,
|
||||
local_data_dir: data_dir.clone(),
|
||||
data_dir,
|
||||
languages,
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: true,
|
||||
})
|
||||
// The client answers no svn prompts here: svn runs non-interactively.
|
||||
.with_subversion(false),
|
||||
);
|
||||
start_mcp(&host, &base);
|
||||
let plugins = start_plugins(&plugins_data, &host, peer.clone());
|
||||
inherit_trust(&host);
|
||||
@@ -312,23 +319,85 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
|
||||
shutdown_all(&host, plugins.as_ref()).await;
|
||||
0
|
||||
}
|
||||
#[cfg(unix)]
|
||||
Mode::Daemon(socket, build) => {
|
||||
let peer = Arc::new(rpc::PeerSlot::default());
|
||||
let sink_peer = peer.clone();
|
||||
let plugins_data = data_dir.clone();
|
||||
Mode::Scheduler => {
|
||||
let host = Arc::new(Host::new(HostConfig {
|
||||
config_dir,
|
||||
local_data_dir: data_dir.clone(),
|
||||
data_dir,
|
||||
languages,
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
|
||||
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: true,
|
||||
}));
|
||||
start_mcp(&host, &base);
|
||||
inherit_trust(&host);
|
||||
host.automations.set_headless_worker_mode(true);
|
||||
host.automations.start(&host);
|
||||
tracing::info!("openidea-server {} headless scheduler started", env!("CARGO_PKG_VERSION"));
|
||||
let mut idle_ticks = 0u32;
|
||||
let mut check = tokio::time::interval(std::time::Duration::from_secs(5));
|
||||
#[cfg(unix)]
|
||||
let mut terminate =
|
||||
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("SIGTERM listener");
|
||||
loop {
|
||||
#[cfg(unix)]
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => break,
|
||||
_ = terminate.recv() => break,
|
||||
_ = check.tick() => {}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => break,
|
||||
_ = check.tick() => {}
|
||||
}
|
||||
let service_enabled = ide_workspace::SettingsStore::load(&host.config_dir, None)
|
||||
.effective()
|
||||
.agents
|
||||
.automations
|
||||
.auto_start_service;
|
||||
let running = host.automations.has_running_runs();
|
||||
if host.automations.worker_stop_requested() || !service_enabled {
|
||||
if !running {
|
||||
tracing::info!("headless scheduler login service disabled; exiting");
|
||||
break;
|
||||
}
|
||||
} else if host.automations.has_enabled_schedules() || running {
|
||||
idle_ticks = 0;
|
||||
} else {
|
||||
idle_ticks += 1;
|
||||
if idle_ticks >= 3 {
|
||||
tracing::info!("no enabled automations remain; headless scheduler exiting");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
shutdown_all(&host, None).await;
|
||||
0
|
||||
}
|
||||
#[cfg(unix)]
|
||||
Mode::Daemon(socket, build) => {
|
||||
let peer = Arc::new(rpc::PeerSlot::default());
|
||||
let sink_peer = peer.clone();
|
||||
let plugins_data = data_dir.clone();
|
||||
let host = Arc::new(
|
||||
Host::new(HostConfig {
|
||||
config_dir,
|
||||
local_data_dir: data_dir.clone(),
|
||||
data_dir,
|
||||
languages,
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: true,
|
||||
})
|
||||
// The client answers no svn prompts here: svn runs non-interactively.
|
||||
.with_subversion(false),
|
||||
);
|
||||
start_mcp(&host, &base);
|
||||
let plugins = start_plugins(&plugins_data, &host, peer.clone());
|
||||
inherit_trust(&host);
|
||||
tracing::info!("openidea-server {} daemon ready at {}", env!("CARGO_PKG_VERSION"), socket.display());
|
||||
|
||||
@@ -398,6 +398,7 @@ pub async fn serve(
|
||||
};
|
||||
|
||||
let shutdown = CancellationToken::new();
|
||||
host.automations.start(&host);
|
||||
let idle_policy = RemoteIdlePolicy { override_seconds: idle_override() };
|
||||
let mut check = tokio::time::interval(Duration::from_secs(idle_policy.override_seconds.unwrap_or(5).min(5)));
|
||||
let mut idle = None;
|
||||
@@ -541,6 +542,7 @@ fn has_live_work(host: &Host) -> bool {
|
||||
!host.terminals.list().is_empty()
|
||||
|| host.processes.has_live_runs()
|
||||
|| !host.debugger.sessions(None).is_empty()
|
||||
|| host.automations.keeps_remote_daemon_alive(host)
|
||||
|| host
|
||||
.projects()
|
||||
.iter()
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -304,10 +304,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());
|
||||
@@ -1214,6 +1225,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();
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
//! runs one on a remote machine and serves it over JSON-RPC ([`rpc`]).
|
||||
|
||||
pub mod agent_secrets;
|
||||
pub mod automations;
|
||||
pub mod catalogue;
|
||||
#[cfg(unix)]
|
||||
pub mod daemon;
|
||||
pub mod data_dirs;
|
||||
pub mod devcontainer;
|
||||
pub mod diagnostics_store;
|
||||
mod direnv;
|
||||
pub mod environment;
|
||||
@@ -27,6 +29,7 @@ pub mod relay;
|
||||
mod requests;
|
||||
pub mod rpc;
|
||||
pub mod shell_env;
|
||||
pub mod svn;
|
||||
mod swiftlint;
|
||||
pub mod trust;
|
||||
mod ts_code_style;
|
||||
@@ -89,9 +92,12 @@ 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>>,
|
||||
/// Subversion is on ([`Host::with_subversion`]); `Some(true)` shows svn's prompts in dialogs.
|
||||
pub(crate) subversion: Option<bool>,
|
||||
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
|
||||
pub mcp: mcp::McpService,
|
||||
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
|
||||
@@ -102,11 +108,16 @@ 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.
|
||||
pub automations: Arc<automations::AutomationService>,
|
||||
pub(crate) agent_catalogs: Arc<ide_agent::AgentCatalogs>,
|
||||
pub trust: std::sync::Arc<trust::TrustStore>,
|
||||
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
|
||||
pub(crate) plugin_approvals: Arc<trust::PluginCapabilityApprovals>,
|
||||
pub config_dir: PathBuf,
|
||||
/// Persistent user state, including credentials and recovery history.
|
||||
pub data_dir: PathBuf,
|
||||
@@ -205,6 +216,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;
|
||||
@@ -218,6 +235,14 @@ impl Host {
|
||||
self
|
||||
}
|
||||
|
||||
/// Adds Subversion: every project gets its own svn settings ([`svn`]) and finds its
|
||||
/// working copies. `prompts` routes svn's login and certificate prompts to the project's
|
||||
/// window (the desktop app, which answers them with `ssh_askpass_answer`).
|
||||
pub fn with_subversion(mut self, prompts: bool) -> Self {
|
||||
self.subversion = Some(prompts);
|
||||
self
|
||||
}
|
||||
|
||||
/// User home directory used by agent memory discovery.
|
||||
pub fn home_dir(&self) -> Option<PathBuf> {
|
||||
self.home_dir.clone()
|
||||
@@ -243,20 +268,27 @@ impl Host {
|
||||
let migration = ssh.clone();
|
||||
runtime.spawn_blocking(move || migration.start_password_migration());
|
||||
ssh.set_configs(global_settings.effective().ssh.configs);
|
||||
let boot_override = if cfg!(test) { Some(data_dir.join("boot-services-test")) } else { None };
|
||||
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,
|
||||
mcp_executable: Arc::default(),
|
||||
mcp: Default::default(),
|
||||
diagnostics,
|
||||
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(),
|
||||
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
|
||||
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
|
||||
plugin_approvals: Arc::new(trust::PluginCapabilityApprovals::load(&data_dir)),
|
||||
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
|
||||
jupyter_tokens: ide_ssh::secrets::SecretFile::new(data_dir.join("jupyter-tokens.json")),
|
||||
proxy_session_password: Mutex::default(),
|
||||
@@ -492,13 +524,20 @@ impl Host {
|
||||
let processes = self.processes.detach_project_kills(&project.root);
|
||||
let terminals = self.terminals.detach_key(self.owner_window(window));
|
||||
let root = (!project.light).then(|| project.root.clone());
|
||||
let shutdown_agents = if !project.light
|
||||
&& self.automations.retain_on_window_close(self, &project.root, &project.agents, agent_reason)
|
||||
{
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![project.agents.clone()]
|
||||
};
|
||||
let handle = self.spawn_project_shutdown(ShutdownWork {
|
||||
notebooks: vec![project.notebooks.clone()],
|
||||
bridges: project.kotlin_bridge.iter().cloned().collect(),
|
||||
lsp: Some(project.lsp.clone()),
|
||||
// Debug sessions under the root belong to windows: a project served without one starts none.
|
||||
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
|
||||
agents: vec![project.agents.clone()],
|
||||
agents: shutdown_agents,
|
||||
agent_reason,
|
||||
terminals: Some(terminals),
|
||||
processes: Some(processes),
|
||||
@@ -627,6 +666,7 @@ impl Host {
|
||||
}
|
||||
|
||||
pub fn shutdown_notebooks_on_exit_with(&self, agent_reason: ide_agent::AgentShutdownReason) {
|
||||
self.automations.stop();
|
||||
let projects = self.projects();
|
||||
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
|
||||
if !projects.is_empty() {
|
||||
|
||||
@@ -444,7 +444,7 @@ impl BackgroundProjects {
|
||||
|
||||
impl Host {
|
||||
/// The window, and its project, that has `root` open as a project (not in LightEdit).
|
||||
fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
|
||||
pub(crate) fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
|
||||
let projects = self.projects.read();
|
||||
let windows = projects.iter().filter(|(w, p)| !BackgroundProjects::is_key(w) && !p.light && p.root == root);
|
||||
windows.min_by_key(|(w, _)| w.as_str()).map(|(w, p)| (w.clone(), p.clone()))
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -242,7 +242,11 @@ marked directory are not marked again.",
|
||||
},
|
||||
)
|
||||
.param(Param::required("directoryPath", ParamType::String, RELATIVE_PATH_IN_PROJECT_DESCRIPTION))
|
||||
.param(Param::optional("maxDepth", ParamType::Integer, "Maximum recursion depth"))
|
||||
.param(Param::optional(
|
||||
"maxDepth",
|
||||
ParamType::Integer,
|
||||
"Levels to list below the directory: 1 lists its entries, 2 their entries too, and so on (default 5)",
|
||||
))
|
||||
.param(Param::optional("limit", ParamType::Integer, "Entries to return at most (default 100)"))
|
||||
.param(Param::optional("offset", ParamType::Integer, OFFSET))
|
||||
.param(Param::optional("timeout", ParamType::Integer, TIMEOUT_MILLISECONDS_DESCRIPTION))
|
||||
@@ -306,6 +310,7 @@ fn marker(git_ignored: bool, ide_excluded: bool) -> &'static str {
|
||||
}
|
||||
|
||||
impl TreeRender {
|
||||
/// `max_depth`: the levels to list below the entry (0 lists the entry alone);
|
||||
/// `mark`: the entry's marker; `marked`: it or a directory above it is marked.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render(
|
||||
@@ -318,7 +323,7 @@ impl TreeRender {
|
||||
mark: &str,
|
||||
marked: bool,
|
||||
) {
|
||||
if max_depth <= 0 || self.timed_out || self.cancel.is_cancelled() {
|
||||
if self.timed_out || self.cancel.is_cancelled() {
|
||||
return;
|
||||
}
|
||||
if Instant::now() >= self.deadline {
|
||||
@@ -343,7 +348,7 @@ impl TreeRender {
|
||||
} else {
|
||||
self.entry(&line)
|
||||
};
|
||||
if !is_dir {
|
||||
if !is_dir || max_depth <= 0 {
|
||||
return;
|
||||
}
|
||||
// Without exclusions, `ignored` is what `.gitignore` says.
|
||||
@@ -482,6 +487,38 @@ mod tests {
|
||||
assert_eq!(render(0, 100).0, " ├── a/\n │ ├── x.txt\n │ └── y.txt\n └── b.txt\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn max_depth_counts_the_levels_below_the_directory() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
for file in ["a/b/c.txt", "d.txt"] {
|
||||
let path = tmp.path().join(file);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
let render = |max_depth| {
|
||||
let mut tree = TreeRender {
|
||||
out: String::new(),
|
||||
errors: Vec::new(),
|
||||
timed_out: false,
|
||||
deadline: Instant::now() + Duration::from_secs(10),
|
||||
cancel: CancellationToken::new(),
|
||||
page: Page { offset: 0, limit: 100 },
|
||||
seen: 0,
|
||||
above: Vec::new(),
|
||||
marks: Marks { root: tmp.path().to_path_buf(), excludes: None },
|
||||
};
|
||||
tree.render(tmp.path(), "", true, max_depth, true, "", false);
|
||||
let root = format!("{}/\n", tmp.path().display());
|
||||
(tree.out.strip_prefix(&root).unwrap().to_owned(), tree.seen)
|
||||
};
|
||||
assert_eq!(render(0), (String::new(), 0), "0 lists the directory alone");
|
||||
assert_eq!(render(1), (" ├── a/\n └── d.txt\n".to_owned(), 2), "1 lists its entries");
|
||||
assert_eq!(render(2), (" ├── a/\n │ └── b/\n └── d.txt\n".to_owned(), 3));
|
||||
let full = " ├── a/\n │ └── b/\n │ └── c.txt\n └── d.txt\n".to_owned();
|
||||
assert_eq!(render(3), (full.clone(), 4));
|
||||
assert_eq!(render(5), (full, 4), "a depth beyond the tree lists all of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_the_project_leaves_out_is_marked_once() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
mod background;
|
||||
mod check;
|
||||
mod debug;
|
||||
mod devcontainer;
|
||||
mod edit;
|
||||
mod editors;
|
||||
mod requests;
|
||||
@@ -27,7 +28,7 @@ use ide_mcp::{ToolCallError, ToolRegistry};
|
||||
pub use reports::{
|
||||
FileProblems, FocusedEditor, Reports, mcp_report_problems, mcp_set_focused_editor, mcp_set_open_editors,
|
||||
};
|
||||
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM};
|
||||
pub use run::agent::{AGENT_PARAM, AgentRun, AgentRuns, NAME_PREFIX, SHELL_PARAM, TARGET_PARAM};
|
||||
use serde_json::json;
|
||||
pub use service::{McpServerStatus, McpService};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -40,7 +41,7 @@ impl Registry {
|
||||
}
|
||||
}
|
||||
|
||||
fn tools() -> Vec<tool::Tool> {
|
||||
fn tools(local_desktop: bool) -> Vec<tool::Tool> {
|
||||
let mut tools = files::tools();
|
||||
tools.extend(search::tools());
|
||||
tools.extend(editors::tools());
|
||||
@@ -53,6 +54,9 @@ fn tools() -> Vec<tool::Tool> {
|
||||
tools.extend(run::tools());
|
||||
tools.extend(vcs::tools());
|
||||
tools.extend(http::tools());
|
||||
if local_desktop {
|
||||
tools.extend(devcontainer::tools());
|
||||
}
|
||||
tools
|
||||
}
|
||||
|
||||
@@ -63,7 +67,7 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool {
|
||||
}
|
||||
|
||||
fn tools_for(host: &Host, root: &Path, trusted: bool) -> Vec<ide_mcp::Tool> {
|
||||
let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect();
|
||||
let mut all: Vec<_> = tools(host.local_desktop).into_iter().map(|t| t.metadata).collect();
|
||||
if let Some(plugins) = host.plugin_host() {
|
||||
all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| with_project_path(tool)));
|
||||
}
|
||||
@@ -144,7 +148,7 @@ impl Registry {
|
||||
{
|
||||
return Some(Found::Plugin { plugins, plugin, tool, metadata });
|
||||
}
|
||||
tools().into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
|
||||
tools(self.0.local_desktop).into_iter().find(|t| t.metadata.name == name).map(Found::Builtin)
|
||||
}
|
||||
|
||||
/// Whether the tools listed for `root` include those that write and run. Opens nothing:
|
||||
@@ -307,10 +311,21 @@ impl Registry {
|
||||
mod tests {
|
||||
#[test]
|
||||
fn restricted_mode_excludes_execution_tools() {
|
||||
let mut tool = super::tools().remove(0).metadata;
|
||||
let mut tool = super::tools(false).remove(0).metadata;
|
||||
assert!(super::allowed(&tool, false));
|
||||
tool.read_only = false;
|
||||
assert!(!super::allowed(&tool, false));
|
||||
assert!(super::allowed(&tool, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dev_container_tools_that_start_run_or_stop_are_not_read_only() {
|
||||
let tools = super::devcontainer::tools();
|
||||
let read_only = |name: &str| tools.iter().find(|t| t.metadata.name == name).unwrap().metadata.read_only;
|
||||
assert!(read_only("devcontainer_status") && read_only("devcontainer_logs"));
|
||||
for name in ["devcontainer_up", "devcontainer_exec", "devcontainer_stop"] {
|
||||
assert!(!read_only(name), "{name}");
|
||||
}
|
||||
assert_eq!(tools.len(), 5);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@
|
||||
|
||||
use super::output::{TRUNCATED_MARKER, temp_output_file};
|
||||
use crate::ops::Emit;
|
||||
use ide_core::{IdeEvent, IdeResult, RunId, SharedSink};
|
||||
use ide_core::event::McpAgentRunTarget;
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, RunId, SharedSink};
|
||||
use ide_run::{OutputChunk, RunConfig, RunInfo};
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::{Map, Value, json};
|
||||
@@ -20,6 +21,8 @@ use std::time::SystemTime;
|
||||
|
||||
/// Run configuration parameter naming the agent tab a start belongs to.
|
||||
pub const AGENT_PARAM: &str = "mcp.agentRun";
|
||||
/// Run configuration parameter containing the serialized execution target.
|
||||
pub const TARGET_PARAM: &str = "mcp.agentTarget";
|
||||
/// Run configuration parameter with Settings › Tools › Terminal › Shell path (may be empty).
|
||||
pub const SHELL_PARAM: &str = "mcp.agentShell";
|
||||
/// What every agent tab's name starts with.
|
||||
@@ -28,6 +31,21 @@ const MAX_NAME_LENGTH: usize = 64;
|
||||
/// How much of the log a wait for a pattern reads at a time.
|
||||
const SCAN_CHUNK: usize = 4 << 20;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum Execution {
|
||||
Host,
|
||||
Container { id: String, config: PathBuf, argv: Vec<String> },
|
||||
}
|
||||
|
||||
impl Execution {
|
||||
pub(crate) fn target(&self) -> McpAgentRunTarget {
|
||||
match self {
|
||||
Self::Host => McpAgentRunTarget::Host,
|
||||
Self::Container { id, .. } => McpAgentRunTarget::Container { id: id.clone() },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The tab name for what an agent asked for: trimmed, with [`NAME_PREFIX`] once.
|
||||
pub fn tab_name(raw: &str) -> IdeResult<String> {
|
||||
let raw = raw.trim();
|
||||
@@ -58,7 +76,7 @@ impl AgentRuns {
|
||||
}
|
||||
|
||||
/// The tab for the agent's next start of `name`: refused while its process runs, since
|
||||
/// only an explicit `stop_run` may end it.
|
||||
/// only an explicit `stop_run` may end it. The execution applies to exactly this command.
|
||||
pub(crate) fn prepare(
|
||||
&self,
|
||||
root: &Path,
|
||||
@@ -66,6 +84,7 @@ impl AgentRuns {
|
||||
name: &str,
|
||||
command: &str,
|
||||
cwd: &str,
|
||||
execution: Execution,
|
||||
) -> Result<Arc<AgentRun>, Arc<AgentRun>> {
|
||||
let mut runs = self.0.lock();
|
||||
let run = match runs.iter().find(|r| r.root == root && r.name == name) {
|
||||
@@ -78,13 +97,15 @@ impl AgentRuns {
|
||||
};
|
||||
drop(runs);
|
||||
let mut s = run.state.lock();
|
||||
if s.running() {
|
||||
if s.running() || s.agent_start {
|
||||
drop(s);
|
||||
return Err(run);
|
||||
}
|
||||
*run.window.lock() = window.to_owned();
|
||||
s.previous = Some(Previous { command: s.command.clone(), cwd: s.cwd.clone(), execution: s.execution.clone() });
|
||||
s.command = command.to_owned();
|
||||
s.cwd = cwd.to_owned();
|
||||
s.execution = execution;
|
||||
s.agent_start = true;
|
||||
s.start_error = None;
|
||||
s.closed_at = None;
|
||||
@@ -94,11 +115,16 @@ impl AgentRuns {
|
||||
Ok(run)
|
||||
}
|
||||
|
||||
/// The agent's start did not reach the Run tool window: a tab that never ran is dropped.
|
||||
/// The agent's start did not reach the Run tool window: a tab that never ran is dropped, and
|
||||
/// one that did keeps the command and execution its window still has the configuration of.
|
||||
pub(crate) fn abandon(&self, run: &Arc<AgentRun>) {
|
||||
let never_ran = {
|
||||
let mut s = run.state.lock();
|
||||
s.agent_start = false;
|
||||
if std::mem::take(&mut s.agent_start)
|
||||
&& let Some(Previous { command, cwd, execution }) = s.previous.take()
|
||||
{
|
||||
(s.command, s.cwd, s.execution) = (command, cwd, execution);
|
||||
}
|
||||
s.process.is_none()
|
||||
};
|
||||
if never_ran {
|
||||
@@ -109,31 +135,59 @@ impl AgentRuns {
|
||||
|
||||
/// Called for every run start: for a start of an agent tab, turns its command line into
|
||||
/// the shell's invocation and opens a new process record.
|
||||
pub(crate) fn launch(&self, root: &Path, window: &str, config: &mut RunConfig) -> Option<Launch> {
|
||||
let name = config.extras.params.get(AGENT_PARAM).cloned()?;
|
||||
pub(crate) fn launch(&self, root: &Path, window: &str, config: &mut RunConfig) -> IdeResult<Option<Launch>> {
|
||||
let unavailable = || IdeError::invalid("the approved agent run target is unavailable; start a new MCP run");
|
||||
let Some(name) = config.extras.params.get(AGENT_PARAM) else {
|
||||
if config.id.starts_with("mcp-agent:") || config.extras.params.contains_key(TARGET_PARAM) {
|
||||
return Err(unavailable());
|
||||
}
|
||||
return Ok(None);
|
||||
};
|
||||
let target: McpAgentRunTarget = config
|
||||
.extras
|
||||
.params
|
||||
.get(TARGET_PARAM)
|
||||
.and_then(|target| serde_json::from_str(target).ok())
|
||||
.ok_or_else(unavailable)?;
|
||||
let line = config.command.clone();
|
||||
let cwd = config.cwd.as_deref().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let run = {
|
||||
let mut runs = self.0.lock();
|
||||
match runs.iter().find(|r| r.root == root && r.name == name) {
|
||||
match runs.iter().find(|r| r.root == root && r.name == *name) {
|
||||
Some(run) => run.clone(),
|
||||
None => {
|
||||
let run = Arc::new(AgentRun::new(root, &name, &line, &cwd));
|
||||
None if target == McpAgentRunTarget::Host => {
|
||||
let run = Arc::new(AgentRun::new(root, name, &line, &cwd));
|
||||
runs.push(run.clone());
|
||||
run
|
||||
}
|
||||
None => return Err(unavailable()),
|
||||
}
|
||||
};
|
||||
let mut state = run.state.lock();
|
||||
if state.execution.target() != target || state.running() {
|
||||
return Err(unavailable());
|
||||
}
|
||||
let (program, args) = match &state.execution {
|
||||
Execution::Host => shell_invocation(config.extras.params.get(SHELL_PARAM).map(String::as_str), &line),
|
||||
Execution::Container { config, argv, .. } => {
|
||||
if state.command != line {
|
||||
return Err(unavailable());
|
||||
}
|
||||
crate::mcp::tool::ensure_inside(root, config)?;
|
||||
let (program, args) = argv.split_first().ok_or_else(unavailable)?;
|
||||
(program.clone(), args.to_vec())
|
||||
}
|
||||
};
|
||||
*run.window.lock() = window.to_owned();
|
||||
let shell = config.extras.params.get(SHELL_PARAM).cloned();
|
||||
let (program, args) = shell_invocation(shell.as_deref(), &line);
|
||||
config.command = program;
|
||||
config.args = args;
|
||||
config.extras.target = Some(String::new());
|
||||
// Pipes: the Run tool window's console shows the output and sends the user's input lines.
|
||||
config.extras.emulate_terminal = false;
|
||||
let generation = run.begin(&line);
|
||||
Some(Launch { run, generation })
|
||||
*run.window.lock() = window.to_owned();
|
||||
let generation = state.begin(&line);
|
||||
drop(state);
|
||||
run.changed.notify_waiters();
|
||||
Ok(Some(Launch { run, generation }))
|
||||
}
|
||||
|
||||
fn by_process(&self, id: RunId) -> Option<Arc<AgentRun>> {
|
||||
@@ -255,9 +309,18 @@ struct Process {
|
||||
stopped_by: Option<Actor>,
|
||||
}
|
||||
|
||||
struct Previous {
|
||||
command: String,
|
||||
cwd: String,
|
||||
execution: Execution,
|
||||
}
|
||||
|
||||
struct State {
|
||||
command: String,
|
||||
cwd: String,
|
||||
execution: Execution,
|
||||
/// What the tab was before the agent's pending start, for [`AgentRuns::abandon`].
|
||||
previous: Option<Previous>,
|
||||
log: Option<(PathBuf, std::fs::File)>,
|
||||
log_len: u64,
|
||||
generation: u64,
|
||||
@@ -280,6 +343,32 @@ impl State {
|
||||
fn running(&self) -> bool {
|
||||
self.process.as_ref().is_some_and(|p| p.ended.is_none())
|
||||
}
|
||||
|
||||
fn begin(&mut self, line: &str) -> u64 {
|
||||
self.generation += 1;
|
||||
let by = if std::mem::take(&mut self.agent_start) { Actor::Agent } else { Actor::User };
|
||||
let now = SystemTime::now();
|
||||
if by == Actor::User {
|
||||
self.interventions.push((now, Intervention::Rerun));
|
||||
}
|
||||
self.command = line.to_owned();
|
||||
self.previous = None;
|
||||
self.agent_stop = false;
|
||||
self.start_error = None;
|
||||
self.closed_at = None;
|
||||
self.typed.clear();
|
||||
self.escape = Escape::None;
|
||||
self.process = Some(Process {
|
||||
generation: self.generation,
|
||||
run: None,
|
||||
by,
|
||||
started_at: now,
|
||||
offset: self.log_len,
|
||||
ended: None,
|
||||
stopped_by: None,
|
||||
});
|
||||
self.generation
|
||||
}
|
||||
}
|
||||
|
||||
/// An agent tab.
|
||||
@@ -326,6 +415,8 @@ impl AgentRun {
|
||||
state: Mutex::new(State {
|
||||
command: command.to_owned(),
|
||||
cwd: cwd.to_owned(),
|
||||
execution: Execution::Host,
|
||||
previous: None,
|
||||
log: None,
|
||||
log_len: 0,
|
||||
generation: 0,
|
||||
@@ -348,28 +439,6 @@ impl AgentRun {
|
||||
self.window.lock().clone()
|
||||
}
|
||||
|
||||
fn begin(&self, line: &str) -> u64 {
|
||||
let mut s = self.state.lock();
|
||||
s.generation += 1;
|
||||
let generation = s.generation;
|
||||
let by = if std::mem::take(&mut s.agent_start) { Actor::Agent } else { Actor::User };
|
||||
let now = SystemTime::now();
|
||||
if by == Actor::User {
|
||||
s.interventions.push((now, Intervention::Rerun));
|
||||
}
|
||||
s.command = line.to_owned();
|
||||
s.agent_stop = false;
|
||||
s.start_error = None;
|
||||
s.closed_at = None;
|
||||
s.typed.clear();
|
||||
s.escape = Escape::None;
|
||||
let offset = s.log_len;
|
||||
s.process = Some(Process { generation, run: None, by, started_at: now, offset, ended: None, stopped_by: None });
|
||||
drop(s);
|
||||
self.changed.notify_waiters();
|
||||
generation
|
||||
}
|
||||
|
||||
fn output(&self, text: &str) {
|
||||
let mut s = self.state.lock();
|
||||
if s.log.is_none() {
|
||||
@@ -874,6 +943,109 @@ mod tests {
|
||||
run.take_interventions().iter().map(|v| v["message"].as_str().unwrap().to_owned()).collect()
|
||||
}
|
||||
|
||||
fn agent_config(line: &str, target: McpAgentRunTarget) -> RunConfig {
|
||||
let mut config = RunConfig {
|
||||
id: "mcp-agent:x".into(),
|
||||
name: "x".into(),
|
||||
kind: "shell".into(),
|
||||
command: line.into(),
|
||||
args: Vec::new(),
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: true,
|
||||
extras: Default::default(),
|
||||
};
|
||||
config.extras.params.insert(AGENT_PARAM.into(), "_agent_x".into());
|
||||
config.extras.params.insert(SHELL_PARAM.into(), "/bin/sh".into());
|
||||
config.extras.params.insert(TARGET_PARAM.into(), serde_json::to_string(&target).unwrap());
|
||||
config
|
||||
}
|
||||
|
||||
fn container_execution(root: &Path, id: &str) -> Execution {
|
||||
Execution::Container {
|
||||
id: id.to_owned(),
|
||||
config: root.join(".devcontainer.json"),
|
||||
argv: ["devcontainer", "exec", "--container-id", id, "sh", "-c", "echo 'a b'"].map(str::to_owned).to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reruns_keep_the_approved_container_and_refuse_missing_or_changed_targets() {
|
||||
let runs = AgentRuns::default();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let id = "a".repeat(64);
|
||||
let execution = container_execution(root, &id);
|
||||
let line = "in the container: echo";
|
||||
let saved = agent_config(line, execution.target());
|
||||
let approve = |execution| runs.prepare(root, "main", "_agent_x", line, "", execution).ok().unwrap();
|
||||
let run = approve(execution);
|
||||
for _ in 0..2 {
|
||||
let mut config = saved.clone();
|
||||
let launch = runs.launch(root, "main", &mut config).unwrap().unwrap();
|
||||
assert_eq!(config.command, "devcontainer");
|
||||
assert_eq!(config.args, ["exec", "--container-id", &id, "sh", "-c", "echo 'a b'"]);
|
||||
run.exited(launch.generation, Some(0));
|
||||
}
|
||||
let mut missing = saved.clone();
|
||||
missing.extras.params.remove(TARGET_PARAM);
|
||||
assert!(runs.launch(root, "main", &mut missing).is_err());
|
||||
missing.extras.params.remove(AGENT_PARAM);
|
||||
assert!(runs.launch(root, "main", &mut missing).is_err());
|
||||
let mut other_line = saved.clone();
|
||||
other_line.command = "something else".into();
|
||||
assert!(runs.launch(root, "main", &mut other_line).is_err());
|
||||
let mut wrong_kind = agent_config(line, McpAgentRunTarget::Host);
|
||||
assert!(runs.launch(root, "main", &mut wrong_kind).is_err());
|
||||
approve(container_execution(root, &"b".repeat(64)));
|
||||
assert!(runs.launch(root, "main", &mut saved.clone()).is_err());
|
||||
runs.abandon(&run);
|
||||
runs.forget_window("main");
|
||||
assert!(runs.launch(root, "main", &mut saved.clone()).is_err());
|
||||
|
||||
runs.prepare(root, "main", "_agent_x", "ls", "", Execution::Host).ok().unwrap();
|
||||
assert!(runs.launch(root, "main", &mut saved.clone()).is_err());
|
||||
let mut shell = agent_config("ls", McpAgentRunTarget::Host);
|
||||
runs.launch(root, "main", &mut shell).unwrap().unwrap();
|
||||
assert_eq!((shell.command.as_str(), shell.args.last().map(String::as_str)), ("/bin/sh", Some("ls")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_abandoned_start_leaves_the_tab_as_its_window_knows_it() {
|
||||
let runs = AgentRuns::default();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
let execution = container_execution(root, &"a".repeat(64));
|
||||
let target = execution.target();
|
||||
let finish = |run: &AgentRun| {
|
||||
let generation = run.state.lock().generation;
|
||||
run.exited(generation, Some(0));
|
||||
};
|
||||
// A shell command, then a dev container one whose start never reaches the window: a
|
||||
// rerun of the shell configuration still runs in the shell.
|
||||
let run = runs.prepare(root, "main", "_agent_x", "ls", "", Execution::Host).ok().unwrap();
|
||||
runs.launch(root, "main", &mut agent_config("ls", McpAgentRunTarget::Host)).unwrap().unwrap();
|
||||
finish(&run);
|
||||
runs.prepare(root, "main", "_agent_x", "in the container: ls", "", execution.clone()).ok().unwrap();
|
||||
runs.abandon(&run);
|
||||
let mut rerun = agent_config("ls", McpAgentRunTarget::Host);
|
||||
runs.launch(root, "main", &mut rerun).unwrap().unwrap();
|
||||
assert_eq!(rerun.command, "/bin/sh");
|
||||
finish(&run);
|
||||
// And the other way round: the dev container configuration keeps its argv.
|
||||
runs.prepare(root, "main", "_agent_x", "in the container: ls", "", execution).ok().unwrap();
|
||||
runs.launch(root, "main", &mut agent_config("in the container: ls", target.clone())).unwrap().unwrap();
|
||||
finish(&run);
|
||||
runs.prepare(root, "main", "_agent_x", "pwd", "", Execution::Host).ok().unwrap();
|
||||
runs.abandon(&run);
|
||||
let mut rerun = agent_config("in the container: ls", target);
|
||||
runs.launch(root, "main", &mut rerun).unwrap().unwrap();
|
||||
assert_eq!(rerun.command, "devcontainer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_get_the_prefix_once() {
|
||||
assert_eq!(tab_name(" build ").unwrap(), "_agent_build");
|
||||
@@ -898,11 +1070,11 @@ mod tests {
|
||||
fn starts_that_the_agent_did_not_ask_for_are_reruns() {
|
||||
let run = run();
|
||||
run.state.lock().agent_start = true;
|
||||
let first = run.begin("echo");
|
||||
let first = run.state.lock().begin("echo");
|
||||
assert!(messages(&run).is_empty());
|
||||
run.exited(first, Some(0));
|
||||
assert_eq!(run.status()["state"], "succeeded");
|
||||
run.begin("echo");
|
||||
run.state.lock().begin("echo");
|
||||
let told = messages(&run);
|
||||
assert_eq!(told.len(), 1);
|
||||
assert!(told[0].starts_with("The user reran this command at "), "{told:?}");
|
||||
@@ -913,7 +1085,7 @@ mod tests {
|
||||
fn stops_are_the_agents_only_when_it_asked() {
|
||||
let run = run();
|
||||
run.state.lock().agent_start = true;
|
||||
let generation = run.begin("sleep 9");
|
||||
let generation = run.state.lock().begin("sleep 9");
|
||||
run.state.lock().process.as_mut().unwrap().run = Some(RunId(7));
|
||||
run.stopping(RunId(7));
|
||||
run.stopping(RunId(7));
|
||||
@@ -922,7 +1094,7 @@ mod tests {
|
||||
assert_eq!(run.status()["state"], "stoppedByUser");
|
||||
|
||||
run.state.lock().agent_start = true;
|
||||
let generation = run.begin("sleep 9");
|
||||
let generation = run.state.lock().begin("sleep 9");
|
||||
run.state.lock().process.as_mut().unwrap().run = Some(RunId(8));
|
||||
run.agent_stopping();
|
||||
run.stopping(RunId(8));
|
||||
@@ -934,12 +1106,12 @@ mod tests {
|
||||
fn faults_are_crashes_and_other_codes_failures() {
|
||||
let run = run();
|
||||
for (code, state) in [(1, "failed"), (130, "failed")] {
|
||||
let generation = run.begin("x");
|
||||
let generation = run.state.lock().begin("x");
|
||||
run.exited(generation, Some(code));
|
||||
assert_eq!(run.status()["state"], state, "{code}");
|
||||
}
|
||||
if cfg!(unix) {
|
||||
let generation = run.begin("x");
|
||||
let generation = run.state.lock().begin("x");
|
||||
run.exited(generation, Some(139));
|
||||
let status = run.status();
|
||||
assert_eq!(status["state"], "crashed");
|
||||
@@ -950,7 +1122,7 @@ mod tests {
|
||||
#[test]
|
||||
fn reads_whole_characters_and_tails_lines() {
|
||||
let run = run();
|
||||
run.begin("x");
|
||||
run.state.lock().begin("x");
|
||||
run.output("one\n");
|
||||
run.output("twö\nthree\n");
|
||||
// `ö` is bytes 6..8: a cut inside it moves to the character's end or start.
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
//! `run_command` and the tools that follow its tab up: `wait_for_run`, `read_run_output`,
|
||||
//! `get_run_status`, `send_run_input`, `stop_run` and `list_runs` (see [`super::agent`]).
|
||||
|
||||
use super::agent::{AgentRun, INTERVENTION_ADVICE, TruncateMode, clean_output, tab_name, truncate_lines};
|
||||
use super::agent::{AgentRun, Execution, INTERVENTION_ADVICE, TruncateMode, clean_output, tab_name, truncate_lines};
|
||||
use super::output::RUN_PREVIEW_MAX_LENGTH;
|
||||
use crate::mcp::page::{OFFSET, Page};
|
||||
use crate::mcp::run::timeout;
|
||||
use crate::mcp::tool::{Call, Output, Param, ParamType, Tool};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::{Map, Value};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
const RUN_TIMEOUT_MS: usize = 10_000;
|
||||
@@ -20,21 +21,22 @@ const READ_CAP: usize = 1 << 20;
|
||||
/// Lines of output quoted when a name is still running.
|
||||
const BUSY_TAIL_LINES: usize = 20;
|
||||
|
||||
const NAME: &str = "Tab name. OpenIDEA shows the tab as `_agent_<name>`; passing the prefixed name works too.";
|
||||
const SEQUENCE: &str = "\n\nUsing the same name for every command of one task reuses its tab: a name whose command \
|
||||
pub(crate) const NAME: &str =
|
||||
"Tab name. OpenIDEA shows the tab as `_agent_<name>`; passing the prefixed name works too.";
|
||||
pub(crate) const SEQUENCE: &str = "\n\nUsing the same name for every command of one task reuses its tab: a name whose command \
|
||||
has finished starts the next command in the same tab. A name whose command is still running is refused (with that \
|
||||
command and its last output); stop it with `stop_run` first or use another name. Nothing is stopped implicitly.";
|
||||
const INTERVENTIONS: &str = "\n\nThe user sees every tab and can type into it, rerun or stop its command, or close \
|
||||
pub(crate) const INTERVENTIONS: &str = "\n\nThe user sees every tab and can type into it, rerun or stop its command, or close \
|
||||
it. Results then carry `interventions` (for example `User input: …` or `The user reran this command at …`) and \
|
||||
`advice`: unless the user asked otherwise, stop what you are doing, tell the user you received the intervention and \
|
||||
wait for their confirmation before you continue.";
|
||||
const OUTPUT: &str = "\n\nThe command runs on pipes, not a terminal, so programs print plain lines (no progress \
|
||||
pub(crate) const OUTPUT: &str = "\n\nThe command runs on pipes, not a terminal, so programs print plain lines (no progress \
|
||||
bars). `output` is that text cleaned of escape sequences, at most `maxLinesCount` lines (default 2000): beyond it, \
|
||||
`truncateMode` START (default) keeps the end, END the start, MIDDLE both ends, NONE everything, with a \
|
||||
`<<<...content truncated...>>>` line where lines were left out and `truncatedLines` saying how many. `outputStart` \
|
||||
and `nextOffset` are positions in the tab's raw output log; pass `nextOffset` as `offset` to read on.";
|
||||
const MAX_LINES: &str = "Lines of output to return at most (default 2000)";
|
||||
const TRUNCATE_MODE: &str = "Which lines to leave out beyond maxLinesCount: START (default, keeps the end), END \
|
||||
pub(crate) const MAX_LINES: &str = "Lines of output to return at most (default 2000)";
|
||||
pub(crate) const TRUNCATE_MODE: &str = "Which lines to leave out beyond maxLinesCount: START (default, keeps the end), END \
|
||||
(keeps the start), MIDDLE (keeps both ends) or NONE";
|
||||
/// `list_runs`: tabs returned by default, and characters of each command, enough to tell them apart.
|
||||
const LIST_LIMIT: usize = 10;
|
||||
@@ -112,7 +114,7 @@ fn offset(call: &Call, name: &str) -> IdeResult<Option<u64>> {
|
||||
}
|
||||
}
|
||||
|
||||
fn busy(run: &AgentRun) -> IdeError {
|
||||
pub(crate) fn busy(run: &AgentRun) -> IdeError {
|
||||
let tail = run.tail(run.process_offset(), BUSY_TAIL_LINES, RUN_PREVIEW_MAX_LENGTH).map(|t| t.0).unwrap_or_default();
|
||||
IdeError::invalid(format!(
|
||||
"`{}` is still running `{}`. Stop it with stop_run first, or use another name.\nLast output:\n{}",
|
||||
@@ -122,6 +124,66 @@ fn busy(run: &AgentRun) -> IdeError {
|
||||
))
|
||||
}
|
||||
|
||||
/// A command to start in an agent tab: [`start_in_tab`].
|
||||
pub(crate) struct Tab {
|
||||
/// What the confirmation dialog is titled with.
|
||||
pub subject: String,
|
||||
/// The tab's name, with its prefix.
|
||||
pub name: String,
|
||||
/// The command line the tab shows and records.
|
||||
pub command: String,
|
||||
/// What the confirmation dialog says the command does.
|
||||
pub detail: String,
|
||||
pub cwd: PathBuf,
|
||||
pub env: Vec<(String, String)>,
|
||||
pub execution: Execution,
|
||||
/// Added to the result.
|
||||
pub extra: Map<String, Value>,
|
||||
}
|
||||
|
||||
/// The rest of `run_command`: asks the user, starts `tab` in the Run tool window and waits as
|
||||
/// the `timeout` and `pattern` arguments say. Refused while the tab's command runs.
|
||||
pub(crate) async fn start_in_tab(call: &Call, tab: Tab, default_timeout_ms: usize) -> IdeResult<Output> {
|
||||
let name = tab.name.clone();
|
||||
let deadline = deadline(call, default_timeout_ms)?;
|
||||
let ready = pattern(call)?;
|
||||
let host = call.host();
|
||||
let runs = &host.mcp_agent_runs;
|
||||
if let Some(run) = runs.get(call.root(), &name).filter(|r| r.running()) {
|
||||
return Err(busy(&run));
|
||||
}
|
||||
call.confirm(&tab.subject, Some(tab.detail)).await?;
|
||||
let shown_cwd = call.display(&tab.cwd);
|
||||
let target = tab.execution.target();
|
||||
let run = runs
|
||||
.prepare(call.root(), call.window(), &name, &tab.command, &shown_cwd, tab.execution)
|
||||
.map_err(|r| busy(&r))?;
|
||||
let request = ide_core::event::McpUiRequest::AgentRun {
|
||||
name: name.clone(),
|
||||
command: tab.command,
|
||||
cwd: tab.cwd.into(),
|
||||
env: tab.env.into_iter().collect(),
|
||||
target,
|
||||
};
|
||||
if let Err(e) = call.ask(request).await {
|
||||
let error = run.start_error();
|
||||
runs.abandon(&run);
|
||||
return Err(match error {
|
||||
Some(error) => IdeError::invalid(format!("`{name}` did not start: {error}")),
|
||||
None => e,
|
||||
});
|
||||
}
|
||||
if let Some(error) = run.start_error() {
|
||||
return Err(IdeError::invalid(format!("`{name}` did not start: {error}")));
|
||||
}
|
||||
let from = run.process_offset();
|
||||
let end = run.wait(deadline, ready.as_ref(), from, &call.cancel).await?;
|
||||
let mut extra = output_view(call, &run, from)?;
|
||||
extra.insert("waitEnded".into(), end.as_str().into());
|
||||
extra.extend(tab.extra);
|
||||
result(&run, extra)
|
||||
}
|
||||
|
||||
pub fn run_command() -> Tool {
|
||||
Tool::new(
|
||||
"run_command",
|
||||
@@ -154,13 +216,6 @@ process) and its output so far.{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
|
||||
None => call.root().to_path_buf(),
|
||||
};
|
||||
let env = call.args.get("envs").filter(|v| !v.is_null()).map(|_| call.str_map("envs")).transpose()?;
|
||||
let deadline = deadline(&call, RUN_TIMEOUT_MS)?;
|
||||
let ready = pattern(&call)?;
|
||||
let host = call.host();
|
||||
let runs = &host.mcp_agent_runs;
|
||||
if let Some(run) = runs.get(call.root(), &name).filter(|r| r.running()) {
|
||||
return Err(busy(&run));
|
||||
}
|
||||
let shown_cwd = call.display(&cwd);
|
||||
let mut detail = format!(
|
||||
"{command}\n\nTab: {name}\nWorking directory: {}",
|
||||
@@ -169,30 +224,17 @@ process) and its output so far.{OUTPUT}{SEQUENCE}{INTERVENTIONS}"
|
||||
for (key, value) in env.iter().flatten() {
|
||||
detail.push_str(&format!("\n{key}={value}"));
|
||||
}
|
||||
call.confirm(&name, Some(detail)).await?;
|
||||
let run = runs.prepare(call.root(), call.window(), &name, &command, &shown_cwd).map_err(|r| busy(&r))?;
|
||||
let request = ide_core::event::McpUiRequest::AgentRun {
|
||||
name: name.clone(),
|
||||
command: command.clone(),
|
||||
cwd: cwd.into(),
|
||||
env: env.unwrap_or_default().into_iter().collect(),
|
||||
let tab = Tab {
|
||||
subject: name.clone(),
|
||||
name,
|
||||
command,
|
||||
detail,
|
||||
cwd,
|
||||
env: env.unwrap_or_default(),
|
||||
execution: Execution::Host,
|
||||
extra: Map::new(),
|
||||
};
|
||||
if let Err(e) = call.ask(request).await {
|
||||
let error = run.start_error();
|
||||
runs.abandon(&run);
|
||||
return Err(match error {
|
||||
Some(error) => IdeError::invalid(format!("`{name}` did not start: {error}")),
|
||||
None => e,
|
||||
});
|
||||
}
|
||||
if let Some(error) = run.start_error() {
|
||||
return Err(IdeError::invalid(format!("`{name}` did not start: {error}")));
|
||||
}
|
||||
let from = run.process_offset();
|
||||
let end = run.wait(deadline, ready.as_ref(), from, &call.cancel).await?;
|
||||
let mut extra = output_view(&call, &run, from)?;
|
||||
extra.insert("waitEnded".into(), end.as_str().into());
|
||||
result(&run, extra)
|
||||
start_in_tab(&call, tab, RUN_TIMEOUT_MS).await
|
||||
},
|
||||
)
|
||||
.write()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Run configurations, builds and agent commands; every start asks the user first.
|
||||
|
||||
pub(crate) mod agent;
|
||||
mod agent_tools;
|
||||
pub(crate) mod agent_tools;
|
||||
mod build;
|
||||
pub(crate) mod configs;
|
||||
mod output;
|
||||
|
||||
@@ -668,6 +668,8 @@ mod tests {
|
||||
selection_range: Range::new(range.start, range.start),
|
||||
children,
|
||||
visibility: None,
|
||||
implements: None,
|
||||
self_type: None,
|
||||
};
|
||||
let method = outline(
|
||||
"total",
|
||||
|
||||
@@ -178,6 +178,11 @@ pub const FLUTTER_BUILD_MENU: &str = "build.flutter";
|
||||
pub const DYNAMIC_XCODE_BUILD: &str = "xcodeBuild";
|
||||
/// Id (and `menu.` label key) of the Build › Xcode submenu.
|
||||
pub const XCODE_BUILD_MENU: &str = "build.xcode";
|
||||
/// Build › CMake: Reload CMake Project, Reset Cache and Reload, CMake Settings, filled only when
|
||||
/// the project has CMake configurations. A submenu after Build › Xcode when it has items.
|
||||
pub const DYNAMIC_CMAKE_BUILD: &str = "cmakeBuild";
|
||||
/// Id (and `menu.` label key) of the Build › CMake submenu.
|
||||
pub const CMAKE_BUILD_MENU: &str = "build.cmake";
|
||||
|
||||
/// The submenu (id, English label) a dynamic slot is shown as when it has items, followed by a
|
||||
/// separator; `None`: its items are listed in place.
|
||||
@@ -185,6 +190,7 @@ pub fn dynamic_submenu(slot: &str) -> Option<(&'static str, &'static str)> {
|
||||
match slot {
|
||||
DYNAMIC_FLUTTER_BUILD => Some((FLUTTER_BUILD_MENU, "Flutter")),
|
||||
DYNAMIC_XCODE_BUILD => Some((XCODE_BUILD_MENU, "Xcode")),
|
||||
DYNAMIC_CMAKE_BUILD => Some((CMAKE_BUILD_MENU, "CMake")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -264,7 +270,22 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("file.save", "Save All"),
|
||||
act("templates.saveFileAsTemplate", "Save File as Template…"),
|
||||
act("file.reloadAllFromDisk", "Reload All from Disk"),
|
||||
sub("fileProperties", "File Properties", vec![act("file.toggleReadOnly", "Make File Read-only / Writable")]),
|
||||
sub(
|
||||
"fileProperties",
|
||||
"File Properties",
|
||||
vec![
|
||||
sub(
|
||||
"lineSeparators",
|
||||
"Line Separators",
|
||||
vec![
|
||||
act("file.lineSeparators.crLf", "CRLF - Windows (\\r\\n)"),
|
||||
act("file.lineSeparators.lf", "LF - Unix and macOS (\\n)"),
|
||||
act("file.lineSeparators.cr", "CR - Classic Mac OS (\\r)"),
|
||||
],
|
||||
),
|
||||
act("file.toggleReadOnly", "Make File Read-only / Writable"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
act("file.projectStructure", "Project Structure…"),
|
||||
SEP,
|
||||
@@ -640,6 +661,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
vec![
|
||||
Entry::Dynamic(DYNAMIC_FLUTTER_BUILD),
|
||||
Entry::Dynamic(DYNAMIC_XCODE_BUILD),
|
||||
Entry::Dynamic(DYNAMIC_CMAKE_BUILD),
|
||||
act("build.buildProject", "Build Project"),
|
||||
act("build.buildModule", "Build Module"),
|
||||
act("build.compileFile", "Recompile"),
|
||||
@@ -735,6 +757,19 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("vcs.syncSubmodules", "Sync Submodule URLs"),
|
||||
],
|
||||
),
|
||||
// What only a Subversion working copy has; disabled for a Git repository.
|
||||
sub(
|
||||
"subversion",
|
||||
"Subversion",
|
||||
vec![
|
||||
act("svn.merge", "Merge From…"),
|
||||
act("svn.cleanup", "Cleanup"),
|
||||
act("svn.lock", "Lock…"),
|
||||
act("svn.unlock", "Unlock"),
|
||||
act("svn.relocate", "Relocate…"),
|
||||
act("svn.properties", "Properties…"),
|
||||
],
|
||||
),
|
||||
SEP,
|
||||
act("vcs.showLog", "Show Git Log"),
|
||||
sub(
|
||||
@@ -822,6 +857,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("deployment.downloadFromDefault", "Download from Default Server"),
|
||||
act("deployment.downloadFrom", "Download from…"),
|
||||
act("deployment.syncWith", "Sync with Deployed…"),
|
||||
act("deployment.compareWithDefault", "Compare with Deployed Version"),
|
||||
act("deployment.compareWith", "Compare with Deployed Version on…"),
|
||||
act("deployment.deleteFromServer", "Delete from Server"),
|
||||
SEP,
|
||||
act("deployment.toggleAutoUpload", "Automatic Upload"),
|
||||
@@ -903,6 +940,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
act("editor.moveToOppositeGroup", "Move to Opposite Group"),
|
||||
act("editor.openInOppositeGroup", "Open in Opposite Group"),
|
||||
act("editor.changeSplitOrientation", "Change Splitter Orientation"),
|
||||
act("editor.maximizeInSplit", "Maximize Editor / Normalize Splits"),
|
||||
act("editor.unsplitAll", "Unsplit All"),
|
||||
act("editor.nextSplitter", "Go to Next Splitter"),
|
||||
act("editor.prevSplitter", "Go to Previous Splitter"),
|
||||
|
||||
Loaded 100 of 1402 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача