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

..
Автор SHA1 Повідомлення Дата
l0ng-ai eefe166cf7 chore: v0.1.35 2026-11-03 22:31:49 +08:00
l0ng-ai 8c9ddb9879 fix(agents): tidy the Built-in agents settings page
- List rows are no longer text-selectable. Settings pages enable text selection
  for their content, and the shared List inherited it, so dragging or ⌘A
  highlighted every row.
- An agent missing from PATH is shown as a muted row with a small "Not found"
  label instead of an orange warning badge; a custom executable gets an accent
  "Custom" label.
- The details header puts the status (with a status dot) and the launch command
  on one line.
- Reset only appears when a custom executable is set.
- The sign-in hint gets its own "Sign in" heading.
- The list/details frame sizes to its content instead of filling the page.
2026-11-03 22:20:58 +08:00
l0ng-ai d54ef98a59 fix(lsp): open library classes behind jar: URIs (#1048)
The official Kotlin LSP answers navigation into a dependency with a
`jar:///…/lib.jar!/pkg/Name.class` URI but does not serve its contents through
`workspace/textDocumentContent`, so opening the target failed with "no
language server provides the contents of jar:…", locally and remotely.

`jar:` URIs are now resolved by the backend, where the jars are:
- An entry that is not a class (a sources jar entry, a resource) is read from
  its archive.
- A class is shown as its source from the artifact's `-sources.jar` in the
  Maven repository or the Gradle cache (`Name.java`/`Name.kt`, an inner
  class's outer file, a `FileKt` facade's `File.kt`, a `@file:JvmName`
  file); Go to Declaration then lands on the declaration of the name it was
  invoked on.
- Otherwise the server's `decompile` command is used when it offers one, and
  the error says that neither a source nor a decompiler is available.
- Library tabs name the archive and package (`spring-boot-3.5.16.jar ›
  org.springframework.boot`).

Fixes #982
2026-11-03 22:04:05 +08:00
l0ng-ai 98517019e7 fix(editor): say when a file is outside the language server's projects (#1046)
jdtls only checks the syntax of a Java file outside every module's source
folders (or outside any imported project) and answers navigation with
nothing. The editor then said only "Cannot find declaration to go to", and
the server's explanation was a warning squiggle on line 1.

- A banner above the editor explains it while the server reports it, for
  jdtls (not on the classpath of a project / non-project file), gopls (no
  package, build constraints — this replaces the Go-only banner) and
  rust-analyzer (unlinked file). For Java it offers the Maven / Gradle reload
  when available.
- Go to Declaration / Implementation / Type Declaration that finds nothing
  in such a file gives the reason in its hint.

Fixes #827
2026-11-03 22:02:50 +08:00
l0ng-ai ae406ca2fb fix(java): resolve Maven projects with the profiles chosen in the Maven tool window (#1044)
The profiles checked in the Maven tool window only reached `mvn` (sync and
goal runs) and the Kotlin bridge. jdtls imported every module without them,
so a dependency whose version, or module, comes from a profile stayed
unresolved and its classes were reported as missing, while Build Project ran
without `-P` as well.

- A Maven sync records the profiles it ran with. jdtls gets a copy of the
  user settings.xml with them in `<activeProfiles>` (m2e has no other input
  for profiles), sent as a setting so a running server re-imports instead of
  restarting; the file name follows its content so m2e reloads it.
- Toggling a profile reloads the Maven projects (once for several toggles in
  a row, again after a sync that started with the previous choice).
- Build Project passes the synced profiles with `-P`.
- When jdtls finishes an import or project update it does not re-check open
  files, so their errors stayed until the next edit; open Java files are now
  re-checked on its ProjectStatus report. This also covers a POM edit or a
  dependency added to ~/.m2.

Fixes #993
2026-11-03 22:02:40 +08:00
arookieofcтаa-rookie-of-C-language 9dbae1d189 feat(agents): configurable executable for every built-in agent (#682)
Settings › Tools › Agents is split into Built-in and ACP Registry tabs. The Built-in tab lists every built-in agent with its status (custom executable or not found on PATH) and, for the selected agent, its default launch line, an Executable field (empty = auto-detect on PATH) with Browse and Reset, and its sign-in hint. Edits are staged with the Settings dialog and written on Apply / OK; Cancel discards them.

The override is written to <config>/agents/<id>.toml, keeping hand-written name, driver, args and env; resetting a command-only override removes the file. AgentProvider now exposes the program, args, built-in defaults, login hint and whether the command is editable: built-ins started through a package runner (npx) and registry installs are read-only, with the reason shown.

Fixes #596

Co-authored-by: a-rookie-of-C-language <[email protected]>
2026-11-03 21:55:51 +08:00
l0ng-ai e4b8b76452 chore: add issue/PR templates, PR check, AGENTS.md and shared agent skills (#1043)
Adds a PR template (linked issue, what and why, how it was verified, review focus), a minimal reproduction field on the bug form and required acceptance criteria on the feature form, and CONTRIBUTING.md with the issue and PR rules. A PR check labels needs-info and leaves one comment when the issue link or the verification section is missing; it only reads the title and description.

AGENTS.md is now tracked, with CLAUDE.md linking to it, and covers layout, rules, commands, the checks CI runs, pitfalls and parallel worktrees. The verify and issue-fix skills are shared under .agents/skills and linked from .claude/skills; the rest of .claude/ stays local.
2026-11-03 21:49:31 +08:00
l0ng-ai e2e699dca9 fix(database): bound large cell previews and use dialog editing (#1040)
Limit grid and export-preview cell text to 1000 UTF-16 code units plus an ellipsis. Edit large values in a wrapped dialog while preserving complete clipboard, export and database values.

Reproduced STATUS_STACK_OVERFLOW (0xC00000FD) in Windows WebView2 against a real PostgreSQL table with nine rows and 8.83 MB of jsonb data. Verified the fix through display, selection, editing, full clipboard copy, JSON file export and PostgreSQL writeback. All PR CI checks passed, including 5625 frontend tests and Rust checks on Windows, macOS and Linux.

Fixes #825
2026-11-03 21:49:26 +08:00
l0ng-ai dcd8ecc5ae fix(java): name reserved Windows device files that abort the Java import (#1032)
On Windows, a project file named after a device (nul, con, aux, prn, com1-9, lpt1-9; nul is typically left by a 2>nul redirect in Git Bash) aborts the Java import: Files.exists reports it missing, Eclipse's refresh builds a child path with an empty name and throws "Path must include project and resource name", so m2e never creates the Java project.

When JDT LS reports that failure on Windows, the server root is scanned for reserved device names (bounded, ignore files not honoured) and a one-time error notification lists them with how to recover. The name check covers COM0-9/LPT0-9 including superscript digits, case-insensitive, with or without extension or trailing spaces. Backend notification texts now go through txTemplate so templated catalog entries translate; zh text added.

Refs #976
2026-11-03 21:09:03 +08:00
l0ng-ai a3b6780823 fix(java): replace module outputs with launch snapshots on Windows (#1038)
Maven launches put a snapshot of each module's class directory on the classpath in place of the original. The originals were built as module.join("target/classes") (`...\app\target/classes` on Windows) while JDT LS reports `...\app\target\classes`; compared as text, the original stayed next to its snapshot, so every resource was on the classpath twice and MyBatis failed with "XML fragments parsed from previous mappers already contains value". Launch class directories are now joined per component, and classpath entries are compared by a key that ignores the verbatim prefix, separators, trailing separators and, on Windows, case.

Fixes #704
2026-11-03 20:59:40 +08:00
arookieofc bd2df0bd3a fix(markdown): keep the preview-only scroll position across remounts (#1009)
Tab switches and mode toggles unmount MarkdownPreview, whose only
scroll state was the DOM scrollTop; Preview Only started over at the
top. Record the preview's own scrollTop in the per-path live markdown
store and restore it on mount (split mode keeps its editor-driven
sync).
2026-11-03 20:55:10 +08:00
Marius Ciepluch 8ca25e1984 fix(markdown): use editor-side tokens in the preview (#992)
* fix(markdown): use editor-side tokens in the preview

The preview paints on var(--bg-editor) but took its text colors from
the UI tokens (--fg, --fg-strong, --fg-secondary), so with a light UI
theme plus a dark editor scheme (e.g. an imported dark .icls) it
rendered black-on-black. The code editor was unaffected because it
uses --fg-editor.

The preview now uses editor-side tokens: text var(--fg-editor),
headings var(--syn-markup-heading), code/pre/th background
var(--bg-editor-inline), blockquote var(--fg-editor) at 80%.

* chore: oxfmt src/features/run/types.ts (fixes format:check broken on main by 002401e8)

* chore: regenerate bindings after rebasing onto main
2026-11-03 20:55:06 +08:00
arookieofc a15712b670 fix(vcs): keep a deleted-upstream branch pushable in the multi-repo Push dialog (#1004)
`@{u}..HEAD` fatally fails when the tracking config remains but the
remote-tracking ref is gone (the upstream branch was deleted on the
remote and the fetch pruned): the repository was dropped from the
multi-repository Push dialog, or, when every repository failed, the
dialog showed the raw fatal and disabled Push. Fall back to recent
history like the single-repository dialog does, so the branch stays
listed and pushable (a plain push recreates the remote branch).
2026-11-03 20:33:41 +08:00
arookieofc 82130d37e5 fix(build): recognize Maven builds whose aggregate POM sits in src/ (#1022) 2026-11-03 20:32:37 +08:00
JawтаClaude Opus 5.5 07456b2562 fix(editor): show the scrollbar thumb over overview marks (#1031)
The overview lane lies over the vertical scrollbar, so a mark the height of the lane (a new file added to git is one green VCS mark) hid the native thumb completely. The lane now draws the thumb itself, above its marks and without taking the pointer, at the position of the native one (scrollbarThumb, inset by its 2px border); it switches to the hover color while the pointer is on the thumb. The native thumb is made transparent in editors that have the lane, so the two don't add up, and still takes the drag. Editors without the lane (notebook cells, previews) keep the native thumb.

Fixes #1014

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-03 20:31:57 +08:00
arookieofc 659afe66f5 fix(code-insight): stop call/type hierarchy from nesting recursive symbols forever (#1016)
A recursive symbol got a fresh id on every level (ids carry the parent
chain), so sibling dedupe never matched and each expansion requested the
same level again, forever. Identify items by their position key instead:
a child whose key repeats an ancestor is kept a leaf, marked recursive,
and never expanded.
2026-11-03 20:31:01 +08:00
JawтаClaude Opus 5.5 a57267fa32 fix(project-tree): reveal files of linked workspace projects (#915) (#1035)
In a workspace the tree's root is the workspace directory, and the linked projects are separate top-level roots outside it. Select Opened File (and other reveals) only looked inside that root and contributed folders, so a file of a linked project was never expanded, selected or scrolled to. Reveal now resolves the innermost linked project containing the path first; the Project Files pane also counts linked projects as shown.

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-03 20:30:07 +08:00
88 змінених файлів з 3589 додано та 199 видалено

No files matched your search

+91
Переглянути файл
@@ -0,0 +1,91 @@
---
name: issue-fix
description: Triage and fix a GitHub issue (or a user-reported bug) end to end — reproduce, find the root cause, generalise it to every sibling case, fix the class rather than the instance, verify, and open one PR. Use when given an issue URL/number or asked to fix a reported bug and open a PR ("看看这个 issue", "修一下这个 bug", "提 pr").
---
# Fix an issue: from one case to the whole class
The reported case is one sample of a defect class. A fix that only makes the
screenshot go away is not done: the next question is always "does this break for other
languages / platforms / entry points too?". Answer that before anyone asks.
## 1. Read and reproduce
- `gh issue view <n> --comments` (repo `l0ng-ai/openidea`). Read attached logs/screenshots
closely: OS, language, toolchain versions, exact error text.
- Locate the code path and confirm the claim in code, with `file:line` evidence.
Say plainly whether it is a real bug, a missing feature, or user environment.
- Reproduce locally when possible (`fixtures/` projects, `/verify` for runtime). If the
reporter's platform (often Windows/Linux) can't be reproduced here, say so up front.
- Do not ask for a generic environment/log checklist before trying the flow and inspecting the code.
Record the attempt and result; ask only for a fact that actually blocks the next diagnostic step.
Missing fields, limited time, or unavailable automation are not by themselves reasons to ask the reporter.
- Treat a maintainer-confirmed bug as an investigation task even if local reproduction fails. Distinguish
“not reproduced here” from “not a bug”, and do not require the reporter to prove its existence again.
## 2. Name the root cause as a class
Write one sentence of the form "<mechanism> is missing/wrong, so any <X> hits it",
not "<this button> is broken". Typical classes in this codebase:
- Per-language config handled for one language only (`languages/*.toml`, `ide-sdk`).
- Platform gaps: paths, executables, shells, `.cmd`/`.exe`, separators — macOS-only code.
- Toolchain/version discovery: one probe location, no version check, no rescan.
- Two features each implementing half a flow and never joined (feature isolation →
should go through an action/service).
- State not reset on project switch / window reuse; events not scoped per window.
- Failure surfaced as raw stderr/stack trace or retried until "crashed" instead of a
clear status with an action.
- UI: same primitive styled differently in N places.
## 3. Sweep for siblings
Search systematically, not by memory:
- Same pattern elsewhere: `git grep` the function, the config key, the error string,
the hard-coded path/flag. Check every `languages/*.toml` entry and every platform branch.
- Same flow for other languages/runtimes (Java ↔ Kotlin/Gradle, Python ↔ venv/uv,
Node ↔ Deno/Bun, Go, Rust …): would they fail the same way?
- Other callers/entry points of the same flow (menu, context menu, gutter, shortcut, CLI arg).
- Neighbouring failure modes of the same mechanism (not installed / wrong version /
installed but crashes / slow start / installed mid-session).
For broad sweeps spawn one Explore agent with the class description, not the instance.
## 4. Decide the fix at the right altitude
- Fix the mechanism once (shared helper, action, config hook) so siblings are fixed
by construction; don't patch each call site.
- Respect `AGENTS.md` rules (crate boundaries, no cross-feature imports, `IdeResult`,
UTF-16). If the right fix breaks a rule, pick the rule-respecting design and say why.
- Compare with how established IDEs solve it when relevant; prefer the established answer.
- Present: root cause, sibling table, proposed fix, what's deferred. When the user leaves
the choice to you, go ahead without asking again.
## 5. Implement and test the class
- Tests cover the class: table-driven over languages/platforms/states, not just the
reported input. Include the reporter's case verbatim.
- Run the scoped checks (`pnpm vitest run <path>`, `cargo nextest run -p <crate>`), then
`/verify` in the app for UI or runtime behaviour.
## 6. PR
- One branch `fix/<slug>`, one PR unless the user asks otherwise; `Fixes #<n>` in the body.
- Don't stage untracked IDE-state dirs (`.ideal/`, `.openidea/`) or screenshots.
- PR body follows `.github/pull_request_template.md`: `Closes #<n>`, then
**What and why** (user-visible change + root cause at class level, 2–4 sentences),
**How it was verified** (commands run and results, siblings fixed/deferred, what could break and how
it was checked, what was not verified, e.g. "Windows not tested"; for UI changes the before/after
screenshot paths from `/verify`), **Review focus** (optional). Short and plain.
## Report format
Reply in the user's language:
```
Root cause: <one sentence, class level>
Sibling sweep:
| Location / case | Affected? | Action |
Fixed / not covered (why) / not verified (platform)
PR: <url>
```
+57
Переглянути файл
@@ -0,0 +1,57 @@
---
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`, ...).
- 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/issue-fix
+1
Переглянути файл
@@ -0,0 +1 @@
../../.agents/skills/verify
+6
Переглянути файл
@@ -42,6 +42,12 @@ body:
3. ...
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Minimal reproduction
description: A link to a small public repository, or the smallest files/snippet that trigger the problem. Optional, but it's the fastest way to get a fix.
placeholder: https://github.com/you/repro-project
- type: textarea
id: expected
attributes:
+10
Переглянути файл
@@ -27,6 +27,16 @@ body:
description: How you'd like it to work. Mockups or examples from other tools are welcome.
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: How we'll know it's done. One observable behavior per line.
placeholder: |
- [ ] Right-clicking a test class shows "Run with Coverage"
- [ ] Coverage results open in the Coverage tool window
validations:
required: true
- type: textarea
id: alternatives
attributes:
+17
Переглянути файл
@@ -0,0 +1,17 @@
Closes #
## What and why
<!-- 2–4 sentences: the change a user notices, and the root cause.
If it doesn't fit, the PR is probably too big; split it. -->
## How it was verified
<!-- Required. Commands you actually ran and their results; what else this could
affect and how you checked it still works.
UI changes: before/after screenshots. Multi-step interactions: a recording.
Backend changes: logs or command output. -->
## Review focus
<!-- Optional: anything you want reviewers to look at closely. -->
+69
Переглянути файл
@@ -0,0 +1,69 @@
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.
pull_request_target:
types: [opened, edited, reopened, ready_for_review]
permissions:
issues: write
pull-requests: write
concurrency:
group: pr-check-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
check:
if: github.event.pull_request.user.type != 'Bot' && !github.event.pull_request.draft
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
with:
script: |
const pr = context.payload.pull_request;
const LABEL = 'needs-info';
const MARKER = '<!-- pr-check -->';
// Docs, CI and pure refactors may skip the linked issue.
const NO_ISSUE_TYPES = /^(docs|ci|build|chore|refactor|style|test)(\(.+\))?!?:/;
const body = (pr.body || '').replace(/<!--[\s\S]*?-->/g, '');
const problems = [];
const linksIssue =
/\b(close[sd]?|fix(e[sd])?|resolve[sd]?)\s*:?\s+(#\d+|https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/issues\/\d+)/i.test(body);
if (!linksIssue && !NO_ISSUE_TYPES.test(pr.title)) {
problems.push('Link the issue this PR resolves, e.g. `Closes #123`.');
}
const verified = body.match(/^##+\s*How it was verified\s*$([\s\S]*?)(?=^##+\s|(?![\s\S]))/im);
if (!verified || !verified[1].trim()) {
problems.push('Fill in **How it was verified**: the commands you ran and their results. UI changes need before/after screenshots.');
}
const { owner, repo } = context.repo;
const issue_number = pr.number;
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);
if (problems.length) {
const text = `${MARKER}\nThanks for the PR. Before review, please update the description (see [CONTRIBUTING.md](https://github.com/${owner}/${repo}/blob/main/CONTRIBUTING.md)):\n\n${problems.map(p => `- ${p}`).join('\n')}\n\nThis check reruns when you edit the description.`;
if (existing) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body: text });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number, body: text });
}
if (!labeled) {
await github.rest.issues.addLabels({ owner, repo, issue_number, labels: [LABEL] });
}
return;
}
// Only undo what this check did: the label is cleared only when our comment exists.
if (existing) {
await github.rest.issues.deleteComment({ owner, repo, comment_id: existing.id });
if (labeled) {
await github.rest.issues.removeLabel({ owner, repo, issue_number, name: LABEL }).catch(() => {});
}
}
+7 -3
Переглянути файл
@@ -30,9 +30,13 @@ target/
test-results/
playwright-report/
# Local AI agent files
CLAUDE.md
.claude/
# Local AI agent files. Shared skills live in .agents/skills; .claude/skills links to them.
CLAUDE.local.md
.claude/*
!.claude/skills/
.claude/skills/*
!.claude/skills/verify
!.claude/skills/issue-fix
# Local reference screenshots
pycharm-screenshots/
+118
Переглянути файл
@@ -0,0 +1,118 @@
# OpenIDEA — contributor guide
Rust + Tauri 2 desktop IDE with full-featured, multi-language code intelligence.
Visual style: dark, low-contrast greys, one cool accent
(`src/styles/tokens.css` is the source of truth for colours and metrics).
## 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`
(thin typed IPC adapters), `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.
- `wit/` — plugin interface definitions; `plugins/` — sample and bundled plugins;
`templates/` — plugin starter templates.
- `e2e/` — Playwright UI tests (`pnpm e2e`). `fixtures/` — sample projects per language
for manual and automated testing.
## 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.
- 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.
- 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).
- Keep comments sparse and purposeful; match surrounding style.
- For GUI verification, prefer Tauri MCP; use Computer Use only when Tauri MCP is
unavailable or cannot cover the required checks.
## Issues & PRs
Follow `CONTRIBUTING.md` and `.github/pull_request_template.md`: one issue per PR with
`Closes #<n>`, reproduce first, keep the diff focused, short plain description, and a
**How it was verified** section with commands run, results and (for UI) before/after screenshots.
Unclear product decisions → `needs-decision` and stop.
## Skills
Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
`verify` drives the running app through Tauri MCP and captures screenshot evidence;
`issue-fix` takes an issue from reproduction to one PR.
## Commands
- `pnpm tauri dev` — run the app with worktree isolation (Node 22.18+).
`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.
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
- `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`.
## 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`, `pnpm lint`, `pnpm format:check`, `pnpm knip`, `pnpm test`,
`pnpm build`, and `pnpm e2e` for UI flows.
- UI or runtime behaviour: verify in the running app (`.agents/skills/verify`).
## 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 (around 5 minutes) and its Cargo output takes
15–30 GB. 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
+35
Переглянути файл
@@ -0,0 +1,35 @@
# Contributing to OpenIDEA
These rules apply to everyone, and to any coding agent working on their behalf.
Project layout, coding rules, commands and checks are in [AGENTS.md](AGENTS.md).
## Issues
- One problem or request per issue. Use the issue forms.
- Bugs: steps that reproduce the problem from a fresh start. A minimal sample
project is the fastest way to get a fix.
- Features: state the problem and the acceptance criteria. A feature is ready to
build once a maintainer labels it `planned`.
- Labels track status: `needs-info` waits on the reporter, `needs-decision` waits
on a maintainer, `planned` is accepted, `needs-acceptance` has a fix waiting to be
checked.
## Pull requests
- One issue per PR, linked with `Closes #123`. Feature PRs need a `planned` issue.
Docs, CI and pure refactors may skip the issue.
- Reproduce the problem first, or write a test that fails before the fix.
- Fix the cause, and check whether the same cause breaks anything nearby.
- Keep the diff focused. Unrelated refactors go in their own PR.
- Title: [Conventional Commits](https://www.conventionalcommits.org/), e.g.
`fix(editor): keep the caret visible after folding`.
- Fill in the template. Keep the description short and in plain words. If it
doesn't fit in a few sentences, the PR is probably too big.
- **How it was verified** is required: the commands you ran and their results,
and what else the change could affect. UI changes need before/after screenshots;
multi-step interactions need a recording.
- If a change needs a product decision you can't make, ask in the issue and stop
rather than guessing.
A check on each PR adds `needs-info` when the issue link or the verification
section is missing, and removes it once they're filled in.
Створено
+36 -35
Переглянути файл
@@ -4038,7 +4038,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"dunce",
"encoding_rs",
@@ -4061,7 +4061,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4075,7 +4075,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -4090,7 +4090,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
@@ -4099,7 +4099,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"dunce",
"encoding_rs",
@@ -4116,7 +4116,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ide-core",
"ide-run",
@@ -4130,7 +4130,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -4148,7 +4148,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"bb8",
"dirs 6.0.0",
@@ -4170,7 +4170,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ide-core",
"serde",
@@ -4183,7 +4183,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4195,7 +4195,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4208,7 +4208,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -4255,7 +4255,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ide-core",
"parking_lot",
@@ -4273,7 +4273,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"blake3",
"criterion",
@@ -4295,7 +4295,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"encoding_rs",
"futures",
@@ -4311,7 +4311,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"blake3",
"criterion",
@@ -4366,7 +4366,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"dunce",
"futures",
@@ -4387,11 +4387,12 @@ dependencies = [
"tokio",
"toml 0.9.12+spec-1.1.0",
"tracing",
"zip",
]
[[package]]
name = "ide-notebook"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"futures",
"ide-core",
@@ -4414,7 +4415,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ide-core",
"ide-language",
@@ -4433,7 +4434,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ide-core",
"ide-run",
@@ -4446,7 +4447,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"globset",
"ide-core",
@@ -4463,7 +4464,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"dunce",
"encoding_rs",
@@ -4486,7 +4487,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"dunce",
"ide-core",
@@ -4505,7 +4506,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"criterion",
"globset",
@@ -4525,7 +4526,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ide-core",
"parking_lot",
@@ -4538,7 +4539,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4557,7 +4558,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ide-core",
"ide-language",
@@ -4572,7 +4573,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ide-core",
"libc",
@@ -4585,7 +4586,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"criterion",
"ide-core",
@@ -4597,7 +4598,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"flate2",
"hex",
@@ -4618,7 +4619,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"dunce",
"encoding_rs",
@@ -4637,7 +4638,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"chardetng",
"dunce",
@@ -4659,7 +4660,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"ide-core",
"open",
@@ -4675,7 +4676,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"blake3",
"dunce",
@@ -6147,7 +6148,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.34"
version = "0.1.35"
dependencies = [
"blake3",
"block2 0.6.2",
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "src-tauri"]
[workspace.package]
version = "0.1.34"
version = "0.1.35"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+14 -11
Переглянути файл
@@ -301,17 +301,11 @@ impl AgentManager {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref());
let list = specs
.iter()
.map(|p| AgentProvider {
id: p.id.clone(),
name: p.name.clone(),
command: std::iter::once(p.command.as_str())
.chain(p.args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" "),
installed: provider::installed(&p.command),
config: self.shared.known_config(&p.id),
commands: self.shared.known_commands(&p.id),
source: p.source.clone(),
.map(|p| {
let mut info = provider::describe(p);
info.config = self.shared.known_config(&p.id);
info.commands = self.shared.known_commands(&p.id);
info
})
.collect();
let mut prev = self.shared.providers.write();
@@ -325,6 +319,15 @@ impl AgentManager {
list
}
/// Overrides built-in `id`'s command with `command` (the driver and arguments stay
/// the built-in's) through its agent file, or returns it to auto-detection with `None`.
pub fn set_builtin_command(&self, id: &str, command: Option<String>) -> IdeResult<()> {
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
return Err(IdeError::unavailable("there is no custom agents directory"));
};
provider::set_builtin_command(&dir, id, command.as_deref())
}
/// Re-reads configured/installed agents, drops cached probes, and notifies subscribers.
pub fn reload_providers(&self) {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref());
+18
Переглянути файл
@@ -322,6 +322,15 @@ pub struct AgentProvider {
pub name: String,
/// The command line that starts its ACP server.
pub command: String,
/// Executable and arguments actually launched, without flattening paths containing spaces.
pub program: String,
pub args: Vec<String>,
pub default_program: Option<String>,
pub default_args: Vec<String>,
pub login_hint: Option<String>,
pub command_overridden: bool,
pub command_editable: bool,
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
/// Whether the command was found (on `PATH`).
pub installed: bool,
/// Settings (models, modes…) the agent offered last time it ran; empty before its first session.
@@ -331,6 +340,15 @@ pub struct AgentProvider {
pub source: AgentSource,
}
/// Why the executable cannot be changed in built-in agent settings.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentCommandReadOnlyReason {
PackageRunner,
Registry,
CustomAgent,
}
/// Where an agent comes from.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
+213 -1
Переглянути файл
@@ -2,7 +2,8 @@
//! `<config>/agents/<id>.toml` (written by hand, or by installing one from the ACP
//! Registry, see `registry`).
use crate::AgentSource;
use crate::{AgentCommandReadOnlyReason, AgentProvider, AgentSource};
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
@@ -92,6 +93,82 @@ pub(crate) fn builtin_name(id: &str) -> Option<&'static str> {
BUILTIN.iter().find(|&&(bid, _, _, _, _)| bid == id).map(|&(_, name, _, _, _)| name)
}
/// The built-in spec of `id`.
pub(crate) fn builtin_spec(id: &str) -> Option<ProviderSpec> {
builtins().into_iter().find(|s| s.id == id)
}
/// Public launch metadata, keeping the built-in defaults separate from agent-file overrides.
pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
let builtin = builtin_spec(&spec.id);
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
Some(AgentCommandReadOnlyReason::Registry)
} else if let Some(default) = &builtin {
matches!(default.command.as_str(), "npx" | "bunx" | "uvx").then_some(AgentCommandReadOnlyReason::PackageRunner)
} else {
Some(AgentCommandReadOnlyReason::CustomAgent)
};
AgentProvider {
id: spec.id.clone(),
name: spec.name.clone(),
command: std::iter::once(spec.command.as_str())
.chain(spec.args.iter().map(String::as_str))
.collect::<Vec<_>>()
.join(" "),
program: spec.command.clone(),
args: spec.args.clone(),
default_program: builtin.as_ref().map(|b| b.command.clone()),
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
login_hint: Some(spec.login_hint.clone()),
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed(&spec.command),
config: vec![],
commands: vec![],
source: spec.source.clone(),
}
}
/// Overrides built-in `id`'s command through its agent file, preserving other
/// customizations. `None` restores the built-in command and removes a redundant file.
pub(crate) fn set_builtin_command(custom_dir: &Path, id: &str, command: Option<&str>) -> IdeResult<()> {
let Some(builtin) = builtin_spec(id) else {
return Err(IdeError::invalid(format!("{id} is not a built-in agent")));
};
let file = custom_dir.join(format!("{id}.toml"));
let mut agent = if file.try_exists()? {
CustomAgent::read(&file).map_err(IdeError::invalid)?
} else {
CustomAgent {
name: Some(builtin.name.clone()),
driver: builtin.driver,
command: builtin.command.clone(),
args: builtin.args.clone(),
env: BTreeMap::new(),
registry: None,
}
};
if agent.registry.is_some() {
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
}
if command.is_none()
&& agent.name.as_deref() == Some(builtin.name.as_str())
&& agent.driver == builtin.driver
&& agent.args == builtin.args
&& agent.env.is_empty()
{
match std::fs::remove_file(&file) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
_ => {}
}
return Ok(());
}
agent.command = command.unwrap_or(&builtin.command).to_owned();
agent.write(&file)?;
Ok(())
}
/// An agent file, `<config>/agents/<id>.toml`.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -182,6 +259,9 @@ pub(crate) fn load(custom_dir: Option<&Path>) -> Vec<ProviderSpec> {
match specs.iter_mut().find(|s| s.id == spec.id) {
Some(existing) => {
spec.login_hint = existing.login_hint.clone();
if spec.source == AgentSource::Custom {
spec.source = AgentSource::Builtin;
}
*existing = spec;
}
None => specs.push(spec),
@@ -221,6 +301,54 @@ fn is_executable(p: &Path) -> bool {
mod tests {
use super::*;
#[test]
fn launch_metadata_distinguishes_defaults_overrides_and_read_only_agents() {
let dir = tempfile::tempdir().unwrap();
let list = || load(Some(dir.path())).iter().map(describe).collect::<Vec<_>>();
let defaults = list();
let codex = defaults.iter().find(|p| p.id == "codex").unwrap();
assert_eq!(codex.program, "codex");
assert_eq!(codex.default_program.as_deref(), Some("codex"));
assert_eq!(codex.args, ["app-server"]);
assert_eq!(codex.default_args, codex.args);
assert_eq!(codex.command, "codex app-server");
assert_eq!(codex.login_hint.as_deref(), Some("Run `codex login` in a terminal."));
assert!(!codex.command_overridden);
assert!(codex.command_editable);
for p in &defaults {
assert_eq!(p.source, AgentSource::Builtin);
assert!(p.default_program.is_some());
assert_eq!(p.command_editable, !p.id.ends_with("-acp"));
assert_eq!(
p.command_read_only_reason,
p.id.ends_with("-acp").then_some(AgentCommandReadOnlyReason::PackageRunner)
);
}
set_builtin_command(dir.path(), "codex", Some("/path with spaces/codex")).unwrap();
let overridden = list().into_iter().find(|p| p.id == "codex").unwrap();
assert_eq!(overridden.program, "/path with spaces/codex");
assert_eq!(overridden.args, codex.args);
assert_eq!(overridden.default_program, codex.default_program);
assert!(overridden.command_overridden && overridden.command_editable);
assert_eq!(overridden.source, AgentSource::Builtin);
set_builtin_command(dir.path(), "codex", Some("codex")).unwrap();
assert!(!list().iter().find(|p| p.id == "codex").unwrap().command_overridden);
std::fs::write(
dir.path().join("gemini.toml"),
"command = \"/registry/gemini\"\n[registry]\nid = \"gemini\"\nversion = \"1.0\"\n",
)
.unwrap();
let registry = list().into_iter().find(|p| p.id == "gemini").unwrap();
assert_eq!(registry.default_program.as_deref(), Some("gemini"));
assert!(!registry.command_editable);
assert_eq!(registry.command_read_only_reason, Some(AgentCommandReadOnlyReason::Registry));
assert!(matches!(registry.source, AgentSource::Registry { .. }));
std::fs::write(dir.path().join("mine.toml"), "command = \"mine\"\n").unwrap();
let custom = list().into_iter().find(|p| p.id == "mine").unwrap();
assert_eq!(custom.default_program, None);
assert_eq!(custom.command_read_only_reason, Some(AgentCommandReadOnlyReason::CustomAgent));
}
#[test]
fn custom_agents_extend_and_override_the_builtins() {
let dir = tempfile::tempdir().unwrap();
@@ -240,6 +368,90 @@ mod tests {
assert!(installed("sh"));
}
#[test]
fn set_builtin_command_overrides_and_clears_a_builtin() {
let dir = tempfile::tempdir().unwrap();
set_builtin_command(dir.path(), "not-a-builtin", Some("/x")).unwrap_err();
set_builtin_command(dir.path(), "claude", Some("/opt/claude")).unwrap();
let claude = load(Some(dir.path())).into_iter().find(|s| s.id == "claude").unwrap();
assert_eq!((claude.command.as_str(), claude.driver), ("/opt/claude", Driver::Claude));
assert!(claude.args.is_empty());
// A registry install is neither overwritten nor removed by a command override.
let path = dir.path().join("codex.toml");
CustomAgent {
name: None,
driver: Driver::Acp,
command: "amp".into(),
args: vec![],
env: BTreeMap::new(),
registry: Some(RegistryRef { id: "amp-acp".into(), version: "1.0.0".into() }),
}
.write(&path)
.unwrap();
set_builtin_command(dir.path(), "codex", Some("/x")).unwrap_err();
set_builtin_command(dir.path(), "codex", None).unwrap_err();
assert!(path.exists());
// Clearing (twice) returns the built-in to auto-detection.
set_builtin_command(dir.path(), "claude", None).unwrap();
set_builtin_command(dir.path(), "claude", None).unwrap();
assert!(!dir.path().join("claude.toml").exists());
assert_eq!(load(Some(dir.path())).iter().find(|s| s.id == "claude").unwrap().command, "claude");
}
#[test]
fn set_builtin_command_preserves_other_customizations_on_save_and_reset() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("claude.toml");
for field in ["name", "driver", "args", "env", "unnamed"] {
let mut agent = CustomAgent {
name: Some("Claude Code".into()),
driver: Driver::Claude,
command: "/old/claude".into(),
args: vec![],
env: BTreeMap::new(),
registry: None,
};
match field {
"name" => agent.name = Some("My Claude".into()),
"driver" => agent.driver = Driver::Acp,
"args" => agent.args.push("--verbose".into()),
"env" => {
agent.env.insert("K".into(), "v".into());
}
"unnamed" => agent.name = None,
_ => unreachable!(),
}
agent.write(&path).unwrap();
set_builtin_command(dir.path(), "claude", Some("/new/claude")).unwrap();
agent.command = "/new/claude".into();
assert_eq!(CustomAgent::read(&path).unwrap(), agent, "{field}");
set_builtin_command(dir.path(), "claude", None).unwrap();
agent.command = "claude".into();
assert_eq!(CustomAgent::read(&path).unwrap(), agent, "{field}");
}
}
#[test]
fn resetting_a_command_only_override_removes_the_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("codex.toml");
std::fs::write(
&path,
"name = \"Codex\"\ndriver = \"codex\"\ncommand = \"/custom/codex\"\nargs = [\"app-server\"]\n",
)
.unwrap();
set_builtin_command(dir.path(), "codex", None).unwrap();
assert!(!path.exists());
assert_eq!(
load(Some(dir.path())).into_iter().find(|s| s.id == "codex").unwrap(),
builtin_spec("codex").unwrap()
);
}
#[test]
fn agent_files_round_trip_with_their_registry_table() {
let dir = tempfile::tempdir().unwrap();
+2 -18
Переглянути файл
@@ -826,15 +826,7 @@ mod tests {
let mut providers: Vec<AgentProvider> = provider::load(Some(&p.agents_dir))
.into_iter()
.filter(|s| s.id == "amp-acp")
.map(|s| AgentProvider {
id: s.id,
name: s.name,
command: s.command,
installed: false,
config: vec![],
commands: vec![],
source: s.source,
})
.map(|s| provider::describe(&s))
.collect();
mark_updates(&p, &mut providers);
assert_eq!(
@@ -1001,15 +993,7 @@ mod tests {
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
let mut providers = vec![AgentProvider {
id: spec.id,
name: spec.name,
command: spec.command,
installed: true,
config: vec![],
commands: vec![],
source: spec.source,
}];
let mut providers = vec![provider::describe(&spec)];
mark_updates(&p, &mut providers);
assert_eq!(
providers[0].source,
+1 -1
Переглянути файл
@@ -18,7 +18,7 @@ mod xml;
pub use gradle::{GradleModel, GradleProject, GradleTask};
pub use maven::{MavenDependency, MavenModel, MavenPlugin, MavenProfile, MavenProject, Omission};
pub use sync::{SyncOptions, SyncProgress, sync_gradle, sync_maven};
pub use sync::{SyncOptions, SyncProgress, maven_profiles, save_maven_profiles, sync_gradle, sync_maven};
use serde::{Deserialize, Serialize};
use specta::Type;
+36 -4
Переглянути файл
@@ -966,13 +966,19 @@ fn rel_path(root: &Path, p: &Path) -> String {
}
/// The POMs that are not modules of another one: the root `pom.xml`, else the
/// shallowest `pom.xml` of each branch (a folder holding several builds).
/// shallowest `pom.xml` of each branch (a folder holding several builds). An
/// aggregate POM directly inside `src/` counts too (issue #1001: `src/pom.xml`
/// with its modules beside it, `src/app/pom.xml` and so on).
fn top_level_poms(root: &Path) -> Vec<PathBuf> {
let top = root.join("pom.xml");
if top.is_file() {
return vec![top];
}
let mut out = Vec::new();
let src_pom = root.join("src").join("pom.xml");
if src_pom.is_file() {
out.push(src_pom);
}
let mut queue: Vec<(PathBuf, usize)> = vec![(root.to_path_buf(), 0)];
while let Some((dir, depth)) = queue.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
@@ -986,9 +992,16 @@ fn top_level_poms(root: &Path) -> Vec<PathBuf> {
}
dirs.sort();
for d in dirs.into_iter().rev() {
if d.join("pom.xml").is_file() {
out.push(d.join("pom.xml"));
} else if depth + 1 < POM_SEARCH_DEPTH {
let pom = d.join("pom.xml");
if pom.is_file() {
out.push(pom);
continue;
}
let src_pom = d.join("src").join("pom.xml");
if src_pom.is_file() {
out.push(src_pom);
}
if depth + 1 < POM_SEARCH_DEPTH {
queue.push((d, depth + 1));
}
}
@@ -1706,6 +1719,25 @@ mod tests {
assert!(!is_maven_project(&root.join("c")));
}
#[test]
fn aggregate_pom_in_src_is_a_build() {
// Issue #1001: `src/pom.xml` aggregating modules under `src/` is recognized,
// with its modules loaded — while `src` stays unsearched otherwise.
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(
root,
"src/pom.xml",
"<project><groupId>g</groupId><artifactId>parent</artifactId><packaging>pom</packaging>\
<modules><module>app</module></modules></project>",
);
write(root, "src/app/pom.xml", "<project><groupId>g</groupId><artifactId>app</artifactId></project>");
let model = load_with_repo(root, None);
let names: Vec<&str> = model.projects.iter().map(|p| p.artifact_id.as_str()).collect();
assert_eq!(names, ["parent", "app"]);
assert!(is_maven_project(root));
}
#[test]
fn property_interpolation() {
let props: HashMap<String, String> =
+18
Переглянути файл
@@ -88,6 +88,24 @@ fn maven_sync_goals(effective: &Path, offline: bool) -> Vec<String> {
]
}
const GRADLE_CACHE: &str = "gradle.json";
const MAVEN_PROFILES: &str = "maven-profiles.json";
/// The Maven profiles (`-P` entries, `!id` deactivates) the project was last synced
/// with: what the IDE resolves it with besides `mvn` (the Java language server, Build Project).
pub fn maven_profiles(cache_dir: &Path) -> Vec<String> {
read_cache(cache_dir, MAVEN_PROFILES).unwrap_or_default()
}
/// Records the profiles of a sync for [`maven_profiles`]; `true` when they changed.
pub fn save_maven_profiles(cache_dir: &Path, profiles: &[String]) -> IdeResult<bool> {
if maven_profiles(cache_dir) == profiles {
return Ok(false);
}
std::fs::create_dir_all(cache_dir)?;
let json = serde_json::to_vec(profiles).map_err(|e| IdeError::internal(e.to_string()))?;
std::fs::write(cache_dir.join(MAVEN_PROFILES), json)?;
Ok(true)
}
fn read_cache<T: DeserializeOwned>(dir: &Path, name: &str) -> Option<T> {
serde_json::from_slice(&std::fs::read(dir.join(name)).ok()?).ok()
+8
Переглянути файл
@@ -23,6 +23,13 @@ pub fn providers(host: &Host, window: &str) -> IdeResult<Vec<AgentProvider>> {
Ok(providers)
}
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
pub fn set_command(host: &Host, window: &str, id: String, command: Option<String>) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.set_builtin_command(&id, command)
}
/// Where ACP Registry agents are saved (`<config>/agents`, like the user's own) and installed.
pub(crate) fn registry_paths(host: &Host) -> RegistryPaths {
RegistryPaths::new(&host.config_dir, &host.local_data_dir)
@@ -187,6 +194,7 @@ pub async fn base_text(host: &Host, window: &str, task: String, path: IpcPath) -
pub(crate) fn register(d: &mut Dispatcher) {
d.add("agent_subscribe", |c| async move { subscribe(&c.host, &c.window, c.channel("onEvent")?) });
d.add("agent_providers", |c| async move { providers(&c.host, &c.window) });
d.add("agent_set_command", |c| async move { set_command(&c.host, &c.window, c.arg("id")?, c.arg("command")?) });
d.add("agent_registry_list", |c| async move { registry_list(&c.host, &c.window, c.arg("request")?).await });
d.add("agent_registry_install", |c| async move {
registry_install(&c.host, &c.window, c.arg("id")?, c.arg("request")?, c.sender("onEvent")?).await
+25 -2
Переглянути файл
@@ -74,6 +74,18 @@ pub fn load(root: &Path, cache: &Path, settings: &Settings) -> BuildModel {
model
}
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
/// the tool window do.
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
let profiles = ide_build::maven_profiles(cache);
if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) {
for p in &mut m.projects {
p.options.push(format!("-P{}", profiles.join(",")));
}
}
model
}
/// Maven and Gradle projects of the window's project, from the build files plus the last sync.
pub async fn build_model(host: &Host, window: &str) -> IdeResult<BuildModel> {
host.require_trust(window)?;
@@ -98,6 +110,12 @@ pub async fn build_sync(
let project = host.project(window)?;
let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective());
let bridge_profiles = profiles.clone();
// What the Java language server and Build Project resolve the project with from now on.
let profiles_changed = tool == BuildTool::Maven
&& ide_build::save_maven_profiles(&cache, &profiles).unwrap_or_else(|e| {
tracing::warn!("Maven profiles not saved: {e}");
false
});
let token = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
let current = load(&root, &cache, &settings);
@@ -152,6 +170,10 @@ pub async fn build_sync(
let lsp = project.lsp.clone();
let uris = build_files.iter().map(|f| ide_lsp::path_to_uri_string(&project.root.join(f))).collect();
tokio::spawn(async move {
if profiles_changed {
// jdtls takes the profiles from its Maven settings (see `ide_sdk::maven_profiles`).
lsp.reconfigure().await;
}
if let Err(e) = lsp.java_update_project_configs(&project.root, uris).await {
tracing::debug!("java/projectConfigurationsUpdate: {e}");
}
@@ -257,7 +279,8 @@ pub async fn build_run(
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
let member_cache = cache.join(crate::project::project_key(member));
let plan = compile::plan(member, &load(member, &member_cache, &settings), kind, file.as_deref())?;
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
let plan = compile::plan(member, &model, kind, file.as_deref())?;
match &mut combined {
Some(combined) => combined.steps.extend(plan.steps),
None => combined = Some(plan),
@@ -267,7 +290,7 @@ pub async fn build_run(
plan.title = workspace.name;
plan
} else {
compile::plan(&root, &load(&root, &cache, &settings), kind, file.as_deref())?
compile::plan(&root, &with_profiles(load(&root, &cache, &settings), &cache), kind, file.as_deref())?
};
let result = compile::run(&root, &plan, &token, &|e| {
let _ = on_event.send(e);
+1 -1
Переглянути файл
@@ -91,7 +91,7 @@ mod tests {
let host = Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
local_data_dir: base.join("data"),
local_data_dir: base.join("local"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(|_| {})),
+10
Переглянути файл
@@ -129,6 +129,7 @@ impl Host {
let root = root.clone();
let data_dir = self.local_data_dir.clone();
let config_dir = self.config_dir.clone();
let build_cache = self.local_data_dir.join("cache").join(&project_key).join("build");
let sink = sink.clone();
let formatter_problem = std::sync::Mutex::new(None);
lsp.set_config_hook(Box::new(move |cfg, server_root| {
@@ -142,6 +143,15 @@ impl Host {
let root = member.as_ref().unwrap_or(&root);
ide_sdk::apply::server_launch_overrides(cfg, &effective);
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
if cfg.name == "jdtls" {
// A workspace member keeps its build model under its own key (Build Project).
let cache = match &member {
Some(member) => build_cache.join(crate::project::project_key(member)),
None => build_cache.clone(),
};
let profiles = ide_build::maven_profiles(&cache);
ide_sdk::maven_profiles::configure_jdtls(cfg, root, &effective, &profiles, &cache);
}
ide_sdk::java::cap_java_home(cfg, &ide_sdk::java::installed_jdks());
if cfg.name == "jdtls" {
let problem = ide_lsp::jdtls::configure_formatter(
+1
Переглянути файл
@@ -24,6 +24,7 @@ globset.workspace = true
ignore.workspace = true
toml.workspace = true
percent-encoding = "2"
zip.workspace = true
[dev-dependencies]
tempfile.workspace = true
+7
Переглянути файл
@@ -228,6 +228,10 @@ impl Handler for ClientHandler {
"window/logMessage" => {
let text = params.get("message").and_then(Value::as_str).unwrap_or_default();
match params.get("type").and_then(Value::as_u64) {
Some(1) if self.server.name == "jdtls" && text.contains(crate::jdtls::reserved_names::IMPORT_FAILURE) => {
tracing::warn!("[{}] {text}", self.server.name);
mgr.report_import_failure(self.server.root.clone(), text.to_owned());
}
Some(1) => tracing::warn!("[{}] {text}", self.server.name),
Some(2 | 3) => tracing::info!("[{}] {text}", self.server.name),
_ => tracing::debug!("[{}] {text}", self.server.name),
@@ -237,6 +241,9 @@ impl Handler for ClientHandler {
"language/status" if self.server.name == "jdtls" && params["type"] == "ServiceReady" => {
mgr.java_import_ready(self.server.clone(), self.generation);
}
"language/status" if self.server.name == "jdtls" && params["type"] == "ProjectStatus" => {
mgr.java_projects_updated(self.server.clone(), self.generation);
}
// The Angular server's project loading, shown like `$/progress`; one
// task while several projects load.
"angular/projectLoadingStart" if !self.server.progress.lock().contains_key(ANGULAR_LOADING) => self
+48
Переглянути файл
@@ -20,6 +20,7 @@ const SERVER: &str = "jdtls";
pub(crate) mod configuration;
mod formatter;
pub(crate) mod reserved_names;
pub use formatter::configure_formatter;
/// First start imports the Maven / Gradle model, which can take minutes.
const READY_TIMEOUT: Duration = Duration::from_secs(240);
@@ -335,6 +336,35 @@ impl LspManager {
});
}
/// jdtls reports `ProjectStatus` when an import or project update ends (a POM
/// change, a Maven sync, other Maven profiles), but does not check open documents
/// again against the new classpath: their errors would stay until the next edit.
pub(crate) fn java_projects_updated(self: &Arc<Self>, server: Arc<Server>, generation: u64) {
let uris: Vec<String> = self
.docs
.lock()
.values()
.filter(|d| d.language.as_str() == "java" && d.path.starts_with(&server.root))
.map(|d| crate::uri::path_to_uri_string(&d.path))
.collect();
if uris.is_empty() {
return;
}
self.runtime.spawn(async move {
let Some(run) = server.running_gen(generation) else { return };
for uri in uris {
let params =
json!({ "command": "java.project.refreshDiagnostics", "arguments": [uri, "thisFile", false] });
let request = run.peer.request::<_, Value>("workspace/executeCommand", params, None);
if let Ok(Err(e)) | Err(e) =
tokio::time::timeout(COMMAND_TIMEOUT, request).await.map_err(|_| ide_jsonrpc::RpcError::Timeout)
{
tracing::debug!("jdtls: java.project.refreshDiagnostics {uri}: {e}");
}
}
});
}
/// The jdtls instance serving `path` (a module directory or source file),
/// started if needed and waited for.
async fn jdtls(&self, path: &Path, cancel: &CancellationToken) -> IdeResult<(Arc<Server>, Running)> {
@@ -664,6 +694,24 @@ impl LspManager {
}
}
impl LspManager {
/// JDT LS aborted its import with `message`: when reserved Windows device names
/// below `root` are the cause, say which (once). The walk runs off the RPC thread.
pub(crate) fn report_import_failure(&self, root: PathBuf, message: String) {
let Some(me) = self.me.upgrade() else { return };
self.runtime.spawn_blocking(move || {
let Some(body) = reserved_names::import_failure_hint(&root, &message, cfg!(windows)) else { return };
if me.first_message(SERVER, &body) {
me.sink().emit(ide_core::IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Error,
title: "Java project import failed".into(),
body: Some(body),
});
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
+180
Переглянути файл
@@ -0,0 +1,180 @@
//! Windows reserved device names (`nul`, `con`, …) inside a Java project.
//!
//! On Windows, a directory listing returns such a file (often left by a shell
//! redirect like `2>nul` in Git Bash), but `Files.exists` reports it missing as the
//! name resolves to the device. Eclipse's resource refresh then builds a child path
//! with an empty name and the Maven / Gradle import aborts during JDT LS
//! initialization with "Path must include project and resource name", so no Java
//! project is created. The user only sees every run fail with "module is not
//! imported"; this names the files that cause it.
use std::path::{Path, PathBuf};
/// What JDT LS logs when the import aborts on such an entry.
pub(crate) const IMPORT_FAILURE: &str = "Path must include project and resource name";
/// Directory entries visited per scan, and reserved names reported at most.
const MAX_VISITED: usize = 200_000;
const MAX_REPORTED: usize = 20;
/// Whether Windows treats `name` as a device: CON, PRN, AUX, NUL, COM0–9 or LPT0–9
/// (also with superscript digits), in any case, with or without an extension and
/// trailing spaces or dots.
pub(crate) fn is_reserved_device_name(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or_default().trim_end_matches(' ');
let upper = stem.to_ascii_uppercase();
if ["CON", "PRN", "AUX", "NUL"].contains(&upper.as_str()) {
return true;
}
let mut chars = upper.chars();
let prefix: String = chars.by_ref().take(3).collect();
let digit: Vec<char> = chars.collect();
(prefix == "COM" || prefix == "LPT")
&& matches!(digit.as_slice(), [d] if d.is_ascii_digit() || matches!(d, '¹' | '²' | '³'))
}
/// Entries below `root` with a reserved device name, in walk order (bounded).
/// Ignore files are not honoured: Eclipse's refresh does not honour them either.
pub(crate) fn reserved_entries(root: &Path) -> Vec<PathBuf> {
ignore::WalkBuilder::new(root)
.standard_filters(false)
.follow_links(false)
.build()
.take(MAX_VISITED)
.filter_map(Result::ok)
.filter(|entry| entry.depth() > 0 && entry.file_name().to_str().is_some_and(is_reserved_device_name))
.map(ignore::DirEntry::into_path)
.take(MAX_REPORTED)
.collect()
}
/// The notification body for a JDT LS log `message` from the server at `root`:
/// the reserved-name entries that abort the import, when the message is that
/// failure and the host is Windows (elsewhere such names are ordinary files).
pub(crate) fn import_failure_hint(root: &Path, message: &str, windows: bool) -> Option<String> {
if !windows || !message.contains(IMPORT_FAILURE) {
return None;
}
let entries = reserved_entries(root);
if entries.is_empty() {
return None;
}
let paths = entries
.iter()
.map(|path| path.strip_prefix(root).unwrap_or(path).display().to_string())
.collect::<Vec<_>>()
.join(", ");
Some(format!(
"The Java project cannot be imported because these files use a name Windows reserves for devices: {paths}. Delete or rename them, then restart the Java language server."
))
}
#[cfg(test)]
mod tests {
use super::*;
/// A path Windows does not resolve to a device (`\\?\`): the only way to create a
/// file named `nul` there. Elsewhere such names are ordinary files.
fn verbatim(path: &Path) -> PathBuf {
let text = path.to_string_lossy();
if cfg!(windows) && !text.starts_with(r"\\?\") {
PathBuf::from(format!(r"\\?\{text}"))
} else {
path.to_path_buf()
}
}
/// Writes `root` / `parts` (joined per component: verbatim paths take no `/`).
fn write(root: &Path, parts: &[&str], text: &str) {
let path = parts.iter().fold(root.to_path_buf(), |path, part| path.join(part));
std::fs::create_dir_all(verbatim(path.parent().unwrap())).unwrap();
std::fs::write(verbatim(&path), text).unwrap();
}
/// Removes a tree that may hold reserved names, which a plain path cannot delete on Windows.
fn remove(dir: tempfile::TempDir) {
let _ = std::fs::remove_dir_all(verbatim(&dir.keep()));
}
#[test]
fn reserved_device_names() {
for name in [
"nul",
"NUL",
"Nul",
"nul.txt",
"nul.tar.gz",
"nul ",
"con",
"prn",
"aux",
"com1",
"COM9",
"com0",
"lpt1",
"LPT9",
"com¹",
"lpt³",
"aux.java",
] {
assert!(is_reserved_device_name(name), "{name}");
}
for name in [
"null",
"nuls",
"anul",
"console",
"auxiliary",
"com",
"com10",
"lpt",
"lptx",
"comA",
".nul",
"",
"src",
"pom.xml",
"nul_file",
] {
assert!(!is_reserved_device_name(name), "{name}");
}
}
#[test]
fn import_failure_names_the_reserved_entries() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
write(root, &["nul"], "54 bytes of shell output");
write(root, &["module", "aux.txt"], "");
write(root, &["node_modules", "x", "con"], "");
write(root, &["module", "src", "Null.java"], "class Null {}");
write(root, &[".gitignore"], "nul\nnode_modules/\n");
let message = "Initialization failed | java.lang.IllegalArgumentException: Path must include project and resource name: /bkbits-parent | at UnifiedTree.createChildNodeFromFileSystem(UnifiedTree.java:320)";
let hint = import_failure_hint(root, message, true).unwrap();
let sep = std::path::MAIN_SEPARATOR;
for path in ["nul".to_owned(), format!("module{sep}aux.txt"), format!("node_modules{sep}x{sep}con")] {
assert!(hint.contains(&path), "{path} missing from {hint}");
}
assert!(!hint.contains("Null.java"));
assert!(hint.ends_with("then restart the Java language server."));
// Other failures, other hosts, and projects without such names stay silent.
assert_eq!(import_failure_hint(root, "Initialization failed | java.lang.NullPointerException", true), None);
assert_eq!(import_failure_hint(root, message, false), None);
let clean = tempfile::tempdir().unwrap();
write(clean.path(), &["pom.xml"], "<project/>");
assert_eq!(import_failure_hint(clean.path(), message, true), None);
remove(dir);
}
#[test]
fn reports_a_bounded_number_of_entries() {
let dir = tempfile::tempdir().unwrap();
for i in 0..30 {
write(dir.path(), &[&format!("m{i}"), "nul"], "");
}
assert_eq!(reserved_entries(dir.path()).len(), MAX_REPORTED);
remove(dir);
}
}
+112 -24
Переглянути файл
@@ -16,6 +16,7 @@ mod handler;
mod inspect;
pub mod jdtls;
mod launch;
mod library_source;
mod scope;
mod server;
mod tcp;
@@ -273,6 +274,30 @@ impl<T> Outcome<T> {
/// Implementation requests of one line-marker pass in flight at once.
const IMPLEMENTATION_CONCURRENCY: usize = 4;
/// Library classes in `jar:` targets (the official Kotlin LSP) go to their source
/// in the artifact's sources jar when it is cached, at the declaration of the
/// name navigated from; [`LspManager::virtual_document`] serves it.
async fn library_sources(snap: &DocSnap, pos: Pos, locs: Vec<Location>) -> Vec<Location> {
if !locs.iter().any(|l| l.uri.as_deref().is_some_and(|u| u.starts_with("jar:") && u.ends_with(".class"))) {
return locs;
}
let name = library_source::identifier_at(snap.text.line(pos.line as usize), pos.col).map(str::to_owned);
tokio::task::spawn_blocking(move || {
locs.into_iter()
.map(|loc| {
let Some(uri) = loc.uri.as_deref().filter(|u| u.starts_with("jar:") && u.ends_with(".class")) else {
return loc;
};
let Some((source, text)) = library_source::class_source(uri) else { return loc };
let range = name.as_deref().map(|n| library_source::declaration_range(&text, n)).unwrap_or_default();
Location { path: source.clone().into(), range, uri: Some(source) }
})
.collect()
})
.await
.unwrap_or_default()
}
fn goto_method(kind: GotoKind) -> (&'static str, &'static str, &'static str) {
match kind {
GotoKind::Definition => ("textDocument/definition", "definitionProvider", "go to definition"),
@@ -1187,6 +1212,7 @@ impl LspManager {
{
Ok(Some(r)) => {
let locs = convert::goto_response(&self.conv(t.enc()), r);
let locs = library_sources(snap, pos, locs).await;
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
if !locs.is_empty() {
return Ok(locs);
@@ -2218,12 +2244,35 @@ impl LspManager {
/// Contents of a virtual document, from the server that owns `uri`:
/// `workspace/textDocumentContent` (LSP 3.18) when the server serves the
/// scheme, jdtls' `java/classFileContents` for `jdt:` URIs. Cached.
/// scheme, jdtls' `java/classFileContents` for `jdt:` URIs. A `jar:` entry
/// is read from its archive, a `jar:` class shown as its library source
/// (see [`library_source`]) or else decompiled by the server. Cached.
pub async fn virtual_document(&self, uri: &str) -> IdeResult<VirtualDocument> {
if let Some(d) = self.virtual_docs.lock().get(uri) {
return Ok(d.clone());
}
let scheme = virtual_doc::scheme(uri).to_owned();
let jar_class = scheme == "jar" && library_source::parse(uri).is_some_and(|e| e.entry.ends_with(".class"));
if scheme == "jar" {
let found = {
let uri = uri.to_owned();
tokio::task::spawn_blocking(move || match library_source::parse(&uri) {
Some(e) if !e.entry.ends_with(".class") => {
library_source::read_entry(&e.jar, &e.entry).map(|text| (e.entry, text))
}
Some(_) => library_source::class_source(&uri)
.and_then(|(source, text)| Some((library_source::parse(&source)?.entry, text))),
None => None,
})
.await
.ok()
.flatten()
};
if let Some((entry, text)) = found {
let title = entry.rsplit('/').next().unwrap_or(&entry).to_owned();
return Ok(self.store_virtual(uri, text, Some(title), &[], self.origin_server(uri).map(|s| s.id)));
}
}
let class_file = scheme == "jdt" || (scheme == "file" && uri.ends_with(".class"));
let origin = self.origin_server(uri);
let mut servers: Vec<Arc<Server>> = origin.iter().cloned().collect();
@@ -2246,6 +2295,25 @@ impl LspManager {
} else if class_file && languages.iter().any(|l| l.as_str() == "java") {
self.call::<_, Option<String>>(t, "java/classFileContents", json!({ "uri": uri }), None, LONG_TIMEOUT)
.await
} else if jar_class && t.caps().commands().iter().any(|c| c == "decompile") {
// The official Kotlin LSP: `decompile` answers `{ code, language }`.
self.call::<_, Option<Value>>(
t,
"workspace/executeCommand",
json!({ "command": "decompile", "arguments": [uri] }),
None,
LONG_TIMEOUT,
)
.await
.map(|v| {
v.and_then(|v| match v {
Value::String(text) => Some(text),
v => ["code", "text", "content"]
.iter()
.find_map(|k| v.get(k).and_then(Value::as_str))
.map(str::to_owned),
})
})
} else {
continue;
};
@@ -2257,33 +2325,53 @@ impl LspManager {
continue;
}
};
let decompiled = virtual_doc::is_decompiled(&text);
let title = virtual_doc::title(uri, decompiled);
let detected = self.languages.detect(Path::new(&title), None);
let language_id = if detected == LanguageId::plain_text() {
languages.first().cloned().unwrap_or(detected)
} else {
detected
};
let doc = VirtualDocument {
uri: uri.to_owned(),
text,
language_id,
title,
description: virtual_doc::description(uri),
decompiled,
};
self.virtual_origins.lock().entry(uri.to_owned()).or_insert(t.server.id);
let mut cache = self.virtual_docs.lock();
if cache.len() >= VIRTUAL_CACHE_LIMIT {
cache.clear();
}
cache.insert(uri.to_owned(), doc.clone());
return Ok(doc);
return Ok(self.store_virtual(uri, text, None, &languages, Some(t.server.id)));
}
if jar_class && error.is_none() {
return Err(IdeError::not_found(format!(
"no source or decompiler is available for {}: its sources jar is not in the local Maven or Gradle cache, and no language server decompiles it",
virtual_doc::title(uri, false)
)));
}
Err(error.unwrap_or_else(|| IdeError::not_found(format!("no language server provides the contents of {uri}"))))
}
/// Caches `text` as the virtual document `uri`, titled `title` (else after the URI).
fn store_virtual(
&self,
uri: &str,
text: String,
title: Option<String>,
languages: &[LanguageId],
server: Option<ide_core::ServerId>,
) -> VirtualDocument {
let decompiled = virtual_doc::is_decompiled(&text);
let title = title.unwrap_or_else(|| virtual_doc::title(uri, decompiled));
let detected = self.languages.detect(Path::new(&title), None);
let language_id = if detected == LanguageId::plain_text() {
languages.first().cloned().unwrap_or(detected)
} else {
detected
};
let doc = VirtualDocument {
uri: uri.to_owned(),
text,
language_id,
title,
description: virtual_doc::description(uri),
decompiled,
};
if let Some(server) = server {
self.virtual_origins.lock().entry(uri.to_owned()).or_insert(server);
}
let mut cache = self.virtual_docs.lock();
if cache.len() >= VIRTUAL_CACHE_LIMIT {
cache.clear();
}
cache.insert(uri.to_owned(), doc.clone());
doc
}
/// Called when a server sends `workspace/applyEdit`; installed by `src-tauri`
/// so edits flow through `ide-workspace::Documents`.
pub fn set_config_hook(&self, hook: Box<ConfigFn>) {
+299
Переглянути файл
@@ -0,0 +1,299 @@
//! `jar:` URIs (`jar:///…/lib.jar!/pkg/Name.class`, also `jar:file:///…`) that
//! language servers return for library code: the official Kotlin LSP for the
//! classes of a dependency, Metals and others for entries of a sources jar.
//! Not every server can serve their contents (`workspace/textDocumentContent`),
//! so they are read here, where the jars are (also on a remote backend): an
//! entry as is, a class as its source from the artifact's `-sources.jar` next to
//! it in the Maven or Gradle cache.
use ide_core::{Pos, Range};
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
use std::io::Read;
use std::path::{Path, PathBuf};
/// An entry of an archive named by a `jar:` URI.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct JarEntry {
/// The URI up to the archive path (`jar:///` or `jar:file:///`), kept for new URIs.
prefix: String,
pub jar: PathBuf,
/// `/`-separated, without a leading `/`.
pub entry: String,
}
pub(crate) fn parse(uri: &str) -> Option<JarEntry> {
let rest = uri.strip_prefix("jar:")?;
let (archive, entry) = rest.split_once("!/")?;
let (prefix, path) = if let Some(path) = archive.strip_prefix("file://") {
("jar:file://", path)
} else if let Some(path) = archive.strip_prefix("//") {
("jar://", path)
} else {
("jar:", archive)
};
let path = percent_decode_str(path).decode_utf8().ok()?;
let path = if cfg!(windows) {
// `/C:/x` → `C:\x`
let trimmed = path.strip_prefix('/').filter(|s| s.as_bytes().get(1) == Some(&b':')).unwrap_or(&path);
PathBuf::from(trimmed.replace('/', "\\"))
} else {
PathBuf::from(path.into_owned())
};
let entry = percent_decode_str(entry.split(['?', '#']).next().unwrap_or(entry)).decode_utf8().ok()?;
Some(JarEntry { prefix: prefix.to_owned(), jar: path, entry: entry.trim_start_matches('/').to_owned() })
}
const PATH: &AsciiSet = &CONTROLS.add(b' ').add(b'#').add(b'%').add(b'?').add(b'!');
impl JarEntry {
/// The URI of `entry` in `jar`, written like the URI this one came from.
fn uri_of(&self, jar: &Path, entry: &str) -> String {
let mut path = jar.to_string_lossy().replace('\\', "/");
if !path.starts_with('/') {
path.insert(0, '/');
}
let encode = |s: &str| utf8_percent_encode(s, PATH).to_string();
format!("{}{}!/{}", self.prefix, encode(&path), encode(entry))
}
}
/// The text of `entry` in the archive `jar`, when it is a UTF-8 file.
pub(crate) fn read_entry(jar: &Path, entry: &str) -> Option<String> {
let mut zip = zip::ZipArchive::new(std::fs::File::open(jar).ok()?).ok()?;
let mut file = zip.by_name(entry).ok()?;
let mut text = String::new();
file.read_to_string(&mut text).ok()?;
Some(text)
}
/// The library source for a class entry: its `.kt` / `.java` file in the
/// artifact's sources jar, as `(uri, text)`.
pub(crate) fn class_source(uri: &str) -> Option<(String, String)> {
let jar = parse(uri)?;
let class = jar.entry.strip_suffix(".class")?;
for sources in sources_jars(&jar.jar) {
if let Some((entry, text)) = source_entry(&sources, class) {
return Some((jar.uri_of(&sources, &entry), text));
}
}
None
}
/// Sources jars of the artifact `jar`: `<name>-sources.jar` next to it (Maven
/// repository), or in a sibling hash folder (Gradle `files-2.1/<g>/<a>/<v>/<hash>/`).
fn sources_jars(jar: &Path) -> Vec<PathBuf> {
let (Some(dir), Some(stem)) = (jar.parent(), jar.file_stem().and_then(|s| s.to_str())) else { return vec![] };
let name = format!("{stem}-sources.jar");
let mut out: Vec<PathBuf> = vec![dir.join(&name)];
if let Some(version_dir) = dir.parent()
&& version_dir.ancestors().any(|a| a.file_name().is_some_and(|n| n == "files-2.1"))
&& let Ok(entries) = std::fs::read_dir(version_dir)
{
out.extend(entries.flatten().map(|e| e.path().join(&name)));
}
out.retain(|p| p.is_file());
out
}
/// The source file of `class` (`pkg/Name`, `pkg/Outer$Inner`, `pkg/FileKt`) in `sources`.
fn source_entry(sources: &Path, class: &str) -> Option<(String, String)> {
let mut zip = zip::ZipArchive::new(std::fs::File::open(sources).ok()?).ok()?;
let (package, name) = class.rsplit_once('/').unwrap_or(("", class));
let outer = name.split('$').next().unwrap_or(name);
let dir = if package.is_empty() { String::new() } else { format!("{package}/") };
let mut candidates = vec![format!("{dir}{outer}.java"), format!("{dir}{outer}.kt")];
// Top-level Kotlin declarations compile to a `<File>Kt` facade class.
if let Some(file) = outer.strip_suffix("Kt").filter(|f| !f.is_empty()) {
candidates.push(format!("{dir}{file}.kt"));
}
let read = |zip: &mut zip::ZipArchive<std::fs::File>, entry: &str| {
let mut text = String::new();
zip.by_name(entry).ok()?.read_to_string(&mut text).ok()?;
Some(text)
};
for entry in &candidates {
if let Some(text) = read(&mut zip, entry) {
return Some((entry.clone(), text));
}
}
// A facade renamed with `@file:JvmName("…")`.
let kotlin_files: Vec<String> = zip
.file_names()
.filter_map(|n| n.ok().map(|n| n.into_owned()))
.filter(|n| n.ends_with(".kt") && n.strip_prefix(&dir).is_some_and(|rest| !rest.contains('/')))
.collect();
let jvm_name = format!("@file:JvmName(\"{outer}\")");
for entry in kotlin_files {
if let Some(text) = read(&mut zip, &entry)
&& text.contains(&jvm_name)
{
return Some((entry, text));
}
}
None
}
/// Where `name` is declared in a Kotlin or Java source `text` (the start of the
/// name), else the start of the file.
pub(crate) fn declaration_range(text: &str, name: &str) -> Range {
const KEYWORDS: [&str; 9] = ["fun", "class", "interface", "object", "val", "var", "typealias", "enum", "record"];
let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
let mut fallback = None;
for (line_no, line) in text.lines().enumerate() {
let mut from = 0;
while let Some(i) = line[from..].find(name) {
let start = from + i;
let end = start + name.len();
from = end;
let before = line[..start].chars().next_back();
let after = line[end..].chars().next();
if before.is_some_and(is_ident) || after.is_some_and(is_ident) {
continue;
}
let head = &line[..start];
let words: Vec<&str> = head.split(|c: char| !is_ident(c)).filter(|w| !w.is_empty()).collect();
let col = head.encode_utf16().count() as u32;
let range = Range {
start: Pos::new(line_no as u32, col),
end: Pos::new(line_no as u32, col + name.encode_utf16().count() as u32),
};
// Kotlin: `fun <T> Foo.name(`, `class Name`; Java: `… Type name(`.
if words.iter().any(|w| KEYWORDS.contains(w)) {
return range;
}
let java_member =
after == Some('(') && !head.trim_end().ends_with('.') && !head.trim().is_empty() && !head.contains('=');
if java_member && fallback.is_none() {
fallback = Some(range);
}
}
}
fallback.unwrap_or_default()
}
/// The identifier around `col` (UTF-16) of `line`.
pub(crate) fn identifier_at(line: &str, col: u32) -> Option<&str> {
let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
let mut utf16 = 0u32;
let mut at = line.len();
for (i, c) in line.char_indices() {
if utf16 >= col {
at = i;
break;
}
utf16 += c.len_utf16() as u32;
}
let start =
line[..at].rfind(|c: char| !is_ident(c)).map_or(0, |i| i + line[i..].chars().next().map_or(1, char::len_utf8));
let end = line[at..].find(|c: char| !is_ident(c)).map_or(line.len(), |i| at + i);
let word = &line[start..end];
(!word.is_empty() && !word.starts_with(|c: char| c.is_ascii_digit())).then_some(word)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn jar(path: &Path, entries: &[(&str, &str)]) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut zip = zip::ZipWriter::new(std::fs::File::create(path).unwrap());
for (name, text) in entries {
zip.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(text.as_bytes()).unwrap();
}
zip.finish().unwrap();
}
const EXTENSIONS: &str = "package org.springframework.boot\n\nimport kotlin.reflect.KClass\n\n/**\n * Top-level function acting as a Kotlin shortcut allowing to write\n * `runApplication<Foo>(arg1, arg2)` instead of `SpringApplication.run(Foo::class.java, arg1, arg2)`.\n */\ninline fun <reified T : Any> runApplication(vararg args: String): ConfigurableApplicationContext =\n\t\tSpringApplication.run(T::class.java, *args)\n";
#[test]
fn parses_both_jar_uri_forms() {
for uri in [
"jar:///home/me/.m2/repository/b/spring-boot-3.5.16.jar!/org/springframework/boot/SpringApplicationExtensionsKt.class",
"jar:file:///home/me/.m2/repository/b/spring-boot-3.5.16.jar!/org/springframework/boot/SpringApplicationExtensionsKt.class",
] {
let e = parse(uri).unwrap();
if !cfg!(windows) {
assert_eq!(e.jar, PathBuf::from("/home/me/.m2/repository/b/spring-boot-3.5.16.jar"));
}
assert_eq!(e.entry, "org/springframework/boot/SpringApplicationExtensionsKt.class");
assert_eq!(e.uri_of(&e.jar, &e.entry), uri, "written back the same way");
}
let spaced = parse("jar:///tmp/my%20libs/a.jar!/A.class").unwrap();
assert!(spaced.jar.to_string_lossy().contains("my libs"));
assert_eq!(spaced.uri_of(&spaced.jar, "A.kt"), "jar:///tmp/my%20libs/a.jar!/A.kt");
assert_eq!(parse("jdt://contents/a.jar/A.class"), None);
assert_eq!(parse("jar:///no/entry.jar"), None);
}
#[test]
fn finds_the_source_of_each_kind_of_class_in_maven_and_gradle_caches() {
let tmp = tempfile::tempdir().unwrap();
let m2 = tmp.path().join("m2/org/springframework/boot/spring-boot/3.5.16");
let gradle = tmp.path().join("gradle/caches/modules-2/files-2.1/org.springframework.boot/spring-boot/3.5.16");
let sources: &[(&str, &str)] = &[
("org/springframework/boot/SpringApplicationExtensions.kt", EXTENSIONS),
("org/springframework/boot/SpringApplication.java", "public class SpringApplication {}"),
(
"org/springframework/boot/Renamed.kt",
"@file:JvmName(\"BootUtils\")\npackage org.springframework.boot\nfun util() {}",
),
("org/springframework/boot/Builder.kt", "class Builder"),
("Root.java", "class Root {}"),
];
jar(&m2.join("spring-boot-3.5.16.jar"), &[]);
jar(&m2.join("spring-boot-3.5.16-sources.jar"), sources);
// Gradle keeps each file under its own hash folder.
jar(&gradle.join("aaa/spring-boot-3.5.16.jar"), &[]);
jar(&gradle.join("bbb/spring-boot-3.5.16-sources.jar"), sources);
for binary in [m2.join("spring-boot-3.5.16.jar"), gradle.join("aaa/spring-boot-3.5.16.jar")] {
let uri = |class: &str| format!("jar://{}!/{class}", binary.to_string_lossy().replace('\\', "/"));
for (class, file) in [
("org/springframework/boot/SpringApplicationExtensionsKt.class", "SpringApplicationExtensions.kt"),
("org/springframework/boot/SpringApplication.class", "SpringApplication.java"),
("org/springframework/boot/SpringApplication$Running.class", "SpringApplication.java"),
("org/springframework/boot/BootUtils.class", "Renamed.kt"),
("org/springframework/boot/Builder.class", "Builder.kt"),
("Root.class", "Root.java"),
] {
let (source_uri, text) = class_source(&uri(class)).unwrap_or_else(|| panic!("{class} in {binary:?}"));
let dir = class.rsplit_once('/').map_or(String::new(), |(p, _)| format!("{p}/"));
assert!(source_uri.ends_with(&format!("-sources.jar!/{dir}{file}")), "{source_uri}");
assert_eq!(
parse(&source_uri).and_then(|e| read_entry(&e.jar, &e.entry)).as_deref(),
Some(text.as_str())
);
}
assert_eq!(class_source(&uri("org/springframework/boot/Missing.class")), None);
}
// No sources jar: nothing to show from here.
let lone = tmp.path().join("lone/x-1.jar");
jar(&lone, &[]);
assert_eq!(class_source(&format!("jar://{}!/X.class", lone.to_string_lossy().replace('\\', "/"))), None);
}
#[test]
fn locates_declarations_in_kotlin_and_java_sources() {
let at = |text: &str, name: &str| {
let r = declaration_range(text, name);
(r.start.line, r.start.col, r.end.col)
};
assert_eq!(at(EXTENSIONS, "runApplication"), (8, 29, 43), "the declaration, not the KDoc mention");
let java = "package a;\n\npublic class SpringApplication {\n public static ConfigurableApplicationContext run(Class<?> source, String... args) {\n return run(new Class<?>[] { source }, args);\n }\n}\n";
assert_eq!(at(java, "SpringApplication"), (2, 13, 30));
assert_eq!(at(java, "run"), (3, 49, 52), "the member, not the call in its body");
assert_eq!(at("val x = 1", "missing"), (0, 0, 0));
assert_eq!(at("// é\nfun ü() {}", "ü"), (1, 4, 5), "UTF-16 columns");
}
#[test]
fn identifier_under_the_caret() {
let line = " runApplication<Application>(*args)";
assert_eq!(identifier_at(line, 4), Some("runApplication"));
assert_eq!(identifier_at(line, 10), Some("runApplication"));
assert_eq!(identifier_at(line, 18), Some("runApplication"), "right after it");
assert_eq!(identifier_at(line, 20), Some("Application"));
assert_eq!(identifier_at("a + b", 2), None);
}
}
+3
Переглянути файл
@@ -60,6 +60,9 @@ pub fn title(uri: &str, decompiled: bool) -> String {
/// Where the document comes from, e.g. the jar path of a `jdt://` class.
pub fn description(uri: &str) -> Option<String> {
if scheme(uri) == "jar" {
return crate::library_source::parse(uri).map(|e| e.jar.to_string_lossy().into_owned());
}
if scheme(uri) != "jdt" {
return None;
}
+143
Переглянути файл
@@ -1200,6 +1200,105 @@ async fn java_launch_serializes_the_classpath_with_the_build_lock() {
assert!(commands.contains(&"java.project.getClasspaths".to_owned()));
}
#[tokio::test(flavor = "multi_thread")]
async fn open_java_files_are_checked_again_after_a_project_update() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let (_, a) = h.open("A.java", "class A {}");
let (_, b) = h.open("B.java", "class B {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let state = h.launcher.state("jdtls");
let refreshed = || {
let mut uris: Vec<Value> = state
.requested("workspace/executeCommand")
.iter()
.filter(|p| p["command"] == "java.project.refreshDiagnostics")
.map(|p| {
assert_eq!(p["arguments"][1], "thisFile");
p["arguments"][0].clone()
})
.collect();
uris.sort_by_key(|u| u.to_string());
uris
};
// Other status messages leave the documents alone.
state
.peer()
.notify("language/status", json!({ "type": "Message", "message": "Updating project configurations..." }))
.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(refreshed().is_empty());
state.peer().notify("language/status", json!({ "type": "ProjectStatus", "message": "OK" })).unwrap();
let mut expected = vec![json!(uri_of(&a)), json!(uri_of(&b))];
expected.sort_by_key(|u| u.to_string());
eventually(|| refreshed() == expected).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn library_classes_in_jars_open_as_their_source_or_decompiled() {
use std::io::Write;
let jar = |path: &Path, entries: &[(&str, &str)]| {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut zip = zip::ZipWriter::new(std::fs::File::create(path).unwrap());
for (name, text) in entries {
zip.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(text.as_bytes()).unwrap();
}
zip.finish().unwrap();
};
let repo = tempfile::tempdir().unwrap();
let dir = repo.path().join("org/springframework/boot/spring-boot/3.5.16");
let source = "package org.springframework.boot\n\ninline fun <reified T : Any> runApplication(vararg args: String) =\n SpringApplication.run(T::class.java, *args)\n";
jar(
&dir.join("spring-boot-3.5.16.jar"),
&[("org/springframework/boot/SpringApplicationExtensionsKt.class", "\u{0}")],
);
jar(
&dir.join("spring-boot-3.5.16-sources.jar"),
&[("org/springframework/boot/SpringApplicationExtensions.kt", source)],
);
let other = repo.path().join("acme/lib/1.0/lib-1.0.jar");
jar(&other, &[("acme/Thing.class", "\u{0}")]);
let jar_uri = |jar: &Path, entry: &str| format!("jar://{}!/{entry}", uri_of(jar).trim_start_matches("file://"));
let r = |l: u32, c0: u32, c1: u32| json!({"start":{"line":l,"character":c0},"end":{"line":l,"character":c1}});
let mut caps = incremental_caps();
caps["executeCommandProvider"] = json!({ "commands": ["decompile"] });
let h = harness_for("kotlin", "kt", &[("kotlin-lsp", caps)], &[]);
let (doc, _) = h.open("Main.kt", "fun main(args: Array<String>) {\n runApplication<App>(*args)\n}\n");
h.wait_status("kotlin-lsp", ServerStatus::Ready).await;
let s = h.launcher.state("kotlin-lsp");
// A class with a cached sources jar: navigation lands on the declaration in its source.
let class =
jar_uri(&dir.join("spring-boot-3.5.16.jar"), "org/springframework/boot/SpringApplicationExtensionsKt.class");
s.respond("textDocument/definition", json!({ "uri": class, "range": r(7, 43, 57) }));
let defs = h.mgr.goto(doc, Pos::new(1, 8), GotoKind::Definition).await.unwrap();
let sources =
jar_uri(&dir.join("spring-boot-3.5.16-sources.jar"), "org/springframework/boot/SpringApplicationExtensions.kt");
assert_eq!(
defs,
vec![ide_core::Location { path: sources.clone().into(), range: rng(2, 29, 2, 43), uri: Some(sources.clone()) }]
);
let vd = h.mgr.virtual_document(&sources).await.unwrap();
assert_eq!((vd.text.as_str(), vd.title.as_str(), vd.decompiled), (source, "SpringApplicationExtensions.kt", false));
assert_eq!(vd.language_id.as_str(), "kotlin");
// The class URI itself (from usages, say) shows the same source.
assert_eq!(h.mgr.virtual_document(&class).await.unwrap().text, source);
assert!(s.requested("workspace/executeCommand").is_empty(), "no server round trip for cached sources");
// No sources jar: the server's `decompile` command.
let thing = jar_uri(&other, "acme/Thing.class");
s.respond("textDocument/definition", json!({ "uri": thing, "range": r(0, 6, 11) }));
let defs = h.mgr.goto(doc, Pos::new(1, 8), GotoKind::Definition).await.unwrap();
assert_eq!(defs[0].uri.as_deref(), Some(thing.as_str()), "kept as the server returned it");
s.respond("workspace/executeCommand", json!({ "code": "package acme\n\nclass Thing", "language": "kotlin" }));
let vd = h.mgr.virtual_document(&thing).await.unwrap();
assert_eq!(vd.text, "package acme\n\nclass Thing");
let asked = s.requested("workspace/executeCommand");
assert_eq!(asked[0], json!({ "command": "decompile", "arguments": [thing] }));
}
#[tokio::test(flavor = "multi_thread")]
async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
// Preferred installed: the alternative is never started.
@@ -3072,3 +3171,47 @@ async fn java_definition_consults_configuration_only_inside_key_arguments() {
}
assert_eq!(s.requested("workspace/executeCommand").len(), 2);
}
/// JDT LS aborts its Maven import on Windows when the project holds a file with a
/// reserved device name (`nul` left by `2>nul`); the error names those files there
/// and stays silent elsewhere, where such names are ordinary files.
#[tokio::test(flavor = "multi_thread")]
async fn jdtls_import_failure_names_reserved_device_files_on_windows() {
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
let s = h.launcher.state("jdtls");
std::fs::write(h.root.join("pom.xml"), "<project/>").unwrap();
// A file named `nul` cannot be created through the Win32 namespace; on Windows use the verbatim path.
let nul = if cfg!(windows) && !h.root.to_string_lossy().starts_with(r"\\?\") {
PathBuf::from(format!(r"\\?\{}", h.root.join("nul").display()))
} else {
h.root.join("nul")
};
std::fs::write(&nul, "54 bytes").unwrap();
h.open("A.java", "class A {}");
h.wait_status("jdtls", ServerStatus::Ready).await;
let failure = "Initialization failed | java.lang.IllegalArgumentException: Path must include project and resource name: /demo | at UnifiedTree.createChildNodeFromFileSystem(UnifiedTree.java:320)";
for _ in 0..2 {
s.peer().notify("window/logMessage", json!({ "type": 1, "message": failure })).unwrap();
}
s.peer().notify("window/showMessage", json!({ "type": 2, "message": "after" })).unwrap();
eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b == "after")))
.await;
// The scan runs off the RPC thread; give it time to report.
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
let failures: Vec<String> = h
.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Notify { title, body: Some(b), .. } if title == "Java project import failed" => Some(b.clone()),
_ => None,
})
.collect();
if cfg!(windows) {
assert_eq!(failures.len(), 1, "reported once: {failures:?}");
assert!(failures[0].contains("nul"), "{failures:?}");
} else {
assert!(failures.is_empty(), "{failures:?}");
}
let _ = std::fs::remove_file(&nul);
}
+1
Переглянути файл
@@ -16,6 +16,7 @@ pub mod jdtls;
pub mod libraries;
pub mod locate;
pub mod lombok;
pub mod maven_profiles;
mod npm;
pub mod pinned;
pub mod python;
+239
Переглянути файл
@@ -0,0 +1,239 @@
//! Maven profiles for the Java language server. jdtls (m2e) has no setting for the
//! profiles a project is imported with; it takes them from `<activeProfiles>` of the
//! user `settings.xml`. The profiles chosen in the Maven tool window are therefore
//! passed as a copy of the user's settings with those profiles activated.
use crate::apply::setting_path;
use ide_core::settings::Settings;
use ide_language::LanguageServerConfig;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
const PREFIX: &str = "jdtls-maven-settings-";
/// Points jdtls at a user `settings.xml` activating `profiles` (`-P` entries of the
/// last Maven sync), written to `dir`. Through `settings`, so a running server
/// re-imports its Maven projects instead of restarting. `!id` entries can't be
/// expressed in `settings.xml` and are left to the POMs' own activation.
pub fn configure_jdtls(cfg: &mut LanguageServerConfig, root: &Path, s: &Settings, profiles: &[String], dir: &Path) {
if cfg.name != "jdtls" {
return;
}
let active: Vec<&str> =
profiles.iter().map(|p| p.trim()).filter(|p| !p.is_empty() && !p.starts_with('!')).collect();
let Some(file) = (!active.is_empty()).then(|| write_settings(root, s, &active, dir)).flatten() else {
remove_generated(dir, None);
return;
};
let layer = json!({ "java": { "configuration": { "maven": { "userSettings": file.to_string_lossy() } } } });
match &mut cfg.settings {
Some(settings) => merge(settings, layer),
None => cfg.settings = Some(layer),
}
}
/// The user's settings (Settings › Maven, else `~/.m2/settings.xml`) with `active`
/// added to `<activeProfiles>`. Named after its content: m2e reloads a settings file
/// only when the configured path changes.
fn write_settings(root: &Path, s: &Settings, active: &[&str], dir: &Path) -> Option<PathBuf> {
let user = setting_path(root, &s.languages.java.maven.user_settings)
.or_else(|| crate::home_dir().map(|h| h.join(".m2").join("settings.xml")));
let base = user.and_then(|f| std::fs::read_to_string(f).ok()).unwrap_or_else(|| "<settings>\n</settings>\n".into());
let Some(text) = with_active_profiles(&base, active) else {
tracing::warn!("Maven profiles not passed to jdtls: the user settings.xml has no <settings> element");
return None;
};
let mut hash = 0xcbf29ce484222325u64;
for byte in text.bytes() {
hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3);
}
let file = dir.join(format!("{PREFIX}{hash:016x}.xml"));
if !file.is_file() {
let written = std::fs::create_dir_all(dir).and_then(|()| std::fs::write(&file, &text));
if let Err(e) = written {
tracing::warn!("Maven profiles not passed to jdtls: {}: {e}", file.display());
return None;
}
}
remove_generated(dir, Some(&file));
Some(file)
}
/// Deletes the settings files written for earlier profile choices.
fn remove_generated(dir: &Path, keep: Option<&Path>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
let generated = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(PREFIX));
if generated && Some(path.as_path()) != keep {
let _ = std::fs::remove_file(path);
}
}
}
/// `text` (a `settings.xml`) with `ids` appended to its `<activeProfiles>`, created
/// when missing; `None` when there is no `<settings>` element to add it to.
pub fn with_active_profiles(text: &str, ids: &[&str]) -> Option<String> {
let entries: String = ids.iter().map(|id| format!(" <activeProfile>{}</activeProfile>\n", escape(id))).collect();
let masked = mask_comments(text);
if let Some(start) = find_tag(&masked, "<activeProfiles", 0) {
let end = start + masked[start..].find('>')?;
if masked[..end].ends_with('/') {
let element = format!("<activeProfiles>\n{entries} </activeProfiles>");
return Some(format!("{}{element}{}", &text[..start], &text[end + 1..]));
}
let close = end + masked[end..].find("</activeProfiles")?;
return Some(format!("{}\n{entries} {}", text[..close].trim_end(), &text[close..]));
}
let close = masked.rfind("</settings")?;
let element = format!(" <activeProfiles>\n{entries} </activeProfiles>\n");
Some(format!("{}\n{element}{}", text[..close].trim_end(), &text[close..]))
}
/// Start of the element `open` (`<name`), not a longer name sharing its prefix.
fn find_tag(masked: &str, open: &str, from: usize) -> Option<usize> {
let mut at = from;
while let Some(i) = masked[at..].find(open) {
let start = at + i;
let next = masked[start + open.len()..].chars().next();
if next.is_some_and(|c| c == '>' || c == '/' || c.is_whitespace()) {
return Some(start);
}
at = start + open.len();
}
None
}
/// `text` with comments and CDATA blanked out, byte offsets unchanged.
fn mask_comments(text: &str) -> String {
let mut out = text.as_bytes().to_vec();
let mut at = 0;
while at < text.len() {
let rest = &text[at..];
let (open, close) = match (rest.find("<!--"), rest.find("<![CDATA[")) {
(Some(c), Some(d)) if d < c => (d, "]]>"),
(Some(c), _) => (c, "-->"),
(None, Some(d)) => (d, "]]>"),
(None, None) => break,
};
let start = at + open;
let end = text[start..].find(close).map_or(text.len(), |i| start + i + close.len());
out[start..end].fill(b' ');
at = end;
}
String::from_utf8(out).unwrap_or_default()
}
fn escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}
fn merge(base: &mut Value, layer: Value) {
match (base, layer) {
(Value::Object(base), Value::Object(layer)) => {
for (k, v) in layer {
match base.get_mut(&k) {
Some(existing) => merge(existing, v),
None => {
base.insert(k, v);
}
}
}
}
(base, layer) => *base = layer,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn jdtls() -> LanguageServerConfig {
serde_json::from_value(json!({ "name": "jdtls", "command": "jdtls" })).unwrap()
}
fn user_settings(cfg: &LanguageServerConfig) -> Option<String> {
cfg.settings.as_ref()?.pointer("/java/configuration/maven/userSettings")?.as_str().map(Into::into)
}
#[test]
fn adds_profiles_to_every_shape_of_settings_xml() {
let ids = ["native", "本地"];
let added = "<activeProfile>native</activeProfile>\n <activeProfile>本地</activeProfile>";
for (text, keeps) in [
("<settings>\n</settings>\n", ""),
("<settings><mirrors><mirror><id>m</id></mirror></mirrors></settings>", "<mirror><id>m</id></mirror>"),
(
"<settings>\n <activeProfiles>\n <activeProfile>nexus</activeProfile>\n </activeProfiles>\n</settings>",
"<activeProfile>nexus</activeProfile>",
),
("<settings><activeProfiles/></settings>", ""),
("<settings><activeProfiles /></settings>", ""),
// Commented-out elements are not where the profiles go.
(
"<settings>\n<!-- <activeProfiles></activeProfiles> </settings> -->\n</settings>",
"<!-- <activeProfiles></activeProfiles> </settings> -->",
),
(
"<?xml version=\"1.0\"?>\n<settings xmlns=\"http://maven.apache.org/SETTINGS/1.0.0\"><activeProfilesX/></settings>",
"<activeProfilesX/>",
),
] {
let out = with_active_profiles(text, &ids).unwrap_or_else(|| panic!("{text}"));
assert!(out.contains(added), "{text}\n→\n{out}");
assert!(out.contains(keeps), "{text}\n→\n{out}");
let out = if keeps.starts_with("<!--") { out.replace(keeps, "") } else { out };
assert_eq!(out.matches("<activeProfiles>").count(), 1, "{text}\n→\n{out}");
let close = out.find("</activeProfiles>").unwrap();
assert!(close < out.rfind("</settings>").unwrap(), "{out}");
assert!(out.find(added).unwrap() < close, "{out}");
}
assert_eq!(with_active_profiles("<settings/>", &ids), None);
assert!(with_active_profiles("<settings></settings>", &["a&b"]).unwrap().contains("a&amp;b"));
}
#[test]
fn jdtls_imports_with_the_synced_profiles() {
let tmp = tempfile::tempdir().unwrap();
let user = tmp.path().join("user-settings.xml");
std::fs::write(&user, "<settings><localRepository>/repo</localRepository></settings>").unwrap();
let mut s = Settings::default();
s.languages.java.maven.user_settings = user.to_string_lossy().into_owned();
let dir = tmp.path().join("build");
let profiles = |p: &[&str]| p.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let mut cfg = jdtls();
configure_jdtls(&mut cfg, tmp.path(), &s, &profiles(&["native", "!dev", "本地"]), &dir);
let first = user_settings(&cfg).expect("generated settings");
let text = std::fs::read_to_string(&first).unwrap();
assert!(text.contains("<localRepository>/repo</localRepository>"), "{text}");
assert!(
text.contains("<activeProfile>native</activeProfile>")
&& text.contains("<activeProfile>本地</activeProfile>")
);
assert!(!text.contains("dev"), "deactivations are not activations: {text}");
// Same choice → same file; another choice → another path (m2e reloads on a new path).
let mut again = jdtls();
configure_jdtls(&mut again, tmp.path(), &s, &profiles(&["native", "本地"]), &dir);
assert_eq!(user_settings(&again).as_deref(), Some(first.as_str()));
let mut other = jdtls();
configure_jdtls(&mut other, tmp.path(), &s, &profiles(&["pro"]), &dir);
let second = user_settings(&other).unwrap();
assert_ne!(second, first);
assert!(!Path::new(&first).exists(), "the previous file is removed");
// No profile (or only deactivations) → the user's settings as configured.
for none in [&[][..], &["!dev"][..]] {
let mut plain = jdtls();
configure_jdtls(&mut plain, tmp.path(), &s, &profiles(none), &dir);
assert_eq!(user_settings(&plain), None);
}
assert!(!Path::new(&second).exists());
let mut other_server: LanguageServerConfig =
serde_json::from_value(json!({ "name": "kotlin-lsp", "command": "kotlin-lsp" })).unwrap();
configure_jdtls(&mut other_server, tmp.path(), &s, &profiles(&["native"]), &dir);
assert_eq!(other_server.settings, None);
}
}
+19
Переглянути файл
@@ -28,3 +28,22 @@ test("the scrollbar thumb drags even where overview marks cover it (#752)", asyn
await page.mouse.move(x, box.y + box.height - 20);
await expect(editor.locator(".cm-openidea-overview")).not.toHaveClass(/cm-openidea-overview-onThumb/);
});
test("the scrollbar thumb shows over a mark the height of the lane (#1014)", async ({ workbench: page }) => {
const editor = await openFromTree(page, "build.gradle.kts");
await editor.locator(".cm-content").click();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText(Array.from({ length: 400 }, (_, i) => `val mark${i} = ${i}`).join("\n"));
await page.keyboard.press("Meta+f");
await page.getByRole("textbox", { name: "Find" }).fill("mark");
await expect(editor.locator(".cm-openidea-overviewMark").first()).toBeVisible();
const thumb = editor.locator(".cm-openidea-overviewThumb");
await expect(thumb).toBeVisible();
// Drawn last in the lane, so it paints over every mark.
expect(await thumb.evaluate((t) => t.nextElementSibling)).toBeNull();
const scroller = editor.locator(".cm-scroller");
const top = async () => (await thumb.boundingBox())!.y;
const before = await top();
await scroller.evaluate((s) => (s.scrollTop = s.scrollHeight));
await expect.poll(top).toBeGreaterThan(before + 100);
});
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.34",
"version": "0.1.35",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+13
Переглянути файл
@@ -36,6 +36,19 @@ pub fn agent_providers(window: Window, state: State<'_, AppState>) -> IdeResult<
agent::providers(&state.host, window.label())
}
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
#[tauri::command]
#[specta::specta]
pub fn agent_set_command(
window: Window,
state: State<'_, AppState>,
id: String,
command: Option<String>,
) -> IdeResult<()> {
agent::set_command(&state.host, window.label(), id, command)
}
/// Agents of the ACP Registry this machine can run, with what is installed; the list
/// saved earlier when the registry is unreachable. Cancel with `cancel_request(request)`.
#[tauri::command]
+1
Переглянути файл
@@ -97,6 +97,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
app::log_frontend,
agent::agent_subscribe,
agent::agent_providers,
agent::agent_set_command,
agent::agent_registry_list,
agent::agent_registry_install,
agent::agent_registry_remove,
+1 -1
Переглянути файл
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "OpenIDEA",
"version": "0.1.34",
"version": "0.1.35",
"identifier": "ai.l0ng.openidea",
"build": {
"beforeDevCommand": "pnpm dev",
+17
Переглянути файл
@@ -86,6 +86,11 @@ export const commands = {
/** Streams the project's agent events to this window; returns every task. */
agentSubscribe: (onEvent: Channel<AgentEvent>) => typedError<AgentTask[], IdeError>(__TAURI_INVOKE("agent_subscribe", { onEvent })),
agentProviders: () => typedError<AgentProvider[], IdeError>(__TAURI_INVOKE("agent_providers")),
/**
* Overrides built-in agent `id`'s command with `command` (its agent file keeps the
* built-in's driver and arguments), or returns it to auto-detection with `None`.
*/
agentSetCommand: (id: string, command: string | null) => typedError<null, IdeError>(__TAURI_INVOKE("agent_set_command", { id, command })),
/**
* Agents of the ACP Registry this machine can run, with what is installed; the list
* saved earlier when the registry is unreachable. Cancel with `cancel_request(request)`.
@@ -1142,6 +1147,9 @@ export type AgentCommand = {
hint: string | null,
};
/** Why the executable cannot be changed in built-in agent settings. */
export type AgentCommandReadOnlyReason = "packageRunner" | "registry" | "customAgent";
/** A setting chosen for a new task, by [`AgentConfigOption::id`]. */
export type AgentConfigChoice = {
id: string,
@@ -1274,6 +1282,15 @@ export type AgentProvider = {
name: string,
/** The command line that starts its ACP server. */
command: string,
/** Executable and arguments actually launched, without flattening paths containing spaces. */
program: string,
args: string[],
defaultProgram: string | null,
defaultArgs: string[],
loginHint: string | null,
commandOverridden: boolean,
commandEditable: boolean,
commandReadOnlyReason: AgentCommandReadOnlyReason | null,
/** Whether the command was found (on `PATH`). */
installed: boolean,
/** Settings (models, modes…) the agent offered last time it ran; empty before its first session. */
+34 -1
Переглянути файл
@@ -64,11 +64,18 @@ class OverviewLane {
private lastKey = "";
/** The last pointer position over the editor, to re-check the thumb when it scrolls. */
private pointer: { x: number; y: number } | null = null;
/**
* The scrollbar thumb drawn over the marks: the native one sits under the lane, so a mark
* the height of the lane (a new file) would hide it (#1014).
*/
private thumb: HTMLElement;
constructor(private view: EditorView) {
this.dom = document.createElement("div");
this.dom.className = "cm-openidea-overview";
this.dom.setAttribute("aria-hidden", "true");
this.thumb = document.createElement("div");
this.thumb.className = "cm-openidea-overviewThumb";
this.dom.addEventListener("mousedown", this.onMouseDown);
view.dom.addEventListener("mousemove", this.onPointerMove);
view.dom.addEventListener("mouseleave", this.onPointerLeave);
@@ -153,9 +160,31 @@ class OverviewLane {
c.className = "cm-openidea-overviewCaret";
c.style.top = `${caret}${unit}`;
frag.appendChild(c);
frag.appendChild(this.thumb);
this.dom.replaceChildren(frag);
},
});
this.scheduleThumb();
}
private scheduleThumb() {
this.view.requestMeasure({
key: this.thumb,
read: (view) => {
const s = view.scrollDOM;
const thumb = scrollbarThumb(s.scrollTop, s.scrollHeight, s.clientHeight);
// The lane starts at the top of the editor, the scrollbar at the top of the scroller.
const offset = s.getBoundingClientRect().top - this.dom.getBoundingClientRect().top;
// Inset by the thumb's 2px transparent border (global.css).
return thumb && { top: thumb.top + offset + 2, height: thumb.bottom - thumb.top - 4 };
},
write: (thumb) => {
this.thumb.style.display = thumb ? "" : "none";
if (!thumb) return;
this.thumb.style.top = `${thumb.top}px`;
this.thumb.style.height = `${thumb.height}px`;
},
});
}
/**
@@ -187,6 +216,7 @@ class OverviewLane {
};
private onScroll = () => {
this.scheduleThumb();
if (this.pointer) this.updateThumbPassThrough();
};
@@ -218,4 +248,7 @@ class OverviewLane {
}
}
export const overviewLane: Extension = ViewPlugin.fromClass(OverviewLane);
export const overviewLane: Extension = [
ViewPlugin.fromClass(OverviewLane),
EditorView.editorAttributes.of({ class: "cm-openidea-withOverview" }),
];
+11
Переглянути файл
@@ -285,6 +285,17 @@ export const openideaTheme = EditorView.theme({
".cm-openidea-overviewMark-thin": { left: "4px", width: "4px", minHeight: "2px" },
// The scrollbar thumb wins over the marks under it (cm/lanes.ts, #752).
".cm-openidea-overview-onThumb .cm-openidea-overviewMark": { pointerEvents: "none" },
// The lane draws the thumb over its marks (#1014); the native one only takes the drag.
"&.cm-openidea-withOverview .cm-scroller::-webkit-scrollbar-thumb:vertical": { backgroundColor: "transparent" },
".cm-openidea-overviewThumb": {
position: "absolute",
right: "2px",
width: "6px",
borderRadius: "3px",
background: "var(--scrollbar-thumb)",
pointerEvents: "none",
},
".cm-openidea-overview-onThumb .cm-openidea-overviewThumb": { background: "var(--scrollbar-thumb-hover)" },
".cm-openidea-overviewCaret": {
position: "absolute",
left: "2px",
+8 -1
Переглянути файл
@@ -7,7 +7,12 @@
*/
import type { Extension } from "@codemirror/state";
import { registerEditorContribution, type EditorDocContext } from "@/editor/api";
import { registerOverlay, registerStatusItem, registerToolWindow } from "@/workbench/contributions";
import {
registerEditorBanner,
registerOverlay,
registerStatusItem,
registerToolWindow,
} from "@/workbench/contributions";
import { lspDoc } from "./lsp";
import { hintExtension } from "./hint";
import { completionExtension } from "./completion";
@@ -31,6 +36,7 @@ import { spellingExtension } from "./spelling";
import { DocumentationWindow, LspPopups, UsagesStatus } from "./Popups";
import { DOCUMENTATION_WINDOW } from "./docs";
import { prefetchMarkdown } from "./markdown";
import { outsideProjectBanner } from "./outsideProject";
import { implementationGutter, registerNavigationActions } from "@/editor/navigation";
export function lspExtensions(ctx: EditorDocContext): Extension[] {
@@ -66,6 +72,7 @@ export function activate(): () => void {
// After the templates (order 90): live template / postfix expansion keeps ⇥ first.
registerEditorContribution({ id: "lsp.parameterTab", order: 95, extensions: () => parameterTabKeys }),
registerOverlay({ id: "editor-lsp.popups", component: LspPopups }),
registerEditorBanner(outsideProjectBanner),
registerStatusItem({ id: "editor-lsp.usagesStatus", align: "left", priority: 10, component: UsagesStatus }),
// IDEA's Documentation tool window: right side, listed once F1 moved documentation there.
registerToolWindow({
+11 -1
Переглянути файл
@@ -47,6 +47,7 @@ import {
type DeclarationTarget,
} from "./syntaxFallback";
import { showHint, showPendingHint } from "./hint";
import { outsideProjectReason } from "./outsideProject";
import { caretAnchor, openPopup, type ListPopupItem } from "./popupStore";
import { readManyFileLines, targetLabel } from "./files";
import { documentLinks, followReference, knownLinks, linkReference, referenceAt, textReference } from "./links";
@@ -198,7 +199,16 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number)
((await gotoWebReference(view, doc, pos, offset)) || (await followReferenceAt(view, doc, offset)))
)
return;
showHint(view, serverDown ? `${NOT_FOUND[kind]}: no language server is running for this file` : NOT_FOUND[kind]);
// The server only checks this file's syntax: say why instead of just "not found".
const reason = serverDown ? null : outsideProjectReason(doc.path);
showHint(
view,
serverDown
? `${NOT_FOUND[kind]}: no language server is running for this file`
: reason
? `${tx(NOT_FOUND[kind])}. ${tx(reason)}`
: NOT_FOUND[kind],
);
return;
}
// IDEA: ⌘B on a declaration shows its usages.
+66
Переглянути файл
@@ -0,0 +1,66 @@
import { expect, it } from "vitest";
import { outsideProjectNotice } from "./outsideProject";
const text = (message: string) => outsideProjectNotice(message)?.text ?? null;
it("recognizes each server's report that a file is outside its projects", () => {
const cases: [string, RegExp | null][] = [
// jdtls: a file outside the module's source folders, and one outside every project.
[
"Extra.java is not on the classpath of project service, only syntax errors are reported",
/source folders of its Java module/,
],
["Scratch.java is a non-project file, only syntax errors are reported", /imported Java project/],
// gopls: build constraints win over the generic "no package".
["No packages found for open file x.go.\nThis file may be excluded due to its build tags", /build constraints/],
["This file may be excluded due to its GOOS/GOARCH, or other build constraints.", /build constraints/],
["No packages found for open file x.go.", /no package of the workspace/],
// rust-analyzer `unlinked-file`.
[
"This file is not included in any crates, so rust-analyzer can't offer IDE services.",
/not included in any crate/,
],
// Ordinary errors are not such reports.
["undefined: missingSymbol", null],
["invalid build tags syntax", null],
["ActionDTO cannot be resolved to a type", null],
["Missing artifact demo:api:jar:1.0", null],
];
for (const [message, expected] of cases) {
const got = text(message);
if (expected) expect(got, message).toMatch(expected);
else expect(got, message).toBeNull();
}
// A build reload is offered only where it can bring the file into a project.
expect(outsideProjectNotice("A.java is a non-project file, only syntax errors are reported")?.reload).toBe(true);
expect(outsideProjectNotice("No packages found for open file x.go.")?.reload).toBeFalsy();
});
it("shows a banner while the server reports the file, with the build reloads available", async () => {
const { renderHook, act } = await import("@testing-library/react");
const { setFileDiagnostics } = await import("./diagnostics");
const { registerActions } = await import("@/platform/actions");
const { outsideProjectBanner } = await import("./outsideProject");
const off = registerActions([{ id: "maven.reload", title: "Reload All Maven Projects", run: () => {} }]);
const path = "/p/service/src/extra/Extra.java";
try {
const { result } = renderHook(() => outsideProjectBanner.useBanner(path));
expect(result.current).toBeNull();
const warning = {
range: { start: { line: 0, col: 0 }, end: { line: 0, col: 1 } },
severity: "warning" as const,
message: "Extra.java is not on the classpath of project service, only syntax errors are reported",
source: "Java",
code: "32",
};
act(() => setFileDiagnostics(path, "jdtls", [warning]));
expect(result.current?.level).toBe("warning");
expect(result.current?.text).toMatch(/source folders of its Java module/);
expect(result.current?.actions?.map((a) => a.label)).toEqual(["Reload Maven Projects"]);
act(() => setFileDiagnostics(path, "jdtls", []));
expect(result.current).toBeNull();
} finally {
off();
setFileDiagnostics(path, "jdtls", []);
}
});
+85
Переглянути файл
@@ -0,0 +1,85 @@
/**
* Files a language server only checks for syntax because they belong to none of
* its projects: a Java file outside every module's source folders, a Rust file in
* no crate, a Go file in no package of the workspace. The server says so in a
* diagnostic; navigation, completion and usages then fail without saying why.
*/
import { useSyncExternalStore } from "react";
import { executeAction, getAction, isActionEnabled } from "@/platform/actions";
import type { EditorBannerContribution } from "@/workbench/contributions";
import { diagnosticsFor, subscribeDiagnostics } from "./diagnostics";
/** `reload`: a build reload may bring the file into a project (a module the import missed). */
const NOTICES: readonly { test: RegExp; text: string; reload?: boolean }[] = [
// jdtls: "Foo.java is not on the classpath of project app, only syntax errors are reported"
{
test: /is not on the classpath of project .*only syntax errors are reported/,
text: "This file is outside the source folders of its Java module: only syntax errors are reported, and navigation and completion don't work.",
reload: true,
},
// jdtls: "Foo.java is a non-project file, only syntax errors are reported"
{
test: /is a non-project file, only syntax errors are reported/,
text: "This file does not belong to an imported Java project: only syntax errors are reported, and navigation and completion don't work.",
reload: true,
},
// gopls, before its generic "No packages found" below.
{
test: /excluded[^\n]*(?:build|GOOS\/GOARCH)/i,
text: "This Go file is excluded by the current build constraints.",
},
{
test: /^No packages found for open file/,
text: "This Go file belongs to no package of the workspace: code insight is limited.",
},
// rust-analyzer's `unlinked-file`.
{
test: /not included in any crates/,
text: "This Rust file is not included in any crate: rust-analyzer can't offer code insight for it.",
},
];
type Notice = (typeof NOTICES)[number];
/** What a server's `message` means for its file, when it says the file is outside its projects. */
export function outsideProjectNotice(message: string): Notice | null {
return NOTICES.find((n) => n.test.test(message)) ?? null;
}
function noticeFor(path: string): Notice | null {
for (const d of diagnosticsFor(path)) {
const notice = outsideProjectNotice(d.message);
if (notice) return notice;
}
return null;
}
/** Why code insight is limited in `path`, from its current diagnostics, or null. */
export function outsideProjectReason(path: string): string | null {
return noticeFor(path)?.text ?? null;
}
const RELOADS = [
{ id: "maven.reload", label: "Reload Maven Projects" },
{ id: "gradle.reload", label: "Reload Gradle Project" },
];
/** The notice above an editor whose file a language server treats as outside its projects. */
export const outsideProjectBanner: EditorBannerContribution = {
id: "lsp.outsideProject",
order: 5,
useBanner: (path) => {
const notice = useSyncExternalStore(
(l) => subscribeDiagnostics(path, l),
() => noticeFor(path),
);
if (!notice) return null;
const actions = notice.reload
? RELOADS.filter(({ id }) => {
const action = getAction(id);
return action && isActionEnabled(action);
}).map(({ id, label }) => ({ label, run: () => void executeAction(id) }))
: [];
return { text: notice.text, level: "warning", actions };
},
};
+23
Переглянути файл
@@ -303,6 +303,29 @@ describe("navigation wiring", () => {
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Cannot find declaration to go to");
});
it("says why when the server only checks the file's syntax", async () => {
const { setFileDiagnostics } = await import("./diagnostics");
setFileDiagnostics("/p/a.ts", "jdtls", [
{
range: { start: { line: 0, col: 0 }, end: { line: 0, col: 1 } },
severity: "warning",
message: "a.ts is not on the classpath of project app, only syntax errors are reported",
source: "Java",
code: "32",
},
]);
try {
cmd.lspGoto.mockReturnValueOnce(ok([]));
const view = editor("const x = 1;\nx;", "typescript", 13);
await gotoTargets(view, "definition");
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe(
"Cannot find declaration to go to. This file is outside the source folders of its Java module: only syntax errors are reported, and navigation and completion don't work.",
);
} finally {
setFileDiagnostics("/p/a.ts", "jdtls", []);
}
});
it("falls back to the local definition when the server is not ready", async () => {
cmd.syntaxLocals.mockReturnValueOnce(ok(local({ references: [r(1, 0, 1)] })));
const view = editor("const x = 1;\nx;", "typescript", 13);
+6 -1
Переглянути файл
@@ -1,11 +1,16 @@
.body {
display: flex;
flex-direction: column;
gap: 8px;
gap: 12px;
height: 100%;
min-height: 0;
}
/* The compact variant may shrink in toolbars; here it keeps its height above the panes. */
.tabs {
flex: none;
}
.notice,
.warning,
.error,
+33 -4
Переглянути файл
@@ -1,14 +1,14 @@
/**
* Settings › Tools › Agents: agents of the ACP Registry this machine can run, with
* Install / Update / Remove. Installs run in the background with progress; leaving the
* page cancels one.
* Settings › Tools › Agents: the launch command of built-in agents (Claude Code…), and
* agents of the ACP Registry this machine can run, with Install / Update / Remove.
* Installs run in the background with progress; leaving the page cancels one.
*/
import { useEffect, useMemo, useRef, useState } from "react";
import type { AgentRegistry, RegistryAgent, RequestId } from "@/bindings";
import { isCancelled, nextRequestId } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
import { Badge, Button, Icon, ProgressBar, SearchField, Spinner, T } from "@/ui";
import { Badge, Button, Icon, ProgressBar, SearchField, Spinner, T, Tabs } from "@/ui";
import { confirm } from "@/workbench/messages";
import { providerIcon } from "./model";
import {
@@ -18,9 +18,12 @@ import {
matchesQuery,
rowActions,
sortAgents,
tauriCommands,
tauriRegistry,
type CommandsBackend,
type RegistryBackend,
} from "./registry";
import { BuiltinAgents } from "./BuiltinAgents";
import styles from "./AgentRegistry.module.css";
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
@@ -35,11 +38,37 @@ interface Job {
export function AgentRegistryPage({
onChanged,
backend = tauriRegistry,
commandBackend = tauriCommands,
}: {
/** An agent was installed, updated or removed (the agent list changed). */
onChanged?: () => void;
backend?: RegistryBackend;
commandBackend?: CommandsBackend;
}) {
const [tab, setTab] = useState("builtin");
return (
<div className={styles.body}>
<Tabs
variant="compact"
className={styles.tabs}
items={[
{ id: "builtin", label: "Built-in" },
{ id: "registry", label: "ACP Registry" },
]}
activeId={tab}
onSelect={setTab}
aria-label={tx("Agents")}
/>
{tab === "builtin" ? (
<BuiltinAgents backend={commandBackend} onChanged={onChanged} />
) : (
<RegistryList backend={backend} onChanged={onChanged} />
)}
</div>
);
}
function RegistryList({ backend, onChanged }: { backend: RegistryBackend; onChanged?: () => void }) {
const [registry, setRegistry] = useState<AgentRegistry | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [query, setQuery] = useState("");
+122
Переглянути файл
@@ -0,0 +1,122 @@
.split {
display: flex;
flex: none;
min-height: 320px;
border: 1px solid var(--border-strong);
border-radius: var(--radius-control);
overflow: hidden;
}
.master {
flex: 0 0 300px;
padding: 6px;
border-right: 1px solid var(--border);
}
.agentRow {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
min-width: 0;
padding: 0 10px;
}
.agentMissing .agentName {
color: var(--fg-muted);
}
.agentMissing svg {
opacity: 0.6;
}
.tag {
flex: none;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.tagCustom {
color: var(--accent);
}
.agentName {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.details {
flex: 1;
min-width: 0;
padding: 20px;
overflow: auto;
}
.title {
display: flex;
align-items: center;
gap: 8px;
color: var(--fg-strong);
}
.title h3 {
margin: 0;
font-size: var(--fs-input-large);
}
.subtitle {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
margin: 6px 0 20px 28px;
color: var(--fg-muted);
font-size: var(--fs-small);
}
.dot {
flex: none;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--fg-subtle);
}
.dotFound {
background: var(--success);
}
.dotCustom {
background: var(--accent);
}
.launch {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: var(--font-mono);
}
.section {
margin: 20px 0 6px;
font-size: var(--fs-ui);
font-weight: 600;
color: var(--fg-strong);
}
.section + .hint {
margin-top: 0;
}
.hint code {
font-family: var(--font-mono);
color: var(--fg);
}
.label {
display: block;
margin-bottom: 6px;
}
.controls {
display: flex;
align-items: center;
gap: 6px;
}
.controls > :first-child {
flex: 1;
min-width: 0;
}
.hint {
margin: 8px 0 16px;
color: var(--fg-muted);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
.error {
color: var(--danger);
white-space: pre-wrap;
}
+202
Переглянути файл
@@ -0,0 +1,202 @@
/** Built-in launch settings; each executable is staged independently until Apply. */
import { useCallback, useEffect, useState } from "react";
import type { AgentProvider } from "@/bindings";
import { tx, useTx } from "@/platform/i18n";
import clsx from "clsx";
import { Button, Icon, IconButton, Input, List, Spinner, T } from "@/ui";
import { useSettingsForm } from "@/workbench/contributions";
import { providerIcon } from "./model";
import type { CommandsBackend } from "./registry";
import styles from "./BuiltinAgents.module.css";
/** Trailing list tag: a missing agent is a normal state, so it is muted rather than a warning. */
function Status({ agent }: { agent: AgentProvider }) {
if (agent.commandOverridden)
return (
<span className={clsx(styles.tag, styles.tagCustom)}>
<T>Custom</T>
</span>
);
if (agent.installed) return null;
return (
<span className={styles.tag}>
<T>Not found</T>
</span>
);
}
export function BuiltinAgents({ backend, onChanged }: { backend: CommandsBackend; onChanged?: () => void }) {
const [agents, setAgents] = useState<AgentProvider[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [selected, setSelected] = useState(0);
useEffect(() => {
let live = true;
backend.providers().then(
(list) => live && setAgents(list.filter((p) => p.defaultProgram != null)),
(e: unknown) => live && setError(e instanceof Error ? e.message : String(e)),
);
return () => {
live = false;
};
}, [backend]);
const refresh = useCallback(async () => {
const list = await backend.providers();
setAgents(list.filter((p) => p.defaultProgram != null));
}, [backend]);
if (error)
return (
<p className={styles.error} role="alert">
{error}
</p>
);
if (!agents) return <Spinner size={14} />;
const agent = agents[selected] ?? agents[0];
return (
<div className={styles.split}>
<List
className={styles.master}
items={agents}
getKey={(p) => p.id}
activeIndex={selected}
onActiveChange={setSelected}
rowHeight={32}
aria-label={tx("Built-in agents")}
renderItem={(p) => (
<div className={clsx(styles.agentRow, !p.installed && !p.commandOverridden && styles.agentMissing)}>
<Icon name={providerIcon(p.id)} size={16} />
<span className={styles.agentName}>{p.name}</span> <Status agent={p} />
</div>
)}
/>
{agent && <Details key={agent.id} agent={agent} backend={backend} refresh={refresh} onChanged={onChanged} />}
</div>
);
}
function Details({
agent,
backend,
refresh,
onChanged,
}: {
agent: AgentProvider;
backend: CommandsBackend;
refresh: () => Promise<void>;
onChanged?: () => void;
}) {
const form = useSettingsForm();
const base = agent.commandOverridden ? agent.program : "";
const { value, current, set, saving } = form.useExternal(`agents.${agent.id}.command`, base, async (draft) => {
const command = draft.trim() || null;
await backend.set(agent.id, command);
await refresh();
onChanged?.();
return command === agent.defaultProgram ? "" : (command ?? "");
});
const [error, setError] = useState<string | null>(null);
// An edit can have been staged by a previous page instance. Its Apply callback
// refreshes that instance; the mounted one follows the newly applied value too.
useEffect(() => {
if (!saving && current !== base) {
void refresh().catch((e: unknown) => setError(e instanceof Error ? e.message : String(e)));
}
}, [base, current, saving, refresh]);
const launch = [agent.defaultProgram, ...agent.defaultArgs].join(" ");
const status = agent.commandOverridden
? tx("Custom executable")
: agent.installed
? tx("Found on PATH")
: tx("Not found on PATH");
return (
<section className={styles.details} aria-label={tx`${agent.name} executable`}>
<div className={styles.title}>
<Icon name={providerIcon(agent.id)} size={20} />
<h3>{agent.name}</h3>
</div>
<div className={styles.subtitle}>
<span
aria-hidden
className={clsx(styles.dot, agent.commandOverridden ? styles.dotCustom : agent.installed && styles.dotFound)}
/>
<span>{status}</span>
<span aria-hidden>·</span>
<code className={styles.launch} title={tx("Launch command")}>
{launch}
</code>
</div>
{agent.commandEditable ? (
<>
<label className={styles.label} htmlFor={`agent-executable-${agent.id}`}>
<T>Executable</T>
</label>
<div className={styles.controls}>
<Input
id={`agent-executable-${agent.id}`}
mono
value={value}
disabled={saving}
placeholder={tx`Auto-detect (${agent.defaultProgram})`}
onChange={(e) => set(e.target.value)}
/>
<IconButton
icon="folder-open"
size="small"
title="Browse…"
disabled={saving}
onClick={async () => {
try {
const path = await backend.chooseExecutable(tx`Select ${agent.name}`, value);
if (path) set(path);
setError(null);
} catch (e) {
setError(e instanceof Error ? e.message : String(e));
}
}}
/>
{value && (
<Button size="small" disabled={saving} onClick={() => set("")}>
<T>Reset</T>
</Button>
)}
</div>
<p className={styles.hint}>
<T>Leave empty to find the executable on PATH. Changes apply to new sessions.</T>
</p>
</>
) : (
<p className={styles.hint}>
{agent.commandReadOnlyReason === "packageRunner" ? (
<T>This agent runs through a package runner (npm or uv) and has no executable to choose.</T>
) : agent.commandReadOnlyReason === "registry" ? (
<T>This agent is installed from the ACP Registry. Manage its installation in the ACP Registry tab.</T>
) : (
<T>This agent is configured in its agent file.</T>
)}
</p>
)}
{agent.loginHint && (
<>
<h4 className={styles.section}>
<T>Sign in</T>
</h4>
<p className={styles.hint}>
<LoginHint text={agent.loginHint} />
</p>
</>
)}
{error && (
<p className={styles.error} role="alert">
{error}
</p>
)}
</section>
);
}
/** Login hints are plain text with optional backtick-delimited command spans. */
function LoginHint({ text }: { text: string }) {
const translate = useTx();
return translate(text)
.split(/(`[^`]+`)/g)
.map((part, i) => (i % 2 === 1 ? <code key={i}>{part.slice(1, -1)}</code> : part));
}
+344 -13
Переглянути файл
@@ -1,13 +1,35 @@
import { describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import type { AgentProvider, AgentRegistry, InstallEvent, RegistryAgent, RequestId } from "@/bindings";
import { IpcError } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { setLocale, tx } from "@/platform/i18n";
import { iconMarkup } from "@/ui/icons";
import { MessagesHost } from "@/workbench/messages";
import { AgentRegistryPage } from "./AgentRegistryPage";
import { AgentRegistryPage as RegistryPage } from "./AgentRegistryPage";
import { SettingsFormContext, registerSettingsPage } from "@/workbench/contributions";
import { useSettingsFormFor } from "@/features/settings/components/context";
import { closeSettings, openSettings, selectPage } from "@/features/settings/model/staging";
import { SettingsDialog } from "@/features/settings/dialog/SettingsDialog";
import { REGISTRY_PAGE } from "./model";
import type { ComponentProps } from "react";
function AgentRegistryPage(props: ComponentProps<typeof RegistryPage>) {
const form = useSettingsFormFor(REGISTRY_PAGE, "global");
return (
<SettingsFormContext.Provider value={form}>
<RegistryPage {...props} />
</SettingsFormContext.Provider>
);
}
import { ADD_AGENT, providerOptions } from "./providerOptions";
import { afterRemove, matchesQuery, rowActions, sortAgents, type RegistryBackend } from "./registry";
import {
afterRemove,
matchesQuery,
rowActions,
sortAgents,
type CommandsBackend,
type RegistryBackend,
} from "./registry";
const agent = (partial: Partial<RegistryAgent> & Pick<RegistryAgent, "id" | "name">): RegistryAgent => ({
version: "1.0.0",
@@ -114,6 +136,14 @@ describe("agent picker", () => {
const provider = (p: Partial<AgentProvider> & Pick<AgentProvider, "id" | "source">): AgentProvider => ({
name: p.id,
command: p.id,
program: p.id,
args: [],
defaultProgram: p.id,
defaultArgs: [],
loginHint: null,
commandOverridden: false,
commandEditable: true,
commandReadOnlyReason: null,
installed: true,
config: [],
commands: [],
@@ -143,10 +173,15 @@ describe("agent picker", () => {
});
describe("Agents settings page", () => {
const renderRegistry = (...args: Parameters<typeof render>) => {
const result = render(...args);
fireEvent.click(screen.getByRole("tab", { name: "ACP Registry" }));
return result;
};
it("shows the built-in Copilot name and icon in its registry row", async () => {
const backend = new FakeBackend();
backend.registry = { agents: [agent({ id: "copilot", name: "GitHub Copilot" })], warning: null };
render(<AgentRegistryPage backend={backend} />);
renderRegistry(<AgentRegistryPage backend={backend} />);
const copilot = await screen.findByRole("listitem", { name: "GitHub Copilot" });
const expected = document.createElement("div");
expected.innerHTML = iconMarkup("agent-copilot")!;
@@ -156,7 +191,7 @@ describe("Agents settings page", () => {
it("lists registry agents, says they are third-party, and searches them", async () => {
const backend = new FakeBackend();
render(<AgentRegistryPage backend={backend} />);
renderRegistry(<AgentRegistryPage backend={backend} />);
await waitFor(() => expect(row("Amp")).toBeInTheDocument());
expect(screen.getByText(/third-party software/)).toBeInTheDocument();
expect(within(row("Amp")).getByRole("button", { name: "Install" })).toBeEnabled();
@@ -175,7 +210,7 @@ describe("Agents settings page", () => {
it("installs with progress, then reports the change", async () => {
const backend = new FakeBackend();
const onChanged = vi.fn();
render(<AgentRegistryPage onChanged={onChanged} backend={backend} />);
renderRegistry(<AgentRegistryPage onChanged={onChanged} backend={backend} />);
await waitFor(() => expect(row("Amp")).toBeInTheDocument());
fireEvent.click(within(row("Amp")).getByRole("button", { name: "Install" }));
expect(backend.installs).toEqual(["amp-acp"]);
@@ -194,7 +229,7 @@ describe("Agents settings page", () => {
it("asks before installing an agent whose download has no checksum", async () => {
const backend = new FakeBackend();
backend.registry = { agents: [{ ...AMP, noChecksum: true }], warning: null };
render(
renderRegistry(
<>
<AgentRegistryPage backend={backend} />
<MessagesHost />
@@ -218,7 +253,7 @@ describe("Agents settings page", () => {
it("installs an agent with a checksum without asking", async () => {
const backend = new FakeBackend();
render(
renderRegistry(
<>
<AgentRegistryPage backend={backend} />
<MessagesHost />
@@ -233,7 +268,7 @@ describe("Agents settings page", () => {
it("shows why an install failed, and cancels one when the page closes", async () => {
const backend = new FakeBackend();
const { unmount } = render(<AgentRegistryPage backend={backend} />);
const { unmount } = renderRegistry(<AgentRegistryPage backend={backend} />);
await waitFor(() => expect(row("Cline")).toBeInTheDocument());
fireEvent.click(within(row("Cline")).getByRole("button", { name: "Update" }));
await act(async () => backend.fail(new IpcError({ kind: "unavailable", message: "npm is required" })));
@@ -251,7 +286,7 @@ describe("Agents settings page", () => {
it("removes an installed agent", async () => {
const backend = new FakeBackend();
const onChanged = vi.fn();
render(<AgentRegistryPage onChanged={onChanged} backend={backend} />);
renderRegistry(<AgentRegistryPage onChanged={onChanged} backend={backend} />);
await waitFor(() => expect(row("fast-agent")).toBeInTheDocument());
fireEvent.click(within(row("fast-agent")).getByRole("button", { name: "Remove" }));
await waitFor(() => expect(within(row("fast-agent")).getByRole("button", { name: "Install" })).toBeEnabled());
@@ -262,12 +297,308 @@ describe("Agents settings page", () => {
it("falls back to the saved list with a warning, and reports a registry it cannot load", async () => {
const backend = new FakeBackend();
backend.registry = { agents: AGENTS, warning: "Could not reach the ACP Registry" };
const { unmount } = render(<AgentRegistryPage backend={backend} />);
const { unmount } = renderRegistry(<AgentRegistryPage backend={backend} />);
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Could not reach the ACP Registry"));
unmount();
backend.list.mockRejectedValueOnce(new IpcError({ kind: "io", message: "offline" }));
render(<AgentRegistryPage backend={backend} />);
renderRegistry(<AgentRegistryPage backend={backend} />);
await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("Cannot load the ACP Registry: offline"));
});
});
class FakeCommands implements CommandsBackend {
list: AgentProvider[] = [];
saved: [string, string | null][] = [];
providers = vi.fn(async () => this.list);
chooseExecutable = vi.fn(async () => "/chosen/agent");
async set(id: string, command: string | null) {
this.saved.push([id, command]);
// What the agent list shows after the override takes effect.
this.list = this.list.map((p) =>
p.id === id
? {
...p,
program: command ?? p.defaultProgram!,
command: command ?? p.defaultProgram!,
commandOverridden: command != null && command !== p.defaultProgram,
}
: p,
);
}
}
const claudeProvider = (command: string): AgentProvider => ({
id: "claude",
name: "Claude Code",
command,
program: command,
args: [],
defaultProgram: "claude",
defaultArgs: [],
loginHint: "Run `claude` in a terminal and sign in.",
commandOverridden: command !== "claude",
commandEditable: true,
commandReadOnlyReason: null,
installed: true,
config: [],
commands: [],
source: { kind: "builtin" },
});
describe("Built-in executable overrides", () => {
let dispose = () => {};
beforeEach(() => openSettings(REGISTRY_PAGE));
afterEach(() => {
closeSettings();
dispose();
});
const openCommands = async (commands: FakeCommands, onChanged = vi.fn()) => {
const backend = new FakeBackend();
dispose = registerSettingsPage({
id: REGISTRY_PAGE,
title: "Agents",
group: "Tools",
component: () => <RegistryPage backend={backend} commandBackend={commands} onChanged={onChanged} />,
});
render(<SettingsDialog />);
return screen.findByRole("region", { name: "Claude Code executable" });
};
const apply = () => screen.getByRole("button", { name: "Apply" });
const field = () => screen.getByRole("textbox", { name: "Executable" });
it("follows locale changes in tabs and renders login commands as inline code", async () => {
const commands = new FakeCommands();
commands.list = [
claudeProvider("claude"),
{
...claudeProvider("codex"),
id: "codex",
name: "Codex",
defaultProgram: "codex",
commandOverridden: false,
installed: false,
},
];
const section = await openCommands(commands);
expect(within(section).getByText("claude", { selector: "p code" })).toBeInTheDocument();
expect(screen.getByText("Found on PATH")).toBeInTheDocument();
expect(screen.getByRole("option", { name: "Claude Code" })).toBeInTheDocument();
try {
await act(async () => {
await setLocale("zh");
});
expect(screen.getByRole("option", { name: "Codex 未找到" })).toBeInTheDocument();
expect(screen.getByRole("tab", { name: "内置" })).toBeInTheDocument();
expect(screen.getByRole("tab", { name: "ACP 注册表" })).toBeInTheDocument();
await act(async () => {
await setLocale("en");
});
expect(screen.getByRole("option", { name: "Codex Not found" })).toBeInTheDocument();
expect(screen.getByRole("tab", { name: "Built-in" })).toBeInTheDocument();
expect(screen.getByRole("tab", { name: "ACP Registry" })).toBeInTheDocument();
} finally {
await act(async () => {
await setLocale("en");
});
}
});
it("reports when providers cannot be read (no trusted project)", async () => {
const commands = new FakeCommands();
commands.providers.mockRejectedValue(new IpcError({ kind: "unavailable", message: "restricted" }));
render(<AgentRegistryPage backend={new FakeBackend()} commandBackend={commands} />);
await waitFor(() => expect(screen.getByRole("alert")).toHaveTextContent("restricted"));
expect(screen.queryByRole("textbox", { name: "Executable" })).toBeNull();
});
it.each(["Apply", "OK"])("stages a binary path and writes it only on %s", async (button) => {
const commands = new FakeCommands();
commands.list = [claudeProvider("claude")];
const onChanged = vi.fn();
const section = await openCommands(commands, onChanged);
expect(apply()).toBeDisabled();
expect(field()).toHaveValue("");
expect(within(section).queryByRole("button", { name: "Save" })).toBeNull();
fireEvent.change(field(), { target: { value: "D:\\tools\\claude.exe" } });
expect(commands.saved).toEqual([]);
expect(onChanged).not.toHaveBeenCalled();
expect(apply()).toBeEnabled();
expect(screen.queryByRole("option", { name: /Claude Code Custom/ })).toBeNull();
await act(async () => fireEvent.click(screen.getByRole("button", { name: button })));
expect(commands.saved).toEqual([["claude", "D:\\tools\\claude.exe"]]);
expect(onChanged).toHaveBeenCalledOnce();
if (button === "Apply") {
expect(screen.getByRole("option", { name: /Claude Code Custom/ })).toBeInTheDocument();
expect(apply()).toBeDisabled();
} else expect(screen.queryByRole("dialog")).toBeNull();
});
it("Cancel discards command edits without writing", async () => {
const commands = new FakeCommands();
commands.list = [
claudeProvider("/saved/claude"),
{
...claudeProvider("codex"),
id: "codex",
name: "Codex",
defaultProgram: "codex",
commandOverridden: false,
},
];
await openCommands(commands);
fireEvent.change(field(), { target: { value: "/unsaved/claude" } });
fireEvent.mouseDown(screen.getByRole("option", { name: "Codex" }));
fireEvent.change(field(), { target: { value: "/unsaved/codex" } });
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(commands.saved).toEqual([]);
act(() => openSettings(REGISTRY_PAGE));
expect(await screen.findByRole("textbox", { name: "Executable" })).toHaveValue("/saved/claude");
expect(apply()).toBeDisabled();
});
it.each(["clear", "Reset"])("%s stages automatic detection until Apply", async (action) => {
const commands = new FakeCommands();
commands.list = [claudeProvider("/saved/claude")];
const section = await openCommands(commands);
if (action === "clear") fireEvent.change(field(), { target: { value: "" } });
else fireEvent.click(within(section).getByRole("button", { name: "Reset" }));
expect(field()).toHaveValue("");
expect(commands.saved).toEqual([]);
expect(screen.getByRole("option", { name: /Claude Code Custom/ })).toBeInTheDocument();
expect(apply()).toBeEnabled();
await act(async () => fireEvent.click(apply()));
expect(commands.saved).toEqual([["claude", null]]);
expect(field()).toHaveValue("");
expect(screen.queryByRole("option", { name: /Claude Code Custom/ })).toBeNull();
expect(apply()).toBeDisabled();
});
it("page Reset discards edits and returning to the saved value clears the modified state", async () => {
const commands = new FakeCommands();
commands.list = [claudeProvider("/saved/claude")];
await openCommands(commands);
fireEvent.change(field(), { target: { value: "/edited/claude" } });
fireEvent.click(screen.getAllByRole("button", { name: "Reset" })[0]!);
expect(field()).toHaveValue("/saved/claude");
expect(apply()).toBeDisabled();
fireEvent.change(field(), { target: { value: "/edited/claude" } });
fireEvent.change(field(), { target: { value: "/saved/claude" } });
expect(apply()).toBeDisabled();
expect(commands.saved).toEqual([]);
});
it.each([false, true])("keeps edits across page navigation and applies with Agents mounted=%s", async (mounted) => {
const commands = new FakeCommands();
commands.list = [claudeProvider("claude")];
await openCommands(commands);
const off = registerSettingsPage({ id: "other", title: "Other" });
try {
fireEvent.change(field(), { target: { value: "/custom/claude" } });
act(() => selectPage("other"));
expect(apply()).toBeEnabled();
if (mounted) {
act(() => selectPage(REGISTRY_PAGE));
expect(await screen.findByRole("textbox", { name: "Executable" })).toHaveValue("/custom/claude");
}
await act(async () => fireEvent.click(apply()));
act(() => selectPage(REGISTRY_PAGE));
expect(await screen.findByRole("textbox", { name: "Executable" })).toHaveValue("/custom/claude");
expect(screen.getByRole("option", { name: /Claude Code Custom/ })).toBeInTheDocument();
expect(commands.saved).toEqual([["claude", "/custom/claude"]]);
expect(apply()).toBeDisabled();
} finally {
off();
}
});
it("retains a failed command for retry and shows only the applied badge", async () => {
const commands = new FakeCommands();
commands.list = [claudeProvider("claude")];
const set = vi.spyOn(commands, "set").mockRejectedValueOnce(new Error("Read-only configuration"));
await openCommands(commands);
fireEvent.change(field(), { target: { value: " /custom/claude " } });
await act(async () => fireEvent.click(apply()));
expect(screen.getByRole("status")).toHaveTextContent("Read-only configuration");
expect(field()).toHaveValue(" /custom/claude ");
expect(screen.queryByRole("option", { name: /Claude Code Custom/ })).toBeNull();
expect(apply()).toBeEnabled();
await act(async () => fireEvent.click(apply()));
expect(set).toHaveBeenCalledTimes(2);
expect(commands.saved).toEqual([["claude", "/custom/claude"]]);
expect(field()).toHaveValue("/custom/claude");
expect(screen.getByRole("option", { name: /Claude Code Custom/ })).toBeInTheDocument();
});
it.each(["Apply", "OK"])("lists built-ins and writes two independent edits on %s", async (button) => {
const commands = new FakeCommands();
commands.list = [
claudeProvider("claude"),
{
...claudeProvider("codex"),
id: "codex",
name: "Codex",
defaultProgram: "codex",
commandOverridden: false,
args: ["app-server"],
defaultArgs: ["app-server"],
installed: false,
},
];
const changed = vi.fn();
await openCommands(commands, changed);
expect(screen.getByRole("option", { name: "Claude Code" })).toBeInTheDocument();
const codex = screen.getByRole("option", { name: "Codex Not found" });
fireEvent.change(field(), { target: { value: "/custom/claude" } });
fireEvent.mouseDown(codex);
expect(screen.getByText("codex app-server")).toBeInTheDocument();
expect(field()).toHaveAttribute("placeholder", "Auto-detect (codex)");
fireEvent.change(field(), { target: { value: "/custom/codex" } });
expect(commands.saved).toEqual([]);
await act(async () => fireEvent.click(screen.getByRole("button", { name: button })));
expect(commands.saved).toEqual([
["claude", "/custom/claude"],
["codex", "/custom/codex"],
]);
expect(changed).toHaveBeenCalledTimes(2);
if (button === "Apply") expect(screen.getByRole("option", { name: "Codex Custom" })).toBeInTheDocument();
});
it.each(["packageRunner", "registry"] as const)("keeps %s built-ins visible and read-only", async (reason) => {
const commands = new FakeCommands();
commands.list = [
{
...claudeProvider("npx"),
id: "claude-acp",
name: "Claude Code (ACP)",
defaultProgram: "npx",
defaultArgs: ["-y", "adapter"],
commandEditable: false,
commandReadOnlyReason: reason,
source: reason === "registry" ? { kind: "registry", version: "1", update: null } : { kind: "builtin" },
},
];
render(<AgentRegistryPage backend={new FakeBackend()} commandBackend={commands} />);
expect(await screen.findByText("npx -y adapter")).toBeInTheDocument();
expect(screen.queryByRole("textbox", { name: "Executable" })).toBeNull();
expect(screen.queryByRole("button", { name: "Browse…" })).toBeNull();
expect(
screen.getByText(
reason === "packageRunner" ? /runs through a package runner/ : /installed from the ACP Registry/,
),
).toBeInTheDocument();
expect(commands.saved).toEqual([]);
});
it("stages a browsed executable", async () => {
const commands = new FakeCommands();
commands.list = [claudeProvider("claude")];
await openCommands(commands);
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Browse…" })));
expect(field()).toHaveValue("/chosen/agent");
expect(commands.saved).toEqual([]);
await act(async () => fireEvent.click(apply()));
expect(commands.saved).toEqual([["claude", "/chosen/agent"]]);
});
});
+8
Переглянути файл
@@ -42,6 +42,14 @@ const claude: AgentProvider = {
installed: true,
config: [],
source: { kind: "builtin" },
program: "claude",
args: [],
defaultProgram: "claude",
defaultArgs: [],
loginHint: null,
commandOverridden: false,
commandEditable: true,
commandReadOnlyReason: null,
// Offered by the agent's last session in this project.
commands: [command("compact", "Free up context")],
};
+27 -1
Переглянути файл
@@ -1,6 +1,14 @@
/** Agents of the ACP Registry: listing, install / update / remove (`agent_registry_*`). */
import { open } from "@tauri-apps/plugin-dialog";
import { Channel } from "@tauri-apps/api/core";
import type { AgentRegistry, InstallEvent, RegistryAgent, RegistryDistribution, RequestId } from "@/bindings";
import type {
AgentProvider,
AgentRegistry,
InstallEvent,
RegistryAgent,
RegistryDistribution,
RequestId,
} from "@/bindings";
import { call, commands } from "@/platform/ipc";
export interface RegistryBackend {
@@ -10,6 +18,13 @@ export interface RegistryBackend {
cancel(request: RequestId): void;
}
/** The built-in agents' launch commands: read, and override through an agent file. */
export interface CommandsBackend {
providers(): Promise<AgentProvider[]>;
set(id: string, command: string | null): Promise<void>;
chooseExecutable(title: string, current?: string): Promise<string | null>;
}
export const tauriRegistry: RegistryBackend = {
list: (request) => call(commands.agentRegistryList(request)),
install: async (id, request, onEvent) => {
@@ -23,6 +38,17 @@ export const tauriRegistry: RegistryBackend = {
cancel: (request) => void commands.cancelRequest(request).catch(() => {}),
};
export const tauriCommands: CommandsBackend = {
providers: () => call(commands.agentProviders()),
chooseExecutable: async (title, current) => {
const picked = await open({ title, defaultPath: current || undefined, directory: false, multiple: false });
return typeof picked === "string" ? picked : null;
},
set: async (id, command) => {
await call(commands.agentSetCommand(id, command));
},
};
export const DISTRIBUTION_LABEL: Record<RegistryDistribution, string> = {
binary: "Binary",
npx: "npm",
+92
Переглянути файл
@@ -0,0 +1,92 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { BuildModel, MavenModel, ProjectInfo } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { loadModel, PROFILE_RELOAD_DELAY_MS, resetBuild, setProfile, useBuild } from "./store";
const mocks = vi.hoisted(() => ({ model: vi.fn(), sync: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
call: (value: unknown) => value,
commands: {
...real.commands,
buildModel: mocks.model,
runConfigs: () => Promise.resolve([]),
buildSync: mocks.sync,
cancelRequest: () => Promise.resolve(),
},
};
});
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage: unknown = null;
},
}));
const maven = {
syncedAt: 1,
stale: false,
syncError: null,
profiles: [
{ id: "native", activeByDefault: false },
{ id: "local", activeByDefault: false },
{ id: "dev", activeByDefault: true },
],
projects: [],
} as unknown as MavenModel;
const model: BuildModel = { maven, gradle: null };
/** The `-P` entries each sync was started with. */
const syncedProfiles = () => mocks.sync.mock.calls.map((c) => c[3] as string[]);
beforeEach(async () => {
vi.clearAllMocks();
localStorage.clear();
resetBuild();
useBuild.setState({ syncing: {} });
useProject.setState({ project: { root: "/p", trusted: true } as ProjectInfo });
mocks.model.mockResolvedValue(model);
await loadModel();
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("reloads Maven once with the new profiles after a few toggles", async () => {
let finish = () => {};
mocks.sync.mockImplementation(() => new Promise((resolve) => (finish = () => resolve(model))));
setProfile("native", true);
setProfile("local", true);
setProfile("dev", false);
expect(mocks.sync).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(PROFILE_RELOAD_DELAY_MS);
expect(syncedProfiles()).toEqual([["native", "local", "!dev"]]);
finish();
await vi.runAllTimersAsync();
expect(mocks.sync).toHaveBeenCalledTimes(1);
});
it("reloads again after a sync that started with the previous profiles", async () => {
const finishes: (() => void)[] = [];
mocks.sync.mockImplementation(() => new Promise((resolve) => finishes.push(() => resolve(model))));
setProfile("native", true);
await vi.advanceTimersByTimeAsync(PROFILE_RELOAD_DELAY_MS);
setProfile("local", true);
await vi.advanceTimersByTimeAsync(PROFILE_RELOAD_DELAY_MS);
expect(syncedProfiles()).toEqual([["native"]]);
finishes[0]!();
await vi.runAllTimersAsync();
expect(syncedProfiles()).toEqual([["native"], ["native", "local"]]);
});
it("does not reload a project closed before the delay ran out", async () => {
setProfile("native", true);
resetBuild();
await vi.advanceTimersByTimeAsync(PROFILE_RELOAD_DELAY_MS);
expect(mocks.sync).not.toHaveBeenCalled();
});
+24
Переглянути файл
@@ -114,8 +114,19 @@ export const toggleSkipTests = () =>
export const toggleGradleOffline = () =>
updateSettings((s) => ({ ...s, gradle: { ...s.gradle, offline: !s.gradle.offline } }));
/** Delay before reloading Maven after a profile toggle, so a few toggles in a row reload once. */
export const PROFILE_RELOAD_DELAY_MS = 800;
let profileReload: ReturnType<typeof setTimeout> | undefined;
export function setProfile(id: string, checked: boolean) {
updateSettings((s) => ({ ...s, maven: { ...s.maven, profiles: { ...s.maven.profiles, [id]: checked } } }));
// The Java language server and Build Project resolve the project with the profiles of the
// last sync, so a new choice reloads it (IDEA re-imports on a profile change too).
clearTimeout(profileReload);
profileReload = setTimeout(() => {
profileReload = undefined;
requestSync("maven");
}, PROFILE_RELOAD_DELAY_MS);
}
export function readHistory(tool: BuildTool): string[] {
@@ -269,6 +280,15 @@ export function initialExpanded(tool: BuildTool, model: BuildModel): Set<string>
const TITLES: Record<BuildTool, string> = { maven: "Syncing Maven projects", gradle: "Syncing Gradle projects" };
/** Tools to sync again once their running sync ends: its options changed meanwhile. */
const queuedSyncs = new Set<BuildTool>();
/** Syncs `tool` now, or right after the sync in progress (which used the previous options). */
export function requestSync(tool: BuildTool) {
if (useBuild.getState().syncing[tool]) queuedSyncs.add(tool);
else void syncTool(tool);
}
/** Reloads all projects of `tool` from the build tool itself (effective POM, dependency tree, task list). */
export async function syncTool(tool: BuildTool): Promise<void> {
const state = useBuild.getState();
@@ -317,6 +337,7 @@ export async function syncTool(tool: BuildTool): Promise<void> {
} finally {
if (useBuild.getState().syncing[tool]?.request === request) setSync(undefined);
upsertTask({ id: taskId, title: TITLES[tool], message: null, fraction: 1, done: true });
if (queuedSyncs.delete(tool) && gen === generation) void syncTool(tool);
}
}
@@ -330,6 +351,9 @@ export function cancelSync(tool: BuildTool) {
export function resetBuild() {
generation++;
clearTimeout(profileReload);
profileReload = undefined;
queuedSyncs.clear();
useAnalyzer.setState({ pom: null });
for (const tool of ["maven", "gradle"] as const) {
cancelSync(tool);
+5
Переглянути файл
@@ -183,6 +183,11 @@ export function HierarchyView() {
{basename(item.path)}:{item.selectionRange.start.line + 1}
</span>
{calls > 1 && <span className={styles.muted}>{tx`(${calls} calls)`}</span>}
{n.node.recursion && (
<span className={styles.muted}>
<T>recursive</T>
</span>
)}
{notes.has(n.id) && (
<span className={styles.muted} title={notes.get(n.id)}>
{notes.get(n.id)}
-14
Переглянути файл
@@ -1,14 +0,0 @@
import { expect, it } from "vitest";
import { goConstraintExcluded } from "./goConstraints";
it("recognizes build exclusion without confusing unrelated package errors", () => {
expect(
goConstraintExcluded("No packages found for open file x.go.\nThis file may be excluded due to its build tags"),
).toBe(true);
expect(goConstraintExcluded("This file may be excluded due to its GOOS/GOARCH, or other build constraints.")).toBe(
true,
);
expect(goConstraintExcluded("No packages found for open file x.go.")).toBe(false);
expect(goConstraintExcluded("undefined: missingSymbol")).toBe(false);
expect(goConstraintExcluded("invalid build tags syntax")).toBe(false);
});
-4
Переглянути файл
@@ -1,4 +0,0 @@
/** Only gopls diagnostics that explicitly identify build exclusion qualify. */
export function goConstraintExcluded(message: string): boolean {
return /excluded[^\n]*(?:build|GOOS\/GOARCH)/i.test(message);
}
+24 -1
Переглянути файл
@@ -54,6 +54,8 @@ const callHierarchy = vi.fn((): { items: HierarchyItem[]; incomplete: References
incomplete: null,
}));
const cancelRequest = vi.fn(async () => undefined);
// The positions a hierarchy request is answered at; anything else is "no symbol".
let servedAt = (pos: { line: number; col: number }) => pos.line === 2 && pos.col === 7;
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
@@ -66,7 +68,7 @@ vi.mock("@/platform/ipc", async (orig) => {
cancelRequest,
lspCallHierarchy: async (_request: number, _doc: number, pos: { line: number; col: number }) => {
// The server prepares a hierarchy only on the method name.
if (pos.line !== 2 || pos.col !== 7) throw new real.IpcError({ kind: "notFound", message: "No symbol" });
if (!servedAt(pos)) throw new real.IpcError({ kind: "notFound", message: "No symbol" });
return callHierarchy();
},
},
@@ -83,6 +85,7 @@ vi.mock("./ipc", async (orig) => ({
const {
enclosingDeclaration,
hierarchyTarget,
loadChildren,
refreshHierarchy,
resetHierarchy,
showHierarchy,
@@ -143,4 +146,24 @@ describe("hierarchy", () => {
expect(cancelRequest).toHaveBeenCalledTimes(1);
answer({ items: [item("stale")], incomplete: null });
});
it("keeps a caller that repeats an ancestor a recursion leaf", async () => {
servedAt = () => true; // `main` calls itself: every level answers with the same item.
try {
useHierarchy.setState({ mode: "call", direction: "incoming" });
await showHierarchy("call");
const [top] = useHierarchy.getState().children.get(ROOT_ID) ?? [];
expect(top?.item.name).toBe("main");
expect(top?.recursion).toBeUndefined();
await loadChildren(top!);
const nested = useHierarchy.getState().children.get(top!.id)?.[0];
expect(nested?.item.name).toBe("main");
expect(nested?.recursion).toBe(true);
// The leaf carries no expandable children, so the tree never requests it again.
expect(useHierarchy.getState().children.get(nested!.id)).toEqual([]);
expect(useHierarchy.getState().failed.size).toBe(0);
} finally {
servedAt = (pos) => pos.line === 2 && pos.col === 7;
}
});
});
+43 -5
Переглянути файл
@@ -13,6 +13,8 @@ export type HierarchyMode = "call" | "type";
export interface HierarchyNode {
id: string;
item: HierarchyItem;
/** Set when the node repeats an ancestor: it is kept a leaf and marked "recursive". */
recursion?: boolean;
}
export interface HierarchyRoot {
@@ -107,19 +109,49 @@ export function childId(parent: string, item: HierarchyItem): string {
return `${parent}/${item.path}:${p.line}:${p.col}:${item.name}`;
}
function setChildren(generation: number, parent: string, items: HierarchyItem[], note: string | null) {
/** Position-unique key of a hierarchy item: the same symbol always has the same one. */
function itemKey(item: HierarchyItem): string {
const p = item.selectionRange.start;
return `${item.path}:${p.line}:${p.col}:${item.name}`;
}
/** The root's key, matching itemKey of the item its position resolves to. */
function rootKey(root: HierarchyRoot): string {
return `${root.path}:${root.line}:${root.col}:${root.name}`;
}
/** Each node's position key plus its ancestors', so a child repeating one is a cycle. */
const nodeKeys = new WeakMap<HierarchyNode, readonly string[]>();
function setChildren(
generation: number,
parent: string,
parentKeys: readonly string[],
items: HierarchyItem[],
note: string | null,
) {
const s = useHierarchy.getState();
if (s.generation !== generation) return;
const ancestors = new Set(parentKeys);
const seen = new Set<string>();
const nodes: HierarchyNode[] = [];
const children = new Map(s.children);
children.set(parent, nodes);
for (const item of items) {
const id = childId(parent, item);
if (seen.has(id)) continue;
seen.add(id);
nodes.push({ id, item });
const key = itemKey(item);
// A recursive symbol arrives with a fresh id on every level (the id carries the
// parent chain); only its position key reveals the cycle. Keep such a node a
// leaf — expanding it again would request the same level forever.
const node: HierarchyNode = ancestors.has(key) ? { id, item, recursion: true } : { id, item };
if (node.recursion) children.set(id, []);
nodeKeys.set(node, [...parentKeys, key]);
nodes.push(node);
}
useHierarchy.setState({
children: new Map(s.children).set(parent, nodes),
children,
...(note ? { notes: new Map(s.notes).set(parent, note) } : {}),
});
}
@@ -138,7 +170,7 @@ async function loadRoot(quiet = false): Promise<RootResult> {
const { items, incomplete } = await withDocument(root.path, (doc) =>
request(s.mode, doc, root.line, root.col, s.direction),
);
setChildren(generation, ROOT_ID, items, incomplete && incompleteNote(incomplete, root.name));
setChildren(generation, ROOT_ID, [rootKey(root)], items, incomplete && incompleteNote(incomplete, root.name));
return "loaded";
} catch (e) {
if (useHierarchy.getState().generation !== generation) return "stale";
@@ -189,7 +221,13 @@ export async function loadChildren(node: HierarchyNode) {
const { items, incomplete } = await withDocument(node.item.path, (doc) =>
request(mode, doc, at.line, at.col, direction),
);
setChildren(generation, node.id, items, incomplete && incompleteNote(incomplete, node.item.name));
setChildren(
generation,
node.id,
nodeKeys.get(node) ?? [],
items,
incomplete && incompleteNote(incomplete, node.item.name),
);
} catch (e) {
if (useHierarchy.getState().generation !== generation) return;
useHierarchy.setState((st) => ({
+1 -17
Переглянути файл
@@ -5,12 +5,7 @@
*/
import { registerActions } from "@/platform/actions";
import { useProject } from "@/platform/project";
import {
registerEditorBanner,
registerOverlay,
registerStatusItem,
registerToolWindow,
} from "@/workbench/contributions";
import { registerOverlay, registerStatusItem, registerToolWindow } from "@/workbench/contributions";
import { clearProblems, installProblemsEvents, useProblems } from "./problemsStore";
import { installProblemDecorations } from "./decorations";
import { ProblemsHeaderActions, ProblemsTabs, ProblemsView, useProblemsHeaderMenu } from "./ProblemsView";
@@ -20,7 +15,6 @@ import { findUsages, rerunActiveUsages, resetUsages, showUsageResults, showUsage
import { HierarchyTabs, HierarchyView } from "./HierarchyView";
import { resetHierarchy, showHierarchy } from "./hierarchy";
import { installServerEvents } from "./servers";
import { goConstraintExcluded } from "./goConstraints";
import { ServerStatus } from "./ServerStatus";
import { installWorkspaceEditUndo } from "./workspaceUndo";
@@ -48,16 +42,6 @@ export function activate(): () => void {
});
const disposers = [
unsubProject,
registerEditorBanner({
id: "go.buildConstraints",
useBanner: (path) => {
const excluded = useProblems(
(s) =>
path.endsWith(".go") && (s.map.get(path)?.get("gopls") ?? []).some((d) => goConstraintExcluded(d.message)),
);
return excluded ? { text: "This Go file is excluded by the current build constraints." } : null;
},
}),
installProblemsEvents(),
installProblemDecorations(),
installServerEvents(),
+15
Переглянути файл
@@ -1259,3 +1259,18 @@
flex: none;
width: 2px;
}
/* Wrap large values instead of laying megabytes out as one line. */
.largeCellEditor {
display: block;
box-sizing: border-box;
width: 100%;
height: min(60vh, 480px);
padding: 8px;
font: inherit;
color: inherit;
background: inherit;
white-space: pre-wrap;
overflow-wrap: anywhere;
resize: vertical;
}
+37
Переглянути файл
@@ -0,0 +1,37 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { commands } from "@/platform/ipc";
import { ExportDialog } from "./ExportDialog";
import { cellPreview } from "./cellPreview";
vi.mock("./store", () => ({ closeDialog: vi.fn() }));
vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify: vi.fn() }) }));
vi.mock("@tauri-apps/api/path", () => ({ homeDir: async () => "/home/test" }));
describe("large value export", () => {
it("bounds preview values while exporting every row in full", async () => {
const full = JSON.stringify({ text: "\u4e2d text ".repeat(200_000), tail: "complete" });
const dbExportFile = vi.spyOn(commands, "dbExportFile").mockResolvedValue({ status: "ok", data: null });
const rows = [[full], ["short"], [null]];
render(
<ExportDialog
data={{ columns: [{ name: "payload", type: "jsonb" }], rows, table: "big", driver: "postgres" }}
source="public.big"
initialFormat="json"
/>,
);
const preview = screen.getByLabelText("Export preview");
expect(JSON.parse(preview.textContent!)).toEqual([
{ payload: cellPreview(full) },
{ payload: "short" },
{ payload: null },
]);
await waitFor(() => expect(screen.getByLabelText("Output file")).toHaveValue("/home/test/big.json"));
fireEvent.click(screen.getByRole("button", { name: "Export to File" }));
await waitFor(() => expect(dbExportFile).toHaveBeenCalled());
const [path, contents] = dbExportFile.mock.calls[0]!;
expect(path).toBe("/home/test/big.json");
expect(JSON.parse(contents)).toEqual(rows.map(([payload]) => ({ payload })));
dbExportFile.mockRestore();
});
});
+10 -1
Переглянути файл
@@ -17,6 +17,7 @@ import {
import { CodePreview } from "./CodePreview";
import { closeDialog } from "./store";
import styles from "./Database.module.css";
import { cellPreview } from "./cellPreview";
const PREVIEW_ROWS = 100;
/** Formats with a tabular layout (the options apply). */
@@ -59,7 +60,15 @@ export function ExportDialog({
const tabular = TABULAR.has(format);
const effective = tabular ? options : DEFAULT_EXPORT_OPTIONS;
const preview = useMemo(
() => exportData(format, { ...data, rows: data.rows.slice(0, PREVIEW_ROWS) }, effective),
() =>
exportData(
format,
{
...data,
rows: data.rows.slice(0, PREVIEW_ROWS).map((row) => row.map((v) => (v === null ? null : cellPreview(v)))),
},
effective,
),
[format, data, effective],
);
const text = () => exportData(format, data, effective);
+58
Переглянути файл
@@ -3,6 +3,8 @@ import { registerActions } from "@/platform/actions";
import { fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Grid } from "./Grid";
import { CELL_PREVIEW_LIMIT, cellPreview } from "./cellPreview";
import { exportData } from "./export";
vi.mock("@tanstack/react-virtual", () => ({
useVirtualizer: ({ count }: { count: number }) => ({
@@ -72,3 +74,59 @@ describe("database grid", () => {
]);
});
});
describe("large database cells", () => {
const full = JSON.stringify({ text: "\u8bf4\u660e text \u6df7\u5408 ".repeat(200_000), tail: "complete" });
const columns = [{ name: "payload", type: "jsonb" }];
it("preserves short values and truncates only beyond the preview limit", () => {
for (const value of ["", "hello", "\u4e2d".repeat(CELL_PREVIEW_LIMIT)]) expect(cellPreview(value)).toBe(value);
expect(cellPreview(full)).toBe(full.slice(0, CELL_PREVIEW_LIMIT) + "\u2026");
expect(cellPreview("a".repeat(999) + "\ud83d\ude00tail")).toBe("a".repeat(999) + "\u2026");
});
it("bounds rendered text while copying and exporting the complete value", () => {
const writeText = vi.fn();
Object.defineProperty(navigator, "clipboard", { configurable: true, value: { writeText } });
render(<Grid columns={columns} rowCount={1} value={() => full} />);
const cell = screen.getByRole("gridcell");
expect(cell.textContent).toBe(cellPreview(full));
expect(cell.title).toBe(full.slice(0, 2000));
fireEvent.mouseDown(cell, { button: 0 });
fireEvent.keyDown(screen.getByRole("grid"), { key: "c", ctrlKey: true });
expect(writeText).toHaveBeenCalledWith(full);
expect(JSON.parse(exportData("json", { columns, rows: [[full]], table: "big", driver: "postgres" }))).toEqual([
{ payload: full },
]);
});
it("edits the full large value in a dialog and supports cancel and apply", () => {
const onEdit = vi.fn();
render(<Grid columns={columns} rowCount={1} value={() => full} editable onEdit={onEdit} />);
fireEvent.doubleClick(screen.getByRole("gridcell"));
expect(screen.getByRole("dialog")).toBeTruthy();
const editor = screen.getByRole("textbox") as HTMLTextAreaElement;
expect(editor.tagName).toBe("TEXTAREA");
expect(editor.value).toBe(full);
fireEvent.change(editor, { target: { value: full + "changed" } });
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
expect(onEdit).not.toHaveBeenCalled();
fireEvent.doubleClick(screen.getByRole("gridcell"));
fireEvent.change(screen.getByRole("textbox"), { target: { value: full + "changed" } });
fireEvent.click(screen.getByRole("button", { name: "Apply" }));
expect(onEdit).toHaveBeenCalledWith(0, 0, full + "changed");
expect(screen.queryByRole("dialog")).toBeNull();
});
it("keeps short values in the inline editor and preserves null display", () => {
const onEdit = vi.fn();
const { rerender } = render(<Grid columns={columns} rowCount={1} value={() => "short"} editable onEdit={onEdit} />);
fireEvent.doubleClick(screen.getByRole("gridcell"));
expect(screen.getByRole("textbox").tagName).toBe("INPUT");
fireEvent.change(screen.getByRole("textbox"), { target: { value: "updated" } });
fireEvent.keyDown(screen.getByRole("textbox"), { key: "Enter" });
expect(onEdit).toHaveBeenCalledWith(0, 0, "updated");
rerender(<Grid columns={columns} rowCount={1} value={() => null} />);
expect(screen.getByRole("gridcell").textContent).toBe("<null>");
});
});
+34 -5
Переглянути файл
@@ -6,10 +6,11 @@
import { useEffect, useMemo, useRef, useState, type ClipboardEvent, type KeyboardEvent, type MouseEvent } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
import clsx from "clsx";
import { Icon, showContextMenu, type MenuItem } from "@/ui";
import { Dialog, Icon, showContextMenu, type MenuItem } from "@/ui";
import { parseDelimited, toCsv, toTsv, type Cell } from "./model";
import styles from "./Database.module.css";
import { tx } from "@/platform/i18n";
import { CELL_PREVIEW_LIMIT, cellPreview } from "./cellPreview";
export interface GridColumn {
name: string;
@@ -103,7 +104,7 @@ export function Grid(props: GridProps) {
window.addEventListener("mouseup", stop);
return () => window.removeEventListener("mouseup", stop);
}, []);
const [editing, setEditing] = useState<{ row: number; col: number; text: string } | null>(null);
const [editing, setEditing] = useState<{ row: number; col: number; text: string; dialog: boolean } | null>(null);
const columnKey = columns.map((c) => c.name).join("\u0000");
const [widths, setWidths] = useState<number[]>([]);
const [numeric, setNumeric] = useState<boolean[]>([]);
@@ -171,7 +172,8 @@ export function Grid(props: GridProps) {
const startEdit = (row: number, col: number) => {
if (!editable || props.rowState?.(row) === "deleted") return;
setEditing({ row, col, text: value(row, col) ?? "" });
const text = value(row, col) ?? "";
setEditing({ row, col, text, dialog: text.length > CELL_PREVIEW_LIMIT });
};
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
@@ -302,6 +304,29 @@ export function Grid(props: GridProps) {
onPaste={onPaste}
onContextMenu={onContextMenu}
>
{editing?.dialog && (
<Dialog
open
title={tx`Edit ${columns[editing.col]!.name}`}
width={720}
onClose={() => setEditing(null)}
buttons={[
{ label: "Cancel", role: "cancel", onClick: () => setEditing(null) },
{ label: "Apply", role: "default", onClick: commit },
]}
>
<textarea
className={styles.largeCellEditor}
aria-label={`Edit ${columns[editing.col]!.name}`}
value={editing.text}
spellCheck={false}
wrap="soft"
onContextMenu={(e) => e.stopPropagation()}
onChange={(e) => setEditing({ ...editing, text: e.target.value })}
onKeyDown={(e) => e.stopPropagation()}
/>
</Dialog>
)}
<div className={styles.gridInner} style={{ width: totalWidth, height: virtualizer.getTotalSize() + ROW_H }}>
<div className={clsx(styles.gridRow, styles.gridHeader)} style={{ gridTemplateColumns: template }} role="row">
<div className={styles.rowNumber} />
@@ -368,7 +393,7 @@ export function Grid(props: GridProps) {
{state === "inserted" ? "+" : (props.rowNumber?.(r) ?? firstRowNumber + r)}
</div>
{columns.map((_, c) => {
if (editing && editing.row === r && editing.col === c) {
if (editing && !editing.dialog && editing.row === r && editing.col === c) {
return (
<input
key={c}
@@ -407,7 +432,11 @@ export function Grid(props: GridProps) {
onDoubleClick={() => startEdit(r, c)}
title={val != null && val.length > 40 ? val.slice(0, 2000) : undefined}
>
{val === null ? <span className={styles.null}>&lt;null&gt;</span> : displayed(val, !!numeric[c])}
{val === null ? (
<span className={styles.null}>&lt;null&gt;</span>
) : (
cellPreview(displayed(val, !!numeric[c]))
)}
</div>
);
})}
+10
Переглянути файл
@@ -0,0 +1,10 @@
export const CELL_PREVIEW_LIMIT = 1000;
/** Bound text layout without changing the underlying value or splitting a surrogate pair. */
export function cellPreview(value: string): string {
if (value.length <= CELL_PREVIEW_LIMIT) return value;
let end = CELL_PREVIEW_LIMIT;
const last = value.charCodeAt(end - 1);
if (last >= 0xd800 && last <= 0xdbff) end--;
return value.slice(0, end) + "\u2026";
}
+11
Переглянути файл
@@ -146,6 +146,17 @@ describe("reveal and expand", () => {
expect(visibleInfo(currentModel(), s.expanded).visible.has("/p/docs/guide.md")).toBe(true);
});
it("reveals files of linked workspace projects outside the workspace directory", async () => {
fs = new MemoryFs({ "/ws/.openidea/workspace.json": "x", "/a/src/app.ts": "x", "/b/lib/util.ts": "x" }, "/");
setProjectFsForTests(fs, "/ws");
initProjectTree("/ws", "ws", ["/a", "/b"]);
expect(revealPath("/b/lib/util.ts")).toBe(true);
await vi.waitFor(() => expect(childLabels("/b/lib")).toEqual(["util.ts"]));
const s = useProjectTree.getState();
expect(s.revealRequest?.path).toBe("/b/lib/util.ts");
expect(visibleInfo(currentModel(), s.expanded).visible.has("/b/lib/util.ts")).toBe(true);
});
it("expands everything below a folder", async () => {
await expandAll();
const s = useProjectTree.getState();
+12 -2
Переглянути файл
@@ -548,7 +548,7 @@ let revealSeq = 0;
export function revealPath(path: string, focus = false) {
const { expanded } = get();
const project = get().root;
const root = project && isSameOrInside(path, project) ? project : project ? extraRootOf(path) : null;
const root = project ? (memberRootOf(path) ?? (isSameOrInside(path, project) ? project : extraRootOf(path))) : null;
if (!root) return false;
// Library folders sit below group nodes (External Libraries › SDK), keyed in their own namespace.
const model = currentModel();
@@ -568,6 +568,16 @@ export function revealPath(path: string, focus = false) {
return true;
}
/**
* The linked workspace project containing `path`, if any (the innermost one). A
* workspace's root is its own directory; its projects are separate top-level roots.
*/
function memberRootOf(path: string): string | null {
let found: string | null = null;
for (const m of get().members ?? []) if (isSameOrInside(path, m) && (!found || m.length > found.length)) found = m;
return found;
}
/** The contributed folder (scratches, a library root…) containing `path`, if any. */
export function extraRootOf(path: string): string | null {
for (const r of extraFolders(projectViewRoots(useProjectViewRoots.getState().roots)))
@@ -583,7 +593,7 @@ export function modeShows(path: string): boolean {
case "project":
return true;
case "projectFiles":
return isSameOrInside(path, root);
return memberRootOf(path) !== null || (!get().members && isSameOrInside(path, root));
case "scratches":
return projectViewRoots(useProjectViewRoots.getState().roots).some(
(r) => r.scope === "scratches" && r.path !== undefined && isSameOrInside(path, r.path),
+16 -1
Переглянути файл
@@ -1,7 +1,7 @@
/** Page context for the form components: which page / scope they edit and the search query. */
import { createContext, useCallback, useContext, useMemo } from "react";
import type { SettingsForm } from "@/workbench/contributions";
import { stage, stagedValue, useSettingsDialog, type Scope } from "../model/staging";
import { externalKey, stage, stageExternal, stagedValue, useSettingsDialog, type Scope } from "../model/staging";
import { labelMatches } from "../model/pages";
export interface PageContextValue {
@@ -38,11 +38,26 @@ export function useSettingsFormFor(pageId: string, scope: Scope): SettingsForm {
scope,
useValue: (key: string) => useStagedValue(scope, key),
set: (key: string, value: unknown) => stage(pageId, scope, key, value),
useExternal: <T>(key: string, base: T, apply: (value: T) => Promise<T>) =>
useExternalValue(pageId, key, base, apply),
}),
[pageId, scope],
);
}
function useExternalValue<T>(page: string, key: string, base: T, apply: (value: T) => Promise<T>) {
const id = externalKey(page, key);
const staged = useSettingsDialog((s) => s.stagedExternal[id]);
const current = useSettingsDialog((s) => (id in s.externalApplied ? (s.externalApplied[id] as T) : base));
const saving = useSettingsDialog((s) => s.saving);
return {
value: staged ? (staged.value as T) : current,
current,
set: (value: T) => stageExternal(page, key, value, current, apply),
saving,
};
}
export function useSearchQuery(): string {
return useSettingsDialog((s) => s.query);
}
+5 -4
Переглянути файл
@@ -220,7 +220,7 @@ function SettingsDialogInner() {
/** Page tree + current page; reads the shared settings staging store. */
export function SettingsLayout() {
const pages = useSettingsPages((s) => s.pages);
const { pageId, query, staged, stagedSecrets, saving } = useSettingsDialog();
const { pageId, query, staged, stagedSecrets, stagedExternal, saving } = useSettingsDialog();
const treeRef = useRef<TreeHandle>(null);
const tree = useMemo(() => buildPageTree(pages.values()), [pages]);
@@ -235,8 +235,9 @@ export function SettingsLayout() {
const dirtyPages = useMemo(() => {
const pages = new Set(Object.values(staged).map((c) => c.page));
if (Object.keys(stagedSecrets).length) pages.add(SSH_SETTINGS_PAGE);
for (const c of Object.values(stagedExternal)) pages.add(c.page);
return pages;
}, [staged, stagedSecrets]);
}, [staged, stagedSecrets, stagedExternal]);
const pageDirty = !!current && dirtyPages.has(current.key);
// Back / forward through pages visited while the dialog is open.
@@ -338,7 +339,7 @@ export function SettingsLayout() {
/** OK / Cancel / Apply, ordered per platform by the dialog primitive. */
function useSettingsButtons(): DialogButton[] {
const { staged, stagedSecrets, base, globalBase, saving } = useSettingsDialog();
const { staged, stagedSecrets, stagedExternal, base, globalBase, saving } = useSettingsDialog();
const pending = useMemo(() => pendingChanges({ base, globalBase, staged }).length > 0, [base, globalBase, staged]);
const ok = async () => {
if (await applySettings()) closeSettings();
@@ -348,7 +349,7 @@ function useSettingsButtons(): DialogButton[] {
{ label: "Cancel", role: "cancel", onClick: closeSettings },
{
label: "Apply",
disabled: (!pending && !Object.keys(stagedSecrets).length) || saving,
disabled: (!pending && !Object.keys(stagedSecrets).length && !Object.keys(stagedExternal).length) || saving,
onClick: () => void applySettings(),
},
];
+54 -2
Переглянути файл
@@ -18,6 +18,12 @@ export interface StagedChange {
page: string;
}
interface ExternalChange {
page: string;
value: unknown;
apply(): Promise<unknown>;
}
export interface SettingsDialogState {
open: boolean;
pageId: string;
@@ -33,6 +39,9 @@ export interface SettingsDialogState {
staged: Record<string, StagedChange>;
/** SSH credentials stay outside settings JSON until Apply / OK. */
stagedSecrets: Record<string, string>;
stagedExternal: Record<string, ExternalChange>;
/** Values written outside settings JSON since opening the dialog. */
externalApplied: Record<string, unknown>;
/** Scope chosen per page (Global / This project). */
scopes: Record<string, Scope>;
saving: boolean;
@@ -52,6 +61,8 @@ export const useSettingsDialog = create<SettingsDialogState>(() => ({
newProjects: false,
staged: {},
stagedSecrets: {},
stagedExternal: {},
externalApplied: {},
scopes: {},
saving: false,
error: null,
@@ -79,6 +90,8 @@ export function openSettings(pageId?: string, opts: { newProjects?: boolean } =
newProjects: opts.newProjects ?? false,
staged: {},
stagedSecrets: {},
stagedExternal: {},
externalApplied: {},
saving: false,
error: null,
});
@@ -108,7 +121,15 @@ type Bases = Pick<SettingsDialogState, "base" | "globalBase">;
const baseFor = (s: Bases, scope: Scope) => (scope === "global" ? s.globalBase : s.base);
export function closeSettings() {
useSettingsDialog.setState({ open: false, staged: {}, stagedSecrets: {}, error: null, saving: false });
useSettingsDialog.setState({
open: false,
staged: {},
stagedSecrets: {},
stagedExternal: {},
externalApplied: {},
error: null,
saving: false,
});
}
/** Shows `pageId` (`page#focus` also selects `focus` on it). */
@@ -180,11 +201,25 @@ export function stageSshSecret(id: string, value: string) {
});
}
export const externalKey = (page: string, key: string) => `${page}|${key}`;
export function stageExternal<T>(page: string, key: string, value: T, base: T, apply: (value: T) => Promise<T>) {
useSettingsDialog.setState((s) => {
if (s.saving) return {};
const stagedExternal = { ...s.stagedExternal };
const id = externalKey(page, key);
if (deepEqual(value, base)) delete stagedExternal[id];
else stagedExternal[id] = { page, value, apply: () => apply(value) };
return { stagedExternal, error: null };
});
}
/** Discards staged edits of one page (the dialog's Reset button). */
export function resetPage(page: string) {
useSettingsDialog.setState((s) => ({
staged: Object.fromEntries(Object.entries(s.staged).filter(([, c]) => c.page !== page)),
stagedSecrets: page === SSH_SETTINGS_PAGE ? {} : s.stagedSecrets,
stagedExternal: Object.fromEntries(Object.entries(s.stagedExternal).filter(([, c]) => c.page !== page)),
error: null,
}));
}
@@ -254,7 +289,8 @@ export async function applySettings(deps: PersistDeps = defaultDeps()): Promise<
if (initial.saving) return false;
const changes = pendingChanges(initial);
const secrets = Object.entries(initial.stagedSecrets);
if (!changes.length && !secrets.length) return true;
const external = Object.entries(initial.stagedExternal);
if (!changes.length && !secrets.length && !external.length) return true;
useSettingsDialog.setState({ saving: true, error: null });
const result = await persistChanges(changes, deps);
const { written } = result;
@@ -293,6 +329,22 @@ export async function applySettings(deps: PersistDeps = defaultDeps()): Promise<
}
}
}
if (!error) {
for (const [id, change] of external) {
if (useSettingsDialog.getState().stagedExternal[id] !== change) continue;
try {
const value = await change.apply();
useSettingsDialog.setState((s) => {
const stagedExternal = { ...s.stagedExternal };
if (stagedExternal[id] === change) delete stagedExternal[id];
return { stagedExternal, externalApplied: { ...s.externalApplied, [id]: value } };
});
} catch (e) {
error = `${id}: ${e instanceof Error ? e.message : String(e)}`;
break;
}
}
}
useSettingsDialog.setState({ saving: false, error });
return error === null;
}
+3
Переглянути файл
@@ -44,6 +44,9 @@ export function TestSettingsForm({
const form = useMemo<SettingsForm>(
() => ({
scope,
useExternal: () => {
throw new Error("External settings are not supported by this stand-in");
},
useValue: (key) => useTestForm((s) => getAt(s.values, key)),
set: (key, value) =>
useTestForm.setState((s) => ({ values: putAt(s.values, key, value), staged: [...s.staged, [key, value]] })),
+59 -2
Переглянути файл
@@ -1,10 +1,31 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import type { BranchInfo } from "@/bindings";
import { messageProblems, wrapAtMargin } from "../CommitView";
import { linkifyIssues } from "../issueLinks";
import { defaultPushChecked, isProtectedBranch, isPushRejected, pushCandidates, type RepoPush } from "../remoteUi";
import {
defaultPushChecked,
isProtectedBranch,
isPushRejected,
pushCandidates,
pushRepoCommits,
type RepoPush,
} from "../remoteUi";
import { attentionRepo } from "../store";
import { statusDecorations } from "../model";
const vcsLog = vi.fn();
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return {
...real,
commands: {
...real.commands,
vcsLog: (repo: unknown, query: unknown) => vcsLog(repo, query),
},
};
});
const cfg = { blankLineAfterSubject: true, limitSubject: true, subjectLimit: 10, limitBody: true, bodyLimit: 8 };
describe("commit message inspections", () => {
@@ -93,3 +114,39 @@ describe("several repositories", () => {
expect([...defaultPushChecked(candidates, "/p/b")]).toEqual(["/p", "/p/b"]);
});
});
describe("pushRepoCommits", () => {
const branch = (head: string | null, upstream: string | null): BranchInfo => ({
head,
headCommit: "c1",
upstream,
ahead: 0,
behind: 0,
operation: null,
});
it("falls back to recent history when the upstream no longer resolves", async () => {
vcsLog.mockImplementation((_repo: unknown, q: { range: string | null }) =>
q.range === "@{u}..HEAD"
? Promise.resolve({
status: "error",
error: "fatal: ambiguous argument '@{u}..HEAD': unknown revision or path not in the working tree.",
})
: Promise.resolve({ status: "ok", data: [{ id: "c1" }] }),
);
await expect(pushRepoCommits("/p", branch("feature", "origin/feature"))).resolves.toEqual([{ id: "c1" }]);
expect(vcsLog).toHaveBeenLastCalledWith("/p", expect.objectContaining({ branch: "HEAD", range: null, limit: 50 }));
});
it("passes the upstream range through when it resolves", async () => {
vcsLog.mockReset().mockResolvedValue({ status: "ok", data: [] });
await pushRepoCommits("/p", branch("main", "origin/main"));
expect(vcsLog).toHaveBeenCalledWith("/p", expect.objectContaining({ range: "@{u}..HEAD", limit: 1000 }));
});
it("lists no commits for a detached HEAD", async () => {
vcsLog.mockClear();
await expect(pushRepoCommits("/p", branch(null, null))).resolves.toEqual([]);
expect(vcsLog).not.toHaveBeenCalled();
});
});
+15 -4
Переглянути файл
@@ -95,6 +95,18 @@ export function outgoingQuery(upstream: string | null): { branch: string; range:
return upstream ? { branch: "HEAD", range: "@{u}..HEAD", limit: 1000 } : { branch: "HEAD", range: null, limit: 50 };
}
/**
* Outgoing commits of one repository in the multi-repository Push dialog. `@{u}` no
* longer resolves once the upstream branch was deleted on the remote (the tracking
* config remains, `upstream_of` still reports it), so the range query falls back to
* recent history and the repository stays in the list, pushable.
*/
export async function pushRepoCommits(root: string, branch: BranchInfo): Promise<Commit[]> {
if (!branch.head) return [];
const q = outgoingQuery(branch.upstream);
return logOf(q.branch, q.limit, q.range, root).catch(() => logOf(q.branch, 50, null, root));
}
export interface PushTarget {
/** Local branch to push (default: the current one). */
branch?: string;
@@ -148,13 +160,12 @@ function MultiPushDialog({ onClose }: { onClose: () => void }) {
useEffect(() => {
let alive = true;
// A repository that cannot be read (e.g. its upstream branch was deleted) is left out.
// A repository whose branch info cannot be read is left out; a deleted upstream
// branch falls back to recent history (pushRepoCommits) and stays pushable.
Promise.allSettled(
roots.map(async (root) => {
const branch = await call(commands.vcsBranchInfo(root));
const q = outgoingQuery(branch.upstream);
const commits = branch.head ? await logOf(q.branch, q.limit, q.range, root) : [];
return { root, branch, commits };
return { root, branch, commits: await pushRepoCommits(root, branch) };
}),
).then((results) => {
if (!alive) return;
+10 -6
Переглянути файл
@@ -34,8 +34,11 @@
overflow: auto;
padding: 16px 28px 40vh;
outline: none;
/* The preview sits on the editor background, so its text comes from the
editor scheme: with a light UI theme + dark editor scheme, the UI's
--fg would be black-on-black here. */
background: var(--bg-editor, var(--bg-app));
color: var(--fg);
color: var(--fg-editor, var(--fg));
font-family: var(--font-ui);
font-size: calc(14px + var(--markdown-font-zoom, 0px));
line-height: 1.6;
@@ -53,7 +56,7 @@
.preview :global(h5),
.preview :global(h6) {
margin: 1.2em 0 0.6em;
color: var(--fg-strong);
color: var(--syn-markup-heading, var(--fg-strong));
line-height: 1.25;
}
.preview :global(h1) {
@@ -90,12 +93,12 @@
font-size: 0.9em;
padding: 0.1em 0.35em;
border-radius: var(--radius-small);
background: var(--bg-elev);
background: var(--bg-editor-inline, var(--bg-elev));
}
.preview :global(pre) {
padding: 10px 12px;
border-radius: var(--radius-control);
background: var(--bg-elev);
background: var(--bg-editor-inline, var(--bg-elev));
overflow: auto;
line-height: 1.45;
}
@@ -107,7 +110,8 @@
.preview :global(blockquote) {
padding: 0 1em;
border-left: 3px solid var(--border-strong);
color: var(--fg-secondary);
color: var(--fg-editor, var(--fg-secondary));
opacity: 0.8;
}
.preview :global(table) {
border-collapse: collapse;
@@ -118,7 +122,7 @@
border: 1px solid var(--border-strong);
}
.preview :global(th) {
background: var(--bg-elev);
background: var(--bg-editor-inline, var(--bg-elev));
}
.preview :global(hr) {
border: none;
+20 -1
Переглянути файл
@@ -20,7 +20,7 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { maybeEditorService } from "@/workbench/contributions";
import { highlightInto } from "@/editor/lsp/markdown";
import { FloatingToolbar, selectableText } from "@/ui";
import { useLiveMarkdown } from "./live";
import { publishPreviewTop, useLiveMarkdown } from "./live";
import { hasMermaid, MERMAID_SELECTOR, renderMermaidIn, subscribeTheme, themeKey } from "./mermaid";
import { modeOf, useMarkdownModes } from "./modes";
import { MarkdownLayoutActions } from "./MarkdownLayoutActions";
@@ -144,6 +144,25 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
root.scrollTop = topLine <= 0 ? 0 : previewOffsetForLine(blocks, topLine, root.scrollHeight);
}, [html, topLine, scrollSeq, sync, diagramsDrawn]);
// The preview's own scroll offset: tab switches and mode toggles unmount the
// preview, so Preview Only would otherwise start over at the top. Writes made
// by the split sync above are captured too — the last visible position wins.
useEffect(() => {
const root = ref.current;
if (!root) return;
const onScroll = () => publishPreviewTop(path, root.scrollTop);
root.addEventListener("scroll", onScroll, { passive: true });
return () => root.removeEventListener("scroll", onScroll);
}, [path]);
// Restore it on mount; in split mode the sync effect positions the preview.
useLayoutEffect(() => {
const root = ref.current;
if (!root || sync) return;
const saved = useLiveMarkdown.getState()[path]?.previewTop ?? 0;
if (saved > 0) root.scrollTop = saved;
}, [path, sync]);
const onClick = (e: MouseEvent) => {
const a = (e.target as Element).closest("a");
if (!a) return;
+8 -1
Переглянути файл
@@ -17,6 +17,8 @@ export interface LiveMarkdown {
scrollSeq: number;
/** The editor's font zoom in px; the preview scales its text by the same amount. */
fontZoom: number;
/** The preview div's own scrollTop, kept so Preview Only survives a remount. */
previewTop: number;
}
export const useLiveMarkdown = create<Record<string, LiveMarkdown | undefined>>(() => ({}));
@@ -25,11 +27,16 @@ const TEXT_DELAY = 120;
function publish(path: string, patch: Partial<LiveMarkdown>) {
useLiveMarkdown.setState((s) => {
const prev = s[path] ?? { text: "", topLine: 0, scrollSeq: 0, fontZoom: 0 };
const prev = s[path] ?? { text: "", topLine: 0, scrollSeq: 0, fontZoom: 0, previewTop: 0 };
return { [path]: { ...prev, ...patch } };
});
}
/** Records the preview's own scroll offset, published by the preview's scroll listener. */
export function publishPreviewTop(path: string, top: number) {
publish(path, { previewTop: top });
}
function topLineOf(view: EditorView): number {
const block = view.lineBlockAtHeight(view.scrollDOM.scrollTop);
return view.state.doc.lineAt(block.from).number - 1;
+82
Переглянути файл
@@ -0,0 +1,82 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, render, screen } from "@testing-library/react";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { _addEditor, _removeEditor, editorContributions, type EditorDocContext } from "@/editor/api";
import { fontZoom } from "@/editor/core/cm/prefs";
import type { EditorSlot } from "@/editor/core/model/slot";
import { useContextKeys } from "@/platform/context";
let activeSlot: Partial<EditorSlot> | null = null;
vi.mock("@/editor/core/controller", async (importOriginal) => ({
...(await importOriginal<object>()),
editorController: () => ({
get activeSlot() {
return activeSlot;
},
}),
}));
const { registerMarkdownLiveSource, useLiveMarkdown } = await import("./live");
const { MarkdownEditor } = await import("./MarkdownEditor");
const { useMarkdownModes } = await import("./modes");
const mdCtx: EditorDocContext = { doc: 1, path: "/p/README.md", language: "markdown", uiMode: null, readOnly: false };
describe("preview-only scroll position", () => {
const disposers: Array<() => void> = [];
const views: EditorView[] = [];
const open = (ctx: EditorDocContext) => {
const live = editorContributions().find((c) => c.id === "viewers.markdownLive")!;
const view = new EditorView({
state: EditorState.create({ doc: "# Title", extensions: [fontZoom, live.extensions(ctx)] }),
});
const handle = { view, ctx };
_addEditor(handle);
disposers.push(() => _removeEditor(handle));
views.push(view);
return view;
};
const activate = (view: EditorView) => (activeSlot = { view, disposed: false });
beforeEach(() => {
disposers.push(registerMarkdownLiveSource());
useContextKeys.setState({ projectOpen: true, textEditorActive: true, editorFocus: true, popupOpen: true });
});
afterEach(() => {
cleanup();
for (const view of views.splice(0)) view.destroy();
for (const dispose of disposers.splice(0).reverse()) dispose();
activeSlot = null;
useLiveMarkdown.setState({}, true);
useContextKeys.setState({}, true);
});
it("restores the preview's own scroll after a remount", async () => {
open(mdCtx);
activate(views[0]!);
act(() => useMarkdownModes.setState((s) => ({ byPath: { ...s.byPath, [mdCtx.path]: "preview" } })));
const first = render(
<MarkdownEditor path={mdCtx.path} tabId="t">
<div />
</MarkdownEditor>,
);
const preview = screen.getByRole("document", { name: "Markdown preview" });
await act(async () => {
preview.scrollTop = 300;
preview.dispatchEvent(new Event("scroll"));
});
expect(useLiveMarkdown.getState()[mdCtx.path]?.previewTop).toBe(300);
// Tab switches and mode toggles unmount the preview; a fresh mount keeps the position.
first.unmount();
const second = render(
<MarkdownEditor path={mdCtx.path} tabId="t">
<div />
</MarkdownEditor>,
);
expect(screen.getByRole("document", { name: "Markdown preview" }).scrollTop).toBe(300);
second.unmount();
});
});
+39 -1
Переглянути файл
@@ -1,8 +1,36 @@
{
"Edit {name}": "编辑 {name}",
"The language server JDK ({path}) must be a full JDK with jdk.compiler, jdk.jdi and jdk.unsupported for Java language support and debugging. jdtls needs JDK {version} or newer. Download JDK {version}, choose a full JDK in {setting}, or set it to Auto.": "语言服务器 JDK({path})必须是包含 jdk.compiler、jdk.jdi 和 jdk.unsupported 的完整 JDK,才能支持 Java 语言功能和调试。jdtls 需要 JDK {version} 或更高版本。请下载 JDK {version},在 {setting} 中选择完整 JDK,或设为自动。",
"ACP Registry": "ACP 注册表",
"Apple's clangd does not run clang-tidy, so checks from .clang-tidy are not shown. Install clangd (LLVM) to get them.": "Apple 的 clangd 不运行 clang-tidy,因此不会显示 .clang-tidy 中配置的检查。请安装 clangd(LLVM)以启用这些检查。",
"Auto-detect ({defaultProgram})": "自动检测({defaultProgram})",
"Built-in": "内置",
"Built-in agents": "内置智能体",
"Custom executable": "自定义可执行文件",
"Found on PATH": "已在 PATH 中找到",
"Launch command": "启动命令",
"Sign in": "登录",
"Leave empty to find the executable on PATH. Changes apply to new sessions.": "留空以从 PATH 查找可执行文件。更改对新会话生效。",
"Newer dependency version available": "有更新的依赖版本可用",
"Not found": "未找到",
"Not found on PATH": "未在 PATH 中找到",
"Reports newer crate versions that Cargo.toml requirements do not already allow.": "报告 Cargo.toml 版本要求尚未允许的较新 crate 版本。",
"Run `auggie login` in a terminal.": "在终端中运行 `auggie login`。",
"Run `claude` in a terminal and sign in.": "在终端中运行 `claude` 并登录。",
"Run `codex login` in a terminal.": "在终端中运行 `codex login`。",
"Run `copilot` in a terminal and sign in.": "在终端中运行 `copilot` 并登录。",
"Run `cursor-agent login` in a terminal.": "在终端中运行 `cursor-agent login`。",
"Run `gemini` in a terminal and sign in.": "在终端中运行 `gemini` 并登录。",
"Run `goose configure` in a terminal.": "在终端中运行 `goose configure`。",
"Run `kimi` in a terminal and sign in.": "在终端中运行 `kimi` 并登录。",
"Run `kiro-cli login` in a terminal.": "在终端中运行 `kiro-cli login`。",
"Run `opencode auth login` in a terminal.": "在终端中运行 `opencode auth login`。",
"Run `qwen` in a terminal and sign in.": "在终端中运行 `qwen` 并登录。",
"Run `vibe` in a terminal and sign in.": "在终端中运行 `vibe` 并登录。",
"Sign in with the agent's own command line first.": "请先使用智能体自身的命令行登录。",
"This agent is configured in its agent file.": "此智能体在其智能体文件中配置。",
"This agent is installed from the ACP Registry. Manage its installation in the ACP Registry tab.": "此智能体从 ACP 注册表安装。请在 ACP 注册表标签页管理其安装。",
"This agent runs through a package runner (npm or uv) and has no executable to choose.": "此智能体通过包运行器(npm 或 uv)启动,无需选择可执行文件。",
"Update to {latest}": "更新至 {latest}",
"A newer version is available: {latest}": "有新版本可用:{latest}",
"Kotlin bridge requires a Maven build root": "Kotlin 桥接需要 Maven 构建根目录",
@@ -1623,6 +1651,7 @@
"oxfmt formatting timed out": "oxfmt 格式化超时",
"{name} does not support selection formatting for this language; formatted the whole file": "{name} 不支持此语言的选区格式化,已格式化整个文件",
"Formatting timed out": "格式化超时",
"{name} executable": "{name} 可执行文件",
"{name}: Node.js is required": "{name}:需要 Node.js",
"Formatter": "格式化工具",
"JSON with Comments": "带注释的 JSON",
@@ -5551,5 +5580,14 @@
"e.g. --keepdb --parallel": "例如 --keepdb --parallel",
"select files in a git repository to shelve": "请选择 Git 仓库中的文件以搁置更改",
"select files from a single git repository to shelve": "请一次只选择同一个 Git 仓库中的文件以搁置更改",
"External file changes sync may be slow": "外部文件更改同步可能较慢"
"External file changes sync may be slow": "外部文件更改同步可能较慢",
"recursive": "递归",
"Java project import failed": "Java 项目导入失败",
"The Java project cannot be imported because these files use a name Windows reserves for devices: {paths}. Delete or rename them, then restart the Java language server.": "无法导入 Java 项目,因为这些文件使用了 Windows 保留的设备名:{paths}。请删除或重命名这些文件,然后重启 Java 语言服务器。",
"This file is outside the source folders of its Java module: only syntax errors are reported, and navigation and completion don't work.": "此文件不在所属 Java 模块的源码目录中:只报告语法错误,跳转和补全不可用。",
"This file does not belong to an imported Java project: only syntax errors are reported, and navigation and completion don't work.": "此文件不属于已导入的 Java 项目:只报告语法错误,跳转和补全不可用。",
"This Go file belongs to no package of the workspace: code insight is limited.": "此 Go 文件不属于工作区中的任何包:代码洞察功能受限。",
"This Rust file is not included in any crate: rust-analyzer can't offer code insight for it.": "此 Rust 文件未包含在任何 crate 中:rust-analyzer 无法为它提供代码洞察。",
"Reload Maven Projects": "重新加载 Maven 项目",
"Reload Gradle Project": "重新加载 Gradle 项目"
}
+9
Переглянути файл
@@ -19,6 +19,15 @@ describe("virtual document URIs", () => {
expect(virtualName(JDT)).toBe("SpringApplication.class");
expect(virtualParent(JDT)).toBe("jdt://contents/spring-boot-4.1.1.jar/org.springframework.boot");
expect(virtualContainer(JDT)).toBe("spring-boot-4.1.1.jar › org.springframework.boot");
// `jar:` targets (official Kotlin LSP, sources jars), in both URI forms.
for (const prefix of ["jar:///", "jar:file:///"])
expect(
virtualContainer(
`${prefix}home/me/.m2/repository/spring-boot-3.5.16-sources.jar!/org/springframework/boot/SpringApplicationExtensions.kt`,
),
).toBe("spring-boot-3.5.16-sources.jar › org.springframework.boot");
expect(virtualContainer("jar:///tmp/my%20libs/a.jar!/Root.class")).toBe("a.jar");
expect(virtualName("jar:///tmp/a.jar!/org/x/Y.class")).toBe("Y.class");
});
it("makes path helpers URI-aware", () => {
+14
Переглянути файл
@@ -37,6 +37,20 @@ export function virtualParent(uri: string): string {
*/
export function virtualContainer(uri: string): string {
const scheme = uri.slice(0, uri.indexOf(":"));
// `jar:///…/spring-boot-3.5.16.jar!/org/springframework/boot/X.class` → `spring-boot-3.5.16.jar › org.springframework.boot`
const jar = scheme === "jar" ? /^jar:(?:file:)?(?:\/\/)?(.*?)!\/(.*)$/.exec(uri.split(/[?#]/)[0]!) : null;
if (jar) {
const decode = (s: string) => {
try {
return decodeURIComponent(s);
} catch {
return s;
}
};
const archive = decode(jar[1]!.split("/").pop() ?? jar[1]!);
const pkg = jar[2]!.split("/").slice(0, -1).map(decode).join(".");
return pkg ? `${archive} › ${pkg}` : archive;
}
const rest = uri.replace(/^[^:]+:(\/\/)?/, "").split(/[?#]/)[0]!;
const segs = rest
.split("/")
+3
Переглянути файл
@@ -3,6 +3,9 @@
min-height: 0;
overflow: auto;
outline: none;
/* Rows are controls: a page that opts into text selection must not select them on drag / ⌘A. */
-webkit-user-select: none;
user-select: none;
}
.list::-webkit-scrollbar {
width: 10px;
+1 -1
Переглянути файл
@@ -22,7 +22,7 @@ describe("selectable read-only surfaces", () => {
it("Markdown preview (the reported case)", () => {
act(() =>
useLiveMarkdown.setState({
"/p/README.md": { text: "# Title\n\nSome *text*", topLine: 0, scrollSeq: 0, fontZoom: 0 },
"/p/README.md": { text: "# Title\n\nSome *text*", topLine: 0, scrollSeq: 0, fontZoom: 0, previewTop: 0 },
}),
);
act(() => useMarkdownModes.setState((s) => ({ byPath: { ...s.byPath, "/p/README.md": "preview" } })));
+11
Переглянути файл
@@ -813,6 +813,17 @@ export interface SettingsForm {
useValue(key: string): unknown;
/** Stages a value; `null` removes the key on Apply. */
set(key: string, value: unknown): void;
/** Values stored outside settings JSON; the writer runs on Apply / OK and returns the saved value. */
useExternal<T>(
key: string,
base: T,
apply: (value: T) => Promise<T>,
): {
value: T;
current: T;
set(value: T): void;
saving: boolean;
};
}
export const SettingsFormContext = createContext<SettingsForm | null>(null);
+3 -2
Переглянути файл
@@ -2,7 +2,7 @@
import type { ReactNode } from "react";
import { create } from "zustand";
import { call, commands, onIdeEvent } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { txTemplate } from "@/platform/i18n";
import { useProject } from "@/platform/project";
import type { NotificationService } from "./contributions";
@@ -197,6 +197,7 @@ export const notificationServiceImpl: NotificationService = {
export function installNotifyEvents(): () => void {
return onIdeEvent(
"notify",
(e) => void notify({ level: e.level, title: tx(e.title), body: e.body ? tx(e.body) : undefined }),
// Backend text may carry values (paths, names); `{name}` catalog templates translate it.
(e) => void notify({ level: e.level, title: txTemplate(e.title), body: e.body ? txTemplate(e.body) : undefined }),
);
}