дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Порівняти коміти
34
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
eefe166cf7 | ||
|
|
8c9ddb9879 | ||
|
|
d54ef98a59 | ||
|
|
98517019e7 | ||
|
|
ae406ca2fb | ||
|
|
9dbae1d189 | ||
|
|
e4b8b76452 | ||
|
|
e2e699dca9 | ||
|
|
dcd8ecc5ae | ||
|
|
a3b6780823 | ||
|
|
bd2df0bd3a | ||
|
|
8ca25e1984 | ||
|
|
a15712b670 | ||
|
|
82130d37e5 | ||
|
|
07456b2562 | ||
|
|
659afe66f5 | ||
|
|
a57267fa32 | ||
|
|
4b1614af1f | ||
|
|
bdeca5803b | ||
|
|
839bd0cdb0 | ||
|
|
ebf2c2f8e3 | ||
|
|
c599265ced | ||
|
|
867774b88a | ||
|
|
d54e852c38 | ||
|
|
efd03630b6 | ||
|
|
bbc6a2bc4c | ||
|
|
86d082974f | ||
|
|
ec5302d838 | ||
|
|
dc14a46a17 | ||
|
|
d830d21d46 | ||
|
|
fd8161a5a7 | ||
|
|
bbb1be69a2 | ||
|
|
58ff3e93d0 | ||
|
|
795f8e85f1 |
No files matched your search
@@ -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>
|
||||
```
|
||||
@@ -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.
|
||||
Symlink
@@ -0,0 +1 @@
|
||||
../../.agents/skills/issue-fix
|
||||
Symlink
@@ -0,0 +1 @@
|
||||
../../.agents/skills/verify
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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. -->
|
||||
@@ -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/
|
||||
@@ -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
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
@@ -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.
|
||||
Створено
+37
-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,12 +6148,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.34"
|
||||
version = "0.1.35"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"block2 0.6.2",
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
"gtk",
|
||||
"ide-agent",
|
||||
"ide-analysis",
|
||||
"ide-build",
|
||||
|
||||
+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"
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
|
||||
## Project Lombok
|
||||
|
||||
`plugins/lombok/lombok-1.18.48-openidea.1.jar` contains Project Lombok v1.18.48 with the Equinox
|
||||
classloader fix from [projectlombok/lombok#4059](https://github.com/projectlombok/lombok/pull/4059).
|
||||
`plugins/lombok/lombok-1.18.48-openidea.2.jar` contains Project Lombok v1.18.48 with the Equinox
|
||||
classloader fix from [projectlombok/lombok#4059](https://github.com/projectlombok/lombok/pull/4059)
|
||||
and the ECJ constructor-call fix from [projectlombok/lombok#4089](https://github.com/projectlombok/lombok/pull/4089).
|
||||
Copyright (C) 2009-2021 The Project Lombok Authors. MIT license and bundled component
|
||||
notices are retained in [plugins/lombok/LICENSE](plugins/lombok/LICENSE) and inside the jar.
|
||||
Source tag, patch commits and build instructions: [plugins/lombok/README.md](plugins/lombok/README.md).
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -158,8 +158,11 @@ fn detect_dir(dir: &Path, model: &BuildModel, root: &Path) -> Option<BuildSystem
|
||||
}
|
||||
|
||||
/// `root/rel`, without a trailing separator for the root itself.
|
||||
/// `root` / `rel`, joined per `/`-separated component: on Windows a single join of
|
||||
/// `a/b` keeps the `/`, and such a path does not compare equal to the same directory
|
||||
/// as other tools (JDT LS) spell it.
|
||||
fn subdir(root: &Path, rel: &str) -> PathBuf {
|
||||
if rel.is_empty() { root.to_path_buf() } else { root.join(rel) }
|
||||
rel.split('/').filter(|part| !part.is_empty()).fold(root.to_path_buf(), |path, part| path.join(part))
|
||||
}
|
||||
|
||||
fn rel_str(root: &Path, dir: &Path) -> String {
|
||||
@@ -737,11 +740,11 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
|
||||
.iter()
|
||||
.flat_map(|s| {
|
||||
["classes/kotlin", "classes/groovy", "classes/scala", "classes/java", "resources"]
|
||||
.map(|d| module.join("build").join(d).join(s))
|
||||
.map(|d| subdir(module, &format!("build/{d}/{s}")))
|
||||
})
|
||||
.collect(),
|
||||
BuildSystem::Maven if test => vec![module.join("target/test-classes"), module.join("target/classes")],
|
||||
BuildSystem::Maven => vec![module.join("target/classes")],
|
||||
BuildSystem::Maven if test => vec![subdir(module, "target/test-classes"), subdir(module, "target/classes")],
|
||||
BuildSystem::Maven => vec![subdir(module, "target/classes")],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
dirs.into_iter().filter(|d| d.is_dir()).collect()
|
||||
@@ -751,6 +754,30 @@ fn launch_class_dirs(system: BuildSystem, module: &Path, test: bool) -> Vec<Path
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Launch outputs use the platform separator throughout, so they compare equal to
|
||||
/// the same directories as JDT LS reports them.
|
||||
#[test]
|
||||
fn launch_dirs_use_one_separator() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let module = subdir(root.path(), "parent/app");
|
||||
for dir in ["target/classes", "target/test-classes", "build/classes/java/main", "build/resources/test"] {
|
||||
std::fs::create_dir_all(subdir(&module, dir)).unwrap();
|
||||
}
|
||||
let foreign = if std::path::MAIN_SEPARATOR == '\\' { '/' } else { '\\' };
|
||||
let dirs = [
|
||||
launch_class_dirs(BuildSystem::Maven, &module, true),
|
||||
launch_class_dirs(BuildSystem::Gradle, &module, true),
|
||||
]
|
||||
.concat();
|
||||
assert_eq!(dirs.len(), 4, "{dirs:?}");
|
||||
for dir in &dirs {
|
||||
let suffix = dir.strip_prefix(root.path()).unwrap().to_string_lossy().into_owned();
|
||||
assert!(!suffix.contains(foreign), "{suffix}");
|
||||
}
|
||||
assert_eq!(subdir(root.path(), ""), root.path());
|
||||
assert_eq!(subdir(root.path(), "a//b/"), root.path().join("a").join("b"));
|
||||
}
|
||||
|
||||
fn write(root: &Path, rel: &str, text: &str) {
|
||||
let p = root.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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> =
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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(|_| {})),
|
||||
|
||||
@@ -86,7 +86,7 @@ async fn resolve_launch(
|
||||
};
|
||||
let mut class_paths: Vec<String> = built.iter().map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
for p in std::mem::take(&mut info.class_paths) {
|
||||
if !class_paths.contains(&p) {
|
||||
if !class_paths.iter().any(|c| same_entry(c, &p, cfg!(windows))) {
|
||||
class_paths.push(p);
|
||||
}
|
||||
}
|
||||
@@ -131,15 +131,44 @@ async fn resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// A classpath entry as a comparable key. Entries come from JDT LS and from our own
|
||||
/// build model, which spell one directory differently on Windows (`\\?\` prefix,
|
||||
/// `/` or `\\`, drive-letter case); compared as text, a module output stayed on the
|
||||
/// classpath next to its launch snapshot and every resource was found twice.
|
||||
fn entry_key(path: &str, windows: bool) -> String {
|
||||
let path = match path.strip_prefix(r"\\?\UNC\") {
|
||||
Some(share) => format!(r"\\{share}"),
|
||||
None => path.strip_prefix(r"\\?\").unwrap_or(path).to_owned(),
|
||||
};
|
||||
let mut key = if windows { path.replace('\\', "/") } else { path };
|
||||
while key.len() > 1 && key.ends_with('/') {
|
||||
key.pop();
|
||||
}
|
||||
if windows { key.to_lowercase() } else { key }
|
||||
}
|
||||
|
||||
fn same_entry(a: &str, b: &str, windows: bool) -> bool {
|
||||
a == b || entry_key(a, windows) == entry_key(b, windows)
|
||||
}
|
||||
|
||||
fn use_snapshot(info: &mut JavaLaunchInfo, built: &[PathBuf], snapshot: &std::path::Path) -> Vec<PathBuf> {
|
||||
use_snapshot_on(info, built, snapshot, cfg!(windows))
|
||||
}
|
||||
|
||||
fn use_snapshot_on(
|
||||
info: &mut JavaLaunchInfo,
|
||||
built: &[PathBuf],
|
||||
snapshot: &std::path::Path,
|
||||
windows: bool,
|
||||
) -> Vec<PathBuf> {
|
||||
let mut copies = Vec::new();
|
||||
for (index, source) in built.iter().enumerate() {
|
||||
let dest = snapshot.join(index.to_string());
|
||||
let original = source.to_string_lossy();
|
||||
info.class_paths.retain(|p| p != original.as_ref());
|
||||
info.class_paths.retain(|p| !same_entry(p, &original, windows));
|
||||
let mut modular = false;
|
||||
for path in &mut info.module_paths {
|
||||
if path == original.as_ref() {
|
||||
if same_entry(path, &original, windows) {
|
||||
*path = dest.to_string_lossy().into_owned();
|
||||
modular = true;
|
||||
}
|
||||
@@ -185,6 +214,39 @@ pub(crate) fn register(d: &mut Dispatcher) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// JDT LS and our build model spell a module output differently on Windows; the
|
||||
/// snapshot must still replace it, or resources (MyBatis mapper XML) load twice.
|
||||
#[test]
|
||||
fn snapshots_replace_outputs_however_windows_spells_them() {
|
||||
let built = PathBuf::from(r"D:\workspace\arm\arm-web\target/classes");
|
||||
let jdtls = [
|
||||
r"D:\workspace\arm\arm-web\target\classes",
|
||||
r"d:\workspace\arm\arm-web\target\classes",
|
||||
r"D:/workspace/arm/arm-web/target/classes/",
|
||||
r"\\?\D:\workspace\arm\arm-web\target\classes",
|
||||
];
|
||||
for spelled in jdtls {
|
||||
let mut info = JavaLaunchInfo {
|
||||
class_paths: vec![spelled.into(), r"D:\m2\mybatis.jar".into()],
|
||||
module_paths: vec![spelled.into()],
|
||||
..Default::default()
|
||||
};
|
||||
use_snapshot_on(&mut info, std::slice::from_ref(&built), std::path::Path::new(r"C:\cache\launch-x"), true);
|
||||
assert_eq!(info.class_paths, [r"D:\m2\mybatis.jar"], "{spelled}");
|
||||
assert_eq!(
|
||||
info.module_paths,
|
||||
[std::path::Path::new(r"C:\cache\launch-x").join("0").to_string_lossy()],
|
||||
"{spelled}"
|
||||
);
|
||||
}
|
||||
assert!(same_entry(r"\\?\UNC\server\share\app\target\classes", r"\\server\share\app\target/classes", true));
|
||||
// Different directories stay different, and other platforms keep case and `\`.
|
||||
assert!(!same_entry(r"D:\a\target\classes", r"D:\a\target\test-classes", true));
|
||||
assert!(!same_entry("/work/App/target/classes", "/work/app/target/classes", false));
|
||||
assert!(!same_entry(r"/work/a\b", "/work/a/b", false));
|
||||
assert!(same_entry("/work/app/target/classes/", "/work/app/target/classes", false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_snapshots_survive_jdt_overwrites_and_replace_module_outputs() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -62,13 +62,24 @@ fn detected_and_saved(
|
||||
all
|
||||
}
|
||||
|
||||
/// Saves the user configurations. They come from [`configs`], toolchains applied, so what
|
||||
/// settings derived is dropped again: only the user's own choices reach `run.toml`.
|
||||
pub fn save_configs(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
configs: &[RunConfig],
|
||||
removed_detected_ids: &[String],
|
||||
) -> IdeResult<()> {
|
||||
ide_run::save_user_configs_with_removals(&host.project(window)?.root, configs, removed_detected_ids)
|
||||
let project = host.project(window)?;
|
||||
let settings = project.settings.effective();
|
||||
let configs: Vec<RunConfig> = configs
|
||||
.iter()
|
||||
.map(|c| match c.kind.as_str() {
|
||||
"gradle" => c.clone(),
|
||||
_ => ide_sdk::apply::without_derived(c, &project.root, &settings),
|
||||
})
|
||||
.collect();
|
||||
ide_run::save_user_configs_with_removals(&project.root, &configs, removed_detected_ids)
|
||||
}
|
||||
|
||||
pub async fn start(host: &Host, window: &str, config: RunConfig, on_output: Emit<OutputChunk>) -> IdeResult<RunInfo> {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -57,6 +57,16 @@ pub fn shared() -> IdeResult<reqwest::Client> {
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
/// `url`, with `http://` in front unless it starts with a scheme: a `://` later
|
||||
/// on (`localhost:8080/login?next=http://…`) does not count.
|
||||
pub(crate) fn with_scheme(url: &str) -> String {
|
||||
let has_scheme = url.split_once("://").is_some_and(|(scheme, _)| {
|
||||
scheme.starts_with(|c: char| c.is_ascii_alphabetic())
|
||||
&& scheme.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
|
||||
});
|
||||
if has_scheme { url.to_owned() } else { format!("http://{url}") }
|
||||
}
|
||||
|
||||
/// HTTP Proxy › Check connection: GETs `url` through `proxy` (the settings as
|
||||
/// edited, not yet applied). Any response but `407` counts as connected.
|
||||
pub async fn check_connection(proxy: &ProxySettings, url: &str, cancel: &CancellationToken) -> IdeResult<String> {
|
||||
@@ -64,7 +74,7 @@ pub async fn check_connection(proxy: &ProxySettings, url: &str, cancel: &Cancell
|
||||
return Err(IdeError::invalid(problem));
|
||||
}
|
||||
let url = url.trim();
|
||||
let url = if url.contains("://") { url.to_owned() } else { format!("http://{url}") };
|
||||
let url = with_scheme(url);
|
||||
let client = build(proxy)?;
|
||||
let request = client.get(&url).timeout(Duration::from_secs(30));
|
||||
let response = tokio::select! {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Preparing (substitution, body includes) and executing requests.
|
||||
|
||||
use crate::client::describe;
|
||||
use crate::client::{describe, with_scheme};
|
||||
use crate::env::{Environments, Resolver};
|
||||
use crate::parse::{BodyPart, RawRequest};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
@@ -84,10 +84,8 @@ pub fn prepare(
|
||||
Some((_, host)) => format!("http://{host}{url}"),
|
||||
None => return Err(IdeError::invalid(format!("relative URL {url} needs a Host header"))),
|
||||
}
|
||||
} else if !url.contains("://") {
|
||||
format!("http://{url}")
|
||||
} else {
|
||||
url
|
||||
with_scheme(&url)
|
||||
};
|
||||
Ok(PreparedRequest {
|
||||
name: raw.block.name.clone(),
|
||||
@@ -214,6 +212,20 @@ mod tests {
|
||||
assert_eq!(p.url, "http://localhost:9000/status");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn urls_without_a_scheme_default_to_http() {
|
||||
let url = |text: &str| {
|
||||
let f = parse(text);
|
||||
prepare(&f.requests[0], &f.variables, &Environments::default(), None, None).unwrap().url
|
||||
};
|
||||
assert_eq!(url("GET localhost:8080/health\n"), "http://localhost:8080/health");
|
||||
assert_eq!(
|
||||
url("GET localhost:8080/login?next=http://localhost:3000/\n"),
|
||||
"http://localhost:8080/login?next=http://localhost:3000/"
|
||||
);
|
||||
assert_eq!(url("GET https://api.test/cb?u=http://x\n"), "https://api.test/cb?u=http://x");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn executes_against_a_local_server() {
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
@@ -24,6 +24,7 @@ globset.workspace = true
|
||||
ignore.workspace = true
|
||||
toml.workspace = true
|
||||
percent-encoding = "2"
|
||||
zip.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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>) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -769,6 +769,47 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
|
||||
}
|
||||
}
|
||||
|
||||
/// `config` as it should be saved: without what [`apply_to_run_configs`] derives from
|
||||
/// settings, so a configuration read from the run list, edited and saved keeps following
|
||||
/// Languages & Frameworks instead of freezing today's toolchain (and the IDE's whole
|
||||
/// `PATH`) into `run.toml`. A value counts as derived when applying settings to the
|
||||
/// configuration without it produces it again: an environment entry (`PATH`,
|
||||
/// `VIRTUAL_ENV`, `JAVA_HOME`, `GOROOT`, …) or an absolute command its bare name
|
||||
/// resolves to (the project interpreter, a toolchain's `cargo` / `go`, Maven's `mvn`).
|
||||
pub fn without_derived(config: &RunConfig, root: &Path, s: &Settings) -> RunConfig {
|
||||
let applied = |c: &RunConfig| {
|
||||
let mut c = c.clone();
|
||||
apply_to_run_configs(std::slice::from_mut(&mut c), root, s);
|
||||
c
|
||||
};
|
||||
let mut out = config.clone();
|
||||
// Until nothing changes: some entries are derived only once others are gone
|
||||
// (the virtualenv's `PATH` is added only without `VIRTUAL_ENV`).
|
||||
while let Some(key) = out
|
||||
.env
|
||||
.iter()
|
||||
.find(|(key, value)| {
|
||||
let mut probe = out.clone();
|
||||
probe.env.remove(*key);
|
||||
applied(&probe).env.get(*key) == Some(*value)
|
||||
})
|
||||
.map(|(key, _)| key.clone())
|
||||
{
|
||||
out.env.remove(&key);
|
||||
}
|
||||
let path = Path::new(&config.command);
|
||||
if path.is_absolute()
|
||||
&& let Some(name) = path.file_name().map(|n| n.to_string_lossy().into_owned())
|
||||
{
|
||||
let mut probe = out.clone();
|
||||
probe.command = name.clone();
|
||||
if applied(&probe).command == config.command {
|
||||
out.command = name;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn sh_quote(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\'', r"'\''"))
|
||||
}
|
||||
|
||||
@@ -884,7 +884,7 @@ mod tests {
|
||||
configure_jdtls(&mut plain, Path::new("/p"), Path::new("/data"), &[], None, None, JDTLS_MIN_JAVA, &[], None);
|
||||
let data = |c: &LanguageServerConfig| c.args[c.args.iter().position(|a| a == "-data").unwrap() + 1].clone();
|
||||
assert_ne!(data(&cfg), data(&plain), "a separate workspace, so everything is rebuilt with the agent");
|
||||
let patched = Path::new("/managed/lombok-1.18.48-openidea.1.jar");
|
||||
let patched = Path::new("/managed/lombok-1.18.48-openidea.2.jar");
|
||||
let mut fixed = jdtls();
|
||||
configure_jdtls(
|
||||
&mut fixed,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -507,7 +507,7 @@ mod tests {
|
||||
let cache = repo.join("org/projectlombok/lombok/1.18.48");
|
||||
fs::create_dir_all(&cache).unwrap();
|
||||
fs::write(cache.join("lombok-1.18.48.jar"), b"official agent").unwrap();
|
||||
let patched = PathBuf::from("/managed/lombok-1.18.48-openidea.1.jar");
|
||||
let patched = PathBuf::from("/managed/lombok-1.18.48-openidea.2.jar");
|
||||
let selected = lombok_agent(tmp.path(), None, Some(patched.clone()), Some(repo.clone()));
|
||||
assert_eq!(selected.jar(), Some(patched.as_path()));
|
||||
assert_eq!(selected.problem(), None);
|
||||
|
||||
@@ -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('&', "&").replace('<', "<").replace('>', ">")
|
||||
}
|
||||
|
||||
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&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);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::apply::{
|
||||
apply_to_run_configs, configure_server, jdtls_jdk, maven_command, maven_options, project_jdk, python_interpreter,
|
||||
terminal_activation, tsdk,
|
||||
terminal_activation, tsdk, without_derived,
|
||||
};
|
||||
use crate::python::parse_pip_list;
|
||||
use crate::{bin_dir, exe, venv_of};
|
||||
@@ -1108,3 +1108,84 @@ fn go_modules_configure_gopls_in_place_and_commands_with_explicit_run_overrides(
|
||||
configure_server(&mut cleared, tmp.path(), tmp.path(), &Settings::default());
|
||||
assert_eq!(cleared.settings.unwrap()["env"], json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_a_loaded_run_configuration_drops_what_settings_derived() {
|
||||
if cfg!(windows) {
|
||||
return; // Unix paths
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
let touch = |rel: &str| {
|
||||
let p = root.join(rel);
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(&p, "").unwrap();
|
||||
p.to_string_lossy().into_owned()
|
||||
};
|
||||
let mut s = Settings::default();
|
||||
s.languages.python.interpreter = fake_venv(root, ".venv").to_string_lossy().into_owned();
|
||||
s.languages.node.interpreter = touch("node/bin/node");
|
||||
touch("rustup/toolchains/stable/bin/cargo");
|
||||
s.languages.rust.toolchain = root.join("rustup/toolchains/stable").to_string_lossy().into_owned();
|
||||
touch("go/bin/go");
|
||||
s.languages.go.goroot = root.join("go").to_string_lossy().into_owned();
|
||||
s.languages.go.gopath = root.join("gopath").to_string_lossy().into_owned();
|
||||
s.languages.go.modules.env = BTreeMap::from([("GOPROXY".into(), "https://proxy.example".into())]);
|
||||
fake_jdk(&root.join("jdk17"));
|
||||
s.languages.java.jdk = root.join("jdk17").to_string_lossy().into_owned();
|
||||
touch("maven/bin/mvn");
|
||||
s.languages.java.maven.home = root.join("maven").to_string_lossy().into_owned();
|
||||
s.languages.ruby.interpreter = touch("ruby/bin/ruby");
|
||||
touch("ruby/bin/bundle");
|
||||
s.tools.insert("godot".into(), ide_core::settings::ToolSettings { path: touch("Godot/godot") });
|
||||
|
||||
let saved = |kind: &str, command: &str, args: &[&str], env: &[(&str, &str)]| {
|
||||
let mut c = run(kind, command, args);
|
||||
c.detected = false;
|
||||
c.env = env.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
c
|
||||
};
|
||||
// As the user saved them: bare tools, only their own environment.
|
||||
let configs = [
|
||||
saved("python", "python", &["app.py"], &[]),
|
||||
saved("pytest", ".venv/bin/pytest", &["-x"], &[("FOO", "1")]),
|
||||
saved("npm", "npm", &["run", "dev"], &[]),
|
||||
saved("cargo", "cargo", &["run"], &[]),
|
||||
saved("go", "go", &["run", "."], &[]),
|
||||
saved("go", "go", &["mod", "tidy"], &[("GOPROXY", "off")]),
|
||||
saved("maven", "mvn", &["package"], &[]),
|
||||
saved("tomcat", "catalina", &[], &[]),
|
||||
saved("ruby", "ruby", &["app.rb"], &[]),
|
||||
saved("rake", "bundle", &["exec", "rake"], &[("RAILS_ENV", "test")]),
|
||||
saved("godot", "godot", &["--path", "."], &[]),
|
||||
// The user's own values that merely look like derived ones stay.
|
||||
saved("cargo", "/opt/rust/bin/cargo", &["build"], &[("PATH", "/custom/bin")]),
|
||||
saved("maven", "mvn", &["verify"], &[("JAVA_HOME", "/other/jdk")]),
|
||||
saved("python", "python", &["x.py"], &[("VIRTUAL_ENV", "/elsewhere/venv")]),
|
||||
];
|
||||
for user in configs {
|
||||
let mut loaded = user.clone();
|
||||
apply_to_run_configs(std::slice::from_mut(&mut loaded), root, &s);
|
||||
assert_ne!(loaded, user, "{} {}: settings apply to it", user.kind, user.command);
|
||||
let stored = without_derived(&loaded, root, &s);
|
||||
assert_eq!(stored, user, "{} {}: saved as the user left it", user.kind, user.command);
|
||||
let mut reloaded = stored;
|
||||
apply_to_run_configs(std::slice::from_mut(&mut reloaded), root, &s);
|
||||
assert_eq!(reloaded, loaded, "{} {}: runs the same after a save", user.kind, user.command);
|
||||
}
|
||||
|
||||
// Another bare name for the interpreter comes back as the interpreter's own.
|
||||
let mut loaded = saved("python", "python3", &["app.py"], &[]);
|
||||
apply_to_run_configs(std::slice::from_mut(&mut loaded), root, &s);
|
||||
assert_eq!(without_derived(&loaded, root, &s).command, exe("python"));
|
||||
|
||||
// A saved configuration follows a later interpreter change instead of a frozen PATH.
|
||||
let mut loaded = saved("ruby", "ruby", &["app.rb"], &[]);
|
||||
apply_to_run_configs(std::slice::from_mut(&mut loaded), root, &s);
|
||||
let mut next = without_derived(&loaded, root, &s);
|
||||
s.languages.ruby.interpreter = touch("ruby2/bin/ruby");
|
||||
apply_to_run_configs(std::slice::from_mut(&mut next), root, &s);
|
||||
let ruby2 = root.join("ruby2/bin");
|
||||
assert_eq!(next.command, ruby2.join("ruby").to_string_lossy());
|
||||
assert!(next.env["PATH"].starts_with(&*ruby2.to_string_lossy()), "{}", next.env["PATH"]);
|
||||
}
|
||||
@@ -18,7 +18,8 @@ use std::time::SystemTime;
|
||||
|
||||
pub use words::{MIN_WORD_CHARS, WordSpan, words};
|
||||
|
||||
/// Where a region's words come from; strings and comments understand escapes.
|
||||
/// Where a region's words come from; strings understand escapes, comments and
|
||||
/// prose skip backslash commands (`\brief`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RegionKind {
|
||||
Comment,
|
||||
@@ -421,15 +422,22 @@ fn capitalize(s: &str) -> String {
|
||||
/// blocks and inline code spans.
|
||||
pub fn prose_regions(text: &str) -> Vec<Region> {
|
||||
let mut out = Vec::new();
|
||||
let mut fence: Option<&str> = None;
|
||||
// The open fence: its character and length.
|
||||
let mut fence: Option<(char, usize)> = None;
|
||||
let mut offset = 0;
|
||||
for line in text.split_inclusive('\n') {
|
||||
let start = offset;
|
||||
offset += line.len();
|
||||
let trimmed = line.trim_start();
|
||||
let marker = ["```", "~~~"].into_iter().find(|m| trimmed.starts_with(m));
|
||||
let marker = ['`', '~'].into_iter().find_map(|c| {
|
||||
let n = trimmed.len() - trimmed.trim_start_matches(c).len();
|
||||
(n >= 3).then_some((c, n))
|
||||
});
|
||||
match (fence, marker) {
|
||||
(Some(open), Some(m)) if m == open => {
|
||||
// CommonMark: a closing fence uses the same character, is at least as
|
||||
// long as the opening one and has no info string, so a ```` fence can
|
||||
// show a ``` block.
|
||||
(Some((open, open_len)), Some((c, n))) if c == open && n >= open_len && trimmed[n..].trim().is_empty() => {
|
||||
fence = None;
|
||||
continue;
|
||||
}
|
||||
@@ -720,6 +728,14 @@ mod tests {
|
||||
assert_eq!(spans, ["Some prose ", " here\n", "more\n"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markdown_fences_close_on_a_matching_fence_only() {
|
||||
let text = "Example:\n````markdown\n```rust\nfn wrng() {}\n```\n````\nmore\n~~~\n```\nnot clsed\n~~~~\nend\n";
|
||||
let regions = prose_regions(text);
|
||||
let spans: Vec<_> = regions.iter().map(|r| &text[r.start..r.end]).collect();
|
||||
assert_eq!(spans, ["Example:\n", "more\n", "end\n"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation() {
|
||||
let s = Speller::default();
|
||||
|
||||
@@ -17,7 +17,11 @@ pub struct WordSpan {
|
||||
/// Words of `text[start..end]` in order, as absolute byte ranges.
|
||||
pub fn words(text: &str, start: usize, end: usize, kind: RegionKind, out: &mut Vec<WordSpan>) {
|
||||
let Some(slice) = text.get(start..end) else { return };
|
||||
let escapes = !matches!(kind, RegionKind::Name);
|
||||
let escapes = match kind {
|
||||
RegionKind::Name => Escapes::None,
|
||||
RegionKind::String => Escapes::Char,
|
||||
RegionKind::Comment | RegionKind::Prose => Escapes::Word,
|
||||
};
|
||||
let mut chunk_start = None;
|
||||
for (i, c) in slice.char_indices().chain(std::iter::once((slice.len(), ' '))) {
|
||||
if c.is_whitespace() {
|
||||
@@ -30,6 +34,18 @@ pub fn words(text: &str, start: usize, end: usize, kind: RegionKind, out: &mut V
|
||||
}
|
||||
}
|
||||
|
||||
/// What a `\` hides from the spell checker.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Escapes {
|
||||
/// Identifiers have no escapes.
|
||||
None,
|
||||
/// String literals: the escape letter (`\n`, `\t`), the rest of the word is text.
|
||||
Char,
|
||||
/// Comments and prose: the whole word, a Doxygen / TeX command (`\brief`,
|
||||
/// `\param`) or an escape quoted in a comment (`\n`).
|
||||
Word,
|
||||
}
|
||||
|
||||
/// URLs, e-mail addresses and the like are not prose.
|
||||
fn skip_chunk(chunk: &str) -> bool {
|
||||
if chunk.contains("://") || chunk.starts_with("www.") {
|
||||
@@ -41,7 +57,7 @@ fn skip_chunk(chunk: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn chunk(slice: &str, from: usize, to: usize, escapes: bool, base: usize, out: &mut Vec<WordSpan>) {
|
||||
fn chunk(slice: &str, from: usize, to: usize, escapes: Escapes, base: usize, out: &mut Vec<WordSpan>) {
|
||||
let text = &slice[from..to];
|
||||
if skip_chunk(text) {
|
||||
return;
|
||||
@@ -57,9 +73,15 @@ fn chunk(slice: &str, from: usize, to: usize, escapes: bool, base: usize, out: &
|
||||
if let Some(s) = run.take() {
|
||||
token(text, s, i, base + from, out);
|
||||
}
|
||||
// `\n`, `\t`, `é`: the escape letter is not part of the next word.
|
||||
if escapes && c == '\\' {
|
||||
chars.next();
|
||||
if c == '\\' {
|
||||
match escapes {
|
||||
Escapes::None => {}
|
||||
// `\n`, `\t`, `é`: the escape letter is not part of the next word.
|
||||
Escapes::Char => {
|
||||
chars.next();
|
||||
}
|
||||
Escapes::Word => while chars.next_if(|&(_, c)| c.is_alphanumeric() || c == '_').is_some() {},
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(s) = run {
|
||||
@@ -164,6 +186,14 @@ mod tests {
|
||||
assert_eq!(split("// 中文注释 naïve", RegionKind::Comment), ["naïve"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_backslash_commands_in_comments() {
|
||||
assert_eq!(split("/// \\brief Returns the sum.", RegionKind::Comment), ["Returns", "the", "sum"]);
|
||||
assert_eq!(split("@see \\ref Foo, \\param[in] count", RegionKind::Comment), ["see", "Foo", "count"]);
|
||||
assert_eq!(split("prints \\nthe line", RegionKind::Comment), ["prints", "line"]);
|
||||
assert_eq!(split("\\emph{word} text", RegionKind::Prose), ["word", "text"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_apostrophes_inside_words() {
|
||||
assert_eq!(split("'don't' shouldn't", RegionKind::Comment), ["don't", "shouldn't"]);
|
||||
|
||||
@@ -637,13 +637,15 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
display: "Lombok (jdtls agent)",
|
||||
kind: Plugin,
|
||||
commands: &["lombok.jar"],
|
||||
// Equinox removed getModuleClassLoader(boolean), breaking lombok.config lookup.
|
||||
// Return to Maven Central once an official release includes lombok#4059.
|
||||
// Equinox removed getModuleClassLoader(boolean), breaking lombok.config lookup (lombok#4059);
|
||||
// ECJ 3.46.200 keeps the constructor call in a constructor's statements, which
|
||||
// @SneakyThrows / @NonNull must not wrap or precede (lombok#4089).
|
||||
// Return to Maven Central once an official release includes both.
|
||||
// Source commit, build instructions and checksum: plugins/lombok/README.md.
|
||||
method: Method::Bundled {
|
||||
filename: "lombok-1.18.48-openidea.1.jar",
|
||||
version: "1.18.48-openidea.1",
|
||||
bytes: include_bytes!("../../../plugins/lombok/lombok-1.18.48-openidea.1.jar"),
|
||||
filename: "lombok-1.18.48-openidea.2.jar",
|
||||
version: "1.18.48-openidea.2",
|
||||
bytes: include_bytes!("../../../plugins/lombok/lombok-1.18.48-openidea.2.jar"),
|
||||
},
|
||||
fallback: None,
|
||||
version: V,
|
||||
|
||||
@@ -56,9 +56,9 @@ fn bundled_lombok_replaces_legacy_installs_on_every_platform_without_downloads()
|
||||
let info = tools.info("lombok", &[]).unwrap();
|
||||
let path = managed_bundle(env.root.parent().unwrap(), "lombok").unwrap();
|
||||
assert_eq!(info.status, ToolStatus::Installed);
|
||||
assert_eq!(info.version.as_deref(), Some("1.18.48-openidea.1"));
|
||||
assert_eq!(info.version.as_deref(), Some("1.18.48-openidea.2"));
|
||||
assert_eq!(info.path, Some(path.clone().into()));
|
||||
assert_eq!(path.file_name().unwrap(), "lombok-1.18.48-openidea.1.jar");
|
||||
assert_eq!(path.file_name().unwrap(), "lombok-1.18.48-openidea.2.jar");
|
||||
assert!(!info.can_install && !info.can_uninstall);
|
||||
assert_eq!(tools.unavailable_reason(registry::find("lombok").unwrap()), None);
|
||||
assert_eq!(fs::read(&legacy).unwrap(), b"old official agent", "other windows may still use it");
|
||||
|
||||
@@ -241,9 +241,9 @@ async fn resolve(shared: &Shared, target: &str) -> Response {
|
||||
let Some(root) = shared.roots.read().get(&key).cloned() else { return NOT_FOUND };
|
||||
let Ok(real_root) = tokio::fs::canonicalize(&root).await else { return NOT_FOUND };
|
||||
let mut file = root;
|
||||
let mut trailing_slash = true;
|
||||
// `/<token>/<key>` names a directory too: it redirects like any other.
|
||||
let trailing_slash = path.ends_with('/');
|
||||
for seg in segments {
|
||||
trailing_slash = seg.is_empty();
|
||||
if seg.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -347,6 +347,10 @@ mod tests {
|
||||
let base = url.trim_end_matches("/web/index.html");
|
||||
assert!(get(&format!("{base}/web/sub/a%20b.js"), None).await.contains("text/javascript"));
|
||||
assert!(get(&format!("{base}/web"), None).await.contains("Location: /"));
|
||||
// The served root itself, so relative URLs of its index page resolve inside it.
|
||||
let page = get(base, None).await;
|
||||
let root_path = base.trim_start_matches("http://").split_once('/').unwrap().1;
|
||||
assert!(page.starts_with("HTTP/1.1 301") && page.contains(&format!("Location: /{root_path}/\r\n")), "{page}");
|
||||
assert!(get(&format!("{base}/web/"), None).await.ends_with("<h1>hi</h1>"));
|
||||
assert!(get(&format!("{base}/../secret.txt"), None).await.starts_with("HTTP/1.1 404"));
|
||||
assert!(get(&format!("{base}/%2e%2e/secret.txt"), None).await.starts_with("HTTP/1.1 404"));
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
# Lombok agent for JDT LS
|
||||
|
||||
`lombok-1.18.48-openidea.1.jar` is the app-provided Java agent for JDT LS. It includes
|
||||
[projectlombok/lombok#4059](https://github.com/projectlombok/lombok/pull/4059), which restores
|
||||
`lombok.config` lookup after Equinox removed `getModuleClassLoader(boolean)`.
|
||||
`lombok-1.18.48-openidea.2.jar` is the app-provided Java agent for JDT LS. It includes:
|
||||
|
||||
- [projectlombok/lombok#4059](https://github.com/projectlombok/lombok/pull/4059), which restores
|
||||
`lombok.config` lookup after Equinox removed `getModuleClassLoader(boolean)`.
|
||||
- [projectlombok/lombok#4089](https://github.com/projectlombok/lombok/pull/4089) (fixes
|
||||
lombok#4084 / #4094). ECJ 3.46.200, bundled with JDT LS 1.63, keeps a constructor's explicit or
|
||||
implicit `super()` / `this()` call as the first element of its statements. Lombok 1.18.48 wrapped
|
||||
that call in the `@SneakyThrows` try block (ECJ then fails with "Internal Error compiling …
|
||||
BlockScope cannot be cast to MethodScope" and the whole workspace build fails) and put `@NonNull`
|
||||
checks before it; constructors Lombok generates lacked the statement.
|
||||
|
||||
The jar is embedded by `ide-tools`, so every platform receives the same bytes without a download.
|
||||
Both Java server startup and launch diagnostics obtain it through `managed_bundle`. Tool detection
|
||||
@@ -12,21 +19,27 @@ The filename includes the patch version because JDT LS workspace keys include th
|
||||
changing agents must rebuild classes produced by the old agent. Old jars remain for running windows.
|
||||
|
||||
Replace this temporary bundle with an official Maven Central release once that release includes
|
||||
#4059. Restore the registry's Maven Central install method and remove the embedded jar. Keep the
|
||||
#4059 and #4089. Restore the registry's Maven Central install method and remove the embedded jar. Keep the
|
||||
workspace migration test when changing its path.
|
||||
|
||||
## Provenance and build
|
||||
|
||||
- Repository: https://github.com/projectlombok/lombok
|
||||
- Base tag: `v1.18.48` (`b48657c83ce44d027984f539bd36048293ce5e8e`).
|
||||
- Cherry-picked commits from PR #4059, in order:
|
||||
- `2d535482a913de46c27d06c5b0b294918ede3f9c`
|
||||
- `3098f4dd78b5349c2f382e7310e64db810dd380b`
|
||||
- Upstream version: `1.18.48`; `openidea.1` identifies this distribution of the patched agent.
|
||||
- Cherry-picked commits, in order:
|
||||
- PR #4059 (`chagong/lombok` `fix-equinox-bundle-wiring`):
|
||||
- `2d535482a913de46c27d06c5b0b294918ede3f9c`
|
||||
- `3098f4dd78b5349c2f382e7310e64db810dd380b`
|
||||
- PR #4089 (`Rawi01/lombok` `eclipse-constructor-call-statement`):
|
||||
- `7832faa49b35c839088866daf865384c82cd555f`
|
||||
- `3f3a80b857a969839ab1baba12767aec4965ac32`
|
||||
- Upstream version: `1.18.48`; `openidea.2` identifies this distribution of the patched agent
|
||||
(`openidea.1` had #4059 only).
|
||||
Upstream's own `java -jar ... --version` still reports `1.18.48`.
|
||||
- SHA-256: `10f5cd1a32b946d3ff1c075735b94f35fffdbac11dea2be29d24dbf591dd51a4`
|
||||
- SHA-256: `2978d8b2d55dac1bb4936ba44562bc4549931d4e71a7ebfeaebccd60bcdf7379`
|
||||
- License: [MIT, including bundled component notices](LICENSE), also retained inside the jar.
|
||||
- Build environment: macOS arm64, OpenJDK 23.0.1, Apache Ant 1.10.15, upstream Ivy setup.
|
||||
- Build environment: macOS arm64, Temurin 25.0.5, Apache Ant 1.10.15, upstream Ivy setup
|
||||
(`openidea.1` was built with OpenJDK 23.0.1).
|
||||
|
||||
Build using the upstream Ant entry point described in its contributing guide:
|
||||
|
||||
@@ -35,16 +48,22 @@ git clone https://github.com/projectlombok/lombok.git
|
||||
cd lombok
|
||||
git checkout -b openidea-1.18.48 v1.18.48
|
||||
git fetch https://github.com/chagong/lombok.git fix-equinox-bundle-wiring
|
||||
git fetch https://github.com/Rawi01/lombok.git eclipse-constructor-call-statement
|
||||
git cherry-pick 2d535482a913de46c27d06c5b0b294918ede3f9c 3098f4dd78b5349c2f382e7310e64db810dd380b
|
||||
git cherry-pick 7832faa49b35c839088866daf865384c82cd555f 3f3a80b857a969839ab1baba12767aec4965ac32
|
||||
ant dist
|
||||
cp dist/lombok.jar /path/to/openidea/plugins/lombok/lombok-1.18.48-openidea.1.jar
|
||||
cp dist/lombok.jar /path/to/openidea/plugins/lombok/lombok-1.18.48-openidea.2.jar
|
||||
```
|
||||
|
||||
The changelog context conflicts because the first commit adds a release-note line under the
|
||||
older development heading and the second removes it. Resolve mechanically by adding then removing
|
||||
only that line, retaining the complete v1.18.48 changelog. The final source diff from v1.18.48 changes
|
||||
only `src/eclipseAgent/lombok/launch/PatchFixesHider.java`, `test/core/src/lombok/TestEclipse.java`,
|
||||
and `test/core/src/lombok/launch/PatchFixesHiderTest.java`; no other Java source changes were made.
|
||||
only that line, retaining the complete v1.18.48 changelog (the second commit is then empty and
|
||||
skipped). The #4089 commits apply cleanly. The final source diff from v1.18.48 changes
|
||||
`src/eclipseAgent/lombok/launch/PatchFixesHider.java`, `test/core/src/lombok/TestEclipse.java`,
|
||||
`test/core/src/lombok/launch/PatchFixesHiderTest.java` (#4059) and the Eclipse handlers
|
||||
`EclipseHandlerUtil`, `HandleConstructor`, `HandleFieldNameConstants`, `HandleNonNull`,
|
||||
`HandleSneakyThrows`, `HandleStandardException`, `HandleSuperBuilder`, `HandleUtilityClass` (#4089);
|
||||
no other Java source changes were made.
|
||||
In the build checkout, the two remote resolvers in
|
||||
`buildScripts/ivysettings.xml` were reordered to try Maven Central before Eclipse staging; the
|
||||
local resolver and all dependency coordinates were retained. The JVM was configured to use the
|
||||
@@ -66,6 +85,19 @@ On macOS arm64 with JDT LS 1.63.0 / Equinox 3.25.0, server OpenJDK 25 and projec
|
||||
identical `javap` output, including default `void` setters.
|
||||
- Upstream `PatchFixesHiderTest` passed both the standard OSGi and legacy Equinox lookup tests.
|
||||
|
||||
`openidea.2` (#4089) on macOS arm64, JDT LS 1.63.0-202610191322 (ECJ
|
||||
`compiler.batch_3.46.200.v20261008-1115`), server Temurin 25:
|
||||
|
||||
- ECJ batch with the agent, compliance 17 and 25, against ECJ 3.46.200 and 3.46.100: `@SneakyThrows`
|
||||
constructors with implicit `super()`, explicit `super()` and `this()`; `@NonNull` constructor
|
||||
parameters; `@RequiredArgsConstructor` with an initialized final field, `@AllArgsConstructor`,
|
||||
`@NoArgsConstructor`, `@Builder` record, `@Value @Builder`, `@UtilityClass`. `openidea.1` failed
|
||||
with "Internal Error compiling" on 3.46.200; `openidea.2` compiled on both ECJ versions, the
|
||||
programs ran with identical output, and `@NonNull` checks run after the constructor call again.
|
||||
- Real JDT LS `java/buildWorkspace(true)` of the same sources with the agent: `openidea.1` reported
|
||||
Failed with three internal errors and wrote no classes; `openidea.2` Succeeded with all classes.
|
||||
- `plugins/java-usages/tests/verify.py` and `read-write.py` passed with `openidea.2`.
|
||||
|
||||
Windows and Linux runtime validation has not been performed. Rust tests cover source selection
|
||||
for both supported architectures on all three OS variants, offline provisioning, corruption
|
||||
repair, concurrent windows, explicit user overrides, and JDT LS workspace migration.
|
||||
@@ -1 +1 @@
|
||||
10f5cd1a32b946d3ff1c075735b94f35fffdbac11dea2be29d24dbf591dd51a4 lombok-1.18.48-openidea.1.jar
|
||||
2978d8b2d55dac1bb4936ba44562bc4549931d4e71a7ebfeaebccd60bcdf7379 lombok-1.18.48-openidea.2.jar
|
||||
BIN
Бінарний файл не відображається.
@@ -79,6 +79,10 @@ objc2-foundation = { version = "0.3", default-features = false, features = ["std
|
||||
# Used only by the debug font-restriction override; Cargo dependency cfg cannot test debug_assertions.
|
||||
objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebViewConfiguration", "WKPreferences"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# Wayland detection and the client size without GTK's CSD shadow (linux_window_state.rs).
|
||||
gtk = "0.18"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Foundation",
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -15,6 +15,8 @@ pub struct AppInfo {
|
||||
pub version: String,
|
||||
pub platform: String,
|
||||
pub config_dir: ide_core::IpcPath,
|
||||
/// Linux on a Wayland display: GTK draws the frameless windows' shadow and resize edges.
|
||||
pub wayland: bool,
|
||||
}
|
||||
|
||||
pub use ide_host::ops::project::ProjectInfo;
|
||||
@@ -27,6 +29,10 @@ pub fn app_info(state: State<'_, AppState>) -> AppInfo {
|
||||
version: env!("CARGO_PKG_VERSION").into(),
|
||||
platform: std::env::consts::OS.into(),
|
||||
config_dir: state.config_dir.clone().into(),
|
||||
#[cfg(target_os = "linux")]
|
||||
wayland: crate::linux_window_state::is_wayland(),
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
wayland: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -14,6 +14,7 @@ mod runtime {
|
||||
use super::*;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::OnceLock;
|
||||
use tauri::{AppHandle, Listener, Manager, Window, WindowEvent, plugin::TauriPlugin};
|
||||
|
||||
const FILE: &str = tauri_plugin_window_state::DEFAULT_FILENAME;
|
||||
@@ -63,8 +64,42 @@ mod runtime {
|
||||
visible: bool,
|
||||
}
|
||||
|
||||
static WAYLAND: OnceLock<bool> = OnceLock::new();
|
||||
|
||||
/// GDK's backend, as tao tests it (`GDK_BACKEND=x11` under a Wayland session is X11).
|
||||
/// Known once the plugin is set up, before any window exists.
|
||||
pub fn is_wayland() -> bool {
|
||||
WAYLAND.get().copied().unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The client size that `set_size` (`gtk_window_resize`) takes. On Wayland, decorated windows
|
||||
/// get a GTK CSD shadow margin that tao's inner and outer sizes (the configure size) include.
|
||||
pub fn content_size(window: &Window) -> tauri::Result<tauri::PhysicalSize<u32>> {
|
||||
let inner = window.inner_size()?;
|
||||
if !is_wayland() {
|
||||
return Ok(inner);
|
||||
}
|
||||
// GTK objects belong to the main thread. `gtk_window_get_size` follows the configure
|
||||
// synchronously; the webview's allocation only catches up on the next layout.
|
||||
let (tx, rx) = std::sync::mpsc::sync_channel(1);
|
||||
let cloned = window.clone();
|
||||
window.run_on_main_thread(move || {
|
||||
let sizes = cloned.gtk_window().ok().zip(cloned.inner_size().ok()).zip(cloned.scale_factor().ok());
|
||||
let _ = tx.send(sizes.map(|((gtk, inner), scale)| {
|
||||
let (width, height) = gtk::prelude::GtkWindowExt::size(>k);
|
||||
let content = tauri::LogicalSize::new(width.max(0) as u32, height.max(0) as u32);
|
||||
(content.to_physical::<u32>(scale), inner)
|
||||
}));
|
||||
})?;
|
||||
let Some((content, inner)) = rx.recv().ok().flatten() else { return Ok(inner) };
|
||||
// An unmapped window reports its size request; never exceed the configure size.
|
||||
let usable =
|
||||
content.width > 1 && content.height > 1 && content.width <= inner.width && content.height <= inner.height;
|
||||
Ok(if usable { content } else { inner })
|
||||
}
|
||||
|
||||
fn frame(window: &Window) -> Option<Frame> {
|
||||
let size = window.inner_size().ok()?;
|
||||
let size = content_size(window).ok()?;
|
||||
Some(Frame {
|
||||
visible: window.is_visible().ok()?,
|
||||
size: Size(size.width, size.height),
|
||||
@@ -381,6 +416,9 @@ mod runtime {
|
||||
pub fn plugin() -> TauriPlugin<tauri::Wry> {
|
||||
tauri::plugin::Builder::new("linux-window-state")
|
||||
.setup(|app, _| {
|
||||
// Plugins are set up on the main thread once GTK is initialised, before any window exists.
|
||||
use gtk::gdk::prelude::DisplayExtManual;
|
||||
let _ = WAYLAND.set(gtk::gdk::Display::default().is_some_and(|d| d.backend().is_wayland()));
|
||||
let saved = app
|
||||
.path()
|
||||
.app_config_dir()
|
||||
@@ -466,7 +504,7 @@ mod runtime {
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use runtime::{normal_size_requested, plugin, prepare, save_before_close};
|
||||
pub use runtime::{content_size, is_wayland, normal_size_requested, plugin, prepare, save_before_close};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
@@ -66,6 +66,10 @@ fn copy_frame(from: &WebviewWindow, to: &WebviewWindow) -> IdeResult<()> {
|
||||
if !maximized {
|
||||
to.unmaximize().map_err(err)?;
|
||||
to.set_position(from.outer_position().map_err(err)?).map_err(err)?;
|
||||
// `set_size` excludes GTK's CSD shadow, which tao's inner size includes on Wayland.
|
||||
#[cfg(target_os = "linux")]
|
||||
let size = crate::linux_window_state::content_size(&from.as_ref().window()).map_err(err)?;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let size = from.inner_size().map_err(err)?;
|
||||
#[cfg(target_os = "linux")]
|
||||
crate::linux_window_state::normal_size_requested(to.app_handle(), to.label(), size);
|
||||
|
||||
@@ -307,6 +307,8 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
|
||||
let window = WebviewWindowBuilder::from_config(app, &config)
|
||||
.and_then(|b| dev_font_preferences(b).build())
|
||||
.map_err(|e| IdeError::internal(format!("cannot create window: {e}")))?;
|
||||
#[cfg(target_os = "linux")]
|
||||
decorate_csd(&window);
|
||||
apply_zoom(app, &window);
|
||||
#[cfg(target_os = "macos")]
|
||||
align_titlebar(app, &window);
|
||||
@@ -329,6 +331,17 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult<
|
||||
Ok(window)
|
||||
}
|
||||
|
||||
/// Wayland: tao already makes frameless windows client-side decorated (an empty GTK title bar, so
|
||||
/// the compositor adds no frame), but undecorated GTK windows get no shadow or resize margin.
|
||||
/// Decorating keeps that empty title bar, so GTK adds the theme's shadow and resize edges and
|
||||
/// nothing else. X11 has no such title bar: decorating there would bring back the WM frame.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn decorate_csd(window: &WebviewWindow) {
|
||||
if crate::linux_window_state::is_wayland() {
|
||||
let _ = window.set_decorations(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the saved IDE zoom before the page loads; applied later by the frontend,
|
||||
/// it would visibly scale up the splash.
|
||||
fn apply_zoom(app: &AppHandle, window: &WebviewWindow) {
|
||||
@@ -800,13 +813,19 @@ pub fn open_settings_window(
|
||||
#[cfg(target_os = "linux")]
|
||||
crate::linux_window_state::prepare(app, &mut config);
|
||||
let builder = WebviewWindowBuilder::from_config(app, &config);
|
||||
// AppKit child windows can disappear when dragged to another display's Space.
|
||||
// The settings label already tracks ownership and parent-close cleanup.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
// Windows: an owned child (WS_POPUP) of a borderless parent gets no DWM
|
||||
// shadow, leaving the frameless settings window flat against its parent.
|
||||
// Ownership is tracked by the `settings-<parent>` label instead
|
||||
// (parent-close cleanup, menu modality), so only Linux keeps the native
|
||||
// parent link. AppKit child windows can disappear when dragged to another
|
||||
// display's Space, so macOS keeps it too.
|
||||
#[cfg(target_os = "linux")]
|
||||
let builder = builder.and_then(|b| b.parent(&parent));
|
||||
let window = builder
|
||||
.and_then(|b| dev_font_preferences(b).build())
|
||||
.map_err(|e| IdeError::internal(format!("cannot create settings window: {e}")))?;
|
||||
#[cfg(target_os = "linux")]
|
||||
decorate_csd(&window);
|
||||
apply_zoom(app, &window);
|
||||
#[cfg(target_os = "macos")]
|
||||
align_titlebar(app, &window);
|
||||
@@ -887,7 +906,12 @@ pub(super) fn place_settings_window(window: &WebviewWindow, parent: &WebviewWind
|
||||
let size = parent.outer_size()?.to_logical::<f64>(scale);
|
||||
let own_scale = window.scale_factor()?;
|
||||
let own = window.outer_size()?.to_logical::<f64>(own_scale);
|
||||
let inner = window.inner_size()?.to_logical::<f64>(own_scale);
|
||||
// On Wayland, the frame is GTK's CSD shadow margin, which tao's inner size includes.
|
||||
#[cfg(target_os = "linux")]
|
||||
let inner = crate::linux_window_state::content_size(&window.as_ref().window())?;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let inner = window.inner_size()?;
|
||||
let inner = inner.to_logical::<f64>(own_scale);
|
||||
let frame = (own.width - inner.width, own.height - inner.height);
|
||||
let bounds = fit_bounds(
|
||||
(pos.x, pos.y, size.width, size.height),
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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. */
|
||||
@@ -1390,6 +1407,8 @@ export type AppInfo = {
|
||||
version: string,
|
||||
platform: string,
|
||||
configDir: IpcPath,
|
||||
/** Linux on a Wayland display: GTK draws the frameless windows' shadow and resize edges. */
|
||||
wayland: boolean,
|
||||
};
|
||||
|
||||
export type AppMetrics = {
|
||||
|
||||
@@ -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" }),
|
||||
];
|
||||
@@ -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",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { language as languageFacet } from "@codemirror/language";
|
||||
import { indentUnit, language as languageFacet } from "@codemirror/language";
|
||||
import { registerSaveParticipant, remoteChange } from "@/editor/api";
|
||||
import { createMemoryBackend, type MemoryBackend } from "../backend";
|
||||
import { _resetLanguages } from "../cm/languages";
|
||||
@@ -56,6 +56,33 @@ describe("DocumentManager + slots", () => {
|
||||
expect(formatOptionsOf(slot.currentState())).toEqual({ tabSize: 1, insertSpaces: false });
|
||||
});
|
||||
|
||||
it("detects the indents again after Reformat Code rewrote them", async () => {
|
||||
const settings = {
|
||||
editor: {
|
||||
codeStyle: {
|
||||
languages: { java: { useTab: true, tabSize: 1, indent: 1 } },
|
||||
detectIndents: true,
|
||||
editorconfig: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
const { manager } = setup({ "/p/A.java": "class A {\n int x;\n}\n" }, settings);
|
||||
const model = await manager.acquire("/p/A.java");
|
||||
const first = new EditorSlot(model, "t1", host);
|
||||
const split = new EditorSlot(model, "t2", host, { from: first });
|
||||
expect(first.currentState().tabSize).toBe(4);
|
||||
// Typing keeps the indents detected when the file was opened.
|
||||
first.dispatchLocal({ changes: { from: 10, to: 14, insert: "\t" }, userEvent: "input.type" });
|
||||
expect(first.currentState().tabSize).toBe(4);
|
||||
first.dispatchLocal({ changes: { from: 10, to: 11, insert: " " }, userEvent: "undo" });
|
||||
first.dispatchLocal({ changes: { from: 10, to: 14, insert: "\t" }, userEvent: "format.reformat" });
|
||||
for (const slot of [first, split]) {
|
||||
expect(slot.currentState().tabSize).toBe(1);
|
||||
expect(slot.currentState().facet(indentUnit)).toBe("\t");
|
||||
}
|
||||
expect(useDocMeta.getState()["/p/A.java"]?.indent).toEqual({ tabSize: 1, insertSpaces: false });
|
||||
});
|
||||
|
||||
it("shares one document between split slots and syncs edits to the backend", async () => {
|
||||
const { backend, manager, frame } = setup({ "/p/a.txt": "hello\n" });
|
||||
const model = await manager.acquire("/p/a.txt");
|
||||
|
||||
@@ -392,7 +392,7 @@ export class DocModel {
|
||||
|
||||
/** Per-file indentation chosen from the status bar; wins over settings until the file is closed. */
|
||||
indentOverride: { tabSize: number; insertSpaces: boolean } | null = null;
|
||||
/** Indentation detected in the file's text at open time. */
|
||||
/** Indentation detected in the file's text at open time and after Reformat Code. */
|
||||
detectedIndent: { insertSpaces: boolean; size?: number } | null = null;
|
||||
/** Last tree-sitter highlighting, for slots opened before the next refresh. */
|
||||
private highlights: { counter: number; value: SyntaxHighlights } | null = null;
|
||||
@@ -418,6 +418,19 @@ export class DocModel {
|
||||
return effectiveIndent(this.settings(), this.info, this.editorconfig, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detects the indents again after Reformat Code rewrote them: tabs written by
|
||||
* the formatter then render at the Code Style tab size and new lines indent
|
||||
* like them, instead of following the indents detected at open time.
|
||||
*/
|
||||
redetectIndent() {
|
||||
const detected = detectIndent(this.sync.localText.sliceString(0, 200_000));
|
||||
const current = this.detectedIndent;
|
||||
if (detected?.insertSpaces === current?.insertSpaces && detected?.size === current?.size) return;
|
||||
this.detectedIndent = detected;
|
||||
this.applySettings();
|
||||
}
|
||||
|
||||
/** Soft wraps toggled for this file (wins over settings until the file is closed). */
|
||||
softWrapOverride: boolean | null = null;
|
||||
|
||||
|
||||
@@ -199,6 +199,7 @@ export class EditorSlot {
|
||||
private onTransactions(trs: readonly Transaction[], view: EditorView) {
|
||||
view.update(trs);
|
||||
let selection = false;
|
||||
let reformatted = false;
|
||||
let navigatedFrom: { line: number; col: number } | undefined;
|
||||
for (const tr of trs) {
|
||||
if (!navigatedFrom && tr.selection && isNavigation(tr)) {
|
||||
@@ -217,8 +218,10 @@ export class EditorSlot {
|
||||
)
|
||||
this.host.onUserEdit(this, tr);
|
||||
}
|
||||
if (tr.docChanged && tr.isUserEvent("format.reformat")) reformatted = true;
|
||||
if (tr.selection || tr.docChanged) selection = true;
|
||||
}
|
||||
if (reformatted) this.model.redetectIndent();
|
||||
if (selection) this.host.onSelection(this, navigatedFrom);
|
||||
}
|
||||
|
||||
@@ -231,6 +234,7 @@ export class EditorSlot {
|
||||
const tr = this.state.update(spec);
|
||||
this.state = tr.state;
|
||||
if (tr.docChanged) this.model.onLocal(tr.changes, this);
|
||||
if (tr.docChanged && tr.isUserEvent("format.reformat")) this.model.redetectIndent();
|
||||
}
|
||||
|
||||
/** Applies changes that are already in the model (other slot / backend). */
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { targetLabel } from "./files";
|
||||
|
||||
describe("targetLabel", () => {
|
||||
const at = (line: string, needle: string) => targetLabel(line, line.indexOf(needle));
|
||||
|
||||
it.each([
|
||||
// Spring configuration consumers start at the string literal, not a name.
|
||||
[' @Value("${app.name}") private String appName;', '"${app', '"${app.name}"'],
|
||||
[" @Value('${app.name}') String appName", "'${app", "'${app.name}'"],
|
||||
[" const key = `app.${env}`;", "`app", "`app.${env}`"],
|
||||
[' String s = "say \\"hi\\"" + x;', '"say', '"say \\"hi\\""'],
|
||||
// Unterminated (multi-line) literals end at the line end.
|
||||
[' String block = "unterminated', '"unterminated', '"unterminated'],
|
||||
// Ordinary declarations keep the identifier.
|
||||
[" private String appName;", "appName", "appName"],
|
||||
[" public int getTimeOut() { return timeOut; }", "getTimeOut", "getTimeOut"],
|
||||
[" int $inner = 1;", "$inner", "$inner"],
|
||||
[" time-out: 30", "time", "time"],
|
||||
])("%s", (line, needle, expected) => {
|
||||
expect(at(line, needle)).toBe(expected);
|
||||
});
|
||||
|
||||
it("shortens long literals", () => {
|
||||
const line = `x("${"a".repeat(100)}")`;
|
||||
const label = targetLabel(line, 2)!;
|
||||
expect(label).toHaveLength(60);
|
||||
expect(label.endsWith("…")).toBe(true);
|
||||
});
|
||||
|
||||
it("has no label for empty literals, numbers or blank positions", () => {
|
||||
expect(targetLabel(' x = "";', 6)).toBeNull();
|
||||
expect(targetLabel(" port: 8080", 8)).toBeNull();
|
||||
expect(targetLabel(" ", 1)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -53,8 +53,28 @@ export async function withDocument<T>(path: string, fn: (doc: number) => Promise
|
||||
}
|
||||
}
|
||||
|
||||
/** Longest literal label before it is shortened with an ellipsis. */
|
||||
const MAX_LITERAL_LABEL = 60;
|
||||
|
||||
/**
|
||||
* Display name of a navigation target starting at `col` of `line`: the string
|
||||
* literal when the target is one (a Spring `@Value("${key}")` consumer, a
|
||||
* configuration key in quotes), else the identifier there; null when neither.
|
||||
*/
|
||||
export function targetLabel(line: string, col: number): string | null {
|
||||
const quote = line[col];
|
||||
if (quote === '"' || quote === "'" || quote === "`") {
|
||||
let end = col + 1;
|
||||
while (end < line.length && line[end] !== quote) end += line[end] === "\\" ? 2 : 1;
|
||||
const literal = line.slice(col, Math.min(end + 1, line.length));
|
||||
if (literal.length > 2)
|
||||
return literal.length > MAX_LITERAL_LABEL ? `${literal.slice(0, MAX_LITERAL_LABEL - 1)}…` : literal;
|
||||
}
|
||||
return identifierAt(line, col);
|
||||
}
|
||||
|
||||
/** The identifier at (or starting right after) `col` of `line`; null when there is none. */
|
||||
export function identifierAt(line: string, col: number): string | null {
|
||||
function identifierAt(line: string, col: number): string | null {
|
||||
const re = /[\p{L}\p{N}_$]+/gu;
|
||||
for (let m = re.exec(line); m; m = re.exec(line)) {
|
||||
const end = m.index + m[0].length;
|
||||
|
||||
@@ -161,7 +161,7 @@ async function format(
|
||||
}
|
||||
view.dispatch({
|
||||
changes,
|
||||
userEvent: "format",
|
||||
userEvent: "format.reformat",
|
||||
annotations: isolateHistory.of("full"),
|
||||
scrollIntoView: false,
|
||||
});
|
||||
@@ -235,7 +235,12 @@ function applyContributedFormat(
|
||||
if (opts.explicit) showHint(view, "No lines changed: content is already properly formatted");
|
||||
return NOTHING;
|
||||
}
|
||||
view.dispatch({ changes, userEvent: "format", annotations: isolateHistory.of("full"), scrollIntoView: false });
|
||||
view.dispatch({
|
||||
changes,
|
||||
userEvent: "format.reformat",
|
||||
annotations: isolateHistory.of("full"),
|
||||
scrollIntoView: false,
|
||||
});
|
||||
return { applied: true, changes: changes.length, lines: formattedLines(state.doc, changes) };
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ import { offsetToPos, rangeToOffsets } from "./positions";
|
||||
import { showHint } from "./hint";
|
||||
import { caretAnchor, focusPopup, openPopup, useLspPopup, type DefinitionTarget, type DocEntry } from "./popupStore";
|
||||
import { selectedLookupDoc, showLookupDocs } from "./completion";
|
||||
import { identifierAt, readFileLines, withDocument } from "./files";
|
||||
import { readFileLines, targetLabel, withDocument } from "./files";
|
||||
import { docWindowVisible, moveDocPopupToWindow, showInDocWindow } from "./docs";
|
||||
import { structure } from "@/editor/structure";
|
||||
import { basename } from "@/platform/project";
|
||||
@@ -326,7 +326,7 @@ async function definitionTarget(loc: Location, fallbackLanguage: string | null):
|
||||
const [lines, declaration] = await Promise.all([readFileLines(loc.path), declarationRange(loc)]);
|
||||
if (!lines) return null;
|
||||
const { first, last } = definitionSpan(loc, lines.length, declaration);
|
||||
const name = identifierAt(lines[loc.range.start.line] ?? "", loc.range.start.col) ?? basename(loc.path);
|
||||
const name = targetLabel(lines[loc.range.start.line] ?? "", loc.range.start.col) ?? basename(loc.path);
|
||||
return {
|
||||
location: loc,
|
||||
name,
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -47,8 +47,9 @@ import {
|
||||
type DeclarationTarget,
|
||||
} from "./syntaxFallback";
|
||||
import { showHint, showPendingHint } from "./hint";
|
||||
import { outsideProjectReason } from "./outsideProject";
|
||||
import { caretAnchor, openPopup, type ListPopupItem } from "./popupStore";
|
||||
import { identifierAt, readManyFileLines } from "./files";
|
||||
import { readManyFileLines, targetLabel } from "./files";
|
||||
import { documentLinks, followReference, knownLinks, linkReference, referenceAt, textReference } from "./links";
|
||||
import { featureBackoff } from "./availability";
|
||||
import { requestHover, showPhpConstructDocumentation } from "./hover";
|
||||
@@ -111,7 +112,7 @@ export async function locationItems(locs: readonly DeclarationTarget[]): Promise
|
||||
run: () => navigateTo(l),
|
||||
};
|
||||
// Server targets: the declared name (speed search matches it), file and line after it.
|
||||
const name = identifierAt(files.get(l.path)?.[l.range.start.line] ?? "", l.range.start.col);
|
||||
const name = targetLabel(files.get(l.path)?.[l.range.start.line] ?? "", l.range.start.col);
|
||||
return {
|
||||
id: `${i}`,
|
||||
label: name ?? basename(l.path),
|
||||
@@ -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.
|
||||
|
||||
@@ -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", []);
|
||||
}
|
||||
});
|
||||
@@ -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 };
|
||||
},
|
||||
};
|
||||
@@ -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,7 +6,7 @@
|
||||
*/
|
||||
import type { Location, OutlineItem, SymbolKind } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { identifierAt } from "@/editor/lsp/files";
|
||||
import { targetLabel } from "@/editor/lsp/files";
|
||||
import { baseName, type SuperMethod } from "./structureNav";
|
||||
|
||||
export type MarkerKind = "implemented" | "overridden" | "implementing" | "overriding";
|
||||
@@ -151,7 +151,7 @@ export function enclosingTypeName(lines: readonly string[] | null | undefined, t
|
||||
/** Display name of a target: the type itself for type markers, the type around it for methods. */
|
||||
export function targetName(lines: readonly string[] | null | undefined, target: Location, method: boolean): string {
|
||||
if (!method) {
|
||||
const name = identifierAt(lines?.[target.range.start.line] ?? "", target.range.start.col);
|
||||
const name = targetLabel(lines?.[target.range.start.line] ?? "", target.range.start.col);
|
||||
if (name) return name;
|
||||
}
|
||||
return enclosingTypeName(lines, target);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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("");
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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"]]);
|
||||
});
|
||||
});
|
||||
@@ -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")],
|
||||
};
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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)}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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) => ({
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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>");
|
||||
});
|
||||
});
|
||||
@@ -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}><null></span> : displayed(val, !!numeric[c])}
|
||||
{val === null ? (
|
||||
<span className={styles.null}><null></span>
|
||||
) : (
|
||||
cellPreview(displayed(val, !!numeric[c]))
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача