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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 3ddd1ea9b8 fix(vcs): show why checkout was blocked 2026-12-02 19:04:39 +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
144 змінених файлів з 7240 додано та 1499 видалено

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));
+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.
+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]
+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"]"#);
}
}
+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
+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`;补全后会删掉自己的留言并移除标签。它只读标题、描述和改动的文件名,不会检出或运行你的代码。
### 要跑的检查
+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();
});
+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" });
+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.
+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));
+6 -2
Переглянути файл
@@ -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 = {
@@ -17322,6 +17324,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>
);
}
+150
Переглянути файл
@@ -0,0 +1,150 @@
// @vitest-environment node
/** Central package management against the real `dotnet` CLI (SDK 10 and 11) and a local folder feed. */
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as platform from "@/platform/dotnet";
import { checkUpdates, refreshCentral, resetCentral, useCentral } from "./central";
import { type Sandbox, cliSdks, sandbox } from "./cliTestkit";
import { changePackage, resetDotnet, useDotnet } from "./store";
// Each test packs or restores with the real CLI, slower on a loaded machine.
vi.setConfig({ testTimeout: 240_000 });
const sdks = cliSdks();
it.runIf(sdks.length === 0)("has no SDK 10 or 11 here (CI fails on this)", () => {
expect(process.env.CI).toBeFalsy();
});
const PROPS = (versions: string, extra = "") =>
`<Project><PropertyGroup><ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>${extra}</PropertyGroup><ItemGroup>${versions}</ItemGroup></Project>`;
describe.each(sdks)("central package management with SDK %s", (sdk) => {
let sb: Sandbox;
let app: string;
let csproj: string;
const props = () => join(sb.root, "Directory.Packages.props");
/** A workspace whose only source is the local feed; the project lives two folders below the props file. */
const workspace = (ref: string, central: string | null, feedPackages = true) => {
const feed = join(sb.root, "feed");
if (feedPackages) {
sb.pack(feed, "Demo.Pkg", ["1.0.0", "1.1.0", "2.0.0-beta.1"]);
sb.pack(feed, "Child.Pkg", ["1.0.0", "1.1.0"]);
sb.pack(feed, "Parent.Pkg", ["1.0.0"], [["Child.Pkg", "1.0.0"]]);
}
writeFileSync(
join(sb.root, "NuGet.Config"),
`<configuration><packageSources><clear /><add key="local" value="./feed" /></packageSources></configuration>`,
);
if (central) writeFileSync(props(), central);
app = join(sb.root, "src", "app");
mkdirSync(app, { recursive: true });
csproj = join(app, "App.csproj");
writeFileSync(
csproj,
`<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net${sb.major}.0</TargetFramework></PropertyGroup><ItemGroup>${ref}</ItemGroup></Project>`,
);
sb.ok(["restore", csproj], app);
// The store's `dotnet()` runs the real CLI in the sandbox; project evaluation is not under test here.
vi.spyOn(platform, "dotnet").mockImplementation(async (args, cwd) => sb.ok(args, cwd));
vi.spyOn(platform, "evaluateProject").mockResolvedValue({
path: csproj,
frameworks: [`net${sb.major}.0`],
} as never);
useDotnet.setState({ selected: csproj, model: { projects: [{ path: csproj } as never], solutions: [] } });
};
beforeEach(() => {
sb = sandbox(sdk);
});
afterEach(() => {
sb.dispose();
resetCentral();
resetDotnet();
vi.restoreAllMocks();
});
it("finds Directory.Packages.props in a parent folder, shows the newer version and Update writes the props file", async () => {
workspace(
`<PackageReference Include="Demo.Pkg" />`,
PROPS(`<PackageVersion Include="Demo.Pkg" Version="1.0.0" />`),
);
await refreshCentral();
const { info } = useCentral.getState();
expect(useCentral.getState().error).toBe("");
expect(info!.enabled).toBe(true);
expect(info!.versions["demo.pkg"]).toEqual({ version: "1.0.0", file: props() });
await checkUpdates();
expect(useCentral.getState().latest).toEqual({ "demo.pkg": "1.1.0" });
await changePackage("Demo.Pkg", "1.1.0");
expect(useDotnet.getState().error).toBe("");
expect(readFileSync(props(), "utf8")).toContain('Version="1.1.0"');
expect(readFileSync(csproj, "utf8")).not.toMatch(/Version=/);
await checkUpdates();
expect(useCentral.getState().latest).toEqual({});
}, 240_000);
it("a VersionOverride stays in the project and Update rewrites it there, not the props file", async () => {
workspace(
`<PackageReference Include="Demo.Pkg" VersionOverride="1.0.0" />`,
PROPS(
`<PackageVersion Include="Demo.Pkg" Version="1.0.0" />`,
`<CentralPackageVersionOverrideEnabled>true</CentralPackageVersionOverrideEnabled>`,
),
);
await refreshCentral();
expect(useCentral.getState().info!.overrides).toEqual({ "demo.pkg": "1.0.0" });
await checkUpdates();
expect(useCentral.getState().latest["demo.pkg"]).toBe("1.1.0");
await changePackage("Demo.Pkg", "1.1.0");
expect(readFileSync(csproj, "utf8")).toContain('VersionOverride="1.1.0"');
expect(readFileSync(props(), "utf8")).toContain('Version="1.0.0"');
}, 240_000);
it("without central management the version stays in the project and nothing is marked as central", async () => {
workspace(`<PackageReference Include="Demo.Pkg" Version="1.0.0" />`, null);
await refreshCentral();
expect(useCentral.getState().info).toMatchObject({ enabled: false, versions: {}, overrides: {} });
await checkUpdates();
expect(useCentral.getState().latest).toEqual({ "demo.pkg": "1.1.0" });
await changePackage("Demo.Pkg", "1.1.0");
expect(readFileSync(csproj, "utf8")).toContain('Version="1.1.0"');
}, 240_000);
it("prereleases count only when asked, and a prerelease in use is compared with its newer releases", async () => {
workspace(`<PackageReference Include="Demo.Pkg" Version="1.1.0" />`, null);
await checkUpdates();
expect(useCentral.getState().latest).toEqual({});
useCentral.setState({ prerelease: true });
await checkUpdates();
expect(useCentral.getState().latest).toEqual({ "demo.pkg": "2.0.0-beta.1" });
}, 240_000);
it("transitive pinning: a PackageVersion for an unreferenced package pins the transitive one", async () => {
workspace(
`<PackageReference Include="Parent.Pkg" />`,
PROPS(
`<PackageVersion Include="Parent.Pkg" Version="1.0.0" /><PackageVersion Include="Child.Pkg" Version="1.1.0" />`,
`<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>`,
),
);
await refreshCentral();
const { info } = useCentral.getState();
expect(info!.pinning).toBe(true);
expect(info!.versions["child.pkg"]!.file).toBe(props());
const listed = sb.ok(["list", csproj, "package", "--include-transitive", "--format", "json"], app);
expect(listed).toMatch(/"id":\s*"Child.Pkg"[^}]*"resolvedVersion":\s*"1\.1\.0"/);
}, 240_000);
it("reports the CLI error for a malformed project and keeps the previous state", async () => {
workspace(`<PackageReference Include="Demo.Pkg" Version="1.0.0" />`, null);
await refreshCentral();
writeFileSync(csproj, "<Project Sdk=");
await refreshCentral();
expect(useCentral.getState().error).not.toBe("");
expect(useCentral.getState().busy).toBe(false);
}, 240_000);
});
+138
Переглянути файл
@@ -0,0 +1,138 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import * as platform from "@/platform/dotnet";
import {
cancelCentral,
checkUpdates,
compareVersions,
parseCentral,
parseOutdated,
refreshCentral,
resetCentral,
useCentral,
} from "./central";
import { resetDotnet, useDotnet } from "./store";
afterEach(() => {
resetCentral();
resetDotnet();
vi.restoreAllMocks();
});
describe("central package state", () => {
it("reports where each PackageVersion is defined and any VersionOverride", () => {
const info = parseCentral({
Properties: { ManagePackageVersionsCentrally: "true", CentralPackageTransitivePinningEnabled: "True" },
Items: {
PackageVersion: [
{ Identity: "Demo.Pkg", Version: "1.0.0", DefiningProjectFullPath: "/r/Directory.Packages.props" },
],
PackageReference: [{ Identity: "Other", VersionOverride: "2.0.0" }, { Identity: "Demo.Pkg" }],
},
});
expect(info).toEqual({
enabled: true,
pinning: true,
versions: { "demo.pkg": { version: "1.0.0", file: "/r/Directory.Packages.props" } },
overrides: { other: "2.0.0" },
});
});
it("ignores the items when central management is off", () => {
const info = parseCentral({
Properties: { ManagePackageVersionsCentrally: "" },
Items: { PackageVersion: [{ Identity: "X", Version: "1" }] },
});
expect(info.enabled).toBe(false);
expect(info.versions).toEqual({});
});
});
describe("outdated packages", () => {
it("keeps the newest latest version across target frameworks and skips current packages", () => {
const latest = parseOutdated({
projects: [
{
frameworks: [
{
topLevelPackages: [
{ id: "A", resolvedVersion: "1.0.0", latestVersion: "1.2.0" },
{ id: "B", resolvedVersion: "2.0.0", latestVersion: "2.0.0" },
],
},
{
topLevelPackages: [{ id: "A", resolvedVersion: "1.0.0", latestVersion: "1.10.0" }],
transitivePackages: [{ id: "T", resolvedVersion: "1", latestVersion: "1.1" }],
},
],
},
],
});
expect(latest).toEqual({ a: "1.10.0", t: "1.1" });
});
it("orders versions by SemVer precedence", () => {
expect(compareVersions("1.10.0", "1.2.0")).toBeGreaterThan(0);
expect(compareVersions("2.0.0", "2.0.0-beta.1")).toBeGreaterThan(0);
expect(compareVersions("2.0.0-beta.10", "2.0.0-beta.2")).toBeGreaterThan(0);
expect(compareVersions("2.0.0-beta", "2.0.0-beta.1")).toBeLessThan(0);
expect(compareVersions("1.0", "1.0.0")).toBe(0);
expect(compareVersions("1.0.0+a", "1.0.0+b")).toBe(0);
});
});
describe("running", () => {
const select = () =>
useDotnet.setState({
selected: "/r/App.csproj",
model: { projects: [{ path: "/r/App.csproj" } as never], solutions: [] },
});
it("surfaces a CLI failure and clears busy", async () => {
select();
vi.spyOn(platform, "dotnet").mockRejectedValue(new Error("MSB4025: The project file could not be loaded"));
await refreshCentral();
expect(useCentral.getState().error).toMatch(/MSB4025/);
expect(useCentral.getState().busy).toBe(false);
});
it("drops a result that arrives after cancellation or a workspace switch", async () => {
select();
let done!: (s: string) => void;
vi.spyOn(platform, "dotnet").mockImplementation(() => new Promise((r) => (done = r)));
const first = checkUpdates();
cancelCentral();
done('{"projects":[]}');
await first;
expect(useCentral.getState().checked).toBe(false);
const second = checkUpdates();
resetCentral();
done('{"projects":[]}');
await second;
expect(useCentral.getState().checked).toBe(false);
expect(useCentral.getState().busy).toBe(false);
});
it("checks versions while the newly opened tool window loads metadata", async () => {
select();
let finish!: (value: string) => void;
vi.spyOn(platform, "dotnet").mockImplementation((args) =>
args[0] === "list"
? new Promise((resolve) => {
finish = resolve;
})
: Promise.resolve('{"Properties":{"ManagePackageVersionsCentrally":"true"}}'),
);
const checking = checkUpdates();
await refreshCentral();
expect(useCentral.getState().info?.enabled).toBe(true);
expect(useCentral.getState().busy).toBe(true);
finish('{"projects":[]}');
await checking;
expect(useCentral.getState().checked).toBe(true);
});
it("passes --include-prerelease only when asked", async () => {
select();
const run = vi.spyOn(platform, "dotnet").mockResolvedValue('{"projects":[]}');
await checkUpdates();
expect(run.mock.calls[0]![0]).not.toContain("--include-prerelease");
useCentral.setState({ prerelease: true });
await checkUpdates();
expect(run.mock.calls[1]![0]).toContain("--include-prerelease");
});
});
+198
Переглянути файл
@@ -0,0 +1,198 @@
import { create } from "zustand";
import { dotnet, jsonOutput } from "@/platform/dotnet";
import { dirname, useProject } from "@/platform/project";
import { selectedProject, useDotnet } from "./store";
export interface CentralInfo {
/** `ManagePackageVersionsCentrally` is on for the project. */
enabled: boolean;
/** `CentralPackageTransitivePinningEnabled`: a `PackageVersion` also pins transitive packages. */
pinning: boolean;
/** Where each `PackageVersion` is written: the file that defines it (`Directory.Packages.props` or an import). */
versions: Record<string, { version: string; file: string }>;
/** `VersionOverride` on a `PackageReference` in the project: the project, not the central file, owns the version. */
overrides: Record<string, string>;
}
interface State {
project: string;
framework: string;
configuration: string;
info: CentralInfo | null;
/** Latest version per package id from `dotnet list package --outdated`; absent when up to date or not checked. */
latest: Record<string, string>;
checked: boolean;
prerelease: boolean;
busy: boolean;
error: string;
}
const byId = <T>(): Record<string, T> => Object.create(null) as Record<string, T>;
const initial: State = {
project: "",
framework: "",
configuration: "",
info: null,
latest: byId<string>(),
checked: false,
prerelease: false,
busy: false,
error: "",
};
export const useCentral = create<State>(() => initial);
type Query = "metadata" | "updates";
const pending = new Map<Query, AbortController>();
export function resetCentral() {
cancelCentral();
pending.clear();
useCentral.setState(initial);
}
export function cancelCentral() {
for (const controller of pending.values()) controller.abort();
}
interface Item {
Identity: string;
Version?: string;
VersionOverride?: string;
DefiningProjectFullPath?: string;
}
interface MsbuildJson {
Properties?: Record<string, string>;
Items?: { PackageVersion?: Item[]; PackageReference?: Item[] };
}
/** `dotnet msbuild -getProperty -getItem`: the evaluated central state, with the file each version comes from. */
export function parseCentral(data: MsbuildJson): CentralInfo {
const on = (v?: string) => v?.toLowerCase() === "true";
const info: CentralInfo = {
enabled: on(data.Properties?.ManagePackageVersionsCentrally),
pinning: on(data.Properties?.CentralPackageTransitivePinningEnabled),
versions: byId<{ version: string; file: string }>(),
overrides: byId<string>(),
};
if (!info.enabled) return info;
for (const v of data.Items?.PackageVersion ?? [])
info.versions[v.Identity.toLowerCase()] = { version: v.Version ?? "", file: v.DefiningProjectFullPath ?? "" };
for (const r of data.Items?.PackageReference ?? [])
if (r.VersionOverride) info.overrides[r.Identity.toLowerCase()] = r.VersionOverride;
return info;
}
interface OutdatedJson {
projects?: Array<{
frameworks?: Array<{
topLevelPackages?: Array<{ id: string; latestVersion?: string; resolvedVersion?: string }>;
transitivePackages?: Array<{ id: string; latestVersion?: string; resolvedVersion?: string }>;
}>;
}>;
}
/** The newest `latestVersion` per package across the project's target frameworks. */
export function parseOutdated(data: OutdatedJson): Record<string, string> {
const latest = byId<string>();
for (const p of data.projects ?? [])
for (const f of p.frameworks ?? [])
for (const pkg of [...(f.topLevelPackages ?? []), ...(f.transitivePackages ?? [])])
if (pkg.latestVersion && pkg.resolvedVersion && compareVersions(pkg.latestVersion, pkg.resolvedVersion) > 0) {
const key = pkg.id.toLowerCase();
if (!latest[key] || compareVersions(pkg.latestVersion, latest[key]) > 0) latest[key] = pkg.latestVersion;
}
return latest;
}
/** SemVer precedence: numeric core, then a release outranks its prereleases. */
export function compareVersions(a: string, b: string): number {
const [coreA = "", preA] = a.split("+")[0]!.split(/-(.*)/s);
const [coreB = "", preB] = b.split("+")[0]!.split(/-(.*)/s);
const na = coreA.split(".").map(Number);
const nb = coreB.split(".").map(Number);
for (let i = 0; i < Math.max(na.length, nb.length); i++) {
const d = (na[i] ?? 0) - (nb[i] ?? 0);
if (d) return d;
}
if (preA === undefined || preB === undefined) return preA === preB ? 0 : preA === undefined ? 1 : -1;
const ia = preA.toLowerCase().split(".");
const ib = preB.toLowerCase().split(".");
for (let i = 0; i < Math.max(ia.length, ib.length); i++) {
const x = ia[i];
const y = ib[i];
if (x === undefined || y === undefined) return x === undefined ? -1 : 1;
const nx = /^\d+$/.test(x);
const ny = /^\d+$/.test(y);
if (nx && ny) {
if (Number(x) !== Number(y)) return Number(x) - Number(y);
} else if (nx !== ny) return nx ? -1 : 1;
else if (x !== y) return x < y ? -1 : 1;
}
return 0;
}
async function run(query: Query, work: (signal: AbortSignal, path: string) => Promise<Partial<State>>) {
const project = selectedProject();
if (!project) return;
const path = project.path;
const root = useProject.getState().project?.root;
const { framework, configuration } = useDotnet.getState();
const contextChanged = () => {
const current = useDotnet.getState();
return (
current.selected !== path ||
current.framework !== framework ||
current.configuration !== configuration ||
useProject.getState().project?.root !== root
);
};
pending.get(query)?.abort();
const abort = new AbortController();
pending.set(query, abort);
const stopIfChanged = () => {
if (contextChanged()) abort.abort();
};
const stopProject = useProject.subscribe(stopIfChanged);
const stopSelection = useDotnet.subscribe(stopIfChanged);
const previous = useCentral.getState();
const sameContext =
previous.project === path && previous.framework === framework && previous.configuration === configuration;
useCentral.setState(
sameContext
? { busy: true, error: "" }
: { ...initial, project: path, framework, configuration, busy: true, prerelease: previous.prerelease },
);
try {
const patch = await work(abort.signal, path);
if (pending.get(query) === abort && !abort.signal.aborted) useCentral.setState(patch);
} catch (e) {
if (pending.get(query) === abort && !abort.signal.aborted) useCentral.setState({ error: String(e) });
} finally {
stopProject();
stopSelection();
if (pending.get(query) === abort) {
pending.delete(query);
useCentral.setState({ busy: pending.size > 0 });
}
}
}
export function refreshCentral() {
const { framework, configuration } = useDotnet.getState();
return run("metadata", async (signal, path) => {
const out = await dotnet(
[
"msbuild",
path,
`-p:Configuration=${configuration}`,
...(framework ? [`-p:TargetFramework=${framework}`] : []),
"-getProperty:ManagePackageVersionsCentrally,CentralPackageTransitivePinningEnabled",
"-getItem:PackageVersion,PackageReference",
],
dirname(path),
signal,
);
return { info: parseCentral(jsonOutput<MsbuildJson>(out)) };
});
}
export function checkUpdates() {
return run("updates", async (signal, path) => {
const args = ["list", path, "package", "--outdated", "--format", "json"];
if (useCentral.getState().prerelease) args.push("--include-prerelease");
const out = await dotnet(args, dirname(path), signal);
return { latest: parseOutdated(jsonOutput<OutdatedJson>(out)), checked: true };
});
}
+102
Переглянути файл
@@ -0,0 +1,102 @@
/**
* Runs the real `dotnet` CLI for tests: an isolated HOME (so the user-wide NuGet.Config and
* the package cache are the test's own), one SDK picked per run through `global.json`, and a
* local folder feed packed on the fly so nothing reaches nuget.org.
*
* With `CI` set a missing SDK fails the run instead of skipping it, so a runner without .NET
* cannot pass these tests silently.
*/
import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
/** Installed SDK versions whose major version is one of `majors` (10 and 11 are the ones tested). */
export function cliSdks(majors: number[] = [10, 11]): string[] {
const out = spawnSync("dotnet", ["--list-sdks"], { encoding: "utf8" });
if (out.status !== 0) {
if (process.env.CI) throw new Error("dotnet is required in CI but was not found");
return [];
}
const versions = out.stdout
.split(/\r?\n/)
.map((l) => l.split(" ")[0]!)
.filter((v) => majors.includes(Number(v.split(".")[0])));
// One SDK per major: the newest installed one.
return majors.flatMap((m) => versions.filter((v) => v.startsWith(`${m}.`)).slice(-1));
}
export interface Sandbox {
/** Workspace root; its global.json pins the SDK. */
root: string;
/** The test's HOME: holds the user-wide NuGet.Config. */
home: string;
major: number;
run(args: string[], cwd?: string): { code: number; out: string };
/** Like `run` but throws on a non-zero exit, as the IDE's `dotnet()` does. */
ok(args: string[], cwd?: string): string;
/** Packs `id` at each version into `feed` (a local folder feed). */
pack(feed: string, id: string, versions: string[], deps?: Array<[id: string, version: string]>): void;
dispose(): void;
}
export function sandbox(sdk: string): Sandbox {
// realpath: the CLI prints resolved paths (macOS /var -> /private/var).
const base = realpathSync(mkdtempSync(join(tmpdir(), "oi-nuget-")));
const root = join(base, "ws");
const home = join(base, "home");
mkdirSync(root);
mkdirSync(home);
writeFileSync(join(root, "global.json"), JSON.stringify({ sdk: { version: sdk, rollForward: "disable" } }));
const major = Number(sdk.split(".")[0]);
const env = {
...process.env,
HOME: home,
USERPROFILE: home,
APPDATA: join(home, "AppData"),
DOTNET_CLI_HOME: home,
NUGET_PACKAGES: join(base, "packages"),
DOTNET_CLI_UI_LANGUAGE: "en",
DOTNET_NOLOGO: "1",
DOTNET_CLI_TELEMETRY_OPTOUT: "1",
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1",
MSBUILDDISABLENODEREUSE: "1",
};
const run = (args: string[], cwd = root) => {
const r = spawnSync("dotnet", args, { cwd, env, encoding: "utf8", timeout: 180_000 });
return { code: r.status ?? -1, out: `${r.stdout}${r.stderr}` };
};
const ok = (args: string[], cwd = root) => {
const r = run(args, cwd);
if (r.code !== 0) throw new Error(`dotnet ${args.join(" ")} exited with ${r.code}\n${r.out}`);
return r.out;
};
return {
root,
home,
major,
run,
ok,
pack(feed, id, versions, deps = []) {
const dir = join(base, `pack-${id}`);
mkdirSync(dir, { recursive: true });
mkdirSync(feed, { recursive: true });
writeFileSync(
join(dir, `${id}.csproj`),
`<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net${major}.0</TargetFramework>` +
`<IncludeBuildOutput>false</IncludeBuildOutput><DisableImplicitFrameworkReferences>true</DisableImplicitFrameworkReferences><EnableDefaultItems>false</EnableDefaultItems><GenerateAssemblyInfo>false</GenerateAssemblyInfo><GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute><NoWarn>NU5128;NU5127</NoWarn>` +
`</PropertyGroup><ItemGroup><None Include="content.txt" Pack="true" PackagePath="content/" />` +
deps.map(([d, v]) => `<PackageReference Include="${d}" Version="${v}" />`).join("") +
`</ItemGroup></Project>`,
);
// Only the feed itself (for dependencies): the user's and the test's sources stay out of packing.
writeFileSync(
join(dir, "NuGet.Config"),
`<configuration><packageSources><clear /><add key="feed" value="${feed}" /></packageSources></configuration>`,
);
writeFileSync(join(dir, "content.txt"), id);
for (const v of versions) ok(["pack", dir, "-p:PackageVersion=" + v, "-o", feed, "--nologo"], dir);
},
dispose: () => rmSync(base, { recursive: true, force: true }),
};
}
+300
Переглянути файл
@@ -0,0 +1,300 @@
import { execFile, execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.setConfig({ testTimeout: 90_000, hookTimeout: 90_000 });
const mocks = vi.hoisted(() => ({ reload: vi.fn(async () => {}), pick: vi.fn(), notify: vi.fn() }));
vi.mock("./store", async (orig) => ({ ...(await orig<typeof import("./store")>()), reloadDotnet: mocks.reload }));
vi.mock("@/platform/choosePath", () => ({ choosePaths: mocks.pick }));
// The real `dotnet` CLI stands in for the Tauri process host: the arguments under test run unchanged.
vi.mock("@/platform/dotnet", async (orig) => ({
...(await orig<typeof import("@/platform/dotnet")>()),
dotnet: (args: string[], cwd: string, signal?: AbortSignal) =>
new Promise<string>((resolve, reject) => {
const child = execFile(
"dotnet",
args,
{ cwd, signal, env: { ...process.env, DOTNET_CLI_UI_LANGUAGE: "en" } },
(err, out, errOut) => (err ? reject(new Error(`${out}${errOut}`.trim() || err.message)) : resolve(out)),
);
child.on("error", reject);
}),
}));
import { useProject } from "@/platform/project";
import { provideNotificationService } from "@/workbench/contributions";
import { useDotnet } from "./store";
import {
addProjectReference,
addProjectsToSolution,
cancelDotnetEdit,
editItems,
referenceArgs,
removeProjectFromSolution,
removeProjectReference,
slnArgs,
} from "./edit";
const hasDotnet = (() => {
try {
execFileSync("dotnet", ["--version"], { stdio: "ignore" });
return true;
} catch {
return false;
}
})();
// CI installs the SDK (setup-dotnet), so a missing one there must fail, not skip.
const real = it.skipIf(!hasDotnet && !process.env.CI);
const csproj = (extra = "") =>
`<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net9.0</TargetFramework></PropertyGroup>${extra}</Project>`;
let dir = "";
const file = (rel: string, text = csproj()) => {
const path = join(dir, rel);
mkdirSync(join(path, ".."), { recursive: true });
writeFileSync(path, text);
return path;
};
const solution = (format: "sln" | "slnx", name = "App") => {
mkdirSync(join(dir, "sln"), { recursive: true });
execFileSync("dotnet", ["new", "sln", "-n", name, "--format", format, "-o", join(dir, "sln")], { stdio: "ignore" });
return join(dir, "sln", `${name}.${format}`);
};
const read = (path: string) => readFileSync(path, "utf8");
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "dotnet-edit-"));
mocks.reload.mockClear();
mocks.notify.mockClear();
provideNotificationService({ notify: mocks.notify });
});
afterEach(() => rmSync(dir, { recursive: true, force: true }));
describe("CLI arguments", () => {
it("builds solution and reference commands", () => {
expect(slnArgs("add", "/a/App.sln", ["/a/B.csproj"])).toEqual(["sln", "/a/App.sln", "add", "/a/B.csproj"]);
expect(referenceArgs("remove", "/a/A.csproj", ["/b/B.csproj"])).toEqual([
"remove",
"/a/A.csproj",
"reference",
"/b/B.csproj",
]);
});
});
it("does not run an edit queued for the previous project", async () => {
const previous = useProject.getState().project;
const projectAt = (root: string) => ({ root }) as NonNullable<typeof previous>;
useProject.setState({ project: projectAt("/first") });
try {
const queued = removeProjectFromSolution("/first/App.sln", "/first/App.csproj");
useProject.setState({ project: projectAt("/second") });
await queued;
expect(mocks.notify).not.toHaveBeenCalled();
expect(mocks.reload).not.toHaveBeenCalled();
} finally {
useProject.setState({ project: previous });
}
});
describe.each(["sln", "slnx"] as const)("solution edits on .%s (real dotnet CLI)", (format) => {
real("adds a project, then removes it, reloading after each", async () => {
const sln = solution(format);
const project = file("src/Lib/Lib.csproj");
await addProjectsToSolution(sln, [project]);
expect(read(sln)).toContain("Lib.csproj");
expect(mocks.reload).toHaveBeenCalledTimes(1);
await removeProjectFromSolution(sln, project);
expect(read(sln)).not.toContain("Lib.csproj");
expect(mocks.reload).toHaveBeenCalledTimes(2);
expect(mocks.notify).not.toHaveBeenCalled();
});
real("an empty solution gains its first project", async () => {
const sln = solution(format);
expect(read(sln)).not.toContain("proj");
await addProjectsToSolution(sln, [file("A/A.csproj")]);
expect(read(sln)).toContain("A.csproj");
});
real("adds a project outside the solution folder (relative .. path)", async () => {
const sln = solution(format);
await addProjectsToSolution(sln, [file("elsewhere/Out/Out.csproj")]);
expect(read(sln).replace(/\\/g, "/")).toContain("../elsewhere/Out/Out.csproj");
});
real("handles spaces and non-ASCII (中文) in paths", async () => {
const sln = solution(format);
const project = file("my 项目/测试 App/测试 App.csproj");
await addProjectsToSolution(sln, [project]);
expect(read(sln)).toContain("测试 App.csproj");
await removeProjectFromSolution(sln, project);
expect(read(sln)).not.toContain("测试 App.csproj");
});
real("a project that was added raises no warning (relative .. path resolved against the list)", async () => {
const sln = solution(format);
await addProjectsToSolution(sln, [file("out/Out/Out.csproj"), file("in/In.csproj")]);
expect(mocks.notify).not.toHaveBeenCalled();
});
real("adds several picked projects in one command", async () => {
const sln = solution(format);
await addProjectsToSolution(sln, [file("A/A.csproj"), file("B/B.csproj")]);
expect(read(sln)).toContain("A.csproj");
expect(read(sln)).toContain("B.csproj");
});
real("same-named projects from two folders: the CLI keeps the first and a warning names the other", async () => {
const sln = solution(format);
await addProjectsToSolution(sln, [file("one/Core/Core.csproj"), file("two/Core/Core.csproj")]);
// `dotnet sln add` matches by file name and exits 0 with "already contains project".
expect(read(sln).match(/Core\.csproj/g)).toHaveLength(1);
expect(mocks.notify).toHaveBeenCalledTimes(1);
expect(mocks.notify.mock.calls[0]![0]).toMatchObject({
level: "warning",
body: expect.stringContaining("Core.csproj"),
});
expect(mocks.reload).toHaveBeenCalledTimes(1);
});
real("removes a project whose file was deleted from disk", async () => {
const sln = solution(format);
const project = file("Gone/Gone.csproj");
await addProjectsToSolution(sln, [project]);
rmSync(join(dir, "Gone"), { recursive: true });
await removeProjectFromSolution(sln, project);
// The CLI refuses a missing file on some SDKs: either it is gone from the file, or an error was reported.
expect(read(sln).includes("Gone.csproj") ? mocks.notify.mock.calls.length : 1).toBeGreaterThan(0);
});
real("a project in two solutions is edited in one only", async () => {
const a = solution(format, "A");
const b = solution(format, "B");
const project = file("Shared/Shared.csproj");
await addProjectsToSolution(a, [project]);
await addProjectsToSolution(b, [project]);
await removeProjectFromSolution(a, project);
expect(read(a)).not.toContain("Shared.csproj");
expect(read(b)).toContain("Shared.csproj");
});
real("reports a CLI failure and refreshes the model after the process exits", async () => {
const sln = solution(format);
await addProjectsToSolution(sln, [join(dir, "missing/Nope.csproj")]);
expect(mocks.notify).toHaveBeenCalledTimes(1);
expect(mocks.notify.mock.calls[0]![0]).toMatchObject({
level: "error",
title: expect.stringContaining("solution"),
});
expect(mocks.reload).toHaveBeenCalledTimes(1);
});
real("a read-only solution file fails with a notification", async () => {
if (process.platform === "win32" || process.getuid?.() === 0) return;
const sln = solution(format);
execFileSync("chmod", ["444", sln]);
await addProjectsToSolution(sln, [file("A/A.csproj")]);
expect(mocks.notify).toHaveBeenCalledTimes(1);
expect(mocks.reload).toHaveBeenCalledTimes(1);
});
real("concurrent edits run one after another and both land", async () => {
const sln = solution(format);
await Promise.all([
addProjectsToSolution(sln, [file("A/A.csproj")]),
addProjectsToSolution(sln, [file("B/B.csproj")]),
]);
expect(read(sln)).toContain("A.csproj");
expect(read(sln)).toContain("B.csproj");
expect(mocks.reload).toHaveBeenCalledTimes(2);
});
it("no pick means no command", async () => {
mocks.pick.mockResolvedValue([]);
await addProjectsToSolution("/nowhere/App.sln");
expect(mocks.notify).not.toHaveBeenCalled();
expect(mocks.reload).not.toHaveBeenCalled();
});
});
describe("project reference edits (real dotnet CLI)", () => {
real("adds and removes a reference, also for a multi-targeted project", async () => {
const lib = file("Lib/Lib.csproj", csproj().replace("net9.0", "net8.0"));
const app = file(
"App/App.csproj",
csproj().replace(
"<TargetFramework>net9.0</TargetFramework>",
"<TargetFrameworks>net8.0;net9.0</TargetFrameworks>",
),
);
await addProjectReference(app, lib);
expect(read(app)).toContain("ProjectReference");
await removeProjectReference(app, lib);
expect(read(app)).not.toContain("ProjectReference");
expect(mocks.reload).toHaveBeenCalledTimes(2);
expect(mocks.notify).not.toHaveBeenCalled();
});
real("handles spaces and non-ASCII in the referenced path", async () => {
const lib = file("库 文件/库 Lib/库 Lib.csproj");
const app = file("App/App.csproj");
await addProjectReference(app, lib);
expect(read(app)).toContain("库 Lib.csproj");
});
real("reports a reference to a missing project", async () => {
const app = file("App/App.csproj");
await addProjectReference(app, join(dir, "nope/Nope.csproj"));
expect(mocks.notify).toHaveBeenCalledTimes(1);
expect(mocks.reload).toHaveBeenCalledTimes(1);
});
real("cancelling a queued edit reports nothing and skips the reload", async () => {
const sln = solution("sln");
const running = addProjectsToSolution(sln, [file("A/A.csproj")]);
cancelDotnetEdit();
await running;
expect(mocks.notify).not.toHaveBeenCalled();
expect(mocks.reload).not.toHaveBeenCalled();
});
});
describe("Project view menu items", () => {
const project = (path: string, references: string[] = []) => ({ path, name: path, references }) as never;
beforeEach(() => {
useDotnet.setState({
model: {
projects: [project("/s/A/A.csproj", ["/s/B/B.csproj"]), project("/s/B/B.csproj")],
solutions: [
{ path: "/s/One.sln", projects: ["/s/A/A.csproj"] },
{ path: "/s/Two.slnx", projects: ["/s/A/A.csproj"] },
],
},
});
});
afterEach(() => useDotnet.setState({ model: { projects: [], solutions: [] } }));
it("a solution offers Add Existing Project", () => {
expect(editItems("/s/One.sln")).toContainEqual(
expect.objectContaining({ action: "dotnet.solution.addProject", arg: { solution: "/s/One.sln" } }),
);
});
it("a project offers add / remove reference and one removal per owning solution", () => {
const items = editItems("/s/A/A.csproj");
expect(items.filter((i) => "action" in i && i.action === "dotnet.solution.removeProject")).toHaveLength(2);
expect(items.some((i) => "submenu" in i)).toBe(true);
expect(items).toContainEqual(expect.objectContaining({ action: "dotnet.project.addReference" }));
});
it("a project without references or solutions offers only Add Project Reference", () => {
const items = editItems("/s/B/B.csproj");
expect(items.some((i) => "submenu" in i)).toBe(false);
expect(items.filter((i) => "action" in i)).toHaveLength(1);
});
});
+195
Переглянути файл
@@ -0,0 +1,195 @@
/**
* Solution and project-reference edits from the Project view (#7421): `dotnet sln add|remove`
* and `dotnet add|remove reference` through the same trusted, cancellable process host as
* Build / Restore / Clean. Edits run one at a time (two writers on one `.sln` would race);
* afterwards the workspace reloads so the tree shows the new state, and a CLI failure
* surfaces as a notification.
*/
import { dotnet, dotnetAbsolutePath } from "@/platform/dotnet";
import { IpcError } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { choosePaths } from "@/platform/choosePath";
import { basename, dirname, useProject } from "@/platform/project";
import type { MenuItem } from "@/ui/Menu";
import { notifications } from "@/workbench/contributions";
import { reloadDotnet, useDotnet } from "./store";
import { isDotnetSolutionPath } from "./target";
let queue: Promise<unknown> = Promise.resolve();
/** Edits that are queued or running: Cancel aborts all of them. */
const pending = new Set<AbortController>();
export const cancelDotnetEdit = () => pending.forEach((c) => c.abort());
/** The CLI arguments of an edit; `solution` and `project` are absolute paths. */
export const slnArgs = (op: "add" | "remove", solution: string, projects: string[]) => [
"sln",
solution,
op,
...projects,
];
export const referenceArgs = (op: "add" | "remove", project: string, references: string[]) => [
op,
project,
"reference",
...references,
];
/**
* `dotnet sln add` exits 0 without adding a project whose file name another project of the
* solution already has ("already contains project"); the projects missing from `dotnet sln list`
* afterwards are warned about instead of passing as added.
*/
async function warnIfNotAdded(solution: string, projects: string[], signal: AbortSignal) {
let output: string;
try {
output = await dotnet(["sln", solution, "list"], dirname(solution), signal);
} catch {
return; // The add itself succeeded; a failing list is not worth a false alarm.
}
const listed = output
.split(/\r?\n/)
.filter((line) => /\.(?:cs|fs|vb)proj$/i.test(line.trim()))
.map((line) => dotnetAbsolutePath(dirname(solution), line.trim()));
const missing = projects.filter((path) => !listed.includes(dotnetAbsolutePath(dirname(solution), path)));
const names = missing.map(basename).join(", ");
if (missing.length)
notifications().notify({
level: "warning",
title: tx("The project was not added to the solution"),
body: tx`The solution already contains a project with the same name as ${names}.`,
group: "tools",
});
}
/** Runs `args` after the edits queued before it, then reloads the model. */
function run(
title: string,
args: string[],
cwd: string,
check?: (signal: AbortSignal) => Promise<void>,
): Promise<void> {
const root = useProject.getState().project?.root;
const stillInProject = () => useProject.getState().project?.root === root;
const abort = new AbortController();
const unsubscribe = useProject.subscribe(() => {
if (!stillInProject()) abort.abort();
});
pending.add(abort);
const next = queue
.catch(() => {})
.then(async () => {
try {
if (abort.signal.aborted) return;
let refresh = false;
try {
await dotnet(args, cwd, abort.signal);
refresh = true;
await check?.(abort.signal);
} catch (e) {
// A CLI process can have written part of a multi-entry edit before failing.
// An IPC rejection means the process could not be started.
refresh ||= !(e instanceof IpcError);
if (!abort.signal.aborted)
notifications().notify({ level: "error", title, body: String(e).trim(), group: "tools" });
}
if (refresh && stillInProject()) await reloadDotnet();
} finally {
unsubscribe();
pending.delete(abort);
}
});
queue = next;
return next;
}
const PROJECT_FILTER = [{ name: ".NET project", extensions: ["csproj", "fsproj", "vbproj"] }];
export async function addProjectsToSolution(solution: string, projects?: string[]) {
const root = useProject.getState().project?.root;
const picked =
projects ??
(await choosePaths({
directory: false,
title: tx("Add Existing Project"),
defaultPath: dirname(solution),
filters: PROJECT_FILTER,
}));
if (!picked.length || useProject.getState().project?.root !== root) return;
return run(
tx("Could not add the project to the solution"),
slnArgs("add", solution, picked),
dirname(solution),
(signal) => warnIfNotAdded(solution, picked, signal),
);
}
export function removeProjectFromSolution(solution: string, project: string) {
return run(
tx("Could not remove the project from the solution"),
slnArgs("remove", solution, [project]),
dirname(solution),
);
}
export async function addProjectReference(project: string, reference?: string) {
const root = useProject.getState().project?.root;
const picked =
reference ??
(await choosePaths({
directory: false,
title: tx("Add Project Reference"),
defaultPath: dirname(project),
filters: PROJECT_FILTER,
}));
const list = typeof picked === "string" ? [picked] : picked;
if (!list.length || useProject.getState().project?.root !== root) return;
return run(tx("Could not add the project reference"), referenceArgs("add", project, list), dirname(project));
}
export function removeProjectReference(project: string, reference: string) {
return run(
tx("Could not remove the project reference"),
referenceArgs("remove", project, [reference]),
dirname(project),
);
}
/** #7421: the solution / reference edits of a solution or project node. */
const solutionName = (path: string) => basename(path).replace(/\.slnx?$/i, "");
export function editItems(path: string): MenuItem[] {
const { model } = useDotnet.getState();
if (isDotnetSolutionPath(path))
return [
{ kind: "separator" },
{ kind: "action", action: "dotnet.solution.addProject", arg: { solution: path }, label: "Add Existing Project…" },
];
const solutions = model.solutions.filter((s) => s.projects.includes(path));
const references = model.projects.find((p) => p.path === path)?.references ?? [];
return [
{ kind: "separator" },
{ kind: "action", action: "dotnet.project.addReference", arg: { project: path }, label: "Add Project Reference…" },
...(references.length
? [
{
label: "Remove Project Reference",
submenu: references.map((reference): MenuItem => ({
kind: "action",
action: "dotnet.project.removeReference",
arg: { project: path, reference },
label: basename(reference),
verbatim: true,
})),
} satisfies MenuItem,
]
: []),
...solutions.map((s): MenuItem => ({
kind: "action",
action: "dotnet.solution.removeProject",
arg: { solution: s.path, project: path },
label: solutions.length > 1 ? tx`Remove from Solution '${solutionName(s.path)}'` : "Remove from Solution",
verbatim: solutions.length > 1,
})),
];
}
+56
Переглянути файл
@@ -0,0 +1,56 @@
/**
* Restricted Mode: every edit goes through `dotnet()` → `run_start`, which the backend refuses in an
* untrusted project (`crates/ide-host/tests/rpc.rs` asserts that for `run_start`). Here the real
* `dotnet()` wrapper meets that refusal: nothing is reloaded, the user gets the error, and no
* process or file is involved.
*/
import { beforeEach, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
runStart: vi.fn(async () => ({
status: "error" as const,
error: { kind: "unavailable", message: "Restricted Mode: trust this project to run it" },
})),
notify: vi.fn(),
reload: vi.fn(async () => {}),
}));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
...real,
commands: { ...real.commands, runStart: mocks.runStart },
ideEventsReady: async () => {},
onIdeEvent: () => () => {},
};
});
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage: unknown;
},
}));
vi.mock("./store", async (orig) => ({ ...(await orig<typeof import("./store")>()), reloadDotnet: mocks.reload }));
import { provideNotificationService } from "@/workbench/contributions";
import { addProjectReference, addProjectsToSolution, removeProjectFromSolution, removeProjectReference } from "./edit";
beforeEach(() => {
vi.clearAllMocks();
provideNotificationService({ notify: mocks.notify });
});
it.each([
["add project to solution", () => addProjectsToSolution("/s/App.sln", ["/s/A/A.csproj"])],
["remove project from solution", () => removeProjectFromSolution("/s/App.sln", "/s/A/A.csproj")],
["add project reference", () => addProjectReference("/s/A/A.csproj", "/s/B/B.csproj")],
["remove project reference", () => removeProjectReference("/s/A/A.csproj", "/s/B/B.csproj")],
])("%s is refused in an untrusted project", async (_name, edit) => {
await edit();
expect(mocks.runStart).toHaveBeenCalledTimes(1);
expect(mocks.notify).toHaveBeenCalledTimes(1);
expect(mocks.notify.mock.calls[0]![0]).toMatchObject({
level: "error",
body: expect.stringContaining("Restricted Mode"),
});
expect(mocks.reload).not.toHaveBeenCalled();
});
+131 -3
Переглянути файл
@@ -3,6 +3,7 @@ import { useProject } from "@/platform/project";
import { lazyComponent } from "@/ui";
import { registerMenuGroup, registerToolWindow, toolWindowService } from "@/workbench/contributions";
import {
useDotnet,
buildDotnet,
cancelDotnet,
changePackage,
@@ -10,11 +11,22 @@ import {
installTrx,
listPackages,
reloadDotnet,
ensureDotnetModel,
resetDotnet,
runTests,
searchPackages,
selectDotnet,
} from "./store";
import { cancelCentral, checkUpdates, refreshCentral, resetCentral, useCentral } from "./central";
import { cancelSources, changeSource, loadSources, resetSources, type SourceOperation } from "./sources";
import {
addProjectReference,
addProjectsToSolution,
cancelDotnetEdit,
editItems,
removeProjectFromSolution,
removeProjectReference,
} from "./edit";
import { isDotnetProjectPath, isDotnetSolutionPath } from "./target";
import { activateTree } from "./tree";
@@ -40,7 +52,58 @@ export function activate() {
when: "projectOpen",
run: () => reloadDotnet(),
},
{ id: "dotnet.cancel", title: "Cancel .NET Operation", category: "Build", run: () => cancelDotnet() },
{
id: "dotnet.cancel",
title: "Cancel .NET Operation",
category: "Build",
run: () => {
cancelDotnet();
cancelSources();
cancelCentral();
cancelDotnetEdit();
},
},
// #7421: solution and project-reference edits; the Project view menu passes the paths.
{
id: "dotnet.solution.addProject",
title: "Add Existing Project to Solution",
category: "Build",
hidden: true,
run: ({ arg }) => {
const a = arg as { solution: string; projects?: string[] };
return addProjectsToSolution(a.solution, a.projects);
},
},
{
id: "dotnet.solution.removeProject",
title: "Remove Project from Solution",
category: "Build",
hidden: true,
run: ({ arg }) => {
const a = arg as { solution: string; project: string };
return removeProjectFromSolution(a.solution, a.project);
},
},
{
id: "dotnet.project.addReference",
title: "Add Project Reference",
category: "Build",
hidden: true,
run: ({ arg }) => {
const a = arg as { project: string; reference?: string };
return addProjectReference(a.project, a.reference);
},
},
{
id: "dotnet.project.removeReference",
title: "Remove Project Reference",
category: "Build",
hidden: true,
run: ({ arg }) => {
const a = arg as { project: string; reference: string };
return removeProjectReference(a.project, a.reference);
},
},
{
id: "dotnet.select",
title: "Select .NET Project",
@@ -85,7 +148,65 @@ export function activate() {
hidden: true,
run: ({ arg }) => {
const a = arg as { id: string; version: string | null };
return changePackage(a.id, a.version);
// A change can write Directory.Packages.props or the project: re-read where versions live.
const project = useDotnet.getState().selected;
const checked = useCentral.getState().project === project && useCentral.getState().checked;
return Promise.resolve(changePackage(a.id, a.version))
.then(() => (useDotnet.getState().selected === project ? refreshCentral() : undefined))
.then(() => (checked && useDotnet.getState().selected === project ? checkUpdates() : undefined));
},
},
{
id: "dotnet.centralRefresh",
title: "Refresh Central Package Management",
category: "Build",
hidden: true,
run: () => refreshCentral(),
},
{
id: "dotnet.checkUpdates",
title: "Check NuGet Package Updates",
category: "Build",
when: "projectOpen",
run: async () => {
toolWindowService().show(NUGET, true);
const root = useProject.getState().project?.root;
await ensureDotnetModel();
if (useProject.getState().project?.root === root) return checkUpdates();
},
},
{
id: "dotnet.sources",
title: "Refresh NuGet Package Sources",
category: "Build",
hidden: true,
run: () => loadSources(),
},
{
id: "dotnet.sourceChange",
title: "Change NuGet Package Source",
category: "Build",
hidden: true,
run: ({ arg }) => {
const a = arg as { op: SourceOperation; name: string; url?: string };
return changeSource(a.op, a.name, a.url);
},
},
{
id: "dotnet.sources",
title: "Refresh NuGet Package Sources",
category: "Build",
hidden: true,
run: () => loadSources(),
},
{
id: "dotnet.sourceChange",
title: "Change NuGet Package Source",
category: "Build",
hidden: true,
run: ({ arg }) => {
const a = arg as { op: SourceOperation; name: string; url?: string };
return changeSource(a.op, a.name, a.url);
},
},
{
@@ -113,7 +234,11 @@ export function activate() {
},
]),
useProject.subscribe((s, old) => {
if (s.project?.root !== old.project?.root) resetDotnet();
if (s.project?.root !== old.project?.root) {
resetDotnet();
resetSources();
resetCentral();
}
}),
// #5635: build / restore / clean act on the right-clicked solution or project.
registerMenuGroup({
@@ -127,6 +252,7 @@ export function activate() {
{ kind: "action", action: "dotnet.build", arg: path },
{ kind: "action", action: "dotnet.restore", arg: path },
{ kind: "action", action: "dotnet.clean", arg: path },
...editItems(path),
];
},
}),
@@ -135,6 +261,8 @@ export function activate() {
];
return () => {
resetDotnet();
resetSources();
resetCentral();
disposers.reverse().forEach((d) => d());
};
}
+159
Переглянути файл
@@ -0,0 +1,159 @@
// @vitest-environment node
/** Package sources against the real `dotnet` CLI (SDK 10 and 11) and a local folder feed. */
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as platform from "@/platform/dotnet";
import { commands } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { cliSdks, type Sandbox, sandbox } from "./cliTestkit";
import {
changeSource,
configChoices,
loadSources,
parseConfigPaths,
parseSources,
resetSources,
useSources,
} from "./sources";
import { resetDotnet, useDotnet } from "./store";
// Each test packs or restores with the real CLI, slower on a loaded machine.
vi.setConfig({ testTimeout: 120_000 });
const sdks = cliSdks();
it.runIf(sdks.length === 0)("has no SDK 10 or 11 here (CI fails on this)", () => {
expect(process.env.CI).toBeFalsy();
});
describe.each(sdks)("package sources with SDK %s", (sdk) => {
let sb: Sandbox;
let app: string;
beforeEach(() => {
sb = sandbox(sdk);
app = join(sb.root, "app");
mkdirSync(app);
writeFileSync(
join(app, "App.csproj"),
`<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net${sb.major}.0</TargetFramework></PropertyGroup></Project>`,
);
});
afterEach(() => {
sb.dispose();
resetSources();
resetDotnet();
vi.restoreAllMocks();
});
const list = (cwd = app) => parseSources(sb.ok(["nuget", "list", "source", "--format", "detailed"], cwd));
const paths = (cwd = app) => parseConfigPaths(sb.ok(["nuget", "config", "paths"], cwd));
it("lists a disabled source, a local folder and masks nothing it was never given (<clear /> in the workspace file)", () => {
mkdirSync(join(sb.root, "feed"), { recursive: true });
writeFileSync(
join(sb.root, "NuGet.Config"),
`<configuration><packageSources><clear /><add key="local" value="./feed" /><add key="priv" value="https://example.invalid/v3/index.json" /></packageSources>` +
`<disabledPackageSources><add key="priv" value="true" /></disabledPackageSources>` +
`<packageSourceCredentials><priv><add key="Username" value="bob" /><add key="ClearTextPassword" value="s3cret-pw" /></priv></packageSourceCredentials></configuration>`,
);
const sources = list();
expect(sources.map((s) => [s.name, s.enabled])).toEqual([
["local", true],
["priv", false],
]);
expect(JSON.stringify(sources)).not.toContain("s3cret-pw");
expect(paths().some((p) => p.endsWith("NuGet.Config") && p.includes("ws"))).toBe(true);
});
it("merges levels: a nearer file adds to the user-wide one and the workspace file is the default target", () => {
writeFileSync(
join(sb.root, "NuGet.Config"),
`<configuration><packageSources><add key="ws" value="./feed" /></packageSources></configuration>`,
);
// The user-wide file is created by the CLI on first use; add a user source through it.
sb.ok(["nuget", "add", "source", "https://user.example.invalid/i.json", "-n", "user-feed"], app);
const names = list().map((s) => s.name);
expect(names).toEqual(expect.arrayContaining(["ws", "user-feed"]));
const choices = configChoices(paths(), sb.root);
expect(choices[0]).toMatchObject({ scope: "workspace", exists: true });
expect(choices.at(-1)!.scope).toBe("user");
expect(choices.at(-1)!.path.startsWith(sb.home)).toBe(true);
});
it("creates the workspace file when none exists and adds, disables, enables and removes through the store", async () => {
const empty = sandbox(sdk);
try {
const proj = join(empty.root, "p");
mkdirSync(proj);
writeFileSync(join(proj, "P.csproj"), "<Project />");
mkdirSync(join(empty.root, "feed"));
vi.spyOn(platform, "dotnet").mockImplementation(async (args, cwd) => empty.ok(args, cwd));
vi.spyOn(commands, "fsCreateFileBytes").mockImplementation(async (path, b64) => {
writeFileSync(path, Buffer.from(b64, "base64"));
return { status: "ok", data: null };
});
useProject.setState({ project: { root: empty.root } as never });
useDotnet.setState({
selected: join(proj, "P.csproj"),
model: { projects: [{ path: join(proj, "P.csproj") } as never], solutions: [] },
});
await loadSources();
expect(useSources.getState().error).toBe("");
const target = join(empty.root, "NuGet.Config").replace(/\\/g, "/");
expect(useSources.getState().target).toBe(target);
expect(existsSync(target)).toBe(false);
await changeSource("add", "local", join(empty.root, "feed"));
expect(useSources.getState().error).toBe("");
expect(readFileSync(target, "utf8")).toContain('key="local"');
expect(useSources.getState().sources.find((s) => s.name === "local")?.enabled).toBe(true);
await changeSource("disable", "local");
expect(useSources.getState().sources.find((s) => s.name === "local")?.enabled).toBe(false);
await changeSource("enable", "local");
expect(useSources.getState().sources.find((s) => s.name === "local")?.enabled).toBe(true);
await changeSource("remove", "local");
expect(useSources.getState().sources.some((s) => s.name === "local")).toBe(false);
// The created file carries no <clear />: the user-wide nuget.org source stays in effect.
expect(useSources.getState().sources.map((s) => s.name)).toContain("nuget.org");
} finally {
empty.dispose();
}
});
it("blocks edits to a source absent from the selected config and keeps the list", async () => {
vi.spyOn(platform, "dotnet").mockImplementation(async (args, cwd) => sb.ok(args, cwd));
useProject.setState({ project: { root: sb.root } as never });
useDotnet.setState({
selected: join(app, "App.csproj"),
model: { projects: [{ path: join(app, "App.csproj") } as never], solutions: [] },
});
await loadSources();
const before = useSources.getState().sources;
await changeSource("remove", "no-such-source");
expect(useSources.getState().error).toContain("Choose the NuGet.Config file that defines this source");
expect(useSources.getState().sources).toEqual(before);
expect(useSources.getState().busy).toBe(false);
});
it("search and install keep using the effective sources (a local feed packed here)", () => {
const feed = join(sb.root, "feed");
sb.pack(feed, "Demo.Pkg", ["1.0.0", "2.0.0-beta.1"]);
writeFileSync(
join(sb.root, "NuGet.Config"),
`<configuration><packageSources><clear /><add key="local" value="./feed" /></packageSources></configuration>`,
);
expect(sb.ok(["package", "search", "Demo.Pkg", "--format", "json"], app)).toContain("Demo.Pkg");
sb.ok(["add", join(app, "App.csproj"), "package", "Demo.Pkg", "--version", "1.0.0"], app);
expect(readFileSync(join(app, "App.csproj"), "utf8")).toContain("Demo.Pkg");
}, 240_000);
it("fails with the CLI's message when the SDK is missing or the file is malformed", () => {
const bad = join(sb.root, "bad");
mkdirSync(bad, { recursive: true });
writeFileSync(join(bad, "NuGet.Config"), "<configuration><packageSources>");
const r = sb.run(["nuget", "list", "source", "--format", "detailed"], bad);
expect(r.code).not.toBe(0);
expect(r.out).toMatch(/NuGet\.Config|XML|configuration/i);
});
});
+86
Переглянути файл
@@ -0,0 +1,86 @@
import { describe, expect, it } from "vitest";
import { configChoices, maskUrl, parseConfigPaths, parseSources, sourceArgs } from "./sources";
describe("package source parsing", () => {
it("reads enabled and disabled sources, names with spaces and local folders", () => {
const text = [
"Registered Sources:",
"",
" 1. nuget.org [Enabled]",
" https://api.nuget.org/v3/index.json",
" 2. My Feed [Disabled]",
" /srv/feed",
"",
].join("\n");
expect(parseSources(text)).toEqual([
{ name: "nuget.org", url: "https://api.nuget.org/v3/index.json", enabled: true },
{ name: "My Feed", url: "/srv/feed", enabled: false },
]);
});
it("reads CRLF output and an empty list", () => {
expect(parseSources("Registered Sources:\r\n\r\n 1. a [Enabled]\r\n /f\r\n")).toHaveLength(1);
expect(parseSources("No sources found.\n")).toEqual([]);
});
it("masks credentials embedded in a source URL", () => {
expect(maskUrl("https://user:[email protected]/v3/index.json")).toBe(
"https://***@pkgs.example.com/v3/index.json",
);
expect(maskUrl("https://[email protected]/i.json")).toBe("https://***@pkgs.example.com/i.json");
expect(maskUrl("https://pkgs.example.com/a@b")).toBe("https://pkgs.example.com/a@b");
const [source] = parseSources(" 1. p [Enabled]\n https://u:[email protected]/i.json\n");
expect(source!.url).not.toContain("ClearTextPassword");
});
it("reads the config path list, ignoring other lines", () => {
expect(parseConfigPaths("/w/NuGet.Config\nC:\\Users\\a\\NuGet.Config\nwarning: x\n")).toEqual([
"/w/NuGet.Config",
"C:\\Users\\a\\NuGet.Config",
]);
});
});
describe("choosing the NuGet.Config to write", () => {
it("defaults to the workspace file nearest the root, user-wide files last", () => {
expect(
configChoices(["/w/app/NuGet.Config", "/w/NuGet.Config", "/home/u/.nuget/NuGet/NuGet.Config"], "/w"),
).toEqual([
{ path: "/w/NuGet.Config", scope: "workspace", exists: true },
{ path: "/w/app/NuGet.Config", scope: "workspace", exists: true },
{ path: "/home/u/.nuget/NuGet/NuGet.Config", scope: "user", exists: true },
]);
});
it("offers a new root file when no workspace file exists, never defaulting to the user file", () => {
const [first, second] = configChoices(["/home/u/.nuget/NuGet/NuGet.Config"], "/w");
expect(first).toEqual({ path: "/w/NuGet.Config", scope: "workspace", exists: false });
expect(second!.scope).toBe("user");
});
it("keeps distinct POSIX directories separate", () => {
const files = configChoices(["/home/user/project/NuGet.Config"], "/home/user/Project");
expect(files.map((file) => file.scope)).toEqual(["workspace", "user"]);
});
it("matches Windows paths case-insensitively", () => {
expect(configChoices(["c:\\Repo\\nuget.config"], "C:\\Repo")[0]!.scope).toBe("workspace");
});
});
describe("dotnet nuget arguments", () => {
it("always names the file", () => {
expect(sourceArgs("add", "/w/NuGet.Config", "n", "/f")).toEqual([
"nuget",
"add",
"source",
"/f",
"--name",
"n",
"--configfile",
"/w/NuGet.Config",
]);
expect(sourceArgs("disable", "/w/NuGet.Config", "n")).toEqual([
"nuget",
"disable",
"source",
"n",
"--configfile",
"/w/NuGet.Config",
]);
});
});
+210
Переглянути файл
@@ -0,0 +1,210 @@
import { create } from "zustand";
import { call, commands, IpcError } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { toBase64 } from "@/platform/base64";
import { dotnet } from "@/platform/dotnet";
import { dirname, useProject } from "@/platform/project";
import { selectedProject, useDotnet } from "./store";
export interface PackageSource {
name: string;
url: string;
enabled: boolean;
}
export interface ConfigFile {
path: string;
/** Where the file lives: next to the project, or in the user / machine-wide hierarchy. */
scope: "workspace" | "user";
/** False for the `NuGet.Config` offered next to the root when no file exists yet. */
exists: boolean;
}
interface State {
sources: PackageSource[];
configs: ConfigFile[];
/** The NuGet.Config the next add / enable / disable / remove writes to. */
target: string;
targetNames: string[];
project: string;
busy: boolean;
error: string;
}
const initial: State = { sources: [], configs: [], target: "", targetNames: [], project: "", busy: false, error: "" };
export const useSources = create<State>(() => initial);
let controller: AbortController | undefined;
let generation = 0;
export function resetSources() {
generation++;
controller?.abort();
useSources.setState(initial);
}
/** A password or token written into a source URL (`https://user:secret@host`) is never shown. */
export function maskUrl(url: string): string {
return url.replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^/@\s]+@/gi, "$1***@");
}
/** `dotnet nuget list source --format detailed`: a numbered `name [Enabled|Disabled]` line, then the URL line. */
export function parseSources(text: string): PackageSource[] {
const result: PackageSource[] = [];
const lines = text.split(/\r?\n/);
for (let i = 0; i < lines.length; i++) {
const head = /^\s*\d+\.\s+(.+?)\s+\[(Enabled|Disabled)(?:,[^\]]*)?\]\s*$/.exec(lines[i]!);
if (!head) continue;
result.push({ name: head[1]!, url: maskUrl((lines[i + 1] ?? "").trim()), enabled: head[2] === "Enabled" });
}
return result;
}
/** `dotnet nuget config paths`: one file per line, nearest first. */
export function parseConfigPaths(text: string): string[] {
return text
.split(/\r?\n/)
.map((l) => l.trim())
.filter((l) => /^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(l));
}
const norm = (p: string) => p.replace(/\\/g, "/").replace(/\/+$/, "");
function inside(path: string, dir: string): boolean {
const file = norm(path);
const root = norm(dir);
if (/^[a-z]:$|^[a-z]:\/|^\/\//i.test(root)) return file.toLowerCase().startsWith(`${root.toLowerCase()}/`);
return file.startsWith(`${root}/`);
}
/**
* The files a source can be written to: those under the workspace root, nearest to the
* root first, with `<root>/NuGet.Config` offered (and created on first write) when none
* exists, then the user-wide ones. The default is the first workspace file.
*/
export function configChoices(paths: string[], root: string): ConfigFile[] {
const workspace = paths.filter((p) => inside(p, root));
const fallback = `${norm(root)}/NuGet.Config`;
const files: ConfigFile[] = (workspace.length ? workspace : [fallback]).map((path) => ({
path,
scope: "workspace" as const,
exists: workspace.length > 0,
}));
files.sort((a, b) => norm(a.path).length - norm(b.path).length);
return [
...files,
...paths.filter((p) => !inside(p, root)).map((path) => ({ path, scope: "user" as const, exists: true })),
];
}
export type SourceOperation = "add" | "enable" | "disable" | "remove";
export function sourceArgs(op: SourceOperation, config: string, name: string, url = ""): string[] {
return op === "add"
? ["nuget", "add", "source", url, "--name", name, "--configfile", config]
: ["nuget", op, "source", name, "--configfile", config];
}
export const EMPTY_CONFIG = toBase64(
new TextEncoder().encode('<?xml version="1.0" encoding="utf-8"?>\n<configuration>\n</configuration>\n'),
);
async function run(work: (signal: AbortSignal, cwd: string, root: string, project: string) => Promise<Partial<State>>) {
const project = selectedProject();
const root = useProject.getState().project?.root;
if (!project || !root) return;
controller?.abort();
const current = ++generation;
const abort = new AbortController();
controller = abort;
const isCurrent = () => selectedProject()?.path === project.path && useProject.getState().project?.root === root;
const stopIfChanged = () => {
if (!isCurrent()) abort.abort();
};
const stopProject = useProject.subscribe(stopIfChanged);
const stopSelection = useDotnet.subscribe(stopIfChanged);
useSources.setState({ busy: true, error: "" });
try {
const patch = await work(abort.signal, dirname(project.path), root, project.path);
if (current === generation && !abort.signal.aborted) useSources.setState(patch);
} catch (e) {
if (current === generation && !abort.signal.aborted) useSources.setState({ error: maskUrl(String(e)) });
} finally {
stopProject();
stopSelection();
if (current === generation) {
controller = undefined;
useSources.setState({ busy: false });
}
}
}
async function namesInConfig(file: ConfigFile | undefined, cwd: string, signal: AbortSignal): Promise<string[]> {
if (!file?.exists) return [];
const list = await dotnet(
["nuget", "list", "source", "--format", "detailed", "--configfile", file.path],
cwd,
signal,
);
return parseSources(list).map((source) => source.name);
}
async function load(
cwd: string,
root: string,
project: string,
signal: AbortSignal,
keep: string,
): Promise<Partial<State>> {
const [list, paths] = await Promise.all([
dotnet(["nuget", "list", "source", "--format", "detailed"], cwd, signal),
dotnet(["nuget", "config", "paths"], cwd, signal),
]);
const configs = configChoices(parseConfigPaths(paths), root);
const target = configs.find((config) => config.path === keep) ?? configs[0];
return {
project,
sources: parseSources(list),
configs,
target: target?.path ?? "",
targetNames: await namesInConfig(target, cwd, signal),
};
}
export function loadSources() {
return run((signal, cwd, root, project) => {
const current = useSources.getState();
return load(cwd, root, project, signal, current.project === project ? current.target : "");
});
}
export function selectSourceConfig(path: string) {
const { configs, project } = useSources.getState();
const config = configs.find((candidate) => candidate.path === path);
if (!config || selectedProject()?.path !== project) return;
useSources.setState({ target: path, targetNames: [] });
return run(async (signal, cwd) => ({ targetNames: await namesInConfig(config, cwd, signal) }));
}
export function cancelSources() {
controller?.abort();
}
export function changeSource(op: SourceOperation, name: string, url = "") {
const { project, target, configs, targetNames } = useSources.getState();
const config = configs.find((candidate) => candidate.path === target);
if (!config || !name.trim() || selectedProject()?.path !== project) return;
const address = url.trim();
if (op === "add" && maskUrl(address) !== address) {
useSources.setState({ error: tx("Remove credentials from the package source URL before adding it.") });
return;
}
if (op !== "add" && !targetNames.includes(name)) {
useSources.setState({ error: tx("Choose the NuGet.Config file that defines this source to change it.") });
return;
}
return run(async (signal, cwd, root, activeProject) => {
if (op === "add" && !config.exists) {
// The default template adds <clear />, which hides the inherited sources.
try {
await call(commands.fsCreateFileBytes(target, EMPTY_CONFIG));
} catch (e) {
if (!(e instanceof IpcError) || e.kind !== "alreadyExists") throw e;
}
}
await dotnet(sourceArgs(op, target, name.trim(), address), cwd, signal);
return load(cwd, root, activeProject, signal, target);
});
}
+78
Переглянути файл
@@ -99,6 +99,84 @@ describe("the .NET solution tree", () => {
["App", "/repo/src/App/App.csproj", true],
["App.Tests", "/repo/tests/App.Tests/App.Tests.csproj", true],
]);
// The group node's context menu is its `.sln`'s (#7421).
expect(solution.menuPath).toBe("/repo/App.sln");
});
it("lists a project's packages, projects, frameworks and analyzers under Dependencies", async () => {
indexed(["/repo/App.sln"]);
vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({
projects: [
{
...project("/repo/App/App.csproj", "App"),
packages: [{ id: "Newtonsoft.Json", version: "13.0.3" }],
references: ["/repo/Lib/Lib.csproj"],
frameworkReferences: ["Microsoft.NETCore.App"],
analyzers: ["Analyzers.dll"],
},
project("/repo/Lib/Lib.csproj", "Lib"),
],
solutions: [{ path: "/repo/App.sln", projects: ["/repo/App/App.csproj", "/repo/Lib/Lib.csproj"] }],
});
dispose = activateTree();
await vi.waitFor(() => expect(dotnetRoots()).toHaveLength(1));
const [app, lib] = useProjectViewRoots.getState().roots.get("dotnetSolution:/repo/App.sln")!.children!;
expect(lib!.children).toBeUndefined();
const deps = app!.children!;
expect(deps.map((d) => d.label)).toEqual(["Dependencies"]);
expect(deps[0]!.children!.map((g) => [g.label, g.children!.map((c) => [c.label, c.detail ?? ""])])).toEqual([
["Packages", [["Newtonsoft.Json", "13.0.3"]]],
["Projects", [["Lib", ""]]],
["Frameworks", [["Microsoft.NETCore.App", ""]]],
["Analyzers", [["Analyzers.dll", ""]]],
]);
});
it("nests solution folders with their projects and solution items under the solution", async () => {
indexed(["/repo/App.sln"]);
vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({
projects: [project("/repo/src/libs/Core/Core.csproj", "Core"), project("/repo/App/App.csproj", "App")],
solutions: [
{
path: "/repo/App.sln",
projects: ["/repo/src/libs/Core/Core.csproj", "/repo/App/App.csproj"],
folders: [
{ path: ["src"], files: ["/repo/README.md"], projects: [] },
{ path: ["src", "libs"], files: [], projects: ["/repo/src/libs/Core/Core.csproj"] },
{ path: ["empty"], files: [], projects: [] },
],
},
],
});
dispose = activateTree();
await vi.waitFor(() => expect(dotnetRoots()).toHaveLength(1));
type Shape = { label: string; file?: boolean; children?: readonly Shape[] };
const shape = (e: Shape): unknown =>
e.children ? [e.label, e.children.map(shape)] : [e.label, e.file ? "file" : "node"];
const solution = useProjectViewRoots.getState().roots.get("dotnetSolution:/repo/App.sln")!;
expect(solution.children!.map(shape)).toEqual([
[
"src",
[
["libs", [["Core", "file"]]],
["README.md", "file"],
],
],
["empty", []],
["App", "file"],
]);
});
it("lists a solution that only has folders", async () => {
indexed(["/repo/App.sln"]);
vi.spyOn(platform, "dotnetWorkspace").mockResolvedValue({
projects: [],
solutions: [
{ path: "/repo/App.sln", projects: [], folders: [{ path: ["Items"], files: ["/repo/a.txt"], projects: [] }] },
],
});
dispose = activateTree();
await vi.waitFor(() => expect(dotnetRoots()).toHaveLength(1));
});
it("shows the solution label through the tx template", async () => {
+123 -9
Переглянути файл
@@ -12,11 +12,15 @@
* ride on one placeholder root's grey detail text — scanning while the shared
* scan runs, the failure after it failed; idle and empty means no root at all.
*/
import type { DotnetWorkspace } from "@/platform/dotnet";
import type { DotnetProject, DotnetSolution, DotnetWorkspace } from "@/platform/dotnet";
import { tx } from "@/platform/i18n";
import { call, commands, onIdeEvent, type ProjectInfo } from "@/platform/ipc";
import { basename, dirname, useProject } from "@/platform/project";
import { registerProjectViewRoot, type ProjectViewRootContribution } from "@/workbench/contributions";
import {
registerProjectViewRoot,
type ProjectViewRootContribution,
type ProjectViewRootEntry,
} from "@/workbench/contributions";
import { ensureDotnetModel, useDotnet } from "./store";
import { isDotnetProjectPath, isDotnetSolutionPath } from "./target";
@@ -63,6 +67,112 @@ const stateRoot = (detail: string): ProjectViewRootContribution => ({
detail,
});
/**
* The Dependencies node of a project (#7429): its direct packages, project references and framework
* references, from the one MSBuild evaluation the workspace scan already ran (no process per
* expansion). Empty groups are left out, and a project with none has no node. Transitive packages
* are not in a static evaluation; they need a restore's assets file.
*/
export function dependencies(
project: DotnetProject | undefined,
nameOf: (path: string) => string,
): ProjectViewRootEntry[] {
if (!project) return [];
const rows = (
items: readonly { id?: string; label: string; detail?: string }[],
icon: string,
): ProjectViewRootEntry[] => items.map((i) => ({ ...i, icon, leaf: true }));
const groups: ProjectViewRootEntry[] = [
{
id: "packages",
label: tx`Packages`,
icon: "package",
children: rows(
project.packages.map((p) => ({ label: p.id, detail: p.version })),
"package",
),
},
{
id: "projects",
label: tx`Projects`,
icon: ICON,
children: rows(
project.references.map((reference) => ({ id: encodeURIComponent(reference), label: nameOf(reference) })),
ICON,
),
},
{
id: "frameworks",
label: tx`Frameworks`,
icon: "library",
children: rows(
(project.frameworkReferences ?? []).map((f) => ({ label: f })),
"library",
),
},
{
id: "analyzers",
label: tx`Analyzers`,
icon: "library",
children: rows(
(project.analyzers ?? []).map((analyzer) => ({ id: encodeURIComponent(analyzer), label: basename(analyzer) })),
"library",
),
},
].filter((g) => g.children.length);
return groups.length
? [
{
id: "dependencies",
label: tx`Dependencies`,
detail: project.frameworks.length > 1 ? (project.evaluatedFramework ?? project.frameworks[0]) : undefined,
icon: "library",
children: groups,
},
]
: [];
}
/**
* A solution's children (#7431): its solution folders as nested virtual folder nodes, each with
* its projects and its solution items (files that open in the editor), then the projects that sit
* outside every folder. A solution without folders lists its projects flat, as before.
*/
export function solutionChildren(
solution: DotnetSolution,
leaf: (path: string) => ProjectViewRootEntry,
): ProjectViewRootEntry[] {
const folders = solution.folders ?? [];
const inFolders = new Set(folders.flatMap((f) => f.projects));
const file = (path: string): ProjectViewRootEntry => ({
label: basename(path),
icon: "file",
path,
file: true,
});
const roots: ProjectViewRootEntry[] = [];
const foldersByPath = new Map<string, ProjectViewRootEntry[]>();
const pathId = (path: string[]) => path.map(encodeURIComponent).join("/");
// SLNX can declare "/src/libs/" without a separate element for "/src/".
for (const folder of folders) {
let siblings = roots;
for (const [index, name] of folder.path.entries()) {
const id = pathId(folder.path.slice(0, index + 1));
let children = foldersByPath.get(id);
if (!children) {
children = [];
foldersByPath.set(id, children);
siblings.push({ id: `folder:${id}`, label: name, icon: "folder", children });
}
siblings = children;
}
}
for (const folder of folders) {
foldersByPath.get(pathId(folder.path))?.push(...folder.projects.map(leaf), ...folder.files.map(file));
}
return [...roots, ...solution.projects.filter((project) => !inFolders.has(project)).map(leaf)];
}
/**
* One group per solution (a leaf per project), standalone projects as roots of
* their own. With the model still empty, the one placeholder root carries the
@@ -95,28 +205,32 @@ export function treeRoots(
// node above the folder. Nested ones (a .NET part of a larger repository) stay in their folders.
const topLevel = (path: string) => contentRoots.includes(dirname(path));
const projectName = (path: string) => model.projects.find((p) => p.path === path)?.name ?? solutionName(path);
const leaf = (path: string) => ({ label: projectName(path), icon: ICON, path, file: true });
const leaf = (path: string): ProjectViewRootEntry => {
const children = dependencies(
model.projects.find((p) => p.path === path),
projectName,
);
return { label: projectName(path), icon: ICON, path, file: true, ...(children.length && { children }) };
};
const grouped = new Set(model.solutions.flatMap((s) => s.projects));
const roots: ProjectViewRootContribution[] = [];
for (const solution of model.solutions) {
if (!solution.projects.length || !topLevel(solution.path)) continue;
if (!(solution.projects.length || solution.folders?.length) || !topLevel(solution.path)) continue;
roots.push({
id: solutionId(solution.path),
label: tx`Solution '${solutionName(solution.path)}'`,
icon: ICON,
menuPath: solution.path,
beforeProject: true,
children: solution.projects.map(leaf),
children: solutionChildren(solution, leaf),
});
}
for (const project of model.projects)
if (!grouped.has(project.path) && topLevel(project.path))
roots.push({
id: projectId(project.path),
label: project.name,
icon: ICON,
beforeProject: true,
path: project.path,
file: true,
...leaf(project.path),
});
return roots.map((root, i) => ({ ...root, order: -200 + i }));
}
+4
Переглянути файл
@@ -72,12 +72,16 @@ describe("standalone .NET tool window removal", () => {
"dotnet.restore /repo/src/App/App.csproj",
"dotnet.clean /repo/src/App/App.csproj",
"separator",
"dotnet.project.addReference [object Object]",
"separator",
]);
expect(actions("/repo/Demo.sln")).toEqual([
"dotnet.build /repo/Demo.sln",
"dotnet.restore /repo/Demo.sln",
"dotnet.clean /repo/Demo.sln",
"separator",
"dotnet.solution.addProject [object Object]",
"separator",
]);
expect(actions("/repo/src/App/Program.cs")).toEqual([]);
});
+21 -1
Переглянути файл
@@ -146,6 +146,26 @@ function sortedGroups(groups: readonly LibraryGroup[]): LibraryGroup[] {
);
}
/** Last folder name of the directory holding `path` (`/a/.venv/Lib` or `E:\a\.venv\Lib` → `.venv`). */
function parentName(path: string): string {
const parts = path.split(/[\\/]+/).filter(Boolean);
return parts[parts.length - 2] ?? "";
}
/**
* "library root", or for a folder sharing its name with a sibling (a venv's `Lib` beside the
* base interpreter's, #7444) also the parent folder (`note`), as IDEA shows a root's location.
*/
export function rootDetail(
roots: readonly { name: string; path: string }[],
root: { name: string; path: string },
): { detail: string; note?: string } {
const same = roots.filter((r) => r.name === root.name);
if (same.length < 2) return { detail: "library root" };
const parent = parentName(root.path);
return parent ? { detail: "library root", note: parent } : { detail: "library root" };
}
/** The "External Libraries" node for `groups` (`< Python 3.12 (.venv) >` › `python3.12`, `site-packages`). */
export function librariesRoot(groups: readonly LibraryGroup[]): ProjectViewRootContribution | null {
if (!groups.length) return null;
@@ -163,7 +183,7 @@ export function librariesRoot(groups: readonly LibraryGroup[]): ProjectViewRootC
label: r.name,
icon: isArchiveRoot(r.path) ? "file-archive" : "folder-library",
path: r.path,
detail: "library root",
...rootDetail(g.roots, r),
})),
})),
};
+57 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it } from "vitest";
import { isLibraryPath, setLibraryRoots } from "@/editor/api";
import { librariesRoot, openedLibraryGroup, touchesManifest } from "./index";
import { librariesRoot, openedLibraryGroup, rootDetail, touchesManifest } from "./index";
import { mergeLibraryGroups } from "@/platform/libraries";
describe("External Libraries", () => {
@@ -185,4 +185,60 @@ describe("External Libraries", () => {
group("maven", "/m2/dep.jar!"),
]);
});
describe("same-named library roots (#7444)", () => {
const uvVenv = [
{ name: "Lib", path: "D:\\uv\\cpython-3.12-windows-x86_64-none\\Lib" },
{ name: "Lib", path: "E:\\proj\\.venv\\Lib" },
{ name: "site-packages", path: "E:\\proj\\.venv\\Lib\\site-packages" },
{ name: "DLLs", path: "D:\\uv\\cpython-3.12-windows-x86_64-none\\DLLs" },
];
it("keeps the plain detail for unique names", () => {
for (const r of uvVenv.slice(2)) expect(rootDetail(uvVenv, r)).toEqual({ detail: "library root" });
expect(rootDetail([], { name: "a", path: "/a" })).toEqual({ detail: "library root" });
});
it("names the parent folder (Windows paths)", () => {
expect(rootDetail(uvVenv, uvVenv[0]!)).toEqual({
detail: "library root",
note: "cpython-3.12-windows-x86_64-none",
});
expect(rootDetail(uvVenv, uvVenv[1]!)).toEqual({ detail: "library root", note: ".venv" });
});
it("handles POSIX paths, three siblings and a root without a parent", () => {
const roots = [
{ name: "lib", path: "/a/lib" },
{ name: "lib", path: "/b/lib" },
{ name: "lib", path: "/c/lib" },
{ name: "lib", path: "/lib" },
];
const out = roots.map((r) => rootDetail(roots, r));
expect(out.map((o) => o.note)).toEqual(["a", "b", "c", undefined]);
});
it("finds the parent folder with mixed and UNC separators", () => {
const roots = ["C:\\a\\Lib", "C:/b/Lib", "\\\\server\\share\\c\\Lib", "/d/Lib", "C:\\e/Lib", "/f/Lib"].map(
(path) => ({ name: "Lib", path }),
);
const out = roots.map((r) => rootDetail(roots, r));
expect(out.map((o) => o.note)).toEqual(["a", "b", "c", "d", "e", "f"]);
});
it("treats names case-sensitively and ignores trailing separators", () => {
const roots = [
{ name: "Lib", path: "C:\\py\\Lib\\" },
{ name: "lib", path: "C:\\py2\\lib" },
];
expect(roots.map((r) => rootDetail(roots, r))).toEqual([{ detail: "library root" }, { detail: "library root" }]);
});
it("reaches the tree nodes of the contribution", () => {
const kids = librariesRoot([{ name: "Python 3.12 (.venv)", kind: "python", roots: uvVenv }])!.children![0]!
.children!;
expect(kids.map((c) => c.detail)).toEqual(Array(4).fill("library root"));
expect(kids.map((c) => c.note)).toEqual(["cpython-3.12-windows-x86_64-none", ".venv", undefined, undefined]);
});
});
});
+18
Переглянути файл
@@ -73,6 +73,24 @@ it("keeps markers on their lines while typing and hides them when the entry goes
await vi.waitFor(() => expect(button()).toBeNull());
});
it("leaves a kept entry's markers where the edits moved them when the store notifies again", async () => {
const { entry } = setup();
await vi.waitFor(() => expect(button()).not.toBeNull());
view!.dispatch({ changes: { from: 0, insert: "\n" } });
const dispatch = vi.spyOn(view!, "dispatch");
// The changed file is reindexing: the store keeps its entry and notifies for other paths (#7422).
// Placing that entry again would put its markers back on their old lines.
usePluginMarkers.setState({
entries: new Map([
[entry.path, entry],
["/p/Other.xml", { ...entry, path: "/p/Other.xml" }],
]),
});
await new Promise((r) => setTimeout(r, 0));
expect(dispatch).not.toHaveBeenCalled();
expect(button()).not.toBeNull();
});
it("merges a line's targets and offers a chooser for several", async () => {
const { entry, target } = setup();
const other = { ...target, path: "/p/Other.java" };
+11 -7
Переглянути файл
@@ -110,7 +110,9 @@ export function indexedMarkers(path: string): Extension {
INDEXED_MARKERS_THEME,
ViewPlugin.fromClass(
class {
last: FileMarkers | undefined;
/** The entry the field shows (null: none yet, or icons or settings changed). The field maps
* its markers through edits, so the same entry is never placed again on an edited text. */
applied: FileMarkers | undefined | null = null;
queued = false;
disposed = false;
generation = 0;
@@ -121,13 +123,13 @@ export function indexedMarkers(path: string): Extension {
constructor(readonly view: EditorView) {
this.off = usePluginMarkers.subscribe(() => this.schedule());
this.offIcons = onMarkerIconsChanged(() => {
this.last = undefined;
this.applied = null;
this.schedule();
});
this.unwatch = watchPluginMarkers(path);
this.prefs = useProject.subscribe((s, prev) => {
if (s.settings !== prev.settings) {
this.last = undefined;
this.applied = null;
this.schedule();
}
});
@@ -136,8 +138,10 @@ export function indexedMarkers(path: string): Extension {
update(update: ViewUpdate) {
const appearanceChanged =
update.startState.field(localAppearanceField, false) !== update.state.field(localAppearanceField, false);
if (appearanceChanged) this.schedule();
if (update.docChanged || appearanceChanged) this.last = undefined;
if (appearanceChanged) {
this.applied = null;
this.schedule();
}
}
schedule() {
if (this.queued || this.disposed) return;
@@ -149,12 +153,12 @@ export function indexedMarkers(path: string): Extension {
}
refresh() {
const entry = usePluginMarkers.getState().entries.get(path);
if (entry && entry === this.last) return;
this.last = entry;
if (entry === this.applied) return;
const doc = this.view.state.doc;
const generation = ++this.generation;
void resolveIcons(entry).then((icons) => {
if (this.disposed || generation !== this.generation || this.view.state.doc !== doc) return;
this.applied = entry;
this.view.dispatch({ effects: setMarkers.of(markersOf(this.view, entry, icons)) });
});
}
+2 -1
Переглянути файл
@@ -55,7 +55,8 @@ it("withdraws old interactive markers on reload and does not refresh on idle sta
expect(mock.markers).toHaveBeenCalledTimes(calls);
mock.markers.mockResolvedValue({ status: "ok", data: [] });
mock.event!({ type: "documentIndexesChanged" });
expect(view.dom.querySelector(".cm-openidea-iconArea .cm-plugin-mapping-button")).toBeNull();
// Shown until the new markers arrive: an empty area would collapse and shift the code (#7422).
expect(view.dom.querySelector(".cm-openidea-iconArea .cm-plugin-mapping-button")).not.toBeNull();
await vi.advanceTimersByTimeAsync(450);
expect(view.dom.querySelector(".cm-openidea-iconArea .cm-plugin-mapping-button")).toBeNull();
view.destroy();
+2 -1
Переглянути файл
@@ -128,8 +128,9 @@ class MarkersPlugin {
) {
const offBackend = pluginsBackend().onEvent((event) => {
if (event.type !== "documentIndexesChanged") return;
// The shown markers stay (mapped through edits) until the new ones arrive: clearing them
// collapsed the icon area after every edit and shifted the code sideways (#7422).
this.generation++;
this.view.dispatch({ effects: setMarkers.of([]) });
this.schedule();
});
const offIcons = onMarkerIconsChanged(() => {
+30 -11
Переглянути файл
@@ -1,5 +1,5 @@
import { afterEach, expect, it, vi } from "vitest";
import { watchPluginMarkers, usePluginMarkers, invalidatePluginMarkers } from "./markerStore";
import { watchPluginMarkers, usePluginMarkers, invalidatePluginMarkers, settlePluginMarkers } from "./markerStore";
import { invalidateNavigationProviders } from "@/editor/api";
const mock = vi.hoisted(() => vi.fn());
vi.mock("@/platform/ipc", async (original) => ({
@@ -34,20 +34,39 @@ it("discards in-flight results after the project/provider epoch changes", async
await vi.advanceTimersByTimeAsync(250);
expect(usePluginMarkers.getState().entries.size).toBe(0);
});
it("invalidates both changed files and markers targeting them", () => {
it("keeps the markers of changed files, and markers targeting them, until their reindex settles", async () => {
vi.useFakeTimers();
const range = { start: { line: 0, col: 0 }, end: { line: 0, col: 1 } };
const entry = {
path: "/p/A.xml",
version: 1,
markers: [{ range, targets: [{ path: "/p/A.java", range }], pluginId: "p", icon: null }],
};
mock.mockResolvedValue({ status: "ok", data: [entry] });
off.push(watchPluginMarkers("/p/A.xml"));
await vi.advanceTimersByTimeAsync(250);
expect(usePluginMarkers.getState().entries.get("/p/A.xml")).toEqual(entry);
invalidatePluginMarkers(["/p/A.java"]);
// While reindexing, the host has no current markers for it (#7422).
mock.mockResolvedValue({ status: "ok", data: [] });
invalidateNavigationProviders();
await vi.advanceTimersByTimeAsync(250);
expect(usePluginMarkers.getState().entries.get("/p/A.xml")).toEqual(entry);
settlePluginMarkers(["/p/A.java"]);
invalidateNavigationProviders();
await vi.advanceTimersByTimeAsync(250);
expect(usePluginMarkers.getState().entries.size).toBe(0);
});
it("drops every marker at once when the providers are reset", () => {
const range = { start: { line: 0, col: 0 }, end: { line: 0, col: 1 } };
usePluginMarkers.setState({
entries: new Map([
[
"/p/A.xml",
{
path: "/p/A.xml",
version: 1,
markers: [{ range, targets: [{ path: "/p/A.java", range }], pluginId: "p", icon: null }],
},
],
["/p/A.xml", { path: "/p/A.xml", version: 1, markers: [{ range, targets: [], pluginId: "p", icon: null }] }],
]),
});
invalidatePluginMarkers(["/p/A.java"]);
invalidatePluginMarkers();
expect(usePluginMarkers.getState().entries.size).toBe(0);
});
+34 -4
Переглянути файл
@@ -12,6 +12,8 @@ let running = false;
let session = 0;
let again = false;
let off: (() => void) | undefined;
/** Paths whose markers are kept, mapped through edits, until their reindex settles. */
const stale = new Set<string>();
function schedule() {
again = true;
if (!timer && !running)
@@ -34,6 +36,7 @@ async function refresh() {
if (epoch !== navigationEpoch() || current !== session) return;
for (const result of results) {
if (!visible.has(result.path)) continue;
stale.delete(result.path);
const previous = entries.get(result.path);
entries.set(
result.path,
@@ -41,6 +44,13 @@ async function refresh() {
);
}
}
// A changed file has no markers until it is indexed again: keep showing the ones it had,
// so the icon area doesn't collapse and shift the code after every edit (#7422).
const shown = usePluginMarkers.getState().entries;
for (const path of stale) {
const kept = shown.get(path);
if (kept && visible.has(path) && !entries.has(path)) entries.set(path, kept);
}
if (epoch === navigationEpoch() && current === session) usePluginMarkers.setState({ entries });
} catch {
// Plugin navigation may be unavailable during project close or reload.
@@ -69,15 +79,35 @@ export function watchPluginMarkers(path: string): () => void {
clearTimeout(timer);
timer = undefined;
again = false;
stale.clear();
usePluginMarkers.setState({ entries: new Map() });
}
};
}
/**
* Changed `paths` are being indexed again: their markers, and markers targeting them, stay until
* the next results replace them or {@link settlePluginMarkers} drops them. No `paths`: the
* providers changed, so every marker goes now.
*/
export function invalidatePluginMarkers(paths?: readonly string[]) {
const entries = new Map(usePluginMarkers.getState().entries);
const entries = usePluginMarkers.getState().entries;
if (!paths) {
stale.clear();
if (entries.size) usePluginMarkers.setState({ entries: new Map() });
return;
}
for (const [path, entry] of entries) {
if (!paths || paths.includes(path) || entry.markers.some((m) => m.targets.some((t) => paths.includes(t.path))))
entries.delete(path);
if (paths.includes(path) || entry.markers.some((m) => m.targets.some((t) => paths.includes(t.path))))
stale.add(path);
}
}
/** The reindex of `paths` finished (or failed): the next results say which of their markers remain. */
export function settlePluginMarkers(paths: readonly string[]) {
const entries = usePluginMarkers.getState().entries;
for (const path of [...stale]) {
const entry = entries.get(path);
if (paths.includes(path) || !entry || entry.markers.some((m) => m.targets.some((t) => paths.includes(t.path))))
stale.delete(path);
}
usePluginMarkers.setState({ entries });
}
+3 -1
Переглянути файл
@@ -15,7 +15,7 @@ import { useProject } from "@/platform/project";
import { notifications, registerDocumentIndexSync } from "@/workbench/contributions";
import { tx } from "@/platform/i18n";
import { pluginsBackend } from "./backend";
import { invalidatePluginMarkers } from "./markerStore";
import { invalidatePluginMarkers, settlePluginMarkers } from "./markerStore";
import { usePlugins } from "./store";
export function startPluginNavigation(): () => void {
@@ -103,6 +103,7 @@ export function startPluginNavigation(): () => void {
failed.delete(p);
if (!pending.has(p)) dirty.delete(p);
});
settlePluginMarkers(paths.filter((p) => !pending.has(p)));
notify();
}
} catch (error) {
@@ -114,6 +115,7 @@ export function startPluginNavigation(): () => void {
dirty.delete(p);
failed.add(p);
});
settlePluginMarkers(paths);
report(error);
}
} finally {
+64
Переглянути файл
@@ -1077,6 +1077,70 @@ describe("ProjectView", () => {
}
});
it("tells same-named library roots apart with their parent folder (#7444)", async () => {
for (const d of ["/base/Lib", "/p/.venv/Lib", "/p/.venv/Lib/site-packages"]) fs.nodes.set(d, { kind: "dir" });
const remove = registerProjectViewRoot({
id: "externalLibraries",
label: "External Libraries",
icon: "library",
readOnly: true,
children: [
{
label: "< Python 3.12 >",
icon: "file-python",
children: [
{
label: "Lib",
icon: "folder-library",
path: "/base/Lib",
detail: "library root",
note: "base",
},
{
label: "Lib",
icon: "folder-library",
path: "/p/.venv/Lib",
detail: "library root",
note: ".venv",
},
{
label: "site-packages",
icon: "folder-library",
path: "/p/.venv/Lib/site-packages",
detail: "library root",
},
],
},
],
});
try {
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("External Libraries"));
fireEvent.mouseDown(row("External Libraries"));
tree.focus();
fireEvent.keyDown(tree, { key: "ArrowRight" });
await waitFor(() => expect(rows()).toContain("< Python 3.12 >"));
fireEvent.mouseDown(row("< Python 3.12 >"));
fireEvent.keyDown(tree, { key: "ArrowRight" });
await waitFor(() => expect(rows()).toContain("site-packageslibrary root"));
const details = [...tree.querySelectorAll(`.${styles.detail}`)].map((d) => d.textContent);
// The project root shows its path first.
expect(details.slice(1)).toEqual(["library root · base", "library root · .venv", "library root"]);
// The `.venv/Lib` listing holds `site-packages` too: every row keeps its own key.
fireEvent.mouseDown(
within(tree)
.getAllByRole("treeitem")
.filter((r) => r.textContent?.startsWith("Lib"))[1]!,
);
fireEvent.keyDown(tree, { key: "ArrowRight" });
await waitFor(() => expect(tree.querySelectorAll("[data-project-key]").length).toBeGreaterThan(5));
const keys = [...tree.querySelectorAll("[data-project-key]")].map((r) => r.getAttribute("data-project-key"));
expect(new Set(keys).size).toBe(keys.length);
} finally {
act(() => remove());
}
});
it("renames in IDEA's Rename dialog with Shift+F6, validating conflicts, and undoes with ⌘Z", async () => {
dispatchViaKeymap();
const { tree, row, rows } = setup();
+34 -9
Переглянути файл
@@ -35,6 +35,7 @@ import {
OWNS_FILE_DROP,
getFileDecoration,
opensExternally,
menuGroupItems,
prepareMenuGroups,
useFileDecoration,
useFileDecorations,
@@ -325,6 +326,7 @@ interface RowProps {
cut: boolean;
dropTarget: boolean;
detail: string | null;
note?: string;
/** Tooltip when no decoration gives one (a root's path while it is not shown beside it). */
hint?: string | null;
onEditDone: () => void;
@@ -344,6 +346,7 @@ const Row = memo(function Row({
cut,
dropTarget,
detail,
note,
hint,
onEditDone,
onClick,
@@ -387,11 +390,12 @@ const Row = memo(function Row({
// IDEA dims the icon of excluded folders only; git-ignored ones just get the ignored colour.
const dimIcon = node.excluded || unavailable;
const showUnavailableDetail = unavailable && node.root && !node.icon;
const fullDetail = detail && note ? `${detail} · ${note}` : detail;
const detailTitle = showUnavailableDetail
? detail
? `${detail} · ${tx("unavailable")}`
? fullDetail
? `${fullDetail} · ${tx("unavailable")}`
: tx("unavailable")
: (detail ?? undefined);
: (fullDetail ?? undefined);
return (
<span
className={clsx(styles.content, cut && styles.cut, dropTarget && styles.dropTarget)}
@@ -455,6 +459,7 @@ const Row = memo(function Row({
{(detail || showUnavailableDetail) && (
<span className={styles.detail} title={detailTitle}>
{detail}
{detail && note ? ` · ${note}` : null}
{detail && showUnavailableDetail ? " · " : null}
{showUnavailableDetail && <T>unavailable</T>}
</span>
@@ -686,8 +691,10 @@ export function ProjectView() {
: n.member
? n.member.children.length > 0
: // A file whose outline came back empty (unsupported or no members) has nothing to show.
showMembers && !n.placeholder && (outlines.get(n.path)?.length ?? 1) > 0,
[showMembers, outlines],
!n.placeholder &&
!n.group &&
(model.children.has(n.key) || (showMembers && (outlines.get(n.path)?.length ?? 1) > 0)),
[model.children, showMembers, outlines],
);
const loadChildren = useCallback(
@@ -698,8 +705,8 @@ export function ProjectView() {
const getChildren = useCallback(
(n: ProjectNode) => {
if (n.member) return memberNodes(n.path, n.member.children);
if (!n.dir) return outlineRows.get(n.path);
const children = model.children.get(n.key);
if (!n.dir && !children) return n.group ? undefined : outlineRows.get(n.path);
if (
!children ||
!decorationProviders.size ||
@@ -726,7 +733,16 @@ export function ProjectView() {
const onSelectionChange = useCallback((next: Set<string>, lead: ProjectNode | null) => {
setSelection(next, lead?.key ?? null);
const { options: o } = useProjectTree.getState();
if (revealing.current || !o.autoscrollToSource || !lead || lead.dir || lead.placeholder || next.size !== 1) return;
if (
revealing.current ||
!o.autoscrollToSource ||
!lead ||
lead.dir ||
lead.group ||
lead.placeholder ||
next.size !== 1
)
return;
const opts = { preview: previewTabEnabled(), focus: false, external: false };
if (lead.member) {
void revealRange(lead.path, { start: lead.member.selection_range.start }, opts);
@@ -736,7 +752,7 @@ export function ProjectView() {
const onActivate = useCallback((node: ProjectNode) => {
if (node.member) {
void revealRange(node.path, { start: node.member.selection_range.start }, { focus: true });
} else if (!node.dir && !node.placeholder) void openFile(node.path, { focus: true });
} else if (!node.dir && !node.placeholder && !node.group) void openFile(node.path, { focus: true });
}, []);
const onContextMenu = useCallback((node: ProjectNode | null, sel: Set<string>, e: ReactMouseEvent) => {
@@ -750,6 +766,13 @@ export function ProjectView() {
}
const nodes = [...sel].map((k) => m.byKey.get(k)).filter((n): n is ProjectNode => !!n && !n.placeholder);
const target = nodes.length ? nodes : [node];
const menuPath = target.length === 1 ? target[0]!.menuPath : undefined;
if (menuPath) {
// A solution group: only the contributed items of its `.sln` (Build, Add Existing Project…).
const items = menuGroupItems("projectView", { paths: [menuPath], dirs: [false] });
if (items.length) showContextMenu(e, items);
return;
}
if (target.every((n) => n.group) || target.some((n) => n.member)) return;
// Contributed groups and collapsed library folders may read the filesystem first (bounded wait).
const at = { x: e.clientX, y: e.clientY };
@@ -765,7 +788,7 @@ export function ProjectView() {
const onRowClick = useCallback((node: ProjectNode, e: ReactMouseEvent) => {
if (e.button !== 0 || e.shiftKey || e.metaKey || e.ctrlKey || e.altKey) return;
if (node.placeholder || dragged.current) return;
if (node.placeholder || node.group || dragged.current) return;
const { options: o, editing: ed } = useProjectTree.getState();
if (ed) return;
if (e.detail > 1 && !(node.dir && o.singleClickExpand && e.detail % 2 === 1)) return;
@@ -1068,6 +1091,7 @@ export function ProjectView() {
editing={editing}
cut={cutPaths.has(node.path)}
dropTarget={dropTarget === node.key}
note={node.note}
detail={
node.detail ??
(rootPath(node) && options.showRootPaths ? rootPath(node) : null) ??
@@ -1140,6 +1164,7 @@ export function ProjectView() {
getDirectory={(node) => (node.group || node.placeholder ? null : targetFolder(node))}
getChildren={getChildren}
isExpandable={isExpandable}
activateExpandable={(node) => !node.dir && model.children.has(node.key)}
loadChildren={loadChildren}
renderNode={renderNode}
rowTint={(n) =>
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff. Show more