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

...
38 Коміти
Автор SHA1 Повідомлення Дата
l0ng-ai 2fd127250e feat(debugger): Browse the debug console history and open diff settings from the keyboard
- Debug console: typed expressions are kept per project, and Browse Console
  History (⌥⌘E / Ctrl+Alt+E) lists them, most recent first, to put one back
  into the input.
- Diff viewer: Diff Settings (⇧⌘D / Ctrl+Shift+D) opens the viewer options
  (side-by-side / unified, whitespace, highlighting, collapsing, scroll sync)
  as a popup menu.
2026-10-29 02:06:24 +08:00
l0ng-ai a28600c55a feat(editor): Show the enclosing declarations with Context Info (#161)
View > Context Info (Ctrl+Shift+Q on macOS, Alt+Q on Windows) shows the
class, method and block header lines around the caret in a hint, which helps
when they are scrolled out of view.
2026-10-29 02:01:18 +08:00
l0ng-ai b35035f8d9 feat(vcs): Accept a diff change from the keyboard and step between diff files (#158)
- Accept Left Side / Accept Right Side copy the change at the caret to the
  other side of a side-by-side diff (⌃⌘→ / ⌃⌘← on macOS, Ctrl+Alt+R /
  Ctrl+Alt+A on Windows).
- Compare Next File / Compare Previous File open the neighbouring file of
  the diff chain directly (⌃⇧→ / ⌃⇧← on macOS, Alt+Shift+→ / ← on Windows).
2026-10-29 01:38:22 +08:00
l0ng-ai cfd2970531 feat(services): List run configurations in the Services tool window (#160)
The Services tool window lists run configurations next to Docker. Spring Boot configurations appear by default; other types (Application, npm, Maven, Gradle, …) are added with + › Run Configuration Type and removed with Remove from Services, remembered per project. Nodes group by type and show running / stopped, with Run / Rerun, Debug, Stop, Show in Run Tool Window and Edit Configuration… in the toolbar and context menu; the detail pane shows the same console as the Run tool window. Running Spring Boot apps show the HTTP port read from the embedded server's "started on port" line.

Rerun now waits for the old process to exit before starting the new one, so a restarted server no longer fails with its port already in use, and a process stopped by the user no longer raises an exit-code notification.

Closes #150

Claude-Session: https://claude.ai/code/session_01Dq6jQQn8ZhRfkkyj3PRutA
2026-10-29 01:06:32 +08:00
itningтаitning 11362a36f8 feat(vcs): Default the Git Log to the current branch and remember the branch filter (#155)
The main Log tab opened with no branch filter and showed all branches. It now starts on HEAD (Current Branch), which follows checkouts, and a branch filter the user picks (including multi-selection and all branches) is remembered per repository across restarts, stored with the other per-repository Git UI state. Remembered refs that no longer exist are dropped, falling back to HEAD when none are left. Also fixes the first checkout or commit after opening the Log not refreshing it.

Claude-Session: https://claude.ai/code/session_01Dq6jQQn8ZhRfkkyj3PRutA
Co-authored-by: itning <[email protected]>
2026-10-29 01:00:26 +08:00
l0ng-ai e43b0b81c7 fix(workbench): Route files opened from inside the app to their project window (#159)
Files opened from inside the app (File › Open File…, a drop on the Welcome screen, Open File in a single-file window) were always kept in the requesting window, so a file belonging to a project open in another window went to the single-file window instead. These paths now follow the same rule as Finder, Dock and second-instance opens: window_open_files normalises the paths and routes them through plan_open via plan_open_files, which sends files inside an open local project to that project's window. It returns only the files the requesting window should open itself. The TypeScript side no longer has any routing logic. Files dropped onto a project window still open in that window.

Refs #128
2026-10-29 00:58:25 +08:00
l0ng-ai 0c9c51b0f5 feat(editor): Add folding, navigation, editing and window shortcuts (#153)
Editing and folding
- Move Caret to Code Block Start / End with Selection, Auto-Indent Lines,
  Move Element Left / Right (swaps call arguments, parameters and list
  entries).
- Fold Code Block folds the {...} block around the caret; Expand to Level
  and Expand All to Level 1-5.
- Custom folding regions (//region, #region, <editor-fold>) fold to their
  description; Navigate > Custom Folding lists them.
- Error Description shows the problems at the caret; Next / Previous
  Highlighted Usage steps through usage highlights.
- Editor tooltips stay below the editor's top edge, so hints on the first
  lines no longer hide under the tab bar.

Navigation, project and run
- Navigate > File Path lists the file and its folders to reveal in the file
  manager.
- Copy... (F5) opens the Copy dialog for the selection or the open file; the
  project view's Refactor submenu gets Copy File.
- Debug... chooses a configuration to debug; Quick Evaluate Expression shows
  the selection's value in an expandable hint.
- Inspect Current File runs the inspection without the scope dialog.
- Surround with Live Template lists only $SELECTION$ templates; Java gets
  Callable, read / write lock and iterate templates.

Windows
- Stretch the active tool window left / right / up / down, Restore Default
  Layout, Go to Next / Previous Splitter, Close Active Tab on a second key,
  Stop Background Processes.

All actions have default shortcuts in both keymaps, VS Code preset entries,
main menu items and Chinese translations.

Project view and Keymap settings
- Project view Options: Sort by Name / Type / Modification Time (also in
  Find Action).
- Settings > Keymap: Add Mouse Shortcut records a side-button click with
  modifiers and checks conflicts like keyboard shortcuts.
- Folding: Expand to Level / Expand All to Level 1-5.
2026-10-29 00:39:37 +08:00
itningтаitning 7e6919010f fix(editor): Draw semantic highlighting above the syntax highlighter (#154)
Semantic token decorations were registered at Prec.high, the same precedence as CodeMirror's tree highlighter, so the syntax span ended up innermost and its colour won over the semantic one (fields, constants and other LSP-coloured identifiers looked like plain text). They now register at Prec.highest. The ⌘-hover link colour is kept over semantic colours, and semantic modifier lookup ignores Object.prototype names, which turned jdtls' `constructor` modifier into a bogus class.

Claude-Session: https://claude.ai/code/session_01Dq6jQQn8ZhRfkkyj3PRutA
Co-authored-by: itning <[email protected]>
2026-10-29 00:36:34 +08:00
l0ng-ai e803d82202 fix(run): Detect Maven / Gradle builds nested in a folder of repositories (#157)
Run configuration detection only looked for pom.xml / build.gradle(.kts) at the opened root, so a Maven or Gradle build in a subfolder produced no configurations, and Java files fell back to a single-file `java X.java` launch without classpath or build. Detection now takes the root build, or else the shallowest build on each branch up to three levels down, with the subfolder in the config's cwd, id and name; a multi-module parent pom counts as one build. Spring Boot applications (@SpringBootApplication with main in a module that applies the Spring Boot plugin) get spring-boot configurations that build the module and run with its classpath. Gutter and file runs pick the build the file belongs to (also for Go modules), and only files outside any build run as single files; the main config lookup takes the nearest bootRun / run / spring-boot:run.

On Windows, piped JVM (java, Maven, Gradle) and Python processes now write in the console encoding instead of the ANSI code page, so their output is no longer garbled. run_configs runs on a blocking thread.

Fixes #149

Claude-Session: https://claude.ai/code/session_01Dq6jQQn8ZhRfkkyj3PRutA
2026-10-29 00:24:46 +08:00
Jaw a7c970a6db feat(vcs): Use the editor's find bar in the diff viewer (#148)
Find in the diff viewer (⌘F / ⌘R / ⌘G) opens the editor's find bar instead of CodeMirror's search panel: same field, Match Case / Words / Regex, counter, navigation, filter menu and highlights. In the side-by-side viewer the bar sits over the side with the caret, Replace is offered only on editable sides, and the shortcuts come from the keymap. Esc closes the bar even while a match is selected.

Claude-Session: https://claude.ai/code/session_01Dq6jQQn8ZhRfkkyj3PRutA
Co-authored-by: jaw52 <[email protected]>
2026-10-29 00:20:23 +08:00
Mykhailo Smolinskyiтаnntndfrk 0184a9c395 feat(angular): Add the Angular Language Server (#147)
ngserver (@angular/language-server) runs next to vtsls and the HTML server in Angular projects, bringing completion, hover, definition, diagnostics, references and rename to external and inline component templates. A language server can now require a root marker (require-root-marker), so the Angular server only serves files below angular.json or node_modules/@angular/core and never hides the typescript-language-server fallback elsewhere. Attached servers keep definition order, and rename merges the edits of every server that accepts the position. Installable from the tools registry via npm.

Claude-Session: https://claude.ai/code/session_01Dq6jQQn8ZhRfkkyj3PRutA
Co-authored-by: nntndfrk <[email protected]>
2026-10-29 00:18:19 +08:00
Jaw 4a15936acb feat(editor): Smooth caret blinking and movement (#146)
Settings › Editor › General › Appearance gets "Use smooth caret blinking" and "Use smooth caret movement" (Snappy / Gliding), both off by default. Smooth movement animates only navigation and clicks; typing, edits and scrolling moves stay instant, and reduced motion turns it off. The diff and merge viewers now use the editor's caret and follow these settings instead of CodeMirror's default caret. Also translates a select's value shown while its checkbox is unchecked.

Claude-Session: https://claude.ai/code/session_01Dq6jQQn8ZhRfkkyj3PRutA
Co-authored-by: jaw52 <[email protected]>
2026-10-29 00:18:14 +08:00
Jaw 811da13a76 feat: Syntax-colour Find in Files and Show Usages result lines (#143)
Result lines in the Find in Files popup and tool window and in the Show Usages popup and Usages tool window are coloured like the editor, using the whole file as context, so a line inside a block comment or a multi-line string gets the right colour. The colouring lives in editor/lineTokens and all four lists share it; each file is parsed once and cached, and the parse runs in 8 ms time slices so large files don't block the UI thread. Lines that moved since the search, and files over 500k characters, are coloured on their own.

Claude-Session: https://claude.ai/code/session_01Dq6jQQn8ZhRfkkyj3PRutA
Co-authored-by: jaw52 <[email protected]>
2026-10-29 00:18:02 +08:00
l0ng-ai 1d383e608c feat(workbench): Open files from Finder in the single-file window (#152)
On macOS, OpenIDEA is now listed under Finder's Open With for text and source files and for folders. It never becomes the default app for any of them: all document types are declared with rank Alternate, and only in tauri.macos.conf.json, so Windows and Linux installers register nothing.

Files opened from Finder, the Dock or a second instance share one routing path (plan_open). A file inside a local project that is already open, or still opening, goes to that project's window, choosing the deepest root when projects are nested. Any other file goes to the existing single-file window, or to a new one. A folder focuses the window that already has it open, otherwise it opens as a project. Paths that arrive before setup are queued and opened with the first launch.

The single-file window now closes with its last tab, restores its files the next time it opens, and only offers Open File and drop hints when empty. Also fixes a regression: reopening projects on startup no longer replaces a file opened at cold start.

Refs #128
2026-10-28 23:56:23 +08:00
l0ng-ai 2d7726cf53 feat(workbench): Edit single files without opening a project (#145)
Files can now be opened without a project. A file dropped on the Welcome screen, picked with File › Open File…, or passed on the command line or to a second instance opens in a lightweight window: editor tabs only, with no project tree, indexing, language servers, VCS or project tool windows. Syntax highlighting, find, save, undo and Local History still work. More files opened later join the same window as new tabs. Open as Project in the status bar opens the file's directory as a full project, following the open-project policy, and reopens the file there.

Backend: a light session reuses Project with an unindexed index, no LSP or VCS, and a flat watch on each opened file's directory. It is never reused as a project for the same root. Previously a file passed at launch opened its parent directory as a project.
2026-10-28 22:06:35 +08:00
l0ng-ai eb67595e72 feat(vcs): Add a modal commit mode and fill in Git log, branch popup and settings (#144)
- Settings › Commit › "Use non-modal commit interface": when off, Local
  Changes, Shelf and Stash become tabs of the Git tool window and ⌘K opens
  a Commit dialog; switches live.
- Git tool window: Worktrees tab; Show History and Show Git Log for a
  branch open their own closable tabs instead of changing the Log filters.
- Log: toolbar and context menu for a commit's changed files, vertical
  toolbar, Tags node and hiding for the branches pane, Collapse / Expand
  Linear Branches as separate actions, and a Version Control › Log page.
- Branch popup: collapsible groups, branches grouped by prefix, an options
  menu behind the gear, incoming / outgoing icons and "Pull into … Using
  Rebase / Merge"; New Branch on ⌥⌘N outside the editor.
- Git main menu regrouped with Uncommitted Changes and Current File
  submenus; rebase / merge controls enabled only while one is in progress.
- Settings: Version Control lists its pages; new options for clearing the
  initial commit message, showing Update options, confirming dropped
  commits, revealing created patches, large-file and file-name warnings,
  the Push dialog after Commit and Push, combined stashes and shelves, and
  removing applied files from the shelf.
2026-10-28 21:49:43 +08:00
l0ng-ai 66c36a7361 fix(workbench): Open files dropped from the OS in the editor (#142)
Root cause: once a project was open, nothing outside the Project view handled files dropped from the OS, so drops onto the editor, tabs or other tool windows were ignored.

A window-wide handler now opens dropped files in the editor (one tab each, last one focused, files outside the project included) and opens a dropped folder as a project through the open-project policy. Regions that handle drops themselves (Project view, agent prompt box) are marked with OWNS_FILE_DROP and hit-tested, so each drop has a single handler; the Welcome screen and remote windows are left alone.
2026-10-28 20:58:42 +08:00
l0ng-ai 8daeb21005 fix(terminal): Line height, colour palette and tab names (#141)
* fix(terminal): Line height, colour palette and tab names

- Line height: with "Use editor font" the terminal took the editor's roomier
  line height (about 1.33 cells), stretching ASCII art and box drawing. It now
  always uses Settings › Tools › Terminal › Line height (default 1.0); that
  field moves out of the "Use editor font" group since it applies either way.
- Colours: the terminal gets its own --terminal-ansi-* palette (the light and
  Darcula terminal colours); the Run console keeps --ansi-*. High-contrast and
  palette themes keep their console colours. Colours below a 4.5:1 contrast
  with the background are adjusted (xterm's minimumContrastRatio), so yellow
  stays readable on white.
- Tab names: tabs keep their default name ("Local", "Local (2)") at the prompt
  and show the title a program sets only while a command runs. Shell
  integration now marks command start and end (OSC 133 C / D) for zsh,
  bash 4.4+ (PS0) and fish.

* fix(themes): Document the terminal ANSI palette for theme plugins

The --terminal-ansi-* tokens belong in a theme's editor colour scheme, like
--ansi-*. The theme plugin template sets them and the token reference lists them.
2026-10-28 20:56:38 +08:00
l0ng-ai 44b2d11b2d feat(agents): Select the active session in the Agents list (#140)
Switching between agent session tabs in the editor now moves the Agents
tool window's selection to that task, expanding its group (e.g. Archived)
when it is collapsed. The list also opens with the active session selected.
Tabs of other kinds leave the selection as it is.

The editor service gains activeInput() and onActiveInputChange() so
features can follow the active tab of any kind.
2026-10-28 20:36:55 +08:00
l0ng-ai f8b3ef6840 chore: Skip the repository-wide formatting commit in git blame (#139) 2026-10-28 19:35:52 +08:00
Jaw 55836e1b49 chore: Format the codebase with oxfmt and check formatting in CI (#135)
Run oxfmt once over the whole repository (formatting only, no logic changes) and add `pnpm format:check` to the frontend CI job so unformatted code no longer builds up. `.oxfmtrc.json` now skips the generated theme docs, test fixtures and code blocks inside Markdown.

Co-authored-by: jaw52 <[email protected]>
2026-10-28 19:35:16 +08:00
胡翀таzzxzz12345 a94b4bff42 feat(vcs): Search the Git log branch filter (#129)
The Branch filter in the Git log opens a popup with a search field instead of a plain menu. Branches are fuzzy-matched with highlights and grouped under HEAD, Local and Remote; arrow keys skip the group headers and Enter applies the filter. The list is virtualized so large repositories stay responsive, and Select… still opens the multi-branch / custom revision chooser.

Co-authored-by: zzxzz12345 <[email protected]>
2026-10-28 19:32:54 +08:00
l0ng-ai 3193fd583f chore: v0.1.22 2026-10-28 19:14:59 +08:00
l0ng-ai 995ea886ab fix(workbench): Keep tool window resizing smooth over a terminal or long conversation (#137)
Dragging the bottom tool window edge over a terminal refit xterm on every
pointer move and sent each intermediate size to the shell, which redrew its
prompt every time. Terminals now refit at most every 100 ms while their host
keeps resizing, plus once when it stops, and the process only learns the size
once it has held for 150 ms. This covers the Terminal tool window and terminals
embedded in Run consoles.

Resizing the width of an agent conversation reflowed every entry, including the
off-screen ones (14-16 ms per move in a long session). Entries now use
content-visibility: auto, so only the visible ones are laid out.
2026-10-28 19:04:18 +08:00
l0ng-ai 630d436e18 fix(editor): Allow selecting and copying text in read-only code previews (#136)
Code previews (Find in Files, Usages) are non-editable CodeMirror views, so their text inherited the workbench's user-select: none and had no tab stop: it couldn't be focused, selected with the keyboard or copied. Previews now opt their content back in with the shared selectable-text class and take a tab stop; editing stays blocked. Same root cause as the read-only diff panes (#126).
2026-10-28 18:32:00 +08:00
Dimas Victorтаdvictor357 a61a89fe86 fix(vcs): Allow selecting and copying read-only diff text (#126)
Read-only revision panes inherited the workbench's user-select: none and had no tab stop, so text couldn't be selected with the mouse or keyboard or copied. The viewer content now allows text selection and read-only panes take focus; editing stays blocked.

Once focusable, these panes picked up CodeMirror's dark-theme focused selection colour, which outranked the viewer's rule and made selected text unreadable in light themes; the viewer's selection rule now matches that specificity.

Co-authored-by: dvictor357 <[email protected]>
2026-10-28 18:21:18 +08:00
l0ng-ai 50212e7397 fix(agents): Don't paint a stray selection sliver after a list item's text (#134)
When a list item's text was followed by a nested list and a selection ended at
the end of that text, WebKit painted a thin strip of selection from there to the
right edge. The text of such items now gets its own block.
2026-10-28 18:15:09 +08:00
l0ng-ai 08fd134bdb fix(workbench): Keep tool window resizing smooth with a long agent conversation (#133)
Dragging a tool window edge set an inherited custom property on the tool window
grid, so every pointer move restyled the whole workbench below it. With a long
agent conversation open each move cost 150-400 ms. The grid track variables are
now registered as non-inherited, and the side splitter sets flex-grow on its two
areas instead of inherited variables on the side.
2026-10-28 17:59:09 +08:00
l0ng-ai ecb3134460 feat(agents): Show subagents as their own conversations (#132)
* feat(agents): Show subagents as their own conversations

Agents that support ACP subagent sessions (Claude Code, Codex) now run each
subagent as a child session. Its tool calls and messages no longer mix into
the task's conversation: the parent shows a card per subagent with its state,
tool call count, latest step, task and result, and the card opens the
subagent's own conversation.

- Route session/update by session id; subagent settings and usage stay out
  of the task.
- Subagent permission requests are answered in the task's conversation,
  named after the subagent.
- Subagent conversations are saved with the task; a running subagent is
  marked stopped after a restart.
- A running subagent can be stopped on its own.

* fix(agents): Save a subagent's state when it changes after the turn
2026-10-28 17:51:55 +08:00
l0ng-ai 5b63a2b95c fix(lsp): Drop language servers that leave the list from the status bar (#125)
Removing a language server (disabled in settings via stop_unlisted, or a fallback detached when its preferred server comes back) only emitted a stopped state, and the status bar list only refreshed for unknown servers, so the removed server stayed until the project was reopened. Both paths now go through forget(), which drops the server and emits IdeEvent::LanguageServerRemoved; the frontend drops the entry and ignores stale lsp_servers results that still contain it. Stopped servers no longer count towards "+N".

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-28 15:06:45 +08:00
胡翀таzzxzz12345 ac426c8881 feat(python): Add ty and select the Python language server (#121)
ty (`ty server`) joins basedpyright and Pyright as a Python language server (fallback, gets the project venv like the others, installable from Tools). Settings › Language Servers gets a Python language server picker: Automatic (first available), basedpyright, Pyright, ty or None, written through the per-server enabled settings (null globally / true in a project for enabled, false for disabled); other combinations show as Custom combination. Picker text is translated; the hint sits on its own line.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
Co-authored-by: zzxzz12345 <[email protected]>
2026-10-28 14:57:34 +08:00
l0ng-ai eef24ea785 fix(agents): Leave changes made before a local checkout task out of its changes (#123)
* fix(agents): Leave changes made before a local checkout task out of its changes

A task in the project's own checkout listed every uncommitted and untracked
file as its own. The files already changed when the task starts are now
recorded with their size and modification time, and drop out of the task's
changes until they are edited again.

* feat(agents): Show the current branch for a local checkout task
2026-10-28 14:55:10 +08:00
l0ng-ai f84ad80305 chore: v0.1.21 2026-10-28 14:45:11 +08:00
l0ng-ai 1f383c4e0e fix(app): Survive panics in background work and log them (#122)
* fix(app): Survive panics in background work and log them

A panic in background work (a spell check, an LSP handler) aborted the whole
app and left nothing behind: the message went to stderr, which a launched app
doesn't keep, and the stripped binary gave crash reports no function names.

- Release builds unwind, so a panic fails one task or command instead of
  quitting the IDE. Commands already turn a panicked blocking task into an
  error, and the existing catch_unwind around JSON-RPC notification handlers
  now takes effect.
- A panic hook appends the thread, location, message and backtrace to the
  log file synchronously, before the non-blocking writer could lose them.
- Release builds keep the symbol table (strip = "debuginfo"), so crash
  reports and logged backtraces name functions.

* test(app): Match the panic location with file!() so the test passes on Windows
2026-10-28 14:44:46 +08:00
Jaw 8ff8f22940 chore: Replace Prettier with oxfmt and ESLint with oxlint (#119)
pnpm lint runs oxlint and pnpm format runs oxfmt: lint ~0.3s instead of ~20s, format check ~0.2s instead of ~11s, with far less memory. Configs come from the official migration tools (.oxlintrc.json from eslint.config.js, .oxfmtrc.json from the Prettier config); six new findings fixed or suppressed in 4 files. No code is reformatted.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
Co-authored-by: jaw52 <[email protected]>
2026-10-28 14:19:38 +08:00
胡翀таzzxzz12345 a10e3c8898 fix(spell): Don't crash on Unicode punctuation before a word (#120)
known_run stepped one byte past the delimiter before a word run, which lands inside a multi-byte character (Chinese punctuation, emoji) and panics when slicing. It now steps past the whole character. Regression test with Chinese punctuation and emoji.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
Co-authored-by: zzxzz12345 <[email protected]>
2026-10-28 14:15:47 +08:00
l0ng-ai 96be40cd84 fix(process): Give child processes the host environment inside an AppImage (#118)
Fixes #117

Inside an AppImage, AppRun and the linuxdeploy GTK/GStreamer hooks point LD_LIBRARY_PATH, PATH, XDG_DATA_DIRS, GIO_MODULE_DIR, GTK_PATH, GST_PLUGIN_* … into the mounted image, and every child inherited them, so host programs loaded the image's older libraries (curl + bundled nghttp2 → symbol lookup error when installing Kotlin LSP). ide_core::process::prepare (formerly no_window) now gives children the host environment back: entries inside $APPDIR are dropped (a <NAME>_ORIG wins), emptied variables and the runtime's launch variables are removed, explicit call-site values are kept; the IDE process itself is unchanged. Covers all spawn sites that used no_window plus terminal/run PTYs, run configuration environments and stop commands, login-shell probes, attach ps/kill, docker PATH, tool search PATH and the Linux browser opener. No-op outside an AppImage. Not verified on a Linux AppImage.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-28 13:50:20 +08:00
l0ng-ai 429e8ffc82 fix(i18n): Translate the remaining Git and pull request text (#116)
Multi-repo branch popup matches actions by their translated label (highlights and Chinese search now work) and translates its group headers. Conflict counts, relative times (shared dateFormat), in-progress operation titles, git operation progress/results, branch widget tooltips, diff/hunk counts, worktree markers, PR author line and review placeholders go through tx; the default "Changes" changelist shows its translated name. HexViewer read-only leaves the untranslated allowlist. 92 zh entries.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-28 12:38:25 +08:00
621 змінених файлів з 20532 додано та 4614 видалено

No files matched your search

+2
Переглянути файл
@@ -0,0 +1,2 @@
# Repository-wide oxfmt formatting (#135)
55836e1b4961c9d87df8503ec374e624c81d6bf6
+1
Переглянути файл
@@ -81,6 +81,7 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm lint
- run: pnpm format:check
- run: pnpm test
- run: pnpm build
+26
Переглянути файл
@@ -0,0 +1,26 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"printWidth": 120,
"semi": true,
"singleQuote": false,
"trailingComma": "all",
"sortPackageJson": false,
"ignorePatterns": [
"dist",
"target",
"src/bindings.ts",
"docs/plugins/themes.md",
"pnpm-lock.yaml",
"**/*.toml",
"fixtures",
"crates/**/tests/fixtures"
],
"overrides": [
{
"files": ["**/*.md"],
"options": {
"embeddedLanguageFormatting": "off"
}
}
]
}
+150
Переглянути файл
@@ -0,0 +1,150 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["typescript", "react"],
"categories": {
"correctness": "off"
},
"env": {
"builtin": true
},
"ignorePatterns": [
"dist",
"target",
"src-tauri",
"crates",
"src/bindings.ts",
"fixtures",
"plugins",
"test-results",
"playwright-report",
".claude"
],
"rules": {
"constructor-super": "error",
"for-direction": "error",
"getter-return": "error",
"no-async-promise-executor": "error",
"no-case-declarations": "error",
"no-class-assign": "error",
"no-compare-neg-zero": "error",
"no-cond-assign": "error",
"no-const-assign": "error",
"no-constant-binary-expression": "error",
"no-constant-condition": "error",
"no-control-regex": "error",
"no-debugger": "error",
"no-delete-var": "error",
"no-dupe-class-members": "error",
"no-dupe-else-if": "error",
"no-dupe-keys": "error",
"no-duplicate-case": "error",
"no-empty": "error",
"no-empty-character-class": "error",
"no-empty-pattern": "error",
"no-empty-static-block": "error",
"no-ex-assign": "error",
"no-extra-boolean-cast": "error",
"no-fallthrough": "error",
"no-func-assign": "error",
"no-global-assign": "error",
"no-import-assign": "error",
"no-invalid-regexp": "error",
"no-irregular-whitespace": "error",
"no-loss-of-precision": "error",
"no-misleading-character-class": "error",
"no-new-native-nonconstructor": "error",
"no-nonoctal-decimal-escape": "error",
"no-obj-calls": "error",
"no-prototype-builtins": "error",
"no-redeclare": "error",
"no-regex-spaces": "error",
"no-self-assign": "error",
"no-setter-return": "error",
"no-shadow-restricted-names": "error",
"no-sparse-arrays": "error",
"no-this-before-super": "error",
"no-unassigned-vars": "error",
"no-unexpected-multiline": "error",
"no-unreachable": "error",
"no-unsafe-finally": "error",
"no-unsafe-negation": "error",
"no-unsafe-optional-chaining": "error",
"no-unused-labels": "error",
"no-unused-private-class-members": "error",
"no-unused-vars": [
"error",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_"
}
],
"no-useless-backreference": "error",
"no-useless-catch": "error",
"no-useless-escape": "error",
"no-with": "error",
"preserve-caught-error": "error",
"require-yield": "error",
"use-isnan": "error",
"valid-typeof": "error",
"no-array-constructor": "error",
"no-unused-expressions": "error",
"react/rules-of-hooks": "error",
"react/exhaustive-deps": "warn",
"react/static-components": "error",
"react/use-memo": "error",
"react/preserve-manual-memoization": "error",
"react/incompatible-library": "warn",
"react/immutability": "error",
"react/globals": "error",
"react/refs": "error",
"react/set-state-in-effect": "error",
"react/error-boundaries": "error",
"react/purity": "error",
"react/set-state-in-render": "error",
"react/unsupported-syntax": "warn",
"typescript/ban-ts-comment": "error",
"typescript/no-duplicate-enum-values": "error",
"typescript/no-empty-object-type": "error",
"typescript/no-explicit-any": "error",
"typescript/no-extra-non-null-assertion": "error",
"typescript/no-misused-new": "error",
"typescript/no-namespace": "error",
"typescript/no-non-null-asserted-optional-chain": "error",
"typescript/no-require-imports": "error",
"typescript/no-this-alias": "error",
"typescript/no-unnecessary-type-constraint": "error",
"typescript/no-unsafe-declaration-merging": "error",
"typescript/no-unsafe-function-type": "error",
"typescript/no-wrapper-object-types": "error",
"typescript/prefer-as-const": "error",
"typescript/prefer-namespace-keyword": "error",
"typescript/triple-slash-reference": "error"
},
"overrides": [
{
"files": ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts"],
"rules": {
"constructor-super": "off",
"getter-return": "off",
"no-class-assign": "off",
"no-const-assign": "off",
"no-dupe-class-members": "off",
"no-dupe-keys": "off",
"no-func-assign": "off",
"no-import-assign": "off",
"no-new-native-nonconstructor": "off",
"no-obj-calls": "off",
"no-redeclare": "off",
"no-setter-return": "off",
"no-this-before-super": "off",
"no-unreachable": "off",
"no-unsafe-negation": "off",
"no-var": "error",
"no-with": "off",
"prefer-const": "error",
"prefer-rest-params": "error",
"prefer-spread": "error"
}
}
]
}
-4
Переглянути файл
@@ -1,4 +0,0 @@
dist
target
src/bindings.ts
pnpm-lock.yaml
-1
Переглянути файл
@@ -1 +0,0 @@
{ "printWidth": 120, "semi": true, "singleQuote": false, "trailingComma": "all" }
Створено
+34 -33
Переглянути файл
@@ -3974,7 +3974,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -3992,7 +3992,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4006,7 +4006,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -4021,11 +4021,11 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.20"
version = "0.1.22"
[[package]]
name = "ide-core"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"dunce",
"serde",
@@ -4038,7 +4038,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"ide-run",
@@ -4052,7 +4052,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"ide-jsonrpc",
@@ -4069,7 +4069,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"dirs 6.0.0",
"futures",
@@ -4088,7 +4088,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"libc",
@@ -4102,7 +4102,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4116,7 +4116,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"dirs 6.0.0",
"dunce",
@@ -4157,7 +4157,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"parking_lot",
@@ -4175,7 +4175,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"blake3",
"criterion",
@@ -4197,7 +4197,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"encoding_rs",
"futures",
@@ -4213,7 +4213,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"blake3",
"criterion",
@@ -4267,7 +4267,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"futures",
"globset",
@@ -4290,7 +4290,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"ide-language",
@@ -4308,7 +4308,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"ide-run",
@@ -4321,7 +4321,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"globset",
"ide-core",
@@ -4338,7 +4338,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4358,7 +4358,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"dunce",
"ide-core",
@@ -4372,12 +4372,13 @@ dependencies = [
"tempfile",
"toml 0.9.12+spec-1.1.0",
"tracing",
"which",
"zip 2.4.2",
]
[[package]]
name = "ide-search"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"criterion",
"globset",
@@ -4397,7 +4398,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"parking_lot",
@@ -4410,7 +4411,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4429,7 +4430,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"ide-language",
@@ -4444,7 +4445,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"libc",
@@ -4457,7 +4458,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"criterion",
"ide-core",
@@ -4469,7 +4470,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"flate2",
"hex",
@@ -4489,7 +4490,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"dunce",
"gix",
@@ -4506,7 +4507,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"chardetng",
"dunce",
@@ -4527,7 +4528,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"ide-core",
"open",
@@ -4543,7 +4544,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"blake3",
"dunce",
@@ -5968,7 +5969,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.20"
version = "0.1.22"
dependencies = [
"blake3",
"dirs 6.0.0",
+5 -3
Переглянути файл
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*", "src-tauri"]
[workspace.package]
version = "0.1.20"
version = "0.1.22"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -108,5 +108,7 @@ opt-level = 2
codegen-units = 1
lto = true
opt-level = 3
panic = "abort"
strip = true
# Unwind, so a panic fails one task or command instead of quitting the IDE.
panic = "unwind"
# Keep the symbol table: crash reports and logged backtraces name functions.
strip = "debuginfo"
+8 -8
Переглянути файл
@@ -30,14 +30,14 @@ for 60+ languages. Builds for macOS, Windows and Linux.
Opening [freqtrade](https://github.com/freqtrade/freqtrade) (Python, ~770 files)
with warm caches, median of 5 runs:
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
|---|---|---|
| Window with the project | **0.9 s** | 3.1 s |
| Ready (CPU settled) | **1.1 s** | 13.2 s |
| Memory (USS, all processes) | **169 MB** | 2011 MB |
| CPU time until ready | **2.4 s** | 47.9 s |
| Idle CPU | **4 %** of a core | 7 % of a core |
| Quit | **0.3 s** | 5.9 s |
| | OpenIDEA | IntelliJ IDEA 2026.2.3 |
| --------------------------- | ----------------- | ---------------------- |
| Window with the project | **0.9 s** | 3.1 s |
| Ready (CPU settled) | **1.1 s** | 13.2 s |
| Memory (USS, all processes) | **169 MB** | 2011 MB |
| CPU time until ready | **2.4 s** | 47.9 s |
| Idle CPU | **4 %** of a core | 7 % of a core |
| Quit | **0.3 s** | 5.9 s |
A release build of OpenIDEA from `main` and IDEA with default settings and plugins, on
Windows 11, 32-core AMD, 62 GB RAM.
+1 -2
Переглянути файл
@@ -116,7 +116,7 @@ Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
@@ -251,7 +251,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```
## Chinese UI terminology from Visual Studio Code
Some Simplified Chinese terms in `src/platform/locales/text/zh.json` follow the
+281
Переглянути файл
@@ -0,0 +1,281 @@
//! A task's conversation and those of its subagents.
//!
//! An agent that supports ACP subagent sessions runs each subagent (Claude Code's Agent
//! tool, Codex's spawned agents) as a child session: `subagent_update` on the parent
//! announces it and reports its state, its own updates carry its session id, and
//! `session_message`s carry what it was asked and what it answered. The parent's
//! timeline shows a card per subagent; each subagent keeps its own timeline.
use crate::model::AgentEntry;
use crate::timeline::{Timeline, blocks_text, content_text};
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// Where an entry lives: the task's own conversation (`None`) or a subagent's session.
pub(crate) type Session = Option<String>;
#[derive(Default)]
pub(crate) struct Conversation {
pub main: Timeline,
/// In the order they started.
subagents: Vec<Subagent>,
}
struct Subagent {
id: String,
/// The session that started it.
parent: Session,
timeline: Timeline,
}
/// A subagent's conversation, as saved with its task.
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct SavedSubagent {
pub id: String,
pub parent: Option<String>,
pub entries: Vec<AgentEntry>,
}
impl Conversation {
pub fn restore(main: Vec<AgentEntry>, subagents: Vec<SavedSubagent>) -> Self {
Self {
main: Timeline::from_entries(main),
subagents: subagents
.into_iter()
.map(|s| Subagent { id: s.id, parent: s.parent, timeline: Timeline::from_entries(s.entries) })
.collect(),
}
}
pub fn saved_subagents(&self) -> Vec<SavedSubagent> {
self.subagents
.iter()
.map(|s| SavedSubagent { id: s.id.clone(), parent: s.parent.clone(), entries: s.timeline.entries.clone() })
.collect()
}
pub fn timeline(&self, session: &Session) -> Option<&Timeline> {
match session {
None => Some(&self.main),
Some(id) => self.subagents.iter().find(|s| &s.id == id).map(|s| &s.timeline),
}
}
fn timeline_mut(&mut self, session: &Session) -> Option<&mut Timeline> {
match session {
None => Some(&mut self.main),
Some(id) => self.subagents.iter_mut().find(|s| &s.id == id).map(|s| &mut s.timeline),
}
}
fn parent_of(&self, id: &str) -> Option<&Session> {
self.subagents.iter().find(|s| s.id == id).map(|s| &s.parent)
}
/// The session an update for session id `session` belongs to: a known subagent's, else the task's.
pub fn owner(&self, session: Option<&str>) -> Session {
session.filter(|s| self.parent_of(s).is_some()).map(str::to_owned)
}
/// The parent's title (or description) for subagent `id`.
pub fn label(&self, id: &str) -> Option<String> {
let parent = self.parent_of(id)?;
self.timeline(parent)?.entries.iter().find_map(|e| match e {
AgentEntry::Subagent { id: card, title, description, .. } if card == id => {
title.clone().or_else(|| description.clone())
}
_ => None,
})
}
/// Applies one `session/update` of session id `session` (the task's own when unknown);
/// returns the entries it added or changed.
pub fn apply(&mut self, session: Option<&str>, update: &Value, now: f64) -> Vec<(Session, usize)> {
let owner = self.owner(session);
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
let mut out = Vec::new();
match kind {
"subagent_update" => {
let Some(id) = update.get("sessionId").and_then(Value::as_str) else { return out };
if self.parent_of(id).is_none() {
self.subagents.push(Subagent { id: id.to_owned(), parent: owner, timeline: Timeline::default() });
}
let parent = self.parent_of(id).cloned().flatten();
let Some(timeline) = self.timeline_mut(&parent) else { return out };
let (index, stopped) = timeline.subagent(id, update, now);
out.push((parent, index));
if stopped && let Some(child) = self.timeline_mut(&Some(id.to_owned())) {
let id = Some(id.to_owned());
out.extend(child.end_turn(None).into_iter().map(|i| (id.clone(), i)));
}
}
"session_message" | "session_message_chunk" => {
let append = kind == "session_message_chunk";
let text = if append {
content_text(update.get("content")).unwrap_or_default()
} else {
blocks_text(update.get("content"))
};
let field = |k: &str| update.get(k).and_then(Value::as_str).map(str::to_owned);
let (sender, recipient) = (field("senderSessionId"), field("recipientSessionId"));
let ours =
|s: &Option<String>| s.as_deref().filter(|s| self.parent_of(s) == Some(&owner)).map(str::to_owned);
// Between this session and a subagent of it: the subagent's task or answer, on its card.
let card = ours(&recipient).map(|c| (c, false)).or_else(|| ours(&sender).map(|c| (c, true)));
let Some(timeline) = self.timeline_mut(&owner) else { return out };
let index = match card {
Some((child, reply)) => timeline.card_message(&child, reply, &text, append),
None => {
let id = field("messageId").unwrap_or_default();
Some(timeline.message(&id, sender != owner, &text, append))
}
};
out.extend(index.map(|i| (owner, i)));
}
_ => {
let Some(timeline) = self.timeline_mut(&owner) else { return out };
out.extend(timeline.apply(update).changed.into_iter().map(|i| (owner.clone(), i)));
if let Some(id) = owner.as_deref()
&& matches!(kind, "tool_call" | "tool_call_update")
{
out.extend(self.refresh_card(id));
}
}
}
out
}
/// Updates subagent `id`'s card from its timeline.
fn refresh_card(&mut self, id: &str) -> Option<(Session, usize)> {
let parent = self.parent_of(id)?.clone();
let child = self.subagents.iter().position(|s| s.id == id)?;
let timeline = std::mem::take(&mut self.subagents[child].timeline);
let changed = self.timeline_mut(&parent).and_then(|p| p.card_activity(id, &timeline));
self.subagents[child].timeline = timeline;
changed.map(|i| (parent, i))
}
/// Settles what an ended turn of the task left open. Subagents work on (in the background).
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<(Session, usize)> {
self.main.end_turn(done).into_iter().map(|i| (None, i)).collect()
}
/// Settles everything left open once the agent is gone, subagents included.
pub fn settle(&mut self, now: f64) -> Vec<(Session, usize)> {
let mut out: Vec<(Session, usize)> = self.main.end_turn(None).into_iter().map(|i| (None, i)).collect();
out.extend(self.main.stop_subagents(now).into_iter().map(|i| (None, i)));
for s in &mut self.subagents {
let id = Some(s.id.clone());
let mut changed = s.timeline.end_turn(None);
changed.extend(s.timeline.stop_subagents(now));
out.extend(changed.into_iter().map(|i| (id.clone(), i)));
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{AgentSubagentStatus, AgentToolStatus};
use serde_json::json;
fn card(c: &Conversation, session: &Session, index: usize) -> AgentEntry {
c.timeline(session).unwrap().entries[index].clone()
}
/// Claude Code's Agent tool, as `claude-agent-acp` reports it to a client with subagent sessions.
#[test]
fn a_subagent_gets_a_card_in_its_parent_and_its_own_timeline() {
let mut c = Conversation::default();
let sub = Some("child".to_owned());
let announce = json!({"sessionUpdate": "subagent_update", "sessionId": "child", "title": "Explore",
"description": "Find the parser", "capabilities": {"cancel": {}}, "state": {"state": "running"}});
assert_eq!(c.apply(Some("root"), &announce, 10.0), vec![(None, 0)]);
// The launch prompt: the parent's outgoing view, then the child's incoming one.
let prompt = json!({"sessionUpdate": "session_message", "messageId": "toolu_1",
"senderSessionId": "root", "recipientSessionId": "child",
"content": [{"type": "text", "text": "Look for it"}]});
assert_eq!(c.apply(Some("root"), &prompt, 11.0), vec![(None, 0)]);
assert_eq!(c.apply(Some("child"), &prompt, 11.0), vec![(sub.clone(), 0)]);
assert_eq!(card(&c, &sub, 0), AgentEntry::Message { incoming: true, text: "Look for it".into() });
// The child's own work stays out of the parent's timeline; its card follows it.
c.apply(
Some("child"),
&json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "hm"}}),
12.0,
);
let changed = c.apply(
Some("child"),
&json!({"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "Read lib.rs", "kind": "read", "status": "in_progress"}),
12.0,
);
assert_eq!(changed, vec![(sub.clone(), 2), (None, 0)]);
assert_eq!(c.main.entries.len(), 1);
// Settings of the child session don't touch the task.
assert_eq!(c.owner(Some("child")), sub);
assert_eq!(c.owner(Some("root")), None);
let done = json!({"sessionUpdate": "subagent_update", "sessionId": "child", "state": {"state": "idle", "stopReason": "end_turn"}});
let changed = c.apply(Some("root"), &done, 20.0);
// Its tool calls left open are settled when it stops.
assert_eq!(changed, vec![(None, 0), (sub.clone(), 2)]);
let reply = json!({"sessionUpdate": "session_message", "messageId": "toolu_1:reply", "senderSessionId": "child",
"recipientSessionId": "root", "content": [{"type": "text", "text": "In "}, {"type": "text", "text": "parser.rs"}]});
c.apply(Some("root"), &reply, 20.0);
assert_eq!(
c.main.entries[0],
AgentEntry::Subagent {
id: "child".into(),
title: Some("Explore".into()),
description: Some("Find the parser".into()),
status: AgentSubagentStatus::Done,
error: None,
prompt: Some("Look for it".into()),
reply: Some("In \nparser.rs".into()),
tools: 1,
activity: Some("Read lib.rs".into()),
started_ms: 10.0,
ended_ms: Some(20.0),
cancellable: true,
}
);
assert_eq!(c.label("child").as_deref(), Some("Explore"));
}
#[test]
fn nested_subagents_and_failures() {
let mut c = Conversation::default();
c.apply(
None,
&json!({"sessionUpdate": "subagent_update", "sessionId": "a", "state": {"state": "running"}}),
1.0,
);
c.apply(
Some("a"),
&json!({"sessionUpdate": "subagent_update", "sessionId": "b", "description": "deeper"}),
2.0,
);
let a = Some("a".to_owned());
assert!(matches!(card(&c, &a, 0), AgentEntry::Subagent { ref id, .. } if id == "b"));
let failed = json!({"sessionUpdate": "subagent_update", "sessionId": "b",
"state": {"state": "idle", "stopReason": "error", "error": {"code": -32603, "message": "boom"}}});
assert_eq!(c.apply(Some("a"), &failed, 3.0), vec![(a.clone(), 0)]);
assert!(matches!(card(&c, &a, 0),
AgentEntry::Subagent { status: AgentSubagentStatus::Failed, error: Some(ref e), ended_ms: Some(3.0), .. } if e == "boom"));
// Saved and restored, then the agent is gone: what still works is stopped.
let mut c = Conversation::restore(c.main.entries.clone(), c.saved_subagents());
c.apply(
Some("a"),
&json!({"sessionUpdate": "tool_call", "toolCallId": "t", "title": "Run", "status": "in_progress"}),
4.0,
);
let settled = c.settle(9.0);
assert_eq!(settled, vec![(None, 0), (a.clone(), 1)]);
assert!(matches!(c.main.entries[0], AgentEntry::Subagent { status: AgentSubagentStatus::Cancelled, .. }));
assert!(matches!(card(&c, &a, 1), AgentEntry::Tool { status: AgentToolStatus::Failed, .. }));
}
}
+99 -36
Переглянути файл
@@ -8,6 +8,7 @@
//! next prompt when the agent supports `session/load`.
mod config;
mod conversation;
mod model;
mod provider;
mod skills;
@@ -16,17 +17,17 @@ mod worktree;
pub use model::*;
use conversation::{Conversation, SavedSubagent, Session};
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_jsonrpc::{Framing, Handler, Peer, RpcError, codes};
use parking_lot::{Mutex, RwLock};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::{Arc, Weak};
use std::time::Duration;
use timeline::Timeline;
/// Receives the events of one project's tasks.
pub type AgentSink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
@@ -39,6 +40,9 @@ const REPLAY_GRACE: Duration = Duration::from_millis(300);
/// can trail its `session/prompt` response by this much.
const TURN_GRACE: Duration = Duration::from_millis(100);
const STDERR_LINES: usize = 20;
/// Updates of a session's state rather than its conversation.
const SESSION_STATE: [&str; 5] =
["session_info_update", "config_option_update", "current_mode_update", "available_commands_update", "usage_update"];
/// Referenced files up to this size are embedded in the prompt (when the agent takes it).
const MAX_EMBED: u64 = 256 * 1024;
@@ -152,13 +156,19 @@ struct TaskFile {
/// Settings the user chose, re-applied to every new or reloaded session.
#[serde(default)]
wanted: Vec<AgentConfigChoice>,
/// In the project's own checkout: files already changed when the task started.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
before: BTreeMap<String, worktree::Stamp>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
subagents: Vec<SavedSubagent>,
}
struct TaskState {
task: AgentTask,
session_id: Option<String>,
timeline: Timeline,
conversation: Conversation,
wanted: Vec<AgentConfigChoice>,
before: Arc<BTreeMap<String, worktree::Stamp>>,
/// A turn is running or about to (prompts arriving now are queued).
busy: bool,
}
@@ -188,7 +198,7 @@ struct Task {
replaying: AtomicBool,
/// The current turn is being cancelled to send the first queued message right away.
send_now: AtomicBool,
dirty: Mutex<BTreeSet<usize>>,
dirty: Mutex<BTreeSet<(Session, usize)>>,
flush_scheduled: AtomicBool,
stderr: Mutex<VecDeque<String>>,
/// Set by `delete`; held while saving.
@@ -231,11 +241,9 @@ impl AgentManager {
// The agent process did not survive the restart: whatever was in flight is over.
if matches!(f.task.status, AgentStatus::Running | AgentStatus::NeedsInput | AgentStatus::Starting) {
f.task.status = AgentStatus::Ready;
let mut timeline = Timeline::from_entries(std::mem::take(&mut f.entries));
timeline.end_turn(None);
f.entries = timeline.entries;
}
let task = Task::restore(f, shared.clone());
task.state.lock().conversation.settle(now_ms());
tasks.insert(task.id.clone(), task);
}
Err(e) => tracing::warn!("skipping agent task {}: {e}", path.display()),
@@ -297,8 +305,12 @@ impl AgentManager {
self.tasks.read().get(id).cloned().ok_or_else(|| IdeError::not_found(format!("no agent task {id}")))
}
pub fn entries(&self, id: &str) -> IdeResult<Vec<AgentEntry>> {
Ok(self.task(id)?.state.lock().timeline.entries.clone())
/// The entries of the task's conversation, or of its subagent `subagent`'s.
pub fn entries(&self, id: &str, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
let task = self.task(id)?;
let s = task.state.lock();
let timeline = s.conversation.timeline(&subagent).ok_or_else(|| IdeError::not_found("no such subagent"))?;
Ok(timeline.entries.clone())
}
/// Creates the task (and its worktree) and sends `req.prompt` as its first message.
@@ -310,18 +322,20 @@ impl AgentManager {
let prompt = clean(req.prompt).ok_or_else(|| IdeError::invalid("describe the task first"))?;
let title = title_of(&prompt);
let root = self.shared.paths.project_root.clone();
let (cwd, branch, base, base_commit) = match req.isolation {
let (cwd, branch, base, base_commit, before) = match req.isolation {
Isolation::Worktree => {
let dir = self.shared.paths.worktrees_dir.clone();
let (t, b) = (title.clone(), req.base.clone());
let c = blocking(move || worktree::create(&root, &dir, &t, b.as_deref())).await?;
(c.path, Some(c.branch), Some(c.base), Some(c.base_commit))
(c.path, Some(c.branch), Some(c.base), Some(c.base_commit), BTreeMap::new())
}
Isolation::Local => {
let r = root.clone();
let head = blocking(move || worktree::head_of(&r)).await.ok();
let (head, before) =
blocking(move || Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default())))
.await?;
let (base, commit) = head.unzip();
(root, None, base, commit)
(root, None, base, commit, before)
}
};
// Until the session reports its own, show what the agent offered last time with the choices applied.
@@ -351,7 +365,14 @@ impl AgentManager {
usage: None,
queue: Vec::new(),
};
let file = TaskFile { task: task.clone(), session_id: None, entries: Vec::new(), wanted: req.config };
let file = TaskFile {
task: task.clone(),
session_id: None,
entries: Vec::new(),
wanted: req.config,
before,
subagents: Vec::new(),
};
let handle = Task::restore(file, self.shared.clone());
handle.state.lock().busy = true;
self.tasks.write().insert(task.id.clone(), handle.clone());
@@ -481,9 +502,17 @@ impl AgentManager {
}
/// Stops the current turn (`session/cancel`); pending permission requests are cancelled.
/// Queued messages stay queued.
pub fn cancel(&self, id: &str) -> IdeResult<()> {
self.task(id)?.cancel();
/// Queued messages stay queued. With `subagent`, stops only that subagent's work.
pub fn cancel(&self, id: &str, subagent: Option<String>) -> IdeResult<()> {
let task = self.task(id)?;
match subagent {
None => task.cancel(),
Some(sub) => {
if let Some(live) = task.live.lock().clone() {
let _ = live.peer.notify("session/cancel", json!({ "sessionId": sub }));
}
}
}
Ok(())
}
@@ -529,8 +558,10 @@ impl AgentManager {
/// Files the task changed since it started.
pub async fn changes(&self, id: &str) -> IdeResult<Vec<AgentChange>> {
let (cwd, base) = self.task(id)?.cwd_and_base();
blocking(move || worktree::changes(&cwd, &base)).await
let task = self.task(id)?;
let (cwd, base) = task.cwd_and_base();
let before = task.state.lock().before.clone();
blocking(move || Ok(worktree::without_untouched(worktree::changes(&cwd, &base)?, &before))).await
}
/// Content of `path` (in the task's directory) when the task started.
@@ -543,6 +574,8 @@ impl AgentManager {
pub fn shutdown(&self) {
for task in self.tasks.read().values() {
task.kill();
// What arrived after the last save (a subagent's late updates).
task.persist();
}
*self.shared.sink.write() = None;
}
@@ -551,15 +584,16 @@ impl AgentManager {
impl Task {
fn restore(file: TaskFile, shared: Arc<Shared>) -> Arc<Self> {
let task = file.task;
let timeline = Timeline::from_entries(file.entries);
let conversation = Conversation::restore(file.entries, file.subagents);
Arc::new(Self {
id: task.id.clone(),
shared,
state: Mutex::new(TaskState {
task,
session_id: file.session_id,
timeline,
conversation,
wanted: file.wanted,
before: Arc::new(file.before),
busy: false,
}),
live: Mutex::new(None),
@@ -614,8 +648,10 @@ impl Task {
serde_json::to_vec(&TaskFile {
task: s.task.clone(),
session_id: s.session_id.clone(),
entries: s.timeline.entries.clone(),
entries: s.conversation.main.entries.clone(),
wanted: s.wanted.clone(),
before: (*s.before).clone(),
subagents: s.conversation.saved_subagents(),
})
};
let path = self.shared.paths.store_dir.join(format!("{}.json", self.id));
@@ -624,7 +660,7 @@ impl Task {
}
}
fn mark_dirty(self: &Arc<Self>, indices: impl IntoIterator<Item = usize>) {
fn mark_dirty(self: &Arc<Self>, indices: impl IntoIterator<Item = (Session, usize)>) {
self.dirty.lock().extend(indices);
if !self.flush_scheduled.swap(true, Ordering::AcqRel) {
let task = self.clone();
@@ -642,9 +678,9 @@ impl Task {
let s = self.state.lock();
indices
.into_iter()
.filter_map(|i| {
let entry = s.timeline.entries.get(i)?.clone();
Some(AgentEvent::Entry { task: self.id.clone(), index: i as u32, entry })
.filter_map(|(subagent, i)| {
let entry = s.conversation.timeline(&subagent)?.entries.get(i)?.clone();
Some(AgentEvent::Entry { task: self.id.clone(), subagent, index: i as u32, entry })
})
.collect()
};
@@ -654,8 +690,8 @@ impl Task {
}
fn push_entry(self: &Arc<Self>, entry: AgentEntry) -> usize {
let i = self.state.lock().timeline.push(entry);
self.mark_dirty([i]);
let i = self.state.lock().conversation.main.push(entry);
self.mark_dirty([(None, i)]);
i
}
@@ -665,7 +701,7 @@ impl Task {
loop {
let result = self.turn(&prompt).await;
tokio::time::sleep(TURN_GRACE).await;
let changed = self.state.lock().timeline.end_turn(Some(now_ms()));
let changed = self.state.lock().conversation.end_turn(Some(now_ms()));
self.mark_dirty(changed);
let send_now = self.send_now.swap(false, Ordering::AcqRel);
let next = {
@@ -779,7 +815,12 @@ impl Task {
"initialize",
json!({
"protocolVersion": 1,
"clientCapabilities": { "fs": { "readTextFile": false, "writeTextFile": false }, "terminal": false },
"clientCapabilities": {
"fs": { "readTextFile": false, "writeTextFile": false },
"terminal": false,
// Subagents as sessions of their own (ACP subagents RFD).
"subagents": {},
},
"clientInfo": { "name": "OpenIDEA", "version": env!("CARGO_PKG_VERSION") },
}),
None,
@@ -880,8 +921,16 @@ impl Task {
}
}
fn on_update(self: &Arc<Self>, update: &Value) {
/// Applies a `session/update` of session `session` (the task's, or one of its subagents').
fn on_update(self: &Arc<Self>, session: Option<&str>, update: &Value) {
let kind = update.get("sessionUpdate").and_then(Value::as_str).unwrap_or_default();
// A subagent's title, settings and usage are its own, not the task's.
if self.state.lock().conversation.owner(session).is_some() {
if !SESSION_STATE.contains(&kind) && !self.replaying.load(Ordering::Acquire) {
self.apply(session, kind, update);
}
return;
}
if kind == "session_info_update" {
// The agent's own title for the session replaces the first line of the prompt.
let title = update.get("title").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
@@ -936,8 +985,16 @@ impl Task {
if self.replaying.load(Ordering::Acquire) {
return;
}
let applied = self.state.lock().timeline.apply(update);
self.mark_dirty(applied.changed);
self.apply(session, kind, update);
}
fn apply(self: &Arc<Self>, session: Option<&str>, kind: &str, update: &Value) {
let applied = self.state.lock().conversation.apply(session, update, now_ms());
self.mark_dirty(applied);
// A subagent can start or finish after the turn that started it: saved right away.
if kind == "subagent_update" {
self.persist();
}
}
/// Blocks the calling (blocking-pool) thread until the user answers.
@@ -949,6 +1006,12 @@ impl Task {
.filter(|t| !t.is_empty())
.unwrap_or("The agent asks for permission")
.to_owned();
// A subagent's request is answered in the task's conversation, named after the subagent.
let session = params.get("sessionId").and_then(Value::as_str);
let title = match session.and_then(|s| self.state.lock().conversation.label(s)) {
Some(label) => format!("{label}: {title}"),
None => title,
};
let options: Vec<AgentPermissionOption> = params
.get("options")
.and_then(Value::as_array)
@@ -976,11 +1039,11 @@ impl Task {
.map_or_else(|| "Cancelled".to_owned(), |o| o.name.clone());
{
let mut s = self.state.lock();
if let Some(AgentEntry::Permission { chosen, .. }) = s.timeline.entries.get_mut(entry) {
if let Some(AgentEntry::Permission { chosen, .. }) = s.conversation.main.entries.get_mut(entry) {
*chosen = Some(name);
}
}
self.mark_dirty([entry]);
self.mark_dirty([(None, entry)]);
let still_asking = !self.permissions.lock().is_empty();
if !still_asking && self.state.lock().task.status == AgentStatus::NeedsInput {
self.set_status(AgentStatus::Running, None);
@@ -1022,7 +1085,7 @@ impl Handler for Client {
if method == "session/update"
&& let (Some(task), Some(update)) = (self.task.upgrade(), params.get("update"))
{
task.on_update(update);
task.on_update(params.get("sessionId").and_then(Value::as_str), update);
}
}
+41 -1
Переглянути файл
@@ -166,6 +166,18 @@ pub struct AgentToolDiff {
pub removed: u32,
}
/// What a subagent is doing, as its parent reports it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentSubagentStatus {
Running,
/// One of its requests (a permission) waits for an answer.
NeedsInput,
Done,
Cancelled,
Failed,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPlanItem {
@@ -218,6 +230,33 @@ pub enum AgentEntry {
Plan {
items: Vec<AgentPlanItem>,
},
/// A subagent the agent started: its own session, whose entries are listed separately.
Subagent {
/// The subagent's session id.
id: String,
title: Option<String>,
description: Option<String>,
status: AgentSubagentStatus,
error: Option<String>,
/// What it was asked to do, last.
prompt: Option<String>,
/// Its answer.
reply: Option<String>,
/// Tool calls it made.
tools: u32,
/// Title of its latest tool call.
activity: Option<String>,
started_ms: f64,
/// When it last stopped working; `None` while it works.
ended_ms: Option<f64>,
/// Whether it can be stopped on its own.
cancellable: bool,
},
/// A message between sessions in a subagent's conversation: its task (`incoming`) or its report.
Message {
incoming: bool,
text: String,
},
Permission {
id: u32,
title: String,
@@ -279,9 +318,10 @@ pub enum AgentEvent {
Removed {
id: String,
},
/// Entry `index` of `task` was added or replaced.
/// Entry `index` of `task` (of its subagent `subagent`) was added or replaced.
Entry {
task: String,
subagent: Option<String>,
index: u32,
entry: AgentEntry,
},
+122 -13
Переглянути файл
@@ -25,6 +25,44 @@ impl FakeAgent {
}
}
impl FakeAgent {
/// Runs a subagent in session `c1`, as an agent with ACP subagent sessions reports it.
fn delegate(&self, root: &str) {
let sub = |state: Value| json!({"sessionUpdate": "subagent_update", "sessionId": "c1", "state": state});
let mut announce = sub(json!({"state": "running"}));
announce["title"] = json!("Explore");
self.update(root, announce);
self.update(
root,
json!({"sessionUpdate": "session_message", "messageId": "m1", "senderSessionId": root,
"recipientSessionId": "c1", "content": [{"type": "text", "text": "Find the lexer"}]}),
);
self.update("c1", json!({"sessionUpdate": "usage_update", "used": 900, "size": 1000}));
self.update(
"c1",
json!({"sessionUpdate": "tool_call", "toolCallId": "c1-t1", "title": "Read lexer.rs",
"kind": "read", "status": "completed"}),
);
let peer = self.peer.get().unwrap().clone();
let _: Value = tokio::runtime::Handle::current()
.block_on(peer.request(
"session/request_permission",
json!({"sessionId": "c1", "toolCall": {"toolCallId": "c1-t2", "title": "Run ls"},
"options": [{"optionId": "yes", "name": "Allow", "kind": "allow_once"}]}),
None,
))
.unwrap();
self.say("c1", "It is in lexer.rs");
self.update(root, sub(json!({"state": "idle", "stopReason": "end_turn"})));
self.update(
root,
json!({"sessionUpdate": "session_message", "messageId": "m2", "senderSessionId": "c1",
"recipientSessionId": root, "content": [{"type": "text", "text": "lexer.rs"}]}),
);
self.say(root, "Found it");
}
}
impl Handler for FakeAgent {
fn on_notification(&self, method: &str, _: Value) {
self.calls.lock().push(method.to_owned());
@@ -34,7 +72,12 @@ impl Handler for FakeAgent {
self.calls.lock().push(method.to_owned());
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
match method {
"initialize" => Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true}})),
"initialize" => {
if params.pointer("/clientCapabilities/subagents").is_some_and(Value::is_object) {
self.calls.lock().push("subagents".into());
}
Ok(json!({"protocolVersion": 1, "agentCapabilities": {"loadSession": true}}))
}
"session/new" => Ok(json!({"sessionId": "s1",
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
"configOptions": [{"id": "model", "category": "model", "type": "select", "currentValue": "big",
@@ -53,6 +96,10 @@ impl Handler for FakeAgent {
self.say(&session, "second turn");
return Ok(json!({"stopReason": "end_turn"}));
}
if text == "delegate" {
self.delegate(&session);
return Ok(json!({"stopReason": "end_turn"}));
}
if text == "wait" {
// Works until cancelled.
while !self.calls.lock().iter().any(|c| c == "session/cancel") {
@@ -194,7 +241,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let permission = mgr
.entries(&task.id)
.entries(&task.id, None)
.unwrap()
.iter()
.find_map(|e| match e {
@@ -205,7 +252,7 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
mgr.respond(&task.id, permission, Some("yes".into())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id).unwrap();
let entries = mgr.entries(&task.id, None).unwrap();
let kinds: Vec<String> = entries
.iter()
.map(|e| match e {
@@ -261,13 +308,13 @@ async fn a_task_runs_asks_for_permission_and_survives_a_restart() {
mgr.shutdown();
let agent2 = Arc::new(FakeAgent::default());
let mgr2 = manager(tmp.path(), agent2.clone());
assert_eq!(mgr2.entries(&task.id).unwrap().len(), 5);
assert_eq!(mgr2.entries(&task.id, None).unwrap().len(), 5);
assert_eq!(mgr2.task(&task.id).unwrap().state.lock().task.title, "Lexer fix");
assert_eq!(mgr2.providers().iter().find(|p| p.id == "claude").unwrap().config.len(), 2);
mgr2.prompt(&task.id, text("again"), false).await.unwrap();
tokio::time::sleep(Duration::from_millis(50)).await;
wait_for(&mgr2, &task.id, AgentStatus::Ready).await;
let entries = mgr2.entries(&task.id).unwrap();
let entries = mgr2.entries(&task.id, None).unwrap();
assert_eq!(entries.len(), 7);
assert_eq!(entries[6], AgentEntry::Agent { text: "second turn".into() });
assert!(agent2.calls.lock().contains(&"session/load".to_owned()));
@@ -303,14 +350,14 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
mgr.send_queued_now(&task.id, &queue[0].id).unwrap();
for _ in 0..500 {
if mgr.entries(&task.id).unwrap().iter().any(|e| *e == AgentEntry::Agent { text: "second turn".into() }) {
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)
.entries(&task.id, None)
.unwrap()
.into_iter()
.filter_map(|e| match e {
@@ -326,7 +373,7 @@ async fn messages_sent_while_busy_are_queued_and_send_now_interrupts() {
wait_for(&mgr, &task.id, AgentStatus::Running).await;
agent.calls.lock().retain(|c| c != "session/cancel");
mgr.prompt(&task.id, text("later"), false).await.unwrap();
mgr.cancel(&task.id).unwrap();
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let queued = mgr.task(&task.id).unwrap().state.lock().task.queue.clone();
assert_eq!(queued.len(), 1);
@@ -334,6 +381,68 @@ 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 subagents_get_their_own_conversation() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("delegate"),
provider: "claude".into(),
config: vec![],
isolation: Isolation::Local,
base: None,
})
.await
.unwrap();
// The subagent's permission request is answered in the task's conversation.
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let (id, title) = mgr
.entries(&task.id, None)
.unwrap()
.into_iter()
.find_map(|e| match e {
AgentEntry::Permission { id, title, .. } => Some((id, title)),
_ => None,
})
.unwrap();
assert_eq!(title, "Explore: Run ls");
mgr.respond(&task.id, id, Some("yes".into())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
assert!(agent.calls.lock().iter().any(|c| c == "subagents"));
let check = |mgr: &AgentManager| {
let main = mgr.entries(&task.id, None).unwrap();
let card = main.iter().find(|e| matches!(e, AgentEntry::Subagent { .. })).unwrap();
let AgentEntry::Subagent { title, status, prompt, reply, tools, activity, .. } = card else { unreachable!() };
assert_eq!(title.as_deref(), Some("Explore"));
assert_eq!(*status, AgentSubagentStatus::Done);
assert_eq!((prompt.as_deref(), reply.as_deref()), (Some("Find the lexer"), Some("lexer.rs")));
assert_eq!((*tools, activity.as_deref()), (1, Some("Read lexer.rs")));
assert!(main.contains(&AgentEntry::Agent { text: "Found it".into() }));
assert!(!main.iter().any(|e| matches!(e, AgentEntry::Tool { .. })));
let sub = mgr.entries(&task.id, Some("c1".into())).unwrap();
assert!(matches!(&sub[0], AgentEntry::Tool { title, .. } if title == "Read lexer.rs"));
assert_eq!(sub[1], AgentEntry::Agent { text: "It is in lexer.rs".into() });
};
// Updates can trail the end of the turn.
for _ in 0..500 {
if mgr.entries(&task.id, None).unwrap().contains(&AgentEntry::Agent { text: "Found it".into() }) {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
check(&mgr);
// The subagent's context use is not the task's.
assert_ne!(mgr.task(&task.id).unwrap().state.lock().task.usage.as_ref().map(|u| u.used), Some(900));
assert!(mgr.entries(&task.id, Some("nope".into())).is_err());
// Saved with the task.
mgr.shutdown();
check(&manager(tmp.path(), Arc::new(FakeAgent::default())));
}
#[test]
fn prompts_become_acp_content_blocks() {
let p = AgentPrompt {
@@ -381,15 +490,15 @@ async fn cancelling_resolves_the_open_permission_and_delete_forgets_the_task() {
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
mgr.cancel(&task.id).unwrap();
mgr.cancel(&task.id, None).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id).unwrap();
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Permission { chosen: Some(c), .. } if c == "Cancelled")));
assert_eq!(entries.last(), Some(&AgentEntry::Agent { text: "chose none".into() }));
assert_eq!(mgr.task(&task.id).unwrap().state.lock().task.model.as_deref(), Some("big"), "the agent's default");
mgr.delete(&task.id, false).await.unwrap();
assert!(mgr.entries(&task.id).is_err());
assert!(mgr.entries(&task.id, None).is_err());
assert!(!tmp.path().join("store").join(format!("{}.json", task.id)).exists());
assert!(
mgr.create(NewAgentTask {
@@ -452,7 +561,7 @@ async fn real_claude_task_in_a_worktree() {
let status = mgr.task(&task.id).unwrap().state.lock().task.status;
match status {
AgentStatus::NeedsInput => {
let pending = mgr.entries(&task.id).unwrap().into_iter().rev().find_map(|e| match e {
let pending = mgr.entries(&task.id, None).unwrap().into_iter().rev().find_map(|e| match e {
AgentEntry::Permission { id, options, chosen: None, .. } => Some((id, options)),
_ => None,
});
@@ -467,7 +576,7 @@ async fn real_claude_task_in_a_worktree() {
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
for e in mgr.entries(&task.id).unwrap() {
for e in mgr.entries(&task.id, None).unwrap() {
eprintln!("{e:?}");
}
let t = mgr.task(&task.id).unwrap().state.lock().task.clone();
+145 -2
Переглянути файл
@@ -1,6 +1,6 @@
//! Folds ACP `session/update` notifications into a task's entries.
use crate::model::{AgentEntry, AgentPlanItem, AgentToolDiff, AgentToolStatus};
use crate::model::{AgentEntry, AgentPlanItem, AgentSubagentStatus, AgentToolDiff, AgentToolStatus};
use ide_core::IpcPath;
use serde_json::Value;
use std::collections::HashMap;
@@ -13,6 +13,10 @@ pub(crate) struct Timeline {
pub entries: Vec<AgentEntry>,
tools: HashMap<String, usize>,
plan: Option<usize>,
/// Subagent cards, by the subagent's session id.
cards: HashMap<String, usize>,
/// Session messages, by message id.
messages: HashMap<String, usize>,
}
/// What a `session/update` changed in the timeline.
@@ -31,6 +35,9 @@ impl Timeline {
t.tools.insert(id.clone(), i);
}
AgentEntry::Plan { .. } => t.plan = Some(i),
AgentEntry::Subagent { id, .. } => {
t.cards.insert(id.clone(), i);
}
_ => {}
}
}
@@ -166,6 +173,119 @@ impl Timeline {
}
}
/// Adds or updates the card of subagent `id` from its `subagent_update`; returns the
/// card's index and whether the subagent just stopped working.
pub fn subagent(&mut self, id: &str, update: &Value, now: f64) -> (usize, bool) {
let index = match self.cards.get(id) {
Some(&i) => i,
None => {
let i = self.push(AgentEntry::Subagent {
id: id.to_owned(),
title: None,
description: None,
status: AgentSubagentStatus::Running,
error: None,
prompt: None,
reply: None,
tools: 0,
activity: None,
started_ms: now,
ended_ms: None,
cancellable: false,
});
self.cards.insert(id.to_owned(), i);
i
}
};
let AgentEntry::Subagent { title, description, status, error, ended_ms, cancellable, .. } =
&mut self.entries[index]
else {
return (index, false);
};
// Patch semantics: an omitted field is unchanged, `null` clears it.
if let Some(v) = update.get("title") {
*title = v.as_str().map(str::to_owned);
}
if let Some(v) = update.get("description") {
*description = v.as_str().map(str::to_owned);
}
if let Some(v) = update.get("capabilities") {
*cancellable = v.get("cancel").is_some_and(Value::is_object);
}
let mut stopped = false;
if let Some((next, message)) = update.get("state").and_then(subagent_status) {
let working = matches!(next, AgentSubagentStatus::Running | AgentSubagentStatus::NeedsInput);
stopped = !working && ended_ms.is_none();
*ended_ms = if working { None } else { ended_ms.or(Some(now)) };
*status = next;
*error = message;
}
(index, stopped)
}
/// Sets (or with `append`, extends) what subagent `id` was asked or answered, on its card.
pub fn card_message(&mut self, id: &str, reply: bool, text: &str, append: bool) -> Option<usize> {
let &index = self.cards.get(id)?;
let AgentEntry::Subagent { prompt, reply: answer, .. } = &mut self.entries[index] else { return None };
let field = if reply { answer } else { prompt };
match field {
Some(t) if append => t.push_str(text),
_ => *field = Some(text.to_owned()),
}
Some(index)
}
/// Adds, replaces or (with `append`) extends session message `id`.
pub fn message(&mut self, id: &str, incoming: bool, text: &str, append: bool) -> usize {
if let Some(&i) = self.messages.get(id)
&& let AgentEntry::Message { text: t, .. } = &mut self.entries[i]
{
if append {
t.push_str(text);
} else {
*t = text.to_owned();
}
return i;
}
let i = self.push(AgentEntry::Message { incoming, text: text.to_owned() });
self.messages.insert(id.to_owned(), i);
i
}
/// Updates subagent `id`'s card with what its own timeline `of` shows: how many tool
/// calls it made and its latest one. Returns the card's index when it changed.
pub fn card_activity(&mut self, id: &str, of: &Timeline) -> Option<usize> {
let &index = self.cards.get(id)?;
let AgentEntry::Subagent { tools, activity, .. } = &mut self.entries[index] else { return None };
let calls = of.entries.iter().filter_map(|e| match e {
AgentEntry::Tool { title, kind, .. } => Some(if title.is_empty() { kind } else { title }),
_ => None,
});
let count = calls.clone().count() as u32;
let latest = calls.clone().next_back().cloned();
if *tools == count && *activity == latest {
return None;
}
*tools = count;
*activity = latest;
Some(index)
}
/// Marks the subagents still working as stopped (their agent is gone).
pub fn stop_subagents(&mut self, now: f64) -> Vec<usize> {
let mut changed = Vec::new();
for (i, e) in self.entries.iter_mut().enumerate() {
if let AgentEntry::Subagent { status, ended_ms, .. } = e
&& matches!(status, AgentSubagentStatus::Running | AgentSubagentStatus::NeedsInput)
{
*status = AgentSubagentStatus::Cancelled;
*ended_ms = Some(now);
changed.push(i);
}
}
changed
}
/// Settles what an ended turn left open: running tools and pending permissions,
/// and records when the turn ended (`done`) on the message that started it.
pub fn end_turn(&mut self, done: Option<f64>) -> Vec<usize> {
@@ -198,7 +318,30 @@ fn str_field(v: &Value, key: &str) -> String {
v.get(key).and_then(Value::as_str).unwrap_or_default().to_owned()
}
fn content_text(content: Option<&Value>) -> Option<String> {
/// The status a subagent `state` reports, with its error message; `None` for an unknown state.
fn subagent_status(state: &Value) -> Option<(AgentSubagentStatus, Option<String>)> {
Some(match state.get("state")?.as_str()? {
"running" => (AgentSubagentStatus::Running, None),
"requires_action" => (AgentSubagentStatus::NeedsInput, None),
"idle" => match state.get("stopReason").and_then(Value::as_str) {
Some("cancelled") => (AgentSubagentStatus::Cancelled, None),
Some("error") => (
AgentSubagentStatus::Failed,
state.pointer("/error/message").and_then(Value::as_str).map(str::to_owned),
),
_ => (AgentSubagentStatus::Done, None),
},
_ => return None,
})
}
/// The text of a list of content blocks, one per line.
pub(crate) fn blocks_text(content: Option<&Value>) -> String {
let blocks = content.and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
blocks.iter().filter_map(|b| content_text(Some(b))).collect::<Vec<_>>().join("\n")
}
pub(crate) fn content_text(content: Option<&Value>) -> Option<String> {
let c = content?;
match c.get("type").and_then(Value::as_str) {
Some("text") => c.get("text").and_then(Value::as_str).map(str::to_owned),
+32
Переглянути файл
@@ -3,7 +3,9 @@
use crate::model::AgentChange;
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_vcs::{ChangeKind, Repo};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
pub(crate) struct Created {
pub path: PathBuf,
@@ -74,6 +76,25 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
Ok(out)
}
/// Size and modification time of a file, `None` once it is gone.
pub(crate) type Stamp = Option<(u64, u128)>;
fn stamp(path: &Path) -> Stamp {
let meta = std::fs::metadata(path).ok()?;
let modified = meta.modified().ok()?.duration_since(UNIX_EPOCH).ok()?.as_nanos();
Some((meta.len(), modified))
}
/// The files already changed in `cwd` against `HEAD`, stamped so later edits to them show.
pub(crate) fn snapshot(cwd: &Path) -> IdeResult<BTreeMap<String, Stamp>> {
Ok(changes(cwd, "HEAD")?.into_iter().map(|c| (c.rel_path, stamp(&c.path))).collect())
}
/// Drops the changes that were there before the task and haven't been touched since.
pub(crate) fn without_untouched(changes: Vec<AgentChange>, before: &BTreeMap<String, Stamp>) -> Vec<AgentChange> {
changes.into_iter().filter(|c| before.get(&c.rel_path).is_none_or(|s| *s != stamp(&c.path))).collect()
}
pub(crate) fn file_at(cwd: &Path, path: &Path, rev: &str) -> IdeResult<Option<String>> {
repo_at(cwd)?.file_at(path, Some(rev))
}
@@ -148,6 +169,17 @@ mod tests {
let base_text = file_at(&created.path, &created.path.join("a.txt"), &created.base_commit).unwrap();
assert_eq!(base_text.as_deref(), Some("one\ntwo\n"));
// Changes already in the checkout drop out until they are edited again.
let before = snapshot(&created.path).unwrap();
std::fs::write(created.path.join("b.txt"), "b\n").unwrap();
let rels = |c: Vec<AgentChange>| c.into_iter().map(|c| c.rel_path).collect::<Vec<_>>();
let after = changes(&created.path, "HEAD").unwrap();
assert_eq!(rels(without_untouched(after, &before)), ["b.txt"]);
std::thread::sleep(std::time::Duration::from_millis(10));
std::fs::write(created.path.join("new.txt"), "x\ny\nz\n").unwrap();
let after = changes(&created.path, "HEAD").unwrap();
assert_eq!(rels(without_untouched(after, &before)), ["b.txt", "new.txt"]);
// A second task with the same title gets its own worktree.
assert_eq!(create(&repo, &tmp.path().join("wt"), "Edit A", None).unwrap().branch, "agent/edit-a-2");
remove(&repo, &created.path).unwrap();
+1 -1
Переглянути файл
@@ -52,7 +52,7 @@ pub(crate) fn run(
use std::os::unix::process::CommandExt;
command.process_group(0);
}
ide_core::process::no_window(&mut command);
ide_core::process::prepare(&mut command);
let mut child = command.spawn().map_err(|e| IdeError::unavailable(format!("cannot start {program}: {e}")))?;
let (tx, rx) = mpsc::channel::<(Stream, String)>();
let pump = |stream: Box<dyn Read + Send>, kind: Stream, tx: mpsc::Sender<(Stream, String)>| {
+9
Переглянути файл
@@ -55,7 +55,13 @@ pub struct EditorAppearanceSettings {
pub caret_blinking: bool,
/// Blink period in ms.
pub caret_blink_period: u32,
/// Fade the caret in and out instead of toggling it; rounds its corners.
pub smooth_caret_blinking: bool,
pub block_caret: bool,
/// Animate the caret between positions when it is moved.
pub smooth_caret_movement: bool,
/// Smooth caret movement curve: `snappy` | `gliding`.
pub caret_movement_style: String,
pub line_numbers: bool,
pub method_separators: bool,
/// Sub-options of `editor.showWhitespace`.
@@ -75,7 +81,10 @@ impl Default for EditorAppearanceSettings {
Self {
caret_blinking: true,
caret_blink_period: 500,
smooth_caret_blinking: false,
block_caret: false,
smooth_caret_movement: false,
caret_movement_style: "snappy".into(),
line_numbers: true,
method_separators: false,
whitespace_leading: true,
+5
Переглянути файл
@@ -67,6 +67,11 @@ pub enum IdeEvent {
status: ServerStatus,
message: Option<String>,
},
/// A stopped language server left the project's list (disabled in settings, or a
/// fallback that a preferred server took over from again).
LanguageServerRemoved {
server: ServerId,
},
/// A language server asked clients to re-request one kind of data for its
/// open documents (`workspace/inlayHint/refresh`, …), e.g. after indexing.
LspRefresh {
+209 -6
Переглянути файл
@@ -5,22 +5,121 @@ use std::process::Command;
use std::sync::OnceLock;
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
/// with other flags. Prefer [`no_window`] otherwise.
/// with other flags (and then call [`host_env`] themselves). Prefer [`prepare`] otherwise.
pub const CREATE_NO_WINDOW: u32 = 0x0800_0000;
/// Keeps a console child (java, node, curl, a language server, ...) from
/// opening its own console window on Windows. Release builds use the GUI
/// subsystem, so without this every spawn flashes a `cmd` window. A no-op
/// elsewhere. For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
pub fn no_window(cmd: &mut Command) -> &mut Command {
/// Readies `cmd` for spawning any child (java, node, curl, git, a language server, ...).
/// For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
///
/// - Windows: release builds use the GUI subsystem, so without `CREATE_NO_WINDOW` every
/// console child flashes a `cmd` window.
/// - Linux AppImage: see [`host_env`].
///
/// Variables the call site has already set are kept; call it before `env_clear`.
pub fn prepare(cmd: &mut Command) -> &mut Command {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(CREATE_NO_WINDOW);
}
host_env(cmd)
}
/// Gives `cmd` the host's environment back when the IDE runs from an AppImage. `AppRun` and
/// its hooks point `LD_LIBRARY_PATH`, `PATH`, `XDG_DATA_DIRS`, `GIO_MODULE_DIR`, `GTK_PATH`,
/// `GST_PLUGIN_*`, ... into the mounted image for the IDE itself; a host program that
/// inherits them loads the image's (older) libraries and plugins next to its own, e.g.
/// `curl: symbol lookup error ... nghttp2_...`. The IDE process keeps its environment
/// (WebKit and GTK still need it). Variables the call site has already set are kept.
/// A no-op outside an AppImage.
pub fn host_env(cmd: &mut Command) -> &mut Command {
let fixes = appimage_fixes();
if fixes.is_empty() {
return cmd;
}
let explicit: Vec<OsString> = cmd.get_envs().map(|(k, _)| k.to_owned()).collect();
for (key, value) in fixes.into_iter().filter(|(k, _)| !explicit.contains(k)) {
match value {
Some(v) => cmd.env(key, v),
None => cmd.env_remove(key),
};
}
cmd
}
/// The [`host_env`] changes as `(name, value)` pairs, `None` meaning "remove", for spawners
/// that are not a `std::process::Command` (a PTY `CommandBuilder`). Apply before the call
/// site's own variables. Empty outside an AppImage.
pub fn host_env_fixes() -> Vec<(OsString, Option<OsString>)> {
appimage_fixes()
}
/// This process's environment as a child should inherit it (see [`host_env`]), for call
/// sites that build a child's environment from the IDE's own instead of inheriting it.
pub fn host_vars() -> impl Iterator<Item = (OsString, OsString)> {
let fixes = appimage_fixes();
std::env::vars_os().filter_map(move |(k, v)| match fixes.iter().find(|(f, _)| *f == k) {
Some((_, fixed)) => fixed.clone().map(|v| (k, v)),
None => Some((k, v)),
})
}
/// [`std::env::var_os`] as a child should see it (see [`host_env`]).
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
let key = key.as_ref();
match appimage_fixes().into_iter().find(|(k, _)| k == key) {
Some((_, fixed)) => fixed,
None => std::env::var_os(key),
}
}
/// Read on every call, not cached: startup rewrites `PATH` (login shell, managed tools).
fn appimage_fixes() -> Vec<(OsString, Option<OsString>)> {
if !cfg!(target_os = "linux") || std::env::var_os("APPDIR").is_none() {
return Vec::new();
}
appimage_env_fixes(&std::env::vars_os().collect::<Vec<_>>())
}
/// Variables the AppImage runtime sets to describe the IDE's own launch.
const APPIMAGE_LAUNCH_VARS: [&str; 4] = ["APPDIR", "APPIMAGE", "ARGV0", "OWD"];
/// What to change in `vars` (an environment) so a child sees the host's environment rather
/// than the AppImage's: every `:`-separated entry inside `$APPDIR` is dropped (a saved
/// `<NAME>_ORIG` wins when present), variables left empty are removed, and so are the
/// runtime's own launch variables. Nothing changes when `APPDIR` is not set.
fn appimage_env_fixes(vars: &[(OsString, OsString)]) -> Vec<(OsString, Option<OsString>)> {
let get = |name: &str| vars.iter().find(|(k, _)| k == name).map(|(_, v)| v);
let Some(appdir) =
get("APPDIR").and_then(|v| v.to_str()).map(|v| v.trim_end_matches('/')).filter(|v| !v.is_empty())
else {
return Vec::new();
};
let inside = |entry: &str| entry.strip_prefix(appdir).is_some_and(|rest| rest.is_empty() || rest.starts_with('/'));
let mut fixes = Vec::new();
for (key, value) in vars {
let (Some(name), Some(value)) = (key.to_str(), value.to_str()) else { continue };
let fixed = if APPIMAGE_LAUNCH_VARS.contains(&name) {
None
} else if value.split(':').any(inside) {
match get(&format!("{name}_ORIG")) {
Some(orig) => Some(orig.clone()),
None => {
let kept: Vec<&str> = value.split(':').filter(|e| !e.is_empty() && !inside(e)).collect();
Some(OsString::from(kept.join(":")))
}
}
} else if name == "GTK_THEME" && value.is_empty() {
// linuxdeploy-plugin-gtk exports `GTK_THEME="$APPIMAGE_GTK_THEME"`, usually empty.
None
} else {
continue;
};
fixes.push((key.clone(), fixed.filter(|v| !v.is_empty())));
}
fixes
}
static SHELL_ENV: OnceLock<Vec<(OsString, OsString)>> = OnceLock::new();
/// Records the login shell's environment, read once at startup off the main thread.
@@ -50,4 +149,108 @@ mod tests {
let vars: Vec<_> = shell_env().collect();
assert_eq!(vars, [(OsStr::new("OPENIDEA_SHELL_ONLY_VAR"), OsStr::new("1"))]);
}
fn env(pairs: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
pairs.iter().map(|(k, v)| (OsString::from(k), OsString::from(v))).collect()
}
fn fixes(pairs: &[(&str, &str)]) -> Vec<(String, Option<String>)> {
appimage_env_fixes(&env(pairs))
.into_iter()
.map(|(k, v)| (k.into_string().unwrap(), v.map(|v| v.into_string().unwrap())))
.collect()
}
fn fix(name: &str, value: Option<&str>) -> (String, Option<String>) {
(name.to_owned(), value.map(str::to_owned))
}
#[test]
fn appimage_entries_are_dropped_and_host_entries_kept() {
let got = fixes(&[
("APPDIR", "/tmp/.mount_OpenIDabc"),
(
"LD_LIBRARY_PATH",
"/tmp/.mount_OpenIDabc/usr/lib/:/tmp/.mount_OpenIDabc/usr/lib/x86_64-linux-gnu/:/opt/cuda/lib64:/usr/local/lib",
),
("PATH", "/tmp/.mount_OpenIDabc/usr/bin/:/tmp/.mount_OpenIDabc/usr/sbin/:/usr/local/bin:/usr/bin"),
("XDG_DATA_DIRS", "/tmp/.mount_OpenIDabc/usr/share:/usr/share:/usr/local/share:/usr/share"),
("HOME", "/home/me"),
("JAVA_HOME", "/tmp/.mount_OpenIDabcdef/jdk"),
]);
assert_eq!(
got,
[
fix("APPDIR", None),
fix("LD_LIBRARY_PATH", Some("/opt/cuda/lib64:/usr/local/lib")),
fix("PATH", Some("/usr/local/bin:/usr/bin")),
fix("XDG_DATA_DIRS", Some("/usr/share:/usr/local/share:/usr/share")),
]
);
}
#[test]
fn variables_left_empty_are_removed() {
// AppRun prepends to an unset variable, leaving a trailing `:`; hooks set single paths.
let got = fixes(&[
("APPIMAGE", "/opt/openidea/OpenIDEA.AppImage"),
("APPDIR", "/tmp/.mount_x/"),
("ARGV0", "/opt/openidea/OpenIDEA.AppImage"),
("OWD", "/home/me"),
("LD_LIBRARY_PATH", "/tmp/.mount_x/usr/lib/:/tmp/.mount_x/lib/:"),
("GIO_MODULE_DIR", "/tmp/.mount_x/usr/lib/gio/modules"),
("GTK_DATA_PREFIX", "/tmp/.mount_x"),
("GDK_PIXBUF_MODULE_FILE", "/tmp/.mount_x/usr/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache"),
("GST_PLUGIN_SYSTEM_PATH_1_0", "/tmp/.mount_x/usr/lib/gstreamer-1.0"),
("GTK_THEME", ""),
]);
let names: Vec<_> = got.iter().filter(|(_, v)| v.is_none()).map(|(k, _)| k.as_str()).collect();
assert_eq!(
names,
[
"APPIMAGE",
"APPDIR",
"ARGV0",
"OWD",
"LD_LIBRARY_PATH",
"GIO_MODULE_DIR",
"GTK_DATA_PREFIX",
"GDK_PIXBUF_MODULE_FILE",
"GST_PLUGIN_SYSTEM_PATH_1_0",
"GTK_THEME",
]
);
assert_eq!(names.len(), got.len());
}
#[test]
fn a_saved_original_value_wins() {
let got = fixes(&[
("APPDIR", "/tmp/.mount_x"),
("LD_LIBRARY_PATH", "/tmp/.mount_x/usr/lib:/opt/lib"),
("LD_LIBRARY_PATH_ORIG", "/opt/lib:/home/me/lib"),
("PYTHONHOME", "/tmp/.mount_x/usr"),
("PYTHONHOME_ORIG", ""),
]);
assert_eq!(
got,
[fix("APPDIR", None), fix("LD_LIBRARY_PATH", Some("/opt/lib:/home/me/lib")), fix("PYTHONHOME", None)]
);
}
#[test]
fn outside_an_appimage_nothing_changes() {
let plain = [("LD_LIBRARY_PATH", "/opt/lib:"), ("PATH", "/usr/bin"), ("GTK_THEME", "")];
assert!(fixes(&plain).is_empty());
assert!(fixes(&[("APPDIR", ""), ("PATH", "/usr/bin")]).is_empty());
assert!(fixes(&[("APPDIR", "/"), ("PATH", "/usr/bin")]).is_empty());
}
#[test]
fn host_env_keeps_what_the_call_site_set() {
let mut cmd = Command::new("true");
cmd.env("PATH", "/custom");
prepare(&mut cmd);
assert_eq!(cmd.get_envs().find(|(k, _)| *k == "PATH").and_then(|(_, v)| v), Some(OsStr::new("/custom")));
}
}
+48 -2
Переглянути файл
@@ -17,6 +17,7 @@ pub struct VcsSettings {
pub git: GitSettings,
pub commit: CommitSettings,
pub confirmation: VcsConfirmationSettings,
pub shelf: ShelfSettings,
/// Issue Navigation: commit-message patterns turned into links.
pub issue_navigation: Vec<IssueLink>,
}
@@ -31,6 +32,7 @@ impl Default for VcsSettings {
git: GitSettings::default(),
commit: CommitSettings::default(),
confirmation: VcsConfirmationSettings::default(),
shelf: ShelfSettings::default(),
issue_navigation: Vec::new(),
}
}
@@ -53,6 +55,17 @@ pub struct GitSettings {
pub protected_branches: String,
/// Initial state of Commit Options › Sign-off Commit.
pub sign_off: bool,
/// Ask before committing files larger than `large_file_mb`.
pub warn_large_files: bool,
pub large_file_mb: u32,
/// Ask before committing names that are invalid on Windows or differ only in case.
pub warn_bad_file_names: bool,
/// Commit and Push opens the Push dialog; otherwise it pushes right away.
pub show_push_dialog: bool,
/// With `show_push_dialog`: only for commits to protected branches.
pub push_dialog_only_protected: bool,
/// Stashes and shelves share one tab.
pub combine_stash_and_shelf: bool,
}
impl Default for GitSettings {
@@ -66,6 +79,12 @@ impl Default for GitSettings {
incoming_check: "auto".into(),
protected_branches: "master; main".into(),
sign_off: false,
warn_large_files: true,
large_file_mb: 50,
warn_bad_file_names: true,
show_push_dialog: true,
push_dialog_only_protected: false,
combine_stash_and_shelf: false,
}
}
}
@@ -74,6 +93,11 @@ impl Default for GitSettings {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct CommitSettings {
/// Commit from the Commit tool window; off = Local Changes in the Git tool
/// window and a Commit dialog.
pub non_modal: bool,
/// Start with an empty message instead of the last one / the changelist's.
pub clear_initial_message: bool,
pub analyze_code: bool,
pub check_todo: bool,
pub reformat: bool,
@@ -91,6 +115,8 @@ pub struct CommitSettings {
impl Default for CommitSettings {
fn default() -> Self {
Self {
non_modal: true,
clear_initial_message: false,
analyze_code: true,
check_todo: true,
reformat: false,
@@ -107,20 +133,40 @@ impl Default for CommitSettings {
}
}
/// Version Control › Confirmation. Values: `ask` | `silently` | `never`.
/// Version Control › Confirmation.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct VcsConfirmationSettings {
/// `ask` | `silently` | `never`.
pub on_create: String,
pub on_delete: String,
/// Update Project opens its options dialog first.
pub show_update_options: bool,
pub confirm_drop_commits: bool,
/// After a patch is saved: `ask` | `no` | `reveal` (show it in the file manager).
pub on_patch_created: String,
}
impl Default for VcsConfirmationSettings {
fn default() -> Self {
Self { on_create: "ask".into(), on_delete: "ask".into() }
Self {
on_create: "ask".into(),
on_delete: "ask".into(),
show_update_options: true,
confirm_drop_commits: true,
on_patch_created: "ask".into(),
}
}
}
/// Version Control › Shelf.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ShelfSettings {
/// Initial state of Unshelve's "Remove successfully applied files from the shelf".
pub remove_applied: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct IssueLink {
+1 -1
Переглянути файл
@@ -206,7 +206,7 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
CoverageReportSpec::Exported { runner, argv, cwd, env, lcov } => {
let (program, args) =
argv.split_first().ok_or_else(|| IdeError::invalid("empty coverage export command"))?;
let out = ide_core::process::no_window(&mut Command::new(program))
let out = ide_core::process::prepare(&mut Command::new(program))
.args(args)
.current_dir(cwd)
.envs(env)
+2 -2
Переглянути файл
@@ -257,7 +257,7 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
return Ok(()); // Reported as a missing adapter when it is started.
};
let mut probe = Command::new(&python);
ide_core::process::no_window(probe.as_std_mut());
ide_core::process::prepare(probe.as_std_mut());
let probe = probe
.args(["-c", "import debugpy.adapter"])
.current_dir(&spec.cwd)
@@ -396,7 +396,7 @@ impl AdapterLauncher for ProcessLauncher {
None => args,
};
let mut cmd = Command::new(&binary);
ide_core::process::no_window(cmd.as_std_mut());
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(&args)
.envs(spec.env.iter().map(|(k, v)| (k, v)))
.current_dir(&spec.cwd)
+4 -2
Переглянути файл
@@ -170,7 +170,7 @@ pub fn is_go_binary(exe: &str) -> bool {
pub fn list_processes() -> IdeResult<Vec<RawProcess>> {
use std::collections::HashMap;
let ps = |fields: &str| -> IdeResult<String> {
let out = std::process::Command::new("ps")
let out = ide_core::process::prepare(&mut std::process::Command::new("ps"))
.args(["-x", "-ww", "-o", fields])
.output()
.map_err(|e| IdeError::unavailable(format!("cannot list processes: {e}")))?;
@@ -212,7 +212,9 @@ pub const NODE_INSPECTOR_PORT: u16 = 9229;
/// picker does) and waits until it listens. Returns the inspector port.
#[cfg(unix)]
pub async fn enable_node_inspector(pid: u32) -> IdeResult<u16> {
let status = tokio::process::Command::new("kill")
let mut kill = tokio::process::Command::new("kill");
ide_core::process::prepare(kill.as_std_mut());
let status = kill
.args(["-USR1", &pid.to_string()])
.status()
.await
+1 -1
Переглянути файл
@@ -55,7 +55,7 @@ pub async fn build(
) -> IdeResult<PathBuf> {
let cargo = find_binary("cargo", cwd).ok_or_else(|| IdeError::unavailable("`cargo` not found on PATH"))?;
let mut cmd = tokio::process::Command::new(cargo);
ide_core::process::no_window(cmd.as_std_mut());
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(args)
.arg("--message-format=json-render-diagnostics")
.current_dir(cwd)
+1 -1
Переглянути файл
@@ -421,7 +421,7 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
return Err("runInTerminal without args".into());
};
let mut cmd = tokio::process::Command::new(program);
ide_core::process::no_window(cmd.as_std_mut());
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(rest)
.envs(ide_core::process::shell_env())
.stdin(Stdio::null())
+1 -1
Переглянути файл
@@ -69,7 +69,7 @@ pub fn docker_executable() -> Option<PathBuf> {
pub fn run_env(ep: &DockerEndpoint) -> std::collections::BTreeMap<String, String> {
let mut env = ep.env_vars();
if let Some(dir) = docker_executable().as_deref().and_then(Path::parent) {
let current = std::env::var_os("PATH").unwrap_or_default();
let current = ide_core::process::host_var_os("PATH").unwrap_or_default();
let mut dirs: Vec<PathBuf> = vec![dir.to_path_buf()];
dirs.extend(std::env::split_paths(&current).filter(|d| d != dir));
if let Ok(path) = std::env::join_paths(dirs) {
+1 -1
Переглянути файл
@@ -25,7 +25,7 @@ fn prepare(cmd: &mut Command) {
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
ide_core::process::no_window(cmd);
ide_core::process::prepare(cmd);
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
+1 -1
Переглянути файл
@@ -25,7 +25,7 @@ fn prepare(cmd: &mut Command) {
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
ide_core::process::no_window(cmd);
ide_core::process::prepare(cmd);
}
fn spawn(cmd: &mut Command) -> IdeResult<Child> {
+8 -6
Переглянути файл
@@ -28,8 +28,9 @@ pub async fn commands(
host.project(window)?.agents.commands(&provider, task.as_deref()).await
}
pub fn entries(host: &Host, window: &str, task: String) -> IdeResult<Vec<AgentEntry>> {
host.project(window)?.agents.entries(&task)
/// Entries of `task`'s conversation, or of its subagent `subagent`'s.
pub fn entries(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
host.project(window)?.agents.entries(&task, subagent)
}
pub async fn create(host: &Host, window: &str, request: NewAgentTask) -> IdeResult<AgentTask> {
@@ -56,8 +57,9 @@ pub async fn set_config(host: &Host, window: &str, task: String, option: String,
host.project(window)?.agents.set_config(&task, &option, value).await
}
pub fn cancel(host: &Host, window: &str, task: String) -> IdeResult<()> {
host.project(window)?.agents.cancel(&task)
/// Stops the task's current turn, or with `subagent` only that subagent's work.
pub fn cancel(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<()> {
host.project(window)?.agents.cancel(&task, subagent)
}
/// Answers a permission request; `option: None` cancels it.
@@ -87,7 +89,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("agent_subscribe", |c| async move { subscribe(&c.host, &c.window, c.channel("onEvent")?) });
d.add("agent_providers", |c| async move { providers(&c.host, &c.window) });
d.add("agent_commands", |c| async move { commands(&c.host, &c.window, c.arg("provider")?, c.arg("task")?).await });
d.add("agent_entries", |c| async move { entries(&c.host, &c.window, c.arg("task")?) });
d.add("agent_entries", |c| async move { entries(&c.host, &c.window, c.arg("task")?, c.arg("subagent")?) });
d.add("agent_create", |c| async move { create(&c.host, &c.window, c.arg("request")?).await });
d.add("agent_prompt", |c| async move {
prompt(&c.host, &c.window, c.arg("task")?, c.arg("prompt")?, c.arg("now")?).await
@@ -100,7 +102,7 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("agent_set_config", |c| async move {
set_config(&c.host, &c.window, c.arg("task")?, c.arg("option")?, c.arg("value")?).await
});
d.add("agent_cancel", |c| async move { cancel(&c.host, &c.window, c.arg("task")?) });
d.add("agent_cancel", |c| async move { cancel(&c.host, &c.window, c.arg("task")?, c.arg("subagent")?) });
d.add("agent_respond", |c| async move {
respond(&c.host, &c.window, c.arg("task")?, c.arg("permission")?, c.arg("option")?)
});
+3
Переглянути файл
@@ -8,6 +8,9 @@ pub async fn open(host: &Host, window: &str, path: PathBuf) -> IdeResult<Documen
host.blocking(move || {
let info = project.documents.open(&path)?;
project.index.mark_recent(&path);
if let Some(dir) = path.parent().filter(|_| project.light) {
project.watch_light_dir(dir);
}
Ok(info)
})
.await
+4 -3
Переглянути файл
@@ -38,7 +38,7 @@ pub async fn open(host: &Arc<Host>, window: &str, path: &Path) -> IdeResult<Arc<
}
pub fn current(host: &Host, window: &str) -> Option<ProjectInfo> {
host.project(window).ok().map(|p| info(&p))
host.project(window).ok().filter(|p| !p.light).map(|p| info(&p))
}
/// Effective settings for the window's project, or global settings without one.
@@ -75,7 +75,8 @@ pub fn set_settings(
let value: serde_json::Value =
serde_json::from_str(value).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?;
let current = host.project(window).ok();
let project_scope = matches!(scope, SettingsScope::Project) && current.is_some();
// A LightEdit window has no project layer: its values are global.
let project_scope = matches!(scope, SettingsScope::Project) && current.as_ref().is_some_and(|p| !p.light);
let settings = match &current {
Some(p) if project_scope => p.settings.set(scope, key, value)?,
Some(p) => {
@@ -90,7 +91,7 @@ pub fn set_settings(
// A global value reaches every other open project too.
if !project_scope {
for project in host.projects() {
if current.as_ref().is_some_and(|c| c.root == project.root) {
if current.as_ref().is_some_and(|c| Arc::ptr_eq(c, &project)) {
continue;
}
let effective = project.settings.reload();
+149 -23
Переглянути файл
@@ -50,6 +50,9 @@ pub struct Project {
/// Watchers of the Project Structure content roots outside the project folder.
pub(crate) content_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
pub(crate) _scratch_watcher: Option<Watcher>,
/// A LightEdit window's loose files ([`Host::open_light`]): global settings only,
/// nothing indexed, no language servers, repositories or project services.
pub light: bool,
}
impl Host {
@@ -66,6 +69,7 @@ impl Host {
// it, with its warm index, language servers and unsaved documents.
if let Ok(current) = self.project(window)
&& current.root == root
&& !current.light
{
return Ok(current);
}
@@ -275,29 +279,7 @@ impl Host {
mark("git");
tracing::info!("opened {} in window {window} in {} ms {laps:?}", root.display(), started.elapsed().as_millis());
let db = Arc::new(ide_db::DbManager::new(
root.clone(),
self.data_dir.join("db-passwords.json"),
self.data_dir.join("db-history.json"),
self.ssh.clone(),
));
let http_history = Arc::new(ide_http::History::new(self.data_dir.join("http-history").join(&project_key)));
let agents = Arc::new(ide_agent::AgentManager::new(
ide_agent::AgentPaths {
project_root: root.clone(),
store_dir: self.data_dir.join("agents").join(&project_key),
// Outside the app data dir: its path has spaces on macOS, which trips up build scripts.
worktrees_dir: dirs::home_dir()
.unwrap_or_else(|| self.data_dir.clone())
.join(".openidea")
.join("worktrees")
.join(&project_key),
models_file: self.data_dir.join("agents").join("models.json"),
custom_agents_dir: Some(self.config_dir.join("agents")),
home_dir: dirs::home_dir(),
},
self.runtime.clone(),
));
let (db, http_history, agents) = self.project_services(&root, &project_key);
let project = Arc::new(Project {
root,
sink,
@@ -319,6 +301,7 @@ impl Host {
watcher,
content_watchers: Mutex::new(content_watchers),
_scratch_watcher: scratch_watcher,
light: false,
});
{
let weak = Arc::downgrade(&project);
@@ -329,6 +312,146 @@ impl Host {
self.insert_project(window, project.clone());
Ok(project)
}
/// Database connections, HTTP Client history and coding agents of the project at `root`.
pub(crate) fn project_services(
&self,
root: &Path,
project_key: &str,
) -> (Arc<ide_db::DbManager>, Arc<ide_http::History>, Arc<ide_agent::AgentManager>) {
let db = Arc::new(ide_db::DbManager::new(
root.to_path_buf(),
self.data_dir.join("db-passwords.json"),
self.data_dir.join("db-history.json"),
self.ssh.clone(),
));
let http_history = Arc::new(ide_http::History::new(self.data_dir.join("http-history").join(project_key)));
let agents = Arc::new(ide_agent::AgentManager::new(
ide_agent::AgentPaths {
project_root: root.to_path_buf(),
store_dir: self.data_dir.join("agents").join(project_key),
// Outside the app data dir: its path has spaces on macOS, which trips up build scripts.
worktrees_dir: dirs::home_dir()
.unwrap_or_else(|| self.data_dir.clone())
.join(".openidea")
.join("worktrees")
.join(project_key),
models_file: self.data_dir.join("agents").join("models.json"),
custom_agents_dir: Some(self.config_dir.join("agents")),
home_dir: dirs::home_dir(),
},
self.runtime.clone(),
));
(db, http_history, agents)
}
}
impl Host {
/// Opens `window` for editing loose files (LightEdit), `file` first: documents
/// with syntax highlighting, saving and Local History over the global settings,
/// without an index, language servers, repositories or project settings. A
/// window already in LightEdit keeps its session; only its watchers grow.
pub fn open_light(&self, window: &str, file: &Path) -> IdeResult<Arc<Project>> {
let file = dunce::canonicalize(file)?;
if file.is_dir() {
return Err(IdeError::invalid(format!("{} is a folder", file.display())));
}
let dir = file.parent().map(Path::to_path_buf).ok_or_else(|| IdeError::invalid("no parent folder"))?;
if let Ok(current) = self.project(window)
&& current.light
{
current.watch_light_dir(&dir);
return Ok(current);
}
self.close_project(window);
let sink: SharedSink = (self.sink_for)(window);
let settings = Arc::new(SettingsStore::load(&self.config_dir, None));
let effective = settings.effective();
let languages = Arc::new(self.languages.fork());
languages.set_file_types(FileTypes::from_settings(&effective.files, None));
let documents = {
let languages = languages.clone();
Arc::new(Documents::new(
sink.clone(),
Box::new(move |p: &Path, first: Option<&str>| languages.detect(p, first)),
))
};
documents.set_file_defaults(ide_workspace::FileDefaults::from_settings(&effective, None));
let history = Arc::new(LocalHistory::open(&self.data_dir.join("history"), &dir)?);
let index = ProjectIndex::unindexed(&dir, languages.clone(), self.syntax(), sink.clone())?;
let lsp = LspManager::new(dir.clone(), languages.clone(), sink.clone());
lsp.set_servers_hook(Box::new(|_, _| Vec::new()));
let syntax = Arc::new(SyntaxCache::new(self.syntax()));
documents.add_observer(Arc::new(SyntaxObserver(syntax.clone())));
documents.add_observer(Arc::new(HistoryObserver(history.clone())));
let watcher = light_watcher(&dir, &sink, &documents, &history)?;
let project_key = project_key(&dir);
let (db, http_history, agents) = self.project_services(&dir, &project_key);
let project = Arc::new(Project {
sink,
languages,
settings,
documents,
history,
moves: FileMoves::new(),
index,
lsp,
repos: Arc::default(),
structure: Arc::new(StructureService::new(syntax.clone())),
syntax,
detected_roots: Arc::default(),
cache_dir: self.data_dir.join("cache").join(&project_key),
db,
http_history,
agents,
watcher,
content_watchers: Mutex::new(Vec::new()),
_scratch_watcher: None,
light: true,
root: dir,
});
tracing::info!("window {window} edits {} without a project", file.display());
self.insert_project(window, project.clone());
Ok(project)
}
}
impl Project {
/// LightEdit: follow external changes to the files of `dir` (its own entries only).
pub fn watch_light_dir(&self, dir: &Path) {
if !self.light {
return;
}
let dir = dunce::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
let mut watchers = self.content_watchers.lock();
if dir == self.root || watchers.iter().any(|(p, _)| *p == dir) {
return;
}
match light_watcher(&dir, &self.sink, &self.documents, &self.history) {
Ok(w) => watchers.push((dir, w)),
Err(e) => tracing::warn!("watching {}: {e}", dir.display()),
}
}
}
fn light_watcher(
dir: &Path,
sink: &SharedSink,
documents: &Arc<Documents>,
history: &Arc<LocalHistory>,
) -> IdeResult<Watcher> {
let (documents, history) = (documents.clone(), history.clone());
Watcher::start_with(
dir,
Vec::new(),
sink.clone(),
Box::new(move |batch| {
let changed: Vec<PathBuf> = batch.created.iter().chain(&batch.modified).cloned().collect();
documents.on_disk_changed(&changed);
record_external_changes(&history, &changed, &batch.removed);
}),
ide_vfs::WatchMode::Flat,
)
}
/// Looks for repositories nested below the project (and the one containing it);
@@ -516,6 +639,9 @@ impl Project {
/// Applies changed content roots and exclude settings to the index (which
/// rescans in the background) and the file watchers, without reopening the project.
pub fn refresh_index_scope(&self) {
if self.light {
return;
}
let (roots, excludes) = (self.content_roots(), self.exclude_globs());
self.index.set_scope(roots.clone(), excludes.clone());
self.watcher.set_excludes(&excludes);
+1 -1
Переглянути файл
@@ -79,7 +79,7 @@ fn read_login_env(timeout: std::time::Duration) -> Option<Vec<(OsString, OsStrin
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".into());
const MARK: &str = "__OPENIDEA_ENV__";
let mut child = Command::new(&shell)
let mut child = ide_core::process::prepare(&mut Command::new(&shell))
.args(["-ilc", &format!("printf '{MARK}'; /usr/bin/env -0; printf '{MARK}'")])
.stdin(Stdio::null())
.stdout(Stdio::piped())
+78
Переглянути файл
@@ -0,0 +1,78 @@
//! LightEdit: a window editing loose files without a project.
use ide_core::{ChangeSet, NullSink, TextChange};
use ide_host::{Host, HostConfig, ops};
use std::sync::Arc;
use std::time::Duration;
fn host(base: &std::path::Path) -> Arc<Host> {
Arc::new(Host::new(HostConfig {
config_dir: base.join("config"),
data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
}))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn edits_loose_files_without_project_services() {
let tmp = tempfile::tempdir().unwrap();
let tmp_root = dunce::canonicalize(tmp.path()).unwrap();
let (a_dir, b_dir) = (tmp_root.join("a"), tmp_root.join("b"));
std::fs::create_dir_all(a_dir.join(".git")).unwrap();
std::fs::create_dir_all(&b_dir).unwrap();
std::fs::write(a_dir.join("one.py"), "print(1)\n").unwrap();
std::fs::write(b_dir.join("two.rs"), "fn main() {}\n").unwrap();
let host = host(&tmp_root.join("app"));
let light = host.open_light("main", &a_dir.join("one.py")).unwrap();
assert!(light.light);
assert_eq!(light.root, a_dir);
assert!(host.open_light("main", &b_dir).is_err(), "a folder is not opened for LightEdit");
let doc = ops::doc::open(&host, "main", a_dir.join("one.py")).await.unwrap();
assert!(doc.text.starts_with("print"));
let changes = ChangeSet { changes: vec![TextChange { from: 0, to: 0, insert: "#\n".into() }] };
let version = ops::doc::edit(&host, "main", doc.id, doc.version, changes).unwrap();
assert!(version > doc.version);
ops::doc::save(&host, "main", doc.id).await.unwrap();
assert_eq!(std::fs::read_to_string(a_dir.join("one.py")).unwrap(), "#\nprint(1)\n");
// More files join the same session, wherever they are.
let again = host.open_light("main", &b_dir.join("two.rs")).unwrap();
assert!(Arc::ptr_eq(&light, &again));
ops::doc::open(&host, "main", b_dir.join("two.rs")).await.unwrap();
assert!(light.index.wait_idle(Duration::from_secs(10)));
assert_eq!(light.index.status().files, 0, "nothing is indexed");
assert!(light.lsp.servers().is_empty(), "no language servers");
assert!(light.repos().is_empty(), "no repositories");
// Opening the folder as a project replaces the LightEdit session.
let project = host.open_project("main", &a_dir).unwrap();
assert!(!project.light);
assert!(!Arc::ptr_eq(&project, &light));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn light_windows_ignore_project_scoped_settings() {
let tmp = tempfile::tempdir().unwrap();
let dir = dunce::canonicalize(tmp.path()).unwrap().join("loose");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("notes.txt"), "x\n").unwrap();
let host = host(&tmp.path().join("app"));
host.open_light("main", &dir.join("notes.txt")).unwrap();
let applied = ops::project::set_settings(
&host,
"main",
ide_workspace::settings::SettingsScope::Project,
"general.projectName",
"\"loose\"",
)
.unwrap();
assert!(!applied.project_scope);
assert!(!dir.join(".openidea").exists(), "no project settings next to the file");
}
+19 -1
Переглянути файл
@@ -90,11 +90,29 @@ impl ProjectIndex {
let store = store::Store::open(cache_dir, &root, &syntax.fingerprint());
let filter = filter::PathFilter::new(&root, &content_roots, &excludes);
let shared = Arc::new(Shared::new(filter, languages, syntax, sink, store));
Self::start(shared, root, true)
}
/// An index that never scans or persists anything (a window editing loose
/// files): queries answer empty, recent files are kept in memory only.
pub fn unindexed(
root: &Path,
languages: Arc<LanguageRegistry>,
syntax: Arc<Syntax>,
sink: SharedSink,
) -> IdeResult<Arc<Self>> {
let root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_owned());
let filter = filter::PathFilter::new(&root, &[], &[]);
let shared = Arc::new(Shared::new(filter, languages, syntax, sink, None));
Self::start(shared, root, false)
}
fn start(shared: Arc<Shared>, root: PathBuf, scan: bool) -> IdeResult<Arc<Self>> {
let worker = {
let shared = shared.clone();
std::thread::Builder::new()
.name("openidea-index".into())
.spawn(move || shared.run())
.spawn(move || shared.run(scan))
.map_err(|e| ide_core::IdeError::internal(format!("cannot start indexer: {e}")))?
};
Ok(Arc::new(Self { shared, worker: Mutex::new(Some(worker)), root }))
+22
Переглянути файл
@@ -473,3 +473,25 @@ fn file_type_changes_reparse_affected_files() {
assert_eq!(symbols(&idx, "beta", SymbolFilter::All), ["beta"]);
assert_eq!(idx.shared.parsed.load(Ordering::SeqCst), parsed + 1, "only the affected file is re-parsed");
}
#[test]
fn unindexed_index_never_scans_or_persists() {
let fx = Fixture::new(&[("a.rs", "fn alpha() {}\n")]);
let events = Arc::new(Mutex::new(Vec::new()));
let sink: SharedSink = {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().push(e))
};
let languages = Arc::new(LanguageRegistry::load(None).unwrap());
let idx = ProjectIndex::unindexed(&fx.root, languages, Arc::new(Syntax::new()), sink).unwrap();
assert!(idx.wait_idle(WAIT));
let st = idx.status();
assert!(!st.indexing);
assert_eq!(st.files, 0);
assert!(files(&idx, "a").is_empty());
idx.mark_recent(&fx.root.join("a.rs"));
assert!(idx.wait_idle(WAIT));
assert_eq!(idx.recent_files(), vec![fx.root.join("a.rs")]);
assert!(!fx.cache.exists());
assert!(!events.lock().iter().any(|e| matches!(e, IdeEvent::Task { .. })), "no indexing task");
}
+8 -3
Переглянути файл
@@ -127,13 +127,18 @@ impl Shared {
// ---------------------------------------------------------------- thread
pub(crate) fn run(&self) {
/// `scan`: load the persisted index and scan the roots before serving updates.
pub(crate) fn run(&self, scan: bool) {
{
let mut q = self.queue.lock();
q.busy = true;
}
self.load_persisted();
self.full_scan();
if scan {
self.load_persisted();
self.full_scan();
} else {
self.indexing.store(false, Ordering::SeqCst);
}
{
let mut q = self.queue.lock();
q.busy = false;
+1 -1
Переглянути файл
@@ -355,7 +355,7 @@ impl Peer {
) -> std::io::Result<Self> {
use std::process::Stdio;
let mut cmd = tokio::process::Command::new(command);
ide_core::process::no_window(cmd.as_std_mut());
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(args)
.current_dir(cwd)
.envs(ide_core::process::shell_env())
+4
Переглянути файл
@@ -69,6 +69,10 @@ pub struct LanguageServerConfig {
/// Files whose presence marks a workspace root, e.g. `Cargo.toml`.
#[serde(default)]
pub root_markers: Vec<String>,
/// Serve only files below a root marker, not the whole project: a framework's
/// server (Angular) next to the language's own one.
#[serde(default)]
pub require_root_marker: bool,
/// JSON passed as `initializationOptions`.
#[serde(default)]
pub initialization_options: Option<toml::Value>,
+30 -5
Переглянути файл
@@ -518,12 +518,37 @@ mod tests {
#[test]
fn alternative_servers_are_fallbacks() {
let reg = reg();
for (lang, servers) in
[("python", ["basedpyright", "pyright"]), ("typescript", ["vtsls", "typescript-language-server"])]
{
for (lang, servers) in [
("python", vec!["basedpyright", "pyright", "ty"]),
("typescript", vec!["vtsls", "typescript-language-server"]),
] {
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
let got: Vec<(&str, bool)> = cfg.language_servers.iter().map(|s| (s.name.as_str(), s.fallback)).collect();
assert_eq!(got, [(servers[0], false), (servers[1], true)]);
let got: Vec<(&str, bool)> = cfg
.language_servers
.iter()
.filter(|s| !s.require_root_marker)
.map(|s| (s.name.as_str(), s.fallback))
.collect();
let expected: Vec<(&str, bool)> = servers.iter().enumerate().map(|(i, name)| (*name, i > 0)).collect();
assert_eq!(got, expected);
}
}
#[test]
fn angular_server_joins_typescript_and_html_in_angular_projects() {
let reg = reg();
let names = |lang: &str| -> Vec<String> {
reg.get(&LanguageId::new(lang)).unwrap().language_servers.iter().map(|s| s.name.clone()).collect()
};
// After the TypeScript fallback (an available server before it would hide
// it); before the HTML server (hover, rename and symbols take the first).
assert_eq!(names("typescript"), ["vtsls", "typescript-language-server", "angular-language-server"]);
assert_eq!(names("html"), ["angular-language-server", "vscode-html-language-server"]);
for lang in ["typescript", "html"] {
let cfg = reg.get(&LanguageId::new(lang)).unwrap();
let angular = cfg.language_servers.iter().find(|s| s.name == "angular-language-server").unwrap();
assert!(angular.require_root_marker && !angular.fallback, "{lang}");
assert_eq!(angular.root_markers, ["angular.json", "node_modules/@angular/core"], "{lang}");
}
}
+273
Переглянути файл
@@ -0,0 +1,273 @@
//! The Angular Language Server next to vtsls in TypeScript files, asked like
//! VS Code's Angular extension asks it: about positions only inside a
//! component's template and styles, since it answers nothing elsewhere and
//! answers late while it analyses the project.
pub(crate) const SERVER: &str = "angular-language-server";
/// Decorator fields holding templates, styles and host bindings.
const PROPERTIES: [&str; 6] = ["template", "templateUrl", "styles", "styleUrls", "styleUrl", "host"];
/// Decorators taking host bindings as string arguments.
const DECORATORS: [&str; 2] = ["HostBinding", "HostListener"];
/// Whether the Angular server is asked about the position at byte `offset` of
/// a `language` document: anywhere in a template file, in TypeScript only in
/// a string of a decorator field.
pub(crate) fn serves_position(language: &str, text: &str, offset: usize) -> bool {
language != "typescript" || in_decorator_field(text, offset)
}
/// Whether the Angular server is asked for the inlay hints of a `language`
/// document: in TypeScript only with Angular imported.
pub(crate) fn serves_inlay_hints(language: &str, text: &str) -> bool {
language != "typescript" || text.contains("@angular/core")
}
/// Whether byte `offset` is inside a string of one of [`PROPERTIES`] (`template:
/// '...'`, `styles: ['...']`) or of an argument of one of [`DECORATORS`]. A
/// port of the VS Code extension's token scan: false positives are fine, the
/// server has the last word.
fn in_decorator_field(text: &str, offset: usize) -> bool {
let mut scanner = Scanner { text: text.as_bytes(), pos: 0, braces: 0, substitutions: Vec::new() };
let (mut last, mut second_last, mut last_text) = (None, None, "");
let (mut braces, mut brackets, mut parens) = (0i32, 0i32, 0i32);
// The brace and bracket depth of the property whose value is being read.
let mut property: Option<(i32, i32)> = None;
// The paren depth of the decorator whose arguments are being read.
let mut decorator: Option<i32> = None;
while let Some((tok, start, end)) = scanner.next() {
if start >= offset {
break;
}
if last == Some(Tok::Ident) && tok == Tok::Colon && PROPERTIES.contains(&last_text) {
property = Some((braces, brackets));
continue;
}
if property == Some((braces, brackets)) && matches!(tok, Tok::Comma | Tok::Semicolon | Tok::CloseBrace) {
property = None;
}
if second_last == Some(Tok::At)
&& last == Some(Tok::Ident)
&& tok == Tok::OpenParen
&& DECORATORS.contains(&last_text)
{
decorator = Some(parens);
}
if tok == Tok::CloseParen && decorator == Some(parens - 1) {
decorator = None;
}
match tok {
Tok::OpenBrace => braces += 1,
Tok::CloseBrace => braces -= 1,
Tok::OpenBracket => brackets += 1,
Tok::CloseBracket => brackets -= 1,
Tok::OpenParen => parens += 1,
Tok::CloseParen => parens -= 1,
_ => {}
}
if (property.is_some() || decorator.is_some()) && tok == Tok::Str && offset <= end {
return true;
}
last_text = text.get(start..end).unwrap_or("");
second_last = last;
last = Some(tok);
}
false
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Tok {
Ident,
Colon,
Comma,
Semicolon,
At,
OpenBrace,
CloseBrace,
OpenBracket,
CloseBracket,
OpenParen,
CloseParen,
/// A string or a template literal without substitutions.
Str,
/// A part of a template literal with substitutions (`` `a${`` / `}b${` / `` }c` ``).
Template,
Other,
}
/// TypeScript tokens, enough to tell strings, names and brackets apart.
/// Like the TypeScript scanner without its parser, `/` is never a regex.
struct Scanner<'a> {
text: &'a [u8],
pos: usize,
/// Open `{`, not counting those of template substitutions.
braces: usize,
/// The brace depth each open `${` started at, innermost last.
substitutions: Vec<usize>,
}
impl Scanner<'_> {
/// The next token and its byte range.
fn next(&mut self) -> Option<(Tok, usize, usize)> {
self.skip_trivia();
let start = self.pos;
let c = *self.text.get(start)?;
self.pos += 1;
let tok = match c {
b'\'' | b'"' => {
self.string(c);
Tok::Str
}
b'`' => {
if self.template() {
Tok::Template
} else {
Tok::Str
}
}
b'{' => {
self.braces += 1;
Tok::OpenBrace
}
// The end of a substitution: the template literal goes on.
b'}' if self.substitutions.last() == Some(&self.braces) => {
self.substitutions.pop();
self.template();
Tok::Template
}
b'}' => {
self.braces = self.braces.saturating_sub(1);
Tok::CloseBrace
}
b'[' => Tok::OpenBracket,
b']' => Tok::CloseBracket,
b'(' => Tok::OpenParen,
b')' => Tok::CloseParen,
b':' => Tok::Colon,
b',' => Tok::Comma,
b';' => Tok::Semicolon,
b'@' => Tok::At,
c if is_ident(c) => {
while self.text.get(self.pos).is_some_and(|&c| is_ident(c)) {
self.pos += 1;
}
if c.is_ascii_digit() { Tok::Other } else { Tok::Ident }
}
_ => Tok::Other,
};
Some((tok, start, self.pos))
}
fn skip_trivia(&mut self) {
loop {
match (self.text.get(self.pos), self.text.get(self.pos + 1)) {
(Some(c), _) if c.is_ascii_whitespace() => self.pos += 1,
(Some(b'/'), Some(b'/')) => {
while self.text.get(self.pos).is_some_and(|&c| c != b'\n') {
self.pos += 1;
}
}
(Some(b'/'), Some(b'*')) => {
self.pos += 2;
while self.pos < self.text.len() && !self.text[self.pos..].starts_with(b"*/") {
self.pos += 1;
}
self.pos = (self.pos + 2).min(self.text.len());
}
_ => return,
}
}
}
/// The rest of a string opened by `quote`, which a line break ends too.
fn string(&mut self, quote: u8) {
while let Some(&c) = self.text.get(self.pos) {
self.pos += if c == b'\\' { 2 } else { 1 };
if c == quote || c == b'\n' {
break;
}
}
self.pos = self.pos.min(self.text.len());
}
/// The rest of a template literal part; `true` when a substitution opens it.
fn template(&mut self) -> bool {
while let Some(&c) = self.text.get(self.pos) {
match c {
b'\\' => self.pos += 2,
b'`' => {
self.pos += 1;
return false;
}
b'$' if self.text.get(self.pos + 1) == Some(&b'{') => {
self.pos += 2;
self.substitutions.push(self.braces);
return true;
}
_ => self.pos += 1,
}
}
self.pos = self.pos.min(self.text.len());
false
}
}
/// Identifier bytes; any non-ASCII byte belongs to one too.
fn is_ident(c: u8) -> bool {
c.is_ascii_alphanumeric() || c == b'_' || c == b'$' || c >= 0x80
}
#[cfg(test)]
mod tests {
use super::*;
/// Whether the position marked `|` in `src` is in a decorator field.
fn at_marker(src: &str) -> bool {
let offset = src.find('|').expect("marker");
in_decorator_field(&src.replacen('|', "", 1), offset)
}
#[test]
fn template_and_style_strings_are_decorator_fields() {
assert!(at_marker("@Component({ selector: 'a', template: `<p>{{ |x }}</p>` })"));
assert!(at_marker("@Component({\n template: '<p>|</p>',\n})"));
assert!(at_marker("@Component({ templateUrl: './a.|html' })"));
assert!(at_marker("@Component({ styles: ['p {}', 'a { |}'] })"));
assert!(at_marker("@Component({ host: { '(click)': 'on|Click()' } })"));
assert!(at_marker("class A { @HostListener('click', ['$event.|target']) on() {} }"));
// Still being typed: the string runs to the end of the line.
assert!(at_marker("@Component({ template: '<p>|"));
}
#[test]
fn code_and_other_strings_are_not() {
assert!(!at_marker("@Component({ selector: 'app-|root', template: '' })"));
assert!(!at_marker("@Component({ template: '' })\nclass A { t|itle = 'x'; }"));
assert!(!at_marker("@Component({ template: '' })\nclass A { title = '|x'; }"));
assert!(!at_marker("@Component({ template: |`<p></p>` })"));
assert!(!at_marker("@Component({ template: '', imports: [A|] })"));
assert!(!at_marker("class A { @HostListener('click') on() { const s = '|'; } }"));
assert!(!at_marker("// template: '|'\nclass A {}"));
assert!(!at_marker("/* template: '|' */"));
}
#[test]
fn substitutions_dont_end_template_literals() {
// `}` closing `${...}` is not the end of the object holding `template`.
assert!(at_marker("const a = `${ {b: 1} }`;\n@Component({ template: '<p>|</p>' })"));
assert!(!at_marker("@Component({ template: `<p>${x}|</p>` })"));
assert!(at_marker("const s = `${'}'}`; @Component({ template: '<i>|</i>' })"));
assert!(!at_marker("const s = `${`${'a'}`}`; class A { b = '|'; }"));
}
#[test]
fn typescript_positions_go_to_angular_only_in_decorator_fields() {
let src = "@Component({ template: '<p></p>' })\nclass A {}";
assert!(serves_position("html", src, src.find("class").unwrap()));
assert!(!serves_position("typescript", src, src.find("class").unwrap()));
assert!(serves_position("typescript", src, src.find("</p>").unwrap()));
assert!(serves_inlay_hints("typescript", "import { Component } from '@angular/core';"));
assert!(!serves_inlay_hints("typescript", "export const a = 1;"));
assert!(serves_inlay_hints("html", ""));
}
}
+57
Переглянути файл
@@ -664,6 +664,36 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
WorkspaceEdit { files }
}
/// Adds the changes of `extra`, another server's edit for the same request, to
/// `edit` where they leave its own alone: what only the other server sees
/// (Angular templates next to vtsls's TypeScript).
pub fn merge_workspace_edit(edit: &mut WorkspaceEdit, extra: WorkspaceEdit) {
let overlap =
|a: &TextEdit, b: &TextEdit| a.range == b.range || (a.range.start < b.range.end && b.range.start < a.range.end);
for file in extra.files {
let FileEdit::Edit { path, edits } = file else {
if !edit.files.contains(&file) {
edit.files.push(file);
}
continue;
};
let own = edit.files.iter_mut().find_map(|f| match f {
FileEdit::Edit { path: p, edits } if *p == path => Some(edits),
_ => None,
});
match own {
Some(own) => {
let added: Vec<TextEdit> = edits.into_iter().filter(|e| !own.iter().any(|o| overlap(o, e))).collect();
if !added.is_empty() {
own.extend(added);
own.sort_by_key(|e| e.range.start);
}
}
None => edit.files.push(FileEdit::Edit { path, edits }),
}
}
}
// ---------------------------------------------------------------- navigation
pub fn goto_response(conv: &Conv, r: lsp::GotoDefinitionResponse) -> Vec<Location> {
@@ -990,6 +1020,33 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn merged_rename_edits_keep_the_first_servers_ones() {
let edit = |l: u32, c: u32, text: &str| TextEdit {
range: Range::new(Pos::new(l, c), Pos::new(l, c + 5)),
new_text: text.into(),
};
let file = |p: &str, edits: Vec<TextEdit>| FileEdit::Edit { path: PathBuf::from(p).into(), edits };
// vtsls renames a shorthand property with an alias; the Angular server
// renames it plainly and adds the template.
let mut merged =
WorkspaceEdit { files: vec![file("/a.ts", vec![edit(3, 2, "items: entries"), edit(9, 4, "entries")])] };
let angular = WorkspaceEdit {
files: vec![
file("/a.ts", vec![edit(9, 4, "entries"), edit(3, 2, "entries"), edit(1, 14, "entries")]),
file("/a.html", vec![edit(0, 7, "entries")]),
],
};
merge_workspace_edit(&mut merged, angular);
assert_eq!(
merged.files,
[
file("/a.ts", vec![edit(1, 14, "entries"), edit(3, 2, "items: entries"), edit(9, 4, "entries")]),
file("/a.html", vec![edit(0, 7, "entries")]),
]
);
}
#[test]
fn snippet_text_takes_placeholder_defaults() {
assert_eq!(snippet_text("foo(${1:a}, $2)$0"), "foo(a, )");
+14
Переглянути файл
@@ -12,6 +12,9 @@ use lsp_types as lsp;
use serde_json::{Value, json};
use std::sync::{Arc, Weak};
/// Progress token standing for `angular/projectLoadingStart` … `Finish`.
const ANGULAR_LOADING: &str = "angular/projectLoading";
pub struct ClientHandler {
mgr: Weak<LspManager>,
server: Arc<Server>,
@@ -201,6 +204,17 @@ impl Handler for ClientHandler {
}
}
"tsserver/request" => mgr.forward_tsserver_requests(self.server.clone(), self.generation, params),
// The Angular server's project loading, shown like `$/progress`; one
// task while several projects load.
"angular/projectLoadingStart" if !self.server.progress.lock().contains_key(ANGULAR_LOADING) => self
.progress(
&mgr,
json!({ "token": ANGULAR_LOADING, "value": { "kind": "begin", "title": "Loading Angular project" } }),
),
"angular/projectLoadingStart" => {}
"angular/projectLoadingFinish" => {
self.progress(&mgr, json!({ "token": ANGULAR_LOADING, "value": { "kind": "end" } }))
}
"telemetry/event" | "$/logTrace" | "$/cancelRequest" => {}
other => tracing::trace!("[{}] unhandled notification {other}", self.server.name),
}
+5
Переглянути файл
@@ -66,6 +66,11 @@ impl LspManager {
pub fn serves_path(&self, path: &Path) -> bool {
let lang = self.languages.detect(path, None);
self.language_servers(&lang).iter().any(|ls| {
if ls.require_root_marker
&& crate::launch::marked_root(&self.project_root, path, &ls.root_markers).is_none()
{
return false;
}
let mut cfg = ls.clone();
if let Some(hook) = self.config_hook.read().clone() {
hook(&mut cfg, &self.project_root);
+21 -3
Переглянути файл
@@ -116,7 +116,7 @@ fn resolve_rustup_proxy(command: &str, binary: PathBuf) -> Option<PathBuf> {
if !is_proxy || command.contains('/') {
return Some(binary);
}
let works = ide_core::process::no_window(&mut std::process::Command::new(&binary))
let works = ide_core::process::prepare(&mut std::process::Command::new(&binary))
.arg("--version")
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
@@ -190,7 +190,7 @@ fn login_shell_path() -> Option<OsString> {
use std::time::{Duration, Instant};
let shell = std::env::var_os("SHELL")?;
const MARK: &str = "__OPENIDEA_PATH__";
let mut child = Command::new(shell)
let mut child = ide_core::process::prepare(&mut Command::new(shell))
.args(["-l", "-c", &format!("printf '{MARK}%s{MARK}' \"$PATH\"")])
.stdin(Stdio::null())
.stdout(Stdio::piped())
@@ -228,6 +228,11 @@ pub fn find_root(project_root: &Path, file: &Path, markers: &[String]) -> Option
if !file.starts_with(project_root) {
return None;
}
Some(marked_root(project_root, file, markers).unwrap_or_else(|| project_root.to_path_buf()))
}
/// The outermost ancestor of `file` within `project_root` containing a root marker.
pub fn marked_root(project_root: &Path, file: &Path, markers: &[String]) -> Option<PathBuf> {
let mut best = None;
for dir in file.ancestors().skip(1) {
if !dir.starts_with(project_root) {
@@ -237,7 +242,7 @@ pub fn find_root(project_root: &Path, file: &Path, markers: &[String]) -> Option
best = Some(dir.to_path_buf());
}
}
Some(best.unwrap_or_else(|| project_root.to_path_buf()))
best
}
fn has_marker(dir: &Path, marker: &str) -> bool {
@@ -275,6 +280,19 @@ mod tests {
std::fs::remove_dir_all(&tmp).unwrap();
}
#[test]
fn marked_root_needs_a_marker() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
let file = root.join("apps/web/src/app.ts");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
let markers = vec!["angular.json".to_string(), "node_modules/@angular/core".to_string()];
assert_eq!(marked_root(root, &file, &markers), None);
std::fs::create_dir_all(root.join("apps/web/node_modules/@angular/core")).unwrap();
assert_eq!(marked_root(root, &file, &markers), Some(root.join("apps/web")));
assert_eq!(marked_root(root, &root.join("apps/api/main.ts"), &markers), None);
}
#[test]
fn search_path_contains_env_path() {
let p = search_path();
+105 -18
Переглянути файл
@@ -6,6 +6,7 @@
//! IDE coordinates (UTF-16, 0-based) and returns IDE types from [`types`],
//! never `lsp-types`, so the IPC surface stays stable.
mod angular;
mod caps;
mod convert;
mod file_ops;
@@ -125,6 +126,7 @@ impl Target {
struct DocSnap {
path: PathBuf,
uri: lsp::Uri,
language: LanguageId,
text: Arc<DocText>,
servers: Vec<Arc<Server>>,
}
@@ -142,6 +144,12 @@ impl DocSnap {
fn pos_params(&self, t: &Target, pos: Pos) -> Value {
json!({ "textDocument": self.ident(), "position": self.position(t, pos) })
}
/// Whether `t` is asked about `pos`: the Angular server not about the
/// TypeScript outside a component's template and styles (see [`angular`]).
fn asks(&self, t: &Target, pos: Pos) -> bool {
t.server.name != angular::SERVER
|| angular::serves_position(self.language.as_str(), self.text.as_str(), self.text.byte_offset(pos))
}
}
pub struct LspManager {
@@ -306,7 +314,8 @@ impl LspManager {
}
/// The servers serving `path`: every regular one, and each `fallback` one
/// only while all servers listed before it are missing.
/// only while all servers listed before it are missing. One that requires a
/// root marker serves only files below one, and stands in for no other.
fn servers_for(&self, language: &LanguageId, path: &Path) -> Vec<Arc<Server>> {
let mut out = Vec::new();
let mut available_before = false;
@@ -314,8 +323,11 @@ impl LspManager {
if sc.fallback && available_before {
continue;
}
if sc.require_root_marker && launch::marked_root(&self.project_root, path, &sc.root_markers).is_none() {
continue;
}
let server = self.server_for(sc, language, path);
available_before |= server.status() != ide_core::event::ServerStatus::Missing;
available_before |= !sc.require_root_marker && server.status() != ide_core::event::ServerStatus::Missing;
out.push(server);
}
out
@@ -343,22 +355,24 @@ impl LspManager {
let mut docs = self.docs.lock();
for (id, servers) in wanted {
let Some(d) = docs.get_mut(&id) else { continue };
for server in servers {
for server in &servers {
if d.servers.iter().any(|a| a.server.id == server.id) {
continue;
}
let mut attached = Attached { server: server.clone(), opened_gen: None };
if let Some(run) = server.running() {
if run.caps.read().open_close {
user_did_open(&server, &run, &d.path, &d.uri, d.did_open_params());
user_did_open(server, &run, &d.path, &d.uri, d.did_open_params());
}
attached.opened_gen = Some(run.generation);
}
d.servers.push(attached);
if !start.iter().any(|s: &Arc<Server>| s.id == server.id) {
start.push(server);
start.push(server.clone());
}
}
// In definition order: the first server answers hover, rename and symbols.
d.servers.sort_by_key(|a| servers.iter().position(|s| s.id == a.server.id).unwrap_or(usize::MAX));
}
}
for server in &start {
@@ -781,6 +795,7 @@ impl LspManager {
Ok(DocSnap {
path: d.path.clone(),
uri: d.uri.clone(),
language: d.language.clone(),
text: d.text.clone(),
servers: d.servers.iter().map(|a| a.server.clone()).collect(),
})
@@ -837,7 +852,7 @@ impl LspManager {
cancel: CancellationToken,
) -> IdeResult<CompletionList> {
let (snap, targets) = self.doc_targets(doc, "completion", |c| c.has("completionProvider")).await?;
let requests = targets.iter().map(|t| {
let requests = targets.iter().filter(|t| snap.asks(t, pos)).map(|t| {
let context = match &trigger {
Some(ch) if t.caps().completion_triggers().contains(ch) => {
json!({ "triggerKind": 2, "triggerCharacter": ch })
@@ -924,7 +939,7 @@ impl LspManager {
pub async fn hover(&self, doc: DocId, pos: Pos, cancel: CancellationToken) -> IdeResult<Option<Hover>> {
let (snap, targets) = self.doc_targets(doc, "hover", |c| c.has("hoverProvider")).await?;
let mut out = Outcome::new();
for t in &targets {
for t in targets.iter().filter(|t| snap.asks(t, pos)) {
let r: IdeResult<Option<lsp::Hover>> =
self.call(t, "textDocument/hover", snap.pos_params(t, pos), Some(&cancel), DEFAULT_TIMEOUT).await;
match r {
@@ -945,7 +960,7 @@ impl LspManager {
pub async fn signature_help(&self, doc: DocId, pos: Pos) -> IdeResult<Option<SignatureHelp>> {
let (snap, targets) = self.doc_targets(doc, "signature help", |c| c.has("signatureHelpProvider")).await?;
let mut out = Outcome::new();
for t in &targets {
for t in targets.iter().filter(|t| snap.asks(t, pos)) {
let mut params = snap.pos_params(t, pos);
params["context"] = json!({ "triggerKind": 1, "isRetrigger": false });
match self
@@ -1007,7 +1022,7 @@ impl LspManager {
cancel: Option<&CancellationToken>,
) -> IdeResult<Vec<Location>> {
let mut out = Outcome::new();
for t in targets {
for t in targets.iter().filter(|t| snap.asks(t, pos)) {
match self
.call::<_, Option<lsp::GotoDefinitionResponse>>(
t,
@@ -1049,6 +1064,9 @@ impl LspManager {
let requests = targets.iter().map(|t| {
let (snap, cancel) = (&snap, &cancel);
async move {
// The Angular server searches the file's own project only: more open
// files don't widen it.
let angular = t.server.name == angular::SERVER;
let query = || async move {
let mut params = snap.pos_params(t, pos);
params["context"] = json!({ "includeDeclaration": include_declaration });
@@ -1059,7 +1077,7 @@ impl LspManager {
};
let files =
|v: &Vec<Location>| v.iter().filter(|l| l.uri.is_none()).map(|l| l.path.to_path_buf()).collect();
let result = if project_wide {
let result = if project_wide && !angular {
self.widened(snap, t, pos, cancel, query, files).await
} else {
query().await.map(|first| {
@@ -1070,12 +1088,25 @@ impl LspManager {
(t, result)
}
});
// The Angular server lists the declaration even when not asked to: the one
// the definition at `pos` points to is taken out of its answer.
let declarations = async {
if include_declaration || !targets.iter().any(|t| t.server.name == angular::SERVER) {
return Vec::new();
}
let defining = self.ready_targets(&snap.servers, |c| c.has("definitionProvider")).await;
self.goto_in(&snap, &defining, "textDocument/definition", pos, Some(&cancel)).await.unwrap_or_default()
};
let (results, declarations) = futures::join!(join_all(requests), declarations);
let mut out = Outcome::new();
for (t, r) in join_all(requests).await {
for (t, r) in results {
match r {
Ok(w) => {
let acc = out.value.get_or_insert_with(References::default);
let locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
let mut locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
if t.server.name == angular::SERVER {
locs.retain(|l| !declarations.contains(l));
}
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
acc.locations.extend(locs);
acc.incomplete = acc.incomplete.or(w.incomplete);
@@ -1296,7 +1327,19 @@ impl LspManager {
pub async fn prepare_rename(&self, doc: DocId, pos: Pos) -> IdeResult<Option<Range>> {
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
let t = &targets[0];
let mut out = Outcome::new();
for t in &targets {
match self.prepare_rename_on(&snap, t, pos).await {
Ok(Some(range)) => return Ok(Some(range)),
Ok(None) => out.value = Some(None),
Err(e) => out.fail(e),
}
}
out.finish(None)
}
/// What `t` renames at `pos`; one without `prepareRename` renames the word there.
async fn prepare_rename_on(&self, snap: &DocSnap, t: &Target, pos: Pos) -> IdeResult<Option<Range>> {
if !t.caps().has_sub("renameProvider", "prepareProvider") {
return Ok(snap.text.word_range_at(pos));
}
@@ -1319,15 +1362,50 @@ impl LspManager {
/// Renames across the project: like [`Self::references`], files outside the
/// server's analysis scope that mention the name are opened for the request.
/// Every server that can rename there does: the Angular server adds the
/// templates to vtsls's edit, whose own edits win where both change the same text.
pub async fn rename(&self, doc: DocId, pos: Pos, new_name: String) -> IdeResult<WorkspaceEdit> {
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
let t = &targets[0];
let renaming = self.rename_targets(&snap, &targets, pos).await;
let edits = join_all(renaming.into_iter().map(|t| self.rename_on(&snap, t, pos, &new_name))).await;
let mut out = Outcome::new();
for edit in edits {
match edit {
Ok(edit) => match &mut out.value {
Some(merged) => convert::merge_workspace_edit(merged, edit),
None => out.value = Some(edit),
},
Err(e) => out.fail(e),
}
}
out.finish(WorkspaceEdit::default())
}
/// The servers that can rename at `pos`, the first one when none can (a
/// single one is asked without `prepareRename`).
async fn rename_targets<'t>(&self, snap: &DocSnap, targets: &'t [Target], pos: Pos) -> Vec<&'t Target> {
if targets.len() > 1 {
let prepared = join_all(targets.iter().map(|t| self.prepare_rename_on(snap, t, pos))).await;
let able: Vec<&Target> =
targets.iter().zip(prepared).filter(|(_, r)| matches!(r, Ok(Some(_)))).map(|(t, _)| t).collect();
if !able.is_empty() {
return able;
}
}
vec![&targets[0]]
}
async fn rename_on(&self, snap: &DocSnap, t: &Target, pos: Pos, new_name: &str) -> IdeResult<WorkspaceEdit> {
let query = || async {
let mut params = snap.pos_params(t, pos);
params["newName"] = json!(new_name);
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
};
// The Angular server renames in the file's own project only, whatever is open.
if t.server.name == angular::SERVER {
return query().await;
}
let files = |e: &WorkspaceEdit| {
e.files
.iter()
@@ -1337,7 +1415,7 @@ impl LspManager {
})
.collect()
};
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
let w = self.widened(snap, t, pos, &CancellationToken::new(), query, files).await?;
// The second edit covers the first: its files stay analysed.
Ok(w.second.unwrap_or(w.first))
}
@@ -1488,7 +1566,8 @@ impl LspManager {
pub async fn inlay_hints(&self, doc: DocId, range: Range) -> IdeResult<Vec<InlayHint>> {
let (snap, targets) = self.doc_targets(doc, "inlay hints", |c| c.has("inlayHintProvider")).await?;
let requests = targets.iter().map(|t| {
let angular = angular::serves_inlay_hints(snap.language.as_str(), snap.text.as_str());
let requests = targets.iter().filter(|t| angular || t.server.name != angular::SERVER).map(|t| {
let params = json!({ "textDocument": snap.ident(), "range": snap.range(t, range) });
async move {
(
@@ -1931,7 +2010,7 @@ impl LspManager {
tracing::info!("{}: shadowed by an enabled server, stopping", s.name);
self.stop_instance(s, true).await;
}
self.servers.lock().retain(|s| !detached.iter().any(|d| d.id == s.id));
self.forget(&detached);
}
/// Stops and forgets the servers that none of their languages uses any more.
@@ -1949,10 +2028,18 @@ impl LspManager {
self.stop_instance(s, true).await;
}
let gone = |s: &Arc<Server>| unlisted.iter().any(|u| u.id == s.id);
self.servers.lock().retain(|s| !gone(s));
for d in self.docs.lock().values_mut() {
d.servers.retain(|a| !gone(&a.server));
}
self.forget(&unlisted);
}
/// Drops stopped servers from the list and tells the UI they are gone.
fn forget(&self, gone: &[Arc<Server>]) {
self.servers.lock().retain(|s| !gone.iter().any(|g| g.id == s.id));
for s in gone {
self.sink.emit(ide_core::IdeEvent::LanguageServerRemoved { server: s.id });
}
}
pub fn set_apply_edit_hook(&self, hook: Box<dyn Fn(WorkspaceEdit) -> bool + Send + Sync>) {
+1 -1
Переглянути файл
@@ -94,7 +94,7 @@ pub(crate) fn connect_or_start(
let args = substitute_args(&config.args, port, root);
let mut cmd = tokio::process::Command::new(binary);
ide_core::process::no_window(cmd.as_std_mut());
ide_core::process::prepare(cmd.as_std_mut());
cmd.args(&args)
.current_dir(root)
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
+221 -3
Переглянути файл
@@ -1,7 +1,7 @@
//! Protocol tests against in-memory mock language servers.
use ide_core::event::ServerStatus;
use ide_core::{DocId, FileEdit, IdeEvent, LanguageId, Pos, Range, Severity, WorkspaceEdit};
use ide_core::{DocId, FileEdit, IdeEvent, LanguageId, Pos, Range, ServerId, Severity, WorkspaceEdit};
use ide_jsonrpc::{Handler, NoopHandler, Peer};
use ide_language::{LanguageConfig, LanguageRegistry, LanguageServerConfig};
use ide_lsp::types::*;
@@ -9,7 +9,7 @@ use ide_lsp::{LaunchError, Launcher, LspManager};
use ide_text::AppliedChange;
use parking_lot::Mutex;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -202,6 +202,7 @@ fn server_cfg(name: &str) -> LanguageServerConfig {
args: vec![],
env: Default::default(),
root_markers: vec!["mock.toml".into()],
require_root_marker: false,
initialization_options: Some(toml::Value::Table(toml::toml! { flag = true nested = { deep = 1 } })),
settings: None,
install_hint: Some(format!("install {name}")),
@@ -222,6 +223,16 @@ fn harness_with_fallbacks(servers: &[(&str, Value)], fallbacks: &[&str]) -> Harn
}
fn harness_for(lang_id: &str, ext: &str, servers: &[(&str, Value)], fallbacks: &[&str]) -> Harness {
harness_configured(lang_id, ext, servers, |cfg| cfg.fallback = fallbacks.contains(&cfg.name.as_str()))
}
/// `adjust` changes each server's configuration.
fn harness_configured(
lang_id: &str,
ext: &str,
servers: &[(&str, Value)],
adjust: impl Fn(&mut LanguageServerConfig),
) -> Harness {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().to_path_buf();
let lang = LanguageConfig {
@@ -237,7 +248,11 @@ fn harness_for(lang_id: &str, ext: &str, servers: &[(&str, Value)], fallbacks: &
tree_sitter: None,
language_servers: servers
.iter()
.map(|(n, _)| LanguageServerConfig { fallback: fallbacks.contains(n), ..server_cfg(n) })
.map(|(n, _)| {
let mut cfg = server_cfg(n);
adjust(&mut cfg);
cfg
})
.collect(),
debugger: None,
};
@@ -275,6 +290,22 @@ impl Harness {
.collect()
}
/// Whether every instance of `name` was reported as removed from the server list.
fn removed(&self, name: &str) -> bool {
let events = self.events.lock();
let ids: HashSet<ServerId> = events
.iter()
.filter_map(|e| match e {
IdeEvent::LanguageServer { server, name: n, .. } if n == name => Some(*server),
_ => None,
})
.collect();
!ids.is_empty()
&& ids.iter().all(|id| {
events.iter().any(|e| matches!(e, IdeEvent::LanguageServerRemoved { server } if server == id))
})
}
async fn wait_status(&self, name: &str, status: ServerStatus) {
eventually(|| self.statuses(name).last() == Some(&status)).await;
}
@@ -697,6 +728,28 @@ async fn progress_tasks_and_busy_status() {
assert!(tasks[2].3);
}
#[tokio::test(flavor = "multi_thread")]
async fn angular_project_loading_shows_as_progress() {
let h = harness(&[("mock", incremental_caps())]);
h.open("a.mk", "x");
h.wait_status("mock", ServerStatus::Ready).await;
let peer = h.launcher.state("mock").peer();
peer.notify("angular/projectLoadingStart", Value::Null).unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
peer.notify("angular/projectLoadingFinish", Value::Null).unwrap();
h.wait_status("mock", ServerStatus::Ready).await;
let tasks: Vec<(String, bool)> = h
.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Task { title, done, .. } => Some((title.clone(), *done)),
_ => None,
})
.collect();
assert_eq!(tasks, [("Loading Angular project".into(), false), ("Loading Angular project".into(), true)]);
}
#[tokio::test(flavor = "multi_thread")]
async fn crash_restarts_and_reopens_documents() {
let h = harness(&[("mock", incremental_caps())]);
@@ -847,6 +900,8 @@ async fn settings_changes_reach_servers_without_restarts() {
h.mgr.reconfigure().await;
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["mock"]);
assert_eq!(h.statuses("extra").last(), Some(&ServerStatus::Stopped));
assert!(h.removed("extra"));
assert!(!h.removed("mock"));
disabled.lock().clear();
h.mgr.reconfigure().await;
h.wait_status("extra", ServerStatus::Ready).await;
@@ -878,6 +933,45 @@ async fn fallback_servers_only_run_when_the_preferred_one_is_missing() {
assert!(h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.is_ok());
}
#[tokio::test(flavor = "multi_thread")]
async fn a_server_requiring_a_root_marker_serves_only_files_below_one() {
// `framework` next to `main` (one instance for the whole project), like the
// Angular server next to vtsls.
let servers = [("main", incremental_caps()), ("framework", incremental_caps())];
let h = harness_configured("mock", "mk", &servers, |cfg| match cfg.name.as_str() {
"framework" => cfg.require_root_marker = true,
_ => cfg.root_markers.clear(),
});
for dir in ["plain", "app"] {
std::fs::create_dir_all(h.root.join(dir)).unwrap();
}
std::fs::write(h.root.join("app/mock.toml"), "").unwrap();
let (_, plain) = h.open("plain/a.mk", "x");
h.wait_status("main", ServerStatus::Ready).await;
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(h.statuses("framework").is_empty());
let (_, app) = h.open("app/b.mk", "y");
h.wait_status("framework", ServerStatus::Ready).await;
let framework = h.launcher.state("framework");
eventually(|| framework.docs.lock().contains_key(&uri_of(&app))).await;
assert!(!framework.docs.lock().contains_key(&uri_of(&plain)));
eventually(|| h.launcher.state("main").docs.lock().len() == 2).await;
// It stands in for no other server: with `ghost` missing, its fallback serves too.
let servers = [("ghost", json!({})), ("framework", incremental_caps()), ("alt", incremental_caps())];
let h = harness_configured("mock", "mk", &servers, |cfg| match cfg.name.as_str() {
"framework" => cfg.require_root_marker = true,
"alt" => cfg.fallback = true,
_ => {}
});
h.launcher.state("ghost").missing.store(true, Ordering::SeqCst);
std::fs::write(h.root.join("mock.toml"), "").unwrap();
h.open("a.mk", "x");
h.wait_status("framework", ServerStatus::Ready).await;
h.wait_status("alt", ServerStatus::Ready).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
let h = harness_with_fallbacks(&[("main", incremental_caps()), ("alt", incremental_caps())], &["alt"]);
@@ -899,6 +993,7 @@ async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
h.wait_status("alt", ServerStatus::Ready).await;
eventually(|| h.launcher.state("alt").docs.lock().contains_key(&uri)).await;
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["alt"]);
assert!(h.removed("main"));
// Enabled again: the fallback closes the document and stops.
disabled.lock().clear();
@@ -907,6 +1002,7 @@ async fn a_fallback_leaves_when_the_preferred_server_is_enabled_again() {
eventually(|| h.launcher.state("main").docs.lock().contains_key(&uri)).await;
assert!(!h.launcher.state("alt").notified("textDocument/didClose").is_empty());
assert_eq!(h.statuses("alt").last(), Some(&ServerStatus::Stopped));
assert!(h.removed("alt"));
assert_eq!(h.mgr.servers().iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["main"]);
assert!(h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.is_ok());
assert_eq!(h.launcher.state("alt").requested("textDocument/hover").len(), 0);
@@ -1024,6 +1120,128 @@ async fn navigation_rename_format_and_decorations() {
assert_eq!(h.mgr.document_symbols(doc).await.unwrap(), None);
}
/// The edits of `edit` in `path`, by range.
fn edits_in(edit: &WorkspaceEdit, path: &Path) -> Vec<(Range, String)> {
edit.files
.iter()
.filter_map(|f| match f {
FileEdit::Edit { path: p, edits } if p.to_path_buf() == path => {
Some(edits.iter().map(|e| (e.range, e.new_text.clone())))
}
_ => None,
})
.flatten()
.collect()
}
#[tokio::test(flavor = "multi_thread")]
async fn rename_merges_the_servers_that_can_rename_there() {
// `ts` can't rename inside a template string (its `prepareRename` is null), `ng` can.
let h = harness(&[("ts", incremental_caps()), ("ng", incremental_caps())]);
let (doc, path) = h.open("a.mk", "template: `{{ title }}`\ntitle = 1\n");
h.wait_status("ts", ServerStatus::Ready).await;
h.wait_status("ng", ServerStatus::Ready).await;
let html = h.root.join("a.html");
let (uri, html_uri) = (uri_of(&path), uri_of(&html));
let r = |l: u32, c0: u32, c1: u32| json!({"start":{"line":l,"character":c0},"end":{"line":l,"character":c1}});
let ng = h.launcher.state("ng");
ng.respond("textDocument/prepareRename", json!({ "range": r(0, 14, 19), "placeholder": "title" }));
ng.respond(
"textDocument/rename",
json!({ "changes": {
uri.clone(): [{ "range": r(0, 14, 19), "newText": "heading" }, { "range": r(1, 0, 5), "newText": "heading" }],
html_uri: [{ "range": r(0, 3, 8), "newText": "heading" }],
} }),
);
assert_eq!(h.mgr.prepare_rename(doc, Pos::new(0, 15)).await.unwrap(), Some(rng(0, 14, 0, 19)));
let edit = h.mgr.rename(doc, Pos::new(0, 15), "heading".into()).await.unwrap();
assert_eq!(edits_in(&edit, &path).len(), 2);
assert!(h.launcher.state("ts").requested("textDocument/rename").is_empty());
// Both can rename the declaration: `ng` adds what `ts` doesn't see, and
// `ts`'s own edits win where both change the same text.
let ts = h.launcher.state("ts");
ts.respond("textDocument/prepareRename", json!({ "range": r(1, 0, 5), "placeholder": "title" }));
ts.respond(
"textDocument/rename",
json!({ "changes": { uri: [{ "range": r(1, 0, 5), "newText": "heading: x" }] } }),
);
let edit = h.mgr.rename(doc, Pos::new(1, 2), "heading".into()).await.unwrap();
assert_eq!(edits_in(&edit, &path), [(rng(0, 14, 0, 19), "heading".into()), (rng(1, 0, 1, 5), "heading: x".into())]);
assert_eq!(edits_in(&edit, &html), [(rng(0, 3, 0, 8), "heading".into())]);
}
#[tokio::test(flavor = "multi_thread")]
async fn angular_server_is_asked_about_typescript_only_in_component_templates() {
let servers = [("vtsls", incremental_caps()), ("angular-language-server", incremental_caps())];
let h = harness_for("typescript", "ts", &servers, &[]);
let (doc, _) = h.open("a.ts", "@Component({ template: '<p>{{ title }}</p>' })\nclass A { title = 1; }\n");
h.wait_status("vtsls", ServerStatus::Ready).await;
h.wait_status("angular-language-server", ServerStatus::Ready).await;
let ng = h.launcher.state("angular-language-server");
let asked = |method: &str| ng.requested(method).len();
let mgr = &h.mgr;
let ask = |pos: Pos| async move {
mgr.completion(doc, pos, None, Default::default()).await.unwrap();
mgr.hover(doc, pos, Default::default()).await.unwrap();
mgr.goto(doc, pos, GotoKind::Definition).await.unwrap();
};
// In the class: vtsls alone, though it has no answer.
ask(Pos::new(1, 12)).await;
assert_eq!(
(asked("textDocument/completion"), asked("textDocument/hover"), asked("textDocument/definition")),
(0, 0, 0)
);
// In the template: the Angular server too.
ask(Pos::new(0, 31)).await;
assert_eq!(
(asked("textDocument/completion"), asked("textDocument/hover"), asked("textDocument/definition")),
(1, 1, 1)
);
// Inlay hints only where Angular is imported.
let lines = rng(0, 0, 2, 0);
h.mgr.inlay_hints(doc, lines).await.unwrap();
assert_eq!(asked("textDocument/inlayHint"), 0);
let (doc, _) = h.open("b.ts", "import { Component } from '@angular/core';\n");
h.mgr.inlay_hints(doc, lines).await.unwrap();
assert_eq!(asked("textDocument/inlayHint"), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn angular_references_leave_out_the_declaration_unless_asked() {
let servers = [("vtsls", incremental_caps()), ("angular-language-server", incremental_caps())];
let h = harness_for("typescript", "ts", &servers, &[]);
let (doc, path) = h.open("a.ts", "class A { title = 1; }\n");
h.wait_status("vtsls", ServerStatus::Ready).await;
h.wait_status("angular-language-server", ServerStatus::Ready).await;
let html = h.root.join("a.html");
let declaration =
json!({ "uri": uri_of(&path), "range": {"start":{"line":0,"character":10},"end":{"line":0,"character":15}} });
let usage =
json!({ "uri": uri_of(&html), "range": {"start":{"line":0,"character":3},"end":{"line":0,"character":8}} });
// Like ngserver, it lists the declaration whatever `includeDeclaration` says;
// vtsls knows where it is.
let ng = h.launcher.state("angular-language-server");
ng.respond("textDocument/references", json!([declaration, usage]));
let vtsls = h.launcher.state("vtsls");
vtsls.respond("textDocument/definition", json!([declaration]));
let mgr = &h.mgr;
let found = |include_declaration: bool| async move {
let refs = mgr.references(doc, Pos::new(0, 11), include_declaration, false, Default::default()).await;
let mut v: Vec<(PathBuf, Range)> =
refs.unwrap().locations.iter().map(|l| (l.path.to_path_buf(), l.range)).collect();
v.sort();
v
};
assert_eq!(found(false).await, [(html.clone(), rng(0, 3, 0, 8))]);
assert_eq!(found(true).await, [(html, rng(0, 3, 0, 8)), (path, rng(0, 10, 0, 15))]);
assert_eq!(vtsls.requested("textDocument/definition").len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn utf8_server_positions_are_converted() {
let h = harness(&[(
+152
Переглянути файл
@@ -69,6 +69,7 @@ async fn missing_binary_is_reported_with_install_hint() {
args: vec![],
env: Default::default(),
root_markers: vec![],
require_root_marker: false,
initialization_options: None,
settings: None,
install_hint: Some("npm i -g nope-ls".into()),
@@ -105,6 +106,44 @@ fn main() {
}
";
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires ty on PATH"]
async fn ty_python_end_to_end() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let path = root.join("example.py");
let source = "def greet(name: str) -> str:\n return name\n\nresult = greet('Ada')\nbad: int = 'wrong'\n";
std::fs::write(&path, source).unwrap();
let mut python = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("python")).unwrap();
python.language_servers.retain(|server| server.name == "ty");
assert_eq!(python.language_servers.len(), 1);
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![python]));
let doc = DocId::next();
mgr.did_open(doc, &path, &LanguageId::new("python"), 1, source);
retry("ty ready", Duration::from_secs(30), || {
let status = last_status(&events, "ty");
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
panic!("ty failed: {msg:?}");
}
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
})
.await;
let defs = retry("ty definition", Duration::from_secs(30), || {
let mgr = mgr.clone();
async move { mgr.goto(doc, Pos::new(3, 10), GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
})
.await;
assert_eq!(defs[0].path, path);
assert_eq!(defs[0].range.start.line, 0);
retry("ty diagnostics", Duration::from_secs(30), || {
let found = events.lock().iter().any(
|event| matches!(event, IdeEvent::Diagnostics { source, items, .. } if source == "ty" && !items.is_empty()),
);
async move { found.then_some(()) }
})
.await;
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires rust-analyzer"]
async fn rust_analyzer_end_to_end() {
@@ -199,6 +238,7 @@ async fn typescript_language_server_end_to_end() {
args: vec!["--stdio".into()],
env: Default::default(),
root_markers: vec!["tsconfig.json".into()],
require_root_marker: false,
initialization_options: None,
settings: None,
install_hint: None,
@@ -243,6 +283,7 @@ fn npm_server(tools: &Path, name: &str, bin: &str, init: Option<serde_json::Valu
args: vec!["--stdio".into()],
env: Default::default(),
root_markers: vec!["package.json".into()],
require_root_marker: false,
initialization_options: init.map(|v| toml::Value::try_from(v).unwrap()),
settings: None,
install_hint: None,
@@ -308,3 +349,114 @@ async fn vue_hybrid_mode_end_to_end() {
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
}
const NG_APP_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.html',\n})\nexport class App {\n title = 'demo';\n}\n";
const NG_APP_HTML: &str = "<h1>{{ title }}</h1>\n<p>{{ missing }}</p>\n";
const NG_INLINE_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-inline',\n template: `<b>{{ count }}</b>`,\n})\nexport class Inline {\n count = 1;\n}\n";
/// The lines `edit` changes in `path`, in order.
fn edited_lines(edit: &ide_core::WorkspaceEdit, path: &Path) -> Vec<u32> {
let mut lines: Vec<u32> = edit
.files
.iter()
.filter_map(|f| match f {
ide_core::FileEdit::Edit { path: p, edits } if p.to_path_buf() == path => {
Some(edits.iter().map(|e| e.range.start.line))
}
_ => None,
})
.flatten()
.collect();
lines.sort();
lines
}
/// The Angular Language Server next to vtsls, in an external and an inline
/// template. Set `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i
/// @angular/language-server @vtsls/language-server @angular/core @angular/common
/// @angular/compiler rxjs`; the project is created inside it, so that it
/// resolves `@angular/core`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @angular/language-server, @vtsls/language-server and @angular/core (OPENIDEA_TEST_NPM_TOOLS)"]
async fn angular_language_server_end_to_end() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir_in(&tools).unwrap();
let root = dir.path().canonicalize().unwrap();
std::fs::write(root.join("angular.json"), "{\"version\":1,\"projects\":{}}").unwrap();
std::fs::write(
root.join("tsconfig.json"),
"{\"compilerOptions\":{\"strict\":true},\"angularCompilerOptions\":{\"strictTemplates\":true},\"include\":[\"src/**/*.ts\"]}",
)
.unwrap();
std::fs::create_dir_all(root.join("src/app")).unwrap();
let app_ts = root.join("src/app/app.ts");
let app_html = root.join("src/app/app.html");
let inline_ts = root.join("src/app/inline.ts");
for (path, text) in [(&app_ts, NG_APP_TS), (&app_html, NG_APP_HTML), (&inline_ts, NG_INLINE_TS)] {
std::fs::write(path, text).unwrap();
}
// The built-in definitions, with vtsls and the Angular server, and the probe
// locations the settings hook adds.
let builtin = LanguageRegistry::load(None).unwrap();
let probes = tools.join("node_modules/@angular/language-server").to_string_lossy().into_owned();
let languages = ["typescript", "html"].map(|id| {
let mut cfg = builtin.get(&LanguageId::new(id)).unwrap();
cfg.language_servers.retain(|s| s.name == "angular-language-server" || s.name == "vtsls");
for server in &mut cfg.language_servers {
let bin = if server.name == "vtsls" { "vtsls" } else { "ngserver" };
server.command = tools.join("node_modules/.bin").join(bin).to_string_lossy().into_owned();
}
let server = cfg.language_servers.iter_mut().find(|s| s.name == "angular-language-server").unwrap();
server.args.extend(["--ngProbeLocations".into(), probes.clone(), "--tsProbeLocations".into(), probes.clone()]);
cfg
});
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(languages.to_vec()));
let (html, ts, inline) = (DocId::next(), DocId::next(), DocId::next());
mgr.did_open(ts, &app_ts, &LanguageId::new("typescript"), 1, NG_APP_TS);
mgr.did_open(html, &app_html, &LanguageId::new("html"), 1, NG_APP_HTML);
mgr.did_open(inline, &inline_ts, &LanguageId::new("typescript"), 1, NG_INLINE_TS);
// `title` in `{{ title }}`.
let hover = retry("hover", Duration::from_secs(90), || {
let mgr = mgr.clone();
async move { mgr.hover(html, Pos::new(0, 8), Default::default()).await.ok().flatten() }
})
.await;
assert!(hover.contents.value.contains("title"), "{}", hover.contents.value);
let defs = mgr.goto(html, Pos::new(0, 8), GotoKind::Definition).await.unwrap();
assert_eq!(defs[0].path, app_ts);
assert_eq!(defs[0].range.start.line, 7);
// `missing` is no member of `App`.
retry("template diagnostics", Duration::from_secs(60), || {
let found = events
.lock()
.iter()
.any(|e| matches!(e, IdeEvent::Diagnostics { path, items, .. } if path == &app_html && !items.is_empty()));
async move { found.then_some(()) }
})
.await;
// `count` in the inline template, which vtsls can't rename: renamed there
// and in the class.
let count = Pos::new(4, 20);
let range = mgr.prepare_rename(inline, count).await.unwrap();
assert_eq!(range, Some(Range::new(Pos::new(4, 19), Pos::new(4, 24))));
let edit = mgr.rename(inline, count, "total".into()).await.unwrap();
assert_eq!(edited_lines(&edit, &inline_ts), [4, 7], "{edit:?}");
// `title` in the class, which both servers rename: vtsls's edit and the
// template's from the Angular server.
let title = Pos::new(7, 3);
let edit = mgr.rename(ts, title, "heading".into()).await.unwrap();
assert_eq!((edited_lines(&edit, &app_ts), edited_lines(&edit, &app_html)), (vec![7], vec![0]), "{edit:?}");
// Its usage in the template, the declaration left out, from either file.
for (doc, pos) in [(ts, title), (html, Pos::new(0, 8))] {
let refs = mgr.references(doc, pos, false, false, Default::default()).await.unwrap();
let found: Vec<(std::path::PathBuf, u32)> =
refs.locations.iter().map(|l| (l.path.to_path_buf(), l.range.start.line)).collect();
assert_eq!(found, [(app_html.clone(), 0)]);
}
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
+1 -1
Переглянути файл
@@ -161,7 +161,7 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
if !data.is_file() {
return Err(nothing_recorded("perf wrote no data"));
}
let out = ide_core::process::no_window(&mut Command::new(perf))
let out = ide_core::process::prepare(&mut Command::new(perf))
.args(["script", "-i"])
.arg(data.as_ref() as &Path)
.current_dir(cwd)
+239 -16
Переглянути файл
@@ -1,4 +1,5 @@
//! Run configuration detection from build files found at the project root.
//! Run configuration detection from build files at the project root, or from the
//! builds nested in a folder that holds several repositories.
//!
//! Detection never fails: unreadable or malformed files simply contribute nothing.
@@ -461,22 +462,89 @@ fn applies_application_plugin(text: &str) -> bool {
})
}
/// How deep a build is looked for when the project root has none (a folder holding
/// several repositories: `backend/pom.xml`, `apps/server/settings.gradle`).
const NESTED_BUILD_DEPTH: usize = 3;
/// The builds marked by any of `markers`: the root itself, else the shallowest marked
/// folder of each branch, up to [`NESTED_BUILD_DEPTH`] levels down.
fn build_dirs(root: &Path, markers: &[&str]) -> Vec<PathBuf> {
let marked = |d: &Path| markers.iter().any(|m| d.join(m).is_file());
if marked(root) {
return vec![root.to_path_buf()];
}
let mut out = Vec::new();
let mut level = vec![root.to_path_buf()];
for _ in 0..NESTED_BUILD_DEPTH {
let mut next = Vec::new();
for sub in level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src") && !d.ends_with("out")) {
if marked(&sub) {
out.push(sub);
} else {
next.push(sub);
}
}
level = next;
}
out.sort();
out
}
/// Ids, names and working directory of the configurations of a build nested in
/// `rel` (`None`: the build at the project root).
struct Scope(Option<String>);
impl Scope {
fn new(root: &Path, dir: &Path) -> Self {
Self((dir != root).then(|| relative(root, dir).to_string_lossy().replace('\\', "/")))
}
fn id(&self, base: &str) -> String {
match &self.0 {
Some(l) => format!("{base}:{l}"),
None => base.to_owned(),
}
}
fn name(&self, base: &str) -> String {
match &self.0 {
Some(l) => format!("{l}: {base}"),
None => base.to_owned(),
}
}
fn cwd(&self) -> Option<PathBuf> {
self.0.as_ref().map(PathBuf::from)
}
}
const GRADLE_SETTINGS: &[&str] = &["settings.gradle.kts", "settings.gradle"];
const GRADLE_BUILDS: &[&str] = &["build.gradle.kts", "build.gradle"];
fn detect_gradle(root: &Path, out: &mut Vec<RunConfig>) {
let names = ["build.gradle.kts", "build.gradle"];
let has_settings = first_existing(root, &["settings.gradle.kts", "settings.gradle"]).is_some();
let text = match collect_texts(root, &names) {
let markers: Vec<&str> = GRADLE_SETTINGS.iter().chain(GRADLE_BUILDS).copied().collect();
for dir in build_dirs(root, &markers) {
detect_gradle_build(root, &dir, out);
}
}
fn detect_gradle_build(root: &Path, dir: &Path, out: &mut Vec<RunConfig>) {
let has_settings = first_existing(dir, GRADLE_SETTINGS).is_some();
let text = match collect_texts(dir, GRADLE_BUILDS) {
Some(t) => t,
None if has_settings => collect_texts_from_subdirs(root, &names),
None if has_settings => collect_texts_from_subdirs(dir, GRADLE_BUILDS),
None => return,
};
let cmd = wrapper(root, "gradlew", "gradlew.bat", "gradle");
out.push(config("gradle:build", "gradle build", "gradle", &cmd, &["build"]));
out.push(config("gradle:test", "gradle test", "gradle", &cmd, &["test"]).test());
let scope = Scope::new(root, dir);
let cmd = wrapper(dir, "gradlew", "gradlew.bat", "gradle");
let gradle = |id: &str, task: &str| {
config(scope.id(id), scope.name(&format!("gradle {task}")), "gradle", &cmd, &[task]).in_dir(scope.cwd())
};
spring_boot_apps(root, dir, out);
out.push(gradle("gradle:build", "build"));
out.push(gradle("gradle:test", "test").test());
if applies_application_plugin(&text) {
out.push(config("gradle:run", "gradle run", "gradle", &cmd, &["run"]));
out.push(gradle("gradle:run", "run"));
}
if text.contains("org.springframework.boot") {
out.push(config("gradle:bootRun", "gradle bootRun", "gradle", &cmd, &["bootRun"]));
out.push(gradle("gradle:bootRun", "bootRun"));
}
}
@@ -494,15 +562,170 @@ fn collect_texts_from_subdirs(root: &Path, names: &[&str]) -> String {
}
fn detect_maven(root: &Path, out: &mut Vec<RunConfig>) {
let Some(text) = collect_texts(root, &["pom.xml"]) else { return };
let cmd = wrapper(root, "mvnw", "mvnw.cmd", "mvn");
out.push(config("maven:package", "mvn package", "maven", &cmd, &["package"]));
out.push(config("maven:test", "mvn test", "maven", &cmd, &["test"]).test());
if text.contains("spring-boot-maven-plugin") {
out.push(config("maven:spring-boot:run", "mvn spring-boot:run", "maven", &cmd, &["spring-boot:run"]));
for dir in build_dirs(root, &["pom.xml"]) {
detect_maven_build(root, &dir, out);
}
}
fn detect_maven_build(root: &Path, dir: &Path, out: &mut Vec<RunConfig>) {
let Some(text) = collect_texts(dir, &["pom.xml"]) else { return };
let scope = Scope::new(root, dir);
let cmd = wrapper(dir, "mvnw", "mvnw.cmd", "mvn");
let maven = |id: &str, goal: &str| {
config(scope.id(id), scope.name(&format!("mvn {goal}")), "maven", &cmd, &[goal]).in_dir(scope.cwd())
};
spring_boot_apps(root, dir, out);
out.push(maven("maven:package", "package"));
out.push(maven("maven:test", "test").test());
if text.contains("spring-boot-maven-plugin") {
out.push(maven("maven:spring-boot:run", "spring-boot:run"));
}
}
// ---------------------------------------------------------------- spring boot
/// Source files read per build when looking for `@SpringBootApplication` classes.
const SPRING_SCAN_FILES: usize = 400;
/// "Spring Boot" configurations for the `@SpringBootApplication` main classes of the
/// modules of the build in `build` that apply the Spring Boot plugin:
/// `java -cp ${classpath} <class>` in the module, the classpath resolved at launch.
fn spring_boot_apps(root: &Path, build: &Path, out: &mut Vec<RunConfig>) {
let mut budget = SPRING_SCAN_FILES;
let mut modules = vec![build.to_path_buf()];
let mut level = vec![build.to_path_buf()];
for _ in 0..NESTED_BUILD_DEPTH {
level = level.iter().flat_map(|d| subdirs(d)).filter(|d| !d.ends_with("src")).collect();
modules.extend(level.iter().cloned());
}
for module in modules {
if budget == 0 {
break;
}
if !applies_spring_boot(&module) {
continue;
}
let module_rel = (module != root).then(|| relative(root, &module).to_string_lossy().replace('\\', "/"));
for class in spring_boot_classes(&module, &mut budget) {
let simple = class.rsplit(['.', '$']).next().unwrap_or(&class).to_owned();
let id = match &module_rel {
Some(m) => format!("application:{m}:{class}"),
None => format!("application:{class}"),
};
out.push(
config(id, simple, "spring-boot", "java", &["-cp", "${classpath}", &class])
.in_dir(module_rel.as_ref().map(PathBuf::from))
.debug("java-debug"),
);
}
}
}
/// The module's own build applies the Spring Boot plugin, and it has main sources.
fn applies_spring_boot(module: &Path) -> bool {
if !["java", "kotlin"].iter().any(|l| module.join("src/main").join(l).is_dir()) {
return false;
}
if let Some(pom) = read(&module.join("pom.xml")) {
return pom.contains("spring-boot-maven-plugin") && !pom.contains("<packaging>pom</packaging>");
}
GRADLE_BUILDS.iter().filter_map(|n| read(&module.join(n))).any(|text| {
text.lines().any(|l| {
let l = l.split("//").next().unwrap_or_default();
// The plugin id (`id("org.springframework.boot")`), not a dependency (`org.springframework.boot:…`).
["org.springframework.boot\"", "org.springframework.boot'"].iter().any(|p| l.contains(p))
&& !l.contains("apply false")
})
})
}
/// Binary names of the `@SpringBootApplication` classes with a `main` under
/// `src/main/{java,kotlin}`, from the shallowest packages that declare one (the
/// application class sits in the root package of the code it scans).
fn spring_boot_classes(module: &Path, budget: &mut usize) -> Vec<String> {
let mut found = Vec::new();
let mut level: Vec<PathBuf> =
["java", "kotlin"].iter().map(|l| module.join("src/main").join(l)).filter(|d| d.is_dir()).collect();
while !level.is_empty() && found.is_empty() && *budget > 0 {
let mut next = Vec::new();
for dir in &level {
let Ok(entries) = fs::read_dir(dir) else { continue };
let mut files = Vec::new();
for e in entries.filter_map(Result::ok) {
let path = e.path();
match e.file_type() {
Ok(t) if t.is_dir() => next.push(path),
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x == "java" || x == "kt") => {
files.push(path)
}
_ => {}
}
}
files.sort();
for file in files {
if *budget == 0 {
break;
}
*budget -= 1;
if fs::metadata(&file).is_ok_and(|m| m.len() > 256 * 1024) {
continue;
}
if let Some(class) = read(&file).and_then(|src| spring_boot_class(&src, &file)) {
found.push(class);
}
}
}
next.sort();
level = next;
}
found
}
/// The class to launch for a source file declaring a `@SpringBootApplication` with a `main`.
pub(crate) fn spring_boot_class(src: &str, file: &Path) -> Option<String> {
let code: Vec<&str> = src.lines().map(|l| l.split("//").next().unwrap_or_default()).collect();
let code = code.join("\n");
let at = code.find("@SpringBootApplication")?;
let package = code
.lines()
.map(str::trim)
.find_map(|l| l.strip_prefix("package "))
.map(|p| p.trim_end_matches(';').trim().to_owned())
.filter(|p| !p.is_empty());
let qualify = |name: &str| match &package {
Some(p) => format!("{p}.{name}"),
None => name.to_owned(),
};
if file.extension().is_some_and(|x| x == "kt") {
// A top-level `fun main` compiles into the file facade (`AppKt`, or `@file:JvmName`).
if code.lines().any(|l| l.starts_with("fun main(")) {
let jvm_name = code
.lines()
.find_map(|l| l.trim().strip_prefix("@file:JvmName(")?.split('"').nth(1).map(str::to_owned));
let facade = jvm_name.unwrap_or_else(|| {
let stem = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
let mut chars = stem.chars();
let upper: String = chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default();
format!("{upper}Kt")
});
return Some(qualify(&facade));
}
if !code.contains("fun main(") {
return None;
}
} else if !code.contains("void main(") {
return None;
}
let name: String = code[at..]
.split_whitespace()
.skip_while(|t| *t != "class")
.nth(1)?
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '$')
.collect();
(!name.is_empty()).then(|| qualify(&name))
}
// ---------------------------------------------------------------- go
fn is_go_main_package(dir: &Path) -> bool {
+2 -1
Переглянути файл
@@ -5,6 +5,7 @@ mod detect;
pub mod envfile;
pub mod java_cmdline;
pub mod junit;
mod output_encoding;
mod process;
mod utf8;
pub mod which;
@@ -209,7 +210,7 @@ pub fn save_templates(root: &Path, templates: &[RunConfig]) -> IdeResult<()> {
/// The environment runs inherit (unless "Include system environment variables" is off).
pub fn system_env() -> BTreeMap<String, String> {
std::env::vars().collect()
ide_core::process::host_vars().filter_map(|(k, v)| Some((k.into_string().ok()?, v.into_string().ok()?))).collect()
}
/// Path of the user run configuration file for `root`.
+167
Переглянути файл
@@ -0,0 +1,167 @@
//! Makes the output of JVM and Python processes match the console's encoding.
//!
//! On Windows both write piped output in the ANSI code page (GBK on a Chinese
//! system: `javac` errors, Maven / Gradle logs, `print`), while the console decodes
//! the configured encoding (UTF-8 by default). They are told which one to use:
//! `java` through `stdout.encoding` / `stderr.encoding` (JDK 19+) and their
//! `sun.*` forerunners (JDK 8–18), Maven and Gradle through `MAVEN_OPTS` /
//! `GRADLE_OPTS`, Python through `PYTHONIOENCODING`.
use std::collections::BTreeMap;
const JAVA_PROPERTIES: &[&str] = &["stdout.encoding", "stderr.encoding", "sun.stdout.encoding", "sun.stderr.encoding"];
/// What a launch needs: `-D` options to put first on a `java` command line, and
/// environment variables to set.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct EncodingFix {
pub java_args: Vec<String>,
pub env: Vec<(String, String)>,
}
fn is_utf8(encoding: &str) -> bool {
matches!(encoding.to_ascii_lowercase().replace('_', "-").as_str(), "utf-8" | "utf8")
}
fn java_options(encoding: &str) -> Vec<String> {
JAVA_PROPERTIES.iter().map(|p| format!("-D{p}={encoding}")).collect()
}
fn sets_java_encoding(text: &str) -> bool {
JAVA_PROPERTIES.iter().any(|p| text.contains(&format!("-D{p}=")))
}
/// The options for a launch of `program` (`args`, environment `vars` over the
/// `inherited` one) whose output is decoded as `encoding`; nothing when the
/// process already writes it (UTF-8 off Windows) or the user chose the options.
pub fn fix(
program: &str,
args: &[String],
vars: &BTreeMap<String, String>,
inherited: impl Fn(&str) -> Option<String>,
encoding: &str,
windows: bool,
) -> EncodingFix {
let encoding = encoding.trim();
let mut out = EncodingFix::default();
if encoding.is_empty() || (!windows && is_utf8(encoding)) {
return out;
}
let current = |key: &str| vars.get(key).cloned().or_else(|| inherited(key));
let name = crate::wrap::program_name(program).to_ascii_lowercase();
match name.as_str() {
"java" | "javaw" => {
if !args.iter().any(|a| sets_java_encoding(a))
&& !current("JDK_JAVA_OPTIONS").is_some_and(|o| sets_java_encoding(&o))
{
out.java_args = java_options(encoding);
}
}
"mvn" | "mvnw" | "mvnd" | "gradle" | "gradlew" => {
let key = if name.starts_with("gradle") { "GRADLE_OPTS" } else { "MAVEN_OPTS" };
let opts = current(key).unwrap_or_default();
if !sets_java_encoding(&opts) {
let added = java_options(encoding).join(" ");
let value = if opts.trim().is_empty() { added } else { format!("{} {added}", opts.trim()) };
out.env.push((key.to_owned(), value));
}
}
_ if is_python(&name) && current("PYTHONIOENCODING").is_none_or(|v| v.trim().is_empty()) => {
out.env.push(("PYTHONIOENCODING".to_owned(), encoding.to_owned()));
}
_ => {}
}
out
}
/// `python`, `python3`, `python3.12`, `py`, and the runners that start one.
fn is_python(name: &str) -> bool {
name == "python"
|| name == "py"
|| name.strip_prefix("python").is_some_and(|v| v.chars().all(|c| c.is_ascii_digit() || c == '.'))
|| matches!(name, "uv" | "poetry" | "pdm" | "pytest" | "pipenv")
}
#[cfg(test)]
mod tests {
use super::*;
fn run(program: &str, args: &[&str], vars: &[(&str, &str)], encoding: &str, windows: bool) -> EncodingFix {
let args: Vec<String> = args.iter().map(|a| (*a).to_owned()).collect();
let vars: BTreeMap<String, String> = vars.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
fix(program, &args, &vars, |_| None, encoding, windows)
}
#[test]
fn java_launches_write_the_console_encoding_on_windows() {
let expected = [
"-Dstdout.encoding=UTF-8",
"-Dstderr.encoding=UTF-8",
"-Dsun.stdout.encoding=UTF-8",
"-Dsun.stderr.encoding=UTF-8",
];
// The reported case: a source-file launch through the Oracle `javapath` shim.
let java = "C:/Program Files/Common Files/Oracle/Java/javapath/java.exe";
for program in [java, "java", "javaw.exe", r"C:\jdk\bin\java.exe"] {
let f = run(program, &["Main.java"], &[], "UTF-8", true);
assert_eq!(f.java_args, expected, "{program}");
assert!(f.env.is_empty());
}
assert_eq!(run("java", &["-cp", "x", "a.Main"], &[], "GBK", true).java_args[0], "-Dstdout.encoding=GBK");
}
#[test]
fn nothing_changes_where_output_already_matches() {
for (program, args) in [("java", vec!["Main.java"]), ("mvn", vec!["package"]), ("python3", vec!["a.py"])] {
assert_eq!(run(program, &args, &[], "UTF-8", false), EncodingFix::default(), "{program}");
assert_eq!(run(program, &args, &[], "utf8", false), EncodingFix::default(), "{program}");
assert_eq!(run(program, &args, &[], "", true), EncodingFix::default(), "{program}");
}
for program in ["node", "cargo", "go", "npm.cmd", "cmd.exe"] {
assert_eq!(run(program, &[], &[], "UTF-8", true), EncodingFix::default(), "{program}");
}
// A console set to another encoding elsewhere still gets it.
assert_eq!(run("java", &["Main"], &[], "GBK", false).java_args.len(), 4);
}
#[test]
fn options_chosen_by_the_user_win() {
assert!(run("java", &["-Dstdout.encoding=GBK", "Main"], &[], "UTF-8", true).java_args.is_empty());
assert!(
run("java", &["Main"], &[("JDK_JAVA_OPTIONS", "-Dsun.stdout.encoding=GBK")], "UTF-8", true)
.java_args
.is_empty()
);
assert!(run("mvn.cmd", &[], &[("MAVEN_OPTS", "-Dstdout.encoding=GBK")], "UTF-8", true).env.is_empty());
assert!(run("python.exe", &[], &[("PYTHONIOENCODING", "gbk")], "UTF-8", true).env.is_empty());
}
#[test]
fn build_tools_and_python_get_environment_variables() {
let opts =
"-Dstdout.encoding=UTF-8 -Dstderr.encoding=UTF-8 -Dsun.stdout.encoding=UTF-8 -Dsun.stderr.encoding=UTF-8";
for program in ["mvn.cmd", "mvnw.cmd", r"C:\maven\bin\mvn.cmd"] {
assert_eq!(
run(program, &["package"], &[], "UTF-8", true).env,
[("MAVEN_OPTS".to_owned(), opts.to_owned())]
);
}
for program in ["gradlew.bat", "gradle.bat"] {
assert_eq!(run(program, &["build"], &[], "UTF-8", true).env, [("GRADLE_OPTS".to_owned(), opts.to_owned())]);
}
// Existing options are kept, from the configuration or the inherited environment.
let f = run("mvn.cmd", &[], &[("MAVEN_OPTS", "-Xmx1g")], "UTF-8", true);
assert_eq!(f.env, [("MAVEN_OPTS".to_owned(), format!("-Xmx1g {opts}"))]);
let inherited =
fix("gradlew.bat", &[], &BTreeMap::new(), |k| (k == "GRADLE_OPTS").then(|| "-Xmx2g".into()), "UTF-8", true);
assert_eq!(inherited.env, [("GRADLE_OPTS".to_owned(), format!("-Xmx2g {opts}"))]);
for program in ["python.exe", "python3", "python3.12", "py.exe", "uv.exe", "poetry"] {
assert_eq!(
run(program, &[], &[], "UTF-8", true).env,
[("PYTHONIOENCODING".to_owned(), "UTF-8".to_owned())],
"{program}"
);
}
assert_eq!(run("python3", &[], &[], "GBK", false).env, [("PYTHONIOENCODING".to_owned(), "GBK".to_owned())]);
}
}
+41 -4
Переглянути файл
@@ -171,6 +171,33 @@ fn shorten_java(inv: &mut Invocation, config: &RunConfig, cwd: &Path) -> IdeResu
Ok(TempFile(Some(s.file)))
}
/// Tells JVM and Python processes to write the encoding the console decodes (see
/// [`crate::output_encoding`]).
fn match_console_encoding(inv: &mut Invocation, env: &mut LaunchEnv, config: &RunConfig, options: &StartOptions) {
if inv.raw_args {
return;
}
let inherit = !env.clear;
let fix = crate::output_encoding::fix(
&inv.program.to_string_lossy(),
&inv.args,
&env.vars,
|key| if inherit { std::env::var(key).ok() } else { None },
options.encoding.as_deref().unwrap_or("UTF-8"),
cfg!(windows),
);
env.vars.extend(fix.env);
if !fix.java_args.is_empty() {
inv.args.splice(0..0, fix.java_args);
let mut display = quote(config.command.trim());
for a in &inv.args {
display.push(' ');
display.push_str(&quote(a));
}
inv.display = display;
}
}
/// A launch's pathing jar / argfile, deleted when dropped (the process exited, or never started).
struct TempFile(Option<PathBuf>);
@@ -275,7 +302,7 @@ impl ProcessManager {
if extras.emulate_terminal && extras.stdin_file.is_some() {
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
}
let env = launch_env(root, config)?;
let mut env = launch_env(root, config)?;
let on_output: OutputFn = Arc::from(on_output);
let on_output = match extras.output_file.as_deref() {
Some(file) => tee_output(&resolve_cwd(root, Some(Path::new(file))), on_output)?,
@@ -286,6 +313,10 @@ impl ProcessManager {
cwd: cwd.clone(),
env: env.clone(),
});
if !extras.emulate_terminal {
// A terminal re-encodes output itself; pipes carry the process's bytes as they are.
match_console_encoding(&mut inv, &mut env, config, options);
}
let temp = shorten_java(&mut inv, config, &cwd)?;
if extras.emulate_terminal {
return self.start_pty(config, &inv, &cwd, &env, stop, options, sink, on_output, temp);
@@ -407,6 +438,12 @@ impl ProcessManager {
if env.clear {
cmd.env_clear();
} else {
for (k, v) in ide_core::process::host_env_fixes() {
match v {
Some(v) => cmd.env(k, v),
None => cmd.env_remove(k),
}
}
for (k, v) in ide_core::process::shell_env() {
cmd.env(k, v);
}
@@ -602,7 +639,7 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
BTreeMap::new()
} else {
let base: BTreeMap<String, String> =
if extras.include_system_env { std::env::vars().collect() } else { BTreeMap::new() };
if extras.include_system_env { crate::system_env() } else { BTreeMap::new() };
let paths: Vec<PathBuf> = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect();
crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))?
};
@@ -620,7 +657,7 @@ fn apply_env(cmd: &mut Command, env: &LaunchEnv) {
if env.clear {
cmd.env_clear();
} else {
cmd.envs(ide_core::process::shell_env());
ide_core::process::host_env(cmd).envs(ide_core::process::shell_env());
}
cmd.envs(&env.vars);
}
@@ -631,6 +668,7 @@ fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
output(OutputChunk::System { text: format!("{}\n", stop.line) });
let inv = shell_invocation(&stop.line, cfg!(windows), std::env::var("COMSPEC").ok());
let mut cmd = Command::new(&inv.program);
ide_core::process::prepare(&mut cmd);
if inv.raw_args {
add_raw_args(&mut cmd, &inv.args);
} else {
@@ -638,7 +676,6 @@ fn run_stop_command(stop: &StopCommand, output: &OutputFn) {
}
cmd.current_dir(&stop.cwd).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::piped());
apply_env(&mut cmd, &stop.env);
ide_core::process::no_window(&mut cmd);
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => {
+1 -1
Переглянути файл
@@ -93,7 +93,7 @@ pub fn find_tool(name: &str, config: &RunConfig, dir: &Path, root: &Path) -> Opt
pub fn probe(argv: &[String], dir: &Path, config: &RunConfig) -> bool {
let Some((program, args)) = argv.split_first() else { return false };
let program = resolve(program, config);
ide_core::process::no_window(&mut Command::new(program))
ide_core::process::prepare(&mut Command::new(program))
.args(args)
.current_dir(dir)
.envs(&config.env)
+124
Переглянути файл
@@ -184,6 +184,130 @@ fn maven_projects() {
assert_eq!(c[0].command, "mvn");
}
const BOOT_POM: &str = "<project><artifactId>app</artifactId><build><plugins><plugin>\
<artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>";
const PARENT_POM: &str = "<project><packaging>pom</packaging><modules><module>app</module></modules>\
<build><pluginManagement><plugins><plugin>\
<artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></pluginManagement>\
</build></project>";
const BOOT_MAIN: &str = "package org.dromara;\n\nimport org.springframework.boot.SpringApplication;\n\
import org.springframework.boot.autoconfigure.SpringBootApplication;\n\n\
/** Entry. */\n@SpringBootApplication\npublic class DromaraApplication {\n\
\x20 public static void main(String[] args) {\n\
\x20 SpringApplication.run(DromaraApplication.class, args);\n }\n}\n";
/// A folder holding a Maven back end and an npm front end, each its own repository
/// (RuoYi-Vue-Plus + plus-ui): the Maven build is detected where it is.
#[test]
fn builds_nested_in_a_folder_of_repositories() {
let dir = project(&[
("RuoYi-Vue-Plus/pom.xml", PARENT_POM),
("RuoYi-Vue-Plus/ruoyi-admin/pom.xml", BOOT_POM),
("RuoYi-Vue-Plus/ruoyi-admin/src/main/java/org/dromara/DromaraApplication.java", BOOT_MAIN),
("RuoYi-Vue-Plus/ruoyi-admin/src/main/java/org/dromara/web/Controller.java", "package org.dromara.web;"),
("RuoYi-Vue-Plus/ruoyi-common/pom.xml", "<project><packaging>pom</packaging></project>"),
("RuoYi-Vue-Plus/ruoyi-common/ruoyi-common-core/pom.xml", "<project/>"),
("RuoYi-Vue-Plus/ruoyi-common/ruoyi-common-core/src/main/java/A.java", "class A {}"),
("plus-ui/package.json", r#"{"scripts":{"dev":"vite"}}"#),
]);
let c = detect(dir.path());
let app = find(&c, "application:RuoYi-Vue-Plus/ruoyi-admin:org.dromara.DromaraApplication");
assert_eq!(app.name, "DromaraApplication");
assert_eq!(app.kind, "spring-boot");
assert_eq!(cmdline(app), "java -cp ${classpath} org.dromara.DromaraApplication");
assert_eq!(app.cwd.as_deref(), Some(Path::new("RuoYi-Vue-Plus/ruoyi-admin")));
assert_eq!(app.debug_adapter.as_deref(), Some("java-debug"));
let package = find(&c, "maven:package:RuoYi-Vue-Plus");
assert_eq!(package.name, "RuoYi-Vue-Plus: mvn package");
assert_eq!(cmdline(package), "mvn package");
assert_eq!(package.cwd.as_deref(), Some(Path::new("RuoYi-Vue-Plus")));
assert!(find(&c, "maven:test:RuoYi-Vue-Plus").is_test);
assert!(ids(&c).contains(&"maven:spring-boot:run:RuoYi-Vue-Plus"));
assert!(ids(&c).contains(&"npm:plus-ui:dev"));
// Modules of the nested build are not builds of their own; only one application.
assert!(!ids(&c).iter().any(|id| id.contains("ruoyi-common")));
assert_eq!(c.iter().filter(|c| c.kind == "spring-boot").count(), 1);
}
#[test]
fn nested_builds_of_every_kind_and_depth() {
let dir = project(&[
("services/api/settings.gradle.kts", "include(\"app\")"),
("services/api/gradlew", "#!/bin/sh"),
("services/api/app/build.gradle.kts", "plugins { id(\"org.springframework.boot\") version \"3.3.0\" }\n"),
(
"services/api/app/src/main/kotlin/com/acme/Api.kt",
"package com.acme\n\n@SpringBootApplication\nclass Api\n\nfun main(args: Array<String>) {\n runApplication<Api>(*args)\n}\n",
),
("billing/pom.xml", BOOT_POM),
("billing/mvnw", "#!/bin/sh"),
(
"billing/src/main/java/Billing.java",
"@SpringBootApplication\nclass Billing { public static void main(String[] a) {} }",
),
// Deeper than a build is looked for.
("a/b/c/d/pom.xml", "<project/>"),
// Build output and sources are not searched.
("web/node_modules/x/pom.xml", "<project/>"),
("tool/src/pom.xml", "<project/>"),
]);
let c = detect(dir.path());
let boot = find(&c, "gradle:bootRun:services/api");
assert_eq!(boot.name, "services/api: gradle bootRun");
assert_eq!(boot.cwd.as_deref(), Some(Path::new("services/api")));
if cfg!(unix) {
assert_eq!(cmdline(boot), "./gradlew bootRun");
assert_eq!(cmdline(find(&c, "maven:package:billing")), "./mvnw package");
}
assert!(find(&c, "gradle:test:services/api").is_test);
let api = find(&c, "application:services/api/app:com.acme.ApiKt");
assert_eq!(api.cwd.as_deref(), Some(Path::new("services/api/app")));
let billing = find(&c, "application:billing:Billing");
assert_eq!(billing.cwd.as_deref(), Some(Path::new("billing")));
let builds: Vec<&str> =
ids(&c).into_iter().filter(|id| id.starts_with("maven:package") || id.starts_with("gradle:build")).collect();
assert_eq!(builds, ["gradle:build:services/api", "maven:package:billing"]);
}
#[test]
fn a_root_build_disables_the_nested_scan() {
let dir = project(&[
("pom.xml", BOOT_POM),
(
"src/main/java/demo/App.java",
"package demo;\n@SpringBootApplication public class App {\n public static void main(String[] args) {}\n}\n",
),
("tools/gen/pom.xml", "<project/>"),
]);
let c = detect(dir.path());
assert!(ids(&c).contains(&"maven:package"));
assert!(!ids(&c).iter().any(|id| id.contains("tools")));
let app = find(&c, "application:demo.App");
assert_eq!(app.cwd, None);
}
#[test]
fn spring_boot_applications_need_the_plugin_and_a_main() {
let main =
"package demo;\n@SpringBootApplication\npublic class App {\n public static void main(String[] args) {}\n}\n";
// A library using Spring Boot without the plugin, a configuration class without `main`,
// the annotation in a comment, a parent POM.
let dir = project(&[
("lib/pom.xml", "<project><dependencies>spring-boot-starter</dependencies></project>"),
("lib/src/main/java/demo/App.java", main),
("svc/pom.xml", BOOT_POM),
("svc/src/main/java/demo/Config.java", "package demo;\n@SpringBootApplication\npublic class Config {}\n"),
(
"svc/src/main/java/demo/Old.java",
"package demo;\n// @SpringBootApplication\nclass Old { public static void main(String[] a) {} }\n",
),
("gr/build.gradle", "dependencies { implementation 'org.springframework.boot:spring-boot-starter' }\n"),
("gr/src/main/java/demo/App.java", main),
]);
let c = detect(dir.path());
assert!(!c.iter().any(|c| c.kind == "spring-boot"), "{:?}", ids(&c));
}
#[test]
fn go_projects() {
let dir = project(&[
+1
Переглянути файл
@@ -17,6 +17,7 @@ serde_json.workspace = true
specta.workspace = true
toml.workspace = true
tracing.workspace = true
which = "8"
zip = { version = "=2.4.2", default-features = false, features = ["deflate"] }
[dev-dependencies]
+90
Переглянути файл
@@ -0,0 +1,90 @@
//! Angular Language Server (`ngserver`): its package, where TypeScript and
//! `@angular/language-service` come from, and the project's Angular version.
use crate::npm::package_dir;
use std::path::{Path, PathBuf};
pub(crate) const SERVER: &str = "angular-language-server";
const PACKAGE: &str = "@angular/language-server";
/// `@angular/language-server`'s directory for an `ngserver` executable.
pub(crate) fn server_package(bin: &Path) -> Option<PathBuf> {
package_dir(bin, PACKAGE)
}
/// Why an `ngserver` whose package isn't found can't start: it loads TypeScript
/// and `@angular/language-service` from there.
pub(crate) fn missing_package_message(bin: &Path) -> String {
format!(
"Can't find the @angular/language-server package of {}, which brings the TypeScript and Angular \
language service the server loads. Reinstall it in Settings › Languages & Frameworks › Language \
Servers or with `npm i -g @angular/language-server`.",
bin.display()
)
}
/// Why a server installed in a directory whose path has a comma can't start.
pub(crate) fn comma_message(package: &str) -> String {
format!(
"The Angular Language Server can't load from {package}: its path has a comma. Install it in a \
directory without one."
)
}
/// The version of the `@angular/core` that `dir` resolves (from its own or an
/// ancestor's `node_modules`, like Node).
pub(crate) fn core_version(dir: &Path) -> Option<String> {
dir.ancestors().find_map(|a| {
let text = std::fs::read_to_string(a.join("node_modules/@angular/core/package.json")).ok()?;
let json: serde_json::Value = serde_json::from_str(&text).ok()?;
json.get("version")?.as_str().map(str::to_owned)
})
}
/// Arguments telling the server the project's Angular `version`: templates of
/// projects before 17 have no blocks (`@if`), before 18.1 no `@let`.
pub(crate) fn version_args(version: &str) -> Vec<String> {
let mut parts = version.split(['.', '-', '+']).map(|p| p.parse::<u32>().ok());
let (Some(Some(major)), Some(Some(minor))) = (parts.next(), parts.next()) else { return Vec::new() };
// 0.0.0: a local build of Angular.
if major == 0 {
return Vec::new();
}
let mut args = vec!["--angularCoreVersion".to_owned(), version.to_owned()];
if major < 17 {
args.push("--disableBlockSyntax".into());
}
if (major, minor) < (18, 1) {
args.push("--disableLetSyntax".into());
}
args
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn template_syntax_follows_the_angular_version() {
let args = |v: &str| version_args(v).into_iter().skip(2).collect::<Vec<_>>();
assert_eq!(version_args("22.2.3")[..2], ["--angularCoreVersion", "22.2.3"]);
assert_eq!(args("22.0.0-next.1"), Vec::<String>::new());
assert_eq!(args("18.1.0"), Vec::<String>::new());
assert_eq!(args("18.0.5"), ["--disableLetSyntax"]);
assert_eq!(args("17.3.12"), ["--disableLetSyntax"]);
assert_eq!(args("16.2.0"), ["--disableBlockSyntax", "--disableLetSyntax"]);
assert!(version_args("0.0.0-PLACEHOLDER").is_empty());
assert!(version_args("next").is_empty());
}
#[test]
fn core_version_is_found_in_an_ancestor() {
let tmp = tempfile::tempdir().unwrap();
let core = tmp.path().join("node_modules/@angular/core");
std::fs::create_dir_all(&core).unwrap();
std::fs::write(core.join("package.json"), r#"{"name":"@angular/core","version":"19.2.1"}"#).unwrap();
let app = tmp.path().join("apps/web");
std::fs::create_dir_all(&app).unwrap();
assert_eq!(core_version(&app).as_deref(), Some("19.2.1"));
}
}
+41 -2
Переглянути файл
@@ -3,12 +3,13 @@
use crate::discover::{project_venv_python, workspace_tsdk};
use crate::exec::{path_with, search_path};
use crate::{angular, godot, vue};
use crate::{bin_dir, exe, venv_of};
use crate::{godot, vue};
use ide_core::settings::{LanguageServerSettings, Settings};
use ide_language::{LanguageConfig, LanguageServerConfig};
use ide_run::RunConfig;
use serde_json::{Value, json};
use std::ffi::OsString;
use std::path::{Path, PathBuf};
fn non_empty(s: &str) -> Option<&str> {
@@ -134,7 +135,7 @@ pub fn tsdk(root: &Path, s: &Settings) -> Option<PathBuf> {
}
}
const PYTHON_SERVERS: [&str; 5] = ["basedpyright", "pyright", "pylsp", "jedi-language-server", "ruff"];
const PYTHON_SERVERS: [&str; 6] = ["basedpyright", "pyright", "ty", "pylsp", "jedi-language-server", "ruff"];
fn merge(base: &mut Value, layer: Value) {
match (base, layer) {
@@ -300,6 +301,11 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
let dirs: Vec<&Path> = path_dirs.iter().map(PathBuf::as_path).collect();
cfg.env.insert("PATH".into(), path_with(&dirs));
}
// Last: it finds the server on the `PATH` set above.
if name == angular::SERVER {
configure_angular(cfg, root, server_root, s);
}
}
/// The servers `language` uses after Settings › Language Servers: the
@@ -334,6 +340,7 @@ fn custom_server(name: &str, ls: &LanguageServerSettings) -> LanguageServerConfi
args: Vec::new(),
env: Default::default(),
root_markers: ls.root_markers.clone(),
require_root_marker: false,
initialization_options: None,
settings: None,
install_hint: Some(match ls.command.trim() {
@@ -394,6 +401,38 @@ fn configure_vue_typescript(cfg: &mut LanguageServerConfig, root: &Path, server_
}
}
/// ngserver loads TypeScript and `@angular/language-service` from probe
/// locations: its own package (it depends on both), then the project. A selected
/// TypeScript version goes first (`--tsdk`); the project's Angular version decides
/// the template syntax. Without its package the server can't start.
fn configure_angular(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
// Found as the launcher finds it; missing, it asks to be installed.
let path = cfg.env.get("PATH").map_or_else(search_path, OsString::from);
let Ok(bin) = which::which_in(&cfg.command, Some(path), server_root) else { return };
let Some(package) = angular::server_package(&bin) else {
cfg.launch_error = Some(angular::missing_package_message(&bin));
return;
};
let package = package.to_string_lossy().into_owned();
// The server splits the list at commas.
if package.contains(',') {
cfg.launch_error = Some(angular::comma_message(&package));
return;
}
// Launch the server whose package is probed, not another one on the path.
cfg.command = bin.to_string_lossy().into_owned();
let project = server_root.to_string_lossy();
let probes = if project.contains(',') { package } else { format!("{package},{project}") };
cfg.args.extend(["--ngProbeLocations".into(), probes.clone(), "--tsProbeLocations".into(), probes]);
if let Some(lib) = tsdk(server_root, s).or_else(|| tsdk(root, s)) {
cfg.args.extend(["--tsdk".into(), lib.to_string_lossy().into_owned()]);
}
// The project root is an ancestor of the server's.
if let Some(version) = angular::core_version(server_root) {
cfg.args.extend(angular::version_args(&version));
}
}
fn is_python_command(cmd: &str) -> bool {
let name = Path::new(cmd).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let name = name.strip_suffix(".exe").unwrap_or(&name);
+9 -3
Переглянути файл
@@ -14,9 +14,15 @@ pub fn search_path() -> OsString {
let mut dirs: Vec<PathBuf> =
std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
if let Some(home) = crate::home_dir() {
for rel in [".cargo/bin", ".local/bin", "go/bin", ".pyenv/shims", ".volta/bin"] {
for rel in [".cargo/bin", ".local/bin", "go/bin", ".pyenv/shims", ".bun/bin", ".npm-global/bin", ".volta/bin"] {
dirs.push(home.join(rel));
}
// nvm: newest installed node's bin, as language servers are launched.
if let Ok(entries) = std::fs::read_dir(home.join(".nvm/versions/node")) {
let mut versions: Vec<PathBuf> = entries.flatten().map(|e| e.path().join("bin")).collect();
versions.sort();
dirs.extend(versions.into_iter().rev());
}
}
for d in ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"] {
dirs.push(PathBuf::from(d));
@@ -59,7 +65,7 @@ pub(crate) fn query_in(
if let Some(cwd) = cwd {
cmd.current_dir(cwd);
}
let mut child = ide_core::process::no_window(&mut cmd)
let mut child = ide_core::process::prepare(&mut cmd)
.args(args)
.env("PATH", search_path())
.envs(env.iter().copied())
@@ -112,7 +118,7 @@ pub(crate) fn stream(
on_line: &dyn Fn(String),
) -> IdeResult<String> {
let mut cmd = Command::new(program);
ide_core::process::no_window(&mut cmd);
ide_core::process::prepare(&mut cmd);
cmd.args(args).env("PATH", search_path()).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
cmd.envs(env.iter().map(|(k, v)| (k, v)));
if let Some(cwd) = cwd {
+2
Переглянути файл
@@ -5,6 +5,7 @@
//! - applying the selected toolchains from settings to language-server launch
//! configs, run configurations and new terminal sessions ([`apply`]).
mod angular;
pub mod apply;
mod discover;
mod exec;
@@ -14,6 +15,7 @@ pub mod jdtls;
pub mod libraries;
pub mod locate;
pub mod lombok;
mod npm;
pub mod python;
mod vue;
+36
Переглянути файл
@@ -0,0 +1,36 @@
//! Node-based language servers installed with npm: the package behind a command.
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
/// `command` as given (a path) or found on `path`, npm shims included.
pub(crate) fn find_command(command: &str, path: &OsStr) -> Option<PathBuf> {
let p = Path::new(command);
if p.is_absolute() {
return p.is_file().then(|| p.to_path_buf());
}
let exts: &[&str] = if cfg!(windows) { &[".cmd", ".exe", ""] } else { &[""] };
std::env::split_paths(path)
.flat_map(|d| exts.iter().map(move |e| d.join(format!("{command}{e}"))))
.find(|c| c.is_file())
}
/// The npm package an executable comes from: next to a `node_modules/.bin` shim
/// (the IDE's tools dir, a project), a Windows global shim (`%APPDATA%\npm`), a
/// Unix global `<prefix>/bin` or a symlink into the package.
pub(crate) fn package_dir(bin: &Path, package: &str) -> Option<PathBuf> {
let dir = bin.parent()?;
let mut candidates = vec![dir.join("node_modules").join(package)];
if dir.file_name() == Some(OsStr::new(".bin"))
&& let Some(node_modules) = dir.parent()
{
candidates.push(node_modules.join(package));
}
if let Ok(real) = dunce::canonicalize(bin) {
candidates.extend(real.ancestors().filter(|a| a.ends_with(package)).map(Path::to_path_buf));
}
if let Some(prefix) = dir.parent() {
candidates.push(prefix.join("lib").join("node_modules").join(package));
}
candidates.into_iter().find(|c| c.join("package.json").is_file())
}
+73
Переглянути файл
@@ -27,6 +27,7 @@ fn server(name: &str) -> LanguageServerConfig {
args: vec![],
env: BTreeMap::new(),
root_markers: vec![],
require_root_marker: false,
initialization_options: None,
settings: None,
install_hint: None,
@@ -600,6 +601,78 @@ fn vue_language_server_gets_a_typescript_with_the_language_service_api() {
assert_eq!(cfg.args, [format!("--tsdk={}", lib.to_string_lossy())]);
}
/// An npm shim for `name` in `dir`: `name.cmd` on Windows, an executable elsewhere.
fn npm_shim(dir: &Path, name: &str) -> std::path::PathBuf {
std::fs::create_dir_all(dir).unwrap();
let shim = dir.join(if cfg!(windows) { format!("{name}.cmd") } else { name.to_owned() });
std::fs::write(&shim, "").unwrap();
#[cfg(unix)]
std::fs::set_permissions(&shim, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
shim
}
#[test]
fn angular_language_server_probes_its_own_package_then_the_project() {
let tmp = tempfile::tempdir().unwrap();
let tools = tmp.path().join("tools/node_modules");
let project = tmp.path().join("app");
let ngserver = npm_shim(&tools.join(".bin"), "ngserver");
for (p, content) in [
(tools.join("@angular/language-server/package.json"), "{}"),
(project.join("node_modules/@angular/core/package.json"), r#"{"version":"17.3.0"}"#),
(project.join("node_modules/typescript/lib/tsserver.js"), ""),
] {
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, content).unwrap();
}
let configured = |command: &str, s: &Settings| {
let mut cfg = server("angular-language-server");
cfg.command = command.into();
cfg.args = vec!["--stdio".into()];
configure_server(&mut cfg, &project, &project, s);
cfg
};
let probes = format!("{},{}", tools.join("@angular/language-server").to_string_lossy(), project.to_string_lossy());
let cfg = configured(&ngserver.to_string_lossy(), &Settings::default());
assert_eq!(
cfg.args,
[
"--stdio",
"--ngProbeLocations",
&probes,
"--tsProbeLocations",
&probes,
"--angularCoreVersion",
"17.3.0",
"--disableLetSyntax"
]
);
assert_eq!(cfg.launch_error, None);
// The project's TypeScript when selected.
let mut s = Settings::default();
s.languages.typescript.version = "workspace".into();
let args = configured(&ngserver.to_string_lossy(), &s).args;
let tsdk = args.iter().position(|a| a == "--tsdk").map(|i| args[i + 1].clone());
assert_eq!(tsdk, Some(project.join("node_modules/typescript/lib").to_string_lossy().into_owned()));
// Found on the selected Node.js's PATH like the launcher finds it, and
// launched from there.
let mut s = Settings::default();
s.languages.node.interpreter = tools.join(".bin/node").to_string_lossy().into_owned();
let cfg = configured("ngserver", &s);
assert_eq!(dunce::canonicalize(&cfg.command).unwrap(), dunce::canonicalize(&ngserver).unwrap());
assert!(cfg.args.contains(&probes));
// Without its package the server can't start; not installed, it asks to be.
let lone = npm_shim(&tmp.path().join("bin"), "ngserver");
let cfg = configured(&lone.to_string_lossy(), &Settings::default());
assert!(cfg.launch_error.is_some_and(|m| m.contains("@angular/language-server")));
assert_eq!(cfg.args, ["--stdio"]);
let cfg = configured(&tmp.path().join("nowhere/ngserver").to_string_lossy(), &Settings::default());
assert_eq!((cfg.launch_error, cfg.args), (None, vec!["--stdio".to_owned()]));
}
#[test]
fn max_java_picks_an_older_jdk() {
let dir = tempfile::tempdir().unwrap();
+1 -32
Переглянути файл
@@ -1,6 +1,7 @@
//! Vue Language Server (Volar 3): the TypeScript it loads as a library, and the
//! `@vue/typescript-plugin` that vtsls' tsserver hosts for it (hybrid mode).
use crate::npm::{find_command, package_dir};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
@@ -14,38 +15,6 @@ pub(crate) fn has_ts_api(lib: &Path) -> bool {
lib.join("typescript.js").is_file()
}
/// `command` as given (a path) or found on `path`, npm shims included.
fn find_command(command: &str, path: &OsStr) -> Option<PathBuf> {
let p = Path::new(command);
if p.is_absolute() {
return p.is_file().then(|| p.to_path_buf());
}
let exts: &[&str] = if cfg!(windows) { &[".cmd", ".exe", ""] } else { &[""] };
std::env::split_paths(path)
.flat_map(|d| exts.iter().map(move |e| d.join(format!("{command}{e}"))))
.find(|c| c.is_file())
}
/// The npm package an executable comes from: next to a `node_modules/.bin` shim
/// (the IDE's tools dir, a project), a Windows global shim (`%APPDATA%\npm`), a
/// Unix global `<prefix>/bin` or a symlink into the package.
fn package_dir(bin: &Path, package: &str) -> Option<PathBuf> {
let dir = bin.parent()?;
let mut candidates = vec![dir.join("node_modules").join(package)];
if dir.file_name() == Some(OsStr::new(".bin"))
&& let Some(node_modules) = dir.parent()
{
candidates.push(node_modules.join(package));
}
if let Ok(real) = dunce::canonicalize(bin) {
candidates.extend(real.ancestors().filter(|a| a.ends_with(package)).map(Path::to_path_buf));
}
if let Some(prefix) = dir.parent() {
candidates.push(prefix.join("lib").join("node_modules").join(package));
}
candidates.into_iter().find(|c| c.join("package.json").is_file())
}
/// `@vue/language-server`'s directory for the `vue-language-server` command.
pub(crate) fn server_package(command: &str, path: &OsStr) -> Option<PathBuf> {
package_dir(&find_command(command, path)?, PACKAGE)
+10 -1
Переглянути файл
@@ -364,7 +364,8 @@ impl Speller {
/// Whether the letter run `w` was split from is a known term as a whole:
/// `IntelliJ` (`Intelli` + `J`), `PostgreSQL` (`Postgre` + `SQL`).
fn known_run(&self, text: &str, w: &WordSpan) -> bool {
let start = text[..w.start].rfind(|c: char| !c.is_alphabetic()).map_or(0, |i| i + 1);
let start =
text[..w.start].char_indices().rev().find(|(_, c)| !c.is_alphabetic()).map_or(0, |(i, c)| i + c.len_utf8());
let end = text[w.end..].find(|c: char| !c.is_alphabetic()).map_or(text.len(), |i| w.end + i);
(start, end) != (w.start, w.end) && self.user_word(&text[start..end].to_lowercase())
}
@@ -504,6 +505,14 @@ mod tests {
assert_eq!(typos[0].range, Range::new(Pos::new(0, 3), Pos::new(0, 10)));
}
#[test]
fn misspellings_after_unicode_punctuation_do_not_panic() {
let text = "// 状态:Recieve and 【mesage】 😀writting";
let typos = Speller::default().check(text, &whole(text, RegionKind::Comment), &|| false).unwrap();
let words: Vec<_> = typos.iter().map(|t| t.word.as_str()).collect();
assert_eq!(words, ["Recieve", "mesage", "writting"]);
}
#[test]
fn identifiers_forgive_case_and_terms() {
let s = Speller::default();
+18 -6
Переглянути файл
@@ -1,6 +1,8 @@
//! Shell integration (Settings › Tools › Terminal › Shell integration): the
//! shell reports its working directory (OSC 7) at every prompt, so links and
//! new splits resolve against the directory the user `cd`-ed into.
//! new splits resolve against the directory the user `cd`-ed into, and marks
//! where a command starts and ends (OSC 133 C / D), so the tab shows the
//! running program's title only while one runs.
//!
//! zsh starts with `ZDOTDIR` pointing at generated startup files that source
//! the user's own ones first; bash gets an `--init-file` that replays the
@@ -29,8 +31,11 @@ ZDOTDIR=$OPENIDEA_USER_ZDOTDIR
[[ -f $ZDOTDIR/.zshrc ]] && . $ZDOTDIR/.zshrc
OPENIDEA_USER_ZDOTDIR=$ZDOTDIR
ZDOTDIR=$_openidea_dir
_openidea_osc7() { printf '\e]7;file://%s%s\a' "${HOST}" "${PWD}" }
autoload -Uz add-zsh-hook 2>/dev/null && add-zsh-hook precmd _openidea_osc7
_openidea_osc7() { printf '\e]133;D\a\e]7;file://%s%s\a' "${HOST}" "${PWD}" }
_openidea_preexec() { printf '\e]133;C\a' }
# First, so the command counts as finished before other hooks set the prompt's title.
precmd_functions=(_openidea_osc7 ${precmd_functions:#_openidea_osc7})
preexec_functions+=(_openidea_preexec)
if [[ ! -o login ]]; then
ZDOTDIR=$OPENIDEA_USER_ZDOTDIR
unset OPENIDEA_USER_ZDOTDIR _openidea_dir
@@ -54,15 +59,22 @@ if [ "${OPENIDEA_LOGIN:-}" = 1 ]; then
else
[ -f ~/.bashrc ] && . ~/.bashrc
fi
__openidea_osc7() { printf '\e]7;file://%s%s\a' "${HOSTNAME}" "${PWD}"; }
__openidea_osc7() { printf '\e]133;D\a\e]7;file://%s%s\a' "${HOSTNAME}" "${PWD}"; }
case ";${PROMPT_COMMAND:-};" in
*";__openidea_osc7;"*) ;;
*) PROMPT_COMMAND="__openidea_osc7${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;;
esac
# PS0 (bash 4.4+) prints before each command runs.
case "${PS0:-}" in
*'133;C'*) ;;
*) PS0="${PS0:-}\e]133;C\a" ;;
esac
"#;
const FISH_INIT: &str =
r#"function __openidea_osc7 --on-event fish_prompt; printf '\e]7;file://%s%s\a' (hostname) $PWD; end"#;
const FISH_INIT: &str = concat!(
r#"function __openidea_osc7 --on-event fish_prompt; printf '\e]133;D\a\e]7;file://%s%s\a' (hostname) $PWD; end; "#,
r#"function __openidea_preexec --on-event fish_preexec; printf '\e]133;C\a'; end"#,
);
/// Directory holding the generated startup files (written on demand).
fn scripts_dir() -> PathBuf {
+6
Переглянути файл
@@ -97,6 +97,12 @@ impl TerminalManager {
let mut cmd = CommandBuilder::new(&shell);
cmd.args(&args);
cmd.cwd(resolve_cwd(&options.cwd));
for (k, v) in ide_core::process::host_env_fixes() {
match v {
Some(v) => cmd.env(k, v),
None => cmd.env_remove(k),
}
}
for (k, v) in env {
cmd.env(k, v);
}
+1 -1
Переглянути файл
@@ -113,7 +113,7 @@ fn extract_zip(archive: &Path, dest: &Path) -> IdeResult<()> {
/// `.tar.xz` goes through the system `tar` (bsdtar on macOS/Windows, GNU tar + xz on Linux).
fn extract_tar_xz(archive: &Path, dest: &Path) -> IdeResult<()> {
let tar = which::which("tar").map_err(|_| IdeError::unavailable("`tar` is required to unpack .tar.xz archives"))?;
let out = ide_core::process::no_window(&mut std::process::Command::new(tar))
let out = ide_core::process::prepare(&mut std::process::Command::new(tar))
.arg("-xJf")
.arg(archive)
.arg("-C")
+2 -2
Переглянути файл
@@ -165,7 +165,7 @@ pub fn extend_process_path(app_data: &Path) {
/// `PATH` plus the usual per-user tool locations (GUI apps on macOS start with a minimal `PATH`).
pub fn default_search_path() -> OsString {
let mut dirs: Vec<PathBuf> =
std::env::var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
ide_core::process::host_var_os("PATH").map(|p| std::env::split_paths(&p).collect()).unwrap_or_default();
if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from) {
for rel in [".cargo/bin", ".local/bin", "go/bin", ".bun/bin", ".volta/bin", ".npm-global/bin", "Library/pnpm"] {
dirs.push(home.join(rel));
@@ -343,7 +343,7 @@ impl Tools {
fn command(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
let mut cmd = Command::new(program);
ide_core::process::no_window(&mut cmd).env("PATH", &self.child_path);
ide_core::process::prepare(&mut cmd).env("PATH", &self.child_path);
cmd
}
+3 -3
Переглянути файл
@@ -48,7 +48,7 @@ pub fn run_streamed(cmd: Command, cancel: &CancellationToken, emit: Emit) -> Ide
/// Like [`run_streamed`] but returns `(success, output, status text)` instead of failing on a non-zero exit.
pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) -> IdeResult<(bool, String, String)> {
emit(InstallEvent::Line { text: format!("$ {}", describe(&cmd)) });
ide_core::process::no_window(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
ide_core::process::prepare(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", describe(&cmd))))?;
let (tx, rx) = mpsc::channel::<String>();
let pipes: [Option<Box<dyn Read + Send>>; 2] = [
@@ -94,7 +94,7 @@ pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) ->
/// Runs `cmd` to completion within `timeout`; returns (success, stdout + stderr).
pub fn run_quiet(mut cmd: Command, timeout: Duration) -> Option<(bool, String)> {
ide_core::process::no_window(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
ide_core::process::prepare(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn().ok()?;
let mut stdout = child.stdout.take()?;
let mut stderr = child.stderr.take()?;
@@ -161,7 +161,7 @@ impl Http {
fn base(&self, url: &str) -> Command {
let mut cmd = Command::new(&self.curl);
ide_core::process::no_window(&mut cmd);
ide_core::process::prepare(&mut cmd);
cmd.args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-A", "openidea"]);
if url.starts_with("https://api.github.com/")
&& let Ok(token) = std::env::var("GITHUB_TOKEN").or_else(|_| std::env::var("GH_TOKEN"))
+21
Переглянути файл
@@ -167,6 +167,16 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://docs.basedpyright.com",
needs: &[],
},
ToolSpec {
name: "ty",
display: "ty (Python)",
kind: LanguageServer,
commands: &["ty"],
method: Method::PipVenv { package: "ty" },
version: ver("ty"),
homepage: "https://docs.astral.sh/ty/",
needs: &[],
},
ToolSpec {
name: "bash-language-server",
display: "Bash Language Server",
@@ -247,6 +257,17 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/vuejs/language-tools",
needs: &[],
},
ToolSpec {
name: "angular-language-server",
display: "Angular Language Server",
kind: LanguageServer,
commands: &["ngserver"],
// Brings the TypeScript and `@angular/language-service` it loads.
method: Method::Npm { packages: &["@angular/language-server"] },
version: V,
homepage: "https://angular.dev/tools/language-service",
needs: &[],
},
ToolSpec {
name: "graphql-lsp",
display: "GraphQL Language Server",
+9
Переглянути файл
@@ -67,6 +67,15 @@ fn everything_missing_on_an_empty_system() {
let vtsls = find(&list, "vtsls");
assert!(vtsls.languages.iter().any(|l| l == "TypeScript"));
assert!(vtsls.unavailable_reason.as_deref().unwrap().contains("npm"));
let ty = find(&list, "ty");
assert_eq!(ty.status, ToolStatus::Missing);
assert_eq!(ty.command, "ty");
assert_eq!(ty.install_method.as_deref(), Some("pip (virtualenv)"));
assert!(ty.languages.iter().any(|language| language == "Python"));
let angular = find(&list, "angular-language-server");
assert_eq!(angular.command, "ngserver");
assert_eq!(angular.install_method.as_deref(), Some("npm"));
assert_eq!(angular.languages, ["HTML", "TypeScript"]);
// Servers without an installer are listed with their manual hint.
let hls = find(&list, "haskell-language-server");
assert_eq!(hls.install_method, None);
+2 -2
Переглянути файл
@@ -72,7 +72,7 @@ pub fn git_version(executable: Option<&Path>) -> IdeResult<String> {
};
let mut cmd = Command::new(&exe);
cmd.arg("--version").stdin(Stdio::null()).env("LC_ALL", "C");
ide_core::process::no_window(&mut cmd);
ide_core::process::prepare(&mut cmd);
let out = cmd.output().map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", exe.display())))?;
let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !out.status.success() || !text.starts_with("git version") {
@@ -106,7 +106,7 @@ pub(crate) fn command(root: &Path) -> IdeResult<Command> {
for (k, v) in ASKPASS.read().unwrap_or_else(|e| e.into_inner()).iter() {
cmd.env(k, v);
}
ide_core::process::no_window(&mut cmd);
ide_core::process::prepare(&mut cmd);
Ok(cmd)
}
+33 -5
Переглянути файл
@@ -32,6 +32,8 @@ pub enum WatchMode {
/// One non-recursive watch per directory, skipping excluded and ignored
/// directories; new directories are picked up as they appear.
PerDirectory,
/// The root's own entries only (loose files edited outside a project).
Flat,
}
impl Default for WatchMode {
@@ -81,7 +83,8 @@ impl Watcher {
on_change(batch);
};
let inner = match mode {
WatchMode::Recursive => Self::start_recursive(root, filter, emit),
WatchMode::Recursive => Self::start_recursive(root, filter, emit, RecursiveMode::Recursive),
WatchMode::Flat => Self::start_recursive(root, filter, emit, RecursiveMode::NonRecursive),
WatchMode::PerDirectory => Self::start_per_directory(root, filter, emit),
}?;
Ok(Self { inner, excludes: shared })
@@ -94,7 +97,7 @@ impl Watcher {
*self.excludes.write() = ExcludeMatcher::new(excludes);
}
/// Number of OS-level watches (1 in recursive mode).
/// Number of OS-level watches (1 in recursive and flat mode).
pub fn watch_count(&self) -> usize {
match &self.inner {
Inner::Recursive(_) => 1,
@@ -106,6 +109,7 @@ impl Watcher {
root: PathBuf,
filter: EventFilter,
emit: impl Fn(&FsBatch) + Send + 'static,
recursive: RecursiveMode,
) -> IdeResult<Inner> {
// No file-id cache: building it walks and stats the whole tree before `watch` returns,
// which made opening large projects block for seconds. Renames arrive as remove + create.
@@ -125,9 +129,7 @@ impl Watcher {
let mut debouncer =
new_debouncer_opt::<_, RecommendedWatcher, _>(DEBOUNCE, None, handler, NoCache, notify::Config::default())
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?;
debouncer
.watch(&root, RecursiveMode::Recursive)
.map_err(|e| io_error(format!("cannot watch {}: {e}", root.display())))?;
debouncer.watch(&root, recursive).map_err(|e| io_error(format!("cannot watch {}: {e}", root.display())))?;
Ok(Inner::Recursive(debouncer))
}
@@ -787,4 +789,30 @@ mod tests {
std::thread::sleep(Duration::from_millis(400));
assert_eq!(batches.lock().len(), n, "no events after drop");
}
#[test]
fn flat_mode_reports_the_roots_own_entries_only() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
std::fs::create_dir_all(root.join("sub")).unwrap();
let batches: Arc<Mutex<Vec<FsBatch>>> = Arc::default();
let sink: SharedSink = Arc::new(|_e: IdeEvent| {});
let watcher = {
let batches = batches.clone();
Watcher::start_with(
&root,
Vec::new(),
sink,
Box::new(move |b| batches.lock().push(b.clone())),
WatchMode::Flat,
)
.unwrap()
};
assert_eq!(watcher.watch_count(), 1);
std::fs::write(root.join("sub/deep.txt"), "x").unwrap();
std::fs::write(root.join("a.txt"), "x").unwrap();
assert!(wait_for(&batches, |b| all_paths(b).contains(&root.join("a.txt"))), "{:?}", batches.lock());
std::thread::sleep(Duration::from_millis(300));
assert!(!all_paths(&batches.lock()).contains(&root.join("sub/deep.txt")));
}
}
+32 -4
Переглянути файл
@@ -96,18 +96,46 @@ pub fn open(url: &str, id: Option<&str>) -> IdeResult<()> {
if !(url.starts_with("http://") || url.starts_with("https://") || url.starts_with("file://")) {
return Err(IdeError::invalid(format!("not a web URL: {url}")));
}
let result = match id {
None => open::that_detached(url),
let app = match id {
None => None,
Some(id) => {
let known =
KNOWN.iter().find(|k| k.id == id).ok_or_else(|| IdeError::invalid(format!("unknown browser: {id}")))?;
let app = locate(known).ok_or_else(|| IdeError::unavailable(format!("{} is not installed", known.name)))?;
open::with_detached(url, app.to_string_lossy().as_ref())
Some(locate(known).ok_or_else(|| IdeError::unavailable(format!("{} is not installed", known.name)))?)
}
};
#[cfg(target_os = "linux")]
let result = spawn_with_host_env(match &app {
None => open::commands(url),
Some(app) => vec![open::with_command(url, app.to_string_lossy())],
});
#[cfg(not(target_os = "linux"))]
let result = match &app {
None => open::that_detached(url),
Some(app) => open::with_detached(url, app.to_string_lossy().as_ref()),
};
result.map_err(|e| IdeError::unavailable(format!("cannot open the browser: {e}")))
}
/// Starts the first launcher that runs (`xdg-open`, `gio`, ...), with the host's environment
/// rather than an AppImage's, and reaps it in the background.
#[cfg(target_os = "linux")]
fn spawn_with_host_env(commands: Vec<std::process::Command>) -> std::io::Result<()> {
use std::process::Stdio;
let mut last_err = None;
for mut cmd in commands {
ide_core::process::prepare(&mut cmd).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
match cmd.spawn() {
Ok(mut child) => {
std::thread::spawn(move || child.wait());
return Ok(());
}
Err(e) => last_err = Some(e),
}
}
Err(last_err.unwrap_or_else(|| std::io::Error::other("no launcher available")))
}
#[cfg(test)]
mod tests {
use super::*;
+22 -1
Переглянути файл
@@ -295,7 +295,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
203 themeable tokens: 113 in the UI theme file, 90 in the editor colour scheme file.
219 themeable tokens: 113 in the UI theme file, 106 in the editor colour scheme file.
### Surfaces (UI theme)
@@ -480,6 +480,27 @@ a token.
| `--ansi-bright-cyan` | `#00e5e5` | `#1b9ea3` |
| `--ansi-bright-white` | `#ffffff` | `#5f6269` |
### Terminal ANSI palette (editor scheme)
| Token | Islands Dark | Islands Light |
|---|---|---|
| `--terminal-ansi-black` | `#000000` | `#000000` |
| `--terminal-ansi-red` | `#f27481` | `#c93645` |
| `--terminal-ansi-green` | `#6bcc62` | `#357d1f` |
| `--terminal-ansi-yellow` | `#e0ce70` | `#b2a400` |
| `--terminal-ansi-blue` | `#5594fa` | `#225cd6` |
| `--terminal-ansi-magenta` | `#c092fa` | `#6e32e5` |
| `--terminal-ansi-cyan` | `#47ccbd` | `#007a80` |
| `--terminal-ansi-white` | `#ced0d6` | `#bec0c5` |
| `--terminal-ansi-bright-black` | `#4e5157` | `#6c707e` |
| `--terminal-ansi-bright-red` | `#ff6b7a` | `#ff5462` |
| `--terminal-ansi-bright-green` | `#67ff59` | `#3dcc3d` |
| `--terminal-ansi-bright-yellow` | `#ffec1a` | `#d4bb00` |
| `--terminal-ansi-bright-blue` | `#3399ff` | `#009dff` |
| `--terminal-ansi-bright-magenta` | `#d970ff` | `#d659ff` |
| `--terminal-ansi-bright-cyan` | `#40ffe9` | `#31c4b3` |
| `--terminal-ansi-bright-white` | `#ffffff` | `#d2d4d9` |
### Shadows and window controls (UI theme)
| Token | Islands Dark | Islands Light |
+5 -5
Переглянути файл
@@ -87,12 +87,12 @@ terminal is a real xterm renderer, without a native PTY or shell. These images
cover the shell, sidebar, editor, gutter, find matches, terminal, Settings,
focused controls, disabled settings and the selected theme popup.
| Theme | Workbench, editor and terminal | Settings and theme popup |
|---|---|---|
| Theme | Workbench, editor and terminal | Settings and theme popup |
| --------------- | -------------------------------------------------------- | ---------------------------------------------------- |
| Solarized Light | [Screenshot](media/themes/solarized-light-workbench.png) | [Screenshot](media/themes/solarized-light-popup.png) |
| Solarized Dark | [Screenshot](media/themes/solarized-dark-workbench.png) | [Screenshot](media/themes/solarized-dark-popup.png) |
| One Light | [Screenshot](media/themes/one-light-workbench.png) | [Screenshot](media/themes/one-light-popup.png) |
| One Dark | [Screenshot](media/themes/one-dark-workbench.png) | [Screenshot](media/themes/one-dark-popup.png) |
| Solarized Dark | [Screenshot](media/themes/solarized-dark-workbench.png) | [Screenshot](media/themes/solarized-dark-popup.png) |
| One Light | [Screenshot](media/themes/one-light-workbench.png) | [Screenshot](media/themes/one-light-popup.png) |
| One Dark | [Screenshot](media/themes/one-dark-workbench.png) | [Screenshot](media/themes/one-dark-popup.png) |
The browser regression also checks refresh / startup cache restoration,
selection visibility, same-kind switches, the quick menu, existing themes,
-30
Переглянути файл
@@ -1,30 +0,0 @@
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import reactHooks from "eslint-plugin-react-hooks";
export default tseslint.config(
{
ignores: [
"dist",
"target",
"src-tauri",
"crates",
"src/bindings.ts",
"fixtures",
"plugins",
"test-results",
"playwright-report",
// Agent worktrees: whole checkouts of the repo.
".claude",
],
},
js.configs.recommended,
...tseslint.configs.recommended,
{
plugins: { "react-hooks": reactHooks },
rules: {
...reactHooks.configs.recommended.rules,
"@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_", varsIgnorePattern: "^_" }],
},
},
);
+11 -2
Переглянути файл
@@ -11,11 +11,20 @@
<div id="root"></div>
<div id="splash" class="splash" data-tauri-drag-region>
<svg class="splash-logo" viewBox="22 24 56 56" aria-hidden="true">
<rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C" /><rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A" /><circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7" /><rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0" /><rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0" /><rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0" /><circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0" />
<rect x="22" y="26" width="56" height="52" rx="12" fill="#D9582C" />
<rect x="27" y="26" width="46" height="42" rx="9" fill="#1B1A1A" />
<circle cx="44" cy="47.4" r="4.1" fill="none" stroke="#EAE7E0" stroke-width="2.7" />
<rect x="54.3" y="42" width="2.8" height="10.5" fill="#EAE7E0" />
<rect x="51.2" y="42" width="5.9" height="2.5" fill="#EAE7E0" />
<rect x="51.2" y="50" width="9.4" height="2.5" fill="#EAE7E0" />
<circle cx="55.7" cy="38.4" r="1.8" fill="#EAE7E0" />
</svg>
<!-- "OpenIDEA" in Inter 500 as outlines: the web font loads late in dev and would swap in. -->
<svg class="splash-wordmark" viewBox="0 -1984 9994 2478" role="img" aria-label="OpenIDEA">
<path fill="currentColor" d="M785.8 20Q592.6 20 440.4 -71.7Q288.2 -163.4 200.4 -334.7Q112.6 -506 112.6 -744Q112.6 -983.2 200.4 -1154.6Q288.2 -1326 440.4 -1418Q592.6 -1510 785.8 -1510Q979 -1510 1130.7 -1418Q1282.4 -1326 1369.8 -1154.6Q1457.3 -983.2 1457.3 -744Q1457.3 -505.8 1369.8 -334.5Q1282.4 -163.2 1130.7 -71.6Q979 20 785.8 20ZM785.8 -187.7Q913 -187.7 1013.5 -251.6Q1114 -315.5 1172.4 -439.9Q1230.7 -564.3 1230.7 -744Q1230.7 -925.6 1172.4 -1050Q1114 -1174.5 1013.5 -1238.4Q913 -1302.3 785.8 -1302.3Q657.9 -1302.3 557 -1238Q456.1 -1173.7 397.7 -1049.2Q339.2 -924.7 339.2 -744Q339.2 -564.3 397.7 -440.3Q456.1 -316.3 557 -252Q657.9 -187.7 785.8 -187.7ZM1717.9 418V-1118H1932.2V-935.9H1950.4Q1970 -970.8 2005.4 -1016.7Q2040.9 -1062.7 2104.6 -1097.3Q2168.3 -1132 2272.6 -1132Q2407.4 -1132 2512.7 -1064Q2617.9 -996 2678.8 -867Q2739.8 -738 2739.8 -556.4Q2739.8 -375.7 2679.8 -246.2Q2619.8 -116.7 2514.5 -47.3Q2409.1 22.2 2272.7 22.2Q2171.8 22.2 2107.4 -12.4Q2043 -47 2006.6 -93.2Q1970.2 -139.3 1950.4 -175H1937.9V418ZM2224 -165.3Q2320.1 -165.3 2384.9 -217.3Q2449.6 -269.3 2482.4 -358.3Q2515.2 -447.3 2515.2 -558Q2515.2 -668.1 2482.8 -755.4Q2450.4 -842.8 2385.7 -893.7Q2321 -944.5 2224 -944.5Q2129.6 -944.5 2065 -896.1Q2000.4 -847.7 1967.4 -761.2Q1934.4 -674.6 1934.4 -558Q1934.4 -441.7 1967.8 -353.2Q2001.2 -264.7 2066.2 -215Q2131.2 -165.3 2224 -165.3ZM3465.8 23.3Q3300.7 23.3 3181.1 -48.1Q3061.4 -119.5 2996.9 -248.5Q2932.4 -377.5 2932.4 -551.1Q2932.4 -723.3 2995.8 -854Q3059.1 -984.7 3175.1 -1058.4Q3291 -1132 3446.8 -1132Q3542.6 -1132 3632 -1100.7Q3721.4 -1069.4 3792.3 -1002.3Q3863.3 -935.2 3904.7 -828.3Q3946.2 -721.5 3946.2 -570.3V-492.2H3054.8V-656.5H3832.8L3730.1 -602.3Q3730.1 -704.7 3698.2 -783.2Q3666.3 -861.7 3603.5 -905.9Q3540.8 -950 3447.5 -950Q3354.2 -950 3288.2 -905Q3222.1 -860 3187.4 -786.5Q3152.6 -712.9 3152.6 -626.1V-514.4Q3152.6 -399.4 3192.1 -319.8Q3231.6 -240.1 3302.9 -199.4Q3374.2 -158.7 3468.1 -158.7Q3529.6 -158.7 3579.9 -176.3Q3630.2 -194 3666.5 -229.4Q3702.8 -264.9 3722.2 -317.2L3928.6 -268.5Q3902.2 -181.6 3838.6 -115.9Q3775 -50.2 3680.4 -13.4Q3585.8 23.3 3465.8 23.3ZM4406.9 -662.4V0H4186.9V-1118H4396.6L4398.9 -844.3H4376.2Q4424.9 -994.3 4517.8 -1063.1Q4610.7 -1132 4742.5 -1132Q4856.6 -1132 4942 -1084.2Q5027.5 -1036.3 5075.1 -942.5Q5122.7 -848.8 5122.7 -710.4V0H4902.7V-682.9Q4902.7 -803.7 4839.8 -872.1Q4776.9 -940.5 4667.3 -940.5Q4592.9 -940.5 4533.8 -907.9Q4474.8 -875.3 4440.8 -813.3Q4406.9 -751.2 4406.9 -662.4ZM5664.4 -1490V0H5435.9V-1490ZM6478.5 0H6109.9V-199.7H6465.8Q6635 -199.7 6747.1 -263Q6859.2 -326.3 6915 -448.6Q6970.8 -571 6970.8 -747.3Q6970.8 -922.1 6915.2 -1043.3Q6859.7 -1164.4 6750.5 -1227.4Q6641.3 -1290.3 6478.4 -1290.3H6102.2V-1490H6493Q6713.2 -1490 6869.9 -1400.9Q7026.7 -1311.8 7110.7 -1145.2Q7194.7 -978.6 7194.7 -747.3Q7194.7 -514.5 7110.4 -347.1Q7026 -179.6 6865.8 -89.8Q6705.5 0 6478.5 0ZM6222.4 -1490V0H5993.9V-1490ZM7471.9 0V-1490H8409.8V-1293.6H7700.4V-849.7H8359.5V-654.7H7700.4V-196.4H8416.4V0ZM8592.9 0 9123.5 -1490H9403.2L9942.8 0H9696.3L9406.1 -828.9Q9372.2 -930 9331.8 -1066.9Q9291.4 -1203.8 9238.4 -1395.6H9284.5Q9232.7 -1202.2 9192.5 -1063.6Q9152.4 -925.1 9121.4 -828.9L8839.9 0ZM8880.4 -392.6V-583.1H9655.3V-392.6Z" />
<path
fill="currentColor"
d="M785.8 20Q592.6 20 440.4 -71.7Q288.2 -163.4 200.4 -334.7Q112.6 -506 112.6 -744Q112.6 -983.2 200.4 -1154.6Q288.2 -1326 440.4 -1418Q592.6 -1510 785.8 -1510Q979 -1510 1130.7 -1418Q1282.4 -1326 1369.8 -1154.6Q1457.3 -983.2 1457.3 -744Q1457.3 -505.8 1369.8 -334.5Q1282.4 -163.2 1130.7 -71.6Q979 20 785.8 20ZM785.8 -187.7Q913 -187.7 1013.5 -251.6Q1114 -315.5 1172.4 -439.9Q1230.7 -564.3 1230.7 -744Q1230.7 -925.6 1172.4 -1050Q1114 -1174.5 1013.5 -1238.4Q913 -1302.3 785.8 -1302.3Q657.9 -1302.3 557 -1238Q456.1 -1173.7 397.7 -1049.2Q339.2 -924.7 339.2 -744Q339.2 -564.3 397.7 -440.3Q456.1 -316.3 557 -252Q657.9 -187.7 785.8 -187.7ZM1717.9 418V-1118H1932.2V-935.9H1950.4Q1970 -970.8 2005.4 -1016.7Q2040.9 -1062.7 2104.6 -1097.3Q2168.3 -1132 2272.6 -1132Q2407.4 -1132 2512.7 -1064Q2617.9 -996 2678.8 -867Q2739.8 -738 2739.8 -556.4Q2739.8 -375.7 2679.8 -246.2Q2619.8 -116.7 2514.5 -47.3Q2409.1 22.2 2272.7 22.2Q2171.8 22.2 2107.4 -12.4Q2043 -47 2006.6 -93.2Q1970.2 -139.3 1950.4 -175H1937.9V418ZM2224 -165.3Q2320.1 -165.3 2384.9 -217.3Q2449.6 -269.3 2482.4 -358.3Q2515.2 -447.3 2515.2 -558Q2515.2 -668.1 2482.8 -755.4Q2450.4 -842.8 2385.7 -893.7Q2321 -944.5 2224 -944.5Q2129.6 -944.5 2065 -896.1Q2000.4 -847.7 1967.4 -761.2Q1934.4 -674.6 1934.4 -558Q1934.4 -441.7 1967.8 -353.2Q2001.2 -264.7 2066.2 -215Q2131.2 -165.3 2224 -165.3ZM3465.8 23.3Q3300.7 23.3 3181.1 -48.1Q3061.4 -119.5 2996.9 -248.5Q2932.4 -377.5 2932.4 -551.1Q2932.4 -723.3 2995.8 -854Q3059.1 -984.7 3175.1 -1058.4Q3291 -1132 3446.8 -1132Q3542.6 -1132 3632 -1100.7Q3721.4 -1069.4 3792.3 -1002.3Q3863.3 -935.2 3904.7 -828.3Q3946.2 -721.5 3946.2 -570.3V-492.2H3054.8V-656.5H3832.8L3730.1 -602.3Q3730.1 -704.7 3698.2 -783.2Q3666.3 -861.7 3603.5 -905.9Q3540.8 -950 3447.5 -950Q3354.2 -950 3288.2 -905Q3222.1 -860 3187.4 -786.5Q3152.6 -712.9 3152.6 -626.1V-514.4Q3152.6 -399.4 3192.1 -319.8Q3231.6 -240.1 3302.9 -199.4Q3374.2 -158.7 3468.1 -158.7Q3529.6 -158.7 3579.9 -176.3Q3630.2 -194 3666.5 -229.4Q3702.8 -264.9 3722.2 -317.2L3928.6 -268.5Q3902.2 -181.6 3838.6 -115.9Q3775 -50.2 3680.4 -13.4Q3585.8 23.3 3465.8 23.3ZM4406.9 -662.4V0H4186.9V-1118H4396.6L4398.9 -844.3H4376.2Q4424.9 -994.3 4517.8 -1063.1Q4610.7 -1132 4742.5 -1132Q4856.6 -1132 4942 -1084.2Q5027.5 -1036.3 5075.1 -942.5Q5122.7 -848.8 5122.7 -710.4V0H4902.7V-682.9Q4902.7 -803.7 4839.8 -872.1Q4776.9 -940.5 4667.3 -940.5Q4592.9 -940.5 4533.8 -907.9Q4474.8 -875.3 4440.8 -813.3Q4406.9 -751.2 4406.9 -662.4ZM5664.4 -1490V0H5435.9V-1490ZM6478.5 0H6109.9V-199.7H6465.8Q6635 -199.7 6747.1 -263Q6859.2 -326.3 6915 -448.6Q6970.8 -571 6970.8 -747.3Q6970.8 -922.1 6915.2 -1043.3Q6859.7 -1164.4 6750.5 -1227.4Q6641.3 -1290.3 6478.4 -1290.3H6102.2V-1490H6493Q6713.2 -1490 6869.9 -1400.9Q7026.7 -1311.8 7110.7 -1145.2Q7194.7 -978.6 7194.7 -747.3Q7194.7 -514.5 7110.4 -347.1Q7026 -179.6 6865.8 -89.8Q6705.5 0 6478.5 0ZM6222.4 -1490V0H5993.9V-1490ZM7471.9 0V-1490H8409.8V-1293.6H7700.4V-849.7H8359.5V-654.7H7700.4V-196.4H8416.4V0ZM8592.9 0 9123.5 -1490H9403.2L9942.8 0H9696.3L9406.1 -828.9Q9372.2 -930 9331.8 -1066.9Q9291.4 -1203.8 9238.4 -1395.6H9284.5Q9232.7 -1202.2 9192.5 -1063.6Q9152.4 -925.1 9121.4 -828.9L8839.9 0ZM8880.4 -392.6V-583.1H9655.3V-392.6Z"
/>
</svg>
<div class="splash-bar" role="progressbar" aria-label="Loading"><i></i></div>
</div>
+10
Переглянути файл
@@ -7,6 +7,16 @@ indent = { tab-size = 2, insert-spaces = true }
ui-mode = "HTML"
tree-sitter = "html"
# Angular projects only: component templates. First, so that hover, rename and
# document symbols of templates come from it rather than plain HTML.
[[language-servers]]
name = "angular-language-server"
command = "ngserver"
args = ["--stdio", "--includeCompletionsWithSnippetText", "--includeAutomaticOptionalChainCompletions"]
root-markers = ["angular.json", "node_modules/@angular/core"]
require-root-marker = true
install-hint = "npm i -g @angular/language-server"
[[language-servers]]
name = "vscode-html-language-server"
command = "vscode-html-language-server"
+8
Переглянути файл
@@ -32,6 +32,14 @@ args = ["--stdio"]
root-markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile", "pyrightconfig.json"]
install-hint = "npm i -g pyright (or: pip install pyright)"
[[language-servers]]
name = "ty"
fallback = true
command = "ty"
args = ["server"]
root-markers = ["ty.toml", "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile"]
install-hint = "uv tool install ty (or: pip install ty)"
[debugger]
adapter = "debugpy"
command = "python3"
+11
Переглянути файл
@@ -23,6 +23,17 @@ args = ["--stdio"]
root-markers = ["tsconfig.json", "jsconfig.json", "package.json"]
install-hint = "npm i -g typescript@\"<7\" typescript-language-server"
# Angular projects only: templates inline in components (`template: ...`),
# and their usages and renames in templates. Last: TypeScript's own hover,
# definition and symbols come first.
[[language-servers]]
name = "angular-language-server"
command = "ngserver"
args = ["--stdio", "--includeCompletionsWithSnippetText", "--includeAutomaticOptionalChainCompletions"]
root-markers = ["angular.json", "node_modules/@angular/core"]
require-root-marker = true
install-hint = "npm i -g @angular/language-server"
[debugger]
adapter = "js-debug"
command = "js-debug-adapter"
+6 -8
Переглянути файл
@@ -2,7 +2,7 @@
"name": "openidea",
"private": true,
"description": "An open-source IDE inspired by IntelliJ IDEA",
"version": "0.1.20",
"version": "0.1.22",
"license": "Apache-2.0",
"type": "module",
"scripts": {
@@ -12,8 +12,9 @@
"tauri": "tauri",
"test": "vitest run",
"test:watch": "vitest",
"lint": "eslint .",
"format": "prettier --write .",
"lint": "oxlint",
"format": "oxfmt",
"format:check": "oxfmt --check",
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p scripts --noEmit",
"gen:bindings": "cargo test -p openidea --test export_bindings",
"gen:theme-docs": "node scripts/theme/gen-docs.ts",
@@ -59,7 +60,6 @@
"zustand": "^5.0.15"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@playwright/test": "^1.64.1",
"@tauri-apps/cli": "^2",
"@testing-library/jest-dom": "^7.0.1",
@@ -70,13 +70,11 @@
"@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^6.0.2",
"eslint": "^10.13.0",
"eslint-plugin-react-hooks": "^7.1.1",
"jsdom": "^30.1.3",
"prettier": "^3.9.10",
"oxfmt": "^0.74.0",
"oxlint": "^1.89.0",
"tsrs": "^0.20.0-ts7.1.0-beta",
"typescript": "~6.0.3",
"typescript-eslint": "^8.71.2",
"vite": "^8.0.16",
"vitest": "^5.0.5"
}
+11 -11
Переглянути файл
@@ -13,15 +13,15 @@ python perf/compare/bench.py ~/src/spring-petclinic --runs 5 --wipe-caches # c
Each run launches the app on the project, waits until it is ready, idles,
closes it, and records:
| Metric | How |
|---|---|
| `window_s` | first visible window whose title matches `window_title` (the project name) |
| `ready_s` | the process tree's CPU stays under `--quiet-cores` for `--quiet-secs`, after the window and any `ready_after` markers |
| markers | first/last time a log line matches, e.g. OpenIDEA `indexed`, IDEA `exit dumb mode` |
| `peak_rss_mb`, `rss_mb`, `uss_mb`, `pss_mb` | summed over every process the app started (WebView2/WebKit, jdtls, language servers, the JVM) |
| `total_cpu_s`, `idle_cpu_pct` | CPU time until ready; CPU while idle for `--idle-secs` |
| `exit_s` | until every process has exited |
| `cache_mb`, install size | `cache_dirs`, `install_dir` |
| Metric | How |
| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `window_s` | first visible window whose title matches `window_title` (the project name) |
| `ready_s` | the process tree's CPU stays under `--quiet-cores` for `--quiet-secs`, after the window and any `ready_after` markers |
| markers | first/last time a log line matches, e.g. OpenIDEA `indexed`, IDEA `exit dumb mode` |
| `peak_rss_mb`, `rss_mb`, `uss_mb`, `pss_mb` | summed over every process the app started (WebView2/WebKit, jdtls, language servers, the JVM) |
| `total_cpu_s`, `idle_cpu_pct` | CPU time until ready; CPU while idle for `--idle-secs` |
| `exit_s` | until every process has exited |
| `cache_mb`, install size | `cache_dirs`, `install_dir` |
Apps run interleaved, rotating the order, after `--warmup` discarded runs.
Output goes to `results/<time>-<project>/`: `report.md` (median, min–max),
@@ -31,8 +31,8 @@ Output goes to `results/<time>-<project>/`: `report.md` (median, min–max),
- Release builds only; a running instance of the same executable (a
`pnpm tauri dev` build too) would take over the launch, so the script refuses.
- IDEA: open the project once by hand and trust it; turn off *Reopen projects
on startup* and *Confirm before exiting*; note the version, `-Xmx` and whether
- IDEA: open the project once by hand and trust it; turn off _Reopen projects
on startup_ and _Confirm before exiting_; note the version, `-Xmx` and whether
Shared Indexes were on.
- Same machine, power plan and plugged in; exclude the project and caches from
antivirus scanning, or neither.
+29 -29
Переглянути файл
@@ -48,11 +48,11 @@ All paths are relative to the package directory and may not leave it.
### Permissions
| Permission | Unlocks |
|----------------|-------------------------------------------------|
| Permission | Unlocks |
| -------------- | ------------------------------------------------- |
| `project-read` | `workspace-root`, `read-file` (project root only) |
| `editor-read` | `active-file` |
| `editor-write` | `insert-text`, `replace-selection` |
| `editor-read` | `active-file` |
| `editor-write` | `insert-text`, `replace-selection` |
`log`, `register-command`, `show-notification`, `register-language` and
`register-theme` are always available. Calling a gated function without its
@@ -133,22 +133,22 @@ Any language with component-model tooling works (e.g. `componentize-py`,
### Host functions
| Function | Notes |
|---|---|
| `log(level, msg)` | Goes to the IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
| `register-command(id, title, category?)` | Becomes action `plugin.<plugin-id>.<id>`; call again to rename. Max 256 commands. |
| `show-notification(level, title, body)` | Balloon in the invoking window. |
| `workspace-root()` | Root of the project the command runs in. |
| `active-file()` | Absolute path of the focused editor's file. |
| `read-file(path)` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB. Unsaved editor contents win over disk. |
| `insert-text(text)` | Inserts at every cursor of the active editor (cursor ends after the text). |
| `replace-selection(text)` | Replaces every selection and selects the new text. |
| `register-language(toml)` | Same format as `languages/<id>.toml`. |
| `register-theme(json)` | See *Themes* below. |
| Function | Notes |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `log(level, msg)` | Goes to the IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. |
| `register-command(id, title, category?)` | Becomes action `plugin.<plugin-id>.<id>`; call again to rename. Max 256 commands. |
| `show-notification(level, title, body)` | Balloon in the invoking window. |
| `workspace-root()` | Root of the project the command runs in. |
| `active-file()` | Absolute path of the focused editor's file. |
| `read-file(path)` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB. Unsaved editor contents win over disk. |
| `insert-text(text)` | Inserts at every cursor of the active editor (cursor ends after the text). |
| `replace-selection(text)` | Replaces every selection and selects the new text. |
| `register-language(toml)` | Same format as `languages/<id>.toml`. |
| `register-theme(json)` | See _Themes_ below. |
`run-command` receives an optional string argument: `executeAction("plugin.hello.insert-date", "arg")`
from another feature, or nothing when run from Search Everywhere / a shortcut.
Returning `Err(msg)` shows *"<title> failed: msg"*; the plugin keeps running.
Returning `Err(msg)` shows _"<title> failed: msg"_; the plugin keeps running.
### Sandbox and limits
@@ -156,13 +156,13 @@ Each plugin gets its own wasmtime `Store`: no preopened directories, no
environment, no network, no inherited stdio — only clocks and randomness from
WASI, plus the host functions above. Every call into the plugin is bounded:
* **CPU:** a fuel budget (≈ 5·10⁹ wasm instructions) per call;
* **time:** 5 s wall clock per call (epoch interruption);
* **memory:** 256 MiB of linear memory.
- **CPU:** a fuel budget (≈ 5·10⁹ wasm instructions) per call;
- **time:** 5 s wall clock per call (epoch interruption);
- **memory:** 256 MiB of linear memory.
A panic, trap, permission violation or exceeded limit stops the plugin and
marks it *Failed* for the session (with the reason in Settings › Plugins);
toggling it off and on, or *Reload*, starts a fresh instance. The IDE itself is
marks it _Failed_ for the session (with the reason in Settings › Plugins);
toggling it off and on, or _Reload_, starts a fresh instance. The IDE itself is
never affected.
## 3. Themes
@@ -181,7 +181,7 @@ Tokens are the CSS variables of `src/styles/tokens.css` (`--bg-*`, `--fg-*`,
keep the values of the built-in base named by `kind`. Values must be plain CSS
values (no `url()`, `;`, braces); `//` and `/* */` comments are allowed. A
manifest theme entry may add `editor-scheme = "themes/x.scheme.json"` (editor
colours, merged over the theme). Pick a theme in Settings › Plugins › *Apply*.
colours, merged over the theme). Pick a theme in Settings › Plugins › _Apply_.
Start from [`templates/theme-plugin`](../templates/theme-plugin); the full guide,
token reference and IntelliJ / VS Code porting tables are in
@@ -196,14 +196,14 @@ token reference and IntelliJ / VS Code porting tables are in
## 5. Installing and developing
* **Install:** Settings › Plugins › *Install Plugin from Disk…* (or the action
*Install Plugin from Disk…*) and pick the package folder. The manifest and the
- **Install:** Settings › Plugins › _Install Plugin from Disk…_ (or the action
_Install Plugin from Disk…_) and pick the package folder. The manifest and the
files it references are copied to `<app-data>/plugins/<id>/`.
* **Dev plugins:** put (or symlink) the package in `<project>/.openidea/plugins/<name>/`.
It loads when the project is opened, is listed with a *dev* tag, and *Reload*
(or the *Reload Plugins* action) picks up a rebuilt `plugin.wasm` without
- **Dev plugins:** put (or symlink) the package in `<project>/.openidea/plugins/<name>/`.
It loads when the project is opened, is listed with a _dev_ tag, and _Reload_
(or the _Reload Plugins_ action) picks up a rebuilt `plugin.wasm` without
restarting the IDE.
* Commands appear in Search Everywhere › Actions under their category, and can
- Commands appear in Search Everywhere › Actions under their category, and can
be bound in Settings › Keymap like any other action.
## 6. Testing
Створено
+440 -1120
File diff suppressed because it is too large. Load diff
+51 -12
Переглянути файл
@@ -4,8 +4,13 @@
Until tokens load, the colours are the last theme's --bg-frame / --fg-muted that boot.js
restored as --boot-*, else these built-in ones; the bar keeps the last --accent throughout. */
/* Not on html: the canvas then takes body's (themed) background, which a fast resize shows before relayout. */
body, .splash { background: var(--bg-frame, var(--boot-frame, #e9eaee)); }
:root[data-theme="dark"] :is(body, .splash) { background: var(--bg-frame, var(--boot-frame, #26282c)); }
body,
.splash {
background: var(--bg-frame, var(--boot-frame, #e9eaee));
}
:root[data-theme="dark"] :is(body, .splash) {
background: var(--bg-frame, var(--boot-frame, #26282c));
}
:root:is([data-theme="dark-hc"], [data-theme="dark"][data-contrast="high"]) :is(body, .splash) {
background: var(--bg-frame, var(--boot-frame, #1a1b1e));
}
@@ -27,12 +32,29 @@ body, .splash { background: var(--bg-frame, var(--boot-frame, #e9eaee)); }
animation: splash-in 240ms ease-out 120ms both;
transition: opacity 160ms ease-out;
}
.splash.splash-out { opacity: 0; pointer-events: none; }
:root[data-theme^="dark"] .splash { color: var(--fg-muted, var(--boot-fg, #8c8f95)); }
.splash-logo { width: 56px; height: 56px; }
.splash.splash-out {
opacity: 0;
pointer-events: none;
}
:root[data-theme^="dark"] .splash {
color: var(--fg-muted, var(--boot-fg, #8c8f95));
}
.splash-logo {
width: 56px;
height: 56px;
}
/* 15px Inter: 2048 units per em, the line box from ascender to descender. */
.splash-wordmark { width: 73.2px; height: 18.15px; }
.splash-bar { width: 120px; height: 2px; border-radius: 1px; overflow: hidden; background: rgb(127 127 127 / 0.18); }
.splash-wordmark {
width: 73.2px;
height: 18.15px;
}
.splash-bar {
width: 120px;
height: 2px;
border-radius: 1px;
overflow: hidden;
background: rgb(127 127 127 / 0.18);
}
/* Fake progress: eases towards ~90% over the 4 s cap; hideSplash() fills it before fading out.
The remembered accent comes first: tokens.css brings the theme's default --accent before
settings restore a custom one, which would flash the default mid-load. */
@@ -44,11 +66,28 @@ body, .splash { background: var(--bg-frame, var(--boot-frame, #e9eaee)); }
animation: splash-fill 4s cubic-bezier(0.1, 0.7, 0.3, 1) both;
}
/* Settings window: a dialog, not a launch. Only the bar, and only if loading takes a while. */
:root[data-window="settings"] .splash { animation-delay: 400ms; }
:root[data-window="settings"] .splash > :not(.splash-bar) { display: none; }
@keyframes splash-in { from { opacity: 0; } }
@keyframes splash-fill { from { transform: scaleX(0.04); } to { transform: scaleX(0.92); } }
:root[data-window="settings"] .splash {
animation-delay: 400ms;
}
:root[data-window="settings"] .splash > :not(.splash-bar) {
display: none;
}
@keyframes splash-in {
from {
opacity: 0;
}
}
@keyframes splash-fill {
from {
transform: scaleX(0.04);
}
to {
transform: scaleX(0.92);
}
}
/* The fill stays: it grows in place, which reduced motion allows. */
@media (prefers-reduced-motion: reduce) {
.splash { animation: none; }
.splash {
animation: none;
}
}
+1 -1
Переглянути файл
@@ -23,7 +23,7 @@ export interface TokenGroup {
}
/** tokens.css sections that IntelliJ keeps in an editor scheme (`.icls`). */
export const SCHEME_GROUPS = ["syntax", "editor", "ANSI palette"];
export const SCHEME_GROUPS = ["syntax", "editor", "ANSI palette", "terminal ANSI palette"];
const LIGHT_SELECTOR = ':root[data-theme="light"]';
+1 -5
Переглянути файл
@@ -2,11 +2,7 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": [
"main",
"project-*",
"settings-*"
],
"windows": ["main", "project-*", "settings-*"],
"permissions": [
"core:default",
"core:window:allow-start-dragging",
+3 -9
Переглянути файл
@@ -2,12 +2,6 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "e2e-bridge",
"description": "Debug-only automation bridge",
"windows": [
"main",
"project-*",
"settings-*"
],
"permissions": [
"mcp-bridge:default"
]
}
"windows": ["main", "project-*", "settings-*"],
"permissions": ["mcp-bridge:default"]
}
+16 -4
Переглянути файл
@@ -46,10 +46,16 @@ pub async fn agent_commands(
agent::commands(&state.host, window.label(), provider, task).await
}
/// Entries of `task`'s conversation, or of its subagent `subagent`'s.
#[tauri::command]
#[specta::specta]
pub fn agent_entries(window: Window, state: State<'_, AppState>, task: String) -> IdeResult<Vec<AgentEntry>> {
agent::entries(&state.host, window.label(), task)
pub fn agent_entries(
window: Window,
state: State<'_, AppState>,
task: String,
subagent: Option<String>,
) -> IdeResult<Vec<AgentEntry>> {
agent::entries(&state.host, window.label(), task, subagent)
}
#[tauri::command]
@@ -108,10 +114,16 @@ pub async fn agent_set_config(
agent::set_config(&state.host, window.label(), task, option, value).await
}
/// Stops the task's current turn, or with `subagent` only that subagent's work.
#[tauri::command]
#[specta::specta]
pub fn agent_cancel(window: Window, state: State<'_, AppState>, task: String) -> IdeResult<()> {
agent::cancel(&state.host, window.label(), task)
pub fn agent_cancel(
window: Window,
state: State<'_, AppState>,
task: String,
subagent: Option<String>,
) -> IdeResult<()> {
agent::cancel(&state.host, window.label(), task, subagent)
}
/// Answers a permission request; `option: null` cancels it.
+17 -1
Переглянути файл
@@ -61,6 +61,22 @@ pub async fn open_project(window: Window, path: PathBuf) -> IdeResult<ProjectInf
Ok(info)
}
/// Edits the loose file `path` in this window without a project (LightEdit);
/// a window already in LightEdit keeps its files. Returns the effective (global) settings.
#[tauri::command]
#[specta::specta]
pub async fn light_edit_open(window: Window, path: PathBuf) -> IdeResult<Settings> {
let app = window.app_handle().clone();
let label = window.label().to_owned();
if app.state::<AppState>().project(&label).is_ok_and(|p| !p.light) {
crate::windows::close_settings_window(&app, &label);
}
let project = tauri::async_runtime::spawn_blocking(move || app.state::<AppState>().open_light(&label, &path))
.await
.map_err(|e| IdeError::internal(e.to_string()))??;
Ok(project.settings.effective())
}
fn project_info(project: &crate::state::Project) -> ProjectInfo {
ide_host::ops::project::info(project)
}
@@ -200,7 +216,7 @@ pub fn project_roots(window: Window, state: State<'_, AppState>) -> IdeResult<id
#[tauri::command]
#[specta::specta]
pub fn project_current(window: Window, state: State<'_, AppState>) -> Option<ProjectInfo> {
state.project(window.label()).ok().map(|p| project_info(&p))
state.project(window.label()).ok().filter(|p| !p.light).map(|p| project_info(&p))
}
#[tauri::command]
+2
Переглянути файл
@@ -59,6 +59,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
app::recent_projects,
app::remove_recent_project,
app::open_project,
app::light_edit_open,
app::project_current,
app::close_project,
app::languages,
@@ -296,6 +297,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
sdk::sdk_python_packages,
sdk::sdk_python_pip,
window::window_open_project,
window::window_open_files,
window::window_open_remote,
window::window_new,
window::window_open_settings,
+6 -2
Переглянути файл
@@ -11,8 +11,12 @@ use tauri::{State, Window};
/// Detected configs followed by user-defined ones (user ids win on conflict).
#[tauri::command]
#[specta::specta]
pub fn run_configs(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<RunConfig>> {
ide_host::ops::run::configs(&state.host, window.label())
pub async fn run_configs(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<RunConfig>> {
// Detection reads build files (and Spring Boot sources): off the command thread.
let (host, label) = (state.host.clone(), window.label().to_owned());
tauri::async_runtime::spawn_blocking(move || ide_host::ops::run::configs(&host, &label))
.await
.map_err(|e| ide_core::IdeError::internal(e.to_string()))?
}
#[tauri::command]
+23 -3
Переглянути файл
@@ -11,10 +11,30 @@ use tauri::{AppHandle, Manager, State, WebviewWindow};
/// Opens `path` in a new window (`new_window`) or tells the caller to open it
/// itself (`current`). A project already open in some window is focused instead.
/// `files` then open in that project's editor.
#[tauri::command]
#[specta::specta]
pub async fn window_open_project(app: AppHandle, path: PathBuf, new_window: bool) -> IdeResult<OpenOutcome> {
windows::open_project_window(&app, &path, new_window)
pub async fn window_open_project(
app: AppHandle,
path: PathBuf,
new_window: bool,
files: Vec<PathBuf>,
) -> IdeResult<OpenOutcome> {
windows::open_project_window(&app, &path, new_window, files)
}
/// Loose `files` opened from a window without a local project: a file inside a local project
/// open in some window goes to that window, the others to the LightEdit window (this one,
/// another, or a new one from a remote project window). Returns the files this window opens
/// itself, in LightEdit.
#[tauri::command]
#[specta::specta]
pub async fn window_open_files(
app: AppHandle,
window: WebviewWindow,
files: Vec<PathBuf>,
) -> IdeResult<Vec<ide_core::IpcPath>> {
Ok(windows::open_files_window(&app, window.label(), files))
}
/// [`window_open_project`] for folder `path` on the host of SSH configuration
@@ -94,7 +114,7 @@ pub fn window_open_projects(
Ok(windows::project_window_labels(&app)
.into_iter()
.filter_map(|label| {
let project = state.project(&label).ok()?;
let project = state.project(&label).ok().filter(|p| !p.light)?;
Some(OpenProject {
name: project.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
root: project.root.clone(),
+22 -2
Переглянути файл
@@ -13,7 +13,10 @@ mod state;
mod theme_frame;
mod windows;
use parking_lot::Mutex;
use state::AppState;
use std::path::PathBuf;
use std::sync::Arc;
use tauri::{Emitter, Manager};
use windows::WindowsState;
@@ -74,6 +77,9 @@ pub fn run() {
#[cfg(debug_assertions)]
let app = app.plugin(tauri_plugin_mcp_bridge::Builder::new().bind_address("127.0.0.1").build());
// Paths macOS asked to open (Finder's Open With, the Dock) before setup ran: the first window takes them.
let early_opens: Arc<Mutex<Option<Vec<PathBuf>>>> = Arc::default();
let setup_opens = early_opens.clone();
app.invoke_handler(builder.invoke_handler())
.setup(move |app| {
builder.mount_events(app);
@@ -82,13 +88,16 @@ pub fn run() {
if let Ok(cwd) = std::env::current_dir()
&& let Some(path) = windows::cli_path(&std::env::args().collect::<Vec<_>>(), &cwd)
{
windows.set_launch("main", windows::Launch { project: Some(path.into()), ..Default::default() });
windows.set_launch("main", windows::path_launch(path));
}
let menu_state = menu::MenuState::default();
menu::install(app.handle(), &menu_state, &state.recent.list());
app.manage(state);
app.manage(windows);
app.manage(menu_state);
if let Some(paths) = setup_opens.lock().take() {
windows::open_paths_at_launch(app.handle(), paths);
}
app.on_menu_event(on_menu_event);
windows::create_main_window(app.handle())?;
Ok(())
@@ -115,7 +124,18 @@ pub fn run() {
})
.build(context)
.expect("error while running OpenIDEA")
.run(|app, event| {
.run(move |app, event| {
#[cfg(target_os = "macos")]
if let tauri::RunEvent::Opened { urls } = &event {
let paths = windows::opened_paths(urls);
if app.try_state::<WindowsState>().is_some() {
windows::open_paths(app, paths);
} else {
early_opens.lock().get_or_insert_default().extend(paths);
}
}
#[cfg(not(target_os = "macos"))]
let _ = &early_opens;
// Quit after installing an update (`app_install_update`): relaunch.
if let tauri::RunEvent::Exit = event
&& app.try_state::<WindowsState>().is_some_and(|w| w.restart_requested())
+54
Переглянути файл
@@ -2,9 +2,13 @@
//! (`~/Library/Logs/<identifier>` on macOS, `<local data>/<identifier>/logs`
//! elsewhere — the same place as Tauri's `app_log_dir`).
use std::fmt::Write as _;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::fmt::format::Writer;
use tracing_subscriber::fmt::time::{FormatTime, SystemTime};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{EnvFilter, Layer};
@@ -40,12 +44,41 @@ pub fn init(identifier: &str) {
.ok()?;
let (writer, guard) = tracing_appender::non_blocking(appender);
let _ = GUARD.set(guard);
log_panics(dir.clone());
let _ = LOG_DIR.set(dir);
Some(tracing_subscriber::fmt::layer().with_ansi(false).with_writer(writer).with_filter(filter()))
});
let _ = tracing_subscriber::registry().with(stdout).with(file).try_init();
}
/// Panics go to the log file synchronously: the non-blocking writer may not
/// get to them before a panic that aborts ends the process.
fn log_panics(dir: PathBuf) {
let default = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let _ = append(&dir, &panic_record(info));
default(info);
}));
}
fn panic_record(info: &std::panic::PanicHookInfo) -> String {
let mut record = String::new();
let _ = SystemTime.format_time(&mut Writer::new(&mut record));
let thread = std::thread::current();
let _ = write!(
record,
" ERROR panic: thread '{}' {info}\n{}\n",
thread.name().unwrap_or("<unnamed>"),
std::backtrace::Backtrace::force_capture()
);
record
}
fn append(dir: &Path, record: &str) -> std::io::Result<()> {
let path = latest_log(dir).unwrap_or_else(|| dir.join(format!("{PREFIX}.panic.{SUFFIX}")));
std::fs::OpenOptions::new().create(true).append(true).open(path)?.write_all(record.as_bytes())
}
pub fn log_dir() -> Option<&'static Path> {
LOG_DIR.get().map(PathBuf::as_path)
}
@@ -76,6 +109,27 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn panic_record_names_thread_location_and_message() {
let dir = std::env::temp_dir().join(format!("openidea-panic-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("openidea.2026-01-01.log"), "earlier\n").unwrap();
let record = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
let sink = record.clone();
let default = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| *sink.lock().unwrap() = panic_record(info)));
let _ = std::thread::Builder::new().name("worker".into()).spawn(|| panic!("boom")).unwrap().join();
std::panic::set_hook(default);
let record = record.lock().unwrap().clone();
let location = format!("ERROR panic: thread 'worker' panicked at {}:", file!());
assert!(record.contains(&location), "{record}");
assert!(record.contains("boom"), "{record}");
append(&dir, &record).unwrap();
let log = std::fs::read_to_string(dir.join("openidea.2026-01-01.log")).unwrap();
assert!(log.starts_with("earlier\n") && log.ends_with(&record));
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn log_dir_is_per_identifier() {
let d = log_dir_for("com.example.x").unwrap();
+162 -17
Переглянути файл
@@ -207,6 +207,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("file.new", "New…"),
act("file.newScratchFile", "New Scratch File…"),
act("file.openProject", "Open…"),
act("file.openFile", "Open File…"),
act("file.openInNewWindow", "Open in New Window…"),
sub(
"openRecent",
@@ -408,8 +409,10 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("navigate.gotoTest", "Test"),
SEP,
act("navigate.fileStructure", "File Structure"),
act("navigate.showFilePath", "File Path"),
act("navigate.callHierarchy", "Call Hierarchy"),
act("navigate.typeHierarchy", "Type Hierarchy"),
act("navigate.customRegion", "Custom Folding…"),
SEP,
act("navigate.nextMethod", "Next Method"),
act("navigate.previousMethod", "Previous Method"),
@@ -438,6 +441,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("code.parameterInfo", "Parameter Info"),
act("code.quickDocumentation", "Quick Documentation"),
act("code.expressionTypeInfo", "Expression Type Info"),
act("code.showErrorDescription", "Error Description"),
act("editor.contextInfo", "Context Info"),
act("code.showIntentions", "Show Context Actions"),
act("code.generate", "Generate…"),
act("code.overrideMethods", "Override Methods…"),
@@ -445,9 +450,11 @@ pub fn spec(os: Os) -> Vec<Entry> {
SEP,
act("code.insertLiveTemplate", "Insert Live Template…"),
act("code.surroundWith", "Surround With…"),
act("code.surroundWithLiveTemplate", "Surround with Live Template…"),
act("code.unwrap", "Unwrap/Remove…"),
SEP,
act("code.reformat", "Reformat Code"),
act("code.autoIndentLines", "Auto-Indent Lines"),
act("code.optimizeImports", "Optimize Imports"),
act("code.cleanup", "Code Cleanup…"),
SEP,
@@ -458,6 +465,10 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("code.shrinkSelection", "Shrink Selection"),
act("code.duplicateLine", "Duplicate Line or Selection"),
act("code.deleteLine", "Delete Line"),
act("code.moveStatementUp", "Move Statement Up"),
act("code.moveStatementDown", "Move Statement Down"),
act("code.moveElementLeft", "Move Element Left"),
act("code.moveElementRight", "Move Element Right"),
act("code.moveLineUp", "Move Line Up"),
act("code.moveLineDown", "Move Line Down"),
SEP,
@@ -468,13 +479,43 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("code.foldToggle", "Expand/Collapse"),
act("code.foldAll", "Collapse All"),
act("code.unfoldAll", "Expand All"),
sub(
"expandToLevel",
"Expand to Level",
vec![
act("code.expandToLevel1", "1"),
act("code.expandToLevel2", "2"),
act("code.expandToLevel3", "3"),
act("code.expandToLevel4", "4"),
act("code.expandToLevel5", "5"),
],
),
sub(
"expandAllToLevel",
"Expand All to Level",
vec![
act("code.expandAllToLevel1", "1"),
act("code.expandAllToLevel2", "2"),
act("code.expandAllToLevel3", "3"),
act("code.expandAllToLevel4", "4"),
act("code.expandAllToLevel5", "5"),
],
),
SEP,
act("code.collapseBlock", "Fold Code Block"),
act("code.foldSelection", "Fold Selection / Remove Region"),
],
),
SEP,
act("analyze.inspectCode", "Inspect Code…"),
sub("analyzeCode", "Analyze Code", vec![act("analyze.locateDuplicates", "Locate Duplicates…")]),
sub(
"analyzeCode",
"Analyze Code",
vec![
act("analyze.inspectFile", "Inspect Current File"),
act("analyze.locateDuplicates", "Locate Duplicates…"),
],
),
act("analyze.stackTrace", "Analyze Stack Trace or Thread Dump…"),
],
));
@@ -496,6 +537,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("refactor.inline", "Inline…"),
SEP,
act("refactor.move", "Move…"),
act("project.copyElement", "Copy…"),
act("refactor.safeDelete", "Safe Delete…"),
],
));
@@ -525,6 +567,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("run.stop", "Stop"),
SEP,
act("run.chooseConfig", "Run…"),
act("run.chooseDebugConfig", "Debug…"),
act("runAnything.show", "Run Anything…"),
act("run.editConfigs", "Edit Configurations…"),
act("debug.attachToProcess", "Attach to Process…"),
@@ -542,6 +585,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("debug.showExecutionPoint", "Show Execution Point"),
act("debug.resetFrame", "Reset Frame"),
act("debug.evaluate", "Evaluate Expression…"),
act("debug.quickEvaluate", "Quick Evaluate Expression"),
sub(
"debuggingActions",
"Debugging Actions",
@@ -568,8 +612,14 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("vcs.pull", "Pull…"),
act("vcs.fetch", "Fetch"),
SEP,
// Operation items (Abort Merge, Continue Rebase…) are enabled only while it is in progress.
act("vcs.merge", "Merge…"),
act("vcs.merge.abort", "Abort Merge"),
act("vcs.rebase", "Rebase…"),
act("vcs.rebase.abort", "Abort Rebase"),
act("vcs.rebase.continue", "Continue Rebase"),
act("vcs.rebase.skip", "Skip Commit"),
act("vcs.resolveConflicts", "Resolve Conflicts…"),
SEP,
act("vcs.branches", "Branches…"),
act("vcs.newBranch", "New Branch…"),
@@ -579,17 +629,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("vcs.newWorktree", "New Worktree…"),
act("vcs.worktrees", "Worktrees…"),
SEP,
act("vcs.showDiff", "Show Diff"),
act("vcs.rollback", "Rollback…"),
act("vcs.annotate", "Annotate with Git Blame"),
act("vcs.showLog", "Show Git Log"),
act("vcs.localHistory", "Local History"),
act("localHistory.putLabel", "Put Label…"),
SEP,
act("vcs.stash", "Stash Changes…"),
act("vcs.unstash", "Unstash Changes…"),
act("vcs.shelve", "Shelve Changes…"),
act("vcs.showShelf", "Show Shelf"),
sub(
"gitPatch",
"Patch",
@@ -599,12 +639,32 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("vcs.applyPatchFromClipboard", "Apply Patch from Clipboard…"),
],
),
SEP,
act("vcs.resolveConflicts", "Resolve Conflicts…"),
act("vcs.rebase.continue", "Continue Rebase"),
act("vcs.rebase.abort", "Abort Rebase"),
act("vcs.rebase.skip", "Skip Commit"),
act("vcs.merge.abort", "Abort Merge"),
sub(
"gitUncommittedChanges",
"Uncommitted Changes",
vec![
act("vcs.shelve", "Shelve Changes…"),
act("vcs.showShelf", "Show Shelf"),
act("vcs.stash", "Stash Changes…"),
act("vcs.unstash", "Unstash Changes…"),
act("vcs.rollback", "Rollback…"),
],
),
sub(
"gitCurrentFile",
"Current File",
vec![
act("vcs.addToVcs", "Add to VCS"),
SEP,
act("vcs.annotate", "Annotate with Git Blame"),
act("vcs.showDiff", "Show Diff"),
act("vcs.compareWithBranch", "Compare with Branch or Revision…"),
act("vcs.showHistory", "Show History"),
SEP,
act("vcs.localHistory", "Local History"),
act("localHistory.putLabel", "Put Label…"),
],
),
SEP,
sub(
"gitHub",
@@ -620,6 +680,11 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("vcs.clone", "Clone…"),
SEP,
act("vcs.operations", "VCS Operations Popup…"),
SEP,
act("vcs.revert.continue", "Continue Revert"),
act("vcs.revert.abort", "Abort Revert"),
act("vcs.cherryPick.continue", "Continue Cherry-Pick"),
act("vcs.cherryPick.abort", "Abort Cherry-Pick"),
],
));
@@ -684,6 +749,16 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("toolwindow.hideActive", "Hide Active Tool Window"),
act("toolwindow.maximize", "Maximize Tool Window"),
act("toolwindow.closeContent", "Close Active Tab"),
sub(
"resizeToolWindow",
"Resize",
vec![
act("toolwindow.resizeLeft", "Stretch to Left"),
act("toolwindow.resizeRight", "Stretch to Right"),
act("toolwindow.resizeUp", "Stretch to Top"),
act("toolwindow.resizeDown", "Stretch to Bottom"),
],
),
SEP,
act("toolwindow.jumpToLast", "Jump to Last Tool Window"),
act("toolwindow.focusEditor", "Focus Editor"),
@@ -706,6 +781,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("editor.splitDown", "Split Down"),
act("editor.unsplit", "Unsplit"),
act("editor.moveToOppositeGroup", "Move to Opposite Group"),
act("editor.nextSplitter", "Go to Next Splitter"),
act("editor.prevSplitter", "Go to Previous Splitter"),
],
),
SEP,
@@ -1213,6 +1290,7 @@ mod tests {
"app.about",
"app.quit",
"file.openProject",
"file.openFile",
"file.openInNewWindow",
"file.closeProject",
"file.save",
@@ -1404,6 +1482,10 @@ mod tests {
"toolwindow.closeContent",
"toolwindow.jumpToLast",
"toolwindow.focusEditor",
"toolwindow.resizeLeft",
"toolwindow.resizeRight",
"toolwindow.resizeUp",
"toolwindow.resizeDown",
]
.contains(id)
}));
@@ -1436,6 +1518,69 @@ mod tests {
assert!(item_enabled("submenu:refactor", &disabled));
}
#[test]
fn git_menu_follows_idea_order() {
let spec = spec(Os::Mac);
let Some(Entry::Submenu { children, .. }) = spec.iter().find(|e| matches!(e, Entry::Submenu { id: "git", .. }))
else {
panic!("Git menu missing");
};
let top: Vec<&str> = children
.iter()
.map(|e| match e {
Entry::Action { id, .. } | Entry::Submenu { id, .. } => *id,
Entry::Separator => "|",
_ => "?",
})
.collect();
assert_eq!(
top,
[
"vcs.commit",
"vcs.push",
"vcs.update",
"vcs.pull",
"vcs.fetch",
"|",
"vcs.merge",
"vcs.merge.abort",
"vcs.rebase",
"vcs.rebase.abort",
"vcs.rebase.continue",
"vcs.rebase.skip",
"vcs.resolveConflicts",
"|",
"vcs.branches",
"vcs.newBranch",
"vcs.newTag",
"vcs.resetHead",
"|",
"vcs.newWorktree",
"vcs.worktrees",
"|",
"vcs.showLog",
"gitPatch",
"gitUncommittedChanges",
"gitCurrentFile",
"|",
"gitHub",
"vcs.manageRemotes",
"vcs.clone",
"|",
"vcs.operations",
"|",
"vcs.revert.continue",
"vcs.revert.abort",
"vcs.cherryPick.continue",
"vcs.cherryPick.abort",
]
);
let ids = action_ids(children);
for moved in ["vcs.showDiff", "vcs.rollback", "vcs.annotate", "vcs.localHistory", "localHistory.putLabel"] {
assert!(ids.contains(&moved), "{moved} missing from the Git menu");
}
}
#[test]
fn idea_menu_items_are_present() {
for os in ALL_OS {
+6
Переглянути файл
@@ -138,6 +138,12 @@ impl AppState {
Ok(project)
}
/// Opens `window` for editing the loose file `file` (LightEdit); not a recent project.
pub fn open_light(&self, window: &str, file: &Path) -> IdeResult<Arc<Project>> {
self.remote_dev.disconnect(window);
self.host.open_light(window, file)
}
pub fn close_project(&self, window: &str) {
self.remote_dev.disconnect(window);
self.host.close_project(window);
Loaded 100 of 621 files, more files were not shown because too many files have changed in this diff. Show more