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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 3fe3088bc8 fix(tools): offer an IDE copy only for a tool found on PATH
An executable chosen in settings wins over the IDE's own copy, so its
install button stays a plain Install.
2026-11-17 19:13:45 +08:00
l0ng-ai 1d9759dda7 feat(tools): show which language servers are interchangeable and which run together
- Interchangeable servers are one radio group (Automatic / each server / None),
  with the server that will run tagged In use.
- Servers that run alongside them are listed separately, each with its own
  on/off box in the list; the box in the details pane is gone.
- Missing tools in the language's banner jump to their row.
- A server found on PATH offers Install IDE Copy instead of a bare Install.
- Languages are listed by popularity; a search lists name matches first.
2026-11-17 17:04:38 +08:00
l0ng-ai 0fb574e815 fix(spell): accept -ize verbs the dictionary lists only as -ization/-ized (#3951)
parallelize, modularize, virtualize and similar verbs were flagged as typos
while parallelization/parallelized passed. Add the missing base forms (US and
UK spelling) to the extra dictionary.
2026-11-17 16:22:24 +08:00
l0ng-ai 43f9ec99f6 feat(plugins): Marketplace / Installed tabs and a roomier page layout (#3950)
Settings › Plugins gets Marketplace and Installed tabs again, centred in the
page header with the gear menu; the Installed tab shows how many updates are
available. Search (and the category filter on Marketplace) sits at the top of
the list column, and the list and details fill the page under the header.

Rows show a bold name, a 40px icon, and version, vendor (marketplace rows:
downloads first) on the second line; the description moves to the details.
Install / Update and the enable checkbox line up with the name, and an
installed plugin's update is an Update button beside its checkbox.

The details header lists tags, then the name, vendor, and the actions with
the version, without the large icon.

Settings pages can put controls beside their title through
useSettingsHeaderSlot and fill the page edge to edge with `bleed`.

Also adds the missing comma after "Add to Message" in en.json and zh.json,
which kept the text catalog from parsing.
2026-11-17 16:19:26 +08:00
Deng Liu e86e2e8e5c test(agents): fix FakeCopilotServer initializer and restore background-shell test (#3935)
When main (#3908) was merged into #3846 right before landing, the conflict resolution at the end of crates/ide-agent/src/native/copilot/tests.rs left shim_forwards_disabled_mcp_servers_on_create_and_resume without background_shell: false and dropped stop_ends_a_turn_left_running_only_by_background_shells (leaving std::time::Duration unused).

Add background_shell: false to the #3908 initializer and restore stop_ends_a_turn_left_running_only_by_background_shells.
2026-11-17 16:00:59 +08:00
l0ng-ai 811b98dd4b fix(plugins): keep version and Update badge intact in plugin rows (#3946)
Only the vendor name shrinks and ellipsizes in a row's meta line, so a long
author list no longer clips the version or tags. The Update badge moves out
of the meta line to a fixed slot before the checkbox, so it lines up across
installed rows.
2026-11-17 15:59:51 +08:00
l0ng-ai 76377b6eec fix(project-view): keep the tree still when a file is dragged out of it (#3930)
Dragging a file from the Project view to the terminal kept scrolling the tree: WebKit autoscrolls the pressed scroll container toward the pointer once it leaves. During a drag the tree now keeps its position while the pointer is outside it and scrolls itself only within 24 px of its top or bottom edge, as IDEA's tree and our tree reorder drag do. Fixes #3902
2026-11-17 15:10:58 +08:00
l0ng-ai 61ba70394f fix(vcs): don't open an empty blame column for a file Git has no commit of (#3927)
Annotate with Git Blame on an unversioned, ignored, or added-but-not-committed file opened a wide, empty annotation column: the backend blames every line of a file missing from HEAD as not committed. The action is now disabled for files the status lists as untracked, ignored or added, as in IDEA, and a blame without a single committed line leaves the column closed with a notification that the file has no committed history. Fixes #3900
2026-11-17 15:05:41 +08:00
defiaтаdefia bbc5412605 feat(editor): expose Find Usages above Go To (#3918)
The editor context menu shows Find Usages at the top level, immediately above the Go To submenu, as IDEA's editor popup does; the rest of Go To, the action, its shortcut and availability are unchanged.

Co-authored-by: defia <[email protected]>
2026-11-17 14:57:12 +08:00
Deng Liuтаarookieofc 3032bf108f feat(agents): surface session pull requests, issues, references, and artifacts above composer (#3819)
Co-authored-by: arookieofc <[email protected]>
2026-11-17 14:55:43 +08:00
Deng Liu bde17e4f47 fix(macos): keep auxiliary windows at full logical size across mixed-DPI displays (#3631)
* fix(macos): keep auxiliary windows at full logical size across mixed-DPI displays

* fix(macos): don't wait forever for the main thread to fit an auxiliary window
2026-11-17 14:55:28 +08:00
l0ng-ai af55109b27 fix(kotlin): open jdtls' class when the Kotlin server names its jar by another path (#3922)
Going to a library class from Kotlin swaps the Kotlin server's signature stub for jdtls' decompiled class, matched by package, name and the jar's path. When the servers know the jar by different paths (a system-scope jar, as reported), nothing matched and the stub stayed. The redirect now takes jdtls' only class of that name and logs why when it still finds none; java_class_file keeps the exact-archive match for debugger line mapping. Refs #3447
2026-11-17 14:55:12 +08:00
Deng Liuтаarookieofc 3663556a2e fix(agents): make Send now and Stop work while Copilot background shells run (#3846)
A Copilot turn only ended on `session.idle`, which Copilot defers until
every attached background shell (e.g. `gh pr checks --watch`) exits. The
main loop had long gone idle, so the turn showed "Writing…" for hours,
messages queued behind it, and Send now on a queued message only
cancelled a turn that `session.abort` could not end.

- Send now on a queued message steers it into the running turn when the
  agent supports steering, and falls back to interrupting the turn.
- The Copilot shim tracks whether its main loop is busy: Stop on a turn
  kept open only by background work ends it at once and leaves that work
  running, and steering then starts a new run instead of joining one.
- The Copilot shim reports background shells and agents
  (`session.tasks.list`) and stops them (`session.tasks.cancel`), so they
  show as background tasks that can be stopped one by one.

Co-authored-by: arookieofc <[email protected]>
2026-11-17 14:53:10 +08:00
l0ng-ai 217bd29860 fix(editor): colour Kotlin soft keywords only where they act as keywords (#3921)
The Kotlin stream mode coloured every soft keyword as a keyword, so a package segment (import top.ttb.data.Model), a member (result.data) or a name (val data = ...) looked like one. A word after . or ?. is now always a name, and a soft keyword is a keyword only before a declaration or another modifier (data class, open fun, by lazy) or, for catch / finally / init / constructor / get / set, before ( or {. Refs #3447
2026-11-17 14:50:25 +08:00
l0ng-ai 25d6e8ac7c fix(remote): browse the remote host when a setting asks for a path (#3920)
In a remote window, choosePath (Project Structure libraries, SDK homes, interpreters and the other settings that pick a file or folder) opened the desktop's own dialog, so it listed this machine's files while the path is used on the remote host. It now opens an in-app chooser that lists the host's folders through fs_read_dir: click selects, double click or Enter opens a folder or chooses the file, the arrow goes to the parent folder, and the path can be typed. Local windows keep the desktop dialog. Refs #3447
2026-11-17 14:48:50 +08:00
misswellтаmisswell 280760a5d4 fix(agents): keep the Agent sessions task list scrollable (#3909)
The imported-sessions section of the Agent sessions popup was flex: none, so many imported sessions (17 took 385 of 420 px) left the task list 0 px tall and the wheel had nothing to scroll. The section now shrinks within a 40% cap and scrolls on its own; the task list keeps its own scroll area.

Co-authored-by: misswell <[email protected]>
2026-11-17 14:26:57 +08:00
Deng Liuтаdengliu b3008be32b fix(agents): disable CLI-configured MCP servers when turned off in Copilot and Codex (#3908)
A server turned off in OpenIDEA (globally, per project, by agent filter, or in the session MCP picker) was only left out of mcpServers; Copilot and Codex still loaded it from their own configuration (~/.copilot/mcp-config.json, ~/.codex/config.toml). The session's _meta.openidea.mcpServersOff now reaches Copilot as disabledMcpServers on session.create/resume (--disable-mcp-server on the --acp fallback) and Codex as mcp_servers.<name>.enabled = false for names its own config defines. servers_off also counts agent-filtered and unapproved workspace entries. Changing Global, Project or built-in IDE MCP settings recycles idle resumable sessions (or reloads after the running turn), and the session picker gets per-session toggles for Agent Config entries.

Co-authored-by: dengliu <[email protected]>
2026-11-17 14:15:40 +08:00
LU XIANGRUIтаwildcatDownstairs 577193d387 feat(plugins): the editor's tab size in editor panels (#3906)
openidea.editor.get() includes tabSize, the editor state's tab size (Code Style, .editorconfig, indent detection or the status bar's indent picker), and onTarget fires again with the new get() value when it changes for the same file, at most once a frame. Documented under API 1.10; the minimap fixture expands tabs to that size.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 13:31:19 +08:00
LU XIANGRUIтаwildcatDownstairs 449db6baa7 feat(plugins): the change-marker lane's VCS changes in editor panels (#3905)
An editor panel's page can read the added, modified and deleted lines the change-marker lane shows with openidea.editor.changes() ([{ line, lastLine, kind }] in file order, [] outside version control) and hear them through onChanges, at most once a frame. The values are the lane's own hunks: hunkField provides a new lineChanges facet in src/editor/api.ts, so the panel reads them without importing the VCS feature. Frames get the lane's colours as --openidea-change-added / -modified / -deleted. Documented under API 1.10; the minimap fixture marks changes at its left edge.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 13:30:29 +08:00
LU XIANGRUIтаwildcatDownstairs ea1f1e54d0 feat(plugins): the caret and selections in editor panels (#3904)
An editor panel's page can read the caret and every selection of its group's editor with openidea.editor.selections() (main selection first, then the others in file order; 0-based lines, UTF-16 columns) and hear them through onSelections, at most once a frame, also after an edit or a file switch. Documented under API 1.10; the editor-panel minimap fixture tints the selected lines and the caret's line.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 13:29:00 +08:00
l0ng-ai 4201aad9f9 feat(vcs): join each merge change to the result with a curved band (#3903)
The merge editor's panes sat edge to edge, so it was hard to see where a side's change lands in the result. A divider between each side and the result now draws a curved band per open change of that side (conflicts in the conflict colour), as IDEA's merge viewer does; a side's band goes once that side is accepted or ignored.

Closes #3876
2026-11-17 13:13:27 +08:00
l0ng-ai 678407f4c0 fix(clipboard): mark copied files as a copy for Windows paste targets (#3901)
Explorer writes "Preferred DropEffect" (DROPEFFECT_COPY) with every file list it copies, and paste targets that transfer files between machines, such as Remote Desktop's clipboard redirection, read it. Files copied in the Project view now carry it too.

Refs #3863
2026-11-17 13:06:31 +08:00
l0ng-ai 7392bd2547 fix(java): remove jdtls workspaces unused for 30 days (#3899)
A jdtls workspace is keyed by the project folder and the settings that need a clean import, so each change of those and each moved or deleted project left 50-200 MB behind for good. jdtls now marks its workspace when it starts, and start-up moves workspaces untouched for 30 days aside and deletes them in the background.

Refs #3869
2026-11-17 13:04:08 +08:00
Daniil Poliakovтаdan548 b1f73e3920 fix(editor): bound rainbow bracket scanning on minified lines (#3884)
Rainbow bracket scanning rescanned a whole minified line after every keystroke (the viewport always holds all of it), so typing lagged in minified files. Lines of at least 10,000 UTF-16 units, the indent-guide threshold, are now skipped by both the parsed and lexical scanners and excluded from nesting, and checkpoints are invalidated from the changed line's start so colours come back when the line shrinks below the limit.

Closes #3883

Co-authored-by: dan548 <[email protected]>
2026-11-17 12:39:54 +08:00
LU XIANGRUIтаwildcatDownstairs e8b12dfb51 fix(color-scheme): show the red-green colours on the Color Scheme page (#3878)
With Adjust colors for red-green vision deficiency on, the editor used the bundled schemes' red-green variants (#3510) but Editor › Color Scheme still showed the plain colours, because schemeTokens() read tokens.css without its [data-red-green] rules. Built-in schemes now resolve with the red-green variant when the setting is on (preview, attribute values, an explicitly chosen bundled scheme), and the page says so with a link to Appearance. Custom schemes and exported .icls files are unchanged.

Closes #3851

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:39:50 +08:00
l0ng-ai fd828c0ade test(plugins): keep the editor panel's problem levels out of the text catalog (#3896)
The severity map's `hint: "weakWarning"` entry read as UI text to the
text-catalog check (`hint` is a text property), failing it on main since #3885.
A function maps the levels instead.
2026-11-17 12:33:53 +08:00
LU XIANGRUIтаwildcatDownstairs ebc879dc8b feat(plugins): folded ranges and wrapped rows for editor panels (#3890)
An editor panel's page could not tell which lines are folded or how many rows a soft-wrapped line takes, so a minimap drew folded code and drifted from the editor. openidea.editor now has folded() ([{ fromLine, toLine }], nested folds merged), wrapped(fromLine, toLine) (visual rows per line, 0 for folded-away lines, null without soft wrap, at most 2000 lines) and onLayout(fn) with { folded, softWrap }, at most once a frame. Folds come from foldedRanges and rows from the editor's own line blocks.

Closes #3867

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:32:03 +08:00
LU XIANGRUIтаwildcatDownstairs 7096a1c374 feat(plugins): include semantic highlighting in editor panels' highlights() (#3887)
openidea.editor.highlights() returned only the Lezer syntax colours, so a minimap drew semantic tokens (cm-sem-* marks, rainbow identifiers) in the wrong colour. It now layers the editor's semantic marks over the syntax spans the way the editor does, and onHighlights reports the lines whose semantic marks changed (RangeSet.compare on the semantic field, so mapped marks report nothing extra). The page API is unchanged.

Closes #3866

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:31:42 +08:00
LU XIANGRUIтаwildcatDownstairs a1d4d6fb7f feat(plugins): the marker bar's problems in editor panels (#3885)
An editor panel's page can now read the problems the marker bar shows: openidea.editor.problems() returns [{ line, lastLine, severity }] (0-based lines; error, warning or weakWarning) and onProblems(fn) reports changes at most once a frame. The data is the marker bar's own diagnostics marks field, exported as markerBarProblems(state), so positions follow edits the same way. Covered by editor.read; the minimap fixture draws them.

Closes #3865

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:31:20 +08:00
Muuтаmuutot 7596e95b76 fix(spell): raw strings keep the letter after a backslash (#3886)
Typo checking treated every backslash in a string literal as an escape and skipped the letter after it, so r"\user" was checked as "ser" and flagged. The syntax layer now marks raw / verbatim strings (Python r/R prefixes with b/f/u combinations, Rust and C++ raw strings, C# verbatim strings, Go backtick strings), and the spelling layer checks them without escape handling.

Co-authored-by: muutot <[email protected]>
2026-11-17 12:30:01 +08:00
Gabriel Gondim cc471029d2 fix(xml): map Doctrine ORM XSD through a LemMinX catalog (#3881)
Doctrine ORM XML mappings that follow Doctrine's docs and point xsi:schemaLocation at https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd failed validation (TargetNamespace.1, cvc-elt.1.a): the hosted XSD declares the schema URL as its targetNamespace after an http→https rewrite. The upstream schema (MIT) is bundled and an OASIS catalog, written to a private per-process directory, is prepended to LemMinX's xml.catalogs so the namespace and both system IDs resolve to it.

Closes #3843

Co-authored-by: GGVidal <[email protected]>
2026-11-17 12:28:31 +08:00
LU XIANGRUIтаwildcatDownstairs ee8afe39a2 fix(build): make the injected WAR and resource init scripts work with the configuration cache (#3877)
With org.gradle.configuration-cache=true, Tomcat WAR deployment and Spring Boot resource update failed: the doLast actions of war.init.gradle and resources.init.gradle referred to the Project and other tasks, which the configuration cache cannot serialize. The values they need (the war archive provider or file, processResources' destination, the manifest file) are now resolved at configuration time. The other injected scripts only configure tasks and have no task actions.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:27:36 +08:00
LU XIANGRUIтаwildcatDownstairs 5f606219b2 fix(run): make the injected Gradle init scripts work on Gradle 4.6–6.3 (#3875)
Run/Debug, tests, bootRun debug, VM options, coverage, resource update and WAR deployment failed on Gradle before 6.4 because the injected init scripts used newer API without a version check: JavaExec.mainClass (6.4+), tasks.register/named/configureEach (4.9+), debugOptions (5.6+), Report.required (6.1+), archiveFile (5.1+), and sourceSets as an extension (4.10+). Each use now falls back to the older API, with Gradle 4.6 as the oldest supported version; newer Gradle keeps the lazy API.

Closes #3864

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-17 12:27:07 +08:00
l0ng-ai 0590a255e8 chore: v0.1.47 2026-11-17 10:51:26 +08:00
l0ng-ai 32d5232010 fix(vcs): the navigation path of a file at a Git revision shows the revision and its folders
The status bar path of a file opened with Show File at Revision showed the hex-encoded location and lost the file's folders. It now shows the short revision, the folders of the file in the working tree and the file name (`617f744a › web › src › app.ts`).
2026-11-17 10:50:33 +08:00
l0ng-ai 382f5d71fa fix(debugger): stream trace from an else-if line, of a stream made parallel earlier, and its cleanup
- At a stop on an `} else if` line, the earlier conditions have already run: their calls no longer count as exits to skip before the chain's root. The trace used to wait for a second `stream()` that never came. Conditions on the same line still count.
- A stream that was parallel before the traced statement (`Stream<T> s = list.parallelStream(); … s.map(…)`) is checked with `isParallel()` when the trace arms and made sequential like a chain with `parallel()`, so its records link correctly; the result says it ran sequentially.
- `arm` carries a token. When its reply times out, the client releases the trace armed with that token, so a slow arm no longer leaves breakpoints off and the next trace busy.
- A finished trace's records keep their objects from being collected until the stop they were read in ends: they are released on the next resume, step or `continued` event instead of the next trace.

The bundle is rebuilt; `tests/stream.py` (JDT LS 1.63.0, JDK 25) passes, with new cases for the three bundle changes.
2026-11-17 10:05:41 +08:00
l0ng-ai 0cd7d9c30e fix(agents): the generated commit message describes exactly what would be committed
The diff sent to the agent was every included file's whole working-tree change. With the staging area, or blocks left out of a partial commit, it also held changes the commit leaves out. It is now made the way Commit makes the commit (the index with the selection applied, partial files' chosen blocks only), through the new `vcs_pending_patch` command.

Before filling in the message, the changes are read again: a file edited and saved while the agent worked, which changes neither the message nor the inclusion, no longer gets a message written for its earlier content.
2026-11-17 09:57:58 +08:00
l0ng-ai dfbe87161b fix(vcs): a file opened at a Git revision shows the revision, not its encoded location
Show File at Revision opens `git-revision:<hex of the target>/<name>`. The tab's directory hint and the status bar path showed the hex string, and the banner called the file a library source. The tab hint is now the short revision, the path shows the revision and the file's folders (`c74989a1 › web › src`), and the banner says it is a file at a Git revision.
2026-11-17 09:53:04 +08:00
l0ng-ai 7a351fe4b0 fix(plugins): name the Failed and Needs permission status dots (#3872)
The status dot of a failed plugin, or one waiting for consent, was announced as "[object Object]": the dot's label is its text, and it was given an element. It is given the translated text now.
2026-11-17 09:51:27 +08:00
l0ng-ai 153a184eac fix(python): an interpreter chosen but not applied yet is not reported missing (#3871)
The interpreter page compared the chosen interpreter with the one the backend resolves, which follows the applied setting. A virtualenv just created (or any other choice before Apply) showed "The configured Python interpreter no longer exists" until the page was opened again. Only the applied interpreter is judged now, and the check runs again once a choice is applied.
2026-11-17 09:51:21 +08:00
l0ng-ai 868f5b18d0 fix(editor): Back reopens a diff closed without leaving it first (#3870)
A diff was recorded as a place only when a file was opened from it. Opening a diff and closing it straight away left the history at the file before it, so Back opened that file instead of the diff. Closing the active diff now records it as the place left.
2026-11-17 09:51:16 +08:00
l0ng-ai 8d87b0de6e fix(java): allow a slow first java -version before excluding a JDK (#3868)
A JDK whose java -version took longer than 5 seconds was treated as unable to run and left out of the jdtls runtimes until the server restarted. The first run of an x86_64 JDK 8 under Rosetta, or of a freshly downloaded JDK being scanned, can take that long, so a Java 8 project compiled against a newer JDK and jdk.nashorn stopped resolving. The probe now waits up to 30 seconds; a java that never answers is still rejected.

Fixes #3684
2026-11-17 09:45:28 +08:00
l0ng-ai c791f2c34c fix(mcp): check scope before touching the file system, and apply it to every symbol result (#3853)
- `scope` is checked to be on a local drive or the project's share before it is resolved: on Windows, resolving `\\host\share` would sign in to that host before the tool refused it as outside the project.
- `search_symbol` with a `scope` filters in the index: the fixed candidate pool was cut before the filter, so matches in the scope ranked past it were dropped without a "more" marker.
- Language server results in attached projects or content roots obey `scope` and `paths` like project files instead of passing as library symbols.
2026-11-17 09:34:11 +08:00
l0ng-ai a52e416ad5 fix(run): a run closed or restarted while starting does not leave its process behind (#3862)
Closing a Java run tab while the plugin list for remote Java agents was loading still started the process, and nothing owned it afterwards. The start is now abandoned when the session was stopped, closed or started again meanwhile, and a process that started anyway is stopped.
2026-11-17 09:34:04 +08:00
l0ng-ai a7464bf631 fix(plugins): translate the Java Agents section title (#3861)
The section listing a plugin's Java agents had no catalog entry and stayed English in the Chinese UI.
2026-11-17 09:33:59 +08:00
l0ng-ai 26810fbcbd fix(welcome): a recent WSL project stored with forward slashes is not shown as missing (#3860)
Recent projects are stored as `//wsl.localhost/Ubuntu/...`; the exemption for WSL shares (a stopped distribution only hides them) recognised the backslash form only.
2026-11-17 09:33:54 +08:00
l0ng-ai 72b17683c9 fix(terminal): open terminals pick up a Nerd Font found in the font catalog (#3859)
Open terminals re-apply their font stack when the native font catalog loads, but the Nerd Fonts outside the known list were picked from it only afterwards, so the terminal kept showing boxes for prompt icons. The catalog now records them before notifying.
2026-11-17 09:33:49 +08:00
l0ng-ai e916af15d4 fix(analysis): Reformat / Code Cleanup on several files saves each file as cleaned (#3858)
The batch saved with Save All after each file. That ran save actions (format on save reformatted the whole file after "only VCS changed text") and saved unrelated unsaved files. Each file is now saved as it is, without save actions, and other files are left alone.
2026-11-17 09:33:43 +08:00
l0ng-ai 88eeb57000 fix(remote): stop reconnecting on its own once a file is edited while waiting (#3857)
Automatic reconnection checked for unsaved edits only when the connection was lost. Edits made during the back-off were dropped when the window reopened the project. Each attempt now checks again and leaves the reconnect to the user (who is asked first) once anything is unsaved.
2026-11-17 09:33:38 +08:00
l0ng-ai ba5c56ade8 fix(agents): switching a saved task to a model of a legacy ACP agent no longer fails (#3856)
An agent that lists models through the legacy `models` field and reports no settings after `session/set_model` made the discovery wait five seconds and fail, and the model choice was reverted. Such a model now has no per-model settings instead. Agents with `configOptions` still report a missing answer as before.
2026-11-17 09:33:33 +08:00
l0ng-ai 88a5602239 fix(agents): generate the commit message in a read-only mode when the agent has one (#3855)
The commit message task picked `default` / `ask` before `read-only`, and Codex runs `ask` with workspace write access. The diff it reads is repository text, so the task now prefers a read-only mode and only falls back to one that asks before writing.
2026-11-17 09:33:28 +08:00
l0ng-ai 907ed1d85f fix(completion): repeat an item at other carets only where it fits, and sync it to the document (#3854)
- A server-inserted item (kotlin-lsp) repeated at the other carets was folded into the server's own transaction, which is never sent back to the document model: the copies vanished after saving and reopening. They now go in as a separate local edit.
- That repetition only goes to carets after the same typed text; a zero-length server edit used to land at every other empty caret.
- Automatic parentheses are decided per caret: `b.cr|()` no longer becomes `b.create()()` when the main caret is at `a.cr|`.
2026-11-17 09:33:10 +08:00
l0ng-ai 7f229acbd9 fix(database): keep dump / restore connections on the chosen database (#3852)
A database named like connection parameters (`host=… dbname=…` or a `postgresql://` URI) went to `--dbname` as is, which pg_dump / pg_restore / psql read as a connection string: it could point the tool, and the data source's password, at another host. Such a name now goes in quoted as the string's `dbname`.

psql restores now run with `--no-psqlrc`, so a `\connect` or setting in `~/.psqlrc` cannot redirect a restore to another database.

Quoted names in the schema and table fields (`public."Order Items"`, as the dialog fills them in for a table node) are no longer split at their spaces or commas.
2026-11-17 09:32:55 +08:00
l0ng-ai 41bae970e0 docs(plugins): regenerate the theme token reference (#3849)
Two editor colour scheme tokens landed without regenerating plugins/themes.md, so the is-current check failed on every branch.
2026-11-17 08:46:13 +08:00
Deng Liuтаdengliu 44b5515432 fix(markdown): honor container align attributes on Mermaid diagrams (#3847)
A Mermaid diagram inside <div align="left"> (or right / center, or <center>) stayed centered in the Markdown preview and agent chat: DOMPurify drops inline style, and .mermaid-output's text-align: center plus the SVG's margin: 0 auto overrode the kept align attribute. Aligned containers now set inherited --mermaid-align / margin properties that the diagram output uses; unaligned diagrams stay centered.

Co-authored-by: dengliu <[email protected]>
2026-11-17 08:09:14 +08:00
l0ng-ai 64d5618cc7 feat(welcome): show recent projects whose folder no longer exists as unavailable (#3845)
When the recent list is read, a local project whose folder is gone is marked
`missing` and loses its stale branch (a deleted repository or a removed git
worktree kept the branch it had). Remote locations (ssh://, wsl://,
devcontainer://) and WSL shares are not checked. The welcome screen, the
project switcher and the recent-projects popup show such an entry with a dimmed
name and badge and a "<path> (unavailable)" tooltip; opening one still offers
to remove it from the list.
2026-11-17 07:56:32 +08:00
l0ng-ai 1a21efa4aa feat(plugins): a plugin command can answer Escape in the editor (API 1.10) (#3844)
`[[contributes.keymaps]]` accepts `key = "Escape"` with a required `when`.
Plain keys stayed out of plugin shortcuts, and Escape could not be added as a
shortcut anyway: the IDE's own keymap uses it, so the binding would be dropped.
It becomes the editor's lowest-precedence Escape handler instead: the command
runs once popups, completion, rename, selection, extra carets and Vim had no
use for the key, and only while its `when` holds (the latest plugin's binding
first). `when` is accepted only on such a binding; manifests that set it
elsewhere, or bind Escape on one platform only, are refused.
2026-11-17 07:15:11 +08:00
l0ng-ai 72cf2f488e test: fix the Windows ui_points and debugger stop tests, and a tight plugin budget (#3842)
- ui_points: a Windows checkout has CRLF line ends, so removing
  "width = 110\n" from the fixture did nothing and the missing-width case
  passed. The fixture text is normalized to LF first.
- ide-dap: the fake adapter stops at a breakpoint after launch, and since
  Stop kills a suspended program's tree at once (#3658), the Windows stop
  test no longer saw the wait it checks. The adapter now continues right
  after that stop, so Stop meets a running program.
- plugin_data_tools: database_calls_enforce_grants… ran its plugin commands
  under a 250 ms budget it does not test; a slow runner's first call timed
  out. It gets 10 s.
2026-11-17 06:23:51 +08:00
235 змінених файлів з 9227 додано та 1146 видалено

No files matched your search

Створено
+45 -45
Переглянути файл
@@ -4144,7 +4144,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -4169,7 +4169,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4183,7 +4183,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"serde",
@@ -4194,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"chardetng",
@@ -4212,7 +4212,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4226,7 +4226,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4237,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dunce",
"encoding_rs",
@@ -4254,7 +4254,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-run",
@@ -4268,7 +4268,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4297,7 +4297,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4333,7 +4333,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"serde",
@@ -4346,7 +4346,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4367,7 +4367,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4379,7 +4379,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4392,7 +4392,7 @@ dependencies = [
[[package]]
name = "ide-heap"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"criterion",
"ide-core",
@@ -4410,7 +4410,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4483,7 +4483,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4502,7 +4502,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"criterion",
@@ -4524,7 +4524,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4536,7 +4536,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"encoding_rs",
"futures",
@@ -4553,7 +4553,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"libc",
"tempfile",
@@ -4562,7 +4562,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"futures",
"serde",
@@ -4573,7 +4573,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"criterion",
@@ -4631,7 +4631,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dunce",
"encoding_rs",
@@ -4659,7 +4659,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"bytes",
"dunce",
@@ -4678,7 +4678,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"futures",
"ide-core",
@@ -4701,7 +4701,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -4724,7 +4724,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4738,7 +4738,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dunce",
"futures",
@@ -4758,7 +4758,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dunce",
"encoding_rs",
@@ -4782,7 +4782,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-tools",
@@ -4798,7 +4798,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dunce",
"flate2",
@@ -4821,7 +4821,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"criterion",
"encoding_rs",
@@ -4842,7 +4842,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"parking_lot",
@@ -4855,7 +4855,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4880,7 +4880,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-language",
@@ -4893,7 +4893,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"ide-language",
@@ -4908,7 +4908,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"ide-core",
"libc",
@@ -4921,7 +4921,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"criterion",
"ide-core",
@@ -4934,7 +4934,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"flate2",
"hex",
@@ -4955,7 +4955,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -4976,7 +4976,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"chardetng",
"dunce",
@@ -5002,7 +5002,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5018,7 +5018,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"blake3",
"dunce",
@@ -6647,7 +6647,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.46"
version = "0.1.47"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.46"
version = "0.1.47"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
+11 -6
Переглянути файл
@@ -72,9 +72,8 @@ async fn run_once(
config::add_client_options(&launch.id, &mut options);
let model_option = options.iter().find(|o| o.category.as_deref() == Some("model"));
let mut levels = BTreeMap::new();
if new.get("configOptions").is_some_and(Value::is_array)
&& let Some(model) = model_option.and_then(|o| o.current.as_ref())
{
let has_config = new.get("configOptions").is_some_and(Value::is_array);
if has_config && let Some(model) = model_option.and_then(|o| o.current.as_ref()) {
levels.insert(model.clone(), levels_for_model_from_slice(&options));
}
if let Some(selected) = selected_model
@@ -88,7 +87,7 @@ async fn run_once(
updates.config.lock().session = Some(session.to_owned());
let response: Value = conn.request(method, params, None).await.map_err(discovery_error)?;
let settings = if let Some(settings) = selected_settings(&response, selected) {
settings
Some(settings)
} else {
tokio::time::timeout(CONFIG_UPDATE_TIMEOUT, async {
loop {
@@ -106,9 +105,15 @@ async fn run_once(
}
})
.await
.map_err(|_| "The agent did not report settings for the selected model".to_owned())?
.ok()
};
match settings {
Some(settings) => levels.insert(selected.to_owned(), levels_for_model_from_slice(&settings)),
// An agent on the legacy `models` field that says nothing more: the model has
// no settings of its own, and switching to it must not fail.
None if !has_config => levels.insert(selected.to_owned(), Vec::new()),
None => return Err("The agent did not report settings for the selected model".to_owned()),
};
levels.insert(selected.to_owned(), levels_for_model_from_slice(&settings));
}
let commands = updates
.commands
+27
Переглянути файл
@@ -774,6 +774,33 @@ async fn selected_model_uses_legacy_set_model_and_authoritative_notifications()
assert!(!catalog.thought_levels.contains_key("default"), "legacy model lists alone do not assert no controls");
}
#[tokio::test]
async fn selected_legacy_model_without_settings_has_no_levels_instead_of_failing() {
let tmp = tempfile::tempdir().unwrap();
configure(tmp.path(), "one");
let mut harness = Harness::new();
let manager = make_manager(tmp.path(), Arc::default(), &harness);
let mut events = events(&manager);
manager.refresh_models(PROVIDER, false, Some("second")).unwrap();
harness
.next()
.await
.reply
.send(Ok(json!({
"sessionId": "discovery-only",
"models": { "currentModelId": "default", "availableModels": [
{ "modelId": "default", "name": "Default" }, { "modelId": "second", "name": "Second" }
] }
})))
.unwrap();
let selected = harness.next().await;
assert_eq!(selected.method, "session/set_model");
selected.reply.send(Ok(json!({}))).unwrap();
let catalog = completed(&mut events).await;
assert!(catalog.error.is_none(), "{:?}", catalog.error);
assert_eq!(catalog.thought_levels.get("second"), Some(&Vec::new()));
}
#[tokio::test]
async fn catalog_replacement_removes_selected_metadata_for_models_no_longer_listed() {
let tmp = tempfile::tempdir().unwrap();
+77 -16
Переглянути файл
@@ -222,13 +222,26 @@ impl Shared {
if builtin_off { Vec::new() } else { mcp_servers_for(init.mcp_stdio(), &self.paths.project_root) };
let configured = self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
servers.extend(mcp::acp_mcp_servers(&configured, provider, init, overrides));
let mut off = mcp::servers_off(&configured, overrides);
if builtin_off {
off.push(BUILTIN_SERVER.to_owned());
}
let off = Self::mcp_off(&configured, provider, overrides);
McpForSession { servers, off }
}
fn mcp_servers_off_for_session(&self, provider: &str, overrides: &BTreeMap<String, bool>) -> Vec<String> {
let configured = self.mcp_servers_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
Self::mcp_off(&configured, provider, overrides)
}
fn mcp_off(configured: &[McpServer], provider: &str, overrides: &BTreeMap<String, bool>) -> Vec<String> {
let mut off = mcp::servers_off(configured, provider, overrides);
if overrides.get(mcp::BUILTIN_MCP_NAME) == Some(&false) {
off.push(BUILTIN_SERVER.to_owned());
off.push(mcp::BUILTIN_MCP_NAME.to_owned());
off.sort();
off.dedup();
}
off
}
fn known_config(&self, provider: &str) -> Vec<AgentConfigOption> {
let config = self.paths.catalogs.cached(self, provider).config;
self.config_for_new_task(config, provider)
@@ -922,29 +935,50 @@ impl AgentManager {
Ok(item)
}
/// Sends queued message `queued` next, cancelling the current turn if there is one.
pub fn send_queued_now(&self, id: &str, queued: &str) -> IdeResult<()> {
/// Sends queued message `queued` now: into the running turn when the agent takes
/// messages mid-turn, else next, cancelling the current turn if there is one.
pub async fn send_queued_now(&self, id: &str, queued: &str) -> IdeResult<()> {
let task = self.task(id)?;
let idle = {
let (item, busy) = {
let mut s = task.state.lock();
let i =
s.task.queue.iter().position(|q| q.id == queued).ok_or_else(|| IdeError::not_found("already sent"))?;
let item = s.task.queue.remove(i);
if s.busy {
s.task.queue.insert(0, item);
None
} else {
let busy = s.busy;
if !busy {
s.busy = true;
Some(item)
}
(item, busy)
};
task.persist();
task.emit_task();
match idle {
Some(item) => {
self.shared.runtime.spawn(async move { task.run(item.prompt).await });
if !busy {
self.shared.runtime.spawn(async move { task.run(item.prompt).await });
return Ok(());
}
// Out of the queue while it is steered, so the turn ending meanwhile doesn't send it twice.
let prompt = match task.steer(item.prompt).await {
Ok(()) => return Ok(()),
Err(prompt) => prompt,
};
let start = {
let mut s = task.state.lock();
if s.busy {
s.task.queue.insert(0, AgentQueued { id: item.id, prompt });
None
} else {
// The turn ended while steering was tried: nothing is left to interrupt.
s.busy = true;
Some(prompt)
}
};
match start {
Some(prompt) => {
self.shared.runtime.spawn(async move { task.run(prompt).await });
}
None => {
task.persist();
task.emit_task();
task.send_now.store(true, Ordering::Release);
task.cancel();
}
@@ -1618,6 +1652,26 @@ impl AgentManager {
Ok(out)
}
/// Recycles idle resumable live sessions (or schedules reload after the running turn) when
/// global, workspace, or built-in IDE MCP server settings change.
pub fn notify_mcp_servers_changed(&self) {
let tasks: Vec<Arc<Task>> = self.tasks.read().values().cloned().collect();
for task in tasks {
let (archived, busy, has_bg) = {
let s = task.state.lock();
(s.task.status == AgentStatus::Archived, s.busy, !s.background_tasks.is_empty())
};
if archived {
continue;
}
if busy || has_bg || !task.permissions.lock().is_empty() {
task.mcp_reload_pending.store(true, Ordering::Release);
} else {
task.recycle_resumable_session();
}
}
}
/// Stops every agent (project closed).
pub fn shutdown(&self) {
for task in self.tasks.read().values() {
@@ -2218,9 +2272,16 @@ impl Task {
saved: Option<String>,
) -> Result<Live, SessionOpenError> {
let launch_cwd = cwd.to_path_buf();
let spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd))
let mut spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd))
.await
.map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?;
if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) {
let mcp_overrides = self.state.lock().task.mcp_overrides.clone();
for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) {
spec.args.push("--disable-mcp-server".into());
spec.args.push(name);
}
}
self.stderr.lock().clear();
self.config_sent.lock().clear();
let weak = Arc::downgrade(self);
+67 -20
Переглянути файл
@@ -10,7 +10,7 @@ use crate::{
};
use ide_core::IpcPath;
use serde_json::{Value, json};
use std::collections::{BTreeMap, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
@@ -89,24 +89,61 @@ fn matches_agent(agents: &[String], provider: &str) -> bool {
/// The configured servers off for this session: off by default and not switched on for it, or
/// switched off for it. Named so an agent that also loads its own configuration can keep a
/// same-named server of it off too. Workspace entries take precedence, as in [`acp_mcp_servers`].
pub(crate) fn servers_off(all: &[McpServer], overrides: &BTreeMap<String, bool>) -> Vec<String> {
let mut seen = HashSet::new();
let ordered =
all.iter().filter(|s| s.scope == McpScope::Workspace).chain(all.iter().filter(|s| s.scope == McpScope::User));
let configured: Vec<String> = ordered
.filter(|s| seen.insert(s.name.as_str()))
.filter(|s| !overrides.get(&s.name).copied().unwrap_or(s.enabled))
.map(|s| s.name.clone())
.collect();
// A server switched off that the IDE doesn't configure may still be the agent's own.
let switched = overrides
pub(crate) fn servers_off(all: &[McpServer], provider: &str, overrides: &BTreeMap<String, bool>) -> Vec<String> {
let mut seen_configured = HashSet::new();
let mut enabled_names = HashSet::new();
let mut off = BTreeSet::new();
let ordered = all
.iter()
.filter(|(name, on)| !**on && name.as_str() != BUILTIN_MCP_NAME && !seen.contains(name.as_str()))
.map(|(name, _)| name.clone());
let mut off: Vec<String> = configured.into_iter().chain(switched).collect();
off.sort();
off.dedup();
off
.filter(|s| s.scope == McpScope::Workspace && !s.unapproved)
.chain(all.iter().filter(|s| s.scope == McpScope::User));
for srv in ordered {
if !seen_configured.insert(srv.name.as_str()) {
continue;
}
let explicit = overrides.get(&srv.name).copied();
let matches = explicit == Some(true) || matches_agent(&srv.agents, provider);
let active = explicit.unwrap_or(srv.enabled) && matches;
if active {
enabled_names.insert(srv.name.as_str());
} else {
off.insert(srv.name.clone());
}
}
for srv in all.iter().filter(|s| s.scope == McpScope::Workspace && s.unapproved) {
if !enabled_names.contains(srv.name.as_str()) {
off.insert(srv.name.clone());
}
}
// A server switched off that the IDE doesn't configure may still be the agent's own.
for (name, &on) in overrides {
if !on && name.as_str() != BUILTIN_MCP_NAME && !enabled_names.contains(name.as_str()) {
off.insert(name.clone());
}
}
off.into_iter().collect()
}
/// Names of MCP servers present in Codex's own TOML configuration files (`~/.codex/config.toml`
/// and `<workspace_root>/.codex/config.toml`).
pub(crate) fn codex_external_server_names(home_dir: Option<&Path>, workspace_root: &Path) -> BTreeSet<String> {
let mut names = BTreeSet::new();
let mut paths = Vec::new();
if let Some(home) = home_dir {
paths.push(home.join(".codex").join("config.toml"));
}
paths.push(workspace_root.join(".codex").join("config.toml"));
for path in paths {
if let Ok(text) = std::fs::read_to_string(&path) {
names.extend(parse_codex_toml_servers(&text).into_keys());
}
}
names
}
/// Builds the ACP `mcpServers` array for `session/new`, `session/load`, and `session/fork`.
@@ -1058,6 +1095,11 @@ mod tests {
#[test]
fn servers_off_follow_the_effective_state() {
let mut claude_only = configured("claude-only", McpScope::User, true);
claude_only.agents = vec!["claude".into()];
let mut unapproved_ws = configured("unapproved-ws", McpScope::Workspace, false);
unapproved_ws.unapproved = true;
let all = [
configured("default-off", McpScope::User, false),
configured("switched-on", McpScope::User, false),
@@ -1066,6 +1108,8 @@ mod tests {
// The workspace entry decides for its name.
configured("both", McpScope::User, true),
configured("both", McpScope::Workspace, false),
claude_only,
unapproved_ws,
];
let overrides = BTreeMap::from([
("switched-on".to_owned(), true),
@@ -1073,8 +1117,11 @@ mod tests {
("agent-own".to_owned(), false),
(BUILTIN_MCP_NAME.to_owned(), false),
]);
assert_eq!(servers_off(&all, &overrides), ["agent-own", "both", "default-off", "switched-off"]);
assert_eq!(servers_off(&all[2..4], &BTreeMap::new()), Vec::<String>::new());
assert_eq!(
servers_off(&all, "copilot", &overrides),
["agent-own", "both", "claude-only", "default-off", "switched-off", "unapproved-ws"]
);
assert_eq!(servers_off(&all[2..4], "copilot", &BTreeMap::new()), Vec::<String>::new());
}
#[test]
+11
Переглянути файл
@@ -1671,6 +1671,17 @@ fn session_mcp_servers_become_thread_configuration() {
json!({"mcp_servers":{"OpenIDEA":{"command":"/app/openidea","args":["--mcp-stdio","--project","/project"],"env":{"K":"V"}}}})
)
);
let external = std::collections::BTreeSet::from(["linear".to_owned()]);
assert_eq!(
super::translate::mcp_config_with_external(
&json!({
"mcpServers": [],
"_meta": { "openidea": { "mcpServersOff": ["linear", "not-in-codex"] } }
}),
&external,
),
Some(json!({ "mcp_servers": { "linear": { "enabled": false } } }))
);
}
#[tokio::test(flavor = "multi_thread")]
+22 -1
Переглянути файл
@@ -923,8 +923,18 @@ fn str_of(v: &Value, key: &str) -> Option<String> {
/// Session-scoped MCP configuration, carried in thread/start, resume and fork.
pub(super) fn mcp_config(params: &Value) -> Option<Value> {
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(std::path::PathBuf::from);
let cwd = params.get("cwd").and_then(Value::as_str).map_or_else(|| std::path::Path::new("."), std::path::Path::new);
let external = crate::mcp::codex_external_server_names(home.as_deref(), cwd);
mcp_config_with_external(params, &external)
}
pub(super) fn mcp_config_with_external(
params: &Value,
external_names: &std::collections::BTreeSet<String>,
) -> Option<Value> {
let mut servers = serde_json::Map::new();
for server in params.get("mcpServers")?.as_array()? {
for server in params.get("mcpServers").and_then(Value::as_array).into_iter().flatten() {
if server.get("type").and_then(Value::as_str).is_some_and(|t| t != "stdio") {
continue;
}
@@ -946,5 +956,16 @@ pub(super) fn mcp_config(params: &Value) -> Option<Value> {
"args":server.get("args").cloned().unwrap_or_else(||json!([])),"env":env}),
);
}
for name in params
.pointer("/_meta/openidea/mcpServersOff")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
{
if !servers.contains_key(name) && external_names.contains(name) {
servers.insert(name.to_owned(), json!({ "enabled": false }));
}
}
(!servers.is_empty()).then(|| json!({"mcp_servers":servers}))
}
+107 -31
Переглянути файл
@@ -19,6 +19,7 @@ mod translate;
mod tests;
use super::Shim;
use crate::BACKGROUND_TASKS_UPDATE;
use crate::acp::AUTH_REQUIRED;
use crate::provider::ProviderSpec;
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
@@ -296,6 +297,25 @@ struct SessionEntry {
prompt: Option<oneshot::Sender<TurnTerminal>>,
early_cancel: Option<Instant>,
temp_files: Vec<PathBuf>,
/// Copilot's main agent loop is processing. It goes idle (`assistant.idle`) before the
/// turn ends (`session.idle`) while background shells or agents it started still run.
main_busy: bool,
/// Counts `session.tasks.list` requests, so only the latest answer is reported.
tasks_seq: u64,
}
impl SessionEntry {
fn new(settings: Settings) -> Self {
Self {
settings,
translator: EventTranslator::default(),
prompt: None,
early_cancel: None,
temp_files: Vec::new(),
main_busy: false,
tasks_seq: 0,
}
}
}
struct CopilotEvents(Weak<CopilotShim>);
@@ -411,6 +431,7 @@ impl CopilotShim {
"session/set_config_option" => self.set_config(&params).await,
"session/prompt" => self.prompt(&params, false).await,
"_openidea/steer" => self.prompt(&params, true).await,
"_openidea/stop_task" => self.stop_task(&params).await,
"session/close" => self.close_session(&params).await,
_ => Err(error(codes::METHOD_NOT_FOUND, format!("unsupported method {method}"))),
}
@@ -425,7 +446,7 @@ impl CopilotShim {
"promptCapabilities": { "image": true, "audio": false, "embeddedContext": true },
"mcpCapabilities": { "http": true, "sse": true, "stdio": true },
"sessionCapabilities": { "close": {}, "list": {} },
"_meta": { "openidea": { "steer": true } },
"_meta": { "openidea": { "steer": true, "backgroundTasks": true } },
},
"agentInfo": {
"name": "copilot",
@@ -471,6 +492,9 @@ impl CopilotShim {
if let Some(mcp) = translate::wire_mcp_servers(params.get("mcpServers")) {
req["mcpServers"] = mcp;
}
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
req["disabledMcpServers"] = disabled;
}
let created = self.call("session.create", req).await?;
let session_id = created
@@ -489,16 +513,7 @@ impl CopilotShim {
}
let options = models::config_options(&catalog, &settings);
self.state.lock().sessions.insert(
session_id.clone(),
SessionEntry {
settings,
translator: EventTranslator::default(),
prompt: None,
early_cancel: None,
temp_files: Vec::new(),
},
);
self.state.lock().sessions.insert(session_id.clone(), SessionEntry::new(settings));
self.publish_commands(&session_id, cwd);
Ok(json!({
"sessionId": session_id,
@@ -527,6 +542,9 @@ impl CopilotShim {
if let Some(mcp) = translate::wire_mcp_servers(params.get("mcpServers")) {
req["mcpServers"] = mcp;
}
if let Some(disabled) = translate::wire_disabled_mcp_servers(params) {
req["disabledMcpServers"] = disabled;
}
let resumed = self.call("session.resume", req).await?;
if let Ok(current) = self.call("session.model.getCurrent", json!({ "sessionId": session_id })).await {
@@ -542,16 +560,7 @@ impl CopilotShim {
}
let actual_id = resumed.get("sessionId").and_then(Value::as_str).unwrap_or(&session_id).to_owned();
let options = models::config_options(&catalog, &settings);
self.state.lock().sessions.insert(
actual_id.clone(),
SessionEntry {
settings,
translator: EventTranslator::default(),
prompt: None,
early_cancel: None,
temp_files: Vec::new(),
},
);
self.state.lock().sessions.insert(actual_id.clone(), SessionEntry::new(settings));
self.publish_commands(&actual_id, cwd);
Ok(json!({
"sessionId": actual_id,
@@ -653,7 +662,11 @@ impl CopilotShim {
let (text, attachments, temp_files) = build_prompt_payload(&session_id, blocks);
if steer {
let is_running = self.state.lock().sessions.get(&session_id).is_some_and(|e| e.prompt.is_some());
let (is_running, main_busy) = {
let st = self.state.lock();
let entry = st.sessions.get(&session_id);
(entry.is_some_and(|e| e.prompt.is_some()), entry.is_some_and(|e| e.main_busy))
};
if !is_running {
cleanup_files(&temp_files);
return Err(error(codes::INVALID_PARAMS, "no turn running to steer"));
@@ -661,14 +674,25 @@ impl CopilotShim {
let mut send_req = json!({
"sessionId": session_id,
"prompt": text,
"mode": "immediate",
});
// Joins the running loop; once it went idle (only background work is left), a plain
// send starts the loop again with this message.
if main_busy {
send_req["mode"] = json!("immediate");
}
if !attachments.is_empty() {
send_req["attachments"] = Value::Array(attachments);
}
if !main_busy && let Some(entry) = self.state.lock().sessions.get_mut(&session_id) {
// Stop must abort the run this send starts, even before `assistant.turn_start`.
entry.main_busy = true;
}
let res = self.call("session.send", send_req).await;
if let Some(entry) = self.state.lock().sessions.get_mut(&session_id) {
entry.temp_files.extend(temp_files);
if res.is_err() && !main_busy {
entry.main_busy = false;
}
}
res?;
return Ok(json!({}));
@@ -685,6 +709,7 @@ impl CopilotShim {
let mode = entry.settings.mode.wire();
if !early {
entry.prompt = Some(done_tx);
entry.main_busy = true;
}
(mode, early)
};
@@ -734,19 +759,24 @@ impl CopilotShim {
}
fn cancel(&self, session_id: &str) {
let has_turn = {
let (has_turn, ended) = {
let mut st = self.state.lock();
if let Some(entry) = st.sessions.get_mut(session_id) {
if entry.prompt.is_none() {
match st.sessions.get_mut(session_id) {
Some(entry) if entry.prompt.is_none() => {
entry.early_cancel = Some(Instant::now());
false
} else {
true
(false, None)
}
} else {
false
// The agent is done with the turn and only its background work runs, which
// `session.idle` waits for: the turn ends now and that work keeps running
// (it shows as background tasks, stoppable one by one).
Some(entry) if !entry.main_busy => (false, entry.prompt.take()),
Some(_) => (true, None),
None => (false, None),
}
};
if let Some(tx) = ended {
let _ = tx.send(TurnTerminal::Idle { aborted: true });
}
if has_turn {
let peer = self.copilot().clone();
let sid = session_id.to_owned();
@@ -790,10 +820,23 @@ impl CopilotShim {
return;
}
let main_agent = event.get("agentId").and_then(Value::as_str).is_none_or(str::is_empty);
let event_type = event.get("type").and_then(Value::as_str).unwrap_or_default();
if main_agent && event_type == "session.background_tasks_changed" {
self.refresh_background_tasks(session_id);
}
let catalog_snapshot = self.catalog.try_lock().ok().and_then(|g| g.clone());
let (updates, done) = {
let mut st = self.state.lock();
let Some(entry) = st.sessions.get_mut(session_id) else { return };
if main_agent {
match event_type {
"assistant.turn_start" => entry.main_busy = true,
"assistant.idle" | "session.idle" | "session.error" => entry.main_busy = false,
_ => {}
}
}
let fallback_limit =
catalog_snapshot.as_deref().and_then(|models| entry.settings.active_context_tokens(models));
let translated = entry.translator.translate(session_id, event, fallback_limit);
@@ -803,11 +846,44 @@ impl CopilotShim {
for (target_session, update) in updates {
self.send_update(&target_session, update);
}
if main_agent && event_type == "session.idle" {
// Nothing runs in the background any more.
self.send_update(session_id, json!({ "sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": [] }));
}
if let Some((tx, outcome)) = done {
let _ = tx.send(outcome);
}
}
/// Reports the session's running background shells and agents (`session.tasks.list`).
fn refresh_background_tasks(self: &Arc<Self>, session_id: &str) {
let seq = {
let mut st = self.state.lock();
let Some(entry) = st.sessions.get_mut(session_id) else { return };
entry.tasks_seq += 1;
entry.tasks_seq
};
let shim = self.clone();
let sid = session_id.to_owned();
self.runtime.spawn(async move {
let Ok(list) = shim.call("session.tasks.list", json!({ "sessionId": sid })).await else { return };
let latest = shim.state.lock().sessions.get(&sid).is_some_and(|e| e.tasks_seq == seq);
if latest {
let tasks = translate::background_tasks(&list);
shim.send_update(&sid, json!({ "sessionUpdate": BACKGROUND_TASKS_UPDATE, "tasks": tasks }));
}
});
}
/// Stops one background shell or agent (`session.tasks.cancel`).
async fn stop_task(self: &Arc<Self>, params: &Value) -> Result<Value, ResponseError> {
let session_id = str_param(params, "sessionId")?;
let task_id = str_param(params, "taskId")?;
self.call("session.tasks.cancel", json!({ "sessionId": session_id, "id": task_id })).await?;
self.refresh_background_tasks(session_id);
Ok(json!({}))
}
fn handle_permission_event(self: &Arc<Self>, session_id: &str, event: &Value) {
let data = &event["data"];
if data.get("resolvedByHook").and_then(Value::as_bool) == Some(true) {
+148 -1
Переглянути файл
@@ -6,6 +6,7 @@ use ide_jsonrpc::{Framing, Handler, Peer, codes};
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::sync::{Arc, OnceLock};
use std::time::Duration;
fn sample_models_list() -> Value {
json!({
@@ -340,6 +341,12 @@ fn headless_and_acp_args_roundtrip_while_preserving_user_flags() {
struct FakeCopilotServer {
peer: OnceLock<Peer>,
calls: Mutex<Vec<(String, Value)>>,
/// `session.send` leaves a shell running: the main loop goes idle but the session doesn't.
background_shell: bool,
}
fn copilot_event(sid: &str, event: Value) -> Value {
json!({ "sessionId": sid, "event": event })
}
impl Handler for FakeCopilotServer {
@@ -355,12 +362,36 @@ impl Handler for FakeCopilotServer {
"commands.list" => Ok(json!({ "commands": [{ "name": "compact", "description": "Compact context" }] })),
"skills.discover" => Ok(json!({ "skills": [] })),
"session.create" => Ok(json!({ "sessionId": "cop-sess-1" })),
"session.resume" => Ok(json!({ "sessionId": params["sessionId"] })),
"session.model.getCurrent" => Ok(json!({ "modelId": "gemini-4-carbon" })),
"session.model.switchTo" => Ok(json!({ "modelId": params["modelId"] })),
"session.mode.set" => Ok(json!({})),
"session.permissions.setApproveAll" => {
assert!(params.get("enabled").and_then(Value::as_bool).is_some());
Ok(json!({ "success": true }))
}
"session.tasks.list" => Ok(json!({ "tasks": [
{ "id": "shell-1", "type": "shell", "status": "running", "description": "",
"command": "gh pr checks 3819 --watch", "attachmentMode": "attached" },
{ "id": "shell-0", "type": "shell", "status": "completed", "description": "ls", "command": "ls" },
] })),
"session.tasks.cancel" => Ok(json!({ "cancelled": true })),
"session.abort" => Ok(json!({})),
"session.send" if self.background_shell => {
if let Some(peer) = self.peer.get().cloned() {
let sid = params["sessionId"].as_str().unwrap_or("cop-sess-1").to_owned();
std::thread::spawn(move || {
for event in [
json!({ "id": "b1", "type": "assistant.turn_start", "data": { "turnId": "t1" } }),
json!({ "id": "b2", "type": "assistant.idle", "data": {} }),
json!({ "id": "b3", "type": "session.background_tasks_changed", "data": {} }),
] {
let _ = peer.notify("session.event", copilot_event(&sid, event));
}
});
}
Ok(json!({ "messageId": "msg-1" }))
}
"session.send" => {
if let Some(peer) = self.peer.get().cloned() {
let sid = params["sessionId"].as_str().unwrap_or("cop-sess-1").to_owned();
@@ -423,7 +454,8 @@ impl Handler for CollectUpdates {
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_turns() {
let server = Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()) });
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates.clone(), move |events| {
@@ -538,3 +570,118 @@ async fn shim_creates_session_with_copilot_defaults_switches_tiers_and_streams_t
.any(|u| u["sessionUpdate"] == "usage_update" && u["size"] == 200_000 && u["used"] == 42_000)
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shim_forwards_disabled_mcp_servers_on_create_and_resume() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: false });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates, move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let _: Value = client.request("initialize", json!({}), None).await.unwrap();
let disabled = json!(["datadog", "github-mcp-server", "linear", "playwright", "slack-official"]);
let _: Value = client
.request(
"session/new",
json!({
"cwd": "/tmp",
"mcpServers": [],
"_meta": { "openidea": { "mcpServersOff": disabled } }
}),
None,
)
.await
.unwrap();
let _: Value = client
.request(
"session/load",
json!({
"sessionId": "cop-sess-1",
"cwd": "/tmp",
"mcpServers": [],
"_meta": { "openidea": { "mcpServersOff": disabled } }
}),
None,
)
.await
.unwrap();
let calls = server.calls.lock();
let (_, create_params) = calls.iter().find(|(m, _)| m == "session.create").unwrap();
assert_eq!(create_params["disabledMcpServers"], disabled);
let (_, resume_params) = calls.iter().find(|(m, _)| m == "session.resume").unwrap();
assert_eq!(resume_params["disabledMcpServers"], disabled);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn stop_ends_a_turn_left_running_only_by_background_shells() {
let server =
Arc::new(FakeCopilotServer { peer: OnceLock::new(), calls: Mutex::new(Vec::new()), background_shell: true });
let updates = Arc::new(CollectUpdates(Mutex::new(Vec::new())));
let server_clone = server.clone();
let client = attach(updates.clone(), move |events| {
let (a, b) = tokio::io::duplex(1 << 16);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let srv_peer = Peer::connect_framed(br, bw, server_clone.clone(), Framing::ContentLength);
let _ = server_clone.peer.set(srv_peer);
Ok(Peer::connect_framed(ar, aw, events, Framing::ContentLength))
})
.unwrap();
let init: Value = client.request("initialize", json!({}), None).await.unwrap();
assert_eq!(init["agentCapabilities"]["_meta"]["openidea"]["backgroundTasks"], true);
let _: Value = client.request("session/new", json!({ "cwd": "/tmp", "mcpServers": [] }), None).await.unwrap();
let prompt_client = client.clone();
let turn = tokio::spawn(async move {
prompt_client
.request::<_, Value>(
"session/prompt",
json!({ "sessionId": "cop-sess-1", "prompt": [{ "type": "text", "text": "watch CI" }] }),
None,
)
.await
});
// The running shell shows as a background task.
let mut shown = None;
for _ in 0..500 {
shown = updates.0.lock().iter().find(|u| u["sessionUpdate"] == crate::BACKGROUND_TASKS_UPDATE).cloned();
if shown.is_some() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(
shown.unwrap()["tasks"],
json!([{ "task_id": "shell-1", "task_type": "local_bash", "description": "gh pr checks 3819 --watch" }])
);
let _: Value = client
.request("_openidea/stop_task", json!({ "sessionId": "cop-sess-1", "taskId": "shell-1" }), None)
.await
.unwrap();
assert!(
server
.calls
.lock()
.iter()
.any(|(m, p)| m == "session.tasks.cancel" && p["sessionId"] == "cop-sess-1" && p["id"] == "shell-1")
);
// The main loop is idle, so Stop ends the turn even though `session.idle` never comes.
assert!(!turn.is_finished());
client.notify("session/cancel", json!({ "sessionId": "cop-sess-1" })).unwrap();
let res = tokio::time::timeout(Duration::from_secs(5), turn).await.unwrap().unwrap().unwrap();
assert_eq!(res["stopReason"], "cancelled");
assert!(!server.calls.lock().iter().any(|(m, _)| m == "session.abort"));
}
+30
Переглянути файл
@@ -522,6 +522,14 @@ pub(super) fn wire_mcp_servers(acp_servers: Option<&Value>) -> Option<Value> {
(!out.is_empty()).then_some(Value::Object(out))
}
/// Extracts `_meta.openidea.mcpServersOff` into Copilot's `disabledMcpServers` string array.
pub(super) fn wire_disabled_mcp_servers(params: &Value) -> Option<Value> {
let list = params.pointer("/_meta/openidea/mcpServersOff")?.as_array()?;
let names: Vec<Value> =
list.iter().filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(|s| json!(s))).collect();
(!names.is_empty()).then_some(Value::Array(names))
}
/// Converts `commands.list` + `skills.discover` results into ACP `availableCommands`.
pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Option<&Value>) -> Vec<Value> {
let mut seen = HashSet::new();
@@ -568,6 +576,28 @@ pub(super) fn available_commands(commands_res: Option<&Value>, skills_res: Optio
out
}
/// The running entries of a `session.tasks.list` result, in the background-task shape the
/// app shows (`task_id`, `task_type`, `description`).
pub(super) fn background_tasks(list: &Value) -> Vec<Value> {
let tasks = list.get("tasks").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
tasks
.iter()
.filter(|t| matches!(str_of(t, "status"), Some("running" | "idle")))
.filter_map(|t| {
let id = str_of(t, "id")?;
let kind = str_of(t, "type").unwrap_or_default();
let task_type = match kind {
"shell" => "local_bash",
"agent" => "local_agent",
other => other,
};
let description =
str_of(t, "description").filter(|d| !d.is_empty()).or_else(|| str_of(t, "command")).unwrap_or(kind);
Some(json!({ "task_id": id, "task_type": task_type, "description": description }))
})
.collect()
}
fn trim_tail(text: &mut String) {
if text.len() > MAX_OUTPUT {
let mut cut = text.len() - MAX_OUTPUT;
+42 -18
Переглянути файл
@@ -1214,25 +1214,15 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
assert_eq!(queue.iter().map(|q| q.prompt.text.as_str()).collect::<Vec<_>>(), ["again"]);
assert!(mgr.prompt(&task.id, text(" "), false).await.is_err());
mgr.send_queued_now(&task.id, &queue[0].id).unwrap();
for _ in 0..500 {
if mgr.entries(&task.id, None).unwrap().iter().any(|e| *e == AgentEntry::Agent { text: "second turn".into() }) {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let users: Vec<String> = mgr
.entries(&task.id, None)
.unwrap()
.into_iter()
.filter_map(|e| match e {
AgentEntry::User { text, .. } => Some(text),
_ => None,
})
.collect();
assert_eq!(users, ["wait", "again"]);
// Sending it now joins the running turn when the agent takes messages mid-turn.
mgr.send_queued_now(&task.id, &queue[0].id).await.unwrap();
assert!(agent.calls.lock().iter().any(|c| c == "_openidea/steer \"again\""));
assert!(!agent.calls.lock().iter().any(|c| c == "session/cancel"));
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::User { text, steered: true, .. } if text == "again")));
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
// Stopping a turn keeps the queue for later.
mgr.prompt(&task.id, text("wait"), false).await.unwrap();
@@ -1247,6 +1237,40 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn send_now_interrupts_the_turn_when_steering_is_refused() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent { session_steering: true, ..FakeAgent::default() });
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("wait"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Running).await;
mgr.prompt(&task.id, text("too late"), false).await.unwrap();
let queued = mgr.task(&task.id).unwrap().state.lock().task.queue[0].id.clone();
mgr.send_queued_now(&task.id, &queued).await.unwrap();
// The fake agent's next turn asks for permission.
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let calls = agent.calls.lock().clone();
assert!(calls.contains(&"_session/steering \"too late\"".to_owned()), "{calls:?}");
assert!(calls.contains(&"session/cancel".to_owned()), "{calls:?}");
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::User { text, steered: false, .. } if text == "too late")));
assert!(mgr.task(&task.id).unwrap().state.lock().task.queue.is_empty());
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn subagents_get_their_own_conversation() {
let tmp = tempfile::tempdir().unwrap();
+22 -6
Переглянути файл
@@ -47,13 +47,20 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
fs::write(
&script,
format!(
r#"gradle.projectsEvaluated {{
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
def resources = p.tasks.named('processResources')
p.tasks.register('openideaUpdateResources') {{
dependsOn resources
doLast {{ new File({}).setText(resources.get().destinationDir.absolutePath, 'UTF-8') }}
def update = {{ t ->
t.dependsOn 'processResources'
// Resolved here so the action holds no task or project (configuration cache).
def dir = p.tasks.getByName('processResources').destinationDir
def manifest = new File({})
t.doLast {{ manifest.setText(dir.absolutePath, 'UTF-8') }}
}}
// `register` is Gradle 4.9+.
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaUpdateResources', update)
else p.tasks.create('openideaUpdateResources', update)
}}
"#,
literal(&p.path),
@@ -172,7 +179,16 @@ mod tests {
assert_eq!(gradle.command, "/tools/gradlew");
assert_eq!(gradle.args.last().unwrap(), ":app:openideaUpdateResources");
let script = fs::read_to_string(cache.join("resources.init.gradle")).unwrap();
assert!(script.contains("processResources") && script.contains("destinationDir.absolutePath"));
assert!(
script.contains("processResources")
&& script.contains(".destinationDir\n")
&& script.contains("setText(dir.absolutePath")
);
// `register` is Gradle 4.9+ (#3864).
assert!(script.contains("else p.tasks.create('openideaUpdateResources', update)"), "{script}");
// The configuration cache can't serialize a task or project the action refers to.
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
assert!(!action.contains("p.") && !action.contains("tasks"), "{action}");
assert!(!script.contains("build/resources/main")); // The task owns custom output locations.
}
+7 -3
Переглянути файл
@@ -30,7 +30,8 @@ def processedResources = { Project p, s ->
def describe = { Project p ->
def m = [path: identity(p), dir: canon(p.projectDir), buildDir: canon(p.layout.buildDirectory.get().asFile)]
if (p.gradle.parent != null) m.build = identity(p.rootProject)
def sets = p.extensions.findByName('sourceSets')
// Gradle 4.x has it as a convention property, not an extension.
def sets = p.extensions.findByName('sourceSets') ?: p.findProperty('sourceSets')
if (sets != null) {
// Test source sets as IDEA classifies them: `test`, test fixtures, JVM test suites,
// and sets whose folders the `idea` plugin lists as test sources.
@@ -51,9 +52,12 @@ def describe = { Project p ->
}
}
try {
// `java` is Gradle 4.10+ (a convention before), its toolchain 6.7+.
def java = p.extensions.findByName('java')
def lv = java?.toolchain?.languageVersion?.getOrNull()
m.java = lv != null ? lv.asInt() : (java?.targetCompatibility?.majorVersion as Integer)
def lv = null
try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {}
def target = java != null ? java.targetCompatibility : p.findProperty('targetCompatibility')
m.java = lv != null ? lv.asInt() : (target?.majorVersion as Integer)
} catch (ignored) {}
println '@openidea-model\t' + JsonOutput.toJson(m)
}
+26 -7
Переглянути файл
@@ -172,13 +172,25 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
fs::write(
&script,
format!(
r#"gradle.projectsEvaluated {{
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
def warTask = p.tasks.named('war')
p.tasks.register('openideaTomcatArtifact') {{
dependsOn warTask
doLast {{ new File({}).setText(warTask.get().archiveFile.get().asFile.absolutePath, 'UTF-8') }}
def artifact = {{ t ->
t.dependsOn 'war'
// Resolved here so the action holds no task or project (configuration cache).
def war = p.tasks.getByName('war')
// `archiveFile` is Gradle 5.1+, `archivePath` is gone in 8.0.
def archive = war.hasProperty('archiveFile') ? war.archiveFile : war.archivePath
def manifest = new File({})
t.doLast {{
def file = archive instanceof File ? archive : archive.get().asFile
manifest.setText(file.absolutePath, 'UTF-8')
}}
}}
// `register` is Gradle 4.9+.
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaTomcatArtifact', artifact)
else p.tasks.create('openideaTomcatArtifact', artifact)
}}
"#,
groovy_literal(path),
@@ -270,7 +282,7 @@ mod tests {
assert_eq!(a.len(), 1);
let plan = build(tmp.path(), &model, &a[0].id, &tmp.path().join("base")).unwrap();
assert!(plan.args.contains(&":openideaTomcatArtifact".into()));
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("archiveFile.get()"));
assert!(fs::read_to_string(tmp.path().join("base/war.init.gradle")).unwrap().contains("? war.archiveFile :"));
assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
}
@@ -297,7 +309,14 @@ mod tests {
assert!(plan.args.contains(&format!("{}:openideaTomcatArtifact", module.trim_end_matches(':'))));
let script = fs::read_to_string(cache.join("war.init.gradle")).unwrap();
assert!(script.contains(&format!("rootProject.project('{}')", module)));
assert!(script.contains("archiveFile.get().asFile.absolutePath, 'UTF-8'"));
assert!(script.contains("manifest.setText(file.absolutePath, 'UTF-8')"));
// `archiveFile` is Gradle 5.1+, `register` 4.9+ (#3864).
assert!(
script.contains(": war.archivePath") && script.contains("else p.tasks.create('openideaTomcatArtifact'")
);
// The configuration cache can't serialize a task or project the action refers to.
let action = &script[script.find("doLast").unwrap()..script.find("// `register`").unwrap()];
assert!(!action.contains("p.") && !action.contains("war."), "{action}");
}
}
}
+36
Переглянути файл
@@ -348,6 +348,35 @@ mod imp {
paths
}
/// `Preferred DropEffect`: a `DWORD` saying whether the files were copied or cut.
/// Explorer writes it with every file list, and paste targets that move files
/// between machines (Remote Desktop's clipboard redirection, #3863) read it.
fn drop_effect_format() -> u32 {
let name: Vec<u16> = "Preferred DropEffect\0".encode_utf16().collect();
unsafe { RegisterClipboardFormatW(name.as_ptr()) }
}
/// `DROPEFFECT_COPY`.
const DROPEFFECT_COPY: u32 = 1;
/// An `HGLOBAL` holding a copy of `bytes`. Null when the allocation failed.
fn global_bytes(bytes: &[u8]) -> Handle {
unsafe {
let memory = GlobalAlloc(GMEM_MOVEABLE, bytes.len());
if memory.is_null() {
return ptr::null_mut();
}
let data = GlobalLock(memory);
if data.is_null() {
GlobalFree(memory);
return ptr::null_mut();
}
ptr::copy_nonoverlapping(bytes.as_ptr(), data as *mut u8, bytes.len());
GlobalUnlock(memory);
memory
}
}
/// An `HGLOBAL` holding `text` as UTF-16 with a terminating NUL, and its
/// byte size. Null when the allocation failed.
fn global_text(text: &str) -> (Handle, usize) {
@@ -430,6 +459,13 @@ mod imp {
if !taken {
GlobalFree(memory);
}
let effect = drop_effect_format();
if effect != 0 {
let effect_memory = global_bytes(&DROPEFFECT_COPY.to_le_bytes());
if !effect_memory.is_null() && SetClipboardData(effect, effect_memory).is_null() {
GlobalFree(effect_memory);
}
}
let (text_memory, _) = global_text(&text);
if !text_memory.is_null() {
// The text alone still pastes somewhere useful.
+8 -5
Переглянути файл
@@ -167,10 +167,11 @@ const GRADLE: &[&str] = &["gradle", "gradlew"];
/// Gradle's own JVM and the compiler's source encoding are untouched.
pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\
// Written by OpenIDEA: a UTF-8 default charset for applications run by Gradle, as the Run console decodes UTF-8.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects {
tasks.withType(JavaExec).configureEach {
defaultCharacterEncoding = 'UTF-8'
}
each(tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
}
";
@@ -621,10 +622,12 @@ mod tests {
#[test]
fn gradle_script_respects_the_builds_own_file_encoding() {
let s = GRADLE_FILE_ENCODING_SCRIPT;
assert!(s.contains("tasks.withType(JavaExec).configureEach"), "{s}");
assert!(s.contains("defaultCharacterEncoding = 'UTF-8'"), "{s}");
assert!(s.contains("each(tasks.withType(JavaExec))"), "{s}");
assert!(s.contains("t.defaultCharacterEncoding = 'UTF-8'"), "{s}");
assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}");
assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}");
// Gradle before 4.9 has no `configureEach` (#3864).
assert!(s.contains("? tasks.configureEach(action) : tasks.all(action)"), "{s}");
}
#[test]
+14 -6
Переглянути файл
@@ -6,11 +6,16 @@ use ide_run::wrap::{self, program_name};
use std::path::Path;
const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage.
allprojects {
plugins.withId('java') {
apply plugin: 'jacoco'
tasks.withType(Test).configureEach { t -> t.finalizedBy(tasks.named('jacocoTestReport')) }
tasks.named('jacocoTestReport') { r -> r.reports { xml.required.set(true) } }
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects { p ->
p.plugins.withId('java') {
p.apply plugin: 'jacoco'
each(p.tasks.withType(Test)) { t -> t.finalizedBy('jacocoTestReport') }
def xml = p.tasks.getByName('jacocoTestReport').reports.xml
// `Report.required` is Gradle 6.1+, `enabled` is gone in 8.0.
if (xml.hasProperty('required')) xml.required.set(true) else xml.enabled = true
}
}
"#;
@@ -391,7 +396,10 @@ mod tests {
let p = prepare(dir.path(), &cfg("gradle", "./gradlew", &[":app:test", "--tests", "*Calc"]), dir.path());
let (l, report) = launch(&p);
assert_eq!(l.args[0], "--init-script");
assert!(std::fs::read_to_string(&l.args[1]).unwrap().contains("jacoco"));
let script = std::fs::read_to_string(&l.args[1]).unwrap();
assert!(script.contains("p.apply plugin: 'jacoco'"), "{script}");
// `Report.required` is Gradle 6.1+, `configureEach` 4.9+ (#3864).
assert!(script.contains("else xml.enabled = true") && script.contains(": tasks.all(action)"), "{script}");
assert!(matches!(report, CoverageReportSpec::Jacoco { .. }));
}
+3
Переглянути файл
@@ -1624,6 +1624,7 @@ impl DebugManager {
// DAP: a response without the flag continued every thread.
let all = body.get("allThreadsContinued").and_then(Value::as_bool).unwrap_or(true);
session.suspended.resumed(ticket, thread_id, all);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: all });
Ok(())
}
@@ -1672,6 +1673,7 @@ impl DebugManager {
step_settled(&session, sent)?;
// A step runs its thread; other threads stopped by their own events stay stopped.
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
Ok(())
}
@@ -1783,6 +1785,7 @@ impl DebugManager {
.await;
step_settled(&session, sent)?;
session.suspended.resumed(ticket, thread_id, false);
stream_trace::release_done(&session);
session.emit(ide_core::event::DebugEvent::Continued { thread_id, all_threads_continued: true });
Ok(())
}
+4
Переглянути файл
@@ -116,6 +116,8 @@ pub(crate) struct Session {
pub jvm_memory: tokio::sync::Mutex<crate::JvmMemoryState>,
pub stream_tracer: parking_lot::Mutex<Option<Arc<dyn ide_jvm_inspect::StreamTracer>>>,
pub(crate) stream_trace: parking_lot::Mutex<Option<crate::stream_trace::ActiveTrace>>,
/// The last trace that finished, until the stop its records were read in ends.
pub(crate) stream_trace_done: parking_lot::Mutex<Option<crate::stream_trace::DoneTrace>>,
/// Used only by a kotlin-lsp session: see [`Session::kotlin_lsp_quirks`].
pub(crate) quirks: kotlin_lsp::Quirks,
pub(crate) unity_startup_activity: Mutex<Instant>,
@@ -281,6 +283,7 @@ impl Session {
jvm_memory: tokio::sync::Mutex::default(),
stream_tracer: parking_lot::Mutex::new(None),
stream_trace: parking_lot::Mutex::new(None),
stream_trace_done: parking_lot::Mutex::new(None),
quirks: kotlin_lsp::Quirks::default(),
unity_startup_activity: Mutex::new(Instant::now()),
}
@@ -774,6 +777,7 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
// DAP: an event without the flag continues its thread alone. The UI keeps treating
// it as all threads; the suspension, which holds only threads that stopped, need not.
s.suspended.continued(int("threadId"), all.unwrap_or(false));
crate::stream_trace::release_done(s);
s.emit(DebugEvent::Continued {
thread_id: int("threadId").unwrap_or(0),
all_threads_continued: all.unwrap_or(true),
+64 -8
Переглянути файл
@@ -88,6 +88,32 @@ pub enum TraceUnavailable {
},
}
/// A trace that finished. Its records keep their objects from being collected until the stop they
/// were read in ends; then the UI no longer shows them and [`release_done`] lets them go.
pub(crate) struct DoneTrace {
tracer: Arc<dyn StreamTracer>,
target: VmTarget,
id: TraceId,
}
/// The stop a finished trace was read in ended (a resume, a step, a `continued` event).
pub(crate) fn release_done(s: &Session) {
let Some(done) = s.stream_trace_done.lock().take() else { return };
let ended = s.ended.clone();
let session = s.id.0;
tokio::spawn(async move {
tokio::select! {
biased;
() = ended.cancelled() => {}
result = done.tracer.release(&done.target, done.id) => {
if let Err(e) = result {
tracing::debug!(session, trace = done.id, "releasing a finished stream trace: {e}");
}
}
}
});
}
/// The session's running trace; `id` is `None` until `arm` answers.
pub(crate) struct ActiveTrace {
tracer: Arc<dyn StreamTracer>,
@@ -181,10 +207,30 @@ pub(crate) async fn run(
if !s.suspended.get() {
return unavailable(TraceUnavailable::NotSuspended);
}
let mut trace =
Trace { mgr, s, tracer: &*tracer, target: &target, thread_id, progress, id: None, last: Counts::default() };
// The bundle releases the previous trace itself when this one arms.
s.stream_trace_done.lock().take();
static TOKENS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
let token =
format!("{}-{}-{}", std::process::id(), s.id.0, TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
let mut trace = Trace {
mgr,
s,
tracer: &*tracer,
target: &target,
thread_id,
progress,
token,
arm_sent: false,
id: None,
last: Counts::default(),
};
match trace.drive(plan, cancel).await {
Ok(run) => run,
Ok(run) => {
if let (TraceRun::Done { .. }, Some(id)) = (&run, trace.id) {
*s.stream_trace_done.lock() = Some(DoneTrace { tracer: tracer.clone(), target: target.clone(), id });
}
run
}
Err(run) => {
// A stop from now on is the user's to see.
set_running(s, false);
@@ -231,6 +277,9 @@ struct Trace<'a, P> {
target: &'a VmTarget,
thread_id: i64,
progress: &'a P,
/// Names the trace to the bundle before `arm` answers (see [`StreamTracer::release_armed`]).
token: String,
arm_sent: bool,
/// Set once `arm` answers.
id: Option<TraceId>,
last: Counts,
@@ -241,8 +290,9 @@ impl<P: Fn(TraceProgress) + Send + Sync> Trace<'_, P> {
async fn drive(&mut self, plan: &Value, cancel: &CancellationToken) -> Result<TraceRun, TraceRun> {
let (s, tracer, target) = (self.s, self.tracer, self.target);
self.report(TracePhase::Arming);
self.arm_sent = true;
let id = self
.until_ended(tracer.arm(target, self.thread_id, plan, BUDGET))
.until_ended(tracer.arm(target, self.thread_id, plan, BUDGET, &self.token))
.await?
.map_err(|e| if s.ended.is_cancelled() { ended() } else { refused(e) })?;
self.id = Some(id);
@@ -313,14 +363,20 @@ impl<P: Fn(TraceProgress) + Send + Sync> Trace<'_, P> {
/// After a trace that ended early. Left to the bundle, an armed trace would keep every
/// breakpoint off and a parked one its thread suspended behind java-debug's back; the bundle
/// undoes either, or does so once a terminal still running returns. Not after a finished
/// trace: the records it unpins are the values the result shows.
/// trace: the records it unpins are the values the result shows ([`release_done`] does, once
/// that stop ends). An `arm` that never answered (it timed out) may still have armed: released
/// by its token.
async fn release(&self) {
let Some(id) = self.id else { return };
if self.s.ended.is_cancelled() {
return;
}
if let Ok(Err(e)) = self.until_ended(self.tracer.release(self.target, id)).await {
tracing::debug!(session = self.s.id.0, trace = id, "stream trace release: {e}");
let work = match self.id {
Some(id) => self.tracer.release(self.target, id),
None if self.arm_sent => self.tracer.release_armed(self.target, &self.token),
None => return,
};
if let Ok(Err(e)) = self.until_ended(work).await {
tracing::debug!(session = self.s.id.0, trace = ?self.id, "stream trace release: {e}");
}
}
+13 -2
Переглянути файл
@@ -72,10 +72,21 @@ async fn windows_stop_releases_the_debuggees_port_before_returning() {
.unwrap();
let pid = child.0.id();
child.1 = Some(ide_core::process::ProcessTree::capture(pid));
let h = harness(Script { debuggee_pid: Some(pid), supports_terminate, ..Default::default() });
// A running program: one suspended at a breakpoint is killed at once (#3658), without the
// wait for its tree this test is about.
let h = harness(Script {
debuggee_pid: Some(pid),
supports_terminate,
continued_after_stop: true,
..Default::default()
});
let id = h.start(config()).await.unwrap();
let session = h.manager.session(id).unwrap();
while session.debuggee_pid.load(Ordering::Acquire) != i64::from(pid) {
// The pid, then the stop at launch and the `continued` that ends it.
while session.debuggee_pid.load(Ordering::Acquire) != i64::from(pid)
|| session.suspended.ticket() == 0
|| session.suspended.get()
{
tokio::time::sleep(Duration::from_millis(10)).await;
}
let stop = tokio::spawn({
+36
Переглянути файл
@@ -55,6 +55,7 @@ impl StreamTracer for FakeTracer {
_thread_id: i64,
_plan: &'a Value,
_budget: u32,
_token: &'a str,
) -> InspectFuture<'a, TraceId> {
self.record("arm", target);
let error = self.arm_error.lock().clone();
@@ -96,6 +97,11 @@ impl StreamTracer for FakeTracer {
self.record("release", target);
Box::pin(async { Ok(()) })
}
fn release_armed<'a>(&'a self, target: &'a VmTarget, _token: &'a str) -> InspectFuture<'a, ()> {
self.record("releaseArmed", target);
Box::pin(async { Ok(()) })
}
}
fn collected() -> TraceCollected {
@@ -443,6 +449,36 @@ async fn a_finished_trace_is_not_released() {
assert!(!tracer.names().contains(&"release"), "{:?}", tracer.names());
}
#[tokio::test]
async fn a_finished_trace_is_released_once_the_program_runs_on() {
let h = harness(java_debug());
let tracer = FakeTracer::scripted([parked()]);
let id = stopped_java(&h, &tracer).await;
assert!(matches!(trace(&h, id).await.unwrap(), TraceRun::Done { .. }));
h.manager.resume(id, 1).await.unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while !tracer.names().contains(&"release") {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the finished trace was not released");
assert_eq!(tracer.names().iter().filter(|n| **n == "release").count(), 1);
}
#[tokio::test]
async fn an_arm_without_a_reply_is_released_by_its_token() {
// The bundle may still finish arming after the reply timed out: its breakpoints would stay off.
let h = harness(java_debug());
let tracer = FakeTracer::scripted([]);
let id = stopped_java(&h, &tracer).await;
*tracer.arm_error.lock() = Some(InspectError::TimedOut);
assert!(matches!(trace(&h, id).await.unwrap(), TraceRun::Failed { .. }));
assert_eq!(tracer.names(), ["arm", "releaseArmed"]);
}
#[tokio::test]
async fn refused_stop_leaves_the_outcome_to_wait() {
let h = harness(java_debug());
+4 -2
Переглянути файл
@@ -179,7 +179,9 @@ fn pg_restore(o: &DbPgRestoreOptions, file: &str) -> Vec<String> {
}
fn psql(o: &DbPsqlOptions, file: &str) -> Vec<String> {
let mut args: Vec<String> = (!file.is_empty()).then(|| format!("--file={file}")).into_iter().collect();
// `~/.psqlrc` could switch databases or change settings before the dump runs.
let mut args = vec!["--no-psqlrc".to_owned()];
args.extend((!file.is_empty()).then(|| format!("--file={file}")));
args.extend(flag(o.single_transaction, "--single-transaction"));
args.extend(flag(o.stop_on_error, "--set=ON_ERROR_STOP=1"));
args
@@ -317,7 +319,7 @@ mod tests {
let options = DbPsqlOptions { single_transaction: true, stop_on_error: true };
assert_eq!(
args(DbToolJob::Psql { file: "/tmp/shop.sql".into(), options }),
["--file=/tmp/shop.sql", "--single-transaction", "--set=ON_ERROR_STOP=1"]
["--no-psqlrc", "--file=/tmp/shop.sql", "--single-transaction", "--set=ON_ERROR_STOP=1"]
);
}
+23 -1
Переглянути файл
@@ -237,7 +237,7 @@ pub fn connection(tool: DbTool, source: &DataSource) -> (Vec<String>, Vec<(Strin
args.push(format!("--username={}", source.user.trim()));
}
if !source.database.is_empty() {
args.push(format!("--dbname={}", source.database));
args.push(format!("--dbname={}", dbname_arg(&source.database)));
}
// Without a terminal a password prompt would wait forever: fail instead.
args.push("--no-password".into());
@@ -271,6 +271,16 @@ pub fn connection(tool: DbTool, source: &DataSource) -> (Vec<String>, Vec<(Strin
(args, env)
}
/// `--dbname` reads a connection string or URI as connection parameters: such a database name
/// goes in quoted as the string's `dbname`, so it cannot pick another host or credentials.
fn dbname_arg(name: &str) -> String {
if name.contains('=') || name.starts_with("postgresql://") || name.starts_with("postgres://") {
format!("dbname='{}'", name.replace('\\', "\\\\").replace('\'', "\\'"))
} else {
name.to_owned()
}
}
/// How a tool is started: connection arguments, then the job's, and the environment.
pub struct Prepared {
pub args: Vec<String>,
@@ -404,6 +414,18 @@ mod tests {
assert!(!env.iter().any(|(k, _)| k == "PGPASSWORD" || k == "PGOPTIONS"));
}
#[test]
fn a_database_named_like_connection_parameters_stays_a_name() {
for (name, arg) in [
("host=evil.example dbname=p", r"--dbname=dbname='host=evil.example dbname=p'"),
(r"it's=\x", r"--dbname=dbname='it\'s=\\x'"),
("postgresql://evil.example/p", "--dbname=dbname='postgresql://evil.example/p'"),
] {
let (args, _) = connection(DbTool::PgDump, &DataSource { database: name.into(), ..pg() });
assert!(args.contains(&arg.to_owned()), "{args:?}");
}
}
#[test]
fn default_port_and_optional_fields() {
let source = DataSource { port: None, user: String::new(), database: String::new(), ..pg() };
+6
Переглянути файл
@@ -191,6 +191,12 @@ impl Host {
};
host.apply_proxy();
host.apply_added_jdks();
// Before any project starts jdtls; the deleting itself can take a while.
let unused =
ide_sdk::jdtls_workspaces::take_unused(&host.local_data_dir, ide_sdk::jdtls_workspaces::UNUSED_FOR);
if !unused.is_empty() {
std::thread::spawn(move || ide_sdk::jdtls_workspaces::remove(unused));
}
ops::agent::move_user_mcp_values(&host);
host
}
+7 -2
Переглянути файл
@@ -25,12 +25,17 @@ impl Scope {
} else {
call.root().join(given)
});
let roots: Vec<PathBuf> =
std::iter::once(call.root().to_path_buf()).chain(call.project().content_roots()).collect();
// Before touching the file system: on Windows, resolving `\\host\share` signs in to that host.
if !ide_vfs::content_path_allowed(&path, &roots) {
return Err(IdeError::invalid(format!("scope {raw} is outside the project")));
}
let path = dunce::canonicalize(&path).unwrap_or(path);
if !path.is_dir() {
return Err(IdeError::not_found(format!("scope {raw} is not a directory")));
}
let roots = std::iter::once(call.root().to_path_buf()).chain(call.project().content_roots());
if !roots.into_iter().any(|root| path.starts_with(root)) {
if !roots.iter().any(|root| path.starts_with(root)) {
return Err(IdeError::invalid(format!("scope {raw} is outside the project")));
}
Ok(Self(Some(path)))
+19 -9
Переглянути файл
@@ -883,14 +883,20 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
let host = call.host();
let project = call.project().clone();
let indexing_before = project.index.status().indexing;
let pool = if scope.is_all() && dir.dir().is_none() {
limit + 1
} else {
((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL)
};
let pool = if scope.is_all() { limit + 1 } else { ((limit + 1) * SYMBOL_POOL_FACTOR).min(MAX_SYMBOL_POOL) };
let found = {
let (project, q) = (project.clone(), q.clone());
host.blocking(move || Ok(project.index.find_symbols(&q, ide_index::SymbolFilter::All, pool))).await?
let (project, q, dir) = (project.clone(), q.clone(), dir.dir().map(Path::to_path_buf));
host.blocking(move || {
Ok(match dir {
// Filtered in the index: a pool cut before the filter could miss every match.
Some(dir) => project
.index
.find_symbols_until(&q, ide_index::SymbolFilter::All, pool, &|p| p.starts_with(&dir), &|| false)
.unwrap_or_default(),
None => project.index.find_symbols(&q, ide_index::SymbolFilter::All, pool),
})
})
.await?
};
let mut items: Vec<SearchItem> = found
.into_iter()
@@ -910,10 +916,14 @@ async fn symbol_search(call: Call) -> IdeResult<Output> {
let budget = MEDIUM_TIMEOUT.saturating_sub(started.elapsed());
let (symbols, out_of_time) = workspace_symbols(&call, &q, budget).await;
timed_out = out_of_time;
let mut roots = project.content_roots();
roots.extend(crate::mcp::tool::attached_projects(call.root()));
for (name, container, location) in symbols {
let path = location.uri.clone().unwrap_or_else(|| call.display(&location.path));
// Project files obey `scope` and `paths`; library symbols are what was asked for.
let inside = location.uri.is_none() && !Path::new(&path).is_absolute();
// Project files (attached projects' too) obey `scope` and `paths`; library symbols
// are what was asked for.
let inside = location.uri.is_none()
&& (!Path::new(&path).is_absolute() || roots.iter().any(|r| location.path.starts_with(r)));
if inside && !(dir.contains_shown(call.root(), &path) && scope.matches(&path)) {
continue;
}
+18 -9
Переглянути файл
@@ -251,9 +251,9 @@ pub fn unqueue(host: &Host, window: &str, task: String, queued: String) -> IdeRe
}
/// Sends a queued message now, interrupting the current turn.
pub fn send_queued_now(host: &Host, window: &str, task: String, queued: String) -> IdeResult<()> {
pub async fn send_queued_now(host: &Host, window: &str, task: String, queued: String) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.send_queued_now(&task, &queued)
host.project(window)?.agents.send_queued_now(&task, &queued).await
}
/// Changes a session setting (model, mode, thinking effort…).
@@ -457,6 +457,7 @@ fn persist_mcp_map(
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.mcpServers", value)?;
for p in host.projects() {
p.settings.reload();
p.agents.notify_mcp_servers_changed();
p.sink.emit(event.clone());
if kept == Kept::LocalFile {
host.agent_secrets.notify_kept_locally(&p.sink);
@@ -466,6 +467,7 @@ fn persist_mcp_map(
McpScope::Workspace => {
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace MCP servers"))?;
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.mcpServers", value)?;
p.agents.notify_mcp_servers_changed();
p.sink.emit(event);
}
}
@@ -533,9 +535,17 @@ pub(crate) fn session_mcp_servers(
use ide_workspace::settings::SettingsScope;
let mut user = settings.layer(SettingsScope::Global).agents.mcp_servers;
fill_mcp_values(secrets, &mut user);
let mut workspace = settings.layer(SettingsScope::Project).agents.mcp_servers;
workspace.retain(|name, srv| approvals.approved(root, name, srv));
ide_agent::mcp::servers_from_settings(&user, &workspace)
let raw_workspace = settings.layer(SettingsScope::Project).agents.mcp_servers;
let workspace = approvals.apply(root, raw_workspace.clone());
let mut out = ide_agent::mcp::servers_from_settings(&user, &workspace);
for srv in &mut out {
if srv.scope == McpScope::Workspace
&& let Some(raw) = raw_workspace.get(&srv.name)
{
srv.unapproved = !approvals.approved(root, &srv.name, raw);
}
}
out
}
/// Lists configured MCP servers across User (`settings.toml`) and Workspace (`.openidea/settings.toml`) scopes.
@@ -877,10 +887,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
prompt(&c.host, &c.window, c.arg("task")?, c.arg("prompt")?, c.arg("now")?).await
});
d.add("agent_unqueue", |c| async move { unqueue(&c.host, &c.window, c.arg("task")?, c.arg("queued")?) });
d.add(
"agent_send_queued_now",
|c| async move { send_queued_now(&c.host, &c.window, c.arg("task")?, c.arg("queued")?) },
);
d.add("agent_send_queued_now", |c| async move {
send_queued_now(&c.host, &c.window, c.arg("task")?, c.arg("queued")?).await
});
d.add("agent_set_config", |c| async move {
set_config(&c.host, &c.window, c.arg("task")?, c.arg("option")?, c.arg("value")?).await
});
+5
Переглянути файл
@@ -238,6 +238,11 @@ pub fn set_settings(
if is_proxy {
host.apply_proxy();
}
if key == "agents" || key == "agents.mcpServers" || key.starts_with("agents.mcpServers.") {
for project in affected() {
project.agents.notify_mcp_servers_changed();
}
}
// A new interpreter / toolchain / server executable restarts the language servers it affects.
// So do inspections that are compiler options (`ide-sdk` `configure_java_compiler`).
let code_style = key == "editor"
+1
Переглянути файл
@@ -65,6 +65,7 @@ pub async fn spell_check(
end: r.end,
kind: match r.kind {
SpellingKind::Comment => RegionKind::Comment,
SpellingKind::String if r.raw => RegionKind::RawString,
SpellingKind::String => RegionKind::String,
SpellingKind::Name => RegionKind::Name,
},
+4
Переглянути файл
@@ -379,6 +379,10 @@ fn ready(
},
};
let mut linked = link_trace(plan, &recording, collected.skipped_breakpoints);
// A stream made parallel before the chain's statement, which the bundle found so at run time.
if collected.sequentialized && !plan.sequentialize {
linked.banners.push(TraceBanner::Sequentialized);
}
if resumed_stops > 0 {
linked.banners.push(TraceBanner::BreakpointsResumed { count: resumed_stops });
}
+17
Переглянути файл
@@ -442,3 +442,20 @@ fn chain_info_steps_keep_modifiers() {
let found = chains_at(service(), &snap, &frame(1), true, true, &CancellationToken::new()).unwrap();
assert_eq!(found[0].info.steps, ["filter", "unordered", "map"]);
}
#[test]
fn ready_says_a_stream_found_parallel_at_run_time_ran_sequentially() {
let java = LanguageId::new("java");
let snap = Snapshot::text(&java, SOURCE);
let found = chains_at(service(), &snap, &frame(line_of("C_SPIKE")), true, true, &CancellationToken::new()).unwrap();
let Candidate { info, chain } = found.into_iter().next().unwrap();
let chain = chain.unwrap();
let plan = real_run_plan(&chain).unwrap();
assert!(!plan.sequentialize);
let collected = TraceCollected { sequentialized: true, ..spike_collected() };
let StreamTraceResult::Ready { banners, .. } = ready(info, &chain, &plan, collected, 9, 0) else {
panic!("not ready");
};
assert!(banners.contains(&TraceBanner::Sequentialized), "{banners:?}");
}
+22
Переглянути файл
@@ -1304,6 +1304,25 @@ pub async fn vcs_create_patch(
.await
}
/// The changes a commit with `options` would make in `repo`, as one patch (what Commit
/// commits: the index with the selection applied, partial files' chosen hunks only).
pub async fn vcs_pending_patch(
host: &Host,
window: &str,
repo: Option<PathBuf>,
options: CommitOptions,
) -> IdeResult<String> {
const MAX_PATCH: usize = 1 << 20;
let project = host.project(window)?;
blocking(move || {
project.with_repo_at(repo.as_deref(), |r| {
let changes = r.pending_changes(&options, MAX_PATCH, &|path| project.vcs_encoding(path, None))?;
Ok(changes.into_iter().filter_map(|c| c.diff).collect())
})
})
.await
}
pub async fn vcs_patch_preview(
host: &Host,
window: &str,
@@ -1663,6 +1682,9 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("vcs_create_patch", |c| async move {
vcs_create_patch(&c.host, &c.window, c.arg("repo")?, c.arg("source")?).await
});
d.add("vcs_pending_patch", |c| async move {
vcs_pending_patch(&c.host, &c.window, c.arg("repo")?, c.arg("options")?).await
});
d.add("vcs_patch_preview", |c| async move {
vcs_patch_preview(&c.host, &c.window, c.arg("repo")?, c.arg("patch")?).await
});
+57 -4
Переглянути файл
@@ -13,6 +13,7 @@
//! [[contributes.keymaps]]
//! command = "check"
//! key = "Ctrl+Alt+C" # `mac` for a different binding on macOS (`Meta+Alt+C`)
//! # key = "Escape" + when = "…" # API 1.10: Escape in an editor that the IDE had no use for
//!
//! [[contributes.statusBar]]
//! id = "branch"
@@ -203,8 +204,16 @@ struct KeymapDecl {
key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
mac: Option<String>,
/// Only with an `Escape` binding (API 1.10): when the command clears something.
#[serde(default, skip_serializing_if = "Option::is_none")]
when: Option<String>,
}
/// The one plain key a plugin may bind (API 1.10): in a focused editor, after the IDE's own uses of
/// Escape (popups, completion, rename, selection, extra carets, Vim) found nothing to do, like a
/// handler at the end of IDEA's EditorEscape chain.
const ESCAPE: &str = "Escape";
const MODIFIERS: [&str; 4] = ["Meta", "Ctrl", "Alt", "Shift"];
const NAMED_KEYS: [&str; 22] = [
"Enter",
@@ -262,9 +271,21 @@ pub fn validate_binding(binding: &str) -> Result<(), String> {
pub(super) fn keymap(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: KeymapDecl = decode(KEYMAPS, decl)?;
declared_command(pkg, KEYMAPS, &d.command)?;
validate_binding(&d.key).map_err(|e| format!("contributes.keymaps: {e}"))?;
if let Some(m) = &d.mac {
validate_binding(m).map_err(|e| format!("contributes.keymaps: {e}"))?;
let escape = d.key == ESCAPE || d.mac.as_deref() == Some(ESCAPE);
if escape {
if d.key != ESCAPE || d.mac.as_deref().is_some_and(|m| m != ESCAPE) {
return Err("contributes.keymaps: an Escape binding is Escape on every platform".into());
}
pkg.manifest.needs_api("contributes.keymaps key = \"Escape\"", 10)?;
let when = d.when.as_deref().ok_or("contributes.keymaps: an Escape binding needs a `when` clause")?;
validate_when(when).map_err(|e| format!("contributes.keymaps: {e}"))?;
} else if d.when.is_some() {
return Err("contributes.keymaps: `when` is only for an Escape binding".into());
}
for binding in std::iter::once(&d.key).chain(&d.mac) {
if binding != ESCAPE {
validate_binding(binding).map_err(|e| format!("contributes.keymaps: {e}"))?;
}
}
Ok(UiDecl::new(d.command.clone(), d.key.clone(), json(&d)?))
}
@@ -1114,6 +1135,37 @@ mod tests {
}
}
#[test]
fn escape_bindings_need_api_1_10_and_a_when_clause() {
let pkg = |api: &str| {
let manifest = ide_extension::Manifest::parse(&format!(
"id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='clear'\ntitle='Clear'"
))
.unwrap();
Package::new(manifest, std::path::PathBuf::from("/unused"))
};
let check = |api: &str, decl: &str| keymap(&pkg(api), toml::from_str(decl).unwrap());
let escape = "command='clear'\nkey='Escape'\nwhen='plugin.test.active'";
let ok = check("^1.10", escape).unwrap();
assert_eq!(ok.json["when"], "plugin.test.active");
assert!(check("^1.10", &format!("{escape}\nmac='Escape'")).is_ok());
for (api, decl, error) in [
("^1.9", escape, "1.10"),
("^1.10", "command='clear'\nkey='Escape'", "when"),
("^1.10", "command='clear'\nkey='Escape'\nwhen='a &&'", "when"),
("^1.10", &format!("{escape}\nmac='Meta+K'") as &str, "every platform"),
("^1.10", "command='clear'\nkey='Ctrl+K'\nmac='Escape'\nwhen='x'", "every platform"),
("^1.10", "command='clear'\nkey='Ctrl+K'\nwhen='x'", "only for an Escape"),
("^1.10", "command='clear'\nkey='Enter'", "needs Ctrl"),
("^1.10", "command='clear'\nkey='Shift+Escape'", "needs Ctrl"),
] {
let err = check(api, decl).unwrap_err();
assert!(err.contains(error), "{api} {decl}\n→ {err}");
}
// Other bindings are unchanged.
assert!(check("^1.9", "command='clear'\nkey='Ctrl+Alt+C'").is_ok());
}
#[test]
fn bindings_need_a_modifier() {
for ok in ["Ctrl+Alt+C", "Meta+Shift+K", "F5", "Shift+F6", "Meta+K Meta+C", "Alt+Enter"] {
@@ -1243,7 +1295,8 @@ mod tests {
#[test]
fn editor_panels_validate_api_width_when_capability_and_page() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/editor-panel");
let source = std::fs::read_to_string(root.join("plugin.toml")).unwrap();
// A Windows checkout may have CRLF line ends; the edits below match on `\n`.
let source = std::fs::read_to_string(root.join("plugin.toml")).unwrap().replace("\r\n", "\n");
let check = |source: &str| {
let manifest = ide_extension::Manifest::parse(source)?;
let decl = manifest.declarations(EDITOR_PANELS).into_iter().next().unwrap();
+1
Переглянути файл
@@ -286,6 +286,7 @@ impl Host {
lsp.set_prepare_hook(Box::new(move |cfg, _, cancel| {
let effective = settings.effective();
if cfg.name == "jdtls" {
ide_sdk::jdtls_workspaces::mark_used(cfg);
crate::java_runtime::prepare(
cfg,
&data_dir,
+21
Переглянути файл
@@ -481,6 +481,27 @@ async fn scope_limits_the_query_tools_to_a_directory() {
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_scoped_symbol_search_finds_matches_past_the_unscoped_ones() {
let h = Harness::new();
std::fs::create_dir_all(h.root.join("many")).unwrap();
for i in 0..60 {
std::fs::write(h.root.join(format!("many/m{i:02}.rs")), "pub fn pool_marker() {}\n").unwrap();
}
std::fs::create_dir_all(h.root.join("zz")).unwrap();
std::fs::write(h.root.join("zz/last.rs"), "pub fn pool_marker() {}\n").unwrap();
// Files written after the project opened reach the index through the watcher.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
while h.json("search_symbol", json!({"q":"pool_marker","limit":100})).await["items"].as_array().map_or(0, Vec::len)
< 61
{
assert!(std::time::Instant::now() < deadline, "the files were never indexed");
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
let found = h.json("search_symbol", json!({"q":"pool_marker","scope":"zz","limit":1})).await;
assert_eq!(found["items"][0]["filePath"], "zz/last.rs", "{found}");
}
#[tokio::test(flavor = "multi_thread")]
async fn scope_reaches_an_attached_worktree_the_repository_ignores() {
let h = Harness::new();
+2 -1
Переглянути файл
@@ -80,7 +80,8 @@ impl Harness {
}
#[tokio::test(flavor = "multi_thread")]
async fn database_calls_enforce_grants_trust_ownership_and_uninstall_lifetime() {
let f = Harness::new();
// Nothing here tests the command budget, and a slow runner's first calls can exceed 250 ms.
let f = Harness::with_timeout(Duration::from_secs(10));
assert!(f.run("sources", None).is_err());
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let source = f.source();
+6 -1
Переглянути файл
@@ -64,13 +64,15 @@ pub struct TraceCollected {
}
pub trait StreamTracer: Send + Sync {
/// `plan` is the JSON of `ide_streams::RealRunPlan`; `budget` caps the records kept.
/// `plan` is the JSON of `ide_streams::RealRunPlan`; `budget` caps the records kept. `token`
/// names the trace for [`release_armed`](Self::release_armed) when no reply arrives.
fn arm<'a>(
&'a self,
target: &'a VmTarget,
thread_id: i64,
plan: &'a serde_json::Value,
budget: u32,
token: &'a str,
) -> InspectFuture<'a, TraceId>;
/// Blocks up to `ms` milliseconds for the trace to leave `Running`.
fn wait<'a>(&'a self, target: &'a VmTarget, trace: TraceId, ms: u32) -> InspectFuture<'a, TraceState>;
@@ -81,4 +83,7 @@ pub trait StreamTracer: Send + Sync {
/// with; reading each takes a round trip to the JVM, so the time allowed grows with them.
fn collect<'a>(&'a self, target: &'a VmTarget, trace: TraceId, records: u64) -> InspectFuture<'a, TraceCollected>;
fn release<'a>(&'a self, target: &'a VmTarget, trace: TraceId) -> InspectFuture<'a, ()>;
/// Releases the trace armed with `token` whose `arm` reply never came (it timed out); nothing
/// when there is none.
fn release_armed<'a>(&'a self, target: &'a VmTarget, token: &'a str) -> InspectFuture<'a, ()>;
}
+34 -3
Переглянути файл
@@ -73,6 +73,33 @@ pub struct SpellingRegion {
pub start: usize,
pub end: usize,
pub kind: SpellingKind,
/// A raw / verbatim string: backslashes are literal text, not escapes
/// (`r"\user"`, `r#"…"#`, `` `…` ``, `@"…"`). The spelling layer must not
/// skip the character after a `\` in one of these.
pub raw: bool,
}
/// Whether `node` is a string literal whose backslashes are not escapes.
fn is_raw_string(node: &Node<'_>, text: &str) -> bool {
let kind = node.kind();
// Rust/C++/C# grammars name the node directly.
if kind == "raw_string_literal" || kind == "verbatim_string_literal" || kind.contains("raw_string") {
return true;
}
// Go backtick strings and Python `r`/`fr`/`rb` prefixes: the grammar uses
// the generic `string` node, so inspect the literal's own prefix.
if kind == "string" || kind == "string_literal" {
let literal = &text[node.start_byte()..node.end_byte()];
if literal.starts_with('`') {
return true;
}
let quote = literal.find(['"', '\'']);
let prefix = quote.map_or("", |i| &literal[..i]);
return !prefix.is_empty()
&& prefix.chars().any(|c| c == 'r' || c == 'R')
&& prefix.chars().all(|c| matches!(c, 'r' | 'R' | 'b' | 'B' | 'f' | 'F' | 'u' | 'U'));
}
false
}
fn is_name_leaf(kind: &str) -> bool {
@@ -101,16 +128,20 @@ fn declares(cursor: &TreeCursor<'_>, node: &Node<'_>) -> bool {
}
/// Comments, string literals and declared names, for spell checking.
pub(crate) fn spelling_regions(tree: &Tree) -> Vec<SpellingRegion> {
pub(crate) fn spelling_regions(tree: &Tree, text: &str) -> Vec<SpellingRegion> {
let mut out = Vec::new();
let mut cursor = tree.walk();
loop {
let node = cursor.node();
let literal = kind_of(&node);
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind };
let region = |kind| SpellingRegion { start: node.start_byte(), end: node.end_byte(), kind, raw: false };
match literal {
Some(LiteralKind::Comment) => out.push(region(SpellingKind::Comment)),
Some(LiteralKind::String) => out.push(region(SpellingKind::String)),
Some(LiteralKind::String) => {
let mut r = region(SpellingKind::String);
r.raw = is_raw_string(&node, text);
out.push(r);
}
None if node.is_named()
&& node.child_count() == 0
&& is_name_leaf(node.kind())
+1 -1
Переглянути файл
@@ -294,7 +294,7 @@ impl Syntax {
/// Comments, string literals and declared names (byte ranges, document
/// order) for the Typo inspection; `None` like [`Self::literals`].
pub fn spelling_regions(&self, lang: &LanguageId, text: &str) -> Option<Vec<SpellingRegion>> {
self.analyze(lang, text, |_, tree, _| Some(literals::spelling_regions(tree)))
self.analyze(lang, text, |_, tree, text| Some(literals::spelling_regions(tree, text)))
}
/// Syntax-aware selection ranges for IDEA "Extend Selection" (⌥↑), innermost first.
+29
Переглянути файл
@@ -1422,6 +1422,35 @@ fn spelling_regions_cover_declared_names_only() {
assert_eq!(names, ["Bird", "fly", "text"]);
}
#[test]
fn spelling_regions_mark_raw_strings() {
let py = r#"a = r"\user" + R'\mesage' + fr"\wrd" + rb"\foo" + "\user""#;
let found: Vec<(&str, bool)> = syntax()
.spelling_regions(&lang("python"), py)
.unwrap()
.iter()
.filter(|r| r.kind == SpellingKind::String)
.map(|r| (&py[r.start..r.end], r.raw))
.collect();
assert_eq!(
found,
vec![
(r#"r"\user""#, true),
(r"R'\mesage'", true),
(r#"fr"\wrd""#, true),
(r#"rb"\foo""#, true),
(r#""\user""#, false),
]
);
// C# verbatim / Rust raw literals are named by the grammar itself.
let cs = r#"var s = @"C:\mesage";"#;
let raw = syntax().spelling_regions(&lang("csharp"), cs).unwrap().iter().any(|r| r.raw);
assert!(raw, "C# verbatim string should be raw");
let rs = r#"let s = r"\mesage";"#;
let raw = syntax().spelling_regions(&lang("rust"), rs).unwrap().iter().any(|r| r.raw);
assert!(raw, "Rust raw string should be raw");
}
// ---------------------------------------------------------------------------
// Script regions of Vue SFCs and HTML documents
+5
Переглянути файл
@@ -0,0 +1,5 @@
doctrine-mapping.xsd is from Doctrine ORM (https://github.com/doctrine/orm),
MIT License. Copyright (c) Doctrine Project.
The copy published at https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd
is broken (wrong targetNamespace / XMLSchema URI after an http→https rewrite);
this file is the upstream schema with the correct namespace.
+643
Переглянути файл
@@ -0,0 +1,643 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:orm="http://doctrine-project.org/schemas/orm/doctrine-mapping"
elementFormDefault="qualified">
<xs:annotation>
<xs:documentation><![CDATA[
This is the XML Schema for the object/relational
mapping file used by the Doctrine ORM.
]]></xs:documentation>
</xs:annotation>
<xs:element name="doctrine-mapping">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="mapped-superclass" type="orm:mapped-superclass" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="entity" type="orm:entity" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="embeddable" type="orm:embeddable" minOccurs="0" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
</xs:element>
<xs:complexType name="emptyType">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="cascade-type">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cascade-all" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-persist" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-merge" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-remove" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-refresh" type="orm:emptyType" minOccurs="0"/>
<xs:element name="cascade-detach" type="orm:emptyType" minOccurs="0"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="lifecycle-callback-type">
<xs:restriction base="xs:token">
<xs:enumeration value="prePersist"/>
<xs:enumeration value="postPersist"/>
<xs:enumeration value="preUpdate"/>
<xs:enumeration value="postUpdate"/>
<xs:enumeration value="preRemove"/>
<xs:enumeration value="postRemove"/>
<xs:enumeration value="postLoad"/>
<xs:enumeration value="preFlush"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="cache-usage-type">
<xs:restriction base="xs:token">
<xs:enumeration value="READ_ONLY"/>
<xs:enumeration value="READ_WRITE"/>
<xs:enumeration value="NONSTRICT_READ_WRITE"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="lifecycle-callback">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="type" type="orm:lifecycle-callback-type" use="required" />
<xs:attribute name="method" type="xs:NMTOKEN" use="required" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="lifecycle-callbacks">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="lifecycle-callback" type="orm:lifecycle-callback" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="named-query">
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="query" type="xs:string" use="required" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="named-queries">
<xs:sequence>
<xs:element name="named-query" type="orm:named-query" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="named-native-query">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="query" type="xs:string" minOccurs="1" maxOccurs="1"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="result-class" type="orm:fqcn" />
<xs:attribute name="result-set-mapping" type="xs:string" />
</xs:complexType>
<xs:complexType name="named-native-queries">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="named-native-query" type="orm:named-native-query" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="entity-listener">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="lifecycle-callback" type="orm:lifecycle-callback" minOccurs="0" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="class" type="orm:fqcn"/>
</xs:complexType>
<xs:complexType name="entity-listeners">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="entity-listener" type="orm:entity-listener" minOccurs="1" maxOccurs="unbounded" />
</xs:choice>
</xs:complexType>
<xs:complexType name="column-result">
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="field-result">
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="column" type="xs:string" />
</xs:complexType>
<xs:complexType name="entity-result">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="field-result" type="orm:field-result" minOccurs="0" maxOccurs="unbounded" />
</xs:choice>
<xs:attribute name="entity-class" type="orm:fqcn" use="required" />
<xs:attribute name="discriminator-column" type="xs:string" use="optional" />
</xs:complexType>
<xs:complexType name="sql-result-set-mapping">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="entity-result" type="orm:entity-result"/>
<xs:element name="column-result" type="orm:column-result"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
<xs:complexType name="sql-result-set-mappings">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="sql-result-set-mapping" type="orm:sql-result-set-mapping" minOccurs="1" maxOccurs="unbounded" />
</xs:choice>
</xs:complexType>
<xs:complexType name="cache">
<xs:attribute name="usage" type="orm:cache-usage-type" />
<xs:attribute name="region" type="xs:string" />
</xs:complexType>
<xs:complexType name="entity">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:element name="indexes" type="orm:indexes" minOccurs="0"/>
<xs:element name="unique-constraints" type="orm:unique-constraints" minOccurs="0"/>
<xs:element name="discriminator-column" type="orm:discriminator-column" minOccurs="0"/>
<xs:element name="discriminator-map" type="orm:discriminator-map" minOccurs="0"/>
<xs:element name="lifecycle-callbacks" type="orm:lifecycle-callbacks" minOccurs="0" maxOccurs="1" />
<xs:element name="entity-listeners" type="orm:entity-listeners" minOccurs="0" maxOccurs="1" />
<xs:element name="named-queries" type="orm:named-queries" minOccurs="0" maxOccurs="1" />
<xs:element name="named-native-queries" type="orm:named-native-queries" minOccurs="0" maxOccurs="1" />
<xs:element name="sql-result-set-mappings" type="orm:sql-result-set-mappings" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="id" type="orm:id" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="field" type="orm:field" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="embedded" type="orm:embedded" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="one-to-one" type="orm:one-to-one" minOccurs="0" maxOccurs="unbounded"/>
<xs:element name="one-to-many" type="orm:one-to-many" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="many-to-one" type="orm:many-to-one" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="many-to-many" type="orm:many-to-many" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="association-overrides" type="orm:association-overrides" minOccurs="0" maxOccurs="unbounded" />
<xs:element name="attribute-overrides" type="orm:attribute-overrides" minOccurs="0" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="table" type="orm:tablename" />
<xs:attribute name="schema" type="xs:NMTOKEN" />
<xs:attribute name="repository-class" type="orm:fqcn"/>
<xs:attribute name="inheritance-type" type="orm:inheritance-type"/>
<xs:attribute name="change-tracking-policy" type="orm:change-tracking-policy" />
<xs:attribute name="read-only" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="tablename" id="tablename">
<xs:restriction base="xs:token">
<xs:pattern value="[a-zA-Z_u01-uff.]+" id="tablename.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="option" mixed="true">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="option" type="orm:option"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="options">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="option" type="orm:option" minOccurs="0" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="mapped-superclass" >
<xs:complexContent>
<xs:extension base="orm:entity"/>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="embeddable">
<xs:complexContent>
<xs:extension base="orm:entity"/>
</xs:complexContent>
</xs:complexType>
<xs:simpleType name="change-tracking-policy">
<xs:restriction base="xs:token">
<xs:enumeration value="DEFERRED_IMPLICIT"/>
<xs:enumeration value="DEFERRED_EXPLICIT"/>
<xs:enumeration value="NOTIFY"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="inheritance-type">
<xs:restriction base="xs:token">
<xs:enumeration value="SINGLE_TABLE"/>
<xs:enumeration value="JOINED"/>
<xs:enumeration value="TABLE_PER_CLASS"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="generator-strategy">
<xs:restriction base="xs:token">
<xs:enumeration value="NONE"/>
<xs:enumeration value="SEQUENCE"/>
<xs:enumeration value="IDENTITY"/>
<xs:enumeration value="AUTO"/>
<xs:enumeration value="UUID"/>
<xs:enumeration value="CUSTOM" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="fk-action">
<xs:restriction base="xs:token">
<xs:enumeration value="CASCADE"/>
<xs:enumeration value="RESTRICT"/>
<xs:enumeration value="SET NULL"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="fetch-type">
<xs:restriction base="xs:token">
<xs:enumeration value="EAGER"/>
<xs:enumeration value="LAZY"/>
<xs:enumeration value="EXTRA_LAZY"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="generated-type">
<xs:restriction base="xs:token">
<xs:enumeration value="NEVER"/>
<xs:enumeration value="INSERT"/>
<xs:enumeration value="ALWAYS"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="orm:type" default="string" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="false" />
<xs:attribute name="insertable" type="xs:boolean" default="true" />
<xs:attribute name="updatable" type="xs:boolean" default="true" />
<xs:attribute name="generated" type="orm:generated-type" default="NEVER" />
<xs:attribute name="enum-type" type="xs:string" />
<xs:attribute name="version" type="xs:boolean" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="precision" type="xs:integer" use="optional" />
<xs:attribute name="scale" type="xs:integer" use="optional" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="embedded">
<xs:sequence>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="class" type="orm:fqcn" use="optional" />
<xs:attribute name="column-prefix" type="xs:string" use="optional" />
<xs:attribute name="use-column-prefix" type="xs:boolean" default="true" use="optional" />
</xs:complexType>
<xs:complexType name="discriminator-column">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="xs:NMTOKEN"/>
<xs:attribute name="field-name" type="xs:NMTOKEN" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="enum-type" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="unique-constraint">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
<xs:attribute name="columns" type="xs:string" use="optional"/>
<xs:attribute name="fields" type="xs:string" use="optional"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="unique-constraints">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="unique-constraint" type="orm:unique-constraint" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="index">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional"/>
<xs:attribute name="columns" type="xs:string" use="optional"/>
<xs:attribute name="fields" type="xs:string" use="optional"/>
<xs:attribute name="flags" type="xs:string" use="optional"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="indexes">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="index" type="orm:index" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="discriminator-mapping">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="value" type="orm:type" use="required"/>
<xs:attribute name="class" type="orm:fqcn" use="required"/>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="discriminator-map">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="discriminator-mapping" type="orm:discriminator-mapping" minOccurs="1" maxOccurs="unbounded"/>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="strategy" type="orm:generator-strategy" use="optional" default="AUTO" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="id">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="generator" type="orm:generator" minOccurs="0" />
<xs:element name="sequence-generator" type="orm:sequence-generator" minOccurs="0" maxOccurs="1" />
<xs:element name="custom-id-generator" type="orm:custom-id-generator" minOccurs="0" maxOccurs="1" />
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="type" type="orm:type" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="association-key" type="xs:boolean" default="false" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="sequence-generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="sequence-name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="allocation-size" type="xs:integer" use="optional" default="1" />
<xs:attribute name="initial-value" type="xs:integer" use="optional" default="1" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="custom-id-generator">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="class" type="orm:fqcn" use="required" />
</xs:complexType>
<xs:simpleType name="fqcn" id="fqcn">
<xs:restriction base="xs:token">
<xs:pattern value="[a-zA-Z_u01-uff][a-zA-Z0-9_u01-uff]+" id="fqcn.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="type" id="type">
<xs:restriction base="xs:token">
<xs:pattern value="([a-zA-Z_u01-uff][a-zA-Z0-9_u01-uff]+)|(\c+)" id="type.class.pattern">
</xs:pattern>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="inverse-join-columns">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-column" type="orm:join-column" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-column">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="optional" />
<xs:attribute name="referenced-column-name" type="xs:NMTOKEN" use="optional" default="id" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="true" />
<xs:attribute name="on-delete" type="orm:fk-action" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-columns">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-column" type="orm:join-column" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="join-table">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-columns" type="orm:join-columns" />
<xs:element name="inverse-join-columns" type="orm:join-columns" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="schema" type="xs:NMTOKEN" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="order-by">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="order-by-field" type="orm:order-by-field" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="order-by-field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="direction" type="orm:order-by-direction" default="ASC" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:simpleType name="order-by-direction">
<xs:restriction base="xs:token">
<xs:enumeration value="ASC"/>
<xs:enumeration value="DESC"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="columntoken" id="columntoken">
<xs:restriction base="xs:token">
<xs:pattern value="[-._:A-Za-z0-9`]+" id="columntoken.pattern"/>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="many-to-many">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:element name="join-table" type="orm:join-table" minOccurs="0" />
<xs:element name="order-by" type="orm:order-by" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" use="required" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="index-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="one-to-many">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:element name="order-by" type="orm:order-by" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" use="required" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" use="required" />
<xs:attribute name="index-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="many-to-one">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:choice minOccurs="0" maxOccurs="1">
<xs:element name="join-column" type="orm:join-column"/>
<xs:element name="join-columns" type="orm:join-columns"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="one-to-one">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="cache" type="orm:cache" minOccurs="0" maxOccurs="1"/>
<xs:element name="cascade" type="orm:cascade-type" minOccurs="0" />
<xs:choice minOccurs="0" maxOccurs="1">
<xs:element name="join-column" type="orm:join-column"/>
<xs:element name="join-columns" type="orm:join-columns"/>
</xs:choice>
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="field" type="xs:NMTOKEN" use="required" />
<xs:attribute name="target-entity" type="xs:string" />
<xs:attribute name="mapped-by" type="xs:NMTOKEN" />
<xs:attribute name="inversed-by" type="xs:NMTOKEN" />
<xs:attribute name="fetch" type="orm:fetch-type" default="LAZY" />
<xs:attribute name="orphan-removal" type="xs:boolean" default="false" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
<xs:complexType name="association-overrides">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="association-override" type="orm:association-override" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="association-override">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="join-table" type="orm:join-table" minOccurs="0" />
<xs:element name="join-columns" type="orm:join-columns" minOccurs="0" />
<xs:element name="inversed-by" type="orm:inversed-by-override" minOccurs="0" maxOccurs="1" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
<xs:attribute name="fetch" type="orm:fetch-type" use="optional" />
</xs:complexType>
<xs:complexType name="inversed-by-override">
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
</xs:complexType>
<xs:complexType name="attribute-overrides">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="attribute-override" type="orm:attribute-override" minOccurs="1" maxOccurs="unbounded" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="attribute-override">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="field" type="orm:attribute-override-field" minOccurs="1" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="name" type="xs:NMTOKEN" use="required" />
</xs:complexType>
<xs:complexType name="attribute-override-field">
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="options" type="orm:options" minOccurs="0" />
<xs:any minOccurs="0" maxOccurs="unbounded" namespace="##other"/>
</xs:choice>
<xs:attribute name="type" type="orm:type" default="string" />
<xs:attribute name="column" type="orm:columntoken" />
<xs:attribute name="length" type="xs:NMTOKEN" />
<xs:attribute name="unique" type="xs:boolean" default="false" />
<xs:attribute name="nullable" type="xs:boolean" default="false" />
<xs:attribute name="insertable" type="xs:boolean" default="true" />
<xs:attribute name="updateable" type="xs:boolean" default="true" />
<xs:attribute name="version" type="xs:boolean" />
<xs:attribute name="column-definition" type="xs:string" />
<xs:attribute name="precision" type="xs:integer" use="optional" />
<xs:attribute name="scale" type="xs:integer" use="optional" />
<xs:anyAttribute namespace="##other"/>
</xs:complexType>
</xs:schema>
+27 -25
Переглянути файл
@@ -1025,36 +1025,38 @@ impl LspManager {
.map_err(|e| IdeError::internal(e.to_string()))
}
/// jdtls' document for class file `entry` of archive `jar`, from its Java model. With
/// `any_archive`, the one class of that name the model has when it knows `jar` by another path.
pub(crate) async fn archive_class(&self, jar: PathBuf, entry: String, any_archive: bool) -> IdeResult<String> {
let cancel = CancellationToken::new();
self.jdtls(&self.project_root, &cancel).await?;
let entry =
entry.strip_prefix("META-INF/versions/").and_then(|s| s.split_once('/').map(|(_, s)| s)).unwrap_or(&entry);
let class = entry.strip_suffix(".class").ok_or_else(|| IdeError::not_found("expected a class file"))?;
let outer = class.split('$').next().unwrap_or(class);
let (package, name) = outer.rsplit_once('/').unwrap_or(("", outer));
let query = outer.replace('/', ".");
let symbols = self.workspace_symbols(&query, cancel).await?;
let package = package.replace('/', ".");
let name = name.to_owned();
let outer = outer.to_owned();
tokio::task::spawn_blocking(move || {
let uris = symbols.into_iter().filter_map(|s| s.location.uri);
crate::virtual_doc::pick_class(uris, &jar, &package, &name, any_archive)
.ok_or_else(|| IdeError::not_found(format!("jdtls could not resolve {} in {}", outer, jar.display())))
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Resolve a disk/archive class to project source or the server's binary document.
/// Archive URIs must come from JDT's Java model: fabricated handles cannot map debug lines.
pub async fn java_class_file(&self, path: &Path, archive: Option<(PathBuf, String)>) -> IdeResult<String> {
if let Some((jar, entry)) = archive {
return self.archive_class(jar, entry, false).await;
}
let cancel = CancellationToken::new();
self.jdtls(&self.project_root, &cancel).await?;
if let Some((jar, entry)) = archive {
let entry = entry
.strip_prefix("META-INF/versions/")
.and_then(|s| s.split_once('/').map(|(_, s)| s))
.unwrap_or(&entry);
let class = entry.strip_suffix(".class").ok_or_else(|| IdeError::not_found("expected a class file"))?;
let outer = class.split('$').next().unwrap_or(class);
let (package, name) = outer.rsplit_once('/').unwrap_or(("", outer));
let query = outer.replace('/', ".");
let symbols = self.workspace_symbols(&query, cancel).await?;
let package = package.replace('/', ".");
let name = name.to_owned();
let outer = outer.to_owned();
return tokio::task::spawn_blocking(move || {
symbols
.into_iter()
.filter_map(|s| s.location.uri)
.find(|uri| crate::virtual_doc::matches_class(uri, &jar, &package, &name))
.ok_or_else(|| {
IdeError::not_found(format!("jdtls could not resolve {} in {}", outer, jar.display()))
})
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
}
let uri = crate::uri::path_to_uri_string(path);
// classFileContents accepts file URIs, but java-debug's line mapping only accepts JDT handles.
let doc = self.virtual_document(&uri).await?;
+9 -1
Переглянути файл
@@ -182,9 +182,10 @@ impl StreamTracer for JdtStreamTracer {
thread_id: i64,
plan: &'a Value,
budget: u32,
token: &'a str,
) -> InspectFuture<'a, TraceId> {
Box::pin(async move {
let args = json!({"threadId": thread_id, "plan": plan, "budget": budget});
let args = json!({"threadId": thread_id, "plan": plan, "budget": budget, "token": token});
Ok(self.call::<Armed>("arm", target, args, COMMAND_TIMEOUT).await?.trace_id)
})
}
@@ -223,6 +224,13 @@ impl StreamTracer for JdtStreamTracer {
self.call::<Value>("release", target, json!({"traceId": trace}), COMMAND_TIMEOUT).await.map(drop)
})
}
fn release_armed<'a>(&'a self, target: &'a VmTarget, token: &'a str) -> InspectFuture<'a, ()> {
Box::pin(async move {
// Waits for an arm still setting up: as long as an arm may take.
self.call::<Value>("release", target, json!({"token": token}), COMMAND_TIMEOUT).await.map(drop)
})
}
}
#[cfg(test)]
+14 -3
Переглянути файл
@@ -40,6 +40,7 @@ mod uri;
mod virtual_doc;
mod vue_navigation;
mod vue_refs;
mod xml_catalog;
pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES};
pub use inspect::{CheckedServer, DocumentCheck, FileInspection, InspectHost, InspectOptions};
@@ -1810,9 +1811,16 @@ impl LspManager {
out.push(loc);
continue;
};
let Ok(uri) = self.java_class_file(Path::new(""), Some((entry.jar, entry.entry))).await else {
out.push(loc);
continue;
// The Kotlin server may name the jar by another path than jdtls (its own copy of a
// `system`-scope jar): its stub would be all the user gets, so take jdtls' only class
// of that name.
let uri = match self.archive_class(entry.jar, entry.entry, true).await {
Ok(uri) => uri,
Err(e) => {
tracing::info!("library class stays a stub: {}", e.message);
out.push(loc);
continue;
}
};
let range = match (&name, self.virtual_document(&uri).await) {
(Some(name), Ok(doc)) => library_source::declaration_range(&doc.text, name),
@@ -3795,6 +3803,9 @@ impl LspManager {
if cfg.name == compose::SERVER {
compose::configure_yaml_compose_schemas(&mut cfg, &self.open_compose_files());
}
if cfg.name == xml_catalog::SERVER {
xml_catalog::configure_lemminx_catalogs(&mut cfg);
}
cfg
}
+63 -2
Переглянути файл
@@ -197,12 +197,17 @@ pub(crate) fn archive_modified(uri: &str) -> Option<std::time::SystemTime> {
std::fs::metadata(archive(uri)?).and_then(|m| m.modified()).ok()
}
/// Check both the package and actual archive, so duplicate type names never pick another jar.
pub(crate) fn matches_class(uri: &str, jar: &std::path::Path, package: &str, name: &str) -> bool {
/// Whether `uri` is jdtls' class `package.name`, in any archive.
pub(crate) fn matches_class_name(uri: &str, package: &str, name: &str) -> bool {
let segs = segments(uri);
scheme(uri) == "jdt"
&& (package.is_empty() && segs.len() == 3 || segs.get(2).is_some_and(|s| s == package))
&& segs.last().is_some_and(|s| s == &format!("{name}.class") || s == &format!("{name}.java"))
}
/// Check both the package and actual archive, so duplicate type names never pick another jar.
pub(crate) fn matches_class(uri: &str, jar: &std::path::Path, package: &str, name: &str) -> bool {
matches_class_name(uri, package, name)
&& description(uri).is_some_and(|p| {
let path = std::path::Path::new(&p);
path == jar
@@ -210,12 +215,68 @@ pub(crate) fn matches_class(uri: &str, jar: &std::path::Path, package: &str, nam
})
}
/// jdtls' document for class `package.name` of archive `jar` among `uris`. With `any_archive`,
/// when the caller names the archive by another path than the Java model does (a copy another
/// server made of a `system`-scope jar, say), the one class of that name in the model; with
/// several, none rather than another jar's.
pub(crate) fn pick_class(
uris: impl IntoIterator<Item = String>,
jar: &std::path::Path,
package: &str,
name: &str,
any_archive: bool,
) -> Option<String> {
let named: Vec<String> = uris.into_iter().filter(|uri| matches_class_name(uri, package, name)).collect();
if let Some(uri) = named.iter().find(|uri| matches_class(uri, jar, package, name)) {
return Some(uri.clone());
}
match named.as_slice() {
[only] if any_archive => Some(only.clone()),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
const JDT: &str = "jdt://contents/spring-boot-4.1.1.jar/org.springframework.boot/SpringApplication.class?=spring-demo/%5C/Users%5C/me%5C/.m2%5C/repository%5C/spring-boot-4.1.1.jar%3Corg.springframework.boot%28SpringApplication.class";
#[test]
fn picks_the_class_of_the_archive_or_the_only_one_of_that_name() {
let jdt = |jar: &str, file: &str| {
format!(
"jdt://contents/{file}/org.springframework.boot/SpringApplication.class?=demo/%5C/repo%5C/{jar}%3Corg.springframework.boot%28SpringApplication.class"
)
};
let (a, b) = (jdt("a.jar", "a.jar"), jdt("b.jar", "b.jar"));
let pick = |uris: &[&String], jar: &str| {
pick_class(
uris.iter().map(|u| (*u).clone()),
std::path::Path::new(jar),
"org.springframework.boot",
"SpringApplication",
true,
)
};
assert_eq!(pick(&[&a, &b], "/repo/b.jar"), Some(b.clone()));
// Another path for the archive: the only class of that name.
assert_eq!(pick(&[&a], "/elsewhere/copy.jar"), Some(a.clone()));
// Two candidates and neither archive matches: none rather than a guess.
assert_eq!(pick(&[&a, &b], "/elsewhere/copy.jar"), None);
let other = JDT.replace("SpringApplication.class", "Banner.class");
assert_eq!(pick(&[&other], "/elsewhere/copy.jar"), None);
// Strict: only the named archive.
let strict = pick_class(
[a.clone()],
std::path::Path::new("/elsewhere/copy.jar"),
"org.springframework.boot",
"SpringApplication",
false,
);
assert_eq!(strict, None);
}
#[test]
fn class_stubs_in_java_or_kotlin() {
let java = "// IntelliJ API Decompiler stub source generated from a class file\n\npackage com.boydti.fawe.util;\n\npublic class EditSessionBuilder {\n}\n";
+149
Переглянути файл
@@ -0,0 +1,149 @@
//! Bundled XML catalogs for LemMinX so known-broken remote XSDs resolve locally.
//!
//! Doctrine's hosted `doctrine-mapping.xsd` advertises the wrong `targetNamespace`
//! (the schema URL itself) after an http→https rewrite, so any mapping file that
//! points `xsi:schemaLocation` at that URL fails with `TargetNamespace.1` /
//! `cvc-elt.1.a`. An OASIS catalog maps the namespace and those system IDs to the
//! correct upstream schema we ship.
use ide_language::LanguageServerConfig;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
pub const SERVER: &str = "lemminx";
const DOCTRINE_XSD: &str = include_str!("../schemas/xml/doctrine-mapping.xsd");
const CATALOG_TEMPLATE: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<uri name="http://doctrine-project.org/schemas/orm/doctrine-mapping" uri="doctrine-mapping.xsd"/>
<uri name="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
<system systemId="https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
<system systemId="http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd" uri="doctrine-mapping.xsd"/>
</catalog>
"#;
/// Writes the bundled catalog (idempotent) and prepends it to LemMinX `xml.catalogs`.
pub fn configure_lemminx_catalogs(cfg: &mut LanguageServerConfig) {
if cfg.name != SERVER {
return;
}
let Some(catalog) = ensure_catalog() else { return };
let catalog = path_for_settings(&catalog);
let mut settings = cfg.settings.take().filter(Value::is_object).unwrap_or_else(|| json!({}));
let Some(root) = settings.as_object_mut() else {
cfg.settings = Some(settings);
return;
};
let Some(xml) = root.entry("xml").or_insert_with(|| json!({})).as_object_mut() else {
cfg.settings = Some(settings);
return;
};
let Some(catalogs) = xml.entry("catalogs").or_insert_with(|| json!([])).as_array_mut() else {
cfg.settings = Some(settings);
return;
};
if catalogs.iter().any(|v| v.as_str() == Some(catalog.as_str())) {
cfg.settings = Some(settings);
return;
}
catalogs.insert(0, Value::String(catalog));
cfg.settings = Some(settings);
}
fn ensure_catalog() -> Option<PathBuf> {
// Per-pid directory: shared `/tmp/openidea-xml-catalog` would let another
// local user plant a catalog that remaps arbitrary schema URIs.
let dir = std::env::temp_dir().join(format!("openidea-xml-catalog-{}", std::process::id()));
if let Err(e) = ide_vfs::create_private_dir(&dir) {
tracing::warn!("xml catalog: cannot create {}: {e}", dir.display());
return None;
}
let xsd = dir.join("doctrine-mapping.xsd");
if !write_if_changed(&xsd, DOCTRINE_XSD.as_bytes()) {
tracing::warn!("xml catalog: cannot write {}", xsd.display());
return None;
}
let catalog = dir.join("catalog.xml");
if !write_if_changed(&catalog, CATALOG_TEMPLATE.as_bytes()) {
tracing::warn!("xml catalog: cannot write {}", catalog.display());
return None;
}
Some(catalog)
}
fn write_if_changed(path: &Path, bytes: &[u8]) -> bool {
if std::fs::read(path).ok().as_deref() == Some(bytes) {
return true;
}
ide_vfs::write_atomic_private(path, bytes).is_ok()
}
fn path_for_settings(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
#[cfg(test)]
mod tests {
use super::*;
use ide_language::LanguageRegistry;
const DOCTRINE_NS: &str = "http://doctrine-project.org/schemas/orm/doctrine-mapping";
const DOCTRINE_SCHEMA_HTTPS: &str = "https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd";
const DOCTRINE_SCHEMA_HTTP: &str = "http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd";
#[test]
fn bundled_xsd_keeps_http_namespace() {
assert!(DOCTRINE_XSD.contains(&format!("targetNamespace=\"{DOCTRINE_NS}\"")));
assert!(!DOCTRINE_XSD.contains("xmlns:xs=\"https://www.w3.org/2001/XMLSchema\""));
assert!(!DOCTRINE_XSD.contains("targetNamespace=\"https://www.doctrine-project.org"));
}
#[test]
fn catalog_maps_namespace_and_system_ids() {
assert!(CATALOG_TEMPLATE.contains(&format!(r#"name="{DOCTRINE_NS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"name="{DOCTRINE_SCHEMA_HTTPS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"systemId="{DOCTRINE_SCHEMA_HTTPS}""#)));
assert!(CATALOG_TEMPLATE.contains(&format!(r#"systemId="{DOCTRINE_SCHEMA_HTTP}""#)));
assert_eq!(CATALOG_TEMPLATE.matches(r#"uri="doctrine-mapping.xsd""#).count(), 4);
}
#[test]
fn prepends_catalog_without_dropping_user_entries() {
let reg = LanguageRegistry::load(None).unwrap();
let xml = reg.get(&ide_core::LanguageId::new("xml")).unwrap();
let mut cfg = xml.language_servers[0].clone();
cfg.settings = Some(json!({"xml": {"catalogs": ["/user/catalog.xml"]}}));
configure_lemminx_catalogs(&mut cfg);
let list: Vec<String> = cfg.settings.as_ref().unwrap()["xml"]["catalogs"]
.as_array()
.unwrap()
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
assert_eq!(list.len(), 2);
assert!(list[0].ends_with("catalog.xml"));
assert!(list[0].contains(&format!("openidea-xml-catalog-{}", std::process::id())));
assert_eq!(list[1], "/user/catalog.xml");
configure_lemminx_catalogs(&mut cfg);
assert_eq!(cfg.settings.as_ref().unwrap()["xml"]["catalogs"].as_array().unwrap().len(), 2);
let catalog = PathBuf::from(&list[0]);
let body = std::fs::read_to_string(&catalog).unwrap();
assert_eq!(body, CATALOG_TEMPLATE);
assert!(body.contains(&format!(r#"name="{DOCTRINE_NS}""#)));
let xsd = catalog.with_file_name("doctrine-mapping.xsd");
assert_eq!(std::fs::read_to_string(xsd).unwrap(), DOCTRINE_XSD);
}
#[test]
fn ignores_other_servers() {
let reg = LanguageRegistry::load(None).unwrap();
let yaml = reg.get(&ide_core::LanguageId::new("yaml")).unwrap();
let mut cfg = yaml.language_servers[0].clone();
let before = cfg.settings.clone();
configure_lemminx_catalogs(&mut cfg);
assert_eq!(cfg.settings, before);
}
}
+9 -3
Переглянути файл
@@ -3193,7 +3193,7 @@ async fn stream_commands_send_target_then_named_fields() {
let plan = json!({"root": {"line": 14}});
s.respond("workspace/executeCommand", json!({"ok": {"traceId": 3}}));
assert_eq!(tracer.arm(&target, 7, &plan, 500).await.unwrap(), 3);
assert_eq!(tracer.arm(&target, 7, &plan, 500, "t1").await.unwrap(), 3);
s.respond(
"workspace/executeCommand",
json!({"ok": {"state": "running", "records": 1, "dropped": 0, "elapsedMs": 2}}),
@@ -3211,18 +3211,24 @@ async fn stream_commands_send_target_then_named_fields() {
tracer.collect(&target, 3, 2).await.unwrap();
s.respond("workspace/executeCommand", json!({"ok": {}}));
tracer.release(&target, 3).await.unwrap();
s.respond("workspace/executeCommand", json!({"ok": {}}));
tracer.release_armed(&target, "t1").await.unwrap();
let asked = s.requested("workspace/executeCommand");
let seen: Vec<_> = asked.iter().map(|p| (p["command"].clone(), p["arguments"].clone())).collect();
assert_eq!(
seen,
vec![
(json!("openidea.jvm.stream.arm"), json!([target_json, {"threadId": 7, "plan": plan, "budget": 500}])),
(
json!("openidea.jvm.stream.arm"),
json!([target_json, {"threadId": 7, "plan": plan, "budget": 500, "token": "t1"}])
),
(json!("openidea.jvm.stream.wait"), json!([target_json, {"traceId": 3, "ms": 250}])),
(json!("openidea.jvm.stream.stop"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.abort"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.collect"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.release"), json!([target_json, {"traceId": 3}])),
(json!("openidea.jvm.stream.release"), json!([target_json, {"token": "t1"}])),
]
);
}
@@ -3303,7 +3309,7 @@ async fn stream_errors_map() {
];
for (reply, expected) in cases {
s.respond("workspace/executeCommand", reply.clone());
assert_eq!(tracer.arm(&target, 1, &json!({}), 10).await.unwrap_err(), expected, "{reply}");
assert_eq!(tracer.arm(&target, 1, &json!({}), 10, "t").await.unwrap_err(), expected, "{reply}");
}
}
+105 -13
Переглянути файл
@@ -21,9 +21,11 @@
<body>
<canvas id="map"></canvas>
<script>
// A minimal minimap over `openidea.editor`: each line 2px high, each character 1px wide,
// in its highlight colour; the visible area as a frame that can be dragged; the wheel
// scrolls the editor.
// A minimal minimap over `openidea.editor`: each line 2px high, each character 1px wide (tabs
// as wide as the editor draws them), in its highlight colour; the visible area as a frame that
// can be dragged; the wheel scrolls the editor; the marker bar's problems as bars at the right
// edge; folded lines left out; the selected lines tinted and the caret's line marked; VCS
// changes at the left edge.
const editor = window.openidea.editor;
const canvas = document.getElementById("map");
const ctx = canvas.getContext("2d");
@@ -33,6 +35,13 @@
let colors = new Map();
let loading = new Set();
let view = null;
let problems = [];
let folds = [];
let selections = [];
let changes = [];
let tabSize = 4;
const PROBLEM_COLOR = { error: "--openidea-danger", warning: "--openidea-warning" };
const PROBLEM_RANK = { error: 2, warning: 1 };
let drag = null;
let queued = false;
@@ -40,19 +49,48 @@
const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(color);
return !!m && Math.max(m[1], m[2], m[3]) - Math.min(m[1], m[2], m[3]) < 24;
};
// Column → x, with tabs expanded to the editor's tab stops.
const xOf = (line) => {
if (!line.includes("\t")) return (c) => c;
const xs = [0];
for (let i = 0, x = 0; i < line.length; i++) xs.push((x += line[i] === "\t" ? tabSize - (x % tabSize) : 1));
return (c) => xs[Math.min(c, line.length)];
};
const cssVar = (name) => (window.openidea.theme && window.openidea.theme.vars[name]) || "";
// Document lines ↔ minimap rows, without the lines folds hide (fractional within a fold's row).
const rowOf = (line) => {
let hidden = 0;
for (const f of folds) {
if (line >= f.toLine + 1) hidden += f.toLine - f.fromLine;
else if (line > f.fromLine) return f.fromLine - hidden + (line - f.fromLine) / (f.toLine + 1 - f.fromLine);
else break;
}
return line - hidden;
};
const lineOfRow = (row) => {
let hidden = 0;
for (const f of folds) {
const r = f.fromLine - hidden;
if (row >= r + 1) hidden += f.toLine - f.fromLine;
else if (row > r) return f.fromLine + (row - r) * (f.toLine + 1 - f.fromLine);
else break;
}
return row + hidden;
};
function layout() {
const H = canvas.clientHeight;
if (!view) return { H, offset: 0, top: 0, height: 0, range: 1, visible: 0 };
const L = Math.max(1, view.lineCount);
const visible = Math.max(0, view.lastLine - view.firstLine);
const L = Math.max(1, rowOf(view.lineCount));
const firstRow = rowOf(view.firstLine);
const visible = Math.max(0, rowOf(view.lastLine) - firstRow);
const scrollable = Math.max(1, view.scrollHeight - view.clientHeight);
const p = Math.min(1, Math.max(0, view.scrollTop / scrollable));
const mapH = L * LINE;
const offset = p * Math.max(0, mapH - H);
const range = Math.max(1, Math.min(H, mapH) - visible * LINE);
return { H, offset, top: view.firstLine * LINE - offset, height: visible * LINE, range, visible, L };
return { H, offset, top: firstRow * LINE - offset, height: visible * LINE, range, visible, L };
}
function redraw() {
@@ -65,7 +103,7 @@
queued = false;
const dpr = window.devicePixelRatio || 1;
const W = canvas.clientWidth;
const { H, offset, top, height } = layout();
const { H, offset, top, height, L } = layout();
if (canvas.width !== Math.round(W * dpr) || canvas.height !== Math.round(H * dpr)) {
canvas.width = Math.round(W * dpr);
canvas.height = Math.round(H * dpr);
@@ -74,16 +112,28 @@
ctx.clearRect(0, 0, W, H);
if (!view) return;
const first = Math.floor(offset / LINE);
const last = Math.min(text.length, Math.ceil((offset + H) / LINE));
const last = Math.min(L, Math.ceil((offset + H) / LINE));
const missing = [];
const muted = cssVar("--openidea-fg-muted");
for (let i = first; i < last; i++) {
const y = i * LINE - offset;
// Selections under the text: the lines they cover tinted, a caret's line a stronger strip.
ctx.fillStyle = cssVar("--openidea-accent");
for (const s of selections) {
const caret = s.anchor.line === s.head.line && s.anchor.column === s.head.column;
const from = Math.floor(rowOf(Math.min(s.anchor.line, s.head.line)));
const to = Math.floor(rowOf(Math.max(s.anchor.line, s.head.line)));
ctx.globalAlpha = caret ? 0.6 : 0.3;
ctx.fillRect(0, from * LINE - offset, W, (to - from + 1) * LINE);
}
ctx.globalAlpha = 1;
for (let row = first; row < last; row++) {
const i = lineOfRow(row);
const y = row * LINE - offset;
const line = text[i] || "";
const x = xOf(line);
// Text without a syntax colour: faint, so the coloured spans stand out.
ctx.globalAlpha = 0.2;
ctx.fillStyle = muted;
for (const m of line.matchAll(/\S+/g)) ctx.fillRect(m.index, y, m[0].length, LINE - 0.5);
for (const m of line.matchAll(/\S+/g)) ctx.fillRect(x(m.index), y, m[0].length, LINE - 0.5);
ctx.globalAlpha = 1;
const spans = colors.get(i);
if (!spans) missing.push(i);
@@ -92,9 +142,23 @@
// Greys (the plain text colour, comments) stay as faint as uncoloured text.
if (grey(s.color)) continue;
ctx.fillStyle = s.color;
ctx.fillRect(s.from, y, s.to - s.from, LINE - 0.5);
ctx.fillRect(x(s.from), y, x(s.to) - x(s.from), LINE - 0.5);
}
}
// Changes in the gutter's colours: a bar over changed lines, a notch where lines were deleted.
for (const c of changes) {
ctx.fillStyle = cssVar(`--openidea-change-${c.kind}`);
const y = Math.floor(rowOf(c.line)) * LINE - offset;
if (c.kind === "deleted") ctx.fillRect(0, y - 1, 4, 2);
else ctx.fillRect(0, y, 2, (Math.floor(rowOf(c.lastLine)) - Math.floor(rowOf(c.line)) + 1) * LINE);
}
// Problems: errors drawn last, on top; weak warnings in the muted colour.
const ranked = [...problems].sort((a, b) => (PROBLEM_RANK[a.severity] || 0) - (PROBLEM_RANK[b.severity] || 0));
for (const p of ranked) {
ctx.fillStyle = cssVar(PROBLEM_COLOR[p.severity] || "--openidea-fg-muted");
const y = Math.floor(rowOf(p.line));
ctx.fillRect(W - 3, y * LINE - offset, 3, Math.max(LINE, (Math.floor(rowOf(p.lastLine)) - y + 1) * LINE));
}
// The visible area: a light accent tint and a 1px border, stronger while dragged.
const frameH = Math.max(height, 4);
ctx.fillStyle = cssVar("--openidea-accent");
@@ -132,8 +196,15 @@
view = null;
return redraw();
}
// `tabSize` is API 1.10.
tabSize = target.tabSize || 4;
const doc = await editor.document.get();
text = doc.text.split("\n");
// `problems` is API 1.10.
problems = editor.problems ? await editor.problems() : [];
folds = editor.folded ? await editor.folded() : [];
selections = editor.selections ? await editor.selections() : [];
changes = editor.changes ? await editor.changes() : [];
view = Object.assign(await editor.viewport(), { version: target.version });
redraw();
}
@@ -151,6 +222,27 @@
for (const k of [...colors.keys()]) if (k >= fromLine && k < toLine) colors.delete(k);
redraw();
});
if (editor.onProblems)
editor.onProblems((p) => {
problems = p;
redraw();
});
// `onLayout` is API 1.10.
if (editor.onLayout)
editor.onLayout((l) => {
folds = l.folded;
redraw();
});
if (editor.onSelections)
editor.onSelections((s) => {
selections = s;
redraw();
});
if (editor.onChanges)
editor.onChanges((c) => {
changes = c;
redraw();
});
window.openidea.onThemeChange(redraw);
new ResizeObserver(redraw).observe(canvas);
@@ -158,7 +250,7 @@
const scrollToFrameTop = (frameTop) => {
const { range, visible, L } = layout();
const p = Math.min(1, Math.max(0, frameTop / range));
void editor.scrollTo(p * Math.max(0, L - visible));
void editor.scrollTo(lineOfRow(p * Math.max(0, L - visible)));
};
canvas.addEventListener("pointerdown", (e) => {
if (!view) return;
+10 -4
Переглянути файл
@@ -26,9 +26,13 @@ pub fn init_script(jvm_args: &[String]) -> String {
let list = jvm_args.iter().map(|a| groovy_string(a)).collect::<Vec<_>>().join(", ");
format!(
"// Written by OpenIDEA: VM options of the run configuration.\n\
import org.gradle.util.GradleVersion\n\
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.\n\
def each = {{ tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? \
tasks.configureEach(action) : tasks.all(action) }}\n\
allprojects {{\n \
tasks.withType(JavaExec).configureEach {{ jvmArgs([{list}]) }}\n \
tasks.withType(Test).configureEach {{ jvmArgs([{list}]) }}\n\
each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \
each(tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\
}}\n"
)
}
@@ -75,8 +79,10 @@ mod tests {
fn adds_each_argument_to_java_exec_and_test_tasks() {
let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"]));
let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']";
assert!(script.contains(&format!("tasks.withType(JavaExec).configureEach {{ jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("tasks.withType(Test).configureEach {{ jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("each(tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
// Gradle before 4.9 has no `configureEach` (#3864).
assert!(script.contains("? tasks.configureEach(action) : tasks.all(action)"), "{script}");
}
#[test]
+27 -1
Переглянути файл
@@ -53,6 +53,12 @@ struct JavaProbe {
static JAVA_PROBES: Mutex<BTreeMap<PathBuf, JavaProbe>> = Mutex::new(BTreeMap::new());
/// How long `java -version` may take before the JDK counts as unable to run. The first
/// run of a JDK can be slow: Rosetta translates an x86_64 JDK on Apple silicon, and
/// malware scans check a freshly downloaded one. Excluded, a project's JDK 8 leaves its
/// `JavaSE-1.8` to a newer JDK, and APIs JDK 8 has (`jdk.nashorn`) stop resolving.
const JAVA_PROBE_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(8) } else { Duration::from_secs(30) };
/// Metadata can describe a JDK built for another architecture. Probe the executable
/// before giving it to JDT, with a short cache shared by server and project selection.
pub(crate) fn java_runs(java: &Path) -> bool {
@@ -72,7 +78,7 @@ pub(crate) fn java_runs(java: &Path) -> bool {
return probe.runnable;
}
}
let runnable = crate::exec::query(java, &["-version"], Duration::from_secs(5)).is_some();
let runnable = crate::exec::query(java, &["-version"], JAVA_PROBE_TIMEOUT).is_some();
JAVA_PROBES.lock().unwrap_or_else(|e| e.into_inner()).insert(
java.to_path_buf(),
JavaProbe { modified, len: metadata.len(), permissions: metadata.permissions(), at: Instant::now(), runnable },
@@ -980,6 +986,26 @@ mod tests {
assert_eq!(std::fs::read_to_string(&probes).unwrap().lines().count(), 1, "probed once");
}
#[cfg(unix)]
#[test]
fn a_jdk_8_slow_on_its_first_run_stays_the_java_8_runtime() {
let tmp = tempfile::tempdir().unwrap();
let jdk8 = test_jdk(tmp.path(), 8, "rosetta8");
let jdk25 = test_jdk(tmp.path(), 25, "native25");
// Longer than the 5 seconds a first run under Rosetta used to be allowed.
std::fs::write(
java_executable(&jdk8.home),
"#!/bin/sh
/bin/sleep 6
echo 'openjdk version 1.8'
",
)
.unwrap();
let rt = runtimes(&[jdk8.clone(), jdk25.clone()]);
assert_eq!(rt[0], json!({ "name": "JavaSE-1.8", "path": jdk8.home }));
assert_eq!(rt[1]["name"], "JavaSE-25");
}
#[cfg(unix)]
#[test]
fn slow_java_probe_does_not_hold_the_cache_lock() {
+172
Переглянути файл
@@ -0,0 +1,172 @@
//! jdtls workspaces (`<local data>/lsp/jdtls/<key>`) that no project uses any more.
//!
//! A workspace is keyed by the project folder and by the settings that need a clean import
//! (source paths, output folder, libraries, linked Gradle projects, unlinked Maven poms), so
//! each change of those, and each moved or deleted project, leaves the previous workspace
//! behind: 50–200 MB of imported model and indexes. Like a cache, one unused for a month is
//! removed at start-up; a project that comes back imports again.
use ide_language::LanguageServerConfig;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
/// Touched each time jdtls starts on a workspace.
const USED_MARKER: &str = ".openidea-last-used";
/// Workspaces being removed (renamed first, so a server never starts on a half-deleted one).
const TRASH_PREFIX: &str = ".removed-";
/// How long a workspace may go unused before start-up removes it.
pub const UNUSED_FOR: Duration = Duration::from_secs(30 * 24 * 60 * 60);
fn root(data_dir: &Path) -> PathBuf {
data_dir.join("lsp").join("jdtls")
}
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder).
pub fn mark_used(cfg: &LanguageServerConfig) {
let Some(dir) = cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)) else { return };
let dir = Path::new(dir);
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| std::fs::write(dir.join(USED_MARKER), b"")) {
tracing::debug!("jdtls: cannot mark {} as used: {e}", dir.display());
}
}
/// When a workspace was last used: the latest of our marker (written when jdtls starts) and what
/// jdtls itself touches while it runs and when it saves on exit (a server can run for weeks).
fn last_used(dir: &Path) -> Option<SystemTime> {
let metadata = dir.join(".metadata");
[
dir.join(USED_MARKER),
metadata.join(".log"),
metadata.join(".plugins").join("org.eclipse.core.resources"),
metadata,
]
.into_iter()
.filter_map(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok())
.max()
}
/// Moves the workspaces unused for longer than `max_age` aside, before any server starts, and
/// returns what [`remove`] deletes. Quick: only renames.
pub fn take_unused(data_dir: &Path, max_age: Duration) -> Vec<PathBuf> {
let root = root(data_dir);
let Ok(entries) = std::fs::read_dir(&root) else { return Vec::new() };
let now = SystemTime::now();
let mut taken = Vec::new();
for entry in entries.flatten() {
if !entry.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
let path = entry.path();
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with(TRASH_PREFIX) {
// Left by a start-up that quit before deleting it.
taken.push(path);
continue;
}
let unused = last_used(&path).and_then(|t| now.duration_since(t).ok()).is_some_and(|age| age > max_age);
if !unused {
continue;
}
let trash = root.join(format!("{TRASH_PREFIX}{name}"));
match std::fs::rename(&path, &trash) {
Ok(()) => taken.push(trash),
Err(e) => tracing::debug!("jdtls: cannot move unused workspace {}: {e}", path.display()),
}
}
taken
}
/// Deletes what [`take_unused`] moved aside; slow for large workspaces, so off the start-up path.
pub fn remove(taken: Vec<PathBuf>) {
for dir in taken {
match std::fs::remove_dir_all(&dir) {
Ok(()) => tracing::info!("jdtls: removed unused workspace {}", dir.display()),
Err(e) => tracing::warn!("jdtls: cannot remove unused workspace {}: {e}", dir.display()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn days_ago(days: u64) -> SystemTime {
SystemTime::now() - Duration::from_secs(days * 24 * 60 * 60)
}
/// Back-dates a file, or (on Unix, where a folder opens as a file) a folder.
fn age(path: &Path, days: u64) {
let file =
if path.is_dir() { std::fs::File::open(path) } else { std::fs::File::options().write(true).open(path) };
file.unwrap().set_modified(days_ago(days)).unwrap();
}
fn cfg(data: &Path) -> LanguageServerConfig {
let languages = ide_language::LanguageRegistry::load(None).unwrap();
let mut cfg = languages.get(&ide_core::LanguageId::new("java")).unwrap().language_servers.remove(0);
cfg.args = vec!["-data".into(), data.to_string_lossy().into_owned()];
cfg
}
#[test]
fn removes_workspaces_unused_for_longer_than_the_limit() {
let tmp = tempfile::tempdir().unwrap();
let root = root(tmp.path());
let (old, recent) = (root.join("old"), root.join("recent"));
mark_used(&cfg(&old));
mark_used(&cfg(&recent));
age(&old.join(USED_MARKER), 40);
age(&recent.join(USED_MARKER), 5);
std::fs::write(root.join("defaults.prefs"), "").unwrap();
let taken = take_unused(tmp.path(), UNUSED_FOR);
assert_eq!(taken.len(), 1, "{taken:?}");
assert!(!old.exists() && recent.exists() && root.join("defaults.prefs").exists());
remove(taken);
let mut left: Vec<_> = std::fs::read_dir(&root).unwrap().map(|e| e.unwrap().file_name()).collect();
left.sort();
assert_eq!(left, ["defaults.prefs", "recent"]);
}
#[test]
fn a_started_server_marks_its_workspace_again() {
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("p");
mark_used(&cfg(&ws));
age(&ws.join(USED_MARKER), 40);
mark_used(&cfg(&ws));
assert!(take_unused(tmp.path(), UNUSED_FOR).is_empty());
assert!(ws.exists());
}
#[cfg(unix)]
#[test]
fn a_workspace_from_before_markers_is_judged_by_its_folders_and_log() {
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("legacy");
std::fs::create_dir_all(ws.join(".metadata")).unwrap();
std::fs::write(ws.join(".metadata/.log"), "").unwrap();
for p in [ws.join(".metadata/.log"), ws.join(".metadata")] {
age(&p, 90);
}
assert_eq!(take_unused(tmp.path(), UNUSED_FOR).len(), 1);
// The log alone being recent keeps it.
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("legacy");
std::fs::create_dir_all(ws.join(".metadata")).unwrap();
std::fs::write(ws.join(".metadata/.log"), "").unwrap();
age(&ws.join(".metadata"), 90);
assert!(take_unused(tmp.path(), UNUSED_FOR).is_empty());
}
#[test]
fn leftovers_of_an_interrupted_removal_are_removed() {
let tmp = tempfile::tempdir().unwrap();
let trash = root(tmp.path()).join(format!("{TRASH_PREFIX}gone"));
std::fs::create_dir_all(trash.join(".metadata")).unwrap();
let taken = take_unused(tmp.path(), UNUSED_FOR);
assert_eq!(taken, std::slice::from_ref(&trash));
remove(taken);
assert!(!trash.exists());
}
}
+1
Переглянути файл
@@ -16,6 +16,7 @@ pub mod go;
pub mod godot;
pub mod java;
pub mod jdtls;
pub mod jdtls_workspaces;
pub mod libraries;
pub mod locate;
pub mod lombok;
+27
Переглянути файл
@@ -1328,3 +1328,30 @@ yodel/SM
yodelled
yodeller/MS
yodelling
annualize/GDS
annualise/GDS
decimalize/GDS
decimalise/GDS
decriminalize/GDS
decriminalise/GDS
demonetize/GDS
demonetise/GDS
denationalize/GDS
denationalise/GDS
depressurize/GDS
depressurise/GDS
disorganize/GDS
disorganise/GDS
modularize/GDS
modularise/GDS
parallelize/GDS
parallelise/GDS
recapitalize/GDS
recapitalise/GDS
ritualize/GDS
ritualise/GDS
underutilize/GDS
underutilise/GDS
virtualize/GDS
virtualise/GDS
reauthorize/GDS
+36 -3
Переглянути файл
@@ -24,6 +24,8 @@ pub use words::{MIN_WORD_CHARS, WordSpan, words};
pub enum RegionKind {
Comment,
String,
/// A raw / verbatim string: `\` is literal text, not an escape (`r"\user"`).
RawString,
/// A declared identifier (`camelCase` / `snake_case` split).
Name,
/// Plain text / Markdown prose.
@@ -53,7 +55,7 @@ impl From<RegionKind> for TypoContext {
fn from(kind: RegionKind) -> Self {
match kind {
RegionKind::Name => Self::Code,
RegionKind::String => Self::Literal,
RegionKind::String | RegionKind::RawString => Self::Literal,
RegionKind::Comment => Self::Comment,
RegionKind::Prose => Self::Prose,
}
@@ -89,7 +91,7 @@ impl SpellScope {
pub fn includes(&self, kind: RegionKind) -> bool {
match kind {
RegionKind::Name => self.code,
RegionKind::String => self.literals,
RegionKind::String | RegionKind::RawString => self.literals,
RegionKind::Comment => self.comments,
RegionKind::Prose => true,
}
@@ -99,7 +101,8 @@ impl SpellScope {
/// At most this many typos are reported per text.
pub const MAX_TYPOS: usize = 2000;
/// The en_GB entries en_US lacks (`colour`, `behaviour`, `normalise`), in the
/// The en_GB entries en_US lacks (`colour`, `behaviour`, `normalise`) and the
/// -ize verbs it lists only as `-ization` / `-ized` (`parallelize`), in the
/// same affix scheme: either spelling passes.
const EN_GB_EXTRA: &str = include_str!("dict/en_GB-extra.dic");
@@ -546,6 +549,27 @@ mod tests {
}
}
#[test]
fn ize_verbs_whose_derivatives_are_listed() {
let s = Speller::default();
for ok in [
"parallelize",
"parallelise",
"parallelizes",
"parallelizing",
"modularize",
"virtualize",
"virtualised",
"decimalize",
"underutilize",
] {
assert!(s.is_correct(ok), "{ok}");
}
for bad in ["desireable", "releative", "parallelizee"] {
assert!(!s.is_correct(bad), "{bad}");
}
}
#[test]
fn british_spellings() {
let s = Speller::default();
@@ -678,6 +702,15 @@ mod tests {
assert_eq!(found, [("mesage", TypoContext::Code)]);
}
#[test]
fn raw_strings_do_not_lose_the_letter_after_a_backslash() {
let s = Speller::default();
let text = r#"r"\user \mesage""#;
let regions = [Region { start: 0, end: text.len(), kind: RegionKind::RawString }];
let typos = s.check(text, &regions, &|| false).unwrap();
assert_eq!(typos.iter().map(|t| t.word.as_str()).collect::<Vec<_>>(), ["mesage"]);
}
#[test]
fn scope_filters_region_kinds() {
let comments_only = SpellScope { code: false, literals: false, comments: true };
+12 -1
Переглянути файл
@@ -18,7 +18,7 @@ pub struct WordSpan {
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 = match kind {
RegionKind::Name => Escapes::None,
RegionKind::Name | RegionKind::RawString => Escapes::None,
RegionKind::String => Escapes::Char,
RegionKind::Comment | RegionKind::Prose => Escapes::Word,
};
@@ -186,6 +186,17 @@ mod tests {
assert_eq!(split("// 中文注释 naïve", RegionKind::Comment), ["naïve"]);
}
#[test]
fn raw_strings_keep_the_letter_after_a_backslash() {
// `\u` in a normal string is an escape: the letter is consumed and only
// `ser` is prose. In a raw string the backslash is literal, so `user`
// must be checked whole (issue: r"\user" flagged as typo 'ser').
assert_eq!(split(r#""\user""#, RegionKind::String), ["ser"]);
assert_eq!(split(r#""\user""#, RegionKind::RawString), ["user"]);
assert_eq!(split(r"\n\t \wrd", RegionKind::RawString), ["wrd"]);
assert_eq!(split(r"C:\Users\mesage", RegionKind::RawString), ["Users", "mesage"]);
}
#[test]
fn skips_backslash_commands_in_comments() {
assert_eq!(split("/// \\brief Returns the sum.", RegionKind::Comment), ["Returns", "the", "sum"]);
+6 -4
Переглянути файл
@@ -332,9 +332,10 @@ impl<'t> Finder<'_, 't> {
/// Subtrees where calls that exit before the root can be: the statement holding
/// the chain, or, for a chain in a compound statement's header, that statement.
/// For an `else if` also the conditions of the `if`s before it, which all ran;
/// their branch bodies did not, since the later condition is only reached when
/// they were skipped.
/// For an `else if` also the conditions of the `if`s before it that start on the
/// line the trace starts from (`} else if` on a line of its own stops after they
/// ran); their branch bodies never count, since the later condition is only
/// reached when they were skipped.
fn skip_regions(&self, anchor: Node<'t>, scope: Node<'t>) -> Vec<Node<'t>> {
let is_statement = |n: Node| n.kind().ends_with("_statement") || n.kind() == "switch_expression";
if anchor.kind() != "method_invocation" {
@@ -344,12 +345,13 @@ impl<'t> Finder<'_, 't> {
.take_while(|n| *n != scope)
.find(|n| is_statement(*n))
.unwrap_or(anchor);
let stop_row = anchor.start_position().row;
let mut regions = vec![region];
while let Some(outer) = region
.parent()
.filter(|p| p.kind() == "if_statement" && p.child_by_field_name("alternative") == Some(region))
{
regions.extend(outer.child_by_field_name("condition"));
regions.extend(outer.child_by_field_name("condition").filter(|c| c.start_position().row >= stop_row));
region = outer;
}
regions
+1
Переглянути файл
@@ -125,6 +125,7 @@ public class Chains {
} else if (list.stream().anyMatch(x -> x.isEmpty())) { // C_PLAN_ELSE_IF_BODY
base--;
}
if (names.stream().anyMatch(x -> x.isEmpty())) base++; else if (list.stream().noneMatch(x -> x.isEmpty())) base--; // C_PLAN_ELSE_IF_ONE_LINE
List<String> out = nums.stream() // C_PLAN_FIRST_LINE
.filter(x -> x > 0)
.map(x -> x * 2)
+10 -2
Переглянути файл
@@ -172,9 +172,17 @@ fn root_skip_counts_sibling_chain_in_if_header() {
}
#[test]
fn root_skip_counts_earlier_condition_of_else_if() {
fn root_skip_leaves_out_an_earlier_condition_that_ran_before_the_stop() {
// Stopped on the `} else if` line, the first condition has already returned.
let root = plan_of("C_PLAN_ELSE_IF").root.unwrap();
assert_eq!(root, spec("stream", 0, 1));
assert_eq!(root, spec("stream", 0, 0));
}
#[test]
fn root_skip_counts_an_earlier_condition_on_the_same_line() {
let chains = chains_at("C_PLAN_ELSE_IF_ONE_LINE");
let later = chains.iter().find(|c| c.terminal.name == "noneMatch").expect("else-if chain");
assert_eq!(real_run_plan(later).unwrap().root, Some(spec("stream", 0, 1)));
}
#[test]
+55 -1
Переглянути файл
@@ -13,6 +13,10 @@ pub struct RecentProject {
/// Git branch shown on the welcome screen. Persisted as of last open; [`RecentProjects::list_live`]
/// refreshes it from `.git/HEAD` when the list is shown.
pub branch: Option<String>,
/// The local folder no longer exists (set by [`with_live_branches`] when the list is shown): the
/// welcome screen shows the entry as unavailable.
#[serde(default)]
pub missing: bool,
}
pub const MAX_RECENT_PROJECTS: usize = 30;
@@ -139,11 +143,25 @@ pub fn with_live_branches(mut items: Vec<RecentProject>) -> Vec<RecentProject> {
for item in &mut items {
if let Ok(branch) = read_head_branch(item.path.as_ref()) {
item.branch = branch;
} else if is_missing(item.path.as_ref()) {
// A deleted repository has no branch to show.
item.missing = true;
item.branch = None;
}
}
items
}
/// A local project folder that is gone. Remote locations (`ssh://`, `wsl://`, `devcontainer://`)
/// and WSL shares, which a stopped distribution only hides, never count as missing.
fn is_missing(path: &Path) -> bool {
let text = path.to_string_lossy();
// Stored paths may use `/` (`//wsl.localhost/Ubuntu/...`); host names ignore case.
let unc = text.replace('/', r"\").to_ascii_lowercase();
let wsl = unc.starts_with(r"\\wsl$") || unc.starts_with(r"\\wsl.localhost");
path.is_absolute() && !text.contains("://") && !wsl && !path.exists()
}
impl RecentProjects {
pub fn load(config_dir: &Path) -> Self {
let file = config_dir.join("recent.json");
@@ -192,7 +210,7 @@ impl RecentProjects {
items.retain(|p| p.path != path);
let name =
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());
items.insert(0, RecentProject { path: path.into(), name, opened_at_ms: now_ms(), branch });
items.insert(0, RecentProject { path: path.into(), name, opened_at_ms: now_ms(), branch, missing: false });
cap(&mut items, &self.groups.lock());
self.persist(&items)
}
@@ -242,6 +260,15 @@ impl RecentProjects {
mod tests {
use super::*;
#[test]
fn wsl_shares_stored_with_forward_slashes_are_never_missing() {
for path in
[r"\\wsl.localhost\Ubuntu\home\me\gone", "//wsl.localhost/Ubuntu/home/me/gone", "//WSL$/Ubuntu/gone"]
{
assert!(!is_missing(Path::new(path)), "{path}");
}
}
#[test]
fn newest_first_capped_and_persisted() {
let tmp = tempfile::tempdir().unwrap();
@@ -341,6 +368,33 @@ mod tests {
assert_eq!(recent.list().iter().find(|i| i.path.as_ref() == repo).unwrap().branch.as_deref(), Some("stale"));
}
#[test]
fn list_live_marks_deleted_folders_missing_without_their_branch() {
let tmp = tempfile::tempdir().unwrap();
let gone = tmp.path().join("removed-worktree");
write_head(&gone.join(".git"), "ref: refs/heads/feature-x\n");
let plain = tmp.path().join("plain");
std::fs::create_dir_all(&plain).unwrap();
let recent = RecentProjects::load(tmp.path().join("config").as_path());
recent.touch(&gone, Some("feature-x".into())).unwrap();
recent.touch(&plain, Some("kept".into())).unwrap();
recent.touch(Path::new("ssh://server/home/me/app"), None).unwrap();
std::fs::remove_dir_all(&gone).unwrap();
let live = recent.list_live();
let by_path = |p: &Path| live.iter().find(|i| i.path.as_ref() == p).unwrap();
assert!(by_path(&gone).missing);
assert_eq!(by_path(&gone).branch, None);
assert!(!by_path(&plain).missing);
assert_eq!(by_path(&plain).branch.as_deref(), Some("kept"));
assert!(!by_path(Path::new("ssh://server/home/me/app")).missing, "remote locations are not checked");
// Only the shown list: the saved one keeps the last branch.
let stored = recent.list();
let stored = stored.iter().find(|i| i.path.as_ref() == gone).unwrap();
assert!(!stored.missing);
assert_eq!(stored.branch.as_deref(), Some("feature-x"));
}
#[test]
fn list_live_follows_worktree_gitdir_and_shows_short_detached_head() {
let tmp = tempfile::tempdir().unwrap();
+18
Переглянути файл
@@ -132,6 +132,24 @@ mac = "Meta+Alt+C" # optional; macOS uses `key` as written when it is mis
the user already uses that keystroke, or when the action already has a binding. The user
can rebind it in **Settings › Keymap**.
### Escape in the editor
API 1.10 lets a command answer a plain <kbd>Escape</kbd> in a focused editor, to clear
something the plugin shows there (a highlight, a mode):
```toml
[[contributes.keymaps]]
command = "clear-highlight"
key = "Escape"
when = "plugin.my-plugin.highlighting" # required; set it with set-context while there is something to clear
```
- It runs only after everything the IDE does with Escape in the editor found nothing to do:
closing a popup, completion or rename, collapsing a selection or extra carets, Vim.
- `when` is required and `key` (and `mac`, if given) must be `Escape`. Escape is the only plain
key a plugin can bind, and `when` is accepted only on such a binding.
- When several plugins' `when` hold, the most recently loaded one runs.
## Menus
```toml
+1 -1
Переглянути файл
@@ -104,7 +104,7 @@ Each contribution point is a table (`[contributes.settings]`) or an array of tab
| ------------------- | -------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) |
| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) |
| `keymaps` | `command`, `key`, `mac?` | no | [Commands and actions](/en/plugins/guides/commands) |
| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) |
| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) |
| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) |
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@ title: "Publish to the marketplace"
description: "How the default marketplace is built, official versus community plugins, and how to list your plugin through the community registry."
---
The IDE's default marketplace is the `plugins-index.json` attached to the latest OpenIDEA release. Users browse it in **Settings › Plugins**, filter by category, and install with one click. It lists two kinds of plugins.
The IDE's default marketplace is the `plugins-index.json` attached to the latest OpenIDEA release. Users browse it in **Settings › Plugins › Marketplace**, filter by category, and install with one click. It lists two kinds of plugins.
| | Official | Community |
| ------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
+1 -1
Переглянути файл
@@ -41,7 +41,7 @@ openidea-plugin merge market/index.json https://github.com/l0ng-ai/openidea/rele
## Point the IDE at it
In **Settings › Plugins**, open the gear menu and choose **Plugin Repository…**. Enter the **Marketplace index URL** (`https://…/index.json` or a folder path); leave it empty to go back to the default repository. The marketplace plugins in the list then come from your index.
In **Settings › Plugins**, open the gear menu and choose **Plugin Repository…**. Enter the **Marketplace index URL** (`https://…/index.json` or a folder path); leave it empty to go back to the default repository. The **Marketplace** tab then lists your index.
The IDE reads one index. If you want users to keep seeing the official plugins, merge the official index into yours.
+15
Переглянути файл
@@ -119,6 +119,21 @@ mac = "Meta+Alt+C" # 可选;缺省时 macOS 原样使用 `key`
- 插件快捷键只是默认值,优先级低于 IDE:按键映射预设或用户已经占用该按键、或该动作已有绑定时,
插件的快捷键会被丢弃。用户可以在 **设置 › 按键映射** 中重新绑定。
### 编辑器中的 Escape
API 1.10 起,命令可以响应焦点编辑器中单独按下的 <kbd>Escape</kbd>,用来清除插件在编辑器里显示的内容(高亮、某种模式):
```toml
[[contributes.keymaps]]
command = "clear-highlight"
key = "Escape"
when = "plugin.my-plugin.highlighting" # 必填;有内容可清除时用 set-context 设置
```
- 只有 IDE 在编辑器里对 Escape 的处理都没有生效时才会执行:关闭弹窗、补全或重命名,收起选区或多余的光标,Vim。
- 必须写 `when`,且 `key`(以及给出的 `mac`)必须是 `Escape`。Escape 是插件唯一能绑定的单独按键,`when` 也只用于这种绑定。
- 多个插件的 `when` 同时成立时,执行最后加载的那个插件的命令。
## 菜单
```toml
+1 -1
Переглянути файл
@@ -104,7 +104,7 @@ optional = ["net:api.openai.com", "secrets"]
| ------------------- | ---------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `commands` | `id`、`title`、`category?`、`when?`、`icon?` | 执行时需要 | [命令与动作](/zh/plugins/guides/commands) |
| `menus` | `menu`、`command`、`when?`、`view?`、`submenu?` | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `keymaps` | `command`、`key`、`mac?` | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `keymaps` | `command`、`key`、`mac?`、`when?`(仅 Escape) | 否 | [命令与动作](/zh/plugins/guides/commands) |
| `statusBar` | `id`、`text`、`tooltip?`、`command?`、`align?`、`priority?` | 否 | [视图与装饰](/zh/plugins/guides/views) |
| `settings` | `schema`(JSON 文件)或 `pages`(API 1.3)、`title?` | 否 | [生命周期与事件](/zh/plugins/lifecycle) |
| `secrets` | `name`、`label`、`description?` | 使用时需要 | [权限与能力](/zh/plugins/capabilities) |
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@ title: "发布到市场"
description: "默认插件市场如何构建,官方插件与社区插件的区别,以及如何通过社区登记仓库上架你的插件。"
---
IDE 默认的插件市场是最新 OpenIDEA release 附带的 `plugins-index.json`。用户在 **设置 › 插件** 中浏览、按分类筛选,一键安装。其中有两类插件:
IDE 默认的插件市场是最新 OpenIDEA release 附带的 `plugins-index.json`。用户在 **设置 › 插件 › 插件市场** 中浏览、按分类筛选,一键安装。其中有两类插件:
| | 官方插件 | 社区插件 |
| ---------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
+1 -1
Переглянути файл
@@ -41,7 +41,7 @@ openidea-plugin merge market/index.json https://github.com/l0ng-ai/openidea/rele
## 让 IDE 使用它
在 **设置 › 插件** 中打开齿轮菜单,选择 **插件仓库…**,在 **插件市场索引 URL:** 中填入 `https://…/index.json` 或一个文件夹路径;留空则恢复默认仓库。之后插件列表里的市场插件就来自你的索引。
在 **设置 › 插件** 中打开齿轮菜单,选择 **插件仓库…**,在 **插件市场索引 URL:** 中填入 `https://…/index.json` 或一个文件夹路径;留空则恢复默认仓库。之后 **插件市场** 标签页列出的就是你的索引。
IDE 只读取一个索引。如果希望用户仍能看到官方插件,请把官方索引合并进你的索引。
+58
Переглянути файл
@@ -902,3 +902,61 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
// Output-less running tool rows align their kind icon with expandable tool rows.
expect(layout.iconLeftDiff).toBeLessThanOrEqual(1);
});
test("aligns Mermaid diagrams in replies to their container align attribute", async ({ page }) => {
const diagram = ["```mermaid", "flowchart LR", " A --> B", "```"].join("\n");
await openReply(
page,
[
"Summary across the full width of the reply column so diagrams sit inside a wider message body.",
"",
diagram,
"",
'<div align="left" style="width: 960px; max-width: 100%; margin-left: 0; text-align: left;">',
"",
diagram,
"",
"</div>",
"",
'<div align="right">',
"",
diagram,
"",
"</div>",
"",
'<div align="left"><div align="center">',
"",
diagram,
"",
"</div></div>",
].join("\n"),
);
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const store = await import(storePath);
store.openTaskInEditorLocation(id);
}, TASK.id);
const reply = page.locator("[class*='_stream_']:visible [class*='_markdown_']").first();
const outputs = reply.locator("[data-mermaid-state='ok'] .mermaid-output");
await expect(outputs).toHaveCount(4);
const offsets = await outputs.evaluateAll((els) =>
els.map((out) => {
const outRect = out.getBoundingClientRect();
const svgRect = out.querySelector("svg")!.getBoundingClientRect();
return {
leftGap: svgRect.left - outRect.left,
rightGap: outRect.right - svgRect.right,
};
}),
);
expect(offsets[0]!.leftGap).toBeGreaterThan(20);
expect(Math.abs(offsets[0]!.leftGap - offsets[0]!.rightGap)).toBeLessThanOrEqual(1.5);
expect(Math.abs(offsets[1]!.leftGap)).toBeLessThanOrEqual(1);
expect(offsets[1]!.rightGap).toBeGreaterThan(40);
expect(offsets[2]!.leftGap).toBeGreaterThan(40);
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
});
+8 -6
Переглянути файл
@@ -125,11 +125,11 @@ const discoveredSources: McpExternalSource[] = [
nativeProvider: "copilot",
servers: [
{
name: "workiq",
name: "playwright",
transport: "stdio",
enabled: true,
command: "npx",
args: ["-y", "@microsoft/workiq", "mcp"],
args: ["-y", "@playwright/mcp@latest"],
url: null,
envKeys: [],
headerKeys: [],
@@ -290,16 +290,18 @@ test("manages multi-level MCP servers in Settings and per-session overrides via
await expect(sessionPopup).toContainText("openidea");
await expect(sessionPopup).toContainText("postgres-local");
await expect(sessionPopup).toContainText("github-mcp-server");
await expect(sessionPopup).toContainText("workiq");
await expect(sessionPopup).toContainText("playwright");
// Disable `slack-official` for this session only and verify IPC call + `Session` badge.
// Disable `slack-official` (Global) and `playwright` (Agent Config) for this session only.
await sessionPopup.getByRole("switch", { name: "Enable slack-official for this session" }).click();
await expect(sessionPopup).toContainText("Session");
await sessionPopup.getByRole("switch", { name: "Enable playwright for this session" }).click();
await expect(sessionPopup).toContainText("Disabled for this session (GitHub Copilot CLI)");
const overrideCalls = await ipcCalls(page, "agent_set_mcp_overrides");
expect(overrideCalls.at(-1)?.overrides).toEqual({ "slack-official": false });
expect(overrideCalls.at(-1)?.overrides).toEqual({ "slack-official": false, playwright: false });
const screenshotDir = process.env.CAPTURE_MCP_SCREENSHOTS;
if (screenshotDir) {
await page.waitForTimeout(250);
await page.screenshot({ path: `${screenshotDir}/mcp-session-picker.png` });
}
+130
Переглянути файл
@@ -0,0 +1,130 @@
/** Session Pull Requests, Issues, References, and Artifacts surfaced above the agent composer. */
import type { AgentEntry, AgentTask } from "../src/bindings";
import { expect, test } from "./fixtures";
const TASK: AgentTask = {
id: "session-assets-task",
title: "Storage session pooling",
provider: "copilot",
model: "claude-sonnet-4",
status: "ready",
isolation: "local",
cwd: "/dev/acme-api",
projectRoot: "/dev/acme-api",
branch: "feat/session-pooling",
base: "main",
baseCommit: null,
error: null,
createdMs: 1_763_250_000_000,
updatedMs: 1_763_250_120_000,
config: [],
commands: [],
usage: null,
queue: [],
};
const ENTRIES: AgentEntry[] = [
{
type: "user",
text: "Investigate [Issue #418: Connection pool contention under burst traffic](https://github.com/acme/acme-api/issues/418) and draft a migration report.",
attachments: [],
sentMs: 1_763_250_010_000,
doneMs: 1_763_250_090_000,
steered: false,
},
{
type: "tool",
id: "tool-issue",
title: 'gh issue create -R acme/acme-api --title "Track session lease renewal metrics"',
kind: "execute",
status: "completed",
locations: [],
output: "https://github.com/acme/acme-api/issues/512\n",
diffs: [],
},
{
type: "tool",
id: "tool-doc",
title: "Write architecture-overview.md",
kind: "edit",
status: "completed",
locations: ["/dev/acme-api/docs/architecture-overview.md"],
output: null,
diffs: [{ path: "/dev/acme-api/docs/architecture-overview.md", added: 64, removed: 0 }],
},
{
type: "agent",
text: [
"Opened PRs and wrote the architecture summary:",
"- [#510 feat(pool): add bounded session lease cache](https://github.com/acme/acme-api/pull/510)",
"- [#511 chore(metrics): export pool saturation histogram](https://github.com/acme/acme-api/pull/511)",
"- Context commit [a4f91c2](https://github.com/acme/acme-api/commit/a4f91c2890123456) and [Discussion #309: Async pool sizing](https://github.com/acme/acme-api/discussions/309)",
"- Live telemetry: [Datadog Dashboard: Pool Latency (abc-def-123)](https://app.datadoghq.com/dashboard/abc-def-123)",
"- Referenced `specs/api-spec.pdf` and `docs/migration-plan.docx`.",
].join("\n"),
},
];
test("surfaces session pull requests, issues, references, and artifacts above the composer", async ({
workbench: page,
}) => {
await page.evaluate(
async ({ task, entries }) => {
const storePath = "/src/features/agents/store.ts";
const ipcPath = "/src/platform/ipc.ts";
const store = await import(storePath);
const { commands } = await import(ipcPath);
commands.agentChanges = async () => ({ status: "ok", data: [] });
store.useAgents.setState({
loaded: true,
error: null,
providers: [],
tasks: new Map([[task.id, task]]),
entries: new Map([[task.id, entries]]),
composers: new Map(),
unread: new Set(),
docked: null,
sessionLocation: "editor",
});
store.openTask(task.id);
},
{ task: TASK, entries: ENTRIES },
);
const bar = page.getByRole("toolbar", { name: "Session references and artifacts" });
await expect(bar).toBeVisible();
await expect(bar.getByRole("button", { name: "2 Pull Requests" })).toBeVisible();
await expect(bar.getByRole("button", { name: "1 Issue" })).toHaveText("#512");
await expect(bar.getByRole("button", { name: "3 References" })).toBeVisible();
await expect(bar.getByRole("button", { name: "4 Artifacts" })).toBeVisible();
// Open Artifacts popup, insert a Markdown artifact mention into the CodeMirror composer, then dismiss one item.
await bar.getByRole("button", { name: "4 Artifacts" }).click();
const dialog = page.getByRole("dialog", { name: "Artifacts" });
await expect(dialog).toBeVisible();
await expect(dialog.getByText("Websites")).toBeVisible();
await expect(dialog.getByText("Files")).toBeVisible();
const mdRow = dialog.getByRole("button", { name: "architecture-overview.md" }).locator("..");
await mdRow.hover();
await mdRow.getByRole("button", { name: "Add to Message" }).click();
await expect(dialog).toHaveCount(0);
const box = page.getByRole("textbox", { name: "Message", exact: true });
await expect(box).toContainText("architecture-overview.md");
await expect
.poll(() =>
page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
return (await import(storePath)).composerDraft(id).text;
}, TASK.id),
)
.toBe("@docs/architecture-overview.md ");
await bar.getByRole("button", { name: "4 Artifacts" }).click();
const dialogAfter = page.getByRole("dialog", { name: "Artifacts" });
const webRow = dialogAfter.getByRole("button", { name: /Datadog Dashboard: Pool Latency/ }).locator("..");
await webRow.hover();
await webRow.getByRole("button", { name: "Remove" }).click();
await expect(bar.getByRole("button", { name: "3 Artifacts" })).toBeVisible();
});
+7 -2
Переглянути файл
@@ -309,7 +309,9 @@ test("⌘B goes to the declaration in another file", async ({ workbench: page })
expect(args).toMatchObject({ pos: at(20, 27), kind: "definition" });
});
test("Find Usages lists every usage by file and opens one", async ({ workbench: page }) => {
test("Find Usages from the editor context menu lists every usage by file and opens one", async ({
workbench: page,
}) => {
const editor = await openSample(page);
await page.evaluate(
({ file, other }) => {
@@ -325,7 +327,10 @@ test("Find Usages lists every usage by file and opens one", async ({ workbench:
{ file: FILE, other: `${ROOT}/settings.gradle.kts` },
);
await caretAt(editor, page, "val order: Order", "service");
await page.keyboard.press("Alt+F7");
const caret = await editor.locator(".cm-cursor").boundingBox();
await page.mouse.click(caret!.x + 2, caret!.y + caret!.height / 2, { button: "right" });
await page.getByRole("menuitem", { name: /^Find Usages/ }).click();
expect((await ipcCalls(page, "lsp_references"))[0]).toMatchObject({ pos: at(20, 27) });
const usages = page.getByRole("tree", { name: /usages/i });
await expect(usages.getByRole("treeitem", { name: "Found usages 3 results" })).toBeVisible();
await expect(usages.getByRole("treeitem", { name: "build.gradle.kts 2 usages" })).toBeVisible();
+6 -4
Переглянути файл
@@ -70,7 +70,7 @@ async function stubRepositoryAndAgent(page: Page, reply: string) {
operation: null,
});
h.vcs_status = () => changes;
h.vcs_create_patch = () => patch;
h.vcs_pending_patch = () => patch;
h.vcs_log = () => [{ id: "1111111", summary: "Bump the wrapper" }];
h.agent_create = (args) => {
const created = { ...task, id: "new", title: "Write a commit message", status: "starting", updatedMs: 9 };
@@ -131,9 +131,11 @@ test("the agent of the latest task writes the commit message of the included cha
// Only the included file's diff, and the style of the latest commits, go to the agent.
expect(created.prompt.text).toContain("+++ b/build.gradle.kts");
expect(created.prompt.text).toContain("- Bump the wrapper");
expect(await ipcCalls(page, "vcs_create_patch")).toEqual([
expect.objectContaining({ source: { from: "changes", paths: [`${ROOT}/build.gradle.kts`], reverse: false } }),
]);
// What Commit would commit: the included file only (read again before the message is filled in).
const pending = await ipcCalls(page, "vcs_pending_patch");
expect(pending.length).toBeGreaterThan(0);
for (const call of pending)
expect(call).toMatchObject({ options: expect.objectContaining({ stage: [`${ROOT}/build.gradle.kts`] }) });
// The task ran for the message only: it is gone again, and nothing was left to read.
expect(await ipcCalls(page, "agent_delete")).toEqual([expect.objectContaining({ task: "new" })]);
await expect(page.getByRole("alert")).toHaveCount(0);
+54
Переглянути файл
@@ -273,6 +273,60 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
});
test("Markdown preview aligns Mermaid diagrams to their container align attribute", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
await content.click();
await page.keyboard.press("Meta+a");
const diagram = ["```mermaid", "flowchart LR", " A --> B", "```"].join("\n");
await page.keyboard.insertText(
[
diagram,
"",
'<div align="left" style="width: 960px; max-width: 100%; margin-left: 0; text-align: left;">',
"",
diagram,
"",
"</div>",
"",
'<div align="right">',
"",
diagram,
"",
"</div>",
"",
'<div align="left"><div align="center">',
"",
diagram,
"",
"</div></div>",
].join("\n"),
);
const preview = page.getByRole("document", { name: "Markdown preview" });
const outputs = preview.locator("[data-mermaid-state='ok'] .mermaid-output");
await expect(outputs).toHaveCount(4);
const offsets = await outputs.evaluateAll((els) =>
els.map((out) => {
const outRect = out.getBoundingClientRect();
const svgRect = out.querySelector("svg")!.getBoundingClientRect();
return {
leftGap: svgRect.left - outRect.left,
rightGap: outRect.right - svgRect.right,
};
}),
);
expect(offsets[0]!.leftGap).toBeGreaterThan(20);
expect(Math.abs(offsets[0]!.leftGap - offsets[0]!.rightGap)).toBeLessThanOrEqual(1.5);
expect(Math.abs(offsets[1]!.leftGap)).toBeLessThanOrEqual(1);
expect(offsets[1]!.rightGap).toBeGreaterThan(40);
expect(offsets[2]!.leftGap).toBeGreaterThan(40);
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
});
test("the bookmark gutter takes no width until the file has a bookmark", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const column = editor.locator(".cm-gutter.cm-openidea-bookmarks");
Бінарний файл не відображається.
+15 -3
Переглянути файл
@@ -6,6 +6,7 @@ import ai.openidea.jvminspect.JavaDebugSessions.HubEvent;
import ai.openidea.jvminspect.RealRunPlan.StepSpec;
import com.sun.jdi.AbsentInformationException;
import com.sun.jdi.ArrayReference;
import com.sun.jdi.BooleanValue;
import com.sun.jdi.ClassType;
import com.sun.jdi.Field;
import com.sun.jdi.IncompatibleThreadStateException;
@@ -162,6 +163,8 @@ final class RealRunTrace {
/** Recorder number of the next wrapped op; modifiers take none. */
private int nextStep;
private ObjectReference lastWrapped;
/** Whether the stream was made sequential: the plan asked, or the stream the chain starts from was parallel. */
private volatile boolean sequentialized;
/** {@code forceEarlyReturn} at a method exit makes that frame exit once more, returning the forced value. */
private Method echoMethod;
private Value echoValue;
@@ -240,11 +243,14 @@ final class RealRunTrace {
subscription = hub.subscribe(this::onEvent, e -> errors.add("event listener: " + e));
if (held != null) {
// Not put back: the program consumes the stream right after.
lastWrapped = wrap(held, nextStep++, plan.sequentialize());
// A stream made parallel before this statement shows no `parallel` in the chain.
sequentialized = plan.sequentialize() || isParallel(held);
lastWrapped = wrap(held, nextStep++, sequentialized);
// The invokes resumed the thread, which invalidated the frame read before them.
thread.frame(0).setValue(local, lastWrapped);
} else {
rootSkip = plan.root().skip();
sequentialized = plan.sequentialize();
}
// Last: with these on, an invoke into the thread would raise the trace's own events inside it.
// The step out of the frame never fires inside an invoke, which runs above it.
@@ -402,7 +408,8 @@ final class RealRunTrace {
}
ObjectReference stream = returned(exit, root);
setEnabled(false);
replace(exit, wrap(stream, nextStep++, plan.sequentialize()));
if (!sequentialized && isParallel(stream)) sequentialized = true;
replace(exit, wrap(stream, nextStep++, sequentialized));
return;
}
if (method.isStatic() || method.isConstructor() || !calledByUser() || !lastWrapped.equals(thread.frame(0).thisObject())) return;
@@ -597,6 +604,11 @@ final class RealRunTrace {
return sequentialize ? invoke(wrapped, "sequential") : wrapped;
}
private boolean isParallel(ObjectReference stream) throws Exception {
Method method = streamMethod(stream.referenceType(), "isParallel", 0);
return stream.invokeMethod(thread, method, List.of(), INVOKE) instanceof BooleanValue b && b.value();
}
private ObjectReference invoke(ObjectReference stream, String name, Value... arguments) throws Exception {
Method method = streamMethod(stream.referenceType(), name, arguments.length);
return keep(RecorderLoader.pin(() -> (ObjectReference) stream.invokeMethod(thread, method, List.of(arguments), INVOKE)));
@@ -1008,7 +1020,7 @@ final class RealRunTrace {
};
int skipped = silencers.stream().mapToInt(Silencer::silencedBreakpoints).sum();
return Values.json("records", records, "dropped", longOf(fields.get(field("dropped"))), "terminal", terminal,
"skippedBreakpoints", skipped, "sequentialized", plan.sequentialize());
"skippedBreakpoints", skipped, "sequentialized", sequentialized);
}
/**
+24 -1
Переглянути файл
@@ -40,6 +40,8 @@ public final class StreamCommand implements IDelegateCommandHandler {
private static final int GONE_KEPT = 16;
private static final AtomicLong IDS = new AtomicLong();
private static final Map<VirtualMachine, RealRunTrace> TRACES = new IdentityHashMap<>();
/** The {@code token} each trace was armed with: a client whose {@code arm} timed out releases by it. */
private static final Map<RealRunTrace, String> TOKENS = new IdentityHashMap<>();
/** By trace id, the answer {@link RealRunTrace#ended} gave: the trace itself would keep its dead VM's mirrors. */
private static final Map<Long, Map<String, Object>> GONE = new LinkedHashMap<>() {
private static final long serialVersionUID = 1L;
@@ -64,6 +66,7 @@ public final class StreamCommand implements IDelegateCommandHandler {
} catch (Failure e) {
Map<String, Object> gone = name.equals("arm") ? null : gone(args);
if (gone == null) throw e;
if (name.equals("release") && args.get("token") instanceof String) return InspectCommand.ok(Map.of());
return InspectCommand.ok(switch (name) {
case "wait" -> gone;
case "release" -> Map.of();
@@ -76,7 +79,9 @@ public final class StreamCommand implements IDelegateCommandHandler {
case "stop" -> Values.json("records", trace(vm, args).stopRecording());
case "abort" -> trace(vm, args).abort();
case "collect" -> collect(vm, target, trace(vm, args));
case "release" -> release(vm, trace(vm, args));
case "release" -> args.get("token") instanceof String token && !(args.get("traceId") instanceof Number)
? releaseArmed(vm, token)
: release(vm, trace(vm, args));
default -> throw new IllegalArgumentException("unknown command " + command);
});
} catch (Failure e) {
@@ -131,6 +136,7 @@ public final class StreamCommand implements IDelegateCommandHandler {
RealRunTrace trace = RealRunTrace.arm(IDS.incrementAndGet(), vm, thread, plan, budget, target.generation(), hub);
synchronized (TRACES) {
TRACES.put(vm, trace);
if (args.get("token") instanceof String token) TOKENS.put(trace, token);
}
return trace.id;
}
@@ -166,11 +172,27 @@ public final class StreamCommand implements IDelegateCommandHandler {
if (!trace.state().wire.equals("running")) {
synchronized (TRACES) {
TRACES.remove(vm, trace);
TOKENS.remove(trace);
}
}
return Map.of();
}
/**
* The trace armed with {@code token}, whose {@code arm} reply the client gave up on: released,
* so its breakpoints come back on. Under the arm lock, so an arm still setting up finishes first.
*/
private static Map<String, Object> releaseArmed(VirtualMachine vm, String token) {
synchronized (InspectCommand.handlesFor(vm)) {
RealRunTrace current;
synchronized (TRACES) {
current = TRACES.get(vm);
if (current == null || !token.equals(TOKENS.get(current))) return Map.of();
}
return release(vm, current);
}
}
/** Releases the traces of VMs java-debug no longer has; their requests and objects went with the VM. */
private static void forgetGone(List<VmInfo> vms) {
Set<VirtualMachine> live = Collections.newSetFromMap(new IdentityHashMap<>());
@@ -182,6 +204,7 @@ public final class StreamCommand implements IDelegateCommandHandler {
if (live.contains(e.getKey())) continue;
RealRunTrace trace = e.getValue();
trace.vmGone();
TOKENS.remove(trace);
GONE.put(trace.id, trace.ended());
gone.add(trace);
i.remove();
+71
Переглянути файл
@@ -91,6 +91,8 @@ public class Real {
case "H": h(); break;
case "local": local(); break;
case "parallel": parallel(); break;
case "plocal": parallelLocal(); break;
case "elif": elseIf(); break;
case "nested": nested(); break;
case "hostile": hostile(); break;
case "sr": stopRecording(Integer.parseInt(a[1])); break;
@@ -167,6 +169,20 @@ public class Real {
System.out.println("P " + p + " " + q);
}
static void parallelLocal() {
Stream<Integer> s = nums.parallelStream();
List<Integer> r = s.map(x -> x + 1).collect(Collectors.toList()); // @plocal
System.out.println("PL " + r);
}
static void elseIf() {
if (nums.stream().anyMatch(x -> x > 100)) {
System.out.println("ELIF no");
} else if (nums.stream().anyMatch(x -> x == 8)) { // @elif
System.out.println("ELIF yes");
}
}
static void nested() {
long n = nums.stream().flatMap(x -> Stream.of(x, x)).count(); // @nested
System.out.println("NESTED " + n);
@@ -833,6 +849,61 @@ def real_run_parallel():
dbg.end()
@case
def real_run_parallel_local():
dbg = real('plocal')
try:
# No `parallel` in the chain: the stream was made parallel before the statement.
trace, state, _ = run_until_parked(dbg, 'plocal', root=None, local='s', steps=(spec('map', 1),), step_kinds=('sync',),
class_filters=('java.util.stream.*',))
c = step_out_and_collect(dbg, trace)
collected_ok('parallel local', c, records='0=5 1=6 0=3 1=4 0=8 1=9 0=1 1=2 0=4 1=5 0=2 1=3 0=9 1=10 0=6 1=7'.split())
check('parallel local: sequentialized', c['sequentialized'] is True, c['sequentialized'])
resume(dbg)
check('parallel local: program output', output_line(dbg, 'PL ') == 'PL [6, 4, 9, 2, 5, 3, 10, 7]')
finally:
dbg.end()
@case
def real_run_else_if():
dbg = real('elif')
try:
# Stopped on the `else if` line, the first condition's `stream()` has already returned.
trace, state, _ = run_until_parked(dbg, 'elif', steps=(), terminal=spec('anyMatch', 1), step_kinds=(), timeout=20)
check('else if: the trace parks with nothing skipped', state['state'] == 'parked', state)
c = step_out_and_collect(dbg, trace)
collected_ok('else if', c, terminal='true')
resume(dbg)
check('else if: program output', output_line(dbg, 'ELIF ') == 'ELIF yes')
finally:
dbg.end()
@case
def release_by_arm_token():
dbg = launch()
try:
def arm_with(token):
return stream('arm', dbg, threadId=dbg.thread, plan=plan('loop'), budget=50_000, token=token)
ok(arm_with('first'))
check('release by another token leaves the trace', ok(stream('release', dbg, token='other')) == {})
check('so the next arm is busy', error(arm_with('second')) == 'busy')
check('release by the arm\'s token answers {}', ok(stream('release', dbg, token='first')) == {})
trace = ok(arm_with('third'))['traceId']
check('arm works again after it', trace is not None, trace)
ok(stream('release', dbg, traceId=trace))
resume(dbg)
try:
body = expect_stop(dbg, 10, 'stop after release')
check('breakpoints are back after a release by token', body.get('reason') == 'breakpoint', body)
except TimeoutError:
check('breakpoints are back after a release by token', False, 'no stop within 10 s')
finally:
dbg.end()
@case
def real_run_nested():
dbg = real('nested')
+1 -1
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.46",
"version": "0.1.47",
"license": "Apache-2.0",
"type": "module",
"scripts": {
+56 -15
Переглянути файл
@@ -150,7 +150,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes |
| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them |
| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`; API 1.4: `editor.title`, `mainToolbar`, `problems.context`, `searchResults.context`), `view?`, `command`, `when?` | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`) | no |
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no |
| `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no |
| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `group?`, `when?` (API 1.3) | without `web` |
@@ -443,6 +443,33 @@ matching SDK. Released 1.9 plugins keep working. New in 1.10:
`build.dependencies`) returns the Maven / Gradle graph the Dependency Analyzer
has, as a flat list with conflict and omission status, behind the low-risk
`build.read` capability. No build tool runs. See _Build dependency graph_.
- **Escape in the editor.** `[[contributes.keymaps]]` takes `key = "Escape"` with a
required `when`: the command runs on a plain Escape in a focused editor once the
IDE's own Escape handling (popups, completion, rename, selection, extra carets,
Vim) found nothing to do.
- **The marker bar's problems in editor panels.** An editor panel's page reads
the problems its group's marker bar shows with `openidea.editor.problems()`
and hears them change through `onProblems`. See _Editor panels_.
- **Semantic highlighting in editor panels.** `openidea.editor.highlights()`
returns the colours the editor shows, semantic highlighting from the language
server layered over the syntax colours, and `onHighlights` reports the lines
whose colours change when semantic tokens arrive. See _Editor panels_.
- **Folds and soft wrap in editor panels.** An editor panel's page reads which
lines are folded with `openidea.editor.folded()`, how many rows each line takes
with soft wrap on with `wrapped(fromLine, toLine)`, and hears both change
through `onLayout`. See _Editor panels_.
- **The caret and selections in editor panels.** An editor panel's page reads
the caret and every selection of its group's editor with
`openidea.editor.selections()` and hears them move through `onSelections`. See
_Editor panels_.
- **VCS changes in editor panels.** An editor panel's page reads the added,
modified and deleted lines its group's change-marker lane shows with
`openidea.editor.changes()` and hears them change through `onChanges`. Frames
get the lane's colours as `--openidea-change-added`, `--openidea-change-modified`
and `--openidea-change-deleted`. See _Editor panels_.
- **The tab size in editor panels.** `openidea.editor.get()` includes the
`tabSize` the editor expands tabs with for the group's file, and `onTarget`
reports it again when it changes. See _Editor panels_.
### API 1.9
@@ -1747,6 +1774,7 @@ values (the body already uses the text colour, UI font and size):
| `--openidea-border`, `--openidea-focus-ring`, `--openidea-link` | Lines, focus, links |
| `--openidea-accent`, `--openidea-fg-on-accent` | Accent and text on it |
| `--openidea-danger`, `--openidea-warning`, `--openidea-success`, `--openidea-info` | Status colours |
| `--openidea-change-added`, `--openidea-change-modified`, `--openidea-change-deleted` | API 1.10: the editor's VCS change markers |
| `--openidea-font-ui`, `--openidea-font-mono`, `--openidea-font-size` | Fonts (web fonts the IDE bundles are not available in the frame) |
Scripts get the same as `openidea.theme` (`{ dark, vars }`) and
@@ -1908,22 +1936,35 @@ sit side by side.
The page gets `openidea.editor` (only an editor panel's page has it). Lines are
0-based, columns UTF-16:
| `openidea.editor` | What it does |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get()` | `{ path, language, version, lineCount }` of the group's file, or `null` |
| `onTarget(fn)` | Called with `get()` when the group shows another file, or none |
| `document.get()` / `document.onChange` | The `openidea.document` of web views, on the group's file and read-only: `edit` and `replace` reject. Changes arrive at most once a frame |
| `viewport()` / `onViewport(fn)` | `{ firstLine, lastLine, lineCount, scrollTop, scrollHeight, clientHeight }`; lines are fractional (the position within a line). Sent on scroll, resize and folding, at most once a frame |
| `scrollTo(line)` | Scrolls so that `line` (fractional) is at the top of the visible area; call it on every move while dragging |
| `scrollBy(pixels)` | Scrolls the editor by `pixels`: hand it the page's wheel |
| `highlights(fromLine, toLine)` | One array per line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): `[{ from, to, color }]`, `color` the syntax colour in the current scheme (a CSS colour) |
| `onHighlights(fn)` | `{ fromLine, toLine }` whose colours may have changed: parsing progressed, the file was edited, the colour scheme changed |
| `openidea.editor` | What it does |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `get()` | `{ path, language, version, lineCount, tabSize }` of the group's file, or `null`; `tabSize` (API 1.10) is the columns a tab takes in the editor (Code Style, `.editorconfig`, indent detection) |
| `onTarget(fn)` | Called with `get()` when the group shows another file, or none, and (API 1.10) when the file's tab size changes |
| `document.get()` / `document.onChange` | The `openidea.document` of web views, on the group's file and read-only: `edit` and `replace` reject. Changes arrive at most once a frame |
| `viewport()` / `onViewport(fn)` | `{ firstLine, lastLine, lineCount, scrollTop, scrollHeight, clientHeight }`; lines are fractional (the position within a line). Sent on scroll, resize and folding, at most once a frame |
| `scrollTo(line)` | Scrolls so that `line` (fractional) is at the top of the visible area; call it on every move while dragging |
| `scrollBy(pixels)` | Scrolls the editor by `pixels`: hand it the page's wheel |
| `highlights(fromLine, toLine)` | One array per line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): `[{ from, to, color }]`, `color` the colour the editor shows in the current scheme (a CSS colour; API 1.10: semantic highlighting included) |
| `onHighlights(fn)` | `{ fromLine, toLine }` whose colours may have changed: parsing progressed, the file was edited, the colour scheme changed, semantic tokens arrived (API 1.10) |
| `problems()` | API 1.10: the problems the marker bar shows, in file order: `[{ line, lastLine, severity }]`, `lastLine` the last line a problem covers, `severity` `error`, `warning` or `weakWarning` |
| `onProblems(fn)` | API 1.10: called with `problems()` when a problem appears or goes away, when edits move them, and when the group shows another file; at most once a frame |
| `folded()` | API 1.10: the folded ranges, in file order: `[{ fromLine, toLine }]`, `fromLine` the line that stays visible (with the placeholder), `toLine` the last line hidden. Folds inside a fold are part of it |
| `wrapped(fromLine, toLine)` | API 1.10: the visual rows of each line from `fromLine` up to `toLine` (exclusive, at most 2000 lines): 1 for a line that fits, 0 for a line a fold hides; `null` while soft wrap is off |
| `onLayout(fn)` | API 1.10: called with `{ folded, softWrap }` (`folded()`, and whether soft wrap is on) when folds change, soft wrap turns on or off, wrapped rows may have changed, and the group shows another file; at most once a frame |
| `selections()` | API 1.10: the caret and selections: `[{ anchor: { line, column }, head: { line, column } }]`, the main selection first, the others in file order; a caret is a selection whose `anchor` equals `head` |
| `onSelections(fn)` | API 1.10: called with `selections()` when the caret moves, a selection changes, and the group shows another file; at most once a frame |
| `changes()` | API 1.10: the VCS changes beside the line numbers, in file order: `[{ line, lastLine, kind }]`, `kind` `added`, `modified` or `deleted`; a deletion's `line` is the line below the deleted text. `[]` outside version control |
| `onChanges(fn)` | API 1.10: called with `changes()` when the changes are recomputed or edits move them, and when the group shows another file; at most once a frame |
Colours come from syntax highlighting only (no semantic highlighting yet); the
Colours are the editor's: syntax highlighting and, from API 1.10, the semantic
highlighting over it (a semantic colour wins where both apply). The
panel's other colours are the frame's theme variables (`openidea.theme`,
`onThemeChange`). Not there yet: the caret and selections, and the marker bar's
problems and changes. `crates/ide-plugin/tests/fixtures/editor-panel` is a
minimal minimap (each line 2 px, its frame draggable) to install and try.
`onThemeChange`). Before API 1.10 there is no `problems`, `folded`, `wrapped`,
`onLayout`, `selections` or `changes`: check for them (`if (editor.problems)`) when the page also runs in
older IDEs. Outside the visible area the editor estimates wrapped rows from the
line's length until it lays the line out; `onLayout` follows when it does.
`crates/ide-plugin/tests/fixtures/editor-panel` is a minimal minimap (each line
2 px, its frame draggable, problems marked at its right edge, folded lines left out, the selected lines and the caret's line tinted, VCS changes at its left edge) to install and try.
### Web frame PTYs (API 1.3)
+1 -1
Переглянути файл
@@ -332,7 +332,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
267 themeable tokens: 125 in the UI theme file, 142 in the editor colour scheme file.
269 themeable tokens: 125 in the UI theme file, 144 in the editor colour scheme file.
### Surfaces (UI theme)
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// The commit being prepared in the window the current command or event came
/// from (the Commit tool window, or the Commit dialog while it is open): the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Plugin-owned project data sources. Requires database.sources and project trust.
/// Runs on the Database subsystem's host, including on remote project servers.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
/// follows its file: the file's own project, or the nearest one when it is outside them all.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// What the pane beside the Services tree shows for a plugin's node.
interface detail-types {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Optional export (world `plugin-diagnostics`): problems in the current,
/// possibly unsaved document, for the languages declared with the
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
interface endpoints-provider {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Workbench events, delivered in batches to `event-handler.handle`.
interface events {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
interface lifecycle {
use types.{context, error};
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// What other plugins contributed to the extension points this plugin declares
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Optional export (world `plugin-file-actions`): quick fixes and
/// refactorings that create, rename or delete files, next to the text edits
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Files outside the open projects: the configuration of the program a
/// plugin integrates with, a tool installed elsewhere, a licence file.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Writes to the IDE log, tagged with the plugin id.
interface log {
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Optional export (world `plugin-hover`): Markdown added to the hover of
/// documents of the languages declared with the `hover` provider kind,
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Cross-file associations a plugin publishes for the files it declares under
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Embedded languages. The host routes plugin providers and configured language
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
/// the languages declared with the `inlay-hints` provider kind, including
+1 -1
Переглянути файл
@@ -1,4 +1,4 @@
package openidea:plugin@1.9.0;
package openidea:plugin@1.10.0;
/// Problems in files, shown in the editor and the Problems view.
interface diagnostics {
Loaded 100 of 235 files, more files were not shown because too many files have changed in this diff. Show more