Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 4f697bf274 fix(settings): align field edges across settings sections 2026-12-02 19:07:39 +08:00
Ivan 2221afad01 feat(mcp): tools for the project's dev container (#7378)
Five MCP tools report, start, rebuild and run commands in the project's dev container through the IDE's own Docker and Dev Containers support, inside its trust checks and confirmations.

Runs keep a structured host-or-container target and refuse to start when an approved container target is missing or no longer matches; the container is identified by both devcontainer labels, pinned to the approved ID, and its config may not escape the project through a symlink. The tools are listed and dispatched only on the local desktop.

Closes #7293

Co-authored-by: Pecnikas <[email protected]>
2026-12-02 19:06:17 +08:00
l0ng-ai 471bce2bb1 test: make the Windows Rust job pass again (#7516)
git_workflows: the 700 overlong paths of the two command-line batching tests exceeded Windows' 260-char MAX_PATH (Git for Windows enforces it without core.longpaths), so git add failed; on Windows they use shorter names that still overflow its 32,000-char command line. xcode_index: the test formatted a path into buildServer.json, and a Windows path's backslashes made the JSON invalid; it is built with serde_json now.
2026-12-02 18:46:03 +08:00
Qslia b630dfad55 fix(notebook): keep source lines whole when typing in a cell (#7502)
Rewriting a cell's source kept every old source element that still prefixed or suffixed the new text, including partial lines, so code typed character by character was saved one character per element and showed one character per line in VS Code and Cursor. Only whole lines (an element ending in a newline, starting at a line start) are reused now; the line being edited is written as one element, the notebook's own JSON layout and string-valued sources stay as they were, and a source already split into characters is joined into lines where it is edited.

Co-authored-by: qslia <[email protected]>
2026-12-02 18:41:09 +08:00
LU XIANGRUIтаwildcatDownstairs 74b50f7592 test(new-project): make apple_app_trees pass on Windows (#7507)
A Windows checkout gives the generator templates CRLF line endings; the test normalizes them before comparing the generated Swift file's first lines. Generated projects are unchanged.

Closes #7506

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:37:42 +08:00
l0ng-ai 95bc3622ab feat(vue): pick the managed Vue language server version per project (#7513)
Vue 2 projects (detected from package.json, or the installed vue for alias/workspace specs) use vue-language-server 3.0.x, which still supports Vue 2; other projects use latest. Each release installs in its own directory with its paired TypeScript. A version setting overrides detection.

Fixes #7357
2026-12-02 18:36:19 +08:00
l0ng-ai b911366115 fix(java): give project-wide Java usages time instead of falling back to a wider search (#7511)
Find Usages in large projects went through the Java usages extension with the default 30 s timeout and, when it ran out, fell back to jdtls' wider textDocument/references, so the user waited for both. A project-wide usages request now gets 300 s (still cancellable), and an extension timeout is returned as a timeout instead of starting the fallback; other extension failures still fall back.

Fixes #7376
2026-12-02 18:31:05 +08:00
l0ng-ai b2a9d105e2 feat(search): Endpoints tab in Search Everywhere and a Go to Endpoint action (#7510)
The request mappings the IDE indexes were only a section of Search Everywhere's All tab. They now have their own Endpoints tab, as in IDEA Ultimate (also /endpoints), and Navigate > Go to Endpoint... opens it with the editor selection as the query. No default shortcut; bindable in Settings > Keymap.
2026-12-02 18:29:03 +08:00
l0ng-ai b83c2cf11a docs(readme): refresh the WeChat group QR code 2026-12-02 18:26:46 +08:00
l0ng-ai 6648f502f1 feat(services): list Spring Boot configurations by default and show their address (#7508)
Projects without a saved Services list show Spring Boot run configurations by default; a saved list stays authoritative. Running Spring Boot nodes show the port and announced context path for runs and debug sessions.

Fixes #7346
2026-12-02 18:25:48 +08:00
LU XIANGRUIтаwildcatDownstairs 115003f0b6 feat(nuget): central package management awareness and one-click update (#7434)
The NuGet Packages window reads Directory.Packages.props: each package shows where its version is defined or pinned and any VersionOverride, and Check NuGet Package Updates offers an update to the newest version.

Metadata and update checks are scoped to the selected project, configuration and framework and run independently; one-click updates are withheld when compatibility across target frameworks is not verified.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:23:33 +08:00
nako-ruruтаnako-ruru 02d912d72a feat(keymap): add NetBeans keymap presets for Windows/Linux and macOS (#7481)
Adds NetBeans presets beside IntelliJ, Eclipse and VS Code, taken from JetBrains' NetBeans keymap (keymaps/NetBeans 6.5.xml) on top of the IntelliJ defaults; actions without an OpenIDEA counterpart keep the IntelliJ binding. IDEA's EditorDeleteLine now maps to code.deleteLine for imported keymaps.

Co-authored-by: nako-ruru <[email protected]>
2026-12-02 18:21:59 +08:00
LU XIANGRUIтаwildcatDownstairs 70fe0e6653 feat(nuget): manage NuGet package sources (#7424)
A Package sources panel lists NuGet sources and adds, enables, disables or removes them through dotnet nuget, writing to a chosen NuGet.Config under the workspace or the user-wide file.

Edits go only to the config file that defines a source, stale work is cancelled when the project or selection changes, and URL credentials are redacted from errors. CI installs SDK 10 and 11 for the real-CLI tests.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:21:34 +08:00
LU XIANGRUIтаwildcatDownstairs 950bf986d6 fix(libraries): tell same-named library roots apart in External Libraries (#7463)
A uv venv reports its own .venv/Lib beside the base interpreter's Lib, so External Libraries showed two rows called Lib. Roots sharing a name in one SDK group now show their parent folder after "library root". A root inside a sibling root (.venv/Lib/site-packages under .venv/Lib) also got the same tree key as its row in the sibling's listing, so the virtual list drew two rows on top of each other; nested roots now get their own key namespace.

Refs #7444

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:21:02 +08:00
LU XIANGRUIтаwildcatDownstairs 310d923480 feat(dotnet): show solution folders and solution items in the Project view (#7435)
Solution folders from .sln and .slnx files appear as nested nodes under the solution, holding their projects and solution items; projects outside every folder follow.

Parent folders an SLNX file only implies are created, literal slashes in legacy folder names are kept, and uppercase .SLNX extensions are accepted.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:19:58 +08:00
l0ng-ai 0c506fa479 style: format the Razor scanner and use spacing tokens in SVN working copies (#7505)
Fixes pnpm format:check and the spacing-scale test on main: two for headers in the Razor scanner are formatted as oxfmt expects, and the SVN Working Copies panel uses --space-* tokens for its gaps (same values, no visible change).
2026-12-02 18:18:43 +08:00
LU XIANGRUIтаwildcatDownstairs bc86836492 feat(dotnet): Dependencies node under each project in the Project view (#7430)
Each .NET project lists its packages, project references, framework references and analyzers under a Dependencies node.

Expandable .csproj rows keep their file behaviour (open, rename, context menu), same-named references and analyzers stay distinct, and the evaluated target framework is labelled.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:16:53 +08:00
l0ng-ai dead55af21 feat(windows): open project windows on the display last worked on (#7123)
On Windows, the display of the last focused or moved project window is saved to last-display.json. A project window opened without a position of its own is centred on that display and sized to its work area while the display is still connected and unchanged; otherwise it opens on the primary display. Cascaded windows keep their place, and macOS and Linux are unchanged.

Fixes #7031
2026-12-02 18:16:48 +08:00
langxpтаkradme c7a4201ce9 fix(agents): support context menu and stable selection (#7490)
Right-clicking the agent composer offered no editing menu. It now has Cut, Copy and Paste; menu paste goes through the same copied-code, link, project-path and long-text handling as a keyboard paste, and falls back to a clipboard image. A deferred multi-click selection handler no longer moves a selection that already left its conversation row back to it, which scrolled the conversation.

Co-authored-by: kradme <[email protected]>
2026-12-02 18:16:31 +08:00
l0ng-ai 91cf66e72e refactor(agents): simplify the automations dashboard and editor (#7491)
The Agents sidebar has a single clock button for Automations, with a dot for unread runs or runs waiting for input. The dashboard puts search and tabs on one row and moves import and pause-all into an Options menu. The automation dialog keeps provider tools with the prompt, moves permissions, continuity and run limits under Advanced, and expands Advanced when an edited schedule uses non-default settings.
2026-12-02 18:16:25 +08:00
l0ng-ai 4a87022e58 fix(agents): retry Cursor capacity errors and show attempt counts (#7500)
Cursor ACP can end a turn successfully while streaming a resource_exhausted error. Such turns now continue in the same conversation after 5, 15 and 30 seconds, with the countdown and attempt number in the working row and each continuation numbered in the history. Stop cancels the wait and Send Now replaces it; after three failed retries the task pauses with a manual Retry button.
2026-12-02 18:15:55 +08:00
l0ng-ai c92bd0999b fix(agents): render ANSI styles in tool output (#7495)
Agent tool cards now render ANSI colours and emphasis in command output with the shared console parser, instead of showing raw escape codes. Plain output keeps its text rendering path.
2026-12-02 18:15:39 +08:00
l0ng-ai 880835f0ac fix(agents): clean up plugin settings layout (#7497)
Plugin rows show the name and version with secondary metadata on its own line, keeping enable toggles and review buttons clear of the text. Manifest formats and marketplace move into the expandable details, and the list adapts to narrow Settings panes.
2026-12-02 18:15:12 +08:00
l0ng-ai ce938df81b fix(welcome): flatten recent project lists across hosts (#7504) 2026-12-02 18:05:39 +08:00
LU XIANGRUIтаwildcatDownstairs 9abe3d7e3c fix(editor): show a followed plugin theme's colours and font styles in Color Scheme (#7474)
With a plugin theme active and the scheme on Theme default, Settings > Editor > Color Scheme resolved attributes and the preview against the built-in scheme instead of the plugin theme's tokens the editor paints with, so an italic comment showed unchecked and clearing it saved nothing. resolvedSchemeTokens / resolvedAttribute now take the followed theme's tokens under the user's overrides, the page shows the plugin theme's name, and Markdown comments follow the comment style variable.

Closes #7453

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:05:29 +08:00
LU XIANGRUIтаwildcatDownstairs 4e5ae49aa9 feat(dotnet): edit solutions and project references from the Project view (#7426)
Add Existing Project, Add/Remove Project Reference and Remove from Solution on .NET solution and project nodes, running dotnet sln/reference one at a time.

Queued edits are cancelled when the workspace changes, the tree refreshes after a partially failed CLI edit, and solution paths are normalized before comparing them.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:05:25 +08:00
l0ng-ai 9443517d1c docs: restore AGENTS.md and add PR evidence rules with a pr skill (#7498)
Restore AGENTS.md (CLAUDE.md links to it) and the verify skill, and add a pr skill covering scope, checks to run, the evidence each kind of change needs and a UX consistency review against DESIGN.md and PRODUCT.md.

The PR template lists evidence by change type, and the PR check also asks for screenshots or a recording when a PR changes UI files under src/, unless the description says "No visible change".
2026-12-02 17:50:30 +08:00
l0ng-ai 29f6131f9d fix(plugins): keep plugin gutter markers while their file is reindexed (#7499)
An edit invalidated the file's indexed markers and the host has none for the new version until it is indexed again, so the gutter icon area emptied, collapsed and shifted the code sideways after every Enter or line copy. Markers now stay, mapped through the edits, until the reindex settles; editors no longer re-place a kept entry at its old lines; plugin line markers likewise stay until the new ones arrive.

Fixes #7422
2026-12-02 17:50:27 +08:00
Isaac Gallartтаigallart 4027b8341f fix(run): keep configuration fields aligned when resizing on Linux (#7470)
Fixes #7469. On Linux, WebKitGTK shifts the tracks of the scrolling options subgrid as the Run/Debug Configurations dialog resizes, moving fields away from the Name column. There the header and the options now share a fixed 150px label column instead of a subgrid; macOS and Windows keep the subgrid whose label column fits the longest label, and narrow panes keep the stacked layout.

Co-authored-by: igallart <[email protected]>
2026-12-02 17:41:13 +08:00
l0ng-ai ddc483fd2a feat(java): end a completed break or continue with a semicolon (#7493)
Fixes #7358. Completing break or continue in Java inserted the bare keyword. As in IDEA's keyword completion, it now ends with a semicolon, or with a space inside a labeled statement where the keyword can name the label; nothing is added when the line already continues. return is left alone.
2026-12-02 17:36:08 +08:00
l0ng-ai 23d81a2b3d feat(tools): show language server updates in the status bar (#7492)
Fixes #7365. Newer versions of the IDE-installed language servers were only visible in Settings > Language Servers. features/tools now looks for updates a minute after startup, at most once a day (the last result is stored and shown meanwhile in every window, and installing drops it), and publishes them through workbench/contributions. The status bar's Language Servers widget marks that an update exists and gives the server's popup row an Update button.
2026-12-02 17:34:26 +08:00
178 змінених файлів з 9551 додано та 1826 видалено

No files matched your search

+129
Переглянути файл
@@ -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.
+59
Переглянути файл
@@ -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.
+1
Переглянути файл
@@ -0,0 +1 @@
../../.agents/skills/pr
+1
Переглянути файл
@@ -0,0 +1 @@
../../.agents/skills/verify
Бінарний файл не відображається.

До

Ширина:  |  Висота:  |  Розмір: 169 KiB

Після

Ширина:  |  Висота:  |  Розмір: 192 KiB

+14 -5
Переглянути файл
@@ -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
+6
Переглянути файл
@@ -370,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
+20 -2
Переглянути файл
@@ -1,9 +1,9 @@
name: PR check
on:
# pull_request_target so the check can label PRs from forks. It never checks out
# or runs PR code: it only reads the PR title and description.
# or runs PR code: it only reads the PR title, description and changed file names.
pull_request_target:
types: [opened, edited, reopened, ready_for_review]
types: [opened, edited, reopened, ready_for_review, synchronize]
permissions:
issues: write
@@ -34,6 +34,24 @@ jobs:
const { owner, repo } = context.repo;
const issue_number = pr.number;
if (verified && verified[1].trim()) {
const section = verified[1];
const hasMedia =
/!\[[^\]]*\]\(|<img\b|<video\b|github\.com\/user-attachments\/|https?:\/\/\S+\.(png|jpe?g|gif|webp|mp4|mov|webm)\b/i.test(section);
const optedOut = /no visible change/i.test(section);
if (!hasMedia && !optedOut) {
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number: issue_number, per_page: 100 });
const ui = files
.filter(f => f.status !== 'removed')
.map(f => f.filename)
.filter(name => /^src\/.*\.(tsx|css)$/.test(name) && !/\.(test|spec)\.tsx$/.test(name));
if (ui.length) {
const shown = ui.slice(0, 3).map(n => `\`${n}\``).join(', ') + (ui.length > 3 ? ', …' : '');
problems.push(`This PR changes UI files (${shown}). Add before/after screenshots, or a recording for interactions, to **How it was verified**; if nothing users see changed, write "No visible change" and say what you checked.`);
}
}
}
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
const existing = comments.find(c => c.user.type === 'Bot' && c.body.includes(MARKER));
const labeled = pr.labels.some(l => l.name === LABEL);
+6 -5
Переглянути файл
@@ -33,12 +33,13 @@ target/
test-results/
playwright-report/
# Local AI agent files
AGENTS.md
CLAUDE.md
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
CLAUDE.local.md
.agents/
.claude/
.claude/*
!.claude/skills/
.claude/skills/*
!.claude/skills/pr
!.claude/skills/verify
# Local reference screenshots
pycharm-screenshots/
+197
Переглянути файл
@@ -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
+1
Переглянути файл
@@ -0,0 +1 @@
AGENTS.md
+8 -2
Переглянути файл
@@ -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.
+112 -17
Переглянути файл
@@ -154,6 +154,9 @@ const REPLAY_GRACE: Duration = Duration::from_millis(300);
/// Notifications are delivered on their own thread: the last `session/update`s of a turn
/// can trail its `session/prompt` response by this much.
const TURN_GRACE: Duration = Duration::from_millis(100);
const CURSOR_CAPACITY_MESSAGE: &str = "Error: RetriableError: [resource_exhausted] Error";
const CURSOR_RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(5), Duration::from_secs(15), Duration::from_secs(30)];
/// A session open can arrive before the agent finishes activating its plugins and MCP
/// servers (OpenCode: "Location plugins did not finish activating"). That is a transient
/// startup race. The window bounds the session-open requests and the waits between them.
@@ -2815,6 +2818,7 @@ impl AgentManager {
let approval_drifted = intr.approval_mode != current_fp;
let eligible = first_reconcile
&& policy_allows
&& intr.reason != InterruptionReason::CursorCapacity
&& safe_session
&& !intr.was_waiting_for_input
&& !approval_drifted
@@ -3619,6 +3623,7 @@ impl AgentManager {
};
self.detach_sinks();
for task in tasks {
task.network_poke.notify_waiters();
let was_live = task.kill().is_some();
task.finish_shutdown(was_live, reason);
}
@@ -4204,6 +4209,7 @@ impl Task {
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
});
}
if in_flight {
@@ -4443,12 +4449,13 @@ impl Task {
self.explicit_stop.store(false, Ordering::Release);
self.force_resume_now.store(false, Ordering::Release);
let mut network_resumes_this_turn: u32 = 0;
let mut capacity_retries = 0;
loop {
if self.shared.shut_down_since(epoch) {
return;
}
self.state.lock().active_scheduled_turn = scheduled.clone();
if recovery.is_none() {
if recovery.is_none() || recovery == Some(InterruptionReason::CursorCapacity) {
if let Err(err) = self.verify_worktree_cwd_confined() {
self.state.lock().active_scheduled_turn = None;
return self.fail(Failure::from(err.to_string()), epoch);
@@ -4469,7 +4476,9 @@ impl Task {
}
}
// The message shows before the checkout is recorded, which can take a while in a large repository.
if !self.show_prompt(&prompt, recovery.take(), epoch) {
let retry_attempt = (recovery == Some(InterruptionReason::CursorCapacity) && capacity_retries > 0)
.then_some(capacity_retries as u32);
if !self.show_prompt(&prompt, recovery.take(), retry_attempt, epoch) {
self.state.lock().active_scheduled_turn = None;
return;
}
@@ -4481,11 +4490,6 @@ impl Task {
if self.shared.shut_down_since(epoch) {
return;
}
let explicit_stop = self.explicit_stop.swap(false, Ordering::AcqRel);
if explicit_stop && result.is_err() {
result = Ok("cancelled".into());
}
self.cancel_pending.store(false, Ordering::Release);
tokio::time::sleep(TURN_GRACE).await;
if self.shared.shut_down_since(epoch) {
return;
@@ -4494,13 +4498,41 @@ impl Task {
if self.shared.shut_down_since(epoch) {
return;
}
// Cursor ACP ends the turn successfully even when its final response is a
// capacity error. Check after TURN_GRACE so trailing chunks have arrived.
if self.cursor_at_capacity(&result) {
if self.cancel_pending.load(Ordering::Acquire) || self.send_now.load(Ordering::Acquire) {
result = Ok("cancelled".into());
} else if let Some(&delay) = CURSOR_RETRY_DELAYS.get(capacity_retries) {
capacity_retries += 1;
if self.wait_for_cursor_retry(capacity_retries, delay, epoch).await {
let changed = self.state.lock().history.conversation.end_turn(Some(now_ms()));
self.mark_dirty(changed);
recovery = Some(InterruptionReason::CursorCapacity);
prompt = continuation_prompt_for(InterruptionReason::CursorCapacity);
continue;
}
if self.shared.shut_down_since(epoch) {
return;
}
result = Ok("cancelled".into());
} else {
self.settle_interrupted(InterruptionReason::CursorCapacity, epoch);
return;
}
}
let explicit_stop = self.explicit_stop.swap(false, Ordering::AcqRel);
if explicit_stop && result.is_err() {
result = Ok("cancelled".into());
}
self.cancel_pending.store(false, Ordering::Release);
if let Err(ref failure) = result
&& failure.network
&& !explicit_stop
{
let window_mins = self.effective_recovery_window_mins();
if window_mins == 0 {
self.settle_network_timeout(epoch);
self.settle_interrupted(InterruptionReason::NetworkTimeout, epoch);
return;
}
if network_resumes_this_turn < MAX_NETWORK_RESUMES_PER_TURN {
@@ -4514,7 +4546,7 @@ impl Task {
result = Ok("cancelled".into());
}
NetworkWaitOutcome::Expired => {
self.settle_network_timeout(epoch);
self.settle_interrupted(InterruptionReason::NetworkTimeout, epoch);
return;
}
NetworkWaitOutcome::Recovered { forced } => {
@@ -4526,7 +4558,7 @@ impl Task {
recovery = Some(InterruptionReason::NetworkTimeout);
continue;
} else {
self.settle_network_timeout(epoch);
self.settle_interrupted(InterruptionReason::NetworkTimeout, epoch);
return;
}
}
@@ -4573,6 +4605,7 @@ impl Task {
}
self.emit_task();
network_resumes_this_turn = 0;
capacity_retries = 0;
prompt = queued.prompt;
scheduled = queued.scheduled;
recovery = None;
@@ -4699,9 +4732,53 @@ impl Task {
}
}
fn settle_network_timeout(self: &Arc<Self>, epoch: u64) {
fn cursor_at_capacity(&self, result: &Result<String, Failure>) -> bool {
let s = self.state.lock();
if s.task.provider != "cursor" {
return false;
}
matches!(result, Ok(stop) if stop == "end_turn")
&& matches!(
s.history.conversation.main.entries.last(),
Some(AgentEntry::Agent { text }) if text.trim() == CURSOR_CAPACITY_MESSAGE
)
}
async fn wait_for_cursor_retry(&self, attempt: usize, delay: Duration, epoch: u64) -> bool {
#[cfg(test)]
let delay = delay.min(Duration::from_millis(150));
let until = tokio::time::Instant::now() + delay;
self.set_retry(Some(AgentRetry {
attempt: attempt as u32,
max_retries: Some(CURSOR_RETRY_DELAYS.len() as u32),
retry_at_ms: now_ms() + delay.as_secs_f64() * 1000.0,
error: Some(CURSOR_CAPACITY_MESSAGE.into()),
deadline_ms: None,
}));
loop {
let notified = self.network_poke.notified();
if self.shared.shut_down_since(epoch)
|| self.cancel_pending.load(Ordering::Acquire)
|| self.explicit_stop.load(Ordering::Acquire)
|| self.send_now.load(Ordering::Acquire)
{
return false;
}
if tokio::time::Instant::now() >= until {
return true;
}
tokio::select! {
_ = tokio::time::sleep_until(until) => {}
_ = notified => {}
}
}
}
fn settle_interrupted(self: &Arc<Self>, reason: InterruptionReason, epoch: u64) {
self.cancel_permissions();
if let Some(live) = self.live.lock().take() {
if reason == InterruptionReason::NetworkTimeout
&& let Some(live) = self.live.lock().take()
{
live.peer.kill();
}
let mut file = self.file.lock();
@@ -4714,12 +4791,15 @@ impl Task {
let dirty = s.history.conversation.settle(now);
let approval_mode = config::approval_fingerprint(&s.task.config);
s.busy = false;
s.task.background.clear();
s.background_tasks.clear();
s.active_scheduled_turn = None;
if reason == InterruptionReason::NetworkTimeout {
s.task.background.clear();
s.background_tasks.clear();
}
s.change_status(AgentStatus::Ready, None);
s.task.unread = true;
s.task.interrupted = Some(Box::new(AgentInterrupted {
reason: InterruptionReason::NetworkTimeout,
reason,
at_ms: now,
was_waiting_for_input: false,
approval_mode,
@@ -4733,6 +4813,9 @@ impl Task {
self.mark_dirty(dirty);
self.emit_task();
self.emit_attention(AgentAttentionReason::Failed);
if reason == InterruptionReason::CursorCapacity {
self.release_when_idle();
}
}
/// Drops an idle resumable live session so the next turn reloads it.
@@ -4976,7 +5059,9 @@ impl Task {
let live = self.live.lock().clone().filter(|l| l.capabilities.steer && !l.peer.is_closed());
let running = {
let s = self.state.lock();
s.busy && s.task.status == AgentStatus::Running
// During Cursor backoff the ACP turn has already ended. Send Now must
// cancel the wait and dispatch the new prompt as a turn of its own.
s.busy && s.task.status == AgentStatus::Running && !(s.task.provider == "cursor" && s.task.retry.is_some())
};
let Some((live, method)) = live
.filter(|l| running && (prompt.images.is_empty() || l.capabilities.images))
@@ -5015,12 +5100,19 @@ impl Task {
done_ms: None,
steered: true,
recovery: None,
retry_attempt: None,
});
Ok(())
}
/// Adds the user's message to the conversation and shows the task starting.
fn show_prompt(self: &Arc<Self>, prompt: &AgentPrompt, recovery: Option<InterruptionReason>, epoch: u64) -> bool {
fn show_prompt(
self: &Arc<Self>,
prompt: &AgentPrompt,
recovery: Option<InterruptionReason>,
retry_attempt: Option<u32>,
epoch: u64,
) -> bool {
let attachments = prompt
.files
.iter()
@@ -5044,6 +5136,7 @@ impl Task {
done_ms: None,
steered: false,
recovery,
retry_attempt,
});
s.change_status(if starting { AgentStatus::Starting } else { AgentStatus::Running }, None);
i
@@ -6038,6 +6131,7 @@ impl Task {
done_ms: None,
steered: false,
recovery: None,
retry_attempt: None,
})
}
};
@@ -6733,6 +6827,7 @@ fn continuation_prompt_for(reason: InterruptionReason) -> AgentPrompt {
InterruptionReason::BackendStop => "the OpenIDEA backend stopped",
InterruptionReason::UnexpectedExit => "OpenIDEA exited unexpectedly",
InterruptionReason::NetworkTimeout => "the network connection dropped",
InterruptionReason::CursorCapacity => "Cursor reported a capacity limit",
};
AgentPrompt {
text: format!(
+4
Переглянути файл
@@ -71,6 +71,7 @@ pub enum InterruptionReason {
BackendStop,
UnexpectedExit,
NetworkTimeout,
CursorCapacity,
}
impl From<AgentShutdownReason> for InterruptionReason {
@@ -641,6 +642,9 @@ pub enum AgentEntry {
/// Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn.
#[serde(default)]
recovery: Option<InterruptionReason>,
/// One-based automatic retry number for this continuation.
#[serde(default)]
retry_attempt: Option<u32>,
},
Agent {
text: String,
+97
Переглянути файл
@@ -69,6 +69,8 @@ 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`.
@@ -297,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"}));
@@ -7263,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};
+2
Переглянути файл
@@ -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));
+1 -1
Переглянути файл
@@ -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))]
+5 -5
Переглянути файл
@@ -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)
}
}
+9
Переглянути файл
@@ -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)]
+2
Переглянути файл
@@ -705,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.
+5
Переглянути файл
@@ -403,6 +403,11 @@ pub(crate) fn snapshot(ep: &DockerEndpoint, timeout: Duration) -> Option<DockerS
Some(snap)
}
/// Every container (`docker ps --all`).
pub(crate) fn containers(ep: &DockerEndpoint, timeout: Duration) -> Option<IdeResult<Vec<DockerContainer>>> {
Some(list_containers(&address(ep)?, timeout))
}
fn list_containers(addr: &Address, timeout: Duration) -> IdeResult<Vec<DockerContainer>> {
let body = check(request(addr, "GET", "/containers/json?all=1", timeout)?)?;
Ok(map_containers(&body))
+19
Переглянути файл
@@ -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 {
+72
Переглянути файл
@@ -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));
}
}
+12
Переглянути файл
@@ -9,6 +9,7 @@ pub mod catalogue;
#[cfg(unix)]
pub mod daemon;
pub mod data_dirs;
pub mod devcontainer;
pub mod diagnostics_store;
mod direnv;
pub mod environment;
@@ -91,6 +92,7 @@ impl HostConfig {
}
pub struct Host {
pub(crate) local_desktop: bool,
local_database_tunnels: bool,
/// Finders of non-Git working copies ([`Host::with_vcs_provider`]); Git is built in.
pub(crate) vcs_providers: Vec<Arc<dyn ide_vcs::BackendProvider>>,
@@ -106,6 +108,8 @@ pub struct Host {
pub mcp_requests: mcp::Requests,
/// Commands agents run in the Run tool window (`run_command`).
pub mcp_agent_runs: mcp::AgentRuns,
/// Dev containers a window is attached to; the MCP tools leave them alone.
pub dev_containers_attached: Arc<devcontainer::AttachedContainers>,
/// Projects the MCP server serves without a window.
pub mcp_background: mcp::BackgroundProjects,
/// Host-owned scheduled agent automations and in-session follow-up timers.
@@ -212,6 +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;
@@ -262,6 +272,7 @@ impl Host {
let automations = automations::AutomationService::new(&data_dir, boot_override);
let host = Self {
plugin_host: RwLock::default(),
local_desktop: false,
local_database_tunnels: false,
vcs_providers: Vec::new(),
subversion: None,
@@ -271,6 +282,7 @@ impl Host {
mcp_reports: Default::default(),
mcp_requests: Default::default(),
mcp_agent_runs: Default::default(),
dev_containers_attached: Default::default(),
mcp_background: Default::default(),
automations,
agent_catalogs: Arc::default(),
+894
Переглянути файл
@@ -0,0 +1,894 @@
//! `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), `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());
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 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(),
}
);
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, &current.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 = "/work/app";
const CONFIG_FILE: &str = "/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());
}
}
+20 -5
Переглянути файл
@@ -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);
}
}
+216 -44
Переглянути файл
@@ -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.
+80 -38
Переглянути файл
@@ -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 -1
Переглянути файл
@@ -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;
+38 -2
Переглянути файл
@@ -6,8 +6,9 @@ use crate::Host;
use ide_command::command;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
use ide_docker::{
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
ComposeOp, ContainerOp, DockerContainer, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer,
DockerLogLine, DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget,
RegistryAuth,
};
use ide_ssh::Tunnel;
use std::collections::{BTreeMap, HashMap};
@@ -97,6 +98,41 @@ pub async fn docker_container_op(
host.blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await
}
/// The containers (running or not) that carry every `label` (`key` or `key=value`).
pub(crate) async fn containers_with_labels(
host: &Host,
endpoint: DockerEndpoint,
labels: Vec<String>,
) -> IdeResult<Vec<DockerContainer>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::containers(&endpoint, &labels)).await
}
/// The last `tail` lines of a container's log, without following it.
pub(crate) async fn log_tail(
host: &Host,
endpoint: DockerEndpoint,
id: String,
tail: u32,
timestamps: bool,
cancel: CancellationToken,
) -> IdeResult<Vec<DockerLogLine>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || {
let lines = std::sync::Mutex::new(Vec::new());
ide_docker::logs(&endpoint, &id, tail, false, timestamps, &cancel, &|batch| {
lines.lock().unwrap_or_else(|e| e.into_inner()).extend(batch)
})?;
Ok(lines.into_inner().unwrap_or_else(|e| e.into_inner()))
})
.await
}
pub(crate) async fn stop_containers(host: &Host, endpoint: DockerEndpoint, ids: Vec<String>) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_op(&endpoint, &ids, ContainerOp::Stop)).await
}
#[command(trust = trusted)]
pub async fn docker_remove(
host: &Host,
+3 -5
Переглянути файл
@@ -326,13 +326,11 @@ pub async fn run_start(
let on_output: Emit<OutputChunk> = Arc::new(move |chunk| {
let _ = on_output.send(chunk);
});
let cancel = request.map(|id| host.begin_request(id)).unwrap_or_default();
let operation = config.extras.params.get("plugin.operation").cloned();
let mut config = config;
let agent = match host.project(window) {
Ok(project) => host.mcp_agent_runs.launch(&project.root, window, &mut config),
Err(_) => None,
};
let project = host.project(window)?;
let agent = host.mcp_agent_runs.launch(&project.root, window, &mut config)?;
let cancel = request.map(|id| host.begin_request(id)).unwrap_or_default();
let on_output = match &agent {
Some(agent) => agent.wrap_output(on_output),
None => on_output,
+53 -1
Переглянути файл
@@ -115,6 +115,23 @@ pub struct Project {
pub light: bool,
}
/// Selects the same managed Vue executable for Volar and the vtsls companion plugin.
fn configure_vue_release(settings: &mut ide_core::settings::Settings, project_root: &Path, app_data: &Path) {
let name = ide_tools::vue::SERVER;
if settings.tool_path(name).is_some()
|| settings.language_servers.get(name).is_some_and(|entry| !entry.command.trim().is_empty())
{
return;
}
let release = ide_tools::vue::release(Some(project_root), &settings.tool_downloads.vue_language_server_version);
if release != "latest" {
let path = ide_tools::vue::managed_command(app_data, release);
settings
.tools
.insert(name.into(), ide_core::settings::ToolSettings { path: path.to_string_lossy().into_owned() });
}
}
impl Host {
pub fn open_project(&self, window: &str, root: &Path) -> IdeResult<Arc<Project>> {
let started = std::time::Instant::now();
@@ -241,12 +258,15 @@ impl Host {
let member = ide_workspace::workspace::Workspace::load(&root).ok().flatten().and_then(|w| {
w.projects.into_iter().filter(|p| server_root.starts_with(p)).max_by_key(|p| p.components().count())
});
let effective = member
let mut effective = member
.as_ref()
.map(|p| SettingsStore::load(&config_dir, Some(p)).effective())
.unwrap_or_else(|| settings.effective());
let window_root = &root;
let root = member.as_ref().unwrap_or(window_root);
if matches!(cfg.name.as_str(), "vue-language-server" | "vtsls" | "typescript-language-server") {
configure_vue_release(&mut effective, root, &data_dir);
}
ide_sdk::apply::server_launch_overrides(cfg, &effective);
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
ide_sdk::json_schemas::configure(cfg, root, &effective.json_schemas);
@@ -2834,6 +2854,38 @@ fn notify_transfer(sink: &SharedSink, what: &str, path: &Path, result: IdeResult
});
}
#[cfg(test)]
mod vue_release_tests {
use super::*;
#[test]
fn vue_release_configures_the_managed_command_and_respects_explicit_settings() {
let project = tempfile::tempdir().unwrap();
let root = project.path();
std::fs::write(root.join("package.json"), r#"{"dependencies":{"vue":"^2.7.16"}}"#).unwrap();
let app_data = root.join("data");
let mut settings = ide_core::settings::Settings::default();
configure_vue_release(&mut settings, root, &app_data);
let name = ide_tools::vue::SERVER;
assert_eq!(
ide_sdk::apply::tool_command(root, &settings, name),
Some(ide_tools::vue::managed_command(&app_data, "3.0.x")),
);
let mut settings = ide_core::settings::Settings::default();
settings.tool_downloads.vue_language_server_version = "3.1.2".into();
configure_vue_release(&mut settings, root, &app_data);
assert_eq!(
ide_sdk::apply::tool_command(root, &settings, name),
Some(ide_tools::vue::managed_command(&app_data, "3.1.2")),
);
settings.tools.get_mut(name).unwrap().path = "custom-vue".into();
configure_vue_release(&mut settings, root, &app_data);
assert_eq!(ide_sdk::apply::tool_command(root, &settings, name), Some(root.join("custom-vue")));
}
}
#[cfg(test)]
mod maven_linkage_tests {
#[test]
+259 -5
Переглянути файл
@@ -19,6 +19,10 @@ struct Harness {
}
impl Harness {
fn new() -> Self {
Self::for_host(true)
}
fn for_host(local_desktop: bool) -> Self {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(root.join("src")).unwrap();
@@ -29,14 +33,15 @@ impl Harness {
std::fs::write(root.join(".gitignore"), "ignored/\n").unwrap();
let events = Arc::new(std::sync::Mutex::new(Vec::new()));
let sink = events.clone();
let host = Arc::new(Host::new(HostConfig {
let host = Host::new(HostConfig {
sink_for: Box::new(move |window| {
let (window, events) = (window.to_owned(), sink.clone());
Arc::new(move |e| events.lock().unwrap().push((window.clone(), e)))
}),
local_data_dir: tmp.path().join("local"),
..common::host_config(tmp.path())
}));
});
let host = Arc::new(if local_desktop { host.with_local_desktop() } else { host });
host.open_project("main", &root).unwrap();
Self { host, root, tmp, events }
}
@@ -1120,11 +1125,13 @@ fn run_tool_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>
let request = events.lock().unwrap().iter().find_map(|(_, e)| match e {
IdeEvent::McpRequest {
id,
request: ide_core::event::McpUiRequest::AgentRun { name, command, cwd, env },
} if !handled.contains(id) => Some((*id, name.clone(), command.clone(), cwd.clone(), env.clone())),
request: ide_core::event::McpUiRequest::AgentRun { name, command, cwd, env, target },
} if !handled.contains(id) => {
Some((*id, name.clone(), command.clone(), cwd.clone(), env.clone(), target.clone()))
}
_ => None,
});
let Some((id, name, command, cwd, env)) = request else {
let Some((id, name, command, cwd, env, target)) = request else {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
continue;
};
@@ -1144,6 +1151,7 @@ fn run_tool_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>
extras: Default::default(),
};
config.extras.params.insert(ide_host::mcp::AGENT_PARAM.into(), name);
config.extras.params.insert(ide_host::mcp::TARGET_PARAM.into(), serde_json::to_string(&target).unwrap());
config.extras.target = Some(String::new());
out.lock().unwrap().push(config.clone());
let result =
@@ -2516,3 +2524,249 @@ async fn agent_plugins_ipc_installs_for_a_harness_and_projects_native_children()
.unwrap_err();
assert!(stale.message.contains("changed since they were shown"), "{stale:?}");
}
const DEV_CONTAINER_TOOLS: [&str; 5] =
["devcontainer_status", "devcontainer_logs", "devcontainer_up", "devcontainer_exec", "devcontainer_stop"];
fn dev_container_tools(tools: Vec<ide_mcp::Tool>) -> Vec<String> {
let mut names: Vec<String> = tools.into_iter().map(|t| t.name).filter(|n| n.starts_with("devcontainer_")).collect();
names.sort();
names
}
#[tokio::test(flavor = "multi_thread")]
async fn server_hosts_neither_list_nor_dispatch_dev_container_tools() {
let h = Harness::for_host(false);
h.trust().await;
let registry = Registry::new(h.host.clone());
let tools = registry.tools(&h.root).unwrap();
assert!(tools.iter().any(|t| t.name == "run_command"));
assert!(dev_container_tools(tools).is_empty());
assert!(dev_container_tools(registry.tools_without_project()).is_empty());
for name in DEV_CONTAINER_TOOLS {
assert_eq!(h.error(name, json!({})).await, format!("unknown tool: {name}"));
}
}
#[tokio::test(flavor = "multi_thread")]
async fn an_untrusted_project_lists_only_the_read_only_dev_container_tools() {
let h = Harness::new();
let registry = Registry::new(h.host.clone());
assert!(!h.host.project("main").unwrap().is_trusted());
assert_eq!(dev_container_tools(registry.tools(&h.root).unwrap()), ["devcontainer_logs", "devcontainer_status"]);
// A write tool called all the same is refused before it asks or runs anything.
for tool in ["devcontainer_up", "devcontainer_exec", "devcontainer_stop"] {
let refused = h.error(tool, json!({"name": "x", "command": "true"})).await;
assert_eq!(refused, "Project is in Restricted Mode. Trust the project to enable execution.", "{tool}");
}
assert!(!h.events.lock().unwrap().iter().any(|(_, e)| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
h.trust().await;
let mut all = DEV_CONTAINER_TOOLS.map(str::to_owned).to_vec();
all.sort();
assert_eq!(dev_container_tools(registry.tools(&h.root).unwrap()), all);
}
#[tokio::test(flavor = "multi_thread")]
async fn dev_container_arguments_are_checked_before_docker_is_asked() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
h.set("runWithoutConfirmation", json!(true));
std::fs::create_dir_all(h.root.join(".devcontainer")).unwrap();
std::fs::write(h.root.join(".devcontainer/devcontainer.json"), "{}").unwrap();
std::fs::write(h.tmp.path().join("devcontainer.json"), "{}").unwrap();
let error = |tool: &'static str, args: Value| {
let h = &h;
async move { h.error(tool, args).await }
};
for tail in [0, -3, 5001] {
let e = error("devcontainer_logs", json!({"tail": tail})).await;
assert_eq!(e, "tail must be between 1 and 5000", "{tail}");
}
assert_eq!(error("devcontainer_logs", json!({"tail": "x"})).await, "tail must be an integer");
// `config` is a devcontainer file of the project.
let outside = h.tmp.path().join("devcontainer.json");
let e = error("devcontainer_status", json!({"config": outside})).await;
assert!(e.contains("outside the project"), "{e}");
let e = error("devcontainer_status", json!({"config": "src/a.txt"})).await;
assert_eq!(e, "config must be a devcontainer.json or .devcontainer.json file");
let e = error("devcontainer_status", json!({"config": ".devcontainer/other/devcontainer.json"})).await;
assert!(e.contains("does not exist") || e.contains("no existing parent"), "{e}");
let e = error("devcontainer_up", json!({"config": "../devcontainer.json"})).await;
assert!(e.contains("outside the project"), "{e}");
for timeout in [0, -1] {
let e = error("devcontainer_up", json!({"timeout": timeout})).await;
assert_eq!(e, "timeout must be positive", "{timeout}");
}
// `noCache` belongs to a rebuild; refused before anything is asked.
let e = error("devcontainer_up", json!({"noCache": true})).await;
assert_eq!(e, "noCache needs rebuild: true");
let e = error("devcontainer_up", json!({"rebuild": true, "timeout": 0})).await;
assert_eq!(e, "timeout must be positive");
// `exec` arguments.
let e = error("devcontainer_exec", json!({"name": "t", "command": " "})).await;
assert_eq!(e, "command must not be empty");
for name in ["1A", "A-B", "", "A B", "A=B"] {
let e = error("devcontainer_exec", json!({"name": "t", "command": "true", "envs": {name: "1"}})).await;
assert!(e.contains("is not a valid variable name"), "{name}: {e}");
}
let e = error("devcontainer_exec", json!({"name": "t", "command": "true", "envs": {"A": 1}})).await;
assert_eq!(e, "envs must contain strings");
let e = error("devcontainer_exec", json!({"name": "t", "command": "true", "envs": ["A=1"]})).await;
assert_eq!(e, "envs must be an object");
// Without a window it is refused like `run_command`.
let inventory = h.serve_inventory();
h.host.trust.decide(&inventory, true, false).unwrap();
let e = h.call_at(&inventory, "devcontainer_exec", json!({"name": "t", "command": "true"})).await.unwrap_err();
assert!(e.starts_with("devcontainer_exec needs the project open in a window"), "{e}");
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn dev_container_configs_cannot_escape_the_project_through_symlinks() {
let h = Harness::new();
h.trust().await;
let outside = h.tmp.path().join("devcontainer.json");
std::fs::write(&outside, "{}").unwrap();
std::fs::create_dir(h.root.join(".devcontainer")).unwrap();
for name in [".devcontainer/devcontainer.json", ".devcontainer.json"] {
let link = h.root.join(name);
std::os::unix::fs::symlink(&outside, &link).unwrap();
for (tool, args) in [
("devcontainer_status", json!({})),
("devcontainer_status", json!({"config": name})),
("devcontainer_up", json!({})),
("devcontainer_exec", json!({"name": "t", "command": "true"})),
] {
let error = h.error(tool, args).await;
assert!(error.contains("path is outside the project"), "{tool} ({name}): {error}");
}
std::fs::remove_file(link).unwrap();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_with_only_named_configurations_says_to_pass_one() {
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
h.set("runWithoutConfirmation", json!(true));
std::fs::create_dir_all(h.root.join(".devcontainer/py")).unwrap();
std::fs::write(h.root.join(".devcontainer/py/devcontainer.json"), "{}").unwrap();
for (tool, args) in [("devcontainer_up", json!({})), ("devcontainer_exec", json!({"name": "t", "command": "true"}))]
{
let e = h.error(tool, args).await;
assert!(e.contains("pass `config` with one of .devcontainer/py/devcontainer.json"), "{tool}: {e}");
}
}
/// Runs `docker` with `args`, returning its trimmed output (None when it failed).
fn docker_output(docker: &Path, args: &[&str]) -> Option<String> {
let out = std::process::Command::new(docker).args(args).output().ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned())
}
/// Removes the test containers (never any other) when dropped, also after a panic.
struct TestContainers(PathBuf, Vec<String>);
impl Drop for TestContainers {
fn drop(&mut self) {
for name in &self.1 {
assert!(name.starts_with("oi-mcpdc-test-"));
let _ = std::process::Command::new(&self.0).args(["rm", "-f", name]).output();
}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn dev_container_tools_work_on_the_containers_of_the_project_only() {
let ep = ide_docker::DockerEndpoint::Default;
let ready = tokio::task::spawn_blocking(move || {
matches!(ide_docker::availability(&ep), ide_docker::DockerAvailability::Ready { .. })
&& ide_docker::endpoint_is_local(&ide_docker::DockerEndpoint::Default).unwrap_or(false)
})
.await
.unwrap();
let docker = ide_docker::docker_executable();
let Some(docker) = docker.filter(|_| ready) else {
eprintln!("skipped: no local Docker daemon is ready");
return;
};
if docker_output(&docker, &["image", "inspect", "--format", "{{.Id}}", "alpine:latest"]).is_none() {
eprintln!("skipped: the image alpine:latest is not present locally (it is not pulled here)");
return;
}
let h = Harness::new();
h.trust().await;
h.host.mcp_requests.set_ready("main", true);
h.set("runWithoutConfirmation", json!(true));
std::fs::create_dir_all(h.root.join(".devcontainer")).unwrap();
let config = h.root.join(".devcontainer/devcontainer.json");
std::fs::write(
&config,
r#"{ // comment
"image": "alpine:latest", "forwardPorts": [3000, "db:5432"] }"#,
)
.unwrap();
let pid = std::process::id();
let (a, b) = (format!("oi-mcpdc-test-{pid}-a"), format!("oi-mcpdc-test-{pid}-b"));
let _remove = TestContainers(docker.clone(), vec![a.clone(), b.clone()]);
let folder_label = format!("devcontainer.local_folder={}", h.root.display());
let config_label = format!("devcontainer.config_file={}", config.display());
let run = |name: &str, labels: &[&str]| {
let mut args = vec!["run", "-d", "--init", "--name", name];
for label in labels {
args.extend(["--label", label]);
}
args.extend(["alpine:latest", "sleep", "300"]);
docker_output(&docker, &args).unwrap_or_else(|| panic!("cannot start {name}"))
};
let id_a = run(&a, &[&folder_label, &config_label]);
let id_b = run(&b, &[&folder_label]);
let status = h.json("devcontainer_status", json!({})).await;
assert_eq!(status["docker"], "ready", "{status}");
assert_eq!(
(status["dockerLocal"].as_bool(), status["configFile"].as_str()),
(Some(true), Some(".devcontainer/devcontainer.json"))
);
assert_eq!(status["configFiles"], json!([".devcontainer/devcontainer.json"]));
assert_eq!(status["forwardPorts"], json!([3000, "db:5432"]));
let containers = status["containers"].as_array().unwrap();
assert_eq!(containers.len(), 1, "only the labelled container: {status}");
assert_eq!((containers[0]["id"].as_str(), containers[0]["name"].as_str()), (Some(id_a.as_str()), Some(a.as_str())));
assert_eq!((containers[0]["state"].as_str(), containers[0]["primary"].as_bool()), (Some("running"), Some(true)));
let logs = h.json("devcontainer_logs", json!({"tail": 5})).await;
assert_eq!(logs["containerId"], id_a.as_str());
assert!(logs["lines"].is_array());
let foreign = h.error("devcontainer_logs", json!({"containerId": id_b})).await;
assert_eq!(foreign, format!("container {id_b} does not belong to this project's dev container"));
let short = h.error("devcontainer_logs", json!({"containerId": &id_b[..12]})).await;
assert!(short.ends_with("does not belong to this project's dev container"), "{short}");
// Without the CLI the tools that need it say so, wherever the container is.
if status["cliInstalled"] == false {
for (tool, args) in
[("devcontainer_up", json!({})), ("devcontainer_exec", json!({"name": "t", "command": "true"}))]
{
let e = h.error(tool, args).await;
assert!(e.starts_with("The Dev Containers CLI is not installed"), "{tool}: {e}");
}
}
// A window open in the container keeps it from being stopped.
let held = h.host.dev_containers_attached.hold(&id_a);
let refused = h.error("devcontainer_stop", json!({})).await;
assert!(refused.contains("is open in a window"), "{refused}");
assert_eq!(docker_output(&docker, &["inspect", "-f", "{{.State.Running}}", &a]).as_deref(), Some("true"));
drop(held);
let stopped = h.json("devcontainer_stop", json!({})).await;
assert_eq!(stopped["stopped"], json!([id_a]));
assert_eq!(docker_output(&docker, &["inspect", "-f", "{{.State.Running}}", &a]).as_deref(), Some("false"));
assert_eq!(docker_output(&docker, &["inspect", "-f", "{{.State.Running}}", &b]).as_deref(), Some("true"));
assert_eq!(h.json("devcontainer_stop", json!({})).await["stopped"], json!([]), "nothing runs now");
let status = h.json("devcontainer_status", json!({})).await;
assert_eq!(status["containers"][0]["state"], "exited", "{status}");
}
+30 -2
Переглянути файл
@@ -95,6 +95,9 @@ const DART_SERVER: &str = "dart";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
const COMPLETION_TIMEOUT: Duration = Duration::from_secs(5);
const LONG_TIMEOUT: Duration = Duration::from_secs(30);
/// An explicit Find Usages in Java (#7376): searching a large workspace's sources takes jdtls
/// longer than other requests, and the user cancels it from the Find tool window instead.
const USAGES_TIMEOUT: Duration = Duration::from_secs(300);
fn did_change_content(
sync: SyncKind,
@@ -376,12 +379,19 @@ fn java_method_reference_at(text: &DocText, pos: Pos) -> bool {
before[colon + 2..].trim_start().chars().all(|c| c.is_alphanumeric() || c == '_' || c == '$')
}
const TIMED_OUT: &str = " timed out";
/// Whether `e` is a request that got no answer in time (see `rpc_err`).
fn is_timeout(e: &IdeError) -> bool {
e.kind == ErrorKind::Protocol && e.message.ends_with(TIMED_OUT)
}
fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
match e {
RpcError::Cancelled => IdeError::cancelled(),
RpcError::Server { code, .. } if code == ide_jsonrpc::codes::CONTENT_MODIFIED => IdeError::cancelled(),
RpcError::Closed => IdeError::unavailable(format!("{server} is not running")),
RpcError::Timeout => IdeError::new(ErrorKind::Protocol, format!("{server}: {method} timed out")),
RpcError::Timeout => IdeError::new(ErrorKind::Protocol, format!("{server}: {method}{TIMED_OUT}")),
RpcError::Server { message, .. } => IdeError::new(ErrorKind::Protocol, format!("{server}: {message}")),
RpcError::Protocol(m) => IdeError::new(ErrorKind::Protocol, format!("{server}: {m}")),
}
@@ -2344,7 +2354,7 @@ impl LspManager {
"workspace/executeCommand",
json!({ "command": "openidea.java.usages", "arguments": arguments }),
Some(cancel),
LONG_TIMEOUT,
if project_wide { USAGES_TIMEOUT } else { LONG_TIMEOUT },
)
.await;
if let Err(e) = &result {
@@ -2456,6 +2466,11 @@ impl LspManager {
{
return Err(IdeError::cancelled());
}
// The standard references search the same sources and the dependencies too:
// after a search that ran out of time, it would only make the wait longer.
if is_timeout(&e) {
return Err(e);
}
if !self.java_usages_warned.swap(true, Ordering::Relaxed) {
tracing::warn!("Java usages extension failed; using standard references: {e}");
}
@@ -4904,6 +4919,19 @@ mod send_check {
}
}
#[cfg(test)]
mod timeout_tests {
use super::*;
#[test]
fn a_request_without_an_answer_in_time_is_a_timeout() {
assert!(is_timeout(&rpc_err("jdtls", "workspace/executeCommand", RpcError::Timeout)));
assert!(!is_timeout(&rpc_err("jdtls", "workspace/executeCommand", RpcError::Protocol("bad".into()))));
assert!(!is_timeout(&rpc_err("jdtls", "workspace/executeCommand", RpcError::Cancelled)));
assert!(!is_timeout(&IdeError::new(ErrorKind::Protocol, "jdtls: NoSuchMethodError")));
}
}
#[cfg(test)]
mod code_action_tests {
use super::source_actions_only;
+55 -1
Переглянути файл
@@ -905,7 +905,9 @@ fn rewritten_source(old: Option<&Node>, text: String) -> Node {
let mut start = 0;
while first < parts.len() {
let part = parts[first].string().expect("validated source text");
if !text[start..].starts_with(part) {
// Only whole lines are kept: a part without its newline (typing at the end of a line, or a
// source saved one character per element) is rewritten with the rest of its line.
if !part.ends_with('\n') || !text[start..].starts_with(part) {
break;
}
start += part.len();
@@ -918,6 +920,11 @@ fn rewritten_source(old: Option<&Node>, text: String) -> Node {
if end - start < part.len() || !text[start..end].ends_with(part) {
break;
}
// ...and only from the start of a line.
let at = end - part.len();
if at > 0 && !text[..at].ends_with('\n') {
break;
}
end -= part.len();
last -= 1;
}
@@ -993,3 +1000,50 @@ fn validate_output_node(node: &Node) -> IdeResult<()> {
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn typing_characters_preserves_source_lines() {
let mut source = Node::new(Value::Array(Vec::new()));
for text in ["a", "ab", "abc"] {
source = rewritten_source(Some(&source), text.to_string());
}
let mut actual = String::new();
source.write(&mut actual);
assert_eq!(actual, r#"["abc"]"#);
}
fn written(node: &Node) -> String {
let mut out = String::new();
node.write(&mut out);
out
}
#[test]
fn typing_keeps_one_element_per_line_and_the_untouched_lines() {
let mut source = Node::new(Value::Array(Vec::new()));
let code = "if True:\n print('hello')\nx = 1";
for end in 1..=code.len() {
source = rewritten_source(Some(&source), code[..end].to_string());
}
assert_eq!(written(&source), r#"["if True:\n"," print('hello')\n","x = 1"]"#);
// Typing at the end of the middle line leaves the other lines' elements as they were.
let edited = "if True:\n print('hello!')\nx = 1";
let source = rewritten_source(Some(&source), edited.to_string());
assert_eq!(written(&source), r#"["if True:\n"," print('hello!')\n","x = 1"]"#);
}
#[test]
fn a_source_saved_one_character_per_element_is_joined_into_lines_where_it_is_edited() {
let parts = "ab\ncd".chars().map(|c| Value::String(c.to_string())).collect();
let source = rewritten_source(Some(&Node::new(Value::Array(parts))), "ab\ncde".to_string());
assert_eq!(written(&source), r#"["ab\n","cde"]"#);
}
}
+5
Переглянути файл
@@ -20,6 +20,11 @@ impl Exec {
Self { docker, up, bin }
}
/// The id of the container.
pub fn container(&self) -> &str {
&self.up.container
}
/// The arguments of `docker` for one connection from the container to `<host>:<port>`.
fn connect_args(&self, host: &str, port: u16) -> Vec<String> {
let port = port.to_string();
+284 -2
Переглянути файл
@@ -1,7 +1,84 @@
//! Validated results of the Dev Containers CLI.
//! The Dev Containers CLI: `devcontainer up` and its validated result, and how a folder and
//! configuration are named to the CLI and to the labels it puts on the container.
use ide_core::{IdeError, IdeResult};
use ide_core::cli_process::{CarriageReturn, CliTool, Decoding, Poll, Stream, keep_stderr_line};
use ide_core::{CancellationToken, IdeError, IdeResult};
use parking_lot::Mutex;
use serde::Deserialize;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
/// Building an image (and its features) can take a while on a first open.
pub const UP_TIMEOUT: Duration = Duration::from_secs(30 * 60);
/// The label of a container naming the folder `devcontainer up` was given.
pub const FOLDER_LABEL: &str = "devcontainer.local_folder";
/// The label of a container naming the configuration file it was started from.
pub const CONFIG_LABEL: &str = "devcontainer.config_file";
/// The folder and configuration file the CLI is pointed at. The same values name the container
/// in its labels, which is how the project's container is found again: the folder as opened
/// (not canonicalised) and the configuration as `folder.join(config)`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
folder: PathBuf,
config: Option<PathBuf>,
}
impl Target {
/// `config` is the configuration file itself; `None` leaves it to the CLI (the default one).
pub fn new(folder: impl Into<PathBuf>, config: Option<PathBuf>) -> Self {
// Native separators throughout, as the CLI's `path.resolve` writes the label on Windows.
Self { folder: folder.into(), config: config.map(|c| c.components().collect()) }
}
/// `config` relative to `folder`; blank means the default one.
pub fn relative(folder: &Path, config: &str) -> Self {
let config = config.trim();
Self::new(folder, (!config.is_empty()).then(|| folder.join(config)))
}
pub fn folder(&self) -> &Path {
&self.folder
}
pub fn config(&self) -> Option<&Path> {
self.config.as_deref()
}
/// `--workspace-folder <folder>` and, with a configuration, `--config <file>`.
pub fn args(&self) -> Vec<OsString> {
let mut args = vec![OsString::from("--workspace-folder"), self.folder.clone().into_os_string()];
if let Some(config) = &self.config {
args.extend([OsString::from("--config"), config.clone().into_os_string()]);
}
args
}
/// The value of [`FOLDER_LABEL`] the CLI puts on this folder's container.
pub fn folder_label(&self) -> String {
label_value(&self.folder.to_string_lossy())
}
/// The value of [`CONFIG_LABEL`], when the configuration is known.
pub fn config_label(&self) -> Option<String> {
self.config.as_deref().map(|c| label_value(&c.to_string_lossy()))
}
}
/// A path as the CLI writes it into a label: on Windows its drive letter is lower case
/// (`c:\work\app`), so a label is compared that way.
pub fn label_value(path: &str) -> String {
let mut chars = path.chars();
match (chars.next(), chars.next()) {
(Some(drive), Some(':')) if drive.is_ascii_alphabetic() => {
format!("{}{}", drive.to_ascii_lowercase(), &path[1..])
}
_ => path.to_owned(),
}
}
/// The container `devcontainer up` started, as it reported it.
#[derive(Debug, PartialEq, Eq)]
@@ -60,9 +137,103 @@ pub fn parse_up(stdout: &str) -> IdeResult<Up> {
}
}
/// The folders whose `devcontainer up` the MCP tools run now.
static BUSY: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
/// Holds `folder` as having an `up` or rebuild of the MCP tools running; released on drop.
#[derive(Debug)]
pub struct Busy(PathBuf);
impl Busy {
/// Takes `folder`, or refuses when another start of it runs. Only the MCP tools take it:
/// Reopen in Container does not, as a retry must not be refused for the length of a build.
pub fn take(folder: &Path) -> IdeResult<Self> {
let mut busy = BUSY.lock();
if busy.iter().any(|f| f == folder) {
return Err(IdeError::unavailable(format!(
"devcontainer up is already running for {}; wait for it to finish",
folder.display()
)));
}
busy.push(folder.to_owned());
Ok(Self(folder.to_owned()))
}
}
impl Drop for Busy {
fn drop(&mut self) {
BUSY.lock().retain(|f| *f != self.0);
}
}
/// `devcontainer up` for `target`, with `extra_args` after the standard ones. Blocks until the
/// CLI exits, `timeout` passes or `cancel` fires (the CLI and what it started are then
/// stopped); its log lines go to `on_line`.
pub fn up(
cli: &Path,
docker: &Path,
target: &Target,
extra_args: &[&str],
timeout: Duration,
on_line: &mut dyn FnMut(&str),
cancel: &CancellationToken,
) -> IdeResult<Up> {
const TOOL: CliTool = CliTool::new("devcontainer", Decoding::Utf8Lossy);
let timed_out = || IdeError::unavailable("devcontainer up did not finish in time");
if timeout.is_zero() {
return Err(timed_out());
}
let mut cmd = Command::new(cli);
cmd.arg("up").args(target.args()).arg("--docker-path").arg(docker).args(extra_args);
// Cancelled by `cancel` and, at the deadline, by the watch below: also while the CLI has
// closed its pipes and runs on.
let stop = cancel.child_token();
let mut lines = TOOL.lines(cmd, &stop, CarriageReturn::Dropped)?;
let (finished, deadline) = std::sync::mpsc::channel::<()>();
let watch = stop.clone();
std::thread::spawn(move || {
// Dropping `finished` (the function returned) ends the watch.
if deadline.recv_timeout(timeout) == Err(std::sync::mpsc::RecvTimeoutError::Timeout) {
watch.cancel();
}
});
let _finished = finished;
let (mut stdout, mut log) = (String::new(), Vec::new());
loop {
match lines.poll(&stop, Duration::from_millis(50)) {
Ok(Poll::Line(Stream::Stdout, line)) => {
stdout.push_str(&line);
stdout.push('\n');
}
Ok(Poll::Line(Stream::Stderr, line)) => {
on_line(&line);
if !line.trim().is_empty() {
keep_stderr_line(&mut log, line);
}
}
Ok(Poll::Closed | Poll::Timeout) => {}
Ok(Poll::Finished) => break,
Err(e) if cancel.is_cancelled() => return Err(e),
Err(_) => return Err(timed_out()),
}
}
let status = lines.finish(&stop).map_err(|e| if cancel.is_cancelled() { e } else { timed_out() })?;
let result = parse_up(&stdout);
if status.success() {
return result;
}
let error = result.err().unwrap_or_else(|| IdeError::unavailable(format!("devcontainer up exited with {status}")));
Err(match log.join("\n") {
t if t.is_empty() => error,
t => IdeError::unavailable(format!("{}\n{t}", error.message)),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
use std::time::Instant;
const ID: &str = "3f1c2b9a7d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8";
@@ -99,4 +270,115 @@ mod tests {
}
assert!(is_user("1000:1000") && is_user("node") && is_user("dev.user"));
}
#[test]
fn the_folder_and_configuration_name_the_cli_arguments_and_the_labels() {
let target = Target::relative(Path::new("/work/my app"), " .devcontainer/py/devcontainer.json ");
let config: PathBuf = Path::new("/work/my app/.devcontainer/py/devcontainer.json").components().collect();
let expected: Vec<OsString> =
vec!["--workspace-folder".into(), "/work/my app".into(), "--config".into(), config.clone().into()];
assert_eq!(target.args(), expected);
assert_eq!(target.folder_label(), "/work/my app");
assert_eq!(target.config_label().unwrap(), config.to_string_lossy());
let default = Target::relative(Path::new("/work/app"), "");
assert_eq!(default.args(), ["--workspace-folder", "/work/app"]);
assert_eq!(default.config_label(), None);
}
#[cfg(windows)]
#[test]
fn a_windows_configuration_label_has_native_separators() {
let target = Target::relative(Path::new(r"C:\work\app"), ".devcontainer/py/devcontainer.json");
assert_eq!(target.config_label().unwrap(), r"c:\work\app\.devcontainer\py\devcontainer.json");
}
#[test]
fn a_windows_drive_letter_is_lower_case_in_a_label() {
assert_eq!(label_value(r"C:\Users\me\app"), r"c:\Users\me\app");
assert_eq!(label_value(r"c:\Users\me\app"), r"c:\Users\me\app");
assert_eq!(label_value("/Users/me/C:/app"), "/Users/me/C:/app");
assert_eq!(label_value("C"), "C");
assert_eq!(label_value(""), "");
}
#[cfg(unix)]
fn fake_cli(dir: &Path, script: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let cli = dir.join("devcontainer");
std::fs::write(&cli, format!("#!/bin/sh\n{script}\n")).unwrap();
std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap();
cli
}
#[test]
fn a_folder_is_held_by_one_start_at_a_time() {
let folder = Path::new("/work/held");
let first = Busy::take(folder).unwrap();
assert!(Busy::take(folder).unwrap_err().message.contains("already running"));
let other = Busy::take(Path::new("/work/other")).unwrap();
drop(first);
drop(Busy::take(folder).unwrap());
drop(other);
}
#[cfg(unix)]
#[test]
fn up_stops_the_cli_on_cancel() {
let dir = tempfile::tempdir().unwrap();
let started = dir.path().join("started");
let cli = fake_cli(dir.path(), &format!("touch '{}'\nsleep 30 & wait", started.display()));
let target = Target::new(dir.path().join("app"), None);
let cancel = CancellationToken::new();
let slow = {
let (cancel, target) = (cancel.clone(), target.clone());
std::thread::spawn(move || up(&cli, Path::new("docker"), &target, &[], UP_TIMEOUT, &mut |_| {}, &cancel))
};
while !started.exists() {
std::thread::sleep(Duration::from_millis(10));
}
cancel.cancel();
assert_eq!(slow.join().unwrap().unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
}
#[cfg(unix)]
#[test]
fn up_stops_a_cli_that_closed_its_pipes_and_runs_on() {
let dir = tempfile::tempdir().unwrap();
let cli = fake_cli(dir.path(), "exec 1>&- 2>&-\nsleep 30");
let target = Target::new(dir.path().join("app"), None);
let began = Instant::now();
let err = up(
&cli,
Path::new("docker"),
&target,
&[],
Duration::from_millis(300),
&mut |_| {},
&CancellationToken::new(),
)
.unwrap_err();
assert!(err.message.contains("did not finish in time"), "{}", err.message);
assert!(began.elapsed() < Duration::from_secs(10));
}
#[cfg(unix)]
#[test]
fn up_stops_a_cli_that_outlives_the_timeout() {
let dir = tempfile::tempdir().unwrap();
let cli = fake_cli(dir.path(), "sleep 30");
let target = Target::new(dir.path().join("app"), None);
let began = Instant::now();
let err = up(
&cli,
Path::new("docker"),
&target,
&[],
Duration::from_millis(200),
&mut |_| {},
&CancellationToken::new(),
)
.unwrap_err();
assert!(err.message.contains("did not finish in time"), "{}", err.message);
assert!(began.elapsed() < Duration::from_secs(10));
}
}
+2 -1
Переглянути файл
@@ -147,8 +147,9 @@ mod tests {
let root = tmp.path();
assert_eq!(xcode_build_root(root), None);
let dd = root.join("DerivedData/App-abc");
// Built as JSON, not by formatting: a Windows path's backslashes need escaping.
let config =
|kind: &str| format!(r#"{{"name":"xcode build server","kind":"{kind}","build_root":"{}"}}"#, dd.display());
|kind: &str| serde_json::json!({"name": "xcode build server", "kind": kind, "build_root": dd}).to_string();
std::fs::write(root.join("buildServer.json"), config("manual")).unwrap();
assert_eq!(xcode_build_root(root), None, "a hand-written .compile config");
std::fs::write(root.join("buildServer.json"), r#"{"name":"sourcekit-xcode-bsp","argv":["x"]}"#).unwrap();
+2 -1
Переглянути файл
@@ -430,7 +430,8 @@ fn apple_app_trees() {
);
let app = std::fs::read_to_string(dir.join("My App/My_AppApp.swift")).unwrap();
assert!(app.contains("struct My_AppApp: App"), "{app}");
let test = std::fs::read_to_string(dir.join("My AppTests/My AppTests.swift")).unwrap();
// A Windows checkout gives the generator's templates CRLF line endings.
let test = std::fs::read_to_string(dir.join("My AppTests/My AppTests.swift")).unwrap().replace("\r\n", "\n");
assert!(test.starts_with("import Testing\n@testable import My_App\n"), "{test}");
let pbxproj = std::fs::read_to_string(dir.join("My App.xcodeproj/project.pbxproj")).unwrap();
assert!(pbxproj.contains("PRODUCT_BUNDLE_IDENTIFIER = \"com.acme.My-App\";"), "{pbxproj}");
+49 -8
Переглянути файл
@@ -29,6 +29,7 @@ mod process;
pub mod registry;
pub mod server;
pub mod sources;
pub mod vue;
use ide_core::error::ErrorKind;
use ide_core::settings::ToolDownloadSettings;
@@ -502,6 +503,7 @@ pub struct Tools {
/// The project the tools are used for: tools that install into "the active runtime" (gems) run here,
/// so a version manager picks the project's Ruby.
work_dir: Option<PathBuf>,
vue_version: Option<String>,
/// Tools › Download sources: the mirror prefix and its fallback behaviour.
downloads: ToolDownloadSettings,
}
@@ -528,6 +530,7 @@ impl Tools {
runtime_env: BTreeMap::new(),
version_timeout: Duration::from_secs(4),
work_dir: None,
vue_version: None,
downloads: ToolDownloadSettings::default(),
}
}
@@ -778,9 +781,29 @@ impl Tools {
}
}
fn vue_release(&self) -> &str {
vue::release(self.work_dir.as_deref(), &self.downloads.vue_language_server_version)
}
fn for_tool(&self, spec: &ToolSpec) -> Self {
let mut tools = self.for_method(spec.method);
if spec.name == vue::SERVER && self.vue_version.is_none() {
let release = self.vue_release();
if release != "latest" {
tools.root = vue::managed_prefix(&tools.root, release);
tools.vue_version = Some(release.to_owned());
}
}
tools
}
fn install_key(&self, name: &str) -> String {
self.vue_version.as_ref().map_or_else(|| name.to_owned(), |release| format!("{name}@{release}"))
}
fn info_for(&self, name: &str, usage: Option<&Usage>) -> Option<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).info_for_runtime(name, usage),
Some(spec) => self.for_tool(spec).info_for_runtime(name, usage),
None => self.info_for_runtime(name, usage),
}
}
@@ -896,6 +919,9 @@ impl Tools {
.or_else(|| self.query_version(spec, &path));
return (ToolStatus::Installed, Some(path), version);
}
if self.vue_version.is_some() {
return (ToolStatus::Missing, None, None);
}
match self.install_method(spec) {
Method::Rustup { .. } => {
let Some(path) = self.which(main) else { return (ToolStatus::Missing, None, None) };
@@ -1004,7 +1030,7 @@ impl Tools {
emit: Emit,
) -> IdeResult<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).install_for_runtime(name, langs, cancel, emit),
Some(spec) => self.for_tool(spec).install_for_runtime(name, langs, cancel, emit),
None => self.install_for_runtime(name, langs, cancel, emit),
}
}
@@ -1026,7 +1052,8 @@ impl Tools {
if let Some(reason) = self.unavailable_reason(spec) {
return Err(IdeError::unavailable(reason));
}
let slot = match install_slot(name, cancel) {
let install_key = self.install_key(name);
let slot = match install_slot(&install_key, cancel) {
Ok(slot) => slot,
Err(slot) => return join_install(&slot, cancel, emit),
};
@@ -1053,7 +1080,16 @@ impl Tools {
c.args(["component", "add", component]);
run_streamed(c, cancel, emit)?;
}
Method::Npm { packages } => self.install_npm(packages, cancel, emit)?,
Method::Npm { packages } => {
if let Some(release) = &self.vue_version {
let primary = format!("{}@{release}", vue::PACKAGE);
let mut packages = packages.to_vec();
packages[0] = &primary;
self.install_npm(&packages, cancel, emit)?;
} else {
self.install_npm(packages, cancel, emit)?;
}
}
Method::Go { module } => self.install_go(spec, module, cancel, emit)?,
Method::Gem { gem } => self.install_gem(spec, gem, cancel, emit)?,
Method::GemActive { gem } => self.install_gem_active(gem, cancel, emit)?,
@@ -1081,7 +1117,7 @@ impl Tools {
});
Ok(info)
})();
release_install_slot(name, &slot);
release_install_slot(&install_key, &slot);
slot.finish(result.clone());
result
}
@@ -1720,6 +1756,10 @@ impl Tools {
let installed: Vec<(&ToolSpec, Method, String)> = TOOLS
.iter()
.filter_map(|spec| {
// Alternate Vue releases are version constraints, like pinned npm packages.
if spec.name == vue::SERVER && self.vue_release() != "latest" {
return None;
}
let method = self.install_method(spec);
Some((spec, method, self.installed_version(spec, method)?))
})
@@ -1801,7 +1841,7 @@ impl Tools {
/// Removes a tool the IDE installed.
pub fn uninstall(&self, name: &str, langs: &[LanguageConfig]) -> IdeResult<ToolInfo> {
match registry::find(name) {
Some(spec) => self.for_method(spec.method).uninstall_for_runtime(name, langs),
Some(spec) => self.for_tool(spec).uninstall_for_runtime(name, langs),
None => self.uninstall_for_runtime(name, langs),
}
}
@@ -1809,10 +1849,11 @@ impl Tools {
fn uninstall_for_runtime(&self, name: &str, langs: &[LanguageConfig]) -> IdeResult<ToolInfo> {
let spec = registry::find(name).ok_or_else(|| IdeError::not_found(format!("unknown tool `{name}`")))?;
// Uninstalling mid-install would tear down the directory under the running installer.
if INSTALLING.lock().as_ref().is_some_and(|m| m.contains_key(name)) {
let install_key = self.install_key(name);
if INSTALLING.lock().as_ref().is_some_and(|m| m.contains_key(&install_key)) {
return Err(IdeError::new(ErrorKind::AlreadyExists, format!("{name} is already being installed")));
}
let _guard = InstallGuard::acquire(&format!("uninstall-{name}"))?;
let _guard = InstallGuard::acquire(&format!("uninstall-{install_key}"))?;
let cancel = CancellationToken::new();
let quiet = |_: InstallEvent| {};
match self.install_method(spec) {
+46
Переглянути файл
@@ -642,6 +642,52 @@ exit 1"#,
assert!(!calls.contains("registry.npmjs.org"), "{calls}");
}
#[cfg(unix)]
#[test]
fn vue_installs_the_selected_release_without_replacing_other_projects() {
let env = Env::new();
env.script(&env.sys, "node", "exit 0");
env.script(
&env.sys,
"npm",
r#"prefix=""; version=""
for arg in "$@"; do
[ "$previous" = "--prefix" ] && prefix="$arg"
case "$arg" in
@vue/language-server@3.0.x) version=3.0.8;;
@vue/language-server@3.1.2) version=3.1.2;;
@vue/language-server@latest) version=3.2.0;;
esac
previous="$arg"
done
[ -n "$version" ] || exit 1
/bin/mkdir -p "$prefix/node_modules/.bin" "$prefix/node_modules/@vue/language-server"
printf '{"version":"%s"}\n' "$version" > "$prefix/node_modules/@vue/language-server/package.json"
printf '#!/bin/sh\necho %s\n' "$version" > "$prefix/node_modules/.bin/vue-language-server"
/bin/chmod +x "$prefix/node_modules/.bin/vue-language-server""#,
);
let project = env._tmp.path().join("vue-two");
fs::create_dir(&project).unwrap();
fs::write(project.join("package.json"), r#"{"dependencies":{"vue":"^2.7.16"}}"#).unwrap();
let tools = env.tools();
let legacy = tools.clone().with_work_dir(Some(project));
let manual = legacy
.clone()
.with_downloads(ToolDownloadSettings { vue_language_server_version: "3.1.2".into(), ..Default::default() });
let install = |tools: &Tools| tools.install(vue::SERVER, &langs(), &CancellationToken::new(), &|_| {}).unwrap();
let stable_info = install(&tools);
let legacy_info = install(&legacy);
let manual_info = install(&manual);
assert_eq!(stable_info.version.as_deref(), Some("3.2.0"));
assert_eq!(legacy_info.version.as_deref(), Some("3.0.8"));
assert_eq!(manual_info.version.as_deref(), Some("3.1.2"));
let path = |release| vue::managed_command(env.root.parent().unwrap(), release);
assert_eq!(legacy_info.path.as_deref(), Some(path("3.0.x").as_path()));
assert_eq!(manual_info.path.as_deref(), Some(path("3.1.2").as_path()));
assert_eq!(tools.info_for(vue::SERVER, None).unwrap().version.as_deref(), Some("3.2.0"));
assert_eq!(legacy.info_for(vue::SERVER, None).unwrap().version.as_deref(), Some("3.0.8"));
}
/// Servers that load TypeScript as a library get one with its JS API: `@latest`
/// is TypeScript 7 (native, no `ts.server`), which crashed vue-language-server (#25).
/// Uninstalling one keeps the TypeScript another installed server still uses.
+110
Переглянути файл
@@ -0,0 +1,110 @@
//! Select and locate an isolated managed Vue language-server version.
use std::path::{Path, PathBuf};
pub const SERVER: &str = "vue-language-server";
pub(crate) const PACKAGE: &str = "@vue/language-server";
const LEGACY: &str = "3.0.x";
/// A chosen version wins over project detection. Invalid values are never given to npm.
pub fn release<'a>(project: Option<&Path>, preferred: &'a str) -> &'a str {
let preferred = preferred.trim();
if preferred == "latest" || preferred == LEGACY || exact_version(preferred) {
return preferred;
}
if project.and_then(uses_vue_two) == Some(true) { LEGACY } else { "latest" }
}
fn exact_version(value: &str) -> bool {
let (release, build) = value.split_once('+').map_or((value, None), |(a, b)| (a, Some(b)));
let (core, pre) = release.split_once('-').map_or((release, None), |(a, b)| (a, Some(b)));
let valid_suffix = |suffix: &str| {
suffix.split('.').all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))
};
core.split('.').count() == 3
&& core.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
&& pre.is_none_or(valid_suffix)
&& build.is_none_or(valid_suffix)
}
fn read_manifest(path: &Path) -> Option<serde_json::Value> {
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
}
fn uses_vue_two(project: &Path) -> Option<bool> {
let manifest = read_manifest(&project.join("package.json"))?;
let dependency = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]
.iter()
.find_map(|group| manifest[*group]["vue"].as_str())?;
let dependency = dependency.trim().strip_prefix("npm:vue@").unwrap_or(dependency.trim());
if !matches!(dependency, "" | "*" | "latest" | "workspace:*" | "workspace:^" | "workspace:~")
&& !["file:", "link:", "git:", "https:", "npm:"].iter().any(|&prefix| dependency.starts_with(prefix))
{
return Some(dependency.strip_prefix("workspace:").unwrap_or(dependency).split("||").all(vue_two_range));
}
// A package-manager alias or workspace range may only identify its version once installed.
let installed = read_manifest(&project.join("node_modules/vue/package.json"));
Some(installed.as_ref().and_then(|p| p["version"].as_str()).is_some_and(vue_two_range))
}
fn vue_two_range(value: &str) -> bool {
let value = value.trim();
let major_two = |version: &str| {
let version = version.trim().trim_start_matches(['=', '^', '~', 'v']).trim();
version == "2" || version.starts_with("2.")
};
if let Some((_, limit)) = value.split_once('<') {
let limit = limit.trim();
if let Some(inclusive) = limit.strip_prefix('=') {
if inclusive.split_whitespace().next().is_some_and(major_two) {
return true;
}
} else if matches!(limit.split_whitespace().next(), Some("3" | "3.0" | "3.0.0" | "3.0.0-0")) {
return true;
}
}
if let Some((minimum, maximum)) = value.split_once(" - ") {
return major_two(minimum) && major_two(maximum);
}
major_two(value)
}
/// Extra releases stay off the process PATH and keep their own paired TypeScript package.
pub(crate) fn managed_prefix(tools: &Path, release: &str) -> PathBuf {
tools.join("vue-language-server-versions").join(release)
}
pub fn managed_command(data: &Path, release: &str) -> PathBuf {
managed_prefix(&crate::tools_dir(data), release).join("node_modules/.bin").join(if cfg!(windows) {
"vue-language-server.cmd"
} else {
SERVER
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn project_release_and_overrides() {
let project = tempfile::tempdir().unwrap();
let root = project.path();
for (version, expected) in [
("^2.7.16", LEGACY),
(">=2.6 <3", LEGACY),
("<=2.7.x", LEGACY),
("~2", LEGACY),
("^3.4.0", "latest"),
("^2.7.16 || ^3.4.0", "latest"),
] {
std::fs::write(root.join("package.json"), serde_json::json!({"dependencies":{"vue":version}}).to_string())
.unwrap();
assert_eq!(release(Some(root), ""), expected);
assert_eq!(release(Some(root), "3.0.6"), "3.0.6");
assert_eq!(release(Some(root), "latest"), "latest");
assert_eq!(release(Some(root), "../unsafe"), expected);
}
assert_eq!(release(None, LEGACY), LEGACY);
}
}
+11 -4
Переглянути файл
@@ -3710,11 +3710,18 @@ fn blocked_restore_keeps_the_deletion_record_for_the_next_attempt() {
assert!(!fx.exists(".git/openidea-saved-deletions"));
}
/// A folder and file name whose 700 paths overflow one command line (32,000 chars on Windows,
/// 120,000 elsewhere), while each absolute path stays within Windows' 260-char `MAX_PATH`,
/// which Git for Windows enforces without `core.longpaths`.
fn overlong_names() -> (String, String) {
if cfg!(windows) { ("f".repeat(40), "n".repeat(60)) } else { ("f".repeat(100), "n".repeat(110)) }
}
#[test]
fn pull_keeps_more_deleted_new_files_than_one_command_line_holds_deleted() {
let (fx, bare) = Fixture::with_origin();
let folder = "f".repeat(100);
let paths: Vec<String> = (0..700).map(|i| format!("{folder}/{i:04}-{}.txt", "n".repeat(110))).collect();
let (folder, name) = overlong_names();
let paths: Vec<String> = (0..700).map(|i| format!("{folder}/{i:04}-{name}.txt")).collect();
for path in &paths {
fx.write(path, "new\n");
}
@@ -3763,8 +3770,8 @@ fn deleting_more_added_files_than_one_command_line_holds_drops_them_all() {
let fx = Fixture::new();
fx.write("base.txt", "base\n");
fx.commit_all("base");
let folder = "f".repeat(100);
let paths: Vec<PathBuf> = (0..700).map(|i| fx.path(&format!("{folder}/{i:04}-{}.txt", "n".repeat(110)))).collect();
let (folder, name) = overlong_names();
let paths: Vec<PathBuf> = (0..700).map(|i| fx.path(&format!("{folder}/{i:04}-{name}.txt"))).collect();
for path in &paths {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "new\n").unwrap();
+1 -1
Переглянути файл
@@ -66,4 +66,4 @@ pnpm e2e -g "opens a file" # by test name
## Verifying in the real app
Unit and E2E tests don't run the Rust backend inside the webview. For UI or runtime behaviour, run `pnpm tauri dev` and check the change in the app. Debug builds include the Tauri MCP bridge, so the check can be scripted; find the port with `pnpm dev:status` (see [Development setup](/en/contribute/setup#mcp-bridge-and-ports)).
Unit and E2E tests don't run the Rust backend inside the webview. For UI or runtime behaviour, run `pnpm tauri dev` and check the change in the app. Debug builds include the Tauri MCP bridge, so the check can be scripted; find the port with `pnpm dev:status` (see [Development setup](/en/contribute/setup#mcp-bridge-and-ports)). The repository's agent skill `.agents/skills/verify` describes driving the app that way and capturing screenshots.
+3 -3
Переглянути файл
@@ -3,7 +3,7 @@ title: "Contribution workflow"
description: "How issues are triaged, what a pull request needs, how verification is checked, and how changes get merged."
---
These rules come from [`CONTRIBUTING.md`](https://github.com/l0ng-ai/openidea/blob/main/CONTRIBUTING.md) and apply to everyone, including coding agents working on someone's behalf.
These rules come from [`CONTRIBUTING.md`](https://github.com/l0ng-ai/openidea/blob/main/CONTRIBUTING.md) and apply to everyone, including coding agents working on someone's behalf. Coding rules, commands, checks and the evidence each kind of change needs are in [`AGENTS.md`](https://github.com/l0ng-ai/openidea/blob/main/AGENTS.md).
## Issues
@@ -60,9 +60,9 @@ This section is required. Include:
- **visible UI changes:** before/after screenshots; **multi-step interactions:** a recording;
- **backend changes:** logs or command output.
Screenshots are not needed for UI that goes away with a removed feature, copy-only changes or non-visual changes; say what you checked instead.
Screenshots are not needed for UI that goes away with a removed feature, copy-only changes or non-visual changes; write "No visible change" and say what you checked instead. [`AGENTS.md`](https://github.com/l0ng-ai/openidea/blob/main/AGENTS.md#issues--prs) lists the evidence for each kind of change: failing-then-passing tests, smoke output, before/after performance numbers, real-machine logs for platform-only changes, and so on.
A workflow (`.github/workflows/pr-check.yml`) reads each PR's description when it is opened or edited. If **How it was verified** is missing or empty, it comments and adds `needs-info`; once you fill it in, it removes its comment and the label. It only reads the title and description, never your code.
A workflow (`.github/workflows/pr-check.yml`) reads each PR's description when it is opened or edited. If **How it was verified** is missing or empty, or the PR changes UI files (`.tsx` or `.css` under `src/`, tests excluded) and the section has no screenshot or recording and doesn't say "No visible change", it comments and adds `needs-info`; once you fix it, it removes its comment and the label. It reads the title, the description and the list of changed file names, never your code.
### Checks to run
+22 -3
Переглянути файл
@@ -135,6 +135,25 @@ As JetBrains IDEs do, the command runs on pipes, not a terminal: programs print
Plugins can add more tools; they appear in the same list. A plugin tool marked as destructive asks for confirmation the same way.
## Dev containers
Five tools work on the project's [dev container](/en/guide/remote/containers) from the local desktop. `devcontainer_status` and `devcontainer_logs` only read Docker's state and are available for any local project. `devcontainer_up`, `devcontainer_exec` and `devcontainer_stop` need a trusted project and ask first, unless brave mode is on.
- `devcontainer_status` lists the project's `devcontainer.json` files and its containers with their state, image and ports, and says whether Docker and the Dev Containers CLI are ready.
- `devcontainer_logs` returns the last lines of a container's log (200 by default, at most 5000).
- `devcontainer_up` starts the container, building it if needed. With `rebuild: true` it removes the container and builds it again; `noCache` (only with `rebuild`) skips the build cache. It waits up to `timeout` milliseconds (30 minutes by default, and more than 0); the Dev Containers CLI is stopped when it passes.
- `devcontainer_exec` runs a command in the container, with the user and environment a terminal in the container has. It runs in a tab of the Run tool window like `run_command`, takes the same `name`, `timeout`, `pattern`, `maxLinesCount` and `truncateMode` arguments, plus `envs` and `config`, and is followed up with `wait_for_run`, `read_run_output` and `stop_run`. It needs a window.
- `devcontainer_stop` stops the container and the other containers of its Compose project. Nothing is removed.
**Which container.** The tools act on the container the Dev Containers CLI labels for the project folder and its `devcontainer.json`. `config` picks another `devcontainer.json` inside the project. For a Compose setup, `devcontainer_logs` and `devcontainer_stop` also cover the other containers of the same Compose project. Any other container is refused, including one named by `containerId`.
**Requirements.** The tools need Docker with a daemon on this computer and the Dev Containers CLI, which you install in **Settings › Languages & Frameworks › Language Servers**. Without them, `devcontainer_status` still answers and says what is missing; the other tools fail with that reason.
- `devcontainer_up` with `rebuild` and `devcontainer_stop` refuse a container that a window is opened in.
- A Run tab rerun uses the original `devcontainer_exec` container ID. To run the command in a replacement container, call `devcontainer_exec` again.
- Stopping the `devcontainer_exec` tab ends the CLI. A process it started in the container may keep running there, because Docker does not stop it when the client goes away.
- Background projects can use every dev container tool except `devcontainer_exec`.
## Background projects
By default the server answers only for projects open in a window. **Serve without a window** lets it also answer for a folder that has no window: the first tool call for a path inside it opens the project, and OpenIDEA unloads it again after it has been idle for a while. The setting is under **Background projects** on **Settings › Agents › IDE MCP Server**. It is off by default.
@@ -170,7 +189,7 @@ What trust decides: a trusted project works as one open in a window, with its la
A background project has no window, so some tools differ:
- `run_command`, `open_file_in_editor`, `xdebug_start_debugger_session` and the breakpoint tools (`xdebug_set_breakpoint`, `xdebug_remove_breakpoint`, `xdebug_list_breakpoints`) need a window. They refuse before they ask.
- `run_command`, `devcontainer_exec`, `open_file_in_editor`, `xdebug_start_debugger_session` and the breakpoint tools (`xdebug_set_breakpoint`, `xdebug_remove_breakpoint`, `xdebug_list_breakpoints`) need a window. They refuse before they ask.
- `get_file_problems` and `get_project_problems` report what a window shows. In a background project they answer with an error that points to `check_files`.
- `get_current_file` and `get_all_open_file_paths` also describe a window. In a background project they answer with an error that says the project needs a window.
- `execute_run_configuration`, `build_project`, `http_run_request` and destructive plugin tools ask in the project window you used last. The dialog has a line `Background project <folder name>` with the full path under it, and requests queue there. The dialog does not take keyboard focus: answer it with a click, or click into it first and then use the keys. If that window closes or loses trust, the request moves to another open project window. With no project window open, the call fails with "no project window is available". Brave mode runs these tools without asking, with or without a window.
@@ -178,13 +197,13 @@ A background project has no window, so some tools differ:
## Safety
- **Untrusted projects** expose only the read-only tools. Tools that write files, rename, reformat, build or run need a project you have trusted. A client started outside every project sees every tool, and so does one that names no project while no window or several windows are open. A tool that writes or runs still refuses a project you have not trusted.
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command` and `http_run_request` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up. In a background project, all of them but `run_command` ask in the project window you used last, and the dialog names the project.
- **Running and building ask first.** `execute_run_configuration`, `build_project`, `run_command`, `http_run_request`, `devcontainer_up`, `devcontainer_exec` and `devcontainer_stop` show a dialog in OpenIDEA naming the client, the project, the tool and what will run. Choose **Allow** or **Deny**; several requests queue up. In a background project, all of them but `run_command` and `devcontainer_exec` ask in the project window you used last, and the dialog names the project.
- Tools that write refuse paths outside the project.
- **Background projects.** Anyone with the token can make the IDE load a project that **Serve without a window** serves, so the setting and the token decide who can open folders on this computer. Listed folders you have not trusted open in Restricted Mode and get only the read-only tools. Keep the list to folders you want agents to reach.
## Remote development
In a remote window ([SSH](/en/guide/remote/ssh), WSL or [Dev Containers](/en/guide/remote/containers)), `openidea-server` runs its own MCP server on the remote host, configured independently in **Settings › Agents › IDE MCP Server** while that remote window is focused. Coding agents started inside the remote window connect to it automatically; external CLI clients on the remote host can use **Copy Stdio Config** (`~/.openidea/bin/openidea-server --mcp-stdio`) or **Copy HTTP Config**, and clients on your desktop can reach it by forwarding its port in the **Ports** tool window. The remote server serves only the project open in its window: [background projects](#background-projects) are served by OpenIDEA on your desktop, and the **Background projects** group is disabled in a remote window's Settings.
In a remote window ([SSH](/en/guide/remote/ssh), WSL or [Dev Containers](/en/guide/remote/containers)), `openidea-server` runs its own MCP server on the remote host, configured independently in **Settings › Agents › IDE MCP Server** while that remote window is focused. Coding agents started inside the remote window connect to it automatically; external CLI clients on the remote host can use **Copy Stdio Config** (`~/.openidea/bin/openidea-server --mcp-stdio`) or **Copy HTTP Config**, and clients on your desktop can reach it by forwarding its port in the **Ports** tool window. The remote server serves only the project open in its window: [background projects](#background-projects) are served by OpenIDEA on your desktop, and the **Background projects** group is disabled in a remote window's Settings. The [dev container tools](#dev-containers) run on the desktop for the local folder; a window opened in the container is a remote window, and its MCP server has no access to the desktop's Docker.
## Limits
+1 -1
Переглянути файл
@@ -66,4 +66,4 @@ pnpm e2e -g "opens a file" # 按测试名
## 在真实应用中验证
单元测试和 E2E 都不会在 webview 里运行 Rust 后端。UI 或运行时行为的改动,请运行 `pnpm tauri dev` 在应用里检查。debug 构建包含 Tauri MCP bridge,可以用脚本驱动检查;端口用 `pnpm dev:status` 查(见[开发环境](/zh/contribute/setup))。
单元测试和 E2E 都不会在 webview 里运行 Rust 后端。UI 或运行时行为的改动,请运行 `pnpm tauri dev` 在应用里检查。debug 构建包含 Tauri MCP bridge,可以用脚本驱动检查;端口用 `pnpm dev:status` 查(见[开发环境](/zh/contribute/setup))。仓库里的 agent skill `.agents/skills/verify` 描述了这种驱动应用并截图的方式。
+3 -3
Переглянути файл
@@ -3,7 +3,7 @@ title: "贡献流程"
description: "issue 如何分流、PR 需要包含什么、验证说明如何检查,以及改动如何合并。"
---
以下规则来自 [`CONTRIBUTING.md`](https://github.com/l0ng-ai/openidea/blob/main/CONTRIBUTING.md),对所有人都适用,包括代表某人工作的编码 agent。
以下规则来自 [`CONTRIBUTING.md`](https://github.com/l0ng-ai/openidea/blob/main/CONTRIBUTING.md),对所有人都适用,包括代表某人工作的编码 agent。编码规则、命令、检查项以及各类改动需要的验收证据见 [`AGENTS.md`](https://github.com/l0ng-ai/openidea/blob/main/AGENTS.md)。
## Issue
@@ -56,9 +56,9 @@ description: "issue 如何分流、PR 需要包含什么、验证说明如何检
- **可见的 UI 改动**:前后对比截图;**多步交互**:录屏;
- **后端改动**:日志或命令输出。
随功能一起删除的 UI、只改文案或不涉及界面的改动不需要截图,写明你检查了什么即可。
随功能一起删除的 UI、只改文案或不涉及界面的改动不需要截图,写上 "No visible change" 并说明你检查了什么即可。各类改动需要的证据(先失败后通过的测试、冒烟输出、性能前后数据、只涉及某个平台时的实机日志等)见 [`AGENTS.md`](https://github.com/l0ng-ai/openidea/blob/main/AGENTS.md#issues--prs)。
工作流 `.github/workflows/pr-check.yml` 会在 PR 创建或编辑时读取描述。如果 **How it was verified** 缺失或为空,它会留言并打上 `needs-info`;补全后会删掉自己的留言并移除标签。它只读标题和描述,不会检出或运行你的代码。
工作流 `.github/workflows/pr-check.yml` 会在 PR 创建或编辑时读取描述。如果 **How it was verified** 缺失或为空,或者 PR 改了 UI 文件(`src/` 下的 `.tsx` 或 `.css`,测试除外)而这一节既没有截图或录屏、也没写 "No visible change",它会留言并打上 `needs-info`;补全后会删掉自己的留言并移除标签。它只读标题、描述和改动的文件名,不会检出或运行你的代码。
### 要跑的检查
+22 -3
Переглянути файл
@@ -134,6 +134,25 @@ stdio 配置大致如下(路径以你机器上的为准):
插件可以添加更多工具,它们会出现在同一个列表中。标记为破坏性操作的插件工具同样会先请求确认。
## 开发容器
五个工具在本地桌面端操作项目的[开发容器](/zh/guide/remote/containers)。`devcontainer_status` 和 `devcontainer_logs` 只读取 Docker 的状态,在所有本地项目中都可用。`devcontainer_up`、`devcontainer_exec` 和 `devcontainer_stop` 需要项目已被信任,并且会先询问,勇敢模式下除外。
- `devcontainer_status` 列出项目的 `devcontainer.json` 文件和容器(含状态、镜像和端口),并说明 Docker 和 Dev Containers CLI 是否就绪。
- `devcontainer_logs` 返回容器日志的最后若干行(默认 200 行,最多 5000 行)。
- `devcontainer_up` 启动容器,需要时先构建。`rebuild: true` 会删除容器并重新构建;`noCache`(仅与 `rebuild` 一起使用)跳过构建缓存。它最多等待 `timeout` 毫秒(默认 30 分钟,且必须大于 0),超时后会停止 Dev Containers CLI。
- `devcontainer_exec` 在容器中执行命令,使用与容器内终端相同的用户和环境。它和 `run_command` 一样在运行工具窗口的标签页中运行,接受相同的 `name`、`timeout`、`pattern`、`maxLinesCount` 和 `truncateMode` 参数,另有 `envs` 和 `config`,之后用 `wait_for_run`、`read_run_output` 和 `stop_run` 跟进。此工具需要窗口。
- `devcontainer_stop` 停止容器,以及同一 Compose 项目中的其他容器。不会删除任何容器。
**操作哪个容器。** 这些工具操作 Dev Containers CLI 为项目文件夹及其 `devcontainer.json` 打上标签的那个容器。`config` 可以指定项目内的另一个 `devcontainer.json`。对于 Compose 配置,`devcontainer_logs` 和 `devcontainer_stop` 还涵盖同一 Compose 项目中的其他容器。其他任何容器都会被拒绝,包括用 `containerId` 指定的。
**前提条件。** 这些工具需要本机上有守护进程的 Docker,以及 Dev Containers CLI(在 **设置 › 语言和框架 › 语言服务器** 中安装)。缺少它们时,`devcontainer_status` 仍会返回结果并说明缺什么;其他工具会失败并给出原因。
- 带 `rebuild` 的 `devcontainer_up` 和 `devcontainer_stop` 会拒绝已有窗口打开的容器。
- 运行标签页重跑时使用 `devcontainer_exec` 原先的容器 ID。要在替换后的容器内运行命令,请再次调用 `devcontainer_exec`。
- 停止 `devcontainer_exec` 的标签页会结束 CLI。它在容器中启动的进程可能继续运行,因为客户端退出后 Docker 不会停止它。
- 后台项目可以使用除 `devcontainer_exec` 之外的所有开发容器工具。
## 后台项目
默认情况下,服务器只为在窗口中打开的项目提供服务。**无窗口时提供服务** 让它也能为没有窗口的文件夹提供服务:第一次针对其中某个路径的工具调用会打开该项目,空闲一段时间后 OpenIDEA 再把它卸载。这项设置在 **设置 › 智能体 › IDE MCP 服务器** 的 **后台项目** 下,默认关闭。
@@ -169,7 +188,7 @@ stdio 配置大致如下(路径以你机器上的为准):
后台项目没有窗口,所以有些工具不同:
- `run_command`、`open_file_in_editor`、`xdebug_start_debugger_session` 和断点工具(`xdebug_set_breakpoint`、`xdebug_remove_breakpoint`、`xdebug_list_breakpoints`)需要窗口,它们会在询问之前直接拒绝。
- `run_command`、`devcontainer_exec`、`open_file_in_editor`、`xdebug_start_debugger_session` 和断点工具(`xdebug_set_breakpoint`、`xdebug_remove_breakpoint`、`xdebug_list_breakpoints`)需要窗口,它们会在询问之前直接拒绝。
- `get_file_problems` 和 `get_project_problems` 报告的是窗口中显示的内容。在后台项目中,它们会返回一个错误,指向 `check_files`。
- `get_current_file` 和 `get_all_open_file_paths` 描述的同样是窗口。在后台项目中,它们会返回一个错误,说明该项目需要窗口。
- `execute_run_configuration`、`build_project`、`http_run_request` 和带破坏性标记的插件工具会在你最后使用的项目窗口中询问。对话框中有一行 `后台项目 <文件夹名>`,下面是完整路径,请求在这里排队。对话框不会获得键盘焦点:用鼠标点击它,或先点进对话框再用键盘操作。该窗口关闭或失去信任时,请求会转到另一个打开的项目窗口。没有打开任何项目窗口时,调用会失败,返回 `no project window is available`。勇敢模式下,这些工具无需询问即可运行,有没有窗口都一样。
@@ -177,13 +196,13 @@ stdio 配置大致如下(路径以你机器上的为准):
## 安全
- **未受信任的项目** 只开放只读工具。写文件、重命名、重新格式化、构建或运行的工具都要求项目已被信任。在所有项目之外启动的客户端能看到全部工具;没有打开窗口或打开了多个窗口时,未指定项目的客户端也是如此。会写入或运行的工具仍会拒绝你没有信任的项目。
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command` 和 `http_run_request` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。在后台项目中,除 `run_command` 外,这些工具都会在你最后使用的项目窗口中询问,对话框会写明该项目。
- **运行和构建会先询问。** `execute_run_configuration`、`build_project`、`run_command`、`http_run_request`、`devcontainer_up`、`devcontainer_exec` 和 `devcontainer_stop` 会在 OpenIDEA 中弹出对话框,说明是哪个客户端、哪个项目、哪个工具以及要运行什么,选择 **允许** 或 **拒绝**;多个请求会排队。在后台项目中,除 `run_command` 和 `devcontainer_exec` 外,这些工具都会在你最后使用的项目窗口中询问,对话框会写明该项目。
- 会写入的工具拒绝项目之外的路径。
- **后台项目。** 任何持有令牌的人都能让 IDE 加载 **无窗口时提供服务** 所提供的项目,所以这项设置和令牌共同决定谁能在这台电脑上打开文件夹。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。列表里只放你愿意让智能体访问的文件夹。
## 远程开发
在远程窗口([SSH](/zh/guide/remote/ssh)、WSL 或[容器](/zh/guide/remote/containers))中,`openidea-server` 会在远程主机上运行自己的 MCP 服务器,可在该远程窗口的 **Settings › Agents › IDE MCP Server** 中独立配置。远程窗口内启动的编程智能体会立即可用内置工具;在远程主机终端运行的外部客户端可使用 **Copy Stdio Config**(`~/.openidea/bin/openidea-server --mcp-stdio`)或 **Copy HTTP Config**,桌面端客户端则可在 **Ports** 工具窗口转发该端口后连接。远程服务器只为其窗口中打开的项目提供服务:[后台项目](#后台项目)由桌面上的 OpenIDEA 提供,远程窗口的设置里 **后台项目** 分组不可编辑。
在远程窗口([SSH](/zh/guide/remote/ssh)、WSL 或[容器](/zh/guide/remote/containers))中,`openidea-server` 会在远程主机上运行自己的 MCP 服务器,可在该远程窗口的 **Settings › Agents › IDE MCP Server** 中独立配置。远程窗口内启动的编程智能体会立即可用内置工具;在远程主机终端运行的外部客户端可使用 **Copy Stdio Config**(`~/.openidea/bin/openidea-server --mcp-stdio`)或 **Copy HTTP Config**,桌面端客户端则可在 **Ports** 工具窗口转发该端口后连接。远程服务器只为其窗口中打开的项目提供服务:[后台项目](#后台项目)由桌面上的 OpenIDEA 提供,远程窗口的设置里 **后台项目** 分组不可编辑。[开发容器工具](#开发容器)在桌面端针对本地文件夹运行;在容器中打开的窗口是远程窗口,它的 MCP 服务器无法访问桌面端的 Docker。
## 限制
+8 -6
Переглянути файл
@@ -442,15 +442,13 @@ test("creates, validates cron, runs, inspects provenance, exports/imports .autom
await page.setViewportSize({ width: 1320, height: 860 });
await installAutomationDesktopHarness(page);
// Open Agents tool window and click the pinned Automations hub row
// Open Agents tool window and click the Automations header button
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("agents.showToolWindow");
});
const hub = page.getByTestId("agents-automations-hub");
await expect(hub).toBeVisible();
await hub.getByRole("button", { name: /Automations/ }).click();
await page.getByRole("button", { name: "Agent Automations" }).click();
const editor = page.getByTestId("automations-editor");
await expect(editor).toBeVisible();
@@ -477,6 +475,7 @@ test("creates, validates cron, runs, inspects provenance, exports/imports .autom
await expect(dialog.getByTestId("automation-schedule-preview")).toContainText("Upcoming runs:");
await expect(dialog.getByRole("button", { name: "Create Automation" })).toBeEnabled();
await dialog.getByRole("button", { name: /Advanced/ }).click();
await dialog.getByLabel("Stop After Runs (optional)").fill("25");
await dialog.getByRole("button", { name: "Create Automation" }).click();
await expect(dialog).toHaveCount(0);
@@ -516,7 +515,8 @@ test("creates, validates cron, runs, inspects provenance, exports/imports .autom
const exportedMd = await exportDialog.getByLabel("Exported Automation Markdown").inputValue();
await exportDialog.getByRole("button", { name: "Close" }).click();
await editor.getByRole("button", { name: "Import .automation.md" }).click();
await editor.getByRole("button", { name: "Options" }).click();
await page.getByRole("menuitem", { name: "Import .automation.md" }).click();
const importDialog = page.getByRole("dialog", { name: "Import .automation.md" });
await importDialog
.getByLabel("Automation Markdown")
@@ -570,6 +570,7 @@ test("supports SameTask rolling continuity, NeedsInput approval flow, and sideba
dialog = page.getByRole("dialog", { name: "New Automation" });
await dialog.getByLabel("Name").fill("Rolling PR Labeler");
await dialog.getByLabel("Prompt Instructions").fill("NEEDS_APPROVAL label triaged PRs");
await dialog.getByRole("button", { name: /Advanced/ }).click();
await dialog.getByRole("button", { name: "Session Continuity" }).click();
await page.getByRole("option", { name: "Reuse rolling session" }).click();
await dialog.getByRole("button", { name: "Create Automation" }).click();
@@ -776,8 +777,9 @@ test("supports Weekly day picker, Local Autonomous warning, ChatOnly workspace,
await dialog.getByRole("button", { name: "Checkout Isolation" }).click();
await page.getByRole("option", { name: "Local checkout" }).click();
await dialog.getByRole("button", { name: /Advanced/ }).click();
await dialog.getByRole("button", { name: "Unattended Permissions" }).click();
await page.getByRole("option", { name: "Allow all (capped by your interactive approval setting)" }).click();
await page.getByRole("option", { name: /Allow all/ }).click();
await expect(dialog).toContainText(
"Warning: Autonomous mode on a local checkout can modify your working files directly.",
);
+127
Переглянути файл
@@ -0,0 +1,127 @@
import type { AgentPluginCatalog, AgentPluginState } from "../src/bindings";
import { expect, stubDesktop, test } from "./fixtures";
const makePlugin = (name: string, consentRequired: boolean): AgentPluginState => ({
plugin: {
id: name,
name,
displayName: name,
version: "26.1021.31345",
description: "A plugin with a long description explaining what it can do for the agent in this workspace.",
marketplace: "context-engineering-marketplace-with-a-long-name",
source: "claudeUser",
scope: "user",
formats: ["claude", "codex", "copilot"],
rootPath: "/Users/dev/.claude/plugins/cache/context-engineering-marketplace/agent-plugin",
defaultEnabled: false,
approxTokens: 2550,
capabilities: {
skillCount: 17,
mcpCount: 1,
ruleCount: 2,
subagentCount: 3,
commandCount: 0,
hookFiles: consentRequired ? ["hooks/a-very-long-lifecycle-hook-file-name.json"] : [],
requiresConsent: consentRequired,
},
valid: true,
},
enabled: !consentRequired,
origin: consentRequired ? "consent" : "none",
consentRequired,
});
test("agent plugin metadata stays clear of enable and review controls at narrow widths", async ({
workbench: page,
}) => {
const longName = "Context Engineering with an exceptionally long plugin display name";
const catalog: AgentPluginCatalog = {
plugins: [makePlugin(longName, true), makePlugin("Frontend Design", false)],
marketplaces: [
{
id: "official",
name: "claude-plugins-official",
source: "example/official",
scope: "user",
discovered: true,
},
{
id: "community",
name: "context-engineering-marketplace-with-a-long-name",
source: "example/community",
scope: "user",
discovered: true,
},
],
projectedSkills: 17,
projectedMcpServers: 1,
projectedRules: 2,
};
await stubDesktop(page);
await page.evaluate(async (catalog) => {
window.__ipc.handlers.agent_plugins_list = () => structuredClone(catalog);
window.__ipc.handlers.window_open_settings = () => {
throw { kind: "unavailable", message: "separate settings window disabled in browser test", detail: null };
};
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
await executeAction("file.settings", "agents.plugins");
}, catalog);
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await expect(dialog).toBeVisible();
const group = dialog.getByRole("region", { name: "Claude Code · User" });
const rows = group.getByRole("listitem");
await expect(rows).toHaveCount(2);
const review = rows.first().getByRole("button", { name: "Review & Enable…" });
await expect(review).toBeVisible();
for (const width of [1120, 780, 580, 520]) {
await page.setViewportSize({ width, height: 760 });
await expect(async () => {
const fit = await rows.evaluateAll((items) =>
items.every((row) => {
const expand = row.querySelector("button[aria-expanded]")!;
const action = expand.nextElementSibling!;
const bounds = row.getBoundingClientRect();
const a = expand.getBoundingClientRect();
const b = action.getBoundingClientRect();
const title = expand.querySelector("[title]")!.getBoundingClientRect();
return (
title.width > 0 &&
a.right <= bounds.right + 1 &&
b.right <= bounds.right + 1 &&
(a.right <= b.left + 1 || a.bottom <= b.top + 1) &&
expand.scrollWidth <= expand.clientWidth + 1
);
}),
);
expect(fit).toBe(true);
}).toPass();
if (process.env.SETTINGS_EVIDENCE)
await dialog.screenshot({
path: `${process.env.SETTINGS_EVIDENCE}/plugins-${width}.png`,
animations: "disabled",
});
}
await rows
.first()
.getByRole("button", { name: new RegExp(longName) })
.click();
await expect(rows.first().getByText(catalog.plugins[0]!.plugin.marketplace!)).toBeVisible();
await expect(rows.first().getByText(".claude-plugin · .codex-plugin · .plugin")).toBeVisible();
await expect(rows.first().getByText(catalog.plugins[0]!.plugin.description, { exact: true })).toBeVisible();
if (process.env.SETTINGS_EVIDENCE) {
await page.setViewportSize({ width: 1120, height: 760 });
await page.evaluate(async () => {
const themePath = "/src/workbench/theme.ts";
const { setTheme } = await import(/* @vite-ignore */ themePath);
await setTheme("dark");
});
await dialog.screenshot({
path: `${process.env.SETTINGS_EVIDENCE}/plugins-expanded-dark.png`,
animations: "disabled",
});
}
await review.click();
await expect(page.getByRole("dialog", { name: /Approve Plugin Capabilities/ })).toBeVisible();
});
+13
Переглянути файл
@@ -70,6 +70,19 @@ async function openHistory(page: Page) {
return stream;
}
// Selecting words in a long conversation must not move the reader away from the clicked text.
test("keeps the conversation position on double-click", async ({ page }) => {
const stream = await openHistory(page);
await stream.evaluate((el) => {
el.scrollTop = el.scrollHeight / 2;
});
const target = stream.locator("[class*='_conversationRow_']").filter({ hasText: "Reply 40" }).last();
await target.scrollIntoViewIfNeeded();
const before = await stream.evaluate((el) => el.scrollTop);
await target.getByText("Reply 40", { exact: true }).dblclick();
await expect.poll(() => stream.evaluate((el, top) => Math.abs(el.scrollTop - top), before)).toBeLessThanOrEqual(1);
});
for (const placement of ["editor", "toolWindow"] as const) {
test(`lets small upward wheel steps leave the end while replies stream in the ${placement}`, async ({ page }) => {
// Streams into an 80-turn conversation for several seconds: close to 30 s on CI runners.
+74
Переглянути файл
@@ -0,0 +1,74 @@
/**
* The Dependencies node under a .NET project in the Project view (#7429), from a stubbed
* workspace model; `src/features/dotnet/tree.test.ts` covers the tree contributions.
*/
import { expect, stubDesktop, test } from "./fixtures";
const SHOTS = process.env.E2E_SHOTS;
test("a project lists its packages, projects, frameworks and analyzers under Dependencies", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
const storeModule = "/src/features/dotnet/store.ts";
const { useDotnet } = await import(/* @vite-ignore */ storeModule);
const project = (path: string, name: string, extra: object = {}) => ({
path,
name,
frameworks: ["net9.0"],
configurations: ["Debug"],
references: [],
packages: [],
test: false,
runner: "vstest",
adapter: "mstest",
trx: false,
...extra,
});
useDotnet.setState({
model: {
projects: [
project("/dev/acme-api/App/App.csproj", "App", {
packages: [{ id: "Newtonsoft.Json", version: "13.0.3" }],
references: ["/dev/acme-api/Core/Core.csproj", "/dev/acme-api/Shared/Core.csproj"],
frameworkReferences: ["Microsoft.AspNetCore.App"],
analyzers: ["Microsoft.AspNetCore.Analyzers.dll"],
}),
project("/dev/acme-api/Core/Core.csproj", "Core"),
project("/dev/acme-api/Shared/Core.csproj", "Core"),
],
solutions: [
{
path: "/dev/acme-api/Acme.sln",
projects: ["/dev/acme-api/App/App.csproj", "/dev/acme-api/Core/Core.csproj"],
},
],
},
});
});
const tree = page.getByRole("tree", { name: "Project" });
await tree.getByRole("treeitem", { name: /Solution 'Acme'/ }).click();
await page.keyboard.press("ArrowRight");
const app = tree.getByRole("treeitem", { name: "App", exact: true });
await app.click();
await page.keyboard.press("ArrowRight");
await tree.getByRole("treeitem", { name: "Dependencies", exact: true }).click();
await page.keyboard.press("ArrowRight");
for (const group of ["Packages", "Projects", "Frameworks", "Analyzers"]) {
await tree.getByRole("treeitem", { name: group, exact: true }).click();
await page.keyboard.press("ArrowRight");
}
// The solution's Core plus each distinct reference with that same display name.
await expect(tree.getByRole("treeitem", { name: "Core", exact: true })).toHaveCount(3);
await expect(tree.getByRole("treeitem", { name: /Newtonsoft\.Json/ })).toContainText("13.0.3");
await expect(tree.getByRole("treeitem", { name: "Microsoft.AspNetCore.App", exact: true })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "Microsoft.AspNetCore.Analyzers.dll", exact: true })).toBeVisible();
// Core has no dependencies: no node.
await expect(tree.getByRole("treeitem", { name: "Dependencies" })).toHaveCount(1);
if (SHOTS) await page.screenshot({ path: `${SHOTS}/b2-dependencies.png`, animations: "disabled" });
const editorTabs = page.getByRole("tablist", { name: "Editor tabs" }).getByRole("tab");
await expect(editorTabs).toHaveText(["App.csproj"]);
await tree.getByRole("treeitem", { name: /Newtonsoft\.Json/ }).dblclick();
await expect(editorTabs).toHaveText(["App.csproj"]);
});
+95
Переглянути файл
@@ -0,0 +1,95 @@
/**
* A stubbed `dotnet` process host for the NuGet window specs. No CLI runs: `window.__dotnetOut`
* (set by the spec) answers each argument list, and a thrown message becomes a non-zero exit.
* The real-CLI vitest tests (`src/features/dotnet/*.cli.test.ts`) are the evidence for what
* `dotnet` actually does; these specs check the UI and the exact commands it starts.
*/
import type { Locator, Page } from "@playwright/test";
import { stubDesktop } from "./fixtures";
declare global {
interface Window {
__runs: string[][];
__dotnetOut: (args: string[]) => string;
}
}
/** One project, `/dev/acme/src/App/App.csproj`, in the workspace rooted at `/dev/acme`. */
export const PROJECT = "/dev/acme/src/App/App.csproj";
export async function installDotnetHost(page: Page) {
await stubDesktop(page);
await page.evaluate(
async ({ project }) => {
window.__runs = [];
window.__dotnetOut = () => "";
let id = 100;
window.__ipc.handlers.run_start = (args) => {
const config = args.config as { args: string[] };
window.__runs.push(config.args);
const run = ++id;
setTimeout(() => {
let text: string;
let code = 0;
try {
text = window.__dotnetOut(config.args);
} catch (e) {
text = (e as Error).message;
code = 1;
}
window.__ipc.send(args.onOutput, { kind: "stdout", text });
window.__ipc.emit({ type: "runExited", run, code });
}, 20);
return { id: run, configId: "x", name: "dotnet", pid: 1, running: true, pty: false };
};
const dotnetStore = "/src/features/dotnet/store.ts";
const projectStore = "/src/platform/project.ts";
const { useDotnet } = await import(/* @vite-ignore */ dotnetStore);
const { useProject } = await import(/* @vite-ignore */ projectStore);
useProject.setState({ project: { ...useProject.getState().project, root: "/dev/acme" } });
useDotnet.setState({
model: {
projects: [
{
path: project,
name: "App",
frameworks: ["net9.0"],
configurations: ["Debug"],
references: [],
packages: [],
test: false,
runner: "vstest",
adapter: "mstest",
trx: false,
},
],
solutions: [],
},
selected: project,
framework: "net9.0",
});
},
{ project: PROJECT },
);
}
export const dotnetRuns = (page: Page) => page.evaluate(() => window.__runs);
/** Opens the NuGet Packages tool window through its action. */
export async function openNuget(page: Page) {
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("dotnet.packages");
});
}
const SHOTS = process.env.E2E_SHOTS;
/** With `E2E_SHOTS` set: a screenshot of the NuGet Packages window scrolled to `focus` (fixture data only). */
export async function shot(page: Page, name: string, focus: Locator) {
if (!SHOTS) return;
await focus.scrollIntoViewIfNeeded();
await page
.locator('section[aria-label="NuGet Packages"]')
.screenshot({ path: `${SHOTS}/${name}.png`, animations: "disabled" });
}
+115
Переглянути файл
@@ -0,0 +1,115 @@
/**
* Solution and project-reference edits from the Project view (#7421). The host is stubbed at the IPC
* layer (no `dotnet` runs; `src/features/dotnet/edit.test.ts` runs the real CLI): the spec checks
* the menus and the exact `dotnet` commands they start.
*/
import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
const SHOTS = process.env.E2E_SHOTS;
/** Stubs the process host: records the `dotnet` argument lists and answers `sln list` with `listed`. */
async function stubHost(page: Page, listed: string[]) {
await stubDesktop(page);
await page.evaluate(
async ({ listed }) => {
const h = window.__ipc.handlers;
const runs: string[][] = [];
(window as unknown as { __runs: string[][] }).__runs = runs;
let id = 100;
h.run_start = (args) => {
const config = args.config as { args: string[] };
runs.push(config.args);
const run = ++id;
setTimeout(() => {
const text = config.args[2] === "list" ? `Project(s)\n----------\n${listed.join("\n")}\n` : "ok\n";
window.__ipc.send(args.onOutput, { kind: "stdout", text });
window.__ipc.emit({ type: "runExited", run, code: 0 });
}, 20);
return { id: run, configId: "x", name: "dotnet", pid: 1, running: true, pty: false };
};
h["plugin:dialog|open"] = () => ["/dev/acme-api/Lib/Lib.csproj"];
const storeModule = "/src/features/dotnet/store.ts";
const { useDotnet } = await import(/* @vite-ignore */ storeModule);
const project = (path: string, name: string, references: string[] = []) => ({
path,
name,
frameworks: ["net9.0"],
configurations: ["Debug"],
references,
packages: [],
test: false,
runner: "vstest",
adapter: "mstest",
trx: false,
});
useDotnet.setState({
model: {
projects: [
project("/dev/acme-api/App/App.csproj", "App", ["/dev/acme-api/Core/Core.csproj"]),
project("/dev/acme-api/Core/Core.csproj", "Core"),
],
solutions: [
{
path: "/dev/acme-api/Acme.sln",
projects: ["/dev/acme-api/App/App.csproj", "/dev/acme-api/Core/Core.csproj"],
},
],
},
});
},
{ listed },
);
}
const runs = (page: Page) => page.evaluate(() => (window as unknown as { __runs: string[][] }).__runs);
test("the solution node adds an existing project with dotnet sln add", async ({ workbench: page }) => {
await stubHost(page, ["Lib/Lib.csproj"]);
const solution = page.getByRole("treeitem", { name: /Solution 'Acme'/ });
await solution.click({ button: "right" });
await expect(page.getByRole("menuitem", { name: "Build .NET Project" })).toBeVisible();
if (SHOTS) await page.screenshot({ path: `${SHOTS}/b1-solution-menu.png`, animations: "disabled" });
await page.getByRole("menuitem", { name: "Add Existing Project…" }).click();
await expect
.poll(() => runs(page))
.toContainEqual(["sln", "/dev/acme-api/Acme.sln", "add", "/dev/acme-api/Lib/Lib.csproj"]);
// The project is listed afterwards, so no warning balloon.
await expect(page.getByText("was not added")).toHaveCount(0);
});
test("a same-named project the CLI skipped gets a warning", async ({ workbench: page }) => {
await stubHost(page, ["Other/Lib.csproj"]);
await page.getByRole("treeitem", { name: /Solution 'Acme'/ }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Add Existing Project…" }).click();
await expect(page.getByText("The project was not added to the solution")).toBeVisible();
if (SHOTS) await page.screenshot({ path: `${SHOTS}/b1-same-name-warning.png`, animations: "disabled" });
});
test("a project node offers reference and solution edits", async ({ workbench: page }) => {
await stubHost(page, []);
await page.getByRole("treeitem", { name: /Solution 'Acme'/ }).click();
await page.keyboard.press("ArrowRight");
const app = page.getByRole("treeitem", { name: "App", exact: true });
await app.click({ button: "right" });
await expect(page.getByRole("menuitem", { name: "Add Project Reference…" })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Remove Project Reference" })).toBeVisible();
if (SHOTS) await page.screenshot({ path: `${SHOTS}/b1-project-menu.png`, animations: "disabled" });
await page.getByRole("menuitem", { name: "Remove from Solution" }).click();
await expect
.poll(() => runs(page))
.toContainEqual(["sln", "/dev/acme-api/Acme.sln", "remove", "/dev/acme-api/App/App.csproj"]);
});
// The model reloads after each edit (the stubbed workspace has no solution), so each edit gets a test.
test("Remove Project Reference removes the chosen reference", async ({ workbench: page }) => {
await stubHost(page, []);
await page.getByRole("treeitem", { name: /Solution 'Acme'/ }).click();
await page.keyboard.press("ArrowRight");
await page.getByRole("treeitem", { name: "App", exact: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Remove Project Reference" }).hover();
await page.getByRole("menuitem", { name: "Core.csproj" }).click();
await expect
.poll(() => runs(page))
.toContainEqual(["remove", "/dev/acme-api/App/App.csproj", "reference", "/dev/acme-api/Core/Core.csproj"]);
});
+70
Переглянути файл
@@ -0,0 +1,70 @@
/**
* Solution folders and solution items in the Project view (#7431), from a stubbed workspace model;
* `src/platform/dotnetSolutionFolders.test.ts` covers parsing `.sln` / `.slnx`.
*/
import { expect, stubDesktop, test } from "./fixtures";
const SHOTS = process.env.E2E_SHOTS;
test("nested solution folders hold projects and solution items that open in the editor", async ({
workbench: page,
}) => {
await stubDesktop(page);
await page.evaluate(async () => {
const storeModule = "/src/features/dotnet/store.ts";
const { useDotnet } = await import(/* @vite-ignore */ storeModule);
const project = (path: string, name: string) => ({
path,
name,
frameworks: ["net9.0"],
configurations: ["Debug"],
references: [],
packages: [],
test: false,
runner: "vstest",
adapter: "mstest",
trx: false,
});
useDotnet.setState({
model: {
projects: [
project("/dev/acme-api/src/libs/Core/Core.csproj", "Core"),
project("/dev/acme-api/App/App.csproj", "App"),
],
solutions: [
{
path: "/dev/acme-api/Acme.slnx",
projects: ["/dev/acme-api/src/libs/Core/Core.csproj", "/dev/acme-api/App/App.csproj"],
folders: [
{
path: ["src", "libs"],
files: ["/dev/acme-api/README.md"],
projects: ["/dev/acme-api/src/libs/Core/Core.csproj"],
},
{ path: ["src", "libs", "core"], files: [], projects: [] },
],
},
],
},
});
});
const tree = page.getByRole("tree", { name: "Project" });
await tree.getByRole("treeitem", { name: /Solution 'Acme'/ }).click();
await page.keyboard.press("ArrowRight");
for (const folder of ["src", "libs"]) {
const node = tree.getByRole("treeitem", { name: folder, exact: true }).first();
await node.click();
await page.keyboard.press("ArrowRight");
}
await expect(tree.getByRole("treeitem", { name: "core", exact: true })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: "Core", exact: true })).toBeVisible();
// The project outside every folder stays at the solution's top level.
await expect(tree.getByRole("treeitem", { name: "App", exact: true })).toBeVisible();
if (SHOTS) await page.screenshot({ path: `${SHOTS}/b3-solution-folders.png`, animations: "disabled" });
// A solution item is a file node: it opens in the editor.
const item = tree.getByRole("treeitem", { name: "README.md", exact: true }).first();
await item.dblclick();
await expect(
page.getByRole("tablist", { name: "Editor tabs" }).getByRole("tab", { name: "README.md" }),
).toBeVisible();
});
+12
Переглянути файл
@@ -44,6 +44,18 @@ test("Gradle keeps the local installation with Distribution and saves edits in p
await expect(distribution).toHaveText("Gradle wrapper");
await expect(installation).toHaveCount(0);
const fields = userHome.or(runUsing).or(distribution).or(jvm);
for (const width of [1120, 800, 520]) {
await page.setViewportSize({ width, height: 760 });
const edges = await fields.evaluateAll((elements) =>
elements.map((element) => {
const { left, right } = element.getBoundingClientRect();
return [Math.round(left), Math.round(right)];
}),
);
expect(edges).toHaveLength(4);
for (const edge of edges.slice(1)) expect(edge).toEqual(edges[0]);
}
await distribution.click();
await page.getByRole("option", { name: "Local installation", exact: true }).click();
const browse = installation.locator("..").getByRole("button", { name: /^Browse/ });
+123
Переглянути файл
@@ -0,0 +1,123 @@
/**
* Central package management in the NuGet Packages window (#7427) over a stubbed `dotnet` host
* (`dotnetHost.ts`): the spec checks what the window shows and the exact commands it starts;
* `src/features/dotnet/central.cli.test.ts` runs the real CLI and shows what `dotnet add package`
* writes.
*/
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
import { dotnetRuns, installDotnetHost, openNuget, PROJECT, shot } from "./dotnetHost";
const PROPS = "/dev/acme/Directory.Packages.props";
/** `override`: the project carries `VersionOverride`, the props file keeps 1.0.0. */
async function stubCentral(page: Page, mode: "central" | "override") {
await installDotnetHost(page);
await page.evaluate(
({ mode, props }) => {
let current = "1.0.0";
const latest = "1.1.0";
const json = (value: unknown) => JSON.stringify(value);
window.__dotnetOut = (args) => {
if (args[0] === "msbuild") {
if (!args.some((a) => a.includes("ManagePackageVersionsCentrally")))
return json({ Properties: { MSBuildProjectName: "App", TargetFramework: "net9.0" }, Items: {} });
return json({
Properties: { ManagePackageVersionsCentrally: "true", CentralPackageTransitivePinningEnabled: "true" },
Items: {
PackageVersion: [
{
Identity: "Demo.Pkg",
Version: mode === "central" ? current : "1.0.0",
DefiningProjectFullPath: props,
},
{ Identity: "Child.Pkg", Version: "1.0.0", DefiningProjectFullPath: props },
],
PackageReference: [
{ Identity: "Demo.Pkg", ...(mode === "override" ? { VersionOverride: current } : {}) },
],
},
});
}
if (args[0] === "add") {
current = args[args.indexOf("--version") + 1]!;
return "ok\n";
}
if (args[0] === "list") {
const demo = { id: "Demo.Pkg", requestedVersion: current, resolvedVersion: current };
const framework = (extra: object) =>
json({ projects: [{ frameworks: [{ framework: "net9.0", ...extra }] }] });
if (args.includes("--outdated"))
return framework({ topLevelPackages: current === latest ? [] : [{ ...demo, latestVersion: latest }] });
return framework({
topLevelPackages: [demo],
transitivePackages: [{ id: "Child.Pkg", resolvedVersion: "1.0.0" }],
});
}
return "ok\n";
};
},
{ mode, props: PROPS },
);
await openNuget(page);
}
const row = (page: Page, id: string) => page.getByRole("listitem").filter({ hasText: id }).last();
test("a centrally managed project shows where versions are defined, marks a newer version and Update writes through dotnet add package", async ({
workbench: page,
}) => {
await stubCentral(page, "central");
await expect(page.getByRole("status")).toContainText("Directory.Packages.props");
await expect(row(page, "Demo.Pkg")).toContainText("Defined in Directory.Packages.props");
await expect(row(page, "Child.Pkg")).toContainText("Pinned in Directory.Packages.props");
await expect(row(page, "Demo.Pkg")).not.toContainText("Newer version");
await page.getByRole("button", { name: "Check for updates" }).click();
await expect(row(page, "Demo.Pkg")).toContainText("Newer version available: 1.1.0");
await shot(page, "d2-central", row(page, "Demo.Pkg"));
await row(page, "Demo.Pkg").getByRole("button", { name: "Update to 1.1.0" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual(["add", PROJECT, "package", "Demo.Pkg", "--version", "1.1.0"]);
// The window re-reads the props file and the outdated list afterwards.
await expect(row(page, "Demo.Pkg")).toContainText("1.1.0");
await expect(row(page, "Demo.Pkg")).toContainText("Defined in Directory.Packages.props");
await expect(row(page, "Demo.Pkg")).not.toContainText("Newer version");
});
test("a VersionOverride in the project is shown as the project's, and Update rewrites it there", async ({
workbench: page,
}) => {
await stubCentral(page, "override");
await expect(row(page, "Demo.Pkg")).toContainText("Version override 1.0.0 in the project");
await expect(row(page, "Demo.Pkg")).not.toContainText("Defined in");
await page.getByRole("button", { name: "Check for updates" }).click();
await expect(row(page, "Demo.Pkg")).toContainText("Newer version available: 1.1.0");
await shot(page, "d2-override", row(page, "Demo.Pkg"));
await row(page, "Demo.Pkg").getByRole("button", { name: "Update to 1.1.0" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual(["add", PROJECT, "package", "Demo.Pkg", "--version", "1.1.0"]);
await expect(row(page, "Demo.Pkg")).toContainText("Version override 1.1.0 in the project");
});
test("without central management nothing is labelled as central", async ({ workbench: page }) => {
await stubCentral(page, "central");
await page.evaluate(() => {
const ok = window.__dotnetOut;
window.__dotnetOut = (args) =>
args[0] === "msbuild" && args.some((a) => a.includes("ManagePackageVersionsCentrally"))
? JSON.stringify({ Properties: { ManagePackageVersionsCentrally: "" }, Items: {} })
: ok(args);
});
await page.getByRole("button", { name: "Refresh packages" }).click();
await expect(row(page, "Demo.Pkg")).toBeVisible();
await page.evaluate(async () => {
const central = "/src/features/dotnet/central.ts";
const { refreshCentral } = await import(/* @vite-ignore */ central);
await refreshCentral();
});
await expect(page.getByText("Defined in")).toHaveCount(0);
await expect(page.getByText("Pinned in")).toHaveCount(0);
await expect(page.getByRole("status")).toHaveCount(0);
});
+134
Переглянути файл
@@ -0,0 +1,134 @@
/**
* Package sources in the NuGet Packages window (#7420) over a stubbed `dotnet` host
* (`dotnetHost.ts`): the spec checks what the window shows and the exact commands it starts;
* `src/features/dotnet/sources.cli.test.ts` runs the real CLI.
*/
import { expect, test } from "./fixtures";
import { dotnetRuns, installDotnetHost, openNuget, shot } from "./dotnetHost";
const CONFIG = "/dev/acme/NuGet.Config";
const USER_CONFIG = "/Users/dev/.nuget/NuGet/NuGet.Config";
async function stubSources(page: Parameters<typeof installDotnetHost>[0]) {
await installDotnetHost(page);
await page.evaluate(
({ config, userConfig }) => {
const sources = [
{ name: "local", url: "/dev/acme/feed", enabled: true },
{ name: "shared", url: "https://pkgs.example.com/v3/index.json", enabled: true },
// A password inside the URL: the window must not show it.
{ name: "private", url: "https://bob:[email protected]/v3/index.json", enabled: false },
];
window.__dotnetOut = (args) => {
const [, verb, , name] = args;
if (args[0] === "list") return '{"projects":[]}';
// Other windows of the NuGet view (central package state) ask MSBuild too.
if (args[0] === "msbuild") return '{"Properties":{},"Items":{}}';
if (args[1] === "config") return `${config}\n${userConfig}\n`;
if (verb === "list") {
const target = args.at(-1);
const listed =
target === config
? sources.filter((s) => s.name !== "shared")
: target === userConfig
? sources.filter((s) => s.name === "shared")
: sources;
return `Registered Sources:\n\n${listed
.map((s, i) => ` ${i + 1}. ${s.name} [${s.enabled ? "Enabled" : "Disabled"}]\n ${s.url}`)
.join("\n")}\n`;
}
if (verb === "add") sources.push({ name: args[args.indexOf("--name") + 1]!, url: args[3]!, enabled: true });
else if (verb === "remove")
sources.splice(
sources.findIndex((s) => s.name === name),
1,
);
else sources.find((s) => s.name === name)!.enabled = verb === "enable";
return "ok\n";
};
},
{ config: CONFIG, userConfig: USER_CONFIG },
);
await openNuget(page);
await page.getByText("Package sources", { exact: true }).click();
}
test("lists the effective sources, masks URL credentials and toggles a source in the workspace file", async ({
workbench: page,
}) => {
await stubSources(page);
const list = page.getByRole("list", { name: "Package sources" });
await expect(list.getByText(/local/)).toBeVisible();
await expect(list.getByText(/private.*Disabled/)).toBeVisible();
await expect(list).toContainText("https://***@pkgs.example.com");
await expect(page.getByText("s3cret-pw")).toHaveCount(0);
await expect(page.getByLabel("NuGet.Config file")).toHaveValue(CONFIG);
await expect(
list.getByRole("listitem").filter({ hasText: "shared" }).getByRole("button", { name: "Disable" }),
).toBeDisabled();
await shot(page, "d1-sources", list.getByText(/private/));
await list.getByRole("listitem").filter({ hasText: "private" }).getByRole("button", { name: "Enable" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual(["nuget", "enable", "source", "private", "--configfile", CONFIG]);
await expect(list.getByText(/private.*Disabled/)).toHaveCount(0);
await list.getByRole("listitem").filter({ hasText: "local" }).getByRole("button", { name: "Disable" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual(["nuget", "disable", "source", "local", "--configfile", CONFIG]);
await expect(list.getByText(/local.*Disabled/)).toBeVisible();
});
test("adds and removes a source; the user-wide file is a labelled, explicit choice", async ({ workbench: page }) => {
await stubSources(page);
await page.getByLabel("Source name").fill("team");
await page.getByLabel("Source URL or folder").fill("https://nuget.team.example/v3/index.json");
await page.getByRole("button", { name: "Add source" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual([
"nuget",
"add",
"source",
"https://nuget.team.example/v3/index.json",
"--name",
"team",
"--configfile",
CONFIG,
]);
const list = page.getByRole("list", { name: "Package sources" });
await expect(list.getByText(/team/)).toBeVisible();
// The user-wide file is last, labelled, and warns once picked.
await expect(page.getByRole("status")).toHaveCount(0);
await page.getByLabel("NuGet.Config file").selectOption(USER_CONFIG);
await expect(page.getByRole("status")).toContainText("every project");
await shot(page, "d1-user-wide", page.getByRole("status"));
await expect(
list.getByRole("listitem").filter({ hasText: "shared" }).getByRole("button", { name: "Disable" }),
).toBeEnabled();
await page.getByLabel("NuGet.Config file").selectOption(CONFIG);
await list.getByRole("listitem").filter({ hasText: "team" }).getByRole("button", { name: "Remove" }).click();
await expect
.poll(() => dotnetRuns(page))
.toContainEqual(["nuget", "remove", "source", "team", "--configfile", CONFIG]);
await expect(list.getByText(/team/)).toHaveCount(0);
});
test("a failing dotnet command shows its message and keeps the list", async ({ workbench: page }) => {
await stubSources(page);
await page.evaluate(() => {
const ok = window.__dotnetOut;
window.__dotnetOut = (args) => {
if (args[2] === "source" && args[1] === "remove") throw new Error("error: Unable to find a source named 'nope'.");
return ok(args);
};
});
await page
.getByRole("list", { name: "Package sources" })
.getByRole("listitem")
.first()
.getByRole("button", { name: "Remove" })
.click();
await expect(page.getByRole("alert")).toContainText("Unable to find a source");
await expect(page.getByRole("list", { name: "Package sources" }).getByRole("listitem")).toHaveCount(3);
});
+14 -6
Переглянути файл
@@ -1,6 +1,6 @@
import { expect, stubDesktop, test } from "./fixtures";
test("keeps the project switcher flat while grouping Welcome and Recent Projects without row overlap", async ({
test("keeps local and remote projects flat in all recent-project lists without row overlap", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 980, height: 740 });
@@ -111,7 +111,7 @@ test("keeps the project switcher flat while grouping Welcome and Recent Projects
await page.keyboard.press("Escape");
await expect(projectPopup).toBeHidden();
// 2. Recent Projects popup groups by host and never overlaps rows (grouped or 3-line search results).
// 2. Recent Projects popup is flat and never overlaps rows, including search results.
await page.evaluate(async () => {
const popupMod = "/src/features/welcome/RecentProjectsPopup.tsx";
const { showRecentProjectsPopup } = await import(/* @vite-ignore */ popupMod);
@@ -128,20 +128,28 @@ test("keeps the project switcher flat while grouping Welcome and Recent Projects
expect(boxes[i]!.y).toBeGreaterThanOrEqual(boxes[i - 1]!.y + boxes[i - 1]!.height - 0.5);
}
};
await expect(recentDialog.getByRole("option")).toHaveCount(6);
await expect(recentDialog.locator("[aria-expanded]")).toHaveCount(0);
await expect(recentDialog.locator("[data-remote-badge]")).toHaveCount(4);
await assertNoVerticalOverlap();
await recentDialog.getByRole("textbox", { name: "Search recent projects" }).fill("openidea_all");
await assertNoVerticalOverlap();
await page.keyboard.press("Escape");
await expect(recentDialog).toBeHidden();
// 3. Welcome › Projects folds and unfolds host groups.
// 3. Welcome › Projects keeps all projects in recency order without host headers.
await page.evaluate(async () => {
const projectMod = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectMod);
useProject.setState({ project: null, lightEdit: false });
});
const welcomeList = page.getByRole("listbox", { name: "Recent projects" });
await expect(welcomeList.getByRole("option")).toHaveCount(11);
await welcomeList.getByRole("option").first().click();
await expect(welcomeList.getByRole("option")).toHaveCount(9);
const welcomeRows = welcomeList.getByRole("option");
await expect(welcomeRows).toHaveCount(7);
await expect(welcomeList.locator("[aria-expanded]")).toHaveCount(0);
await expect(welcomeList.locator("[data-remote-badge]")).toHaveCount(4);
await expect(welcomeRows.nth(0)).toContainText("[email protected]:22:/home/coder/git/openidea_all");
await expect(welcomeRows.nth(1)).toContainText("dev-mbp1.local:/Users/dev/git/gocommon");
await expect(welcomeRows.nth(2)).toContainText("~/git/gocommon");
await expect(welcomeRows.nth(3)).toContainText("[email protected]:22:/home/coder/git/gocommon");
});
+47
Переглянути файл
@@ -297,6 +297,53 @@ test("run configuration fields share a control column including the name", async
expect(boxes[0]!.width).toBeGreaterThan(80);
});
test("on Linux, Python configuration fields stay aligned with long arguments when resizing", async ({
workbench: page,
}) => {
const args = '-c "conf/development settings.conf" -d DEMO_DEVELOPMENT -u demo_module --log-level debug';
await page.evaluate(async (args) => {
// WebKitGTK's subgrid tracks shift with a scrollbar (#7469): Linux has its own fixed label column.
document.documentElement.dataset.os = "linux";
const store = "/src/features/run/store.ts";
const types = "/src/features/run/types.ts";
const { useRun } = await import(/* @vite-ignore */ store);
const { newConfigOfType, typeFor, withParams } = await import(/* @vite-ignore */ types);
const type = typeFor("python")!;
const base = newConfigOfType(type, []);
const config = withParams(
{ ...base, name: "Python demo", target: "development", env: { APP_ENV: "development" } },
{ ...base.params, script: "src/main.py", args },
type,
);
useRun.setState({ configs: [config], selectedId: config.id, loaded: true, editorOpen: true });
}, args);
const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
const content = dialog.locator("#run-config-content");
const argumentField = dialog.getByRole("textbox", { name: "Arguments", exact: true });
const fields = ["Name", "Arguments", "Working directory", "Environment variables"].map((name) =>
dialog.getByRole("textbox", { name, exact: true }),
);
for (const field of fields) await expect(field).toBeVisible();
await expect(argumentField).toHaveValue(args);
const initial = (await content.boundingBox())!;
const argumentsBeforeResize = (await argumentField.boundingBox())!;
const offset = argumentsBeforeResize.x - initial.x;
const grip = (await dialog.getByRole("separator", { name: "Resize", exact: true }).boundingBox())!;
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
await page.mouse.down();
await page.mouse.move(grip.x - 160, grip.y - 180, { steps: 5 });
await page.mouse.up();
const resized = (await content.boundingBox())!;
expect(resized.width).toBeLessThan(initial.width);
expect((await argumentField.boundingBox())!.width).toBeLessThan(argumentsBeforeResize.width);
const boxes = await Promise.all(fields.map((field) => field.boundingBox()));
for (const box of boxes) expect(box!.x - resized.x).toBeCloseTo(offset, 0);
await expect(argumentField).toHaveValue(args);
});
test("resizing the configuration dialog grows its panes and keeps the footer visible", async ({ workbench: page }) => {
await openConfigurations(page);
const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
+63 -28
Переглянути файл
@@ -2,34 +2,39 @@ import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
/** Supply detected configurations without launching desktop processes. */
async function configure(page: Page, extra = 0) {
await page.evaluate(async (extra) => {
const storePath = "/src/features/run/store.ts";
const projectPath = "/src/platform/project.ts";
const { useRun } = await import(storePath);
const { useProject } = await import(projectPath);
localStorage.setItem(`openidea.services.runTypes:${useProject.getState().project.root}`, '["spring-boot","npm"]');
useRun.setState({
configs: [
["gateway", "spring-boot"],
["portal", "spring-boot"],
["web", "npm"],
["worker", "npm"],
...Array.from({ length: extra }, (_, i) => [`app-${i}`, "spring-boot"]),
].map(([id, kind]) => ({
id,
name: id,
kind,
command: kind,
args: [],
env: {},
cwd: null,
detected: true,
isTest: false,
debugAdapter: null,
})),
});
}, extra);
async function configure(page: Page, extra = 0, useDefaults = false) {
await page.evaluate(
async ({ extra, useDefaults }) => {
const storePath = "/src/features/run/store.ts";
const projectPath = "/src/platform/project.ts";
const { useRun } = await import(storePath);
const { useProject } = await import(projectPath);
const key = `openidea.services.runTypes:${useProject.getState().project.root}`;
if (useDefaults) localStorage.removeItem(key);
else localStorage.setItem(key, '["spring-boot","npm"]');
useRun.setState({
configs: [
["gateway", "spring-boot"],
["portal", "spring-boot"],
["web", "npm"],
["worker", "npm"],
...Array.from({ length: extra }, (_, i) => [`app-${i}`, "spring-boot"]),
].map(([id, kind]) => ({
id,
name: id,
kind,
command: kind,
args: [],
env: {},
cwd: null,
detected: true,
isTest: false,
debugAdapter: null,
})),
});
},
{ extra, useDefaults },
);
if (!(await page.getByRole("tree", { name: "Services", exact: true }).isVisible()))
await page.keyboard.press("Meta+8");
await expect(page.getByRole("tree", { name: "Services", exact: true })).toBeVisible();
@@ -48,6 +53,36 @@ async function move(page: Page, source: string, target: string) {
await page.mouse.up();
}
test("Services shows Spring Boot run configurations and their running ports by default", async ({
workbench: page,
}) => {
await configure(page, 0, true);
const tree = page.getByRole("tree", { name: "Services", exact: true });
await expect(tree.getByRole("treeitem")).toHaveText(["Spring Boot", "gateway", "portal"]);
await page.evaluate(async () => {
const storePath = "/src/features/run/store.ts";
const { useRun } = (await import(/* @vite-ignore */ storePath)) as typeof import("../src/features/run/store");
const config = useRun.getState().configs.find((config) => config.id === "gateway")!;
useRun.setState({
sessions: [
{
id: "gateway-run",
config,
runId: null,
status: "running",
exitCode: null,
startedAt: Date.now(),
endedAt: null,
stdinClosed: true,
httpPort: 8080,
httpPath: "/api",
},
],
});
});
await expect(tree.getByRole("treeitem", { name: /gateway/ })).toContainText(":8080/api/");
});
test("Services favors details and stacks the panes when docked to the side", async ({ workbench: page }) => {
await configure(page);
const services = page.getByRole("region", { name: "Services", exact: true });
+42
Переглянути файл
@@ -275,6 +275,48 @@ test("Language Servers page installs a tool with progress (in-memory installer)"
await expect(dialog.getByLabel("solargraph details")).toContainText("gem install solargraph");
});
test("Vue Language Server accepts a manual managed version in Settings", async ({ workbench: page }) => {
await page.evaluate(async () => {
const path = "/src/features/tools/backend.ts";
const { MemoryToolsBackend, sampleTools, setToolsBackend } = (await import(
/* @vite-ignore */ path
)) as typeof import("../src/features/tools/backend");
const sample = sampleTools().find((tool) => tool.name === "gopls")!;
setToolsBackend(
new MemoryToolsBackend([
{
...sample,
name: "vue-language-server",
displayName: "Vue Language Server",
command: "vue-language-server",
languages: ["Vue"],
installMethod: "npm",
},
]),
);
});
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings" });
await dialog.getByRole("textbox", { name: "Search settings" }).fill("Language Servers");
await dialog.getByRole("treeitem", { name: "Language Servers", exact: true }).click();
await dialog
.getByRole("list", { name: "Languages", exact: true })
.getByRole("button", { name: /^Vue\b/ })
.click();
await dialog.locator('[data-tool="vue-language-server"]').click();
const version = dialog.getByLabel(/Vue Language Server version/);
await expect(version).toBeEmpty();
await version.fill("../invalid");
await expect(version).toHaveAttribute("aria-invalid", "true");
await version.fill("3.0.8");
await expect(version).not.toHaveAttribute("aria-invalid", "true");
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
await expect(apply).toBeEnabled();
await apply.click();
await expect(apply).toBeDisabled();
await expect(version).toHaveValue("3.0.8");
});
test("font picker supports manual families and CJK fallback in browser development", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings" });
+41
Переглянути файл
@@ -74,6 +74,47 @@ test("settings forms share control columns and keep font metrics on one row", as
}
});
test("toolchain, encoding and Subversion settings align field frames across sections", async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const body = page.getByRole("dialog", { name: "Settings", exact: true }).locator("[class*='pageBody']");
for (const [id, title, count] of [
["languages.go", "Go", 2],
["languages.java", "Java", 4],
["languages.rust", "Rust", 4],
["languages.node", "JavaScript Runtime", 4],
["languages.php", "PHP", 4],
["build.maven", "Maven", 8],
["editor.fileEncodings", "File Encodings", 4],
["vcs.svn", "Subversion", 2],
] as const) {
await selectPage(page, id);
await expect(page.getByLabel("Breadcrumb").locator('[aria-current="page"]')).toHaveText(title);
if (id === "vcs.svn") {
await body.getByRole("checkbox", { name: "Use custom configuration directory" }).check();
await expect(body.getByRole("textbox", { name: /Configuration directory/ })).toBeEnabled();
}
const fields = body
.getByRole("button")
.and(body.locator("[aria-haspopup='listbox']"))
.or(body.getByRole("textbox"))
.or(body.getByRole("combobox"))
.and(body.locator(':not([aria-label="Thread count"])'));
await expect(fields).toHaveCount(count);
for (const width of [1200, 800, 520]) {
await page.setViewportSize({ width, height: 800 });
for (const group of [fields, body.getByRole("button", { name: "Browse…", exact: true })]) {
const edges = await group.evaluateAll((elements) =>
elements.map((element) => {
const { left, right } = element.getBoundingClientRect();
return [Math.round(left), Math.round(right)];
}),
);
for (const edge of edges.slice(1)) expect(edge, `${id} at ${width}px`).toEqual(edges[0]);
}
}
}
});
for (const locale of ["en", "zh"]) {
test(`${locale} forms fit narrow settings panes without horizontal scrolling`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
+23
Переглянути файл
@@ -117,6 +117,29 @@ test("Live Templates gives the editor the full settings pane width and keeps var
expect(await variables.evaluate((element) => element.scrollWidth - element.clientWidth)).toBe(0);
});
test("Project settings aligns the visible fields and their browse buttons", async ({ workbench: page }) => {
await page.keyboard.press("Meta+;");
const dialog = page.getByRole("dialog", { name: "Project Structure", exact: true });
const fields = dialog
.getByRole("button", { name: /^(Project SDK|Project language level|Language server JDK)$/ })
.or(dialog.getByRole("textbox", { name: "Compiler output" }));
const browse = dialog.getByRole("button", { name: "Browse…" });
await expect(fields).toHaveCount(4);
await expect(browse).toHaveCount(3);
for (const width of [1400, 800, 520]) {
await page.setViewportSize({ width, height: 800 });
for (const group of [fields, browse]) {
const edges = await group.evaluateAll((elements) =>
elements.map((element) => {
const { left, right } = element.getBoundingClientRect();
return [Math.round(left), Math.round(right)];
}),
);
for (const edge of edges.slice(1)) expect(edge).toEqual(edges[0]);
}
}
});
test("Project Structure keeps every details pane usable in a compact window", async ({ workbench: page }) => {
await page.keyboard.press("Meta+;");
const dialog = page.getByRole("dialog", { name: "Project Structure", exact: true });
+31
Переглянути файл
@@ -42,3 +42,34 @@ test("Welcome keeps project search and actions on one row at a narrow width", as
await expect(more).toBeFocused();
await expect(search).toHaveValue("tokio");
});
test("Welcome lists local and remote projects at the same level", async ({ workbench: page }) => {
await page.evaluate(async () => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
useProject.setState({ project: null, lightEdit: false });
});
const list = page.getByRole("listbox", { name: "Recent projects" });
const rows = list.getByRole("option");
await expect(rows).toHaveCount(4);
await page.evaluate(async () => {
const recentPath = "/src/features/welcome/recent.ts";
const { useRecent } = await import(/* @vite-ignore */ recentPath);
useRecent.setState({
groups: [],
projects: [
{ name: "tty7", path: "ssh://macmini/Users/thomas/repo/tty7", branch: null, openedAtMs: 100 },
{ name: "OpenIDEA", path: "/Users/dev/dev/openidea", branch: null, openedAtMs: 90 },
{ name: "tty7", path: "/Users/dev/dev/tty7", branch: null, openedAtMs: 80 },
],
});
});
await expect(rows).toHaveCount(3);
await expect(rows.nth(0)).toContainText("macmini:/Users/thomas/repo/tty7");
await expect(rows.nth(1)).toContainText("OpenIDEA");
await expect(rows.nth(2)).toContainText("~/dev/tty7");
await expect(list.locator("[aria-expanded]")).toHaveCount(0);
await expect(list.locator("[data-remote-badge]")).toHaveCount(1);
const avatars = await rows.evaluateAll((els) => els.map((el) => el.firstElementChild!.getBoundingClientRect().x));
expect(avatars).toEqual([avatars[0], avatars[0], avatars[0]]);
});
+8
Переглянути файл
@@ -38,6 +38,8 @@ mod theme_frame;
#[cfg(target_os = "macos")]
mod titlebar;
mod updates;
#[cfg(any(windows, test))]
mod window_display;
mod window_groups;
#[cfg(any(windows, test))]
mod window_work_area;
@@ -295,6 +297,8 @@ pub fn run() {
}
tauri::WindowEvent::Focused(true) => {
application_focus::changed(window.app_handle(), true);
#[cfg(windows)]
window_display::remember(window);
if let Some(w) = window.try_state::<WindowsState>() {
w.focused(window.label());
}
@@ -302,6 +306,10 @@ pub fn run() {
tauri::WindowEvent::Focused(false) => application_focus::changed(window.app_handle(), false),
tauri::WindowEvent::Moved(_) | tauri::WindowEvent::Resized(_) => {
window_groups::frame_changed(window.app_handle(), window.label());
#[cfg(windows)]
if matches!(event, tauri::WindowEvent::Moved(_)) {
window_display::remember(window);
}
}
tauri::WindowEvent::Destroyed => {
// Also release a view that failed during startup, before the parent could watch it.
+25 -58
Переглянути файл
@@ -14,73 +14,39 @@ use crate::remote_wsl::{Probe, Tail, install_script, parse_probe, probe_script,
use ide_core::{IdeError, IdeResult};
use ide_jsonrpc::{Handler, Peer};
use ide_remote::container_tunnel::Exec;
use ide_remote::devcontainer::{Up, parse_up};
use ide_remote::devcontainer::{self, Target, UP_TIMEOUT, Up};
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncBufReadExt;
/// Building an image (and its features) can take a while on a first open.
const UP_TIMEOUT: Duration = Duration::from_secs(30 * 60);
const PROBE_TIMEOUT: Duration = Duration::from_secs(60);
/// The Dev Containers CLI: the IDE-managed copy (Settings › Languages & Frameworks › Language Servers) or one on `PATH`.
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.",
)
})
}
/// `devcontainer up` for `folder` (with configuration `config`, relative to it; empty = the
/// default one). Its log goes to `tail` and the IDE log.
async fn up(cli: &Path, docker: &Path, folder: &Path, config: &str, tail: &Tail) -> IdeResult<Up> {
let mut cmd = tokio::process::Command::new(cli);
ide_core::process::prepare(cmd.as_std_mut());
cmd.arg("up").arg("--workspace-folder").arg(folder);
if !config.trim().is_empty() {
cmd.arg("--config").arg(folder.join(config.trim()));
}
cmd.arg("--docker-path")
.arg(docker)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("cannot start devcontainer: {e}")))?;
let stderr = child.stderr.take();
let log = tail.clone();
let reader = tokio::spawn(async move {
let Some(stderr) = stderr else { return };
let mut lines = tokio::io::BufReader::new(stderr).lines();
while let Ok(Some(line)) = lines.next_line().await {
tracing::info!(target: "devcontainer", "{line}");
log.push(line);
}
});
let out = tokio::time::timeout(UP_TIMEOUT, child.wait_with_output())
.await
.map_err(|_| IdeError::unavailable("devcontainer up did not finish in time"))?
.map_err(|e| IdeError::unavailable(format!("devcontainer up failed: {e}")))?;
let _ = reader.await;
let result = parse_up(&String::from_utf8_lossy(&out.stdout));
if out.status.success() {
return result;
}
let error = result
.err()
.unwrap_or_else(|| IdeError::unavailable(format!("devcontainer up exited with {status}", status = out.status)));
Err(match tail.text() {
t if t.is_empty() => error,
t => IdeError::unavailable(format!("{}\n{t}", error.message)),
let (cli, docker, target, tail) =
(cli.to_owned(), docker.to_owned(), Target::relative(folder, config), tail.clone());
let cancel = ide_core::CancellationToken::new();
// This future dropped (the command was cancelled): the CLI stops with it. A superseded
// attempt is not dropped and runs on; Reopen in Container is not held to one start per folder.
let _stop = cancel.clone().drop_guard();
tokio::task::spawn_blocking(move || {
devcontainer::up(
&cli,
&docker,
&target,
&[],
UP_TIMEOUT,
&mut |line| {
tracing::info!(target: "devcontainer", "{line}");
tail.push(line.to_owned());
},
&cancel,
)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// `docker exec [-i] -u <user> <container> sh -c <script> sh <args>…`.
@@ -214,8 +180,9 @@ pub(crate) async fn connect(
));
}
let data = state.host.local_data_dir.clone();
let cli =
tokio::task::spawn_blocking(move || cli(&data)).await.map_err(|e| IdeError::internal(e.to_string()))??;
let cli = tokio::task::spawn_blocking(move || ide_host::devcontainer::cli(&data))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
let up = up(&cli, &docker, &local, config, tail).await?;
let bin = ensure_server(state, &docker, &up, progress).await?;
progress(RemoteStage::Starting, None);
+7
Переглянути файл
@@ -89,6 +89,8 @@ pub struct Connection {
session: Option<Arc<ide_ssh::Session>>,
/// How to reach a dev container's ports; `None` for SSH and WSL.
exec: Option<Arc<ide_remote::container_tunnel::Exec>>,
/// Marks a dev container's container as open in a window for as long as the connection lives.
_attached: Option<ide_host::devcontainer::AttachedContainer>,
/// Remote ports forwarded to this machine (Ports tool window), by host (`None`: the remote
/// host itself) and remote port.
forwards: Mutex<Vec<(ForwardKey, Forward)>>,
@@ -738,6 +740,7 @@ pub async fn remote_connect(
});
let tail = crate::remote_wsl::Tail::default();
let mut exec = None;
let mut attached = None;
let (peer, session, host, title_tag) = match &target {
RemoteTarget::Ssh { config: id } => {
let config = state.ssh.config(id)?;
@@ -774,6 +777,8 @@ pub async fn remote_connect(
let (peer, root, run) =
crate::remote_container::connect(&state, folder, config, replace, handler, &tail, &progress).await?;
path = root;
// The MCP tools leave this container alone while a window is open in it.
attached = Some(state.host.dev_containers_attached.hold(run.container()));
exec = Some(Arc::new(run));
let name = std::path::Path::new(folder)
.file_name()
@@ -847,6 +852,7 @@ pub async fn remote_connect(
forwards: Mutex::new(Vec::new()),
web_forwards: Mutex::new(Vec::new()),
exec,
_attached: attached,
});
let _ = connection_slot.set(Arc::downgrade(&connection));
if let RemoteTarget::DevContainer { folder, config } = &target {
@@ -1615,6 +1621,7 @@ mod tests {
next_channel: std::sync::atomic::AtomicU64::new(1),
session: None,
exec: None,
_attached: None,
forwards: Mutex::new(Vec::new()),
web_forwards: Mutex::new(Vec::new()),
}
+1
Переглянути файл
@@ -112,6 +112,7 @@ impl AppState {
runtime,
project_environment: false,
})
.with_local_desktop()
.with_local_database_tunnels()
.with_subversion(true),
);
+135
Переглянути файл
@@ -0,0 +1,135 @@
//! The display the user last worked on, on Windows. The window-state plugin restores only the
//! maximized and full-screen flags there (`window_state_flags`), so without this every project
//! window that opens at launch, or after the last one closed, lands on the primary display.
use serde::{Deserialize, Serialize};
/// A display by its physical position and size in the virtual screen.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Display {
x: i32,
y: i32,
width: u32,
height: u32,
}
/// The connected display that is the saved one: same position and size. Displays rearranged or
/// resized since then are not matched, so the window opens on the primary display as before.
fn find(connected: &[Display], saved: Display) -> Option<usize> {
connected.iter().position(|d| *d == saved)
}
/// The top-left corner, in the display's logical pixels, that centres a window of `size` in a
/// work area at `origin` of `area` (both logical).
fn centred(origin: (f64, f64), area: (f64, f64), size: (f64, f64)) -> (f64, f64) {
(origin.0 + ((area.0 - size.0) / 2.0).max(0.0), origin.1 + ((area.1 - size.1) / 2.0).max(0.0))
}
#[cfg(windows)]
pub use native::{place, remember};
#[cfg(windows)]
mod native {
use super::{Display, centred, find};
use parking_lot::Mutex;
use std::path::PathBuf;
use tauri::{AppHandle, Manager, Monitor, Runtime, Window, utils::config::WindowConfig};
const FILE: &str = "last-display.json";
/// The saved display, read from disk once.
static SAVED: Mutex<Option<Option<Display>>> = Mutex::new(None);
fn display(monitor: &Monitor) -> Display {
let (position, size) = (monitor.position(), monitor.size());
Display { x: position.x, y: position.y, width: size.width, height: size.height }
}
fn file<R: Runtime>(app: &AppHandle<R>) -> Option<PathBuf> {
ide_host::data_dirs::config_dir(&app.config().identifier).ok().map(|dir| dir.join(FILE))
}
fn saved<R: Runtime>(app: &AppHandle<R>) -> Option<Display> {
*SAVED.lock().get_or_insert_with(|| {
let text = std::fs::read_to_string(file(app)?).ok()?;
serde_json::from_str(&text).ok()
})
}
/// Records the display a project window is on, when it is focused or moved.
pub fn remember<R: Runtime>(window: &Window<R>) {
if crate::windows::auxiliary_parent(window.label()).is_some() {
return;
}
let Ok(Some(monitor)) = window.current_monitor() else { return };
let now = display(&monitor);
let app = window.app_handle();
if saved(app) == Some(now) {
return;
}
*SAVED.lock() = Some(Some(now));
let Some(path) = file(app) else { return };
if let Ok(text) = serde_json::to_string(&now)
&& let Err(e) = std::fs::write(&path, text)
{
tracing::debug!("cannot save {}: {e}", path.display());
}
}
/// Where a new project window opens: the saved display when it is still connected, else the
/// primary one. A window without a position of its own (not cascaded from another window) is
/// centred on it. Returns the display, whose work area sizes the window.
pub fn place<R: Runtime>(app: &AppHandle<R>, config: &mut WindowConfig) -> Option<Monitor> {
let primary = app.primary_monitor().ok().flatten();
if config.x.is_some() {
return primary;
}
let connected = app.available_monitors().unwrap_or_default();
let displays: Vec<Display> = connected.iter().map(display).collect();
let Some(monitor) = saved(app).and_then(|s| find(&displays, s)).map(|i| connected[i].clone()) else {
return primary;
};
if primary.as_ref().is_some_and(|p| display(p) == display(&monitor)) {
return primary;
}
let scale = monitor.scale_factor();
let area = monitor.work_area();
let origin = area.position.to_logical::<f64>(scale);
let size = area.size.to_logical::<f64>(scale);
let window = (config.width.min(size.width), config.height.min(size.height));
let (x, y) = centred((origin.x, origin.y), (size.width, size.height), window);
// tao places a logical position on the display it falls on, using that display's scale.
config.x = Some(x);
config.y = Some(y);
config.center = false;
Some(monitor)
}
}
#[cfg(test)]
mod tests {
use super::*;
const PRIMARY: Display = Display { x: 0, y: 0, width: 2560, height: 1440 };
const SECOND: Display = Display { x: 2560, y: 0, width: 1920, height: 1080 };
#[test]
fn finds_the_saved_display_only_while_it_is_connected_unchanged() {
assert_eq!(find(&[PRIMARY, SECOND], SECOND), Some(1));
assert_eq!(find(&[PRIMARY], SECOND), None);
// Rearranged to the left of the primary display: not the saved one any more.
assert_eq!(find(&[PRIMARY, Display { x: -1920, ..SECOND }], SECOND), None);
}
#[test]
fn centres_in_the_work_area_and_keeps_a_larger_window_at_its_corner() {
assert_eq!(centred((2560.0, 0.0), (1920.0, 1040.0), (1440.0, 900.0)), (2800.0, 70.0));
assert_eq!(centred((2560.0, 0.0), (1280.0, 680.0), (1440.0, 900.0)), (2560.0, 0.0));
}
#[test]
fn the_saved_display_round_trips_through_json() {
let text = serde_json::to_string(&SECOND).unwrap();
assert_eq!(serde_json::from_str::<Display>(&text).unwrap(), SECOND);
}
}
+2 -2
Переглянути файл
@@ -1102,9 +1102,9 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
#[cfg(target_os = "linux")]
let show_after_build = crate::linux_window_state::prepare(app, &mut config);
// Windows opens a project window at the configured size (window-state restores only the
// maximized flag there), which Restore Down returns to.
// maximized flag there), which Restore Down returns to, on the display last worked on.
#[cfg(windows)]
if let Ok(Some(monitor)) = app.primary_monitor() {
if let Some(monitor) = crate::window_display::place(app, &mut config) {
let area = monitor.work_area().size.to_logical::<f64>(monitor.scale_factor());
let min = (config.min_width.unwrap_or(0.0), config.min_height.unwrap_or(0.0));
let (size, min) = fit_new_window((config.width, config.height), min, (area.width, area.height));
+10 -3
Переглянути файл
@@ -3421,7 +3421,9 @@ doneMs?: number | null;
/** Sent into a running turn rather than starting one. */
steered?: boolean;
/** Set when this turn was started automatically or via 1-click Resume to recover an interrupted turn. */
recovery?: InterruptionReason | null } | { type: "agent"; text: string } |
recovery?: InterruptionReason | null;
/** One-based automatic retry number for this continuation. */
retryAttempt?: number | null } | { type: "agent"; text: string } |
/** A question that can be answered while the agent keeps working, or after the turn ends. */
{ type: "question"; id: string; title: string; questions: AgentQuestion[];
/** The submitted answers, or `Skipped`; `None` while unanswered. */
@@ -11227,7 +11229,7 @@ export type InterfaceMember = {
};
/** Why an in-flight turn stopped before completing. */
export type InterruptionReason = "windowClose" | "quit" | "restart" | "backendUpgrade" | "backendStop" | "unexpectedExit" | "networkTimeout";
export type InterruptionReason = "windowClose" | "quit" | "restart" | "backendUpgrade" | "backendStop" | "unexpectedExit" | "networkTimeout" | "cursorCapacity";
/** Optional parts of the invalidation; the symbol index is always rebuilt. */
export type InvalidateCachesOptions = {
@@ -12497,6 +12499,9 @@ export type MavenSettings = {
runTestsUsing?: MavenRunTestsUsing,
};
/** The execution target recorded with an MCP agent run. */
export type McpAgentRunTarget = { kind: "host" } | { kind: "container"; id: string };
/** What keeps an idle background project loaded. */
export type McpBackgroundHold =
/** A tool call is in flight. */
@@ -12820,7 +12825,7 @@ export type McpUiRequest = { type: "confirm"; client: string; tool: string; subj
* The project is served without a window: the request shows in another project's window,
* which names it and keeps the keyboard focus where it is.
*/
background?: boolean } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string } } | { type: "runConfiguration"; config: unknown } |
background?: boolean } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string }; target: McpAgentRunTarget } | { type: "runConfiguration"; config: unknown } |
/** Start a run configuration in Debug mode as the IDE's Debug action would. */
{ type: "debugConfiguration"; config: unknown } |
/**
@@ -17322,6 +17327,8 @@ export type ToolDownloadSettings = {
* crates.io). Off by default.
*/
configuredRegistriesOnly?: boolean,
/** The managed Vue Language Server release. Empty selects it from the project's Vue dependency. */
vueLanguageServerVersion?: string,
};
/** UI-facing state of one tool. */
+2 -2
Переглянути файл
@@ -260,7 +260,7 @@ class Scanner {
return end < 0 ? n : end + quotes;
}
if (!verbatim && quotes === 2) return j + 2;
for (j++; j < n; ) {
for (j++; j < n;) {
const c = s[j];
if (verbatim) {
if (c === '"') {
@@ -304,7 +304,7 @@ class Scanner {
const s = this.s,
n = this.n;
let depth = 0;
for (let i = start; i < n; ) {
for (let i = start; i < n;) {
const c = s[i];
if (this.startsString(i)) {
i = this.skipString(i);
+39
Переглянути файл
@@ -308,6 +308,45 @@ describe("applying completions", () => {
expect(view.state.selection.main.head).toBe(expected.indexOf("|"));
});
it.each([
{
name: "break in a switch case",
doc: "switch (c) {\n case A:\n bre|\n default:\n}",
label: "break",
expected: "switch (c) {\n case A:\n break;|\n default:\n}",
},
{
name: "continue in a loop",
doc: "for (var e : list) {\n if (e == null) cont|\n}",
label: "continue",
expected: "for (var e : list) {\n if (e == null) continue;|\n}",
},
{
name: "break inside a labeled loop, which can name the label",
doc: "outer:\nfor (int i = 0; i < n; i++) {\n while (true) {\n bre|\n }\n}",
label: "break",
expected: "outer:\nfor (int i = 0; i < n; i++) {\n while (true) {\n break |\n }\n}",
},
{ name: "break before its semicolon", doc: "bre|;", label: "break", expected: "break|;" },
{ name: "break before a label", doc: "bre| outer;", label: "break", expected: "break| outer;" },
])("completes a Java $name as IDEA does (#7358)", ({ doc, label, expected }) => {
const { view, req, pos } = setup(doc);
const typed = doc.slice(0, doc.indexOf("|")).match(/\w+$/)![0];
apply(
view,
makeCompletion(item({ label, kind: "keyword", insertText: label }), { ...req, language: "java" }),
pos - typed.length,
);
expect(view.state.doc.toString()).toBe(expected.replace("|", ""));
expect(view.state.selection.main.head).toBe(expected.indexOf("|"));
});
it("leaves other languages' break alone", () => {
const { view, req, pos } = setup("bre|");
apply(view, makeCompletion(item({ label: "break", kind: "keyword", insertText: "break" }), req), pos - 3);
expect(view.state.doc.toString()).toBe("break");
});
it("replaces a Java annotation name before its existing arguments with Tab", () => {
const { view, req, pos } = setup('@Sup|pressWarnings("unused")');
const suggestion = item({
+34
Переглянути файл
@@ -253,6 +253,8 @@ function completionInsertText(
to: number,
): string {
const { insertText } = item;
if (language === "java" && item.kind === "keyword" && JUMP_KEYWORDS.has(insertText))
return insertText + javaJumpTail(doc, from, to);
// JDT LS can append a space to a bare annotation name. It is useful only as a separator.
if (language !== "java" || item.kind !== "interface" || insertText !== `${item.label} `) return insertText;
const line = doc.lineAt(from);
@@ -262,6 +264,38 @@ function completionInsertText(
return item.label;
}
const JUMP_KEYWORDS = new Set(["break", "continue"]);
const LABEL =
/[\n;{}]\s*(?!case\b|default\b)[\p{L}_$][\p{L}\p{N}_$]*\s*:\s*(?:for|while|do|switch)?\s*(?:\([^]*\))?\s*$/u;
/** How far back the enclosing statements are looked for. */
const LABEL_SCAN = 20_000;
/**
* What follows a completed `break` / `continue` in Java (#7358), as in IDEA: `;`, or a space for
* the label inside a labeled statement; nothing when the line already goes on (`break;`, `break outer`).
*/
function javaJumpTail(doc: Text, from: number, to: number): string {
const after = doc.sliceString(to, doc.lineAt(to).to);
if (/^\s*[;\p{L}\p{N}_$]/u.test(after)) return "";
return insideLabeledStatement(doc, from) ? " " : ";";
}
/** Whether a block enclosing `pos` is a labeled statement's (`outer: for (…) {`); comments and strings are not skipped. */
function insideLabeledStatement(doc: Text, pos: number): boolean {
const start = Math.max(0, pos - LABEL_SCAN);
const text = doc.sliceString(start, pos);
let depth = 0;
for (let i = text.length - 1; i >= 0; i--) {
const ch = text[i];
if (ch === "}") depth++;
else if (ch === "{") {
if (depth > 0) depth--;
else if (LABEL.test("\n" + text.slice(Math.max(0, i - 400), i))) return true;
}
}
return false;
}
/** ↵ (`insert`) or ⇥ (`replace`: also overwrites the rest of the identifier). */
export function applyLspCompletion(
view: EditorView,
+1 -1
Переглянути файл
@@ -82,7 +82,7 @@ const markdown = {
".tok-string, .tok-string2": { color: "var(--syn-string)" },
".tok-number, .tok-bool, .tok-atom": { color: "var(--syn-number)" },
".tok-typeName, .tok-className, .tok-namespace": { color: "var(--syn-type)" },
".tok-comment": { color: "var(--syn-comment)", fontStyle: "italic" },
".tok-comment": { color: "var(--syn-comment)", fontStyle: "var(--syn-comment-italic, var(--syn-comment-style))" },
".tok-meta, .tok-macroName": { color: "var(--syn-annotation)" },
".tok-propertyName": { color: "var(--syn-property)" },
".tok-variableName.tok-definition": { color: "var(--syn-function)" },
+129 -17
Переглянути файл
@@ -1,17 +1,49 @@
/* Keep technical metadata from competing with the row's name and action. */
.row {
min-height: var(--h-row);
padding-block: 2px;
padding: var(--space-1-5) var(--space-2);
}
.expand {
align-items: flex-start;
min-width: 0;
}
.expand > svg {
margin-top: var(--space-0-5);
}
.titleRow {
display: flex;
align-items: baseline;
gap: var(--space-1-5);
min-width: 0;
}
.entryTitle {
flex-shrink: 0;
min-width: 0;
color: var(--fg-strong);
font-weight: 500;
overflow-wrap: anywhere;
}
.titleRow .entryTitle {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.version {
flex: none;
max-width: 40%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fg-muted);
font-size: var(--fs-small);
}
.subtitle {
flex: 1;
min-width: 0;
color: var(--fg-muted);
font-size: var(--fs-small);
@@ -20,8 +52,81 @@
white-space: nowrap;
}
.scopeSelect {
min-width: 120px;
.statusRow {
display: flex;
flex-wrap: wrap;
gap: var(--space-0-5) var(--space-2);
color: var(--warning);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
.nativeHint {
display: flex;
align-items: center;
gap: var(--space-1);
}
.nativeHint > svg,
.nativeHint > img {
flex-shrink: 0;
}
.description {
color: var(--fg);
line-height: 1.45;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.groupTitle {
flex-shrink: 0;
max-width: calc(100% - 48px);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.groupPath {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rowControls {
justify-content: flex-end;
}
@container settings-content (max-width: 360px) {
.reviewRow {
flex-wrap: wrap;
}
.reviewRow .expand {
flex-basis: 100%;
}
.version {
display: none;
}
.groupToggle {
flex-wrap: wrap;
}
.groupPath {
flex-basis: 100%;
padding-left: var(--space-4);
}
.searchRow {
flex-wrap: wrap;
}
.searchRow > :first-child {
flex-basis: 100%;
}
}
.controls {
@@ -36,7 +141,7 @@
display: flex;
flex-direction: column;
gap: var(--space-2);
padding: 10px 12px;
padding: var(--space-2) var(--space-3);
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
@@ -54,7 +159,8 @@
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
gap: var(--space-1) var(--space-3);
min-width: 0;
}
.summaryTitle {
@@ -66,12 +172,15 @@
display: inline-flex;
align-items: center;
gap: var(--space-1);
padding: 2px 8px;
border-radius: var(--radius-small);
border: 1px solid var(--border);
background: var(--bg-app);
padding: 0;
border: 0;
background: none;
color: var(--link);
font-size: var(--fs-tiny);
font-size: var(--fs-small);
text-align: left;
min-width: 0;
max-width: 100%;
overflow-wrap: anywhere;
cursor: pointer;
}
@@ -98,14 +207,17 @@
display: inline-flex;
align-items: center;
gap: var(--space-1);
padding: 2px 7px;
border-radius: var(--radius-small);
background: var(--bg-app);
box-shadow: inset 0 0 0 1px var(--border);
font-size: var(--fs-tiny);
min-width: 0;
max-width: 100%;
font-size: var(--fs-small);
color: var(--fg-secondary);
}
.marketplaceChip > span:not(:first-child) {
overflow-wrap: anywhere;
min-width: 0;
}
.dialogBody {
display: flex;
flex-direction: column;
+105 -61
Переглянути файл
@@ -213,38 +213,38 @@ export function AgentPluginsPage({ backend = defaultPluginsBackend }: { backend?
<div className={styles.summaryBox}>
<div className={styles.summaryHeader}>
<div className={styles.summaryPills}>
<span className={styles.summaryTitle}>
<T>Active Bundle Projection</T>
</span>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", SKILLS_PAGE)}
>
{formatMessage(tx("{count} skills → Skills"), { count: catalog.projectedSkills })}
</button>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", MCP_PAGE)}
>
{formatMessage(tx("{count} MCP servers → MCP Connections"), { count: catalog.projectedMcpServers })}
</button>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", MEMORY_PAGE)}
>
{formatMessage(tx("{count} rules → Memory"), { count: catalog.projectedRules })}
</button>
</div>
<span className={styles.summaryTitle}>
<T>Active Bundle Projection</T>
</span>
{backend.addMarketplace && (
<Button size="small" onClick={() => setMarketplacesOpen(true)}>
{formatMessage(tx("Marketplaces ({count})…"), { count: catalog.marketplaces.length })}
</Button>
)}
</div>
<div className={styles.summaryPills}>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", SKILLS_PAGE)}
>
{formatMessage(tx("{count} skills → Skills"), { count: catalog.projectedSkills })}
</button>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", MCP_PAGE)}
>
{formatMessage(tx("{count} MCP servers → MCP Connections"), { count: catalog.projectedMcpServers })}
</button>
<button
type="button"
className={styles.projectionLink}
onClick={() => void executeAction("file.settings", MEMORY_PAGE)}
>
{formatMessage(tx("{count} rules → Memory"), { count: catalog.projectedRules })}
</button>
</div>
{catalog.marketplaces.length > 0 && (
<div className={styles.marketplaceRow}>
@@ -289,7 +289,7 @@ export function AgentPluginsPage({ backend = defaultPluginsBackend }: { backend?
/>
</div>
<div className={page.searchRow}>
<div className={clsx(page.searchRow, styles.searchRow)}>
<SearchField
className={page.search}
value={query}
@@ -322,14 +322,16 @@ export function AgentPluginsPage({ backend = defaultPluginsBackend }: { backend?
<div className={page.sectionBar}>
<button
type="button"
className={page.sectionToggle}
className={clsx(page.sectionToggle, styles.groupToggle)}
aria-expanded={!isCollapsed}
onClick={() => setCollapsed((prev) => ({ ...prev, [key]: !prev[key] }))}
>
<Icon name={isCollapsed ? "chevron-right" : "chevron-down"} size={14} className={page.chevron} />
<span className={page.sectionTitle}>{title}</span>
<span className={clsx(page.sectionTitle, styles.groupTitle)}>{title}</span>
<span className={page.badge}>{items.length}</span>
<span className={page.sectionHint}>{pluginGroupPath(source, scope)}</span>
<span className={clsx(page.sectionHint, styles.groupPath)} title={pluginGroupPath(source, scope)}>
{pluginGroupPath(source, scope)}
</span>
</button>
</div>
@@ -438,41 +440,55 @@ function PluginCard({
const { plugin } = state;
const summary = componentSummary(state, tx);
const group = PLUGIN_SOURCE_GROUPS[plugin.source];
const details = [summary, plugin.approxTokens > 0 ? `~${plugin.approxTokens}t` : ""].filter(Boolean).join(" · ");
const subtitle = [details, plugin.description].filter(Boolean).join(" · ");
const needsReview = state.consentRequired && !state.enabled;
return (
<div role="listitem" className={page.card}>
<div className={clsx(page.cardHeader, styles.row)}>
<button type="button" className={page.cardExpandBtn} aria-expanded={isExpanded} onClick={onToggleExpand}>
<div className={clsx(page.cardHeader, styles.row, needsReview && styles.reviewRow)}>
<button
type="button"
className={clsx(page.cardExpandBtn, styles.expand)}
aria-expanded={isExpanded}
onClick={onToggleExpand}
>
<Icon name={isExpanded ? "chevron-down" : "chevron-right"} size={13} className={page.chevron} />
<span className={styles.entryTitle}>{plugin.displayName}</span>
{plugin.version && <span className={page.tag}>v{plugin.version}</span>}
{plugin.marketplace && <span className={page.tag}>{plugin.marketplace}</span>}
{plugin.formats.map((f) => (
<span key={f} className={page.tag}>
{pluginFormatLabel(f)}
<span className={page.cardMain}>
<span className={styles.titleRow}>
<span className={styles.entryTitle} title={plugin.displayName}>
{plugin.displayName}
</span>
{plugin.version && (
<span className={styles.version} title={plugin.version}>
v{plugin.version}
</span>
)}
</span>
))}
{summary && <span className={page.tag}>{summary}</span>}
{plugin.approxTokens > 0 && <span className={page.tag}>~{plugin.approxTokens}t</span>}
{plugin.description && (
<span className={styles.subtitle} title={plugin.description}>
{plugin.description}
</span>
)}
{state.origin === "trust" && (
<span className={clsx(page.tag, page.tagWarning)}>
<T>Untrusted workspace</T>
</span>
)}
{state.consentRequired && (
<span className={clsx(page.tag, page.tagWarning)}>
<T>Approval required</T>
</span>
)}
{subtitle && (
<span className={styles.subtitle} title={subtitle}>
{subtitle}
</span>
)}
{(state.origin === "trust" || state.consentRequired) && (
<span className={styles.statusRow}>
{state.origin === "trust" && (
<span>
<T>Untrusted workspace</T>
</span>
)}
{state.consentRequired && (
<span>
<T>Approval required</T>
</span>
)}
</span>
)}
</span>
</button>
<div className={styles.controls}>
{state.consentRequired && !state.enabled ? (
<div className={clsx(styles.controls, styles.rowControls)}>
{needsReview ? (
<Button
size="small"
disabled={busy || (state.origin === "trust" && !hasTrustedProject)}
@@ -493,7 +509,34 @@ function PluginCard({
{isExpanded && (
<div className={page.cardDrawer}>
{plugin.description && <span className={styles.description}>{plugin.description}</span>}
{details && <span className={styles.hint}>{details}</span>}
<div className={page.metaGrid}>
{plugin.version && (
<>
<span className={page.metaLabel}>
<T>Version</T>
</span>
<span className={page.metaValue}>{plugin.version}</span>
</>
)}
{plugin.marketplace && (
<>
<span className={page.metaLabel}>
<T>Marketplace</T>
</span>
<span className={page.metaValue}>{plugin.marketplace}</span>
</>
)}
{plugin.formats.length > 0 && (
<>
<span className={page.metaLabel}>
<T>Format</T>
</span>
<span className={page.metaValue}>{plugin.formats.map(pluginFormatLabel).join(" · ")}</span>
</>
)}
<span className={page.metaLabel}>
<T>Scope</T>
</span>
@@ -558,7 +601,7 @@ function PluginCard({
</button>
)}
{(plugin.capabilities.hookFiles?.length ?? 0) > 0 && (
<span className={page.tag}>{(plugin.capabilities.hookFiles ?? []).join(", ")}</span>
<span className={page.metaValue}>{(plugin.capabilities.hookFiles ?? []).join(", ")}</span>
)}
</span>
@@ -573,8 +616,9 @@ function PluginCard({
</div>
{group.agent && (
<span className={styles.hint}>
<Icon name={providerIcon(group.agent)} size={12} /> {tx(group.label)} reads this bundle natively.
<span className={clsx(styles.hint, styles.nativeHint)}>
<Icon name={providerIcon(group.agent)} size={12} />
<span>{tx(group.label)} reads this bundle natively.</span>
</span>
)}
+7 -46
Переглянути файл
@@ -62,13 +62,7 @@ import { setFocusedTaskList } from "./taskListFocus";
import { matchTask } from "./taskSearch";
import { SessionEditor } from "./SessionEditor";
import { HomeEditor } from "./HomeEditor";
import {
automatedTaskVisible,
openAutomationDialog,
openAutomations,
useAutomations,
useAutomationsSync,
} from "./automationsModel";
import { automatedTaskVisible, useAutomations, useAutomationsSync } from "./automationsModel";
import styles from "./Agents.module.css";
import autoStyles from "./Automations.module.css";
import { basename, useProject } from "@/platform/project";
@@ -76,10 +70,15 @@ import { useTx } from "@/platform/i18n";
import { executeAction } from "@/platform/actions";
export function AgentsHeaderActions() {
const host = useAutomations((s) => s.snapshot.host);
const hasAttention = host.unreadRuns > 0 || host.needsInputRuns > 0;
return (
<>
<IconButton icon="plus" action="agents.newTask" />
<IconButton icon="clock" action="agents.automations" />
<span className={autoStyles.headerBadgeWrap}>
<IconButton icon="clock" action="agents.automations" />
{hasAttention && <span className={autoStyles.headerBadgeDot} aria-hidden="true" />}
</span>
<IconButton icon="settings" action="agents.mcpServers" />
</>
);
@@ -179,8 +178,6 @@ export function AgentsView() {
const providers = useAgents((s) => s.providers);
const docked = useAgents((s) => s.docked);
const homeOpen = useAgents((s) => s.homeOpen);
const automationHost = useAutomations((s) => s.snapshot.host);
const automationCount = useAutomations((s) => s.snapshot.automations.length);
const automatedRunFilter = useAutomations((s) => s.automatedRunFilter);
const inline = docked !== null || homeOpen;
const historyRef = useRef<HTMLButtonElement>(null);
@@ -535,42 +532,6 @@ export function AgentsView() {
setFocusedTaskList(null);
}}
>
<div className={autoStyles.hubBar} data-testid="agents-automations-hub">
<button
type="button"
className={autoStyles.hubBtn}
onClick={() => {
setHistoryOpen(false);
openAutomations();
}}
>
<Icon name="clock" size={14} />
<span>
<T>Automations</T>
</span>
<span className={autoStyles.hubMeta}>
{automationHost.activeSchedules > 0 ? (
<span>
{automationHost.activeSchedules === 1 ? tx("1 active") : tx`${automationHost.activeSchedules} active`}
</span>
) : automationCount > 0 ? (
<span>{automationCount}</span>
) : null}
{automationHost.unreadRuns > 0 && (
<span className={clsx(autoStyles.tag, autoStyles.tagUnread)}>{automationHost.unreadRuns}</span>
)}
</span>
</button>
<IconButton
icon="plus"
size="small"
title="New Automation"
onClick={() => {
setHistoryOpen(false);
openAutomationDialog();
}}
/>
</div>
{tasks.size > 0 && (
<SearchField
className={styles.taskSearch}
+223 -168
Переглянути файл
@@ -49,9 +49,21 @@ const SCHEDULE_KIND_OPTIONS: ReadonlyArray<SelectOption<TriggerKind>> = [
];
const PERMISSION_OPTIONS: ReadonlyArray<SelectOption<AutomationPermissionMode>> = [
{ value: "assisted", label: "Accept edits (edit workspace files without asking; ask before commands)" },
{ value: "allowAll", label: "Allow all (capped by your interactive approval setting)" },
{ value: "default", label: "Ask for approval (ask before edits and commands)" },
{
value: "assisted",
label: "Accept edits",
detail: "Edit workspace files without asking; ask before commands",
},
{
value: "allowAll",
label: "Allow all",
detail: "Capped by your interactive approval setting",
},
{
value: "default",
label: "Ask for approval",
detail: "Ask before edits and commands",
},
];
const CONTINUITY_OPTIONS: ReadonlyArray<SelectOption<AutomationContinuity>> = [
@@ -178,6 +190,18 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
const [disableAfterStr, setDisableAfterStr] = useState(() =>
editing?.disableAfterMs ? toDatetimeLocalValue(editing.disableAfterMs).slice(0, 10) : "",
);
// Expand Advanced automatically when editing a schedule with non-default advanced options.
const [advancedOpen, setAdvancedOpen] = useState(() =>
Boolean(
editing &&
(editing.permissions !== "assisted" ||
editing.continuity !== "newTask" ||
editing.misfirePolicy != null ||
editing.maxRuns != null ||
editing.disableAfterMs != null ||
(editing.workspace.kind === "project" && !editing.workspace.autoCleanWorktree)),
),
);
const [fetchedBranches, setFetchedBranches] = useState<{ root: string; list: Branch[] }>({ root: "", list: [] });
const [previewState, setPreviewState] = useState<{ runs: number[]; error: string | null }>({
@@ -249,12 +273,15 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
const previewError = currentTrigger.kind === "manual" ? null : previewState.error;
const selectedProvider = providers.find((p) => p.id === providerId) ?? providers[0];
// Exclude interactive permission/approval controls here so they don't conflict with Unattended Permissions.
const providerConfig = useMemo(
() =>
(selectedProvider?.config ?? []).map((opt) => ({
...opt,
current: configMap[opt.id] ?? opt.current,
})),
(selectedProvider?.config ?? [])
.filter((opt) => opt.category !== "permissions" && opt.category !== "approval" && opt.category !== "mode")
.map((opt) => ({
...opt,
current: configMap[opt.id] ?? opt.current,
})),
[selectedProvider, configMap],
);
@@ -275,6 +302,9 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
[branches, tx],
);
const permissionSummary = tx(PERMISSION_OPTIONS.find((o) => o.value === permissions)?.label ?? "Accept edits");
const continuitySummary = continuity === "sameTask" ? tx("Rolling session") : tx("Fresh session");
const toggleWeekday = (day: number) => {
setWeeklyDays((cur) =>
cur.includes(day) ? (cur.length > 1 ? cur.filter((d) => d !== day) : cur) : [...cur, day].sort(),
@@ -343,7 +373,7 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
open={dialog.open}
onClose={closeAutomationDialog}
title={editing ? tx("Edit Automation") : tx("New Automation")}
width={620}
width={560}
maxHeight={760}
resizable="both"
footerStart={<Checkbox checked={enabled} onChange={setEnabled} label="Active schedule" />}
@@ -395,107 +425,25 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
<label className={styles.fieldLabel} htmlFor="automation-prompt-input">
<T>Prompt Instructions</T>
</label>
<textarea
id="automation-prompt-input"
className={styles.promptTextarea}
value={promptText}
onChange={(e) => setPromptText(e.target.value)}
placeholder={tx("Describe what the agent should inspect, verify, or report on each run…")}
/>
<div className={styles.pickerBar}>
<ConfigPickers
config={providerConfig}
onChange={(id, val) => setConfigMap((prev) => ({ ...prev, [id]: val }))}
<div className={styles.promptBox}>
<textarea
id="automation-prompt-input"
className={styles.promptTextarea}
value={promptText}
onChange={(e) => setPromptText(e.target.value)}
placeholder={tx("Describe what the agent should inspect, verify, or report on each run…")}
/>
<McpPicker provider={providerId} overrides={mcpOverrides} onChange={setMcpOverrides} />
<SkillsPicker provider={providerId} overrides={skillOverrides} onChange={setSkillOverrides} />
<MemoryPicker provider={providerId} overrides={memoryOverrides} onChange={setMemoryOverrides} />
</div>
</div>
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Workspace Target</T>
</span>
<Select
aria-label={tx("Workspace Target")}
value={workspaceMode}
options={[
...(projectRoot ? [{ value: "project", label: tx("Project workspace") }] : []),
{ value: "chatOnly", label: tx("No workspace (chat only)") },
]}
onChange={(v) => setWorkspaceMode(v as "project" | "chatOnly")}
/>
</div>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Session Continuity</T>
</span>
<Select
aria-label={tx("Session Continuity")}
value={continuity}
options={CONTINUITY_OPTIONS}
onChange={(v) => setContinuity(v)}
/>
</div>
</div>
{workspaceMode === "project" && projectRoot && (
<div className={styles.fieldRow}>
{workspaceProjects.length > 1 ? (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Repository</T>
</span>
<Select
aria-label={tx("Repository")}
value={projectRoot}
options={workspaceProjects.map((p) => ({ value: p, label: basename(p) }))}
onChange={setProjectRoot}
/>
</div>
) : null}
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Checkout Isolation</T>
</span>
<Select
aria-label={tx("Checkout Isolation")}
value={isolation}
options={[
{ value: "worktree", label: tx("Isolated Git worktree (Recommended)") },
{ value: "local", label: tx("Local checkout") },
]}
onChange={(v) => setIsolation(v as Isolation)}
<div className={styles.promptBar}>
<ConfigPickers
config={providerConfig}
onChange={(id, val) => setConfigMap((prev) => ({ ...prev, [id]: val }))}
/>
<McpPicker provider={providerId} overrides={mcpOverrides} onChange={setMcpOverrides} />
<SkillsPicker provider={providerId} overrides={skillOverrides} onChange={setSkillOverrides} />
<MemoryPicker provider={providerId} overrides={memoryOverrides} onChange={setMemoryOverrides} />
</div>
{isolation === "worktree" && (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Base Branch</T>
</span>
<Select
aria-label={tx("Base Branch")}
value={baseBranch}
options={branchOptions}
onChange={setBaseBranch}
/>
</div>
)}
</div>
)}
{workspaceMode === "project" && isolation === "worktree" && continuity === "newTask" && (
<Checkbox
checked={autoCleanWorktree}
onChange={setAutoCleanWorktree}
label="Auto-delete temporary worktree when the run makes zero file changes"
/>
)}
</div>
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
@@ -604,15 +552,15 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
)}
{triggerKind !== "manual" && (
<div className={styles.previewBox} data-testid="automation-schedule-preview">
<div className={styles.previewLine} data-testid="automation-schedule-preview">
{previewError ? (
<span style={{ color: "var(--danger)" }}>{previewError}</span>
<span className={styles.previewError}>{previewError}</span>
) : previewRuns.length > 0 ? (
<>
<strong>
<span className={styles.previewLabel}>
<T>Upcoming runs:</T>
</strong>
<span>{previewRuns.map((ms) => formatShortTimestamp(ms)).join(" · ")}</span>
</span>
<span>{previewRuns.map((ms) => formatShortTimestamp(ms)).join(" · ")}</span>
</>
) : (
<span>
@@ -622,76 +570,183 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) {
</div>
)}
<div className={styles.fieldRow}>
<div className={styles.workspaceRow}>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Unattended Permissions</T>
<T>Workspace Target</T>
</span>
<Select
aria-label={tx("Unattended Permissions")}
value={permissions}
options={PERMISSION_OPTIONS}
onChange={(v) => setPermissions(v)}
aria-label={tx("Workspace Target")}
value={workspaceMode}
options={[
...(projectRoot ? [{ value: "project", label: tx("Project workspace") }] : []),
{ value: "chatOnly", label: tx("No workspace (chat only)") },
]}
onChange={(v) => setWorkspaceMode(v as "project" | "chatOnly")}
/>
</div>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Missed Schedule Policy</T>
</span>
<Select
aria-label={tx("Missed Schedule Policy")}
value={misfirePolicy}
options={MISFIRE_OPTIONS}
onChange={setMisfirePolicy}
/>
</div>
{workspaceMode === "project" && projectRoot && workspaceProjects.length > 1 && (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Repository</T>
</span>
<Select
aria-label={tx("Repository")}
value={projectRoot}
options={workspaceProjects.map((p) => ({ value: p, label: basename(p) }))}
onChange={setProjectRoot}
/>
</div>
)}
{workspaceMode === "project" && projectRoot && (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Checkout Isolation</T>
</span>
<Select
aria-label={tx("Checkout Isolation")}
value={isolation}
options={[
{ value: "worktree", label: tx("Isolated Git worktree"), detail: tx("Recommended") },
{ value: "local", label: tx("Local checkout") },
]}
onChange={(v) => setIsolation(v as Isolation)}
/>
</div>
)}
{workspaceMode === "project" && projectRoot && isolation === "worktree" && (
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Base Branch</T>
</span>
<Select
aria-label={tx("Base Branch")}
value={baseBranch}
options={branchOptions}
onChange={setBaseBranch}
/>
</div>
)}
</div>
{agentSettings.newTaskApprovals === "ask" && permissions !== "default" && (
<div className={styles.fieldHint}>
<T>
Your interactive New Tasks setting is Asking for approval, so scheduled turns are capped to ask before
edits and commands.
</T>
</div>
)}
<div className={styles.advancedSection}>
<button
type="button"
className={styles.advancedToggle}
aria-expanded={advancedOpen}
onClick={() => setAdvancedOpen((v) => !v)}
>
<span className={styles.advancedTitle}>
<Icon name={advancedOpen ? "chevron-down" : "chevron-right"} size={13} />
<T>Advanced</T>
</span>
{!advancedOpen && (
<span className={styles.advancedSummary}>
{permissionSummary} · {continuitySummary}
</span>
)}
</button>
{permissions === "allowAll" && workspaceMode === "project" && isolation === "local" && (
<div className={styles.fieldHint} style={{ color: "var(--warning)" }}>
<T>
Warning: Autonomous mode on a local checkout can modify your working files directly. Prefer an isolated
Git worktree.
</T>
</div>
)}
{advancedOpen && (
<div className={styles.advancedBody}>
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Unattended Permissions</T>
</span>
<Select
aria-label={tx("Unattended Permissions")}
value={permissions}
options={PERMISSION_OPTIONS}
onChange={(v) => setPermissions(v)}
/>
</div>
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-max-runs-input">
<T>Stop After Runs (optional)</T>
</label>
<Input
id="automation-max-runs-input"
type="number"
min={1}
value={maxRunsStr}
onChange={(e) => setMaxRunsStr(e.target.value)}
placeholder="50"
/>
</div>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Session Continuity</T>
</span>
<Select
aria-label={tx("Session Continuity")}
value={continuity}
options={CONTINUITY_OPTIONS}
onChange={(v) => setContinuity(v)}
/>
</div>
</div>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-disable-after-input">
<T>Disable After Date (optional)</T>
</label>
<Input
id="automation-disable-after-input"
type="date"
value={disableAfterStr}
onChange={(e) => setDisableAfterStr(e.target.value)}
/>
</div>
{agentSettings.newTaskApprovals === "ask" && permissions !== "default" && (
<div className={styles.fieldHint}>
<T>
Your interactive New Tasks setting is Asking for approval, so scheduled turns are capped to ask
before edits and commands.
</T>
</div>
)}
{permissions === "allowAll" && workspaceMode === "project" && isolation === "local" && (
<div className={styles.fieldHint} style={{ color: "var(--warning)" }}>
<T>
Warning: Autonomous mode on a local checkout can modify your working files directly. Prefer an
isolated Git worktree.
</T>
</div>
)}
{workspaceMode === "project" && isolation === "worktree" && continuity === "newTask" && (
<Checkbox
checked={autoCleanWorktree}
onChange={setAutoCleanWorktree}
label="Auto-delete temporary worktree when the run makes zero file changes"
/>
)}
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<span className={styles.fieldLabel}>
<T>Missed Schedule Policy</T>
</span>
<Select
aria-label={tx("Missed Schedule Policy")}
value={misfirePolicy}
options={MISFIRE_OPTIONS}
onChange={setMisfirePolicy}
/>
</div>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-max-runs-input">
<T>Stop After Runs (optional)</T>
</label>
<Input
id="automation-max-runs-input"
type="number"
min={1}
value={maxRunsStr}
onChange={(e) => setMaxRunsStr(e.target.value)}
placeholder="50"
/>
</div>
</div>
<div className={styles.fieldRow}>
<div className={styles.fieldGroup}>
<label className={styles.fieldLabel} htmlFor="automation-disable-after-input">
<T>Disable After Date (optional)</T>
</label>
<Input
id="automation-disable-after-input"
type="date"
value={disableAfterStr}
onChange={(e) => setDisableAfterStr(e.target.value)}
/>
</div>
</div>
</div>
)}
</div>
</div>
</Dialog>
+272 -148
Переглянути файл
@@ -1,61 +1,67 @@
/* Agent Automations editor tab, creation dialog, and status widgets (Islands style). */
.editor {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
background: var(--bg-app);
overflow-y: auto;
background: var(--bg-editor);
color: var(--fg);
font-size: var(--fs-ui);
}
.column {
display: flex;
flex-direction: column;
flex: 1;
width: 100%;
max-width: 820px;
margin: 0 auto;
padding: 20px 28px 24px;
box-sizing: border-box;
min-height: 0;
}
.header {
display: flex;
align-items: center;
align-items: flex-start;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
padding: 12px 18px 10px;
border-bottom: 1px solid var(--border);
background: var(--bg-elev);
gap: var(--space-3);
padding-bottom: 14px;
}
.headerMain {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
flex-direction: column;
gap: var(--space-1);
min-width: 0;
}
.headerTitle {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
margin: 0;
font-size: 14px;
font-size: 16px;
font-weight: 600;
letter-spacing: -0.01em;
line-height: 1.3;
color: var(--fg-strong);
}
.headerActions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
flex-shrink: 0;
gap: var(--space-1);
}
.hostPill {
.hostMeta {
display: inline-flex;
align-items: center;
gap: var(--space-1);
height: 22px;
padding: 0 8px;
border-radius: var(--radius-small);
background: var(--bg-floating-toolbar);
box-shadow: inset 0 0 0 1px var(--border);
color: var(--fg-secondary);
font-size: var(--fs-tiny);
white-space: nowrap;
flex-wrap: wrap;
gap: var(--space-1-5);
color: var(--fg-muted);
font-size: var(--fs-small);
line-height: 1.4;
}
.statusDot {
@@ -78,35 +84,42 @@
background: var(--danger);
}
.tabBar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 14px;
border-bottom: 1px solid var(--border);
background: var(--bg-elev);
gap: var(--space-2);
}
.filterRow {
/* Compact navigation tabs and inline search/filter on one hairline row. */
.navRow {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--space-2);
padding: 10px 18px 6px;
padding-bottom: 8px;
border-bottom: 1px solid var(--border);
}
.navControls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
margin-left: auto;
}
.searchWrap {
flex: 1;
min-width: 180px;
max-width: 360px;
width: 220px;
max-width: 100%;
min-width: 150px;
}
.filterRight {
display: flex;
.tabBadge {
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
justify-content: center;
min-width: 16px;
height: 16px;
padding: 0 3px;
color: var(--fg-muted);
font-size: var(--fs-tiny);
font-variant-numeric: tabular-nums;
line-height: 1;
}
.bannerWarn {
@@ -114,10 +127,10 @@
align-items: center;
justify-content: space-between;
gap: var(--space-2);
margin: 10px 18px 0;
margin-bottom: 12px;
padding: 8px 12px;
border-radius: var(--radius-control);
background: var(--bg-floating-toolbar);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--warning);
color: var(--fg-strong);
font-size: var(--fs-small);
@@ -132,19 +145,19 @@
.body {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 8px 18px 20px;
display: flex;
flex-direction: column;
gap: var(--space-2);
gap: var(--space-3);
padding: 16px 0 20px;
min-height: 0;
}
/* Framed list with hairline dividers, matching Settings > Agents > Skills. */
.listFrame {
display: flex;
flex-direction: column;
border-radius: var(--radius-control);
background: var(--bg-elev);
background: var(--bg-editor);
box-shadow: inset 0 0 0 1px var(--border);
overflow: hidden;
}
@@ -167,7 +180,7 @@
.rowFocused {
background: var(--bg-hover);
box-shadow: inset 2px 0 0 var(--link);
box-shadow: inset 2px 0 0 var(--accent);
}
.rowLeft {
@@ -201,6 +214,12 @@
text-overflow: ellipsis;
}
.rowSchedule {
color: var(--fg-secondary);
font-size: var(--fs-small);
white-space: nowrap;
}
.rowPrompt {
color: var(--fg-muted);
font-size: var(--fs-small);
@@ -215,7 +234,7 @@
flex-wrap: wrap;
gap: var(--space-1-5);
font-size: var(--fs-tiny);
color: var(--fg-secondary);
color: var(--fg-subtle);
}
.tag {
@@ -225,7 +244,7 @@
height: 18px;
padding: 0 6px;
border-radius: var(--radius-small);
background: var(--bg-floating-toolbar);
background: var(--bg-elev);
color: var(--fg-secondary);
font-size: var(--fs-tiny);
white-space: nowrap;
@@ -236,7 +255,7 @@
}
.tagUnread {
background: var(--link);
background: var(--accent);
color: #fff;
font-weight: 600;
}
@@ -262,15 +281,18 @@
flex-shrink: 0;
}
.emptyCard {
/* Open, cardless empty state with a single-column hairline template list. */
.emptySection {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--space-3);
padding: 18px;
border-radius: var(--radius-control);
background: var(--bg-elev);
box-shadow: inset 0 0 0 1px var(--border);
padding-top: 4px;
}
.emptyHeader {
display: flex;
flex-direction: column;
gap: var(--space-1);
}
.emptyTitle {
@@ -284,40 +306,42 @@
margin: 0;
color: var(--fg-muted);
font-size: var(--fs-small);
line-height: 1.45;
max-width: 620px;
line-height: 1.5;
max-width: 600px;
}
.templatesGrid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
gap: var(--space-2);
width: 100%;
}
.templateBtn {
.templateRow {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--space-1);
align-items: center;
justify-content: space-between;
gap: var(--space-3);
width: 100%;
padding: 10px 12px;
border-radius: var(--radius-control);
border: none;
background: var(--bg-app);
box-shadow: inset 0 0 0 1px var(--border);
border: 0;
background: transparent;
color: var(--fg);
font: inherit;
text-align: left;
cursor: pointer;
}
.templateBtn:hover {
.templateRow + .templateRow {
box-shadow: inset 0 1px 0 var(--border);
}
.templateRow:hover {
background: var(--bg-hover);
}
.templateMain {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
}
.templateTitle {
font-weight: 600;
font-size: var(--fs-small);
font-weight: 500;
font-size: var(--fs-ui);
color: var(--fg-strong);
}
@@ -326,12 +350,28 @@
color: var(--fg-muted);
}
/* Dialog form */
.templatePlus {
flex-shrink: 0;
color: var(--fg-muted);
}
.footerBar {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding-top: 12px;
border-top: 1px solid var(--border);
color: var(--fg-secondary);
font-size: var(--fs-small);
}
/* Dialog form (aligned to Dialog's 16px titlebar / footer insets). */
.dialogForm {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 4px 0;
padding: 4px 16px 12px;
font-size: var(--fs-ui);
}
@@ -339,58 +379,109 @@
display: flex;
flex-direction: column;
gap: var(--space-1);
min-width: 0;
}
.fieldRow {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: var(--space-3);
}
.workspaceRow {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: var(--space-2);
}
.fieldLabel {
font-size: var(--fs-small);
font-weight: 600;
color: var(--fg-strong);
font-weight: 500;
color: var(--fg-secondary);
}
.fieldHint {
font-size: var(--fs-tiny);
color: var(--fg-muted);
line-height: 1.4;
line-height: 1.45;
}
/* Unified prompt surface matching the HomeEditor composer frame. */
.promptBox {
display: flex;
flex-direction: column;
border-radius: var(--radius-control);
background: var(--bg-field, var(--bg-app));
box-shadow: inset 0 0 0 1px var(--border-button);
transition: box-shadow var(--dur-fast) var(--ease);
}
.promptBox:focus-within {
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
}
.promptTextarea {
width: 100%;
min-height: 92px;
padding: 8px 10px;
border-radius: var(--radius-control);
border: 1px solid var(--border);
background: var(--bg-app);
min-height: 84px;
padding: 8px 10px 6px;
border: 0;
background: transparent;
color: var(--fg-strong);
font-family: var(--font-ui, inherit);
font-size: var(--fs-ui);
line-height: 1.45;
line-height: 1.5;
resize: vertical;
box-sizing: border-box;
}
.promptTextarea:focus {
outline: none;
border-color: var(--link);
}
.pickerBar {
.promptTextarea::placeholder {
color: var(--fg-faint);
}
/* Standalone monospace textarea used in Import / Export markdown dialogs. */
.codeTextarea {
width: 100%;
min-height: 168px;
padding: 8px 10px;
border: 0;
border-radius: var(--radius-control);
background: var(--bg-field, var(--bg-app));
box-shadow: inset 0 0 0 1px var(--border-button);
color: var(--fg-strong);
font-family: var(--font-mono);
font-size: var(--fs-small);
line-height: 1.5;
resize: vertical;
box-sizing: border-box;
}
.codeTextarea:focus {
outline: none;
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
}
.promptBar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
gap: var(--space-1);
padding: 4px 6px;
border-top: 1px solid var(--border);
}
.weekdayRow {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1-5);
gap: var(--space-1);
}
.dayBtn {
@@ -398,30 +489,87 @@
min-width: 34px;
padding: 0 8px;
border-radius: var(--radius-small);
border: 1px solid var(--border);
background: var(--bg-app);
box-shadow: inset 0 0 0 1px var(--border-button);
background: var(--bg-field, var(--bg-app));
color: var(--fg-secondary);
font-size: var(--fs-tiny);
cursor: pointer;
}
.dayBtn:hover {
background: var(--bg-hover);
}
.dayBtnActive {
border-color: var(--link);
background: var(--bg-hover);
box-shadow: inset 0 0 0 1px var(--accent);
background: var(--bg-selected);
color: var(--fg-strong);
font-weight: 600;
font-weight: 500;
}
.previewBox {
.previewLine {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: var(--space-1);
font-size: var(--fs-tiny);
color: var(--fg-muted);
line-height: 1.4;
}
.previewLabel {
color: var(--fg-secondary);
font-weight: 500;
}
.previewError {
color: var(--danger);
}
.advancedSection {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
padding: 7px 10px;
border-radius: var(--radius-control);
background: var(--bg-floating-toolbar);
box-shadow: inset 0 0 0 1px var(--border);
font-size: var(--fs-tiny);
border-top: 1px solid var(--border);
padding-top: 8px;
}
.advancedToggle {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
width: 100%;
padding: 4px 2px;
border-radius: var(--radius-small);
color: var(--fg-secondary);
font-size: var(--fs-small);
font-weight: 500;
text-align: left;
}
.advancedToggle:hover {
color: var(--fg-strong);
}
.advancedTitle {
display: inline-flex;
align-items: center;
gap: var(--space-1);
}
.advancedSummary {
color: var(--fg-muted);
font-size: var(--fs-tiny);
font-weight: 400;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.advancedBody {
display: flex;
flex-direction: column;
gap: var(--space-3);
padding-top: 10px;
}
.errorBox {
@@ -436,45 +584,21 @@
font-size: var(--fs-small);
}
/* Sidebar hub row */
.hubBar {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-1-5);
padding: 4px 8px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.hubBtn {
display: flex;
align-items: center;
gap: var(--space-1-5);
flex: 1;
min-width: 0;
padding: 3px 6px;
border: none;
border-radius: var(--radius-small);
background: none;
color: var(--fg-strong);
font: inherit;
font-size: var(--fs-small);
text-align: left;
cursor: pointer;
}
.hubBtn:hover {
background: var(--bg-hover);
}
.hubMeta {
margin-left: auto;
/* Sidebar tool window header badge dot for unread/attention runs. */
.headerBadgeWrap {
position: relative;
display: inline-flex;
align-items: center;
gap: var(--space-1-5);
color: var(--fg-muted);
font-size: var(--fs-tiny);
}
.headerBadgeDot {
position: absolute;
top: 4px;
right: 4px;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
pointer-events: none;
}
/* Session provenance banner & schedule strip */
+405 -378
Переглянути файл
@@ -293,6 +293,35 @@ export function AutomationsEditor({
}
};
const { host } = snapshot;
const projectActiveSchedules = useMemo(
() => snapshot.automations.filter((a) => a.enabled && a.trigger.kind !== "manual").length,
[snapshot.automations],
);
const headerMoreMenu = (): MenuItem[] => [
{
kind: "item",
id: "import",
label: "Import .automation.md",
icon: "download",
disabled: untrustedProject,
run: () => setImportOpen(true),
},
...(projectActiveSchedules > 0
? [
{
kind: "item" as const,
id: "pause-all",
label: "Pause All",
icon: "pause",
disabled: untrustedProject,
run: () => void handlePauseAll(),
},
]
: []),
];
const automationMenu = (auto: AgentAutomation_Serialize): MenuItem[] => [
{
kind: "item",
@@ -340,394 +369,394 @@ export function AutomationsEditor({
},
];
const { host } = snapshot;
const projectActiveSchedules = useMemo(
() => snapshot.automations.filter((a) => a.enabled && a.trigger.kind !== "manual").length,
[snapshot.automations],
);
return (
<div className={styles.editor} data-testid="automations-editor">
<div className={styles.header}>
<div className={styles.headerMain}>
<h2 className={styles.headerTitle}>
<Icon name="clock" size={16} />
<T>Agent Automations</T>
</h2>
<span className={styles.hostPill} data-testid="scheduler-host-pill">
<span
className={clsx(styles.statusDot, host.activeSchedules > 0 && styles.statusDotOn)}
aria-hidden="true"
/>
<Icon name={host.remote ? "remote" : "server"} size={12} />
<span>{host.remote ? tx("Remote Daemon") : tx("Local Host")}</span>
<span>·</span>
<span>
{host.activeSchedules === 1 ? tx("1 active schedule") : tx`${host.activeSchedules} active schedules`}
</span>
{host.bootServiceRegistered && (
<>
<span>·</span>
<span>
<T>Auto-starts on login</T>
</span>
</>
)}
</span>
</div>
<div className={styles.headerActions}>
<Button size="small" icon="download" disabled={untrustedProject} onClick={() => setImportOpen(true)}>
<T>Import .automation.md</T>
</Button>
{projectActiveSchedules > 0 && (
<Button size="small" icon="pause" disabled={untrustedProject} onClick={() => void handlePauseAll()}>
<T>Pause All</T>
</Button>
)}
<IconButton
icon="settings"
title="Automation Settings"
onClick={() => void executeAction("file.settings", AUTOMATIONS_PAGE)}
/>
<Button
variant="primary"
size="small"
icon="plus"
disabled={untrustedProject}
onClick={() => openAutomationDialog()}
>
<T>New Automation</T>
</Button>
</div>
</div>
{loadError && (
<div className={styles.errorBox} style={{ margin: "10px 18px 0" }} role="alert">
<Icon name="error" size={14} />
<span>{loadError}</span>
</div>
)}
{host.bootServiceError && (
<div className={styles.errorBox} style={{ margin: "10px 18px 0" }} role="alert">
<Icon name="warning" size={14} />
<span>{host.bootServiceError}</span>
</div>
)}
{untrustedProject && (
<div className={styles.bannerWarn} role="status">
<div className={styles.bannerLeft}>
<Icon name="warning" size={14} />
<span>
<T>This project is untrusted. Workspace automations stay paused until you trust the project.</T>
<div className={styles.column}>
<header className={styles.header}>
<div className={styles.headerMain}>
<h2 className={styles.headerTitle}>
<T>Agent Automations</T>
</h2>
<span className={styles.hostMeta} data-testid="scheduler-host-pill">
<span
className={clsx(styles.statusDot, host.activeSchedules > 0 && styles.statusDotOn)}
aria-hidden="true"
/>
{host.remote && <Icon name="remote" size={12} />}
<span>{host.remote ? tx("Remote Daemon") : tx("Local Host")}</span>
<span>·</span>
<span>
{host.activeSchedules === 1 ? tx("1 active schedule") : tx`${host.activeSchedules} active schedules`}
</span>
{host.bootServiceRegistered && (
<>
<span>·</span>
<span>
<T>Auto-starts on login</T>
</span>
</>
)}
</span>
</div>
</div>
)}
<div className={styles.tabBar}>
<Tabs
activeId={activeTab}
onSelect={(id) => setAutomationsTab(id as "schedules" | "runs")}
items={[
{
id: "schedules",
label: <T>Schedules</T>,
text: "Schedules",
trailing: snapshot.automations.length ? <span>{snapshot.automations.length}</span> : undefined,
},
{
id: "runs",
label: <T>Run History</T>,
text: "Run History",
trailing:
host.unreadRuns > 0 ? (
<span className={clsx(styles.tag, styles.tagUnread)}>{host.unreadRuns}</span>
) : snapshot.runs.length ? (
<span>{snapshot.runs.length}</span>
<div className={styles.headerActions}>
<Button
variant="primary"
size="small"
icon="plus"
disabled={untrustedProject}
onClick={() => openAutomationDialog()}
>
<T>New Automation</T>
</Button>
<IconButton
icon="settings"
title="Automation Settings"
onClick={() => void executeAction("file.settings", AUTOMATIONS_PAGE)}
/>
<IconButton icon="more" title="Options" onClick={(e) => showContextMenu(e, headerMoreMenu())} />
</div>
</header>
{loadError && (
<div className={styles.errorBox} style={{ marginBottom: 12 }} role="alert">
<Icon name="error" size={14} />
<span>{loadError}</span>
</div>
)}
{host.bootServiceError && (
<div className={styles.errorBox} style={{ marginBottom: 12 }} role="alert">
<Icon name="warning" size={14} />
<span>{host.bootServiceError}</span>
</div>
)}
{untrustedProject && (
<div className={styles.bannerWarn} role="status">
<div className={styles.bannerLeft}>
<Icon name="warning" size={14} />
<span>
<T>This project is untrusted. Workspace automations stay paused until you trust the project.</T>
</span>
</div>
</div>
)}
<div className={styles.navRow}>
<Tabs
variant="compact"
activeId={activeTab}
onSelect={(id) => setAutomationsTab(id as "schedules" | "runs")}
items={[
{
id: "schedules",
label: <T>Schedules</T>,
text: "Schedules",
trailing: snapshot.automations.length ? (
<span className={styles.tabBadge}>{snapshot.automations.length}</span>
) : undefined,
},
]}
/>
</div>
<div className={styles.filterRow}>
<div className={styles.searchWrap}>
<SearchField
value={query}
onChange={setQuery}
clearable
placeholder={tx("Filter automations and runs")}
aria-label={tx("Filter automations and runs")}
},
{
id: "runs",
label: <T>Run History</T>,
text: "Run History",
trailing:
host.unreadRuns > 0 ? (
<span className={clsx(styles.tag, styles.tagUnread)}>{host.unreadRuns}</span>
) : snapshot.runs.length ? (
<span className={styles.tabBadge}>{snapshot.runs.length}</span>
) : undefined,
},
]}
/>
<div className={styles.navControls}>
<div className={styles.searchWrap}>
<SearchField
value={query}
onChange={setQuery}
clearable
placeholder={tx("Filter automations and runs")}
aria-label={tx("Filter automations and runs")}
/>
</div>
{activeTab === "runs" && (
<>
<Select
variant="ghost"
aria-label={tx("Run filter")}
value={runFilter}
options={[
{ value: "all", label: tx("All runs") },
{ value: "unread", label: tx("Unread only") },
{ value: "needsInput", label: tx("Waiting for input") },
]}
onChange={(v) => setRunFilter(v as "all" | "unread" | "needsInput")}
/>
{host.unreadRuns > 0 && (
<Button size="small" icon="check" onClick={() => void handleMarkAllRead()}>
<T>Mark All as Read</T>
</Button>
)}
</>
)}
</div>
</div>
{activeTab === "schedules" ? (
<div className={styles.filterRight}>
<div className={styles.body}>
{activeTab === "schedules" ? (
filteredAutomations.length === 0 ? (
<div className={styles.emptySection}>
<div className={styles.emptyHeader}>
<h3 className={styles.emptyTitle}>
{query ? <T>No matching automations</T> : <T>Automate recurring agent workflows</T>}
</h3>
{!query && (
<p className={styles.emptyDesc}>
<T>
Schedules run directly on your local host or remote daemon—even when editor windows are closed
or after an OS reboot—using isolated Git worktrees so your working tree stays clean.
</T>
</p>
)}
</div>
{!query && (
<div className={styles.listFrame}>
{STARTER_TEMPLATES.map((tpl) => (
<button
key={tpl.name}
type="button"
className={styles.templateRow}
onClick={() => openAutomationDialog({ prefillName: tpl.name, prefillPrompt: tpl.prompt })}
>
<span className={styles.templateMain}>
<span className={styles.templateTitle}>{tx(tpl.name)}</span>
<span className={styles.templateSub}>{tx(tpl.sub)}</span>
</span>
<Icon name="plus" size={14} className={styles.templatePlus} />
</button>
))}
</div>
)}
</div>
) : (
<div className={styles.listFrame}>
{filteredAutomations.map((auto) => (
<div
key={auto.id}
data-testid={`automation-row-${auto.id}`}
className={clsx(styles.row, focusAutomationId === auto.id && styles.rowFocused)}
onContextMenu={(e) => showContextMenu(e, automationMenu(auto))}
>
<div className={styles.rowLeft}>
<span
className={clsx(styles.statusDot, auto.enabled && styles.statusDotOn)}
style={{ marginTop: 6 }}
title={auto.enabled ? tx("Active") : tx("Paused")}
/>
<Icon name={providerIcon(auto.provider)} size={16} label={providerName(auto.provider)} />
<div className={styles.rowContent}>
<div className={styles.rowTitleLine}>
<span className={styles.rowTitle}>{auto.name}</span>
<span className={styles.rowSchedule}>{describeTrigger(auto.trigger, tx)}</span>
{!auto.enabled && (
<span className={styles.tag}>
<T>Paused</T>
</span>
)}
{auto.unreadRuns > 0 && (
<span className={clsx(styles.tag, styles.tagUnread)}>
{auto.unreadRuns === 1 ? tx("1 unread") : tx`${auto.unreadRuns} unread`}
</span>
)}
</div>
<div className={styles.rowPrompt}>{auto.prompt.text}</div>
{auto.pausedReason && (
<div className={styles.fieldHint} style={{ color: "var(--warning)" }}>
{auto.pausedReason}
</div>
)}
<div className={styles.rowMeta}>
<span>{providerName(auto.provider)}</span>
<span>·</span>
<span>
{auto.workspace.kind === "chatOnly"
? tx("Chat only")
: auto.workspace.isolation === "worktree"
? `${basename(auto.workspace.root)} · ${tx("Worktree")}`
: `${basename(auto.workspace.root)} · ${tx("Local checkout")}`}
</span>
<span>·</span>
<span>{auto.continuity === "sameTask" ? tx("Rolling session") : tx("Fresh session")}</span>
{auto.enabled && auto.nextRunMs ? (
<>
<span>·</span>
<span>
<T>Next:</T> {formatShortTimestamp(auto.nextRunMs)}
</span>
</>
) : null}
{auto.maxRuns ? (
<>
<span>·</span>
<span>
{auto.runCount}/{auto.maxRuns} <T>runs</T>
</span>
</>
) : null}
</div>
</div>
</div>
<div className={styles.rowActions}>
<Button
size="small"
icon="run"
disabled={busyId === auto.id || untrustedProject}
onClick={() => void handleRunNow(auto)}
>
<T>Run Now</T>
</Button>
<IconButton
icon={auto.enabled ? "pause" : "resume"}
title={auto.enabled ? "Pause Schedule" : "Resume Schedule"}
disabled={busyId === auto.id || untrustedProject}
onClick={() => void handleToggleEnabled(auto)}
/>
<IconButton
icon="edit"
title="Edit Automation"
disabled={untrustedProject}
onClick={() => openAutomationDialog({ editing: auto })}
/>
<IconButton
icon="more"
title="More Actions"
disabled={untrustedProject}
onClick={(e) => showContextMenu(e, automationMenu(auto))}
/>
</div>
</div>
))}
</div>
)
) : filteredRuns.length === 0 ? (
<div className={styles.emptySection}>
<div className={styles.emptyHeader}>
<h3 className={styles.emptyTitle}>
<T>No automation runs yet</T>
</h3>
<p className={styles.emptyDesc}>
<T>
Scheduled and manual runs appear here with diff summaries, approval badges, and one-click session
transcripts.
</T>
</p>
</div>
</div>
) : (
<div className={styles.listFrame}>
{filteredRuns.map((run) => (
<div
key={run.id}
data-testid={`automation-run-${run.id}`}
className={styles.row}
onClick={() => void handleOpenRun(run)}
>
<div className={styles.rowLeft}>
<RunStatusGlyph status={run.status} />
<div className={styles.rowContent}>
<div className={styles.rowTitleLine}>
<span className={styles.rowTitle}>
{run.automationName} <span className={styles.mono}>#{run.runNumber}</span>
</span>
{run.status === "needsInput" && (
<span className={clsx(styles.tag, styles.tagWarn)}>
<Icon name="warning" size={11} />
<T>Needs approval</T>
</span>
)}
{run.unread && (
<span className={clsx(styles.tag, styles.tagUnread)}>
<T>Unread</T>
</span>
)}
{run.origin.kind === "scheduled" && run.origin.catchUp && (
<span className={styles.tag}>
<T>Catch-up</T>
</span>
)}
</div>
{run.error && (
<div className={styles.rowPrompt} style={{ color: "var(--danger)" }}>
{run.error}
</div>
)}
<div className={styles.rowMeta}>
<span>{formatShortTimestamp(run.startedMs)}</span>
<span>·</span>
<span>{run.origin.kind === "manual" ? tx("Manual run") : tx("Scheduled run")}</span>
{run.branch && (
<>
<span>·</span>
<span className={styles.mono}>{run.branch}</span>
</>
)}
{(run.added > 0 || run.removed > 0) && (
<>
<span>·</span>
<span className={styles.diffAdded}>+{run.added}</span>
<span className={styles.diffRemoved}>-{run.removed}</span>
</>
)}
{run.worktreeCleaned && (
<>
<span>·</span>
<span>
<T>Zero-diff worktree cleaned</T>
</span>
</>
)}
</div>
</div>
</div>
<div className={styles.rowActions} onClick={(e) => e.stopPropagation()}>
{run.unread && (
<IconButton
icon="check"
title="Mark as Read"
onClick={() => void backend.markRead(run.id, null).then(() => refreshAutomations(backend))}
/>
)}
{run.taskId && (
<Button size="small" onClick={() => void handleOpenRun(run)}>
<T>Open Session</T>
</Button>
)}
</div>
</div>
))}
{snapshot.runsNextCursor != null && (
<div className={styles.row} style={{ justifyContent: "center" }}>
<Button size="small" onClick={() => void loadMoreRuns(backend)}>
<T>Show more</T>
</Button>
</div>
)}
</div>
)}
</div>
{activeTab === "schedules" && (
<div className={styles.footerBar}>
<Checkbox
checked={autoStartEnabled}
onChange={(v) => void handleToggleAutoStart(v)}
label="Keep automations running when OpenIDEA is closed"
/>
</div>
) : (
<div className={styles.filterRight}>
<Select
aria-label={tx("Run filter")}
value={runFilter}
options={[
{ value: "all", label: tx("All runs") },
{ value: "unread", label: tx("Unread only") },
{ value: "needsInput", label: tx("Waiting for input") },
]}
onChange={(v) => setRunFilter(v as "all" | "unread" | "needsInput")}
/>
{host.unreadRuns > 0 && (
<Button size="small" icon="check" onClick={() => void handleMarkAllRead()}>
<T>Mark All as Read</T>
</Button>
)}
</div>
)}
</div>
<div className={styles.body}>
{activeTab === "schedules" ? (
filteredAutomations.length === 0 ? (
<div className={styles.emptyCard}>
<h3 className={styles.emptyTitle}>
{query ? <T>No matching automations</T> : <T>Automate recurring agent workflows</T>}
</h3>
{!query && (
<>
<p className={styles.emptyDesc}>
<T>
Schedules run directly on your local host or remote daemon—even when editor windows are closed or
after an OS reboot—using isolated Git worktrees so your working tree stays clean.
</T>
</p>
<div className={styles.templatesGrid}>
{STARTER_TEMPLATES.map((tpl) => (
<button
key={tpl.name}
type="button"
className={styles.templateBtn}
onClick={() => openAutomationDialog({ prefillName: tpl.name, prefillPrompt: tpl.prompt })}
>
<span className={styles.templateTitle}>{tx(tpl.name)}</span>
<span className={styles.templateSub}>{tx(tpl.sub)}</span>
</button>
))}
</div>
</>
)}
</div>
) : (
<div className={styles.listFrame}>
{filteredAutomations.map((auto) => (
<div
key={auto.id}
data-testid={`automation-row-${auto.id}`}
className={clsx(styles.row, focusAutomationId === auto.id && styles.rowFocused)}
onContextMenu={(e) => showContextMenu(e, automationMenu(auto))}
>
<div className={styles.rowLeft}>
<span
className={clsx(styles.statusDot, auto.enabled && styles.statusDotOn)}
style={{ marginTop: 6 }}
title={auto.enabled ? tx("Active") : tx("Paused")}
/>
<Icon name={providerIcon(auto.provider)} size={16} label={providerName(auto.provider)} />
<div className={styles.rowContent}>
<div className={styles.rowTitleLine}>
<span className={styles.rowTitle}>{auto.name}</span>
<span className={styles.tag}>{describeTrigger(auto.trigger, tx)}</span>
{!auto.enabled && (
<span className={styles.tag}>
<T>Paused</T>
</span>
)}
{auto.unreadRuns > 0 && (
<span className={clsx(styles.tag, styles.tagUnread)}>
{auto.unreadRuns === 1 ? tx("1 unread") : tx`${auto.unreadRuns} unread`}
</span>
)}
</div>
<div className={styles.rowPrompt}>{auto.prompt.text}</div>
{auto.pausedReason && (
<div className={styles.fieldHint} style={{ color: "var(--warning)" }}>
{auto.pausedReason}
</div>
)}
<div className={styles.rowMeta}>
<span>{providerName(auto.provider)}</span>
<span>·</span>
<span>
{auto.workspace.kind === "chatOnly"
? tx("Chat only")
: auto.workspace.isolation === "worktree"
? `${basename(auto.workspace.root)} · ${tx("Worktree")}`
: `${basename(auto.workspace.root)} · ${tx("Local checkout")}`}
</span>
<span>·</span>
<span>{auto.continuity === "sameTask" ? tx("Rolling session") : tx("Fresh session")}</span>
{auto.enabled && auto.nextRunMs ? (
<>
<span>·</span>
<span>
<T>Next:</T> {formatShortTimestamp(auto.nextRunMs)}
</span>
</>
) : null}
{auto.maxRuns ? (
<>
<span>·</span>
<span>
{auto.runCount}/{auto.maxRuns} <T>runs</T>
</span>
</>
) : null}
</div>
</div>
</div>
<div className={styles.rowActions}>
<Button
size="small"
icon="run"
disabled={busyId === auto.id || untrustedProject}
onClick={() => void handleRunNow(auto)}
>
<T>Run Now</T>
</Button>
<IconButton
icon={auto.enabled ? "pause" : "resume"}
title={auto.enabled ? "Pause Schedule" : "Resume Schedule"}
disabled={busyId === auto.id || untrustedProject}
onClick={() => void handleToggleEnabled(auto)}
/>
<IconButton
icon="edit"
title="Edit Automation"
disabled={untrustedProject}
onClick={() => openAutomationDialog({ editing: auto })}
/>
<IconButton
icon="more"
title="More Actions"
disabled={untrustedProject}
onClick={(e) => showContextMenu(e, automationMenu(auto))}
/>
</div>
</div>
))}
</div>
)
) : filteredRuns.length === 0 ? (
<div className={styles.emptyCard}>
<h3 className={styles.emptyTitle}>
<T>No automation runs yet</T>
</h3>
<p className={styles.emptyDesc}>
<T>
Scheduled and manual runs appear here with diff summaries, approval badges, and one-click session
transcripts.
</T>
</p>
</div>
) : (
<div className={styles.listFrame}>
{filteredRuns.map((run) => (
<div
key={run.id}
data-testid={`automation-run-${run.id}`}
className={styles.row}
onClick={() => void handleOpenRun(run)}
style={{ cursor: run.taskId ? "pointer" : "default" }}
>
<div className={styles.rowLeft}>
<RunStatusGlyph status={run.status} />
<div className={styles.rowContent}>
<div className={styles.rowTitleLine}>
<span className={styles.rowTitle}>
{run.automationName} <span className={styles.mono}>#{run.runNumber}</span>
</span>
{run.status === "needsInput" && (
<span className={clsx(styles.tag, styles.tagWarn)}>
<Icon name="warning" size={11} />
<T>Needs approval</T>
</span>
)}
{run.unread && (
<span className={clsx(styles.tag, styles.tagUnread)}>
<T>Unread</T>
</span>
)}
{run.origin.kind === "scheduled" && run.origin.catchUp && (
<span className={styles.tag}>
<T>Catch-up</T>
</span>
)}
</div>
{run.error && (
<div className={styles.rowPrompt} style={{ color: "var(--danger)" }}>
{run.error}
</div>
)}
<div className={styles.rowMeta}>
<span>{formatShortTimestamp(run.startedMs)}</span>
<span>·</span>
<span>{run.origin.kind === "manual" ? tx("Manual run") : tx("Scheduled run")}</span>
{run.branch && (
<>
<span>·</span>
<span className={styles.mono}>{run.branch}</span>
</>
)}
{(run.added > 0 || run.removed > 0) && (
<>
<span>·</span>
<span className={styles.diffAdded}>+{run.added}</span>
<span className={styles.diffRemoved}>-{run.removed}</span>
</>
)}
{run.worktreeCleaned && (
<>
<span>·</span>
<span>
<T>Zero-diff worktree cleaned</T>
</span>
</>
)}
</div>
</div>
</div>
<div className={styles.rowActions} onClick={(e) => e.stopPropagation()}>
{run.unread && (
<IconButton
icon="check"
title="Mark as Read"
onClick={() => void backend.markRead(run.id, null).then(() => refreshAutomations(backend))}
/>
)}
{run.taskId && (
<Button size="small" onClick={() => void handleOpenRun(run)}>
<T>Open Session</T>
</Button>
)}
</div>
</div>
))}
{snapshot.runsNextCursor != null && (
<div className={styles.row} style={{ justifyContent: "center" }}>
<Button size="small" onClick={() => void loadMoreRuns(backend)}>
<T>Show more</T>
</Button>
</div>
)}
</div>
)}
</div>
@@ -770,8 +799,7 @@ export function AutomationsEditor({
</span>
<textarea
aria-label={tx("Automation Markdown")}
className={styles.promptTextarea}
style={{ minHeight: 160, fontFamily: "var(--font-mono)" }}
className={styles.codeTextarea}
value={importText}
onChange={(e) => setImportText(e.target.value)}
placeholder={
@@ -802,8 +830,7 @@ export function AutomationsEditor({
<textarea
readOnly
aria-label={tx("Exported Automation Markdown")}
className={styles.promptTextarea}
style={{ minHeight: 180, fontFamily: "var(--font-mono)" }}
className={styles.codeTextarea}
value={exportState?.markdown ?? ""}
/>
</div>
+62
Переглянути файл
@@ -32,6 +32,7 @@ import { isRemoteWindow } from "@/platform/remote";
import { isMacHost, registerKeyClaim } from "@/platform/keymap";
import { isVirtualUri } from "@/platform/virtualDocs";
import { copySourceOf } from "@/platform/clipboardSource";
import { readClipboardText } from "@/platform/clipboard";
import { blobLink, blobPathCandidates, isRemoteOf, markdownLink, pastedUrl } from "./composerLinks";
import {
EDITOR_TAB_MIME,
@@ -53,6 +54,7 @@ import {
listNavigate,
fileIconName,
registerDropTarget,
showContextMenu,
} from "@/ui";
import {
IMAGE_EXTENSIONS,
@@ -295,6 +297,7 @@ export function Composer(props: ComposerProps) {
// Late-bound handlers: the editor is created once per draft, the props change every render.
const onKeyDownRef = useRef<(e: KeyboardEvent, view: EditorView) => boolean>(() => false);
const onPasteRef = useRef<(e: ClipboardEvent, view: EditorView) => boolean>(() => false);
const onContextMenuRef = useRef<(e: MouseEvent, view: EditorView) => boolean>(() => false);
const onUpdateRef = useRef<(u: ViewUpdate) => void>(() => {});
useLayoutEffect(() => {
@@ -319,6 +322,7 @@ export function Composer(props: ComposerProps) {
EditorView.domEventHandlers({
keydown: (e, v) => onKeyDownRef.current(e, v),
paste: (e, v) => onPasteRef.current(e, v),
contextmenu: (e, v) => onContextMenuRef.current(e, v),
}),
),
referenceExtensions(),
@@ -1106,6 +1110,63 @@ export function Composer(props: ComposerProps) {
return false;
};
// Menu actions have no native paste event, so use the same transformations explicitly.
const onContextMenu = (e: MouseEvent, view: EditorView): boolean => {
const hasSelection = !view.state.selection.main.empty;
showContextMenu(e, [
...(hasSelection
? [
{
label: "Cut",
icon: "cut",
run: () => {
view.focus();
document.execCommand("cut");
},
},
{
label: "Copy",
icon: "copy",
run: () => {
view.focus();
document.execCommand("copy");
},
},
]
: []),
{
label: "Paste",
icon: "paste",
run: () =>
void (async () => {
try {
const plain = await readClipboardText();
if (!view.dom.isConnected) return;
if (plain) {
if (
!pasteCopied(plain, view) &&
!pasteLink(plain, view) &&
!pastePath(plain, view) &&
!pasteLong(plain, view)
) {
view.dispatch(view.state.replaceSelection(plain), { userEvent: "input.paste", scrollIntoView: true });
}
view.focus();
} else if (isTauri()) {
await pasteClipboardImage();
} else {
view.focus();
document.execCommand("paste");
}
} catch (error) {
notifications().notify({ level: "error", title: tx("Cannot paste"), body: String(error) });
}
})(),
},
]);
return true;
};
// Files dropped from the OS onto the box: images are inlined when they can be, other files
// referenced, or attached by path when outside the project.
useEffect(() => {
@@ -1284,6 +1345,7 @@ export function Composer(props: ComposerProps) {
useLayoutEffect(() => {
onUpdateRef.current = onUpdate;
onPasteRef.current = onPaste;
onContextMenuRef.current = onContextMenu;
onKeyDownRef.current = onKeyDown;
});
+21 -1
Переглянути файл
@@ -6,7 +6,7 @@ import { trackEditorCopies } from "./references";
import userEvent from "@testing-library/user-event";
import { caretOf, setCaret, textOf, typeChars, typeIn } from "./composerTesting";
import chipStyles from "./ReferenceChip.module.css";
import { FILES_DRAG, dragSession } from "@/ui";
import { FILES_DRAG, dragSession, useContextMenuStore } from "@/ui";
import { EDITOR_TAB_MIME, provideEditorService, type EditorService } from "@/workbench/contributions";
import { useProject } from "@/platform/project";
@@ -97,6 +97,26 @@ beforeEach(() => {
);
});
// Menu paste must take the same path conversion as a keyboard paste.
it("pastes a project path from the context menu", async () => {
const box = renderComposer();
vi.stubGlobal("navigator", { ...navigator, clipboard: { readText: vi.fn().mockResolvedValue("/p/src/a.ts:3-5") } });
try {
fireEvent.contextMenu(box);
const item = useContextMenuStore
.getState()
.menu?.items.find((entry) => "label" in entry && entry.label === "Paste");
expect(item && "run" in item && item.run).toBeTruthy();
await act(async () => {
if (item && "run" in item) item.run?.();
});
expect(textOf(box)).toContain("@src/a.ts:3-5");
} finally {
vi.unstubAllGlobals();
useContextMenuStore.setState({ menu: null });
}
});
describe("Composer dropped paths", () => {
function drop(box: HTMLElement, payload: string) {
const restore = document.elementFromPoint;
+4
Переглянути файл
@@ -233,6 +233,8 @@ export function interruptionBannerText(reason: InterruptionReason, wasWaitingFor
return "Interrupted when the OpenIDEA backend stopped.";
case "unexpectedExit":
return "Interrupted when OpenIDEA exited unexpectedly.";
case "cursorCapacity":
return "Cursor is still at capacity. Automatic retries have stopped.";
case "networkTimeout":
return "Paused after the network retry window expired.";
}
@@ -252,6 +254,8 @@ export function recoveryDividerLabel(reason: InterruptionReason): string {
return "Resumed after backend stop";
case "unexpectedExit":
return "Resumed after unexpected exit";
case "cursorCapacity":
return "Retry after Cursor capacity limit";
case "networkTimeout":
return "Resumed after network drop";
}
+33
Переглянути файл
@@ -386,6 +386,39 @@ describe("inline Interrupted banner, Waiting for network banner, and RecoveryTur
await vi.waitFor(() => expect(backend.cancel).toHaveBeenCalledWith("n1"));
});
it("shows the retry number during backoff and offers Retry once Cursor is still at capacity", async () => {
const task = makeTask("cursor-retry", {
provider: "cursor",
status: "running",
retry: { attempt: 2, maxRetries: 3, retryAtMs: Date.now() + 15_000, error: null },
});
const view = render(<WorkingRow task={task} entries={[]} subagent={null} />);
expect(screen.getByText(/retrying in .*s \(attempt 2\/3\)/)).toBeVisible();
const paused = {
...task,
status: "ready" as const,
retry: null,
interrupted: { reason: "cursorCapacity" as const, atMs: Date.now() },
};
useAgents.setState({ tasks: new Map([[paused.id, paused]]) });
view.rerender(
<SessionComposer
task={paused}
focusRequest={0}
focusRoot={{ current: null }}
entries={[]}
head={null}
changes={null}
commits={[]}
onOpenChanges={() => {}}
onOpenSubagent={() => {}}
/>,
);
expect(screen.getByText("Cursor is still at capacity. Automatic retries have stopped.")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await vi.waitFor(() => expect(backend.resumeTask).toHaveBeenCalledWith(paused.id));
});
it("renders synthetic recovery User entries as a compact separator pill instead of a chat bubble", () => {
const t = makeTask("m1");
const drafts = { current: new Map() };
+2 -2
Переглянути файл
@@ -122,7 +122,7 @@ function InterruptedBanner({ task }: { task: AgentTask }) {
<span className={styles.bannerMeta}>{age(intr.atMs ?? 0)}</span>
</span>
<div className={styles.bannerActions}>
<RecoveryWindowPicker task={task} />
{intr.reason !== "cursorCapacity" && <RecoveryWindowPicker task={task} />}
<Button
size="small"
variant="primary"
@@ -141,7 +141,7 @@ function InterruptedBanner({ task }: { task: AgentTask }) {
.finally(() => setResuming(false));
}}
>
<T>Resume</T>
{intr.reason === "cursorCapacity" ? <T>Retry</T> : <T>Resume</T>}
</Button>
<IconButton
icon="close"
+3 -2
Переглянути файл
@@ -36,11 +36,12 @@ describe("clampSelectionToRow", () => {
expect(selection.toString()).toBe("Last");
});
it("collapses a selection made entirely outside the row", () => {
it("leaves a selection moved entirely outside the row in place", () => {
const { reply, next } = conversation();
const selection = document.getSelection()!;
selection.setBaseAndExtent(next, 0, next, 4);
clampSelectionToRow(selection, reply);
expect(selection.isCollapsed).toBe(true);
expect(selection.toString()).toBe("Next");
expect(selection.anchorNode).toBe(next);
});
});
+3 -5
Переглянути файл
@@ -13,11 +13,9 @@ export function clampSelectionToRow(selection: Selection | null, row: Element) {
const first = texts[0];
const last = texts.at(-1);
if (!first || !last) return;
if (!startInside && !endInside) {
// The whole selection went past the row: none of the row's text is in it.
selection.collapse(last, last.length);
return;
}
// A deferred multi-click handler can run after the selection moved elsewhere. Moving it
// back to this row would also make the browser scroll to the stale selection.
if (!startInside && !endInside) return;
const [startNode, startOffset] = startInside ? [range.startContainer, range.startOffset] : [first, 0];
const [endNode, endOffset] = endInside ? [range.endContainer, range.endOffset] : [last, last.length];
const backward = selection.anchorNode === range.endContainer && selection.anchorOffset === range.endOffset;
+2 -1
Переглянути файл
@@ -352,12 +352,13 @@ function UserMessage({
const [editWidth, setEditWidth] = useState<number | null>(null);
const bubbleRef = useRef<HTMLDivElement>(null);
if (entry.recovery) {
const attempt = entry.retryAttempt;
return (
<div className={styles.recoveryDivider} role="separator">
<span className={styles.recoveryRule} aria-hidden="true" />
<span className={styles.recoveryPill}>
<Icon name="agent-resume" size={12} />
<span>{tx(recoveryDividerLabel(entry.recovery))}</span>
<span>{attempt != null ? tx`Retry ${attempt}` : tx(recoveryDividerLabel(entry.recovery))}</span>
<MessageTime sentMs={entry.sentMs ?? null} doneMs={null} />
</span>
<span className={styles.recoveryRule} aria-hidden="true" />
+19 -2
Переглянути файл
@@ -2,6 +2,7 @@ import type { AgentEntry, AgentTask } from "@/bindings";
import { useTx } from "@/platform/i18n";
import { basename } from "@/platform/project";
import { Icon, IconButton, Spinner, T } from "@/ui";
import { AnsiStream, spanStyle } from "@/ui/ansi";
import clsx from "clsx";
import { memo, useLayoutEffect } from "react";
import { AgentReply } from "../AgentReply";
@@ -108,6 +109,16 @@ export function pathInTitle(title: string, path: string): { from: number; to: nu
return { from, to: at + name.length + (end < 0 ? rest.length : end) };
}
function ToolOutput({ text }: { text: string }) {
if (!text.includes("\x1b")) return text;
return new AnsiStream().parse(text).map((span, index) => (
// oxlint-disable-next-line react/no-array-index-key -- ANSI spans follow their order in the output.
<span key={index} style={spanStyle(span)}>
{span.text}
</span>
));
}
export const ToolEntry = memo(function ToolEntry({
task,
entry,
@@ -240,10 +251,16 @@ export const ToolEntry = memo(function ToolEntry({
<pre className={styles.terminalCommand}>
<span className={styles.prompt}>$</span> {commandText}
</pre>
{run?.output && <pre className={styles.terminalOutput}>{run.output}</pre>}
{run?.output && (
<pre className={styles.terminalOutput}>
<ToolOutput text={run.output} />
</pre>
)}
</div>
) : (
<pre className={styles.output}>{entry.output}</pre>
<pre className={styles.output}>
<ToolOutput text={entry.output} />
</pre>
)}
</Fold>
</div>
+10
Переглянути файл
@@ -1272,6 +1272,16 @@ describe("scrolling", () => {
});
describe("tool calls", () => {
it.each(["pnpm dev:app", null])("renders ANSI diagnostics with command %s", (command) => {
const output = "\x1b[1m\x1b[33mwarning\x1b[0m: 未使用的字段\n\x1b[94m12 |\x1b[0m authors";
const entry = tool("cargo", { kind: "execute", status: "running", command, output });
useAgents.setState({ entries: new Map([["A", [entry]]]) });
render(<SessionEditor input={input("A")} />);
const warning = screen.getByText("warning");
expect(warning.style.color).toBe("var(--ansi-yellow)");
expect(warning.closest("pre")?.textContent).toBe("warning: 未使用的字段\n12 | authors");
});
it.each(["pending", "running"] as const)("keeps %s tools in their run, named on its summary", async (status) => {
backend.entries.set("A", [tool("done one"), tool("done two"), tool("live", { status, output: "Reading files…" })]);
useAgents.setState({ entries: new Map(backend.entries) });
+6
Переглянути файл
@@ -83,3 +83,9 @@
-webkit-user-select: text;
user-select: text;
}
/* Some server has a newer version (Update in its row). */
.updateBadge {
margin-left: 4px;
color: var(--accent);
}
+28 -1
Переглянути файл
@@ -3,6 +3,7 @@ import { fireEvent, render, screen } from "@testing-library/react";
import { registerAction } from "@/platform/actions";
import { ServerStatus } from "./ServerStatus";
import { useServers, type ServerEntry } from "./servers";
import { useToolUpdates } from "@/workbench/contributions";
const ISSUE_49 =
"jdtls needs JDK 25 or newer to run (found JDK 8, 17, 21). Download JDK 25, or pick an installed one in Settings › Languages & Frameworks › Java › Language Server › JDK (it restarts automatically); the project can still target an older Java version.";
@@ -10,9 +11,35 @@ const ISSUE_49 =
const server = (status: ServerEntry["status"], message: string | null): ServerEntry =>
({ id: 1, name: "jdtls", status, message, languages: ["Java"], root: null }) as unknown as ServerEntry;
afterEach(() => useServers.setState({ servers: new Map() }));
afterEach(() => {
useServers.setState({ servers: new Map() });
useToolUpdates.setState({ latest: {} });
});
describe("Language server status popup", () => {
it("marks a server with a newer version and updates it from its row (#7365)", () => {
const install = vi.fn();
const off = registerAction({ id: "tools.install", title: "Install", run: ({ arg }) => install(arg) });
useServers.setState({ servers: new Map([[1 as never, server("ready", null)]]) });
useToolUpdates.setState({ latest: { jdtls: "1.64.0" } });
render(<ServerStatus />);
expect(screen.getByLabelText("Language server updates are available")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /Language servers/ }));
fireEvent.click(screen.getByRole("button", { name: "Update jdtls" }));
expect(install).toHaveBeenCalledWith("jdtls");
off();
});
it("shows no update mark without one", () => {
const off = registerAction({ id: "tools.install", title: "Install", run: () => {} });
useServers.setState({ servers: new Map([[1 as never, server("ready", null)]]) });
render(<ServerStatus />);
expect(screen.queryByLabelText("Language server updates are available")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: /Language servers/ }));
expect(screen.queryByRole("button", { name: "Update jdtls" })).toBeNull();
off();
});
it("offers Download JDK N when jdtls can't start for want of a JDK", () => {
const run = vi.fn();
const off = registerAction({ id: "java.downloadJdk", title: "Download JDK…", run: ({ arg }) => run(arg) });
+27 -1
Переглянути файл
@@ -2,7 +2,7 @@
import { useMemo, useRef, useState } from "react";
import clsx from "clsx";
import { getAction, executeAction } from "@/platform/actions";
import { BarButton, Button, IconButton, Popup, T } from "@/ui";
import { BarButton, Button, Icon, IconButton, Popup, T } from "@/ui";
import { downloadJdkActions } from "@/platform/jdk";
import { relativePath, useProject } from "@/platform/project";
import {
@@ -17,6 +17,7 @@ import {
} from "./servers";
import styles from "./ServerStatus.module.css";
import { tx } from "@/platform/i18n";
import { useToolUpdates } from "@/workbench/contributions";
export function ServerStatus() {
const map = useServers((s) => s.servers);
@@ -28,6 +29,9 @@ export function ServerStatus() {
// features/tools owns installing; without it, fall back to the manual hint text.
const canInstall = !!getAction("tools.install");
const canConfigure = !!getAction("tools.languageServers");
const latestVersions = useToolUpdates((s) => s.latest);
// Installed servers with a newer version; the same tool can back several servers.
const updatable = canInstall ? servers.filter((s) => latestVersions[s.name]) : [];
if (!summary) return null;
return (
<>
@@ -40,6 +44,14 @@ export function ServerStatus() {
>
<span className={clsx(styles.dot, styles[summary.tone])} aria-hidden />
{summary.text}
{updatable.length > 0 && (
<Icon
name="arrow-up"
size={12}
className={styles.updateBadge}
label={tx("Language server updates are available")}
/>
)}
</BarButton>
<Popup
open={open}
@@ -56,6 +68,7 @@ export function ServerStatus() {
{servers.map((s) => {
// jdtls without a JDK new enough to run it: "Download JDK 25".
const [jdkFix] = s.status === "misconfigured" ? downloadJdkActions(s.message) : [];
const latest = latestVersions[s.name];
return (
<div key={s.id} className={styles.server}>
<div className={styles.line}>
@@ -81,6 +94,19 @@ export function ServerStatus() {
</Button>
) : (
<>
{latest && updatable.includes(s) && (
<Button
size="small"
aria-label={tx`Update ${s.name}`}
title={tx`Version ${latest} is available.`}
onClick={() => {
setOpen(false);
void executeAction("tools.install", s.name);
}}
>
<T>Update</T>
</Button>
)}
{s.status === "missing" && canInstall && (
<Button
size="small"
+4
Переглянути файл
@@ -49,3 +49,7 @@
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.view .inline {
flex-direction: row;
align-items: center;
}
+77 -17
Переглянути файл
@@ -7,9 +7,13 @@ import { useEffect, useState } from "react";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { Button, Input } from "@/ui";
import { compareVersions, useCentral } from "./central";
import { ensureDotnetModel, useDotnet } from "./store";
import { SourcesPanel } from "./SourcesPanel";
import styles from "./Nuget.module.css";
const baseName = (path: string) => path.replace(/\\/g, "/").split("/").pop() ?? path;
export function NugetView() {
const s = useDotnet();
const tx = useTx();
@@ -17,20 +21,66 @@ export function NugetView() {
const results = new Map<string, string[]>();
for (const p of s.found) results.set(p.id, [...new Set([...(results.get(p.id) ?? []), p.version])]);
const project = s.model.projects.find((p) => p.path === s.selected);
const central = useCentral();
const matches =
central.project === s.selected && central.framework === s.framework && central.configuration === s.configuration;
const info = matches ? central.info : null;
const working = s.busy || central.busy;
const knownLatest = (p: { id: string; version: string }) => {
const latest = matches ? central.latest[p.id.toLowerCase()] : undefined;
return latest && compareVersions(latest, p.version) > 0 ? latest : undefined;
};
const note = (p: { id: string; version: string; transitive?: boolean }) => {
const key = p.id.toLowerCase();
const override = info?.overrides[key];
const file = baseName(info?.versions[key]?.file ?? "");
const latest = knownLatest(p);
return [
override ? tx`Version override ${override} in the project` : "",
!override && file ? (p.transitive ? tx`Pinned in ${file}` : tx`Defined in ${file}`) : "",
latest ? tx`Newer version available: ${latest}` : "",
]
.filter(Boolean)
.join(" · ");
};
const action = (id: string, arg?: unknown) => void executeAction(`dotnet.${id}`, arg);
// The workspace scan used to run when the standalone .NET window opened; without it the
// window shows no project to manage packages for.
useEffect(() => {
void ensureDotnetModel();
}, []);
// Where versions live (Directory.Packages.props, VersionOverride) follows the selected project.
useEffect(() => {
if (s.selected) void executeAction("dotnet.centralRefresh");
}, [s.selected, s.framework, s.configuration]);
return (
<div className={styles.view}>
<div className={styles.toolbar}>
<Button disabled={s.busy} onClick={() => action("packages")}>
{tx("Refresh packages")}
</Button>
{s.busy && <Button onClick={() => action("cancel")}>{tx("Cancel")}</Button>}
<Button disabled={working || !project} onClick={() => action("checkUpdates")}>
{tx("Check for updates")}
</Button>
<label className={styles.inline}>
<input
type="checkbox"
checked={central.prerelease}
disabled={working}
onChange={(e) => useCentral.setState({ prerelease: e.target.checked })}
/>
{tx("Include prereleases")}
</label>
{working && <Button onClick={() => action("cancel")}>{tx("Cancel")}</Button>}
</div>
{matches && central.error && (
<div role="alert" className={styles.error}>
{central.error}
</div>
)}
{info?.enabled && (
<div role="status">{tx("Central package management is on: versions are set in Directory.Packages.props.")}</div>
)}
{s.error && (
<div role="alert" className={styles.error}>
{s.error}
@@ -54,6 +104,7 @@ export function NugetView() {
</label>
{project && (
<>
<SourcesPanel project={project.path} />
<form
className={styles.toolbar}
onSubmit={(e) => {
@@ -97,23 +148,32 @@ export function NugetView() {
})}
</ul>
<ul className={styles.list}>
{s.packages.map((p) => (
<li key={`${p.id}:${p.version}`}>
<span>
{p.id} {p.version} {p.transitive ? tx("Transitive") : ""}
</span>
{!p.transitive && (
<>
<Button disabled={s.busy} onClick={() => action("search", { query: p.id, exact: true })}>
{tx("Versions")}
{s.packages.map((p) => {
const latest = knownLatest(p);
return (
<li key={`${p.id}:${p.version}`}>
<span>
{p.id} {p.version} {p.transitive ? tx("Transitive") : ""}
{note(p) && ` · ${note(p)}`}
</span>
{latest && !p.transitive && (project?.frameworks.length ?? 0) <= 1 && (
<Button disabled={working} onClick={() => action("packageChange", { id: p.id, version: latest })}>
{tx`Update to ${latest}`}
</Button>
<Button disabled={s.busy} onClick={() => action("packageChange", { id: p.id, version: null })}>
{tx("Remove")}
</Button>
</>
)}
</li>
))}
)}
{!p.transitive && (
<>
<Button disabled={s.busy} onClick={() => action("search", { query: p.id, exact: true })}>
{tx("Versions")}
</Button>
<Button disabled={s.busy} onClick={() => action("packageChange", { id: p.id, version: null })}>
{tx("Remove")}
</Button>
</>
)}
</li>
);
})}
</ul>
</>
)}
+65
Переглянути файл
@@ -0,0 +1,65 @@
import { afterEach, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import * as actions from "@/platform/actions";
import * as dotnet from "@/platform/dotnet";
import { useProject } from "@/platform/project";
import { resetSources, useSources } from "./sources";
import { SourcesPanel } from "./SourcesPanel";
import { resetDotnet, useDotnet } from "./store";
afterEach(() => {
cleanup();
resetSources();
resetDotnet();
useProject.setState({ project: null });
vi.restoreAllMocks();
});
function show() {
const run = vi.spyOn(actions, "executeAction").mockResolvedValue(undefined as never);
useProject.setState({ project: { root: "/w" } as never });
useDotnet.setState({
selected: "/w/App.csproj",
model: { projects: [{ path: "/w/App.csproj" } as never], solutions: [] },
});
vi.spyOn(dotnet, "dotnet").mockResolvedValue("");
useSources.setState({
project: "/w/App.csproj",
sources: [
{ name: "local", url: "/feed", enabled: true },
{ name: "priv", url: "https://***@h.example/i.json", enabled: false },
],
configs: [
{ path: "/w/NuGet.Config", scope: "workspace", exists: true },
{ path: "/home/u/NuGet.Config", scope: "user", exists: true },
],
target: "/w/NuGet.Config",
targetNames: ["local", "priv"],
});
render(<SourcesPanel project="/w/App.csproj" />);
return run;
}
it("shows state and masked URLs, and toggles and removes by name", () => {
const run = show();
expect(screen.getByText(/priv.*https:\/\/\*\*\*@h\.example/)).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Disable" }));
fireEvent.click(screen.getByRole("button", { name: "Enable" }));
fireEvent.click(screen.getAllByRole("button", { name: "Remove" })[0]!);
expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "disable", name: "local" });
expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "enable", name: "priv" });
expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "remove", name: "local" });
});
it("warns before the user-wide file is the write target and adds a source", async () => {
const run = show();
expect(screen.queryByRole("status")).toBeNull();
fireEvent.change(screen.getByLabelText("NuGet.Config file"), { target: { value: "/home/u/NuGet.Config" } });
expect(screen.getByRole("status").textContent).toMatch(/every project/);
fireEvent.change(screen.getByLabelText("Source name"), { target: { value: "n" } });
fireEvent.change(screen.getByLabelText("Source URL or folder"), { target: { value: "/f" } });
const add = screen.getByRole<HTMLButtonElement>("button", { name: "Add source" });
await waitFor(() => expect(add.disabled).toBe(false));
fireEvent.click(add);
expect(run).toHaveBeenCalledWith("dotnet.sourceChange", { op: "add", name: "n", url: "/f" });
});
+85
Переглянути файл
@@ -0,0 +1,85 @@
/** Package sources of the selected project's NuGet.Config hierarchy (#7420). */
import { useEffect, useState } from "react";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { Button, Input } from "@/ui";
import { selectSourceConfig, useSources } from "./sources";
import styles from "./Nuget.module.css";
export function SourcesPanel({ project }: { project: string }) {
const s = useSources();
const tx = useTx();
const [name, setName] = useState("");
const [url, setUrl] = useState("");
const action = (id: string, arg?: unknown) => void executeAction(`dotnet.${id}`, arg);
useEffect(() => {
action("sources");
}, [project]);
const target = s.configs.find((c) => c.path === s.target);
return (
<details>
<summary>{tx("Package sources")}</summary>
{s.error && (
<div role="alert" className={styles.error}>
{s.error}
</div>
)}
<ul className={styles.list} aria-label={tx("Package sources")}>
{s.sources.map((p) => (
<li key={p.name}>
<span>
{p.name} {p.enabled ? "" : tx("Disabled")} {p.url}
</span>
<Button
disabled={s.busy || !s.targetNames.includes(p.name)}
onClick={() => action("sourceChange", { op: p.enabled ? "disable" : "enable", name: p.name })}
>
{p.enabled ? tx("Disable") : tx("Enable")}
</Button>
<Button
disabled={s.busy || !s.targetNames.includes(p.name)}
onClick={() => action("sourceChange", { op: "remove", name: p.name })}
>
{tx("Remove")}
</Button>
</li>
))}
</ul>
{s.sources.some((source) => !s.targetNames.includes(source.name)) && (
<p>{tx("Choose the NuGet.Config file that defines this source to change it.")}</p>
)}
<label>
{tx("Write changes to")}
<select
aria-label={tx("NuGet.Config file")}
value={s.target}
disabled={s.busy}
onChange={(e) => void selectSourceConfig(e.target.value)}
>
{s.configs.map((c) => (
<option key={c.path} value={c.path}>
{c.scope === "user" ? tx`User-wide: ${c.path}` : c.path}
</option>
))}
</select>
</label>
{target?.scope === "user" && <div role="status">{tx("This file applies to every project of this user.")}</div>}
<form
className={styles.toolbar}
onSubmit={(e) => {
e.preventDefault();
action("sourceChange", { op: "add", name, url });
setName("");
setUrl("");
}}
>
<Input aria-label={tx("Source name")} value={name} onChange={(e) => setName(e.target.value)} />
<Input aria-label={tx("Source URL or folder")} value={url} onChange={(e) => setUrl(e.target.value)} />
<Button type="submit" disabled={s.busy || !name.trim() || !url.trim()}>
{tx("Add source")}
</Button>
</form>
<div>{tx("Credentials are handled by dotnet and its credential providers; the IDE does not store them.")}</div>
</details>
);
}
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff. Show more