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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 31af591525 perf(index): space snapshot refreshes by how long the last one took
Any index write drops the startup snapshot, and it was written again at
most every 10 s, also inline after every subtree scan. In a project of
160 000 files a write takes up to 11 s and holds the disk, so a build
writing into the project kept it rewriting for minutes after startup.

The gap after a write is now 30 times what it took, between 10 s and
5 min; a subtree scan within the gap leaves the write to the scheduled
refresh. Full scans still write at once. The snapshot only speeds up the
next startup: one that is missing falls back to a scan.

Refs #7363
2026-12-02 13:41:06 +08:00
l0ng-ai de41651a5e fix(agents): ask AskUserQuestion forms one question at a time (#7396)
claude-agent-acp now sends AskUserQuestion as an ACP form (a choice field per question, each followed by a text field for a typed answer), and OMP's ask tool sends the same shape. They were shown as a plain form with every question stacked above the composer, at up to half the window, which in a short Agents panel left the conversation no room to scroll.

Such forms are now shown as the question card in the conversation, one question at a time with Previous/Next, option descriptions and previews; the answers are turned back into the form's values (picked options as the choice, typed text in its companion field; Skip declines). Other forms stay forms, and a long one waiting above the composer now leaves the conversation a share of the panel and scrolls within itself.

Fixes #7359
2026-12-02 13:36:43 +08:00
l0ng-ai 6bd2d5f843 fix(run): keep a log line with a stray NUL byte out of UTF-16 decoding (#7390)
On Windows the console decoder took any read containing a NUL byte for UTF-16LE output (wsl.exe, cmd /u). A Spring Boot app logging a payload that ends in a NUL turned the whole read into CJK-looking garbage. A read is now UTF-16LE only when NUL bytes are dense (one byte in eight or more, as every ASCII character in UTF-16 has one) or one follows a line feed (every UTF-16 line end has one).

Fixes #7362
2026-12-02 13:30:02 +08:00
l0ng-ai 93c15547ef fix(sdk): add a JDK from disk in Settings opened from the Welcome screen (#7389)
sdk_jdk_at was a trusted command, which needs an open trusted project, so Add JDK from Disk on the Welcome screen always failed and the error was shown as 'not a valid home for JDK'. SDKs are IDE-wide: sdk_jdk_at, sdk_flutter_at, sdk_locate_tools and sdk_php_xdebug now run outside Restricted Mode like sdk_detect (a restricted project still refuses them). A failed check now shows its error instead of calling the folder invalid.

Fixes #7361
2026-12-02 13:28:49 +08:00
Ivan 90d98f3edd feat(editor): gutter icons between Rust traits and their impls (#7253)
Rust files get RustRover's line markers between traits and implementations: an impl block and its methods get ↑ to the trait (or the trait's method, required vs default from the trait file's outline), a trait and its methods get ↓ to their implementations. The trait and the self type come from the tree-sitter impl header (outline items carry implements / self_type ranges, merged into rust-analyzer's outline), so multi-line generic headers, where clauses and const generic arguments label correctly. Lookups are asked only near the viewport, per-kind provider availability is cached, and every request of a pass is guarded by the document and pass generation, so an edit cancels a running pass and stale markers are refreshed.

Covered by lineMarkers.test.ts, ide-language syntax tests and the ide-lsp mock server.

Co-authored-by: Pecnikas <[email protected]>
2026-12-02 13:17:39 +08:00
Kamal ElFadlтаelfadl b7ef68df71 feat(debugger): make the expanded value tree popup resizable (#7374)
Expanding an object in the debugger's editor value tooltip fixed the tree at 460x260 px inside the hint's 480 px cap, truncating nested fields and package paths. The expanded tree now resizes from all eight edges and corners up to the viewport (minimum 280x120 px) and remembers its size (openidea.debugger.valueTreeSize.v1). hint.ts forwards resize/positioned from built hint content to CodeMirror's TooltipView so the tooltip keeps the dragged size and position.

Covered by valueHint.test.ts.

Co-authored-by: elfadl <[email protected]>
2026-12-02 13:08:52 +08:00
Kamal ElFadlтаelfadl fdc4df4752 feat(search): make Search Everywhere resizable from all edges and corners (#7373)
Search Everywhere opened at a fixed 700 px width with its height capped at 600 px, clipping long paths, containers and previews on wide monitors. Dialog's resizable="both" now resizes from all eight edges and corners (the opposite edge stays put), not only the bottom-right grip, and Search Everywhere uses it with a remembered size (openidea.search.everywhereSize.v1, clamped to its minimum). The other resizable dialogs get the edge handles too.

Covered by Dialog and Search Everywhere tests.

Co-authored-by: elfadl <[email protected]>
2026-12-02 13:04:52 +08:00
l0ng-ai 54ce048ec9 fix(vim): let af / if work on the right-hand side of a noremap (#7382)
A noremap runs its keys against codemirror-vim's built-in keymap only, and the function text objects were added after every mapclear as user mappings, so nnoremap X daf deleted nothing (same cause as <C-g>u in #7364). af / if are now part of the built-in keymap through the existing vim-core patch, with a placeholder motion the host overrides, and are no longer re-mapped after mapclear.
2026-12-02 12:58:43 +08:00
l0ng-ai a372385788 feat(vim): apply number and relativenumber from the rc file to the line numbers (#7381)
set relativenumber in ~/.ideavimrc was reported as an unsupported option and the gutter kept absolute numbers. As in IdeaVim, number (nu) and relativenumber (rnu) now set every editor's line numbers over Settings › Editor › General › Appearance › Show line numbers: both on is hybrid, relativenumber alone shows 0 on the caret line, both off hides them. An option the rc file leaves alone reads and follows Settings, nothing is written back, and turning Vim mode off or reloading an rc file without them returns to Settings. The options live in an editor-core store that lineNumbersExtension reads; the controller re-applies settings when it changes, as for Distraction Free Mode.

Fixes #7341
2026-12-02 12:53:37 +08:00
nako-ruruтаnako-ruru 7ff8d472f7 feat(chooser): mark interface targets in the implementation chooser (#7328)
Go to Implementation can list an interface declaration among the implementations (gopls answers both ways), and every row carried the same file icon. A target that is an interface or trait, or a method declared in one, now shows the editor's interface badge in place of the file icon, as GoLand does. LSP implementation answers carry no symbol kind, so the target file's outline supplies it; with targets in more than eight files the chooser opens with the kinds the index already knows instead of opening every file in the language server.

Covered by navigationInterfaceMark.test.ts.

Co-authored-by: nako-ruru <[email protected]>
2026-12-02 12:48:35 +08:00
GuoYuтаguoyucode 4de01a91c5 fix(mcp): list_directory_tree's maxDepth counts the levels below the directory (#7375)
list_directory_tree with maxDepth 1 listed nothing: the directory's own line took the first level, so 1 returned only that line with total 0, and the default 5 listed four levels. maxDepth now counts the levels below the directory (0: the directory alone, 1: its entries, …) and the parameter description says so. Paging, markers and the output format are unchanged.

Covered by max_depth_counts_the_levels_below_the_directory.

Co-authored-by: guoyucode <[email protected]>
2026-12-02 12:45:26 +08:00
LU XIANGRUIтаwildcatDownstairs 657d49e30a fix(debug): bind Xcode breakpoints for projects under /private/tmp (#7368)
Debugging an Xcode app whose project lives under /private/tmp never stopped at a breakpoint: the IDE sends breakpoints on the canonical /private/tmp/… path, while Xcode writes the files into the debug info as /tmp/…. The simulator attach now passes lldb-dap a sourceMap (/tmp, /var, /etc → /private/…). The map is Xcode-only: clang, swift build and cargo record /private/tmp/…, and LLDB uses only the first matching entry.

lldb-dap and CodeLLDB give no reason for a breakpoint they cannot bind; such breakpoints now carry one (code not loaded yet, or debug info under another path), shown translated on hover in the gutter and in the Breakpoints dialog, and dropped once the breakpoint binds.

Fixes #7367

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 12:40:05 +08:00
LU XIANGRUIтаwildcatDownstairs 2a7975a077 fix(xcode): select the root scheme and the backend's default simulator in Xcode projects (#7366)
An Xcode project with an npm package in a subfolder opened with that package's dev script selected, and the simulator chooser showed an iPad when nothing was booted.

- defaultSelection scored a root Xcode scheme the same as any run/dev script, so list order decided. A root scheme (kind xcode, no cwd) now scores like a Spring Boot application; schemes in subfolders and other project types keep their order, and a saved selection still wins.
- currentIosSimulator fell back to the first listed simulator, while the backend's pick_simulator takes a booted simulator, then the newest iPhone. The toolbar now applies the same rule, and pick_simulator ranks over simulator::parse_list so both sides agree on ties.

Fixes #7354

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 12:35:54 +08:00
tongkangwangтаchiyanking 71d88d0b55 fix(code-insight): allow dragging the Show Usages popup by its title bar (#7370)
The Show Usages popup could be resized but not moved: its header had no move handler, so it could not be dragged off the code it covers. Popup gains an opt-in `draggable` mode that moves it by descendants marked `data-popup-drag` (the same pattern Dialog uses with `data-dialog-drag`), skipping interactive controls; once moved the popup is positioned at its new place without flipping back to the anchor and stays 6 px inside the viewport. Show Usages marks its header as the drag handle.

Covered by e2e/usagesPopupLayout.spec.ts.

Co-authored-by: chiyanking <[email protected]>
2026-12-02 12:32:30 +08:00
angelf015таangelf015 c6faf280db fix(vim): support <C-g>u undo breaks in Insert mode (#7364)
An Insert-mode mapping such as `inoremap . .<C-g>u` typed the literal text ".<C-g>u": codemirror-vim has no <C-g>u command and writes unknown <...> keys of a mapping's right-hand side into the document. inoremap only searches the engine's built-in keymap, so the key is added there through a patch to @replit/codemirror-vim-core, bound to an action that isolates the next history event so the text after it starts a new undo group.

Covered by a Vim engine unit test and e2e/vimUndoBreak.spec.ts.

Co-authored-by: angelf015 <[email protected]>
2026-12-02 12:29:12 +08:00
王斌 fba7705acf feat(docker): run containers detached and open their log in Services (#7345)
Dockerfile and Docker Image runs start the container detached by default. The Run console keeps the build output; once the command line returns, a new exited hook on the run type reveals the container in the Services tool window with its Log tab (or a log editor tab for the CLI's default daemon). Closing the Run window or the IDE leaves the container running; an attached run still stops it with docker stop.

Co-authored-by: kitter960324 <[email protected]>
2026-12-02 11:48:52 +08:00
Alexanderтаstalexxx f87fb35be5 fix(libraries): don't list in-project Cargo path dependencies as External Libraries (#7316)
cargo metadata in a sub-crate's own workspace reported the project root (a path dependency such as vpn-core = { path = ".." }) as an external package, so the whole project became a read-only library root. Cargo library roots now drop path dependencies inside the open project, reusing is_project_source as Go modules do, so vendor copies stay libraries.

Co-authored-by: stalexxx <[email protected]>
2026-12-02 11:46:56 +08:00
Mansur Akhmadiтаmansur-akhmadi f4236a0ea1 feat(problems): Expand All / Collapse All in the Problems tool window toolbar (#7325)
The Problems toolbar gets Expand All and Collapse All; they touch only the files the current tab shows.

Closes #7324

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 11:20:51 +08:00
LU XIANGRUIтаwildcatDownstairs 1eece0ae51 fix(editor): scale gutter icons with the editor font zoom (#7352)
Gutter icons kept a fixed 14px while the editor font zoomed. They now follow the font size through --openidea-gutter-icon-size (14px at the default size, within 10-32px), applied to the icon area, the http/GraphQL/database run gutters and the feature icon wrappers.

Closes #7332

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 11:20:42 +08:00
LU XIANGRUIтаwildcatDownstairs 7361707b63 fix(astro): keep tag expressions with quoted strings as one attribute (#7331)
Quoted strings inside an Astro tag expression split the expression into several attributes. The tokenizer now skips string literals inside braces.

Closes #7330

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 11:20:30 +08:00
audichuang 8e56d3b73e fix(lsp): keep a newer Parameter Info reply when an older one arrives late (#7322)
fetchSignature applied every reply as it arrived, so a late reply for a call the caret had left replaced the newer signature. A reply is now skipped while a newer request's tooltip is still shown for the current document and caret.

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:20:22 +08:00
audichuang e5453a8a97 fix(search): keep pinned Find results when the tab limit drops one (#7323)
Over the tab limit the Find tool window always dropped the first tab, even when pinned. With a pinned first tab it now drops the earliest unpinned search instead (the selected one only when it is the last unpinned).

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:20:13 +08:00
audichuang 27689f09d3 fix(project): close the window on File → Close Project when another project is open (#7320)
File → Close Project always switched the window to Welcome. Like the native close button, it now closes the emptied window when another project window is open, and shows Welcome only for the last one.

Closes #7312

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:20:06 +08:00
audichuang 9b468b0873 fix(vcs): keep the Git Log commit list a single Tab stop (#7321)
Every actionable graph edge and node had tabIndex 0, so Tab from the Commits list stopped on each graph segment of every row. They now use tabIndex -1 and stay clickable; the keyboard route is Collapse/Expand Linear Branches.

Closes #7311

Co-authored-by: audichuang <[email protected]>
2026-12-02 11:19:58 +08:00
audichuang cb887dad80 fix(search): report Replace All files left unsaved by a disk conflict (#7309)
Replace in Files saves clean open tabs through Documents::autosave, which keeps an external change and returns false when the file changed on disk first. That result was dropped, so the notification claimed every file was written. ReplaceHost::edit_file now also returns whether the edits were left unsaved, ReplaceSummary gains an unsaved count, and the summary reports it as a warning.

Closes #7273

Co-authored-by: audichuang <[email protected]>
2026-12-02 10:35:56 +08:00
audichuang 3cfbf80e26 fix(todo): drop the previous project's scan results after switching projects (#7318)
A scan of the old project still running after a project switch kept writing its files into the new project's TODO index. On a project change the index now bumps the scan counters (plus a new projectGen for file rescans), drops refreshes queued for the old project and resets the spinners.

Co-authored-by: audichuang <[email protected]>
2026-12-02 10:35:47 +08:00
audichuang 97add1f448 fix(coverage): show whole percentages like 29/100 as 29%, not 28% (#7317)
percent() divided before multiplying, so (29 / 100) * 100 was 28.999999999999996 and the whole-percent floor showed 28%. It now multiplies first, which is exact for integer counts.

Co-authored-by: audichuang <[email protected]>
2026-12-02 10:35:37 +08:00
Deng Liuтаdengliu 35a6bec1c2 feat(agents): implement unified Agent Plugins Hub across harnesses (#6877)
Adds a Plugins page under Settings > Agents for the plugin bundles each agent harness installs natively (Claude Code, GitHub Copilot, Codex, Gemini CLI).

- Rows are grouped by harness and scope with counts and paths. Toggles change only the harness's own enablement record, and row ids are stable and owner-qualified, so a toggle never reaches another project's row.
- Enabled plugins project their skills, MCP servers and memory files into Skills, MCP Connections and Memory; a workspace override decides what a globally enabled plugin projects in that workspace.
- Marketplaces can be browsed, previewed and installed from, with pinned git installs. Installs are written into each harness's native store without following symlinks, including at the store root.
- Plugins that run local MCP processes or lifecycle hooks need capability consent. Previews and installed folders resolve capabilities the same way, and consent is tied to the capability hash the user was shown: an install or enable whose capabilities differ is refused.

Closes #6872

Co-authored-by: dengliu <[email protected]>
2026-12-02 09:32:33 +08:00
Deng Liuтаdengliu f8ba067e1d feat(agents): add host-owned local and remote agent automations (#7084)
Adds agent automations owned by the host rather than a window: scheduled, one-shot and manual automations, in-session /loop and Send Later, and .automation.md import/export.

- Schedules run while OpenIDEA or openidea-server --daemon is running. An optional login service (LaunchAgent, systemd --user unit or Windows Startup entry), off by default, keeps them running when OpenIDEA is closed; a schedule that came due while nothing was running follows the missed-run policy.
- Every automated turn is capped at the interactive approval setting. A run fails and its schedule pauses unless the provider confirms the required ceiling, including for turns that waited in the queue.
- Scheduled turns re-check project and repository trust at dispatch; Restricted Mode pauses them.
- Worktree runs use new agent/* branches, keep the working directory confined to the worktree, and cleanup never deletes branches. Imported .automation.md files only create disabled copies.
- Automation state is shared across processes with one lock order, and in-memory claims roll back when persisting fails. Windows and peers can only act on tasks of projects they own.

Closes #6942

Co-authored-by: dengliu <[email protected]>
2026-12-02 09:19:54 +08:00
Deng Liuтаdengliu 85cbc6bacd feat(mdx): add side-by-side MDX preview with opt-in sandboxed JSX execution (#6881)
Adds Editor Only / Editor and Preview / Preview Only layouts for .mdx files.

- Safe Static Mode on open: frontmatter, GFM, math, Mermaid, MDX comments and documentation tags (Steps, CardGroup, Note, Tabs, Accordion) render through the sanitized Markdown pipeline with scroll sync and no script execution.
- Run JSX (or Trust Project in Restricted Mode) lazy-loads @mdx-js/mdx and sucrase and evaluates JSX, workspace/tsconfig/node_modules imports, .mdx transclusions, stylesheets, assets and custom layouts inside an opaque-origin sandboxed iframe with its own CSP, no network and no IPC.
- The host-guest bridge is a per-document MessagePort; image, media, module and link resolution stay inside the window's project roots, checked lexically and after canonicalization (new fs_canonicalize command, which rejects parent traversal).
- Execution requires a current, affirmative trust result for the file's owning project, including attached workspace members, whose trust changes now emit ProjectTrustChanged.
- External links open only from a real click on an anchor in the frame and always go through a confirmation dialog showing the parsed destination.
- Settings > Languages & Frameworks > Markdown adds MDX component execution (Ask before running / Run automatically in trusted projects / Disabled), a user-only setting that project settings cannot enable.

Closes #6876

Co-authored-by: dengliu <[email protected]>
2026-12-02 08:39:22 +08:00
l0ng-ai 3f490684d6 feat(run): expanded editor for program arguments in every run configuration (#7319)
Program, script and application argument fields of the other run configuration types use the arguments control added for Python: a one-line field with an editor showing one argument per line. A test keeps argument fields on that control.
2026-12-02 07:32:31 +08:00
Isaac Gallartтаigallart 8f6200c3fa feat(run): add an expanded editor for Python arguments (#7307)
The Python run configuration's Arguments field becomes a one-line field with an expand button that opens the editor with one argument per line. Accepting joins them into one command line with single spaces, keeping quotes and escapes (new splitArgsText in platform/commandLine).

Closes #7306

Co-authored-by: igallart <[email protected]>
2026-12-02 07:27:18 +08:00
Mansur Akhmadiтаmansur-akhmadi 0aa64c2c6e feat(todo): Expand All / Collapse All in the TODO tool window toolbar (#7314)
The TODO toolbar gets Expand All and Collapse All for the file groups, on the scope tabs and on commit TODO review tabs. A review tab's collapsed groups move from component state to its tab entry in useTodoView, so the toolbar and the tree share them; the scope tabs touch only the groups shown.

Closes #7313

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 07:27:10 +08:00
KaKi87таKaKi87 8d4e016cb0 fix(terminal): keep bash integration working with a trailing ";" in PROMPT_COMMAND and with ble.sh (#7310)
The bash integration appended ";__openidea_prompt_end" to PROMPT_COMMAND, so a user value ending in "; " became "; ;", a syntax error at every prompt that also lost the prompt-end mark. Trailing semicolons and spaces are now stripped first.

ble.sh decodes CSI sequences itself, so the readline bind of the line-clearing key never fired and vi_nmap warned about kill-whole-line. With ble.sh the sequence is mapped to F20 and bound in its emacs, vi_imap and vi_nmap keymaps.

Co-authored-by: KaKi87 <[email protected]>
2026-12-02 07:04:59 +08:00
l0ng-ai a1ef8ca749 fix(projects): keep remote open-project actions on one row (#7133)
The Open Project prompt was sized for its four actions only for the local Attach variant, so the remote variant wrapped its buttons. It is now sized for all four actions when New Tab is available, keeping responsive wrapping in narrow windows and the existing button order and default.
2026-12-02 05:33:43 +08:00
tongkangwangтаchiyanking 669462c4de fix(debugger): keep selected tab when stopping a root debug session (#7223)
When the active debug session terminated, the debugger selected the first live session in tab order, so with several independent root sessions (e.g. several Spring Boot apps) stopping one jumped to the leftmost tab and the console switched with it. A stopped root session now keeps its tab selected as finished; a finished child still hands selection back to its live parent.

Co-authored-by: chiyanking <[email protected]>
2026-12-02 05:33:31 +08:00
l0ng-ai 90eb6bac1b fix(run): save a before launch task's project directory (#7305)
Run Maven Goal / Run Gradle Task before launch steps (#7294) keep their project in projectDir, but the run configuration file never wrote it, so after a reload the step had no project and could not run (and ide-run's config round-trip test failed on main). The file now writes project-dir and reads it back.
2026-12-02 05:30:21 +08:00
l0ng-ai 674e925c9a fix(vcs): show only the branch on the toolbar branch widget (#7304)
With several repositories on different branches, the toolbar branch widget put the current repository's name before the branch, capped at 120px and ellipsized, so repositories sharing a name prefix looked the same. The button now shows only the branch and the tooltip names the repository.

Refs #7288
2026-12-02 05:23:42 +08:00
Mansur Akhmadiтаmansur-akhmadi ddd27a6e50 feat(debugger): Compare Value with Clipboard in the Variables view's context menu (#7296)
Adds Compare Value with Clipboard to the Variables view's context menu: it reads the clipboard on the click, gets the variable's full value the way Copy Value does, and opens a diff with the clipboard on the left and the value on the right.

Closes #7295

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 05:18:52 +08:00
Mansur Akhmadiтаmansur-akhmadi d4791ea0c2 feat(editor): Reopen Closed Tab in the editor tab context menu (#7298)
Adds Reopen Closed Tab to the editor tab context menu, in its own group after Configure Editor Tabs…; it is disabled when there is no closed tab to reopen.

Closes #7297

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 05:18:44 +08:00
l0ng-ai baea2733f8 test(editor): give the layout test's controller mock ensureSlot (#7303)
The Markdown preview now asks the editor controller for the tab's document slot (#7299); the layout actions test mocked the controller without ensureSlot, so 7 tests failed on main.
2026-12-02 05:17:38 +08:00
faysouтаfaysou 0d2401705e fix(preview): render Markdown and reStructuredText through symlinks (#7299)
When a file was opened under a second name (a symlink), the editor shared one document across both paths, but the preview waited for live text under the second tab's path and never rendered. The Markdown and reStructuredText previews now read the shared document's path from the editor slot and keep the tab's own path for relative links and images.

Co-authored-by: faysou <[email protected]>
2026-12-02 05:10:15 +08:00
l0ng-ai 6c96b79538 feat(agents): open the file a tool title names with a click (#7301)
A tool entry whose title already names its file ("Read src/index.ts") suppressed the separate file link, so the file could not be opened from the row. The file word in the title is now itself a link that opens the file in the editor; files the title doesn't name keep their links next to it.

Fixes #7285
2026-12-02 05:08:04 +08:00
Ivan 878e86e10c perf(vcs): read only the clicked file's change for the annotate gutter's Show Diff (#7257)
Show Diff in the annotate gutter listed every change of the blamed commit, with rename detection, only to learn how one file changed; on a commit touching thousands of files that was the whole wait. A new vcs_commit_file_change reads the file off the commit's and first parent's trees, and only runs the rename search for an added file, against the commit's deletions. Backend::commit_file_change defaults to filtering commit_files, so other backends (SVN) stay correct.

Fixes #7169

Co-authored-by: Pecnikas <[email protected]>
2026-12-02 05:02:36 +08:00
l0ng-ai 6c36723a7d fix(agents): drop the project folder from Windows paths in tool titles (#7300)
shortTitle stripped the task folder followed by '/' literally, so on Windows tool titles kept the full absolute path (backslashes, another drive-letter case). For Windows paths the task folder now matches with either separator and any letter case; commandTitle's cd check uses the same comparison.

Fixes #7286
2026-12-02 04:58:51 +08:00
Mansur Akhmadiтаmansur-akhmadi ed58f1aba0 feat(editor): Maximize Editor / Normalize Splits (#7275)
Adds Maximize Editor / Normalize Splits (IDEA's MaximizeEditorInSplit) to Window › Editor Tabs and the tab context menu of a split: it grows the current group in every split around it, and while that group stays maximized the same item gives all editor splits equal sizes. The tab menu label names what a click will do.

Closes #7274

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 04:56:12 +08:00
Mansur Akhmadiтаmansur-akhmadi adda2cbb93 feat(editor): File Properties › Line Separators (#7290)
File › File Properties gains a Line Separators submenu (CRLF / LF / CR) that converts the active file's line separators, like the status bar widget; it marks the file modified, does nothing when the file already uses that separator, and is disabled for read-only files and notebook cells. Mapped to IDEA's ConvertTo…LineSeparators action ids.

Closes #7289

Co-authored-by: mansur-akhmadi <[email protected]>
2026-12-02 04:56:03 +08:00
Vadim LazukтаInf1mum 132259242a fix(app): skip the exit confirmation when only the Welcome screen is open (#7284)
With Confirm application exit on, closing or quitting from the Welcome screen still asked, though no project would be lost. The confirmation now guards only a project or LightEdit session: a lone Welcome window closes and quits without it, while quitting from Welcome with other project windows open still asks.

Closes #7267

Co-authored-by: Inf1mum <[email protected]>
2026-12-02 04:29:12 +08:00
Vadim LazukтаInf1mum 1a400d3405 fix(editor): clamp horizontal scroll-hold spacer to scrollWidth (#7276)
The editor could scroll horizontally past the end of the longest line without end, because the scroll-hold spacer kept growing. It is now clamped to the content's scroll width.

Closes #7270

Co-authored-by: Inf1mum <[email protected]>
2026-12-02 04:26:59 +08:00
audichuang aa1711194c fix(tools): keep another program's tsconfig.json change when enabling CSS Modules Kit (#7281)
Enabling CSS Modules Kit saved tsconfig.json unconditionally, overwriting a change another program made on disk after the editor read it. The save is now guarded like an autosave; when refused, nothing is installed, the editor keeps the buffer and the user is told.

Co-authored-by: audichuang <[email protected]>
2026-12-02 04:26:52 +08:00
audichuang 83dcdc8eca fix(vcs): follow a branch rename only in Log tabs of that repository (#7283)
Renaming a branch renamed the Branch filter and Log tabs of every repository that had a branch of the same name. The rename now applies only to views scoped to the renamed repository (and its linked worktrees, which share its branches).

Co-authored-by: audichuang <[email protected]>
2026-12-02 04:26:44 +08:00
Vadim LazukтаInf1mum 783daaa041 fix(vcs): show mailmap-mapped authors in the Git Log (#7287)
The Git Log showed the raw author stored in each commit and ignored the repository's .mailmap, so one person with several name variants appeared as different authors. The log index now maps authors through .mailmap on read (reloaded when the file changes), and the User filter lists mailmap-mapped identities. Uses gix's mailmap feature.

Closes #7277

Co-authored-by: Inf1mum <[email protected]>
2026-12-02 04:26:37 +08:00
l0ng-ai dc74595bca feat(run): Tomcat before launch task list with Maven goal and Gradle task steps (#7294)
The Tomcat Server form's Before launch section only toggled one Build item. It now uses the same task list as other run configurations (BeforeLaunchTasks), with Tomcat's artifact Build as a removable, reorderable entry that existing configurations keep. Before launch also gains Run Maven Goal and Run Gradle Task steps that run through the build tools' existing execution and abort the launch on failure; BeforeLaunchTask gets an optional projectDir.

Fixes #7200
2026-12-02 04:19:59 +08:00
l0ng-ai aa596f1125 fix(vcs): put Select… and me first in the Git Log User filter (#7272)
With many authors the Git Log User menu was taller than the window, and Select..., the only way to filter by several users, came last and out of view.

The menu now starts with Select... and me, then the recent filters under a Recent header (several users apply in one click), then up to 30 known authors. A click on an author still sets the filter to that author alone.

Fixes #7254
2026-12-02 00:25:00 +08:00
l0ng-ai 6927b787b2 fix(vcs): move on to the next file from the changes diff preview (#7271)
The diff preview embedded in the Commit tool window and the Git window's Local Changes tab built a diff for the selected file without its sibling files, so F7 / the down arrow past the last difference did nothing there.

The changes tree now publishes its files in tree order (unversioned included, amend entries left out) and the preview uses them as the diff's chain. Past the last (first) difference the diff hints, then shows the next (previous) file in the preview itself and asks the tree to select it; the tree reveals it the same way it follows the active diff tab.

Fixes #7149
2026-12-02 00:15:32 +08:00
arookieofcтаarookieofc e1e9ede2d6 fix(agents): resolve agent CLIs on the shared tool search path (#7269)
Agent CLI detection looked only at the process PATH, and the registry, CLI update, native launch and spawn paths each used their own lookup (which::which, host PATH, login-shell PATH). When the app is launched from the desktop, CLIs installed in ~/.local/bin, ~/.npm-global/bin, ~/.bun/bin, nvm or Homebrew were reported as not installed or failed to start.

All of them now fall back to ide_core::tool_path::search_path(), which merges the host PATH, the login shell's PATH, the Windows user PATH, common home bin folders and version manager shims. A provider's own PATH from its env is checked first. MCP server launches and replayed agent sessions go through ide_jsonrpc::resolve_spawn_program as well instead of their own copies, and ide-agent no longer depends on which.

Fixes #7246

Co-authored-by: arookieofc <[email protected]>
2026-12-02 00:09:51 +08:00
LU XIANGRUIтаwildcatDownstairs 839292fb30 fix(run): keep the xcodebuild log out of an Xcode run's console (#7265)
Running an Xcode scheme printed the whole xcodebuild log in the Run console ahead of the app's output, so on a large project the console trimmed away or buried what the app printed.

The host now wraps an Xcode run's console (after Problems has read the output) with RunOutputSplit: everything up to xcodebuild's BUILD SUCCEEDED / FAILED / INTERRUPTED line goes to a per-configuration build log in the temporary folder, and the console shows the result and a link to the log. A failed build still shows its error lines (or the log's last lines when it printed none) and the failed commands. The app console leaves out simctl's '<bundle id>: <pid>' lines, keeping the first one while a debugger waits for it, and the runtime's 'Class ... is implemented in both' warnings. A build that ends without a result line is finished on the process's exit line.

Fixes #7264

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 00:07:01 +08:00
LU XIANGRUIтаwildcatDownstairs 2a4bf1f848 fix(run): skip SourcePackages, Pods, Carthage and DerivedData when discovering run configurations (#7263)
Run configuration discovery walks three levels deep and its shared skip list only knew node_modules, target, build and a few others, so an iOS project with resolved Swift packages in SourcePackages/checkouts listed every dependency's Rakefiles, CMake targets, Makefiles, Swift packages and Xcode schemes (252 configurations on a real Tuist app, 218 of them from dependencies).

project_roots now exposes the skip list as is_skipped_dir and adds SourcePackages, Pods, Carthage and DerivedData. Xcode's project_stamp uses the same list (plus Tuist) instead of its own copy, so build discovery, run discovery and the settings stamp agree on one list.

Fixes #7261

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 00:04:22 +08:00
l0ng-aiтаCursor 3e41c93a95 fix(ci): skip RPM bundles in nightly builds (#7258)
Co-authored-by: Cursor <[email protected]>
2026-12-02 00:00:57 +08:00
l0ng-ai b85027dc47 fix(database): colour quoted identifiers as names in DuckDB and Snowflake consoles (#7260)
The DuckDB and Snowflake console dialects are built from lang-sql directly, which tags QuotedIdentifier like a string, so "schema"."table" was still painted in the string colour there after #7255 fixed the plain SQL mode. Both dialects now restyle QuotedIdentifier as a name.
2026-12-01 23:08:39 +08:00
Alexanderтаformiat 63c2ced086 fix(vcs): focus the diff's text when the modal diff window opens (#7252)
Under the modal commit interface the diff window gave initial focus to its toolbar's first button, so F7 / Shift+F7 did nothing until a click in the text. The dialog body is now the autofocus target and an editor focus host, handing focus to the diff's text.

Closes #7250

Co-authored-by: formiat <[email protected]>
2026-12-01 23:06:34 +08:00
faysouтаfaysou d73b8d8ec1 fix(markdown): render equations in HTML table cells (#7249)
Marked passes raw HTML tables through untouched, so TeX delimiters stayed visible in their cells. Inline equations in sanitized cell text are now marked and sent through the existing preview typesetter; code and attributes stay literal.

Co-authored-by: faysou <[email protected]>
2026-12-01 23:06:15 +08:00
Ivan 74b90a114a fix(sql): colour quoted identifiers as names, not strings (#7255)
lang-sql tags QuotedIdentifier as special(string), so "schema"."table" and quoted column lists were painted in the string colour. The SQL mode now restyles QuotedIdentifier as a name.

Co-authored-by: Pecnikas <[email protected]>
2026-12-01 23:06:02 +08:00
koeriaтаkoeria e70b516ca0 fix(lsp): do not swallow } when inline completion is unsupported (#7251)
Call Inline Completion is Alt+\, which on some macOS layouts types a character such as }. When no language server or plugin supports inline completion, the shortcut consumed the key and showed a hint. The action now re-inserts the typed character in that case, and once the provider is known to be unavailable the key is left to the editor.

Closes #7247

Co-authored-by: koeria <[email protected]>
2026-12-01 23:05:50 +08:00
LU XIANGRUIтаwildcatDownstairs 7d15681313 feat(svn): built-in Subversion support (#7131)
Adds an ide-svn backend on top of the generic VCS layer (#7065): SVN working copies are detected and routed through the shared Backend/BackendProvider, reusing the existing VCS UI for status, diff, commit, history, annotate, update and revert. CI installs Subversion on Linux and macOS; on Windows the SVN integration tests skip when svn is missing.

Closes #178

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 22:57:35 +08:00
l0ng-ai 2ecaefe859 fix(java): normalize Maven system-scope jar paths on Windows (#7248)
${pom.basedir}/src/main/... resolved to a path mixing \\ and / on Windows, so the launch classpath carried it in an odd spelling and the #7226 test failed on the Windows runner. The resolved path is rebuilt from its components.
2026-12-01 22:17:51 +08:00
Mykhailo Smolinskyiтаnntndfrk 895e5bd56e fix(editor): bump @codemirror/view to 6.44.2 for the Safari tooltip fix (#570)
@codemirror/view 6.44 contains the upstream fix for tooltip positioning in Safari/WebKit; bump to ^6.44.2 and rebase the local patch onto it.

Co-authored-by: nntndfrk <[email protected]>
2026-12-01 21:56:40 +08:00
solhovoy 2dc577614b fix(vcs): keep find in modal diff (#7198)
⌘F in the modal diff opened Find in the editor tab behind it. The diff dialog now claims the Find keys while it has focus, so Find opens in the modal; Replace works there on an editable side as in any diff.

Co-authored-by: solhovoy <[email protected]>
2026-12-01 21:47:09 +08:00
LU XIANGRUIтаLU XIANGRUI a9e92d0665 fix(python): load package description images only when asked (#6616)
* fix(python): load package description images only when asked, and list the PyPI link once

* fix(python): hold back image inputs and backgrounds too, and match the PyPI page by name

---------

Co-authored-by: LU XIANGRUI <[email protected]>
2026-12-01 21:22:13 +08:00
LU XIANGRUIтаwildcatDownstairs fa0be07436 perf(xcode): read a run's build settings once and say so in the console (#7244)
▶ on an Xcode scheme ran xcodebuild -showBuildSettings twice before building (8–13 s each on a large Tuist workspace) with an empty console. One read now also decides whether the app runs on the Mac, settings are cached until project.pbxproj, the workspace, a scheme, an xcconfig or Package.resolved changes, and the console reports the read and its duration.

Fixes #7236
Fixes #7237

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 21:19:28 +08:00
l0ng-ai fea27f5608 fix(format): reformat a directory without opening an editor for each file (#7245)
Reformat Code and Code Cleanup on a directory opened every file in a focused tab. As in IDEA, files that aren't open are formatted on their shared document and saved without a tab; open files are changed in place, keeping the active tab and focus, one undo step each.

Fixes #7221
2026-12-01 21:04:59 +08:00
LU XIANGRUIтаwildcatDownstairs a4d172ac83 fix(xcode): end the app when an iOS Simulator debug session stops (#7241)
Stopping an Xcode debug session on the iOS Simulator left simctl and the app running. Stopping now terminates the launched app on the simulator and ends the launcher.

Fixes #7240

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 20:52:43 +08:00
LU XIANGRUIтаwildcatDownstairs c40d06c702 fix(xcode): give xcode-build-server the build folder of the project's scheme (#7233)
Generating buildServer.json failed on a Tuist workspace whose first scheme is a Swift package: xcode-build-server read that scheme's build settings, which have no build folder. The IDE reads the DerivedData folder from the first project scheme and passes it as --build_root, with an absolute container path.

Fixes #7232

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-01 20:52:36 +08:00
Alexanderтаformiat 619ae7f727 fix(vcs): keep the end of a diff line clear of the overview lane (#7229)
At full horizontal scroll the end of a diff's longest line stayed under the change overview lane. The diff editors reserve the lane's width at the end of the content, in split and unified modes.

Fixes #7228

Co-authored-by: formiat <[email protected]>
2026-12-01 20:52:29 +08:00
l0ng-ai c725b1629d fix(vim): replace a Visual selection when Ctrl+V is given to the IDE (#7242)
With Ctrl+V's handler set to the IDE, pasting over a Visual selection inserted after it because the browser paste ran after Vim collapsed the selection. In Visual mode an IDE-handled paste stroke runs Paste, replacing the selection in one transaction; with the default handler Ctrl+V still starts a Visual block, as in IdeaVim.

Fixes #7192
2026-12-01 20:47:41 +08:00
l0ng-ai b0033a869d test(vcs): give the unavailable-root fixtures their VCS kind (#7238)
#7065 made VcsRoot.kind required; the fixtures #7161 added on main lacked it, so tsc failed on main.
2026-12-01 20:44:00 +08:00
l0ng-ai 4ed4ced5b1 fix(plugins): warn once about a duplicate plugin directory (#7235)
A plugin found both at an older location and a linked one logged "ignored: already loaded from" on every rescan, tens of thousands of times a session. The warning is given once per plugin directory.

Refs #7207
2026-12-01 20:29:57 +08:00
517 змінених файлів з 61776 додано та 1896 видалено

No files matched your search

+7
Переглянути файл
@@ -11,3 +11,10 @@ package(=ide-clipboard) & (
)
'''
test-group = "windows-clipboard"
# The Subversion tests run svn against throwaway servers: none should take minutes. A test
# that hangs (a server left stopped) is ended after 5 minutes instead of waiting for svn's own
# timeout.
[[profile.default.overrides]]
filter = 'package(=ide-svn) | (package(=ide-host) & (binary(=svn) | binary(=ij_svn_roots)))'
slow-timeout = { period = "60s", terminate-after = 5 }
+11 -1
Переглянути файл
@@ -150,8 +150,18 @@ jobs:
- name: Linux deps
if: runner.os == 'Linux'
run: |
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf)
pkgs=(libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev libssl-dev patchelf subversion sqlite3)
dpkg -s "${pkgs[@]}" >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; }
# The Subversion tests run the real svn, svnadmin and svnserve (and sqlite3, to write a
# working copy's database); with CI set they fail instead of skipping when these are
# missing. Linux gets them with the deps above; macOS has sqlite3. Windows runners skip them.
- name: Subversion (macOS)
if: runner.os == 'macOS'
run: command -v svnadmin >/dev/null || brew install subversion
- name: Subversion version
if: runner.os != 'Windows'
shell: bash
run: svn --version --quiet && svnadmin --version --quiet && svnserve --version --quiet && sqlite3 --version
# tauri-build checks that frontendDist exists.
- run: pnpm install --frozen-lockfile && mkdir -p dist
shell: bash
+4 -2
Переглянути файл
@@ -284,6 +284,8 @@ jobs:
return;
}
// Bundle suffix → updater platform keys, as tauri-action names them.
// Nightly builds skip RPM because RPM rejects `-` in SemVer prerelease versions.
const nightly = tag.includes("-nightly.");
const windows = (arch, msi, nsis) => [
[msi, [`windows-${arch}`, `windows-${arch}-msi`]],
[nsis, [`windows-${arch}-nsis`]],
@@ -291,10 +293,10 @@ jobs:
const kinds = [
[/_aarch64\.AppImage$/, ["linux-aarch64", "linux-aarch64-appimage"]],
[/_arm64\.deb$/, ["linux-aarch64-deb"]],
[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]],
...(nightly ? [] : [[/\.aarch64\.rpm$/, ["linux-aarch64-rpm"]]]),
[/_amd64\.AppImage$/, ["linux-x86_64", "linux-x86_64-appimage"]],
[/_amd64\.deb$/, ["linux-x86_64-deb"]],
[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]],
...(nightly ? [] : [[/\.x86_64\.rpm$/, ["linux-x86_64-rpm"]]]),
[/_aarch64\.app\.tar\.gz$/, ["darwin-aarch64", "darwin-aarch64-app"]],
[/_x64\.app\.tar\.gz$/, ["darwin-x86_64", "darwin-x86_64-app"]],
...windows("aarch64", /_arm64_en-US\.msi$/, /_arm64-setup\.exe$/),
Створено
+31 -1
Переглянути файл
@@ -2766,6 +2766,7 @@ dependencies = [
"gix-ignore",
"gix-index",
"gix-lock",
"gix-mailmap",
"gix-note",
"gix-object",
"gix-odb",
@@ -3132,6 +3133,18 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "gix-mailmap"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a30866257cc7f0af5b85f98a9e87dc73e46de8cb1838ee18c9dbe08a2461717e"
dependencies = [
"bstr",
"gix-actor",
"gix-date",
"gix-error",
]
[[package]]
name = "gix-note"
version = "0.3.1"
@@ -4166,6 +4179,7 @@ dependencies = [
"ide-tools",
"ide-vcs",
"ide-vfs",
"jiff",
"parking_lot 0.12.5",
"rustix",
"semver",
@@ -4177,9 +4191,9 @@ dependencies = [
"tempfile",
"tokio",
"toml 0.9.12+spec-1.1.0",
"toml_edit 0.25.17+spec-1.1.0",
"tracing",
"uuid",
"which",
]
[[package]]
@@ -4514,6 +4528,7 @@ dependencies = [
"ide-spell",
"ide-ssh",
"ide-streams",
"ide-svn",
"ide-syntax",
"ide-terminal",
"ide-text",
@@ -4972,6 +4987,21 @@ dependencies = [
"tree-sitter",
]
[[package]]
name = "ide-svn"
version = "0.1.56"
dependencies = [
"dunce",
"encoding_rs",
"ide-core",
"ide-vcs",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"tempfile",
"which",
"windows-sys 0.61.2",
]
[[package]]
name = "ide-syntax"
version = "0.1.56"
+2
Переглянути файл
@@ -24,6 +24,7 @@ ide-jsonrpc = { path = "crates/ide-jsonrpc" }
ide-lsp = { path = "crates/ide-lsp" }
ide-dap = { path = "crates/ide-dap" }
ide-vcs = { path = "crates/ide-vcs" }
ide-svn = { path = "crates/ide-svn" }
ide-github = { path = "crates/ide-github" }
ide-terminal = { path = "crates/ide-terminal" }
ide-run = { path = "crates/ide-run" }
@@ -90,6 +91,7 @@ trash = "5"
blake3 = "1"
dunce = "1"
dirs = "6"
jiff = "0.2"
memmap2 = "0.9"
zip = { version = "9.2.3", default-features = false, features = ["deflate"] }
flate2 = "1"
+5
Переглянути файл
@@ -6,6 +6,11 @@ contributors as part of the IntelliJ Platform (https://github.com/JetBrains/inte
https://github.com/JetBrains/intellij-plugins), licensed under the Apache License 2.0.
Copyright 2000-2026 JetBrains s.r.o. and contributors.
The Subversion tests (crates/ide-svn/tests/matrix.rs) take the tree-conflict scenarios,
their names and file contents from IntelliJ's svn4idea TreeConflictData
(plugins/svn4idea/testSource/org/jetbrains/idea/svn/), Apache License 2.0, Copyright
2000-2026 JetBrains s.r.o. and contributors.
Some Simplified Chinese UI terms follow the Visual Studio Code Simplified Chinese
language pack (https://github.com/microsoft/vscode-loc), Copyright (c) Microsoft
Corporation, licensed under the MIT License.
+2 -1
Переглянути файл
@@ -21,12 +21,13 @@ specta.workspace = true
sqlx.workspace = true
tokio.workspace = true
toml.workspace = true
toml_edit.workspace = true
tracing.workspace = true
parking_lot.workspace = true
dunce.workspace = true
jiff.workspace = true
uuid.workspace = true
tempfile.workspace = true
which = "8"
semver = "1"
sha1 = "0.10"
File diff suppressed because it is too large. Load diff
+3 -1
Переглянути файл
@@ -58,7 +58,9 @@ impl AgentManager {
if spec.source != AgentSource::Builtin {
return Ok(AgentCliUpdateResult::Unmanaged);
}
let Ok(npm) = which::which("npm") else { return Ok(AgentCliUpdateResult::Unmanaged) };
let Some(npm) = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path()) else {
return Ok(AgentCliUpdateResult::Unmanaged);
};
let program = spec.resolve_for_launch(&self.shared.paths.project_root).command;
match maintain(&npm, Path::new(&program), &builtin.command, pkg, offer, cancel) {
Err(e) if e.kind == ErrorKind::Unavailable => Ok(AgentCliUpdateResult::Error { code: e.message }),
+338 -1
Переглянути файл
@@ -131,7 +131,263 @@ fn is_bypass_mode(mode: &str) -> bool {
let lower = mode.to_lowercase();
let m: String =
lower.rsplit(['#', '/']).next().unwrap_or_default().chars().filter(char::is_ascii_lowercase).collect();
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous"
m.contains("bypass") || m == "yolo" || m.contains("fullaccess") || m == "dangerous" || m == "autopilot"
}
fn upsert_choice(wanted: &mut Vec<crate::model::AgentConfigChoice>, id: &str, value: &str) {
if let Some(existing) = wanted.iter_mut().find(|c| c.id == id) {
existing.value = value.to_owned();
} else {
wanted.push(crate::model::AgentConfigChoice { id: id.to_owned(), value: value.to_owned() });
}
}
pub(crate) fn is_approval_option(opt: &AgentConfigOption) -> bool {
opt.id == CURSOR_APPROVAL || matches!(opt.category.as_deref(), Some("mode" | "permissions" | "approval"))
}
fn wanted_val(wanted: &[crate::model::AgentConfigChoice], id: &str) -> Option<String> {
wanted.iter().find(|c| c.id == id).map(|c| c.value.clone())
}
/// Applies an automation's permission policy (`mode`) to `config` and `wanted`, enforcing the
/// user's interactive approval setting (`interactive`) as a strict ceiling. When `mode` is `None`
/// (an in-session `/loop` or `Send Later` turn), clamps any bypass options down when `interactive`
/// is [`ide_core::settings::NewTaskApprovals::Ask`].
pub(crate) fn clamp_automation_permissions(
provider: &str,
mode: Option<crate::automation::AutomationPermissionMode>,
interactive: ide_core::settings::NewTaskApprovals,
config: &mut [AgentConfigOption],
wanted: &mut Vec<crate::model::AgentConfigChoice>,
) {
use crate::automation::AutomationPermissionMode;
use ide_core::settings::NewTaskApprovals;
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
return;
}
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
if !allow_bypass {
// Strip any explicit bypass choices from `wanted` first so they cannot re-elevate later.
wanted.retain(|c| match c.id.as_str() {
"mode" => !is_bypass_mode(&c.value),
"allow_all" | "permissions" => !matches!(c.value.to_ascii_lowercase().as_str(), "on" | "true"),
"approval" | CURSOR_APPROVAL => !c.value.eq_ignore_ascii_case("bypass"),
"approval_policy" => !c.value.eq_ignore_ascii_case("never"),
_ => true,
});
ask_for_approvals(config);
}
match provider {
"claude" | "claude-acp" => {
let cur_wanted = wanted_val(wanted, "mode");
let target = if allow_bypass {
match cur_wanted.as_deref() {
Some("default" | "plan" | "acceptEdits") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "bypassPermissions".to_owned(),
}
} else if interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::Assisted) {
match cur_wanted.as_deref() {
Some("default" | "plan") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "acceptEdits".to_owned(),
}
} else {
// Either Default mode or interactive policy is Ask (where interactive Claude starts in `default`).
match cur_wanted.as_deref() {
Some("plan") => "plan".to_owned(),
_ => "default".to_owned(),
}
};
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
&& opt.values.iter().any(|v| v.value == target)
{
let id = opt.id.clone();
opt.current = Some(target.clone());
upsert_choice(wanted, &id, &target);
} else if mode.is_some() || cur_wanted.is_some() {
upsert_choice(wanted, "mode", &target);
}
}
"codex" | "codex-acp" => {
let cur_wanted = wanted_val(wanted, "mode");
let target = if allow_bypass {
match cur_wanted.as_deref() {
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "full-access".to_owned(),
}
} else if mode == Some(AutomationPermissionMode::Default) {
"read-only".to_owned()
} else if mode.is_some() {
// Assisted, or AllowAll clamped by interactive Ask (`ask_for_approvals` maps full-access -> ask).
match cur_wanted.as_deref() {
Some("read-only") => "read-only".to_owned(),
_ => "ask".to_owned(),
}
} else {
// Scheduled /loop or Send Later under interactive Ask: never full-access.
match cur_wanted.as_deref() {
Some("read-only" | "ask" | "auto") => cur_wanted.as_deref().unwrap().to_owned(),
_ => "ask".to_owned(),
}
};
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
&& opt.values.iter().any(|v| v.value == target)
{
let id = opt.id.clone();
opt.current = Some(target.clone());
upsert_choice(wanted, &id, &target);
} else if mode.is_some() || cur_wanted.is_some() {
upsert_choice(wanted, "mode", &target);
}
}
"copilot" => {
if allow_bypass {
if !matches!(wanted_val(wanted, "allow_all").as_deref(), Some("off" | "false")) {
upsert_choice(wanted, "allow_all", "on");
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
opt.current = Some("on".into());
}
}
} else {
upsert_choice(wanted, "allow_all", "off");
if let Some(opt) = config.iter_mut().find(|o| o.id == "allow_all") {
opt.current = Some("off".into());
}
let non_auto = match wanted_val(wanted, "mode").as_deref() {
Some("plan") => "plan",
_ => "agent",
};
if mode.is_some() || config.iter().any(|o| o.id == "mode" && o.current.as_deref() == Some("autopilot"))
{
upsert_choice(wanted, "mode", non_auto);
}
if let Some(opt) = config.iter_mut().find(|o| o.id == "mode")
&& (mode.is_some() || opt.current.as_deref() == Some("autopilot"))
&& opt.values.iter().any(|v| v.value == non_auto)
{
opt.current = Some(non_auto.into());
}
}
}
"cursor" => {
let target = if allow_bypass && wanted_val(wanted, CURSOR_APPROVAL).as_deref() != Some("ask") {
"bypass"
} else {
"ask"
};
upsert_choice(wanted, CURSOR_APPROVAL, target);
if let Some(opt) = config.iter_mut().find(|o| o.id == CURSOR_APPROVAL) {
opt.current = Some(target.into());
}
}
_ => {
if allow_bypass {
let user_chose_non_bypass = config.iter().any(|o| {
is_approval_option(o)
&& wanted.iter().any(|c| {
c.id == o.id && o.category.as_deref().and_then(bypass_value).is_some_and(|b| !b(&c.value))
})
});
if !user_chose_non_bypass {
apply_bypass_approvals(config);
}
}
}
}
// Ensure every approval-bearing option in `config` has its enforced value mirrored in `wanted`
// so `open_session` actively configures the live session even if the CLI's own config differs.
for opt in config.iter().filter(|o| is_approval_option(o)) {
if let Some(cur) = opt.current.as_deref() {
upsert_choice(wanted, &opt.id, cur);
}
}
}
/// Verifies that the session's reported `config` options do not exceed the required automation
/// permission ceiling (`min(mode, interactive)`). Returns `Err(reason)` if the provider remained
/// in a more permissive mode than allowed.
pub(crate) fn verify_automation_ceiling(
provider: &str,
mode: Option<crate::automation::AutomationPermissionMode>,
interactive: ide_core::settings::NewTaskApprovals,
config: &[AgentConfigOption],
) -> Result<(), String> {
use crate::automation::AutomationPermissionMode;
use ide_core::settings::NewTaskApprovals;
if mode.is_none() && interactive == NewTaskApprovals::Bypass {
return Ok(());
}
let allow_bypass = interactive == NewTaskApprovals::Bypass && mode == Some(AutomationPermissionMode::AllowAll);
if !allow_bypass && bypass_approvals(config) {
return Err("Agent did not confirm the required approval ceiling (session remained in bypass mode).".into());
}
let cur_of = |id: &str| config.iter().find(|o| o.id == id).and_then(|o| o.current.as_deref());
let mode_cur = config
.iter()
.find(|o| o.id == "mode" || o.category.as_deref() == Some("mode"))
.and_then(|o| o.current.as_deref());
if !allow_bypass {
match provider {
"claude" | "claude-acp" => {
if let Some(cur) = mode_cur {
let allowed = if interactive == NewTaskApprovals::Bypass
&& mode == Some(AutomationPermissionMode::Assisted)
{
matches!(cur, "default" | "plan" | "acceptEdits")
} else {
matches!(cur, "default" | "plan")
};
if !allowed {
return Err(format!(
"Claude session remained in mode '{cur}', exceeding the required approval ceiling."
));
}
}
}
"codex" | "codex-acp" => {
if let Some(cur) = mode_cur {
let allowed = if mode == Some(AutomationPermissionMode::Default) {
cur == "read-only"
} else if mode.is_some() {
matches!(cur, "read-only" | "ask")
} else {
matches!(cur, "read-only" | "ask" | "auto")
};
if !allowed {
return Err(format!(
"Codex session remained in mode '{cur}', exceeding the required approval ceiling."
));
}
}
}
"copilot" => {
if let Some(cur) = cur_of("allow_all")
&& matches!(cur.to_ascii_lowercase().as_str(), "on" | "true")
{
return Err("Copilot session kept allow_all enabled above the approval ceiling.".into());
}
if let Some(cur) = mode_cur
&& cur.eq_ignore_ascii_case("autopilot")
{
return Err("Copilot session remained in autopilot mode above the approval ceiling.".into());
}
}
"cursor" if cur_of(CURSOR_APPROVAL).is_some_and(|cur| cur.eq_ignore_ascii_case("bypass")) => {
return Err("Cursor session remained in bypass mode above the approval ceiling.".into());
}
_ => {}
}
}
Ok(())
}
/// The settings in a `session/new` or `session/load` result: its select `configOptions`,
@@ -669,6 +925,87 @@ mod tests {
);
}
#[test]
fn automation_permissions_respect_interactive_approval_ceiling() {
use crate::automation::AutomationPermissionMode;
use crate::model::AgentConfigChoice;
use ide_core::settings::NewTaskApprovals;
let claude_opts = || {
options_of(&json!({"configOptions": [{
"id": "mode", "category": "mode", "type": "select", "currentValue": "bypassPermissions",
"defaultValue": "default",
"options": [
{"value": "default"}, {"value": "acceptEdits"}, {"value": "plan"}, {"value": "bypassPermissions"}
]
}]}))
};
// Claude Assisted under interactive Bypass -> acceptEdits; under interactive Ask -> default!
let mut c = claude_opts();
let mut wanted = Vec::new();
clamp_automation_permissions(
"claude",
Some(AutomationPermissionMode::Assisted),
NewTaskApprovals::Bypass,
&mut c,
&mut wanted,
);
assert_eq!(c[0].current.as_deref(), Some("acceptEdits"));
assert!(wanted.iter().any(|w| w.id == "mode" && w.value == "acceptEdits"));
let mut c_ask = claude_opts();
let mut wanted_ask = vec![AgentConfigChoice { id: "mode".into(), value: "bypassPermissions".into() }];
clamp_automation_permissions(
"claude",
Some(AutomationPermissionMode::AllowAll),
NewTaskApprovals::Ask,
&mut c_ask,
&mut wanted_ask,
);
assert_eq!(c_ask[0].current.as_deref(), Some("default"));
assert_eq!(wanted_ask, vec![AgentConfigChoice { id: "mode".into(), value: "default".into() }]);
// Copilot AllowAll under interactive Ask clamps allow_all -> off and autopilot -> agent.
let mut copilot = options_of(&json!({"configOptions": [
{"id": "mode", "category": "mode", "type": "select", "currentValue": "autopilot",
"options": [{"value": "agent"}, {"value": "plan"}, {"value": "autopilot"}]},
{"id": "allow_all", "category": "permissions", "type": "select", "currentValue": "on",
"options": [{"value": "off"}, {"value": "on"}]}
]}));
let mut copilot_wanted = vec![AgentConfigChoice { id: "allow_all".into(), value: "on".into() }];
clamp_automation_permissions(
"copilot",
Some(AutomationPermissionMode::AllowAll),
NewTaskApprovals::Ask,
&mut copilot,
&mut copilot_wanted,
);
assert_eq!(ids(&copilot), [("mode", Some("agent")), ("allow_all", Some("off"))]);
assert!(!bypass_approvals(&copilot));
// Codex Default -> read-only, Assisted -> ask, AllowAll + Ask -> ask, AllowAll + Bypass -> full-access.
let codex_opts = || {
options_of(&json!({"configOptions": [{
"id": "mode", "category": "mode", "type": "select", "currentValue": "full-access",
"defaultValue": "ask",
"options": [{"value": "read-only"}, {"value": "ask"}, {"value": "auto"}, {"value": "full-access"}]
}]}))
};
for (perm, interactive, expected) in [
(AutomationPermissionMode::Default, NewTaskApprovals::Bypass, "read-only"),
(AutomationPermissionMode::Assisted, NewTaskApprovals::Bypass, "ask"),
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Ask, "ask"),
(AutomationPermissionMode::AllowAll, NewTaskApprovals::Bypass, "full-access"),
] {
let mut opts = codex_opts();
let mut w = Vec::new();
clamp_automation_permissions("codex", Some(perm), interactive, &mut opts, &mut w);
assert_eq!(opts[0].current.as_deref(), Some(expected), "{perm:?} + {interactive:?}");
assert!(w.iter().any(|c| c.id == "mode" && c.value == expected));
}
}
#[test]
fn command_sources_in_updates_and_stored_tasks() {
let update = json!({"availableCommands": [
+182 -1
Переглянути файл
@@ -1,7 +1,10 @@
//! ACP elicitation in form mode: the agent's restricted JSON Schema as form fields, and the
//! user's answer as the `elicitation/create` response.
use crate::model::{AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption};
use crate::model::{
AgentForm, AgentFormField, AgentFormFieldKind, AgentFormOption, AgentPermissionOption, AgentQuestion,
AgentQuestionOption,
};
use serde::Deserialize;
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
use serde_json::{Map, Value, json};
@@ -10,6 +13,9 @@ use serde_json::{Map, Value, json};
/// anything else cancels it.
const DECLINE: &str = "decline";
/// What the question card sends for Skip.
const SKIP: &str = "reject";
/// The form `elicitation/create` asks for; `Err` when it asks for something else.
pub(crate) fn form_of(params: &Value) -> Result<AgentForm, String> {
if params.get("mode").and_then(Value::as_str) != Some("form") {
@@ -148,6 +154,97 @@ fn scalar(value: &Value) -> Option<String> {
}
}
/// The questions a form asks when it is an agent's question tool in form shape: every field
/// a choice, each followed by its own text field for a typed answer, named after it
/// (`question_0` + `question_0_custom` from claude-agent-acp's `AskUserQuestion`, `q0` +
/// `q0__other` from OMP's `ask`). They are shown and answered as the agent's questions, one
/// at a time like a native `AskUserQuestion` (#7359); [`answer_questions`] turns the answers
/// back into the form's values. `None` for any other form.
pub(crate) fn questions_of(form: &AgentForm, params: &Value, message: &str) -> Option<Vec<AgentQuestion>> {
let choices = form.fields.len() / 2;
if choices == 0 || form.fields.len() % 2 == 1 {
return None;
}
let properties = params.pointer("/requestedSchema/properties");
form.fields
.chunks(2)
.map(|pair| {
let [choice, text] = pair else { return None };
let asks = matches!(choice.kind, AgentFormFieldKind::Choice | AgentFormFieldKind::Choices)
&& !choice.options.is_empty()
&& text.kind == AgentFormFieldKind::Text
&& text.name.len() > choice.name.len()
&& text.name.starts_with(&choice.name);
if !asks {
return None;
}
let (title, description) = (choice.title.trim(), choice.description.trim());
let (header, question) = if choices == 1 && !message.is_empty() {
(if title == message || title == choice.name { "" } else { title }, message)
} else if description.is_empty() {
("", title)
} else {
(if title == choice.name { "" } else { title }, description)
};
let schema = properties.and_then(|p| p.get(&choice.name));
let options = choice
.options
.iter()
.map(|option| AgentQuestionOption {
label: option.label.clone(),
description: option.description.clone(),
preview: schema.and_then(|s| option_preview(s, &option.value)),
})
.collect();
Some(AgentQuestion {
answer_key: Some(choice.name.clone()),
header: header.to_owned(),
question: question.to_owned(),
multi_select: choice.kind == AgentFormFieldKind::Choices,
options,
})
})
.collect()
}
/// The preview claude-agent-acp forwards beside an option (`_meta["_claude/askUserQuestionOption"]`).
fn option_preview(schema: &Value, value: &str) -> Option<String> {
let listed = schema.get("oneOf").or_else(|| schema.get("anyOf")).or_else(|| schema.pointer("/items/anyOf"));
listed?
.as_array()?
.iter()
.find(|o| o.get("const").and_then(Value::as_str) == Some(value))?
.pointer("/_meta/_claude~1askUserQuestionOption/preview")?
.as_str()
.map(str::to_owned)
}
/// The form reply to the answers of [`questions_of`]'s questions (question key to the picked
/// labels and the typed text): picked options as the choice's values, the text in the field
/// beside it. The question card's Skip declines the form; nothing passes through.
pub(crate) fn answer_questions(form: &AgentForm, reply: Option<&str>) -> Option<String> {
let reply = reply?;
if reply == SKIP {
return Some(DECLINE.to_owned());
}
let Ok(answers) = serde_json::from_str::<Map<String, Value>>(reply) else { return Some(reply.to_owned()) };
let mut values = Map::new();
for pair in form.fields.chunks(2) {
let [choice, text] = pair else { continue };
let items = answers.get(&choice.name).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str);
let (mut picked, mut typed) = (Vec::new(), Vec::new());
for item in items {
match choice.options.iter().find(|o| o.label == item) {
Some(option) => picked.push(json!(option.value)),
None => typed.push(item),
}
}
values.insert(choice.name.clone(), Value::Array(picked));
values.insert(text.name.clone(), json!([typed.join("\n")]));
}
Some(Value::Object(values).to_string())
}
/// A form is submitted from its own card; this option only names a declined form.
pub(crate) fn options() -> Vec<AgentPermissionOption> {
vec![AgentPermissionOption { id: DECLINE.to_owned(), name: "Decline".to_owned(), kind: "reject_once".to_owned() }]
@@ -295,6 +392,90 @@ mod tests {
assert_eq!(chosen, "count: 3; ok: no; size: Small; tags: a, b");
}
/// What claude-agent-acp sends for `AskUserQuestion` with two questions.
fn claude_questions() -> Value {
json!({
"sessionId": "s", "mode": "form", "message": "Please answer the following questions.",
"requestedSchema": { "type": "object", "properties": {
"question_0": { "type": "string", "title": "Delivery", "description": "How should it ship?",
"oneOf": [{ "const": "Util + table (Recommended)", "title": "Util + table (Recommended)",
"description": "Tracks tasks",
"_meta": { "_claude/askUserQuestionOption": { "preview": "```\nUtil\n```" } } },
{ "const": "Util only", "title": "Util only" }] },
"question_0_custom": { "type": "string", "title": "Other" },
"question_1": { "type": "array", "title": "Targets", "description": "Who receives it?",
"items": { "anyOf": [{ "const": "Members", "title": "Members" },
{ "const": "Tags", "title": "Tags" }] } },
"question_1_custom": { "type": "string", "title": "Other" }
} }
})
}
fn in_order(params: &Value, names: &[&str]) -> AgentForm {
let mut form = form_of(params).unwrap();
form.fields.sort_by_key(|f| names.iter().position(|n| *n == f.name));
form
}
#[test]
fn a_question_tool_form_is_asked_as_questions() {
let params = claude_questions();
let form = in_order(&params, &["question_0", "question_0_custom", "question_1", "question_1_custom"]);
let questions = questions_of(&form, &params, "Please answer the following questions.").unwrap();
let [delivery, targets] = questions.as_slice() else { panic!("{questions:?}") };
assert_eq!(
(
delivery.answer_key.as_deref(),
delivery.header.as_str(),
delivery.question.as_str(),
delivery.multi_select
),
(Some("question_0"), "Delivery", "How should it ship?", false)
);
assert_eq!(delivery.options[0].description, "Tracks tasks");
assert_eq!(delivery.options[0].preview.as_deref(), Some("```\nUtil\n```"));
assert_eq!(delivery.options[1].preview, None);
assert_eq!((targets.question.as_str(), targets.multi_select), ("Who receives it?", true));
let reply = json!({ "question_0": ["Util only", "keep it small"], "question_1": ["Members", "Tags"] });
let reply = answer_questions(&form, Some(&reply.to_string()));
let (response, chosen) = answer(&form, reply.as_deref());
assert_eq!(
response,
json!({ "action": "accept", "content": {
"question_0": "Util only", "question_0_custom": "keep it small", "question_1": ["Members", "Tags"]
} })
);
assert_eq!(chosen, "Delivery: Util only; Other: keep it small; Targets: Members, Tags");
assert_eq!(answer_questions(&form, Some(SKIP)).as_deref(), Some(DECLINE));
assert_eq!(answer_questions(&form, None), None);
}
#[test]
fn a_single_question_reads_from_the_message() {
let params = ask();
let form = in_order(&params, &["q0", "q0__other"]);
let questions = questions_of(&form, &params, "Which database?").unwrap();
assert_eq!((questions[0].header.as_str(), questions[0].question.as_str()), ("", "Which database?"));
assert_eq!(questions[0].options[0].label, "Postgres");
let reply = answer_questions(&form, Some(&json!({ "q0": ["SQLite"] }).to_string()));
assert_eq!(answer(&form, reply.as_deref()).0, json!({ "action": "accept", "content": { "q0": "sqlite" } }));
}
#[test]
fn other_forms_stay_forms() {
let only_choices = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"size": { "type": "string", "enum": ["s", "l"] }, "env": { "type": "string", "enum": ["dev"] }
} } }))
.unwrap();
assert_eq!(questions_of(&only_choices, &json!({}), "Pick"), None);
let unrelated_text = form_of(&json!({ "mode": "form", "requestedSchema": { "type": "object", "properties": {
"size": { "type": "string", "enum": ["s", "l"] }, "note": { "type": "string" }
} } }))
.unwrap();
assert_eq!(questions_of(&unrelated_text, &json!({}), "Pick"), None);
}
#[test]
fn declining_and_dismissing_send_no_content() {
let form = form_of(&ask()).unwrap();
File diff suppressed because it is too large. Load diff
+29 -16
Переглянути файл
@@ -68,9 +68,25 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer
headers: cfg.headers.iter().map(|(k, v)| McpKeyValue { name: k.clone(), value: v.clone() }).collect(),
agents: cfg.agents.clone(),
unapproved: false,
plugin_id: None,
plugin_name: None,
}
}
/// Merges `projected` MCP servers from enabled agent plugins behind `configured` User and
/// Workspace servers so standalone settings entries always take precedence on name clashes.
pub fn merge_projected_servers(mut configured: Vec<McpServer>, projected: Vec<McpServer>) -> Vec<McpServer> {
let existing: HashSet<String> = configured.iter().map(|s| s.name.clone()).collect();
// Same-named servers from different bundles are distinct rows (ids are `plugin:<bundle>:<server>`).
let mut seen_projected: HashSet<String> = HashSet::new();
for srv in projected {
if !existing.contains(&srv.name) && seen_projected.insert(srv.id.clone()) {
configured.push(srv);
}
}
configured
}
fn normalize_provider(id: &str) -> &str {
id.strip_suffix("-acp").unwrap_or(id)
}
@@ -399,13 +415,8 @@ pub fn apply_save_json(
Ok(saved_names)
}
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
".github/plugin/plugin.json",
".plugin/plugin.json",
".claude-plugin/plugin.json",
".cursor-plugin/plugin.json",
"plugin.json",
];
const COPILOT_PLUGIN_MANIFESTS: &[&str] =
&[".github/plugin/plugin.json", ".plugin/plugin.json", ".claude-plugin/plugin.json", "plugin.json"];
#[derive(Clone, PartialEq, Eq)]
enum SourceFormat {
@@ -1051,6 +1062,14 @@ fn extract_servers_from_root(root: &Value, fallback_name: Option<&str>) -> BTree
out
}
pub(crate) fn read_external_mcp_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
read_external_file(path)
}
pub(crate) fn parse_mcp_value(root: &Value) -> Result<BTreeMap<String, AgentMcpServer>, String> {
Ok(extract_servers_from_root(root, None))
}
fn read_external_file(path: &Path) -> BTreeMap<String, AgentMcpServer> {
let Ok(text) = std::fs::read_to_string(path) else {
return BTreeMap::new();
@@ -1088,15 +1107,7 @@ pub async fn probe_stdio_server(server: &AgentMcpServer, cwd: &Path) -> McpProbe
env.push((k.clone(), v.clone()));
}
}
let search_path = env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
let program = ide_core::process::find_executable(raw_cmd, &search_path)
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| raw_cmd.to_owned());
let program = ide_jsonrpc::resolve_spawn_program(raw_cmd, &env).to_string_lossy().into_owned();
let stderr_lines = std::sync::Arc::new(parking_lot::Mutex::new(Vec::<String>::new()));
let stderr_capture = stderr_lines.clone();
@@ -1259,6 +1270,8 @@ mod tests {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
}
}
+24
Переглянути файл
@@ -453,6 +453,26 @@ pub fn discover_memories(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Age
out
}
/// Discovers all standalone memory entries across `workspaces` and `home`, then appends
/// projected rule/context entries from enabled agent plugins (deduplicated by canonical path).
pub fn discover_memories_with_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
projected: Vec<AgentMemoryEntry>,
) -> Vec<AgentMemoryEntry> {
let mut out = discover_memories(workspaces, home);
let mut seen: HashSet<PathBuf> =
out.iter().map(|e| dunce::canonicalize(&e.path.0).unwrap_or_else(|_| e.path.0.clone())).collect();
for mut entry in projected {
let canon = dunce::canonicalize(&entry.path.0).unwrap_or_else(|_| entry.path.0.clone());
entry.path = canon.clone().into();
if seen.insert(canon) {
out.push(entry);
}
}
out
}
/// Resolves the full [`AgentMemoryCatalog`] (entries + per-provider auto-memory statuses)
/// against `policy` and optional per-session `session_overrides`.
pub fn resolve_catalog(
@@ -1412,6 +1432,8 @@ fn parse_cursor_mdc(path: &Path, rel: &str) -> Option<AgentMemoryEntry> {
writable: false,
valid: true,
warnings,
plugin_id: None,
plugin_name: None,
})
}
@@ -1482,6 +1504,8 @@ fn parse_entry(
writable,
valid: true,
warnings,
plugin_id: None,
plugin_name: None,
})
}
+414 -3
Переглянути файл
@@ -199,6 +199,10 @@ pub struct AgentTask {
/// Per-session recovery / network auto-retry window override in minutes (`0` = Off; `None` = inherit global).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recovery_window_mins: Option<u32>,
/// Provenance metadata when this task was created or continued by an [`crate::automation::AgentAutomation`].
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub automation: Option<Box<crate::automation::AgentTaskAutomation>>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
@@ -454,11 +458,29 @@ pub struct AgentPrompt {
pub images: Vec<AgentImage>,
}
/// Provenance carried with a scheduled turn (`SameTask`, `Send Later`, or `/loop`), including
/// while queued behind a busy turn, so trust and approval ceilings are re-checked at dispatch.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ScheduledTurnMeta {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub permissions: Option<crate::automation::AutomationPermissionMode>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub extra_choices: Vec<AgentConfigChoice>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub automation_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_schedule_id: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentQueued {
pub id: String,
pub prompt: AgentPrompt,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(skip)]
pub scheduled: Option<ScheduledTurnMeta>,
}
/// A setting chosen for a new task, by [`AgentConfigOption::id`].
@@ -920,7 +942,7 @@ pub struct AgentModelCatalog {
}
/// Streamed to the window that subscribed (`AgentManager::subscribe_as`).
#[derive(Clone, Debug, Serialize, Type)]
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum AgentEvent {
/// A task was created or its metadata changed.
@@ -1018,6 +1040,14 @@ pub struct McpServer {
/// True when this Workspace server was added outside OpenIDEA and has not been approved yet.
#[serde(default)]
pub unapproved: bool,
/// Parent agent plugin ID when this server is live-projected from an enabled agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// Payload for creating or updating a user or workspace MCP server.
@@ -1051,8 +1081,8 @@ fn default_true() -> bool {
}
pub use ide_core::settings::{
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentProviderMemoryPolicy, AgentSkillMode,
AgentSkillPolicy, AutoMemoryMode,
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemorySettings, AgentPluginEntryPolicy, AgentPluginSettings,
AgentProviderMemoryPolicy, AgentSkillMode, AgentSkillPolicy, AutoMemoryMode,
};
/// Kind of discovered agent memory entry.
@@ -1165,6 +1195,14 @@ pub struct AgentMemoryEntry {
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
/// Parent agent plugin ID when this rule/instruction is live-projected from an enabled agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// A discovered memory entry paired with its resolved [`AgentMemoryMode`] and origin.
@@ -1337,6 +1375,14 @@ pub struct AgentSkill {
pub valid: bool,
/// What validation found (`name` mismatch, missing or over-long description…).
pub warnings: Vec<String>,
/// Parent agent plugin ID when this skill comes from an agent plugin bundle.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_id: Option<String>,
/// Display name of the parent agent plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub plugin_name: Option<String>,
}
/// A skill as Settings › Agents › Skills shows it: discovery plus the effective mode and
@@ -1398,6 +1444,371 @@ pub struct McpDiscoveredServer {
pub header_keys: Vec<String>,
}
/// Which workspace, user, or CLI store an agent plugin bundle was discovered in.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginSource {
/// `~/.copilot/installed-plugins/{<marketplace>,_direct}/*`.
#[default]
CopilotUser,
/// `~/.claude/plugins/installed_plugins.json` & `~/.claude/plugins/cache/*`.
ClaudeUser,
/// `~/.codex/plugins/cache/*`.
CodexUser,
/// `~/.gemini/extensions/*`.
GeminiUser,
}
/// Manifest format(s) recognized inside an agent plugin directory.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginFormat {
/// Vendor-neutral Agent Plugins 1.0 / 1.1 (`plugin.json` with `$schema`).
#[default]
AgentPluginsV1,
/// `.openidea/plugin.json`.
OpenIdea,
/// `.claude-plugin/plugin.json`.
Claude,
/// `.plugin/plugin.json`, `.github/plugin/plugin.json`, or legacy root `plugin.json`.
Copilot,
/// `.codex-plugin/plugin.json`.
Codex,
/// `gemini-extension.json`.
GeminiExtension,
}
/// Which policy layer decided an [`AgentPluginState::enabled`] status.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginOrigin {
/// Native harness configuration owns the enabled state.
#[default]
None,
/// Locked `Off` because the workspace is untrusted.
Trust,
/// Locked `Off` until executable capabilities (stdio MCP / lifecycle hooks) are approved.
Consent,
}
/// Data type of a plugin `userConfig` / `variables` / `settings` option.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AgentPluginConfigFieldKind {
#[default]
String,
Number,
Boolean,
Secret,
}
/// One configurable option declared by an agent plugin (`userConfig`, `variables`, or Gemini `settings`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginConfigField {
pub key: String,
pub title: String,
#[serde(default)]
pub description: String,
pub kind: AgentPluginConfigFieldKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub default_value: Option<String>,
#[serde(default)]
pub required: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub env_var: Option<String>,
/// Current non-sensitive value (always empty when `kind == Secret`).
#[serde(default)]
pub value: String,
/// True when a secret is stored in OS Keychain for this field.
#[serde(default)]
pub has_secret: bool,
}
/// Summary of components and executable capabilities bundled inside an agent plugin.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginCapabilities {
pub skill_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub skill_names: Vec<String>,
pub mcp_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub mcp_names: Vec<String>,
pub rule_count: u32,
pub subagent_count: u32,
pub command_count: u32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub hook_files: Vec<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub stdio_commands: Vec<String>,
#[serde(default)]
pub has_lsp: bool,
#[serde(default)]
pub has_canvas_or_app: bool,
/// Harnesses that have native non-portable components (hooks, subagents, canvases/apps, LSP) in this bundle.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub native_harnesses: Vec<String>,
/// Deterministic BLAKE3 hex digest of executable capabilities (`stdio_commands` + `hook_files` contents).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub capability_hash: Option<String>,
#[serde(default)]
pub requires_consent: bool,
}
/// One discovered agent plugin bundle on disk (or built-in).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPlugin {
pub id: String,
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub author: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub homepage: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repository: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub license: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
pub source: AgentPluginSource,
/// Scope this bundle is installed in. Native plugin folders and enablement config are
/// resolved relative to this scope.
pub scope: McpScope,
/// Workspace whose native configuration owns this row's enablement (workspace scope only).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub workspace_root: Option<IpcPath>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub also_in: Vec<AgentPluginSource>,
pub formats: Vec<AgentPluginFormat>,
pub root_path: IpcPath,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub manifest_path: Option<IpcPath>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub readme_path: Option<IpcPath>,
pub default_enabled: bool,
pub approx_tokens: u32,
pub capabilities: AgentPluginCapabilities,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub config_fields: Vec<AgentPluginConfigField>,
pub valid: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
}
/// Resolved agent plugin state paired with its policy origin and consent status.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginState {
pub plugin: AgentPlugin,
pub enabled: bool,
pub origin: AgentPluginOrigin,
/// True when executable stdio MCP / hook capabilities require user approval before enabling.
pub consent_required: bool,
}
/// Summary of a configured or repository-discovered plugin marketplace.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceInfo {
pub id: String,
pub name: String,
pub source: String,
pub scope: McpScope,
/// True when discovered from a harness-native marketplace/configuration file.
pub discovered: bool,
}
/// Full catalog returned to Settings › Agents › Plugins.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginCatalog {
pub plugins: Vec<AgentPluginState>,
pub marketplaces: Vec<AgentMarketplaceInfo>,
pub projected_skills: u32,
pub projected_mcp_servers: u32,
pub projected_rules: u32,
}
/// One installable plugin entry listed inside a marketplace or repository.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceCandidate {
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub author: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
/// Source spec to pass to preview (`"owner/repo[/subpath][@ref]"` or local directory path).
pub source_spec: String,
pub subpath: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub keywords: Vec<String>,
pub already_installed_user: bool,
pub already_installed_workspace: bool,
}
/// Result of browsing a marketplace (`owner/repo`, local marketplace path, or direct plugin repo).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentMarketplaceBrowseResult {
pub source: String,
pub marketplace_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub git_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub tree_sha: Option<String>,
pub candidates: Vec<AgentMarketplaceCandidate>,
}
/// Whether a previewed plugin can be installed for one harness, and where it is already installed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginInstallTarget {
pub harness: String,
pub supported: bool,
/// Why the harness cannot install this plugin.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub reason: Option<String>,
/// Whether this harness can enable the plugin for just one workspace.
pub workspace_supported: bool,
/// This harness already records the plugin for the user / for the current workspace.
pub installed_user: bool,
pub installed_workspace: bool,
/// The harness store already holds this plugin version's folder, so installing replaces it.
pub overwrite_required: bool,
}
/// Security and capability preview of an agent plugin bundle before installation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct AgentPluginPreview {
/// `"github"` or `"local"`.
pub source_kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub git_ref: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub tree_sha: Option<String>,
/// Pinned commit SHA from preview when `source_kind == "github"`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub commit_sha: Option<String>,
#[serde(default)]
pub subpath: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub local_path: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub marketplace_source: Option<String>,
pub name: String,
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub version: Option<String>,
pub description: String,
pub formats: Vec<AgentPluginFormat>,
pub capabilities: AgentPluginCapabilities,
pub files: Vec<crate::skill_installer::RemoteSkillFile>,
pub scan_warnings: Vec<crate::skill_installer::SkillScanWarning>,
/// Per-harness install eligibility and existing installs for this plugin and marketplace.
pub targets: Vec<AgentPluginInstallTarget>,
}
/// Request payload to install a previewed agent plugin into a selected harness's native plugin directory.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct InstallAgentPluginRequest {
/// `"github"` or `"local"`.
pub source_kind: String,
#[serde(default)]
#[specta(optional)]
pub owner: Option<String>,
#[serde(default)]
#[specta(optional)]
pub repo: Option<String>,
#[serde(default)]
#[specta(optional)]
pub git_ref: Option<String>,
/// Pinned root tree SHA from preview when `source_kind == "github"`.
#[serde(default)]
#[specta(optional)]
pub tree_sha: Option<String>,
/// Pinned commit SHA from preview when `source_kind == "github"`.
#[serde(default)]
#[specta(optional)]
pub commit_sha: Option<String>,
#[serde(default)]
pub subpath: String,
#[serde(default)]
#[specta(optional)]
pub local_path: Option<String>,
#[serde(default)]
#[specta(optional)]
pub marketplace: Option<String>,
#[serde(default)]
#[specta(optional)]
pub marketplace_source: Option<String>,
pub scope: McpScope,
/// Native harness the plugin is installed for (`claude`, `copilot`, `codex`, or `gemini`).
pub harness: String,
#[serde(default)]
pub approve_capabilities: bool,
/// The preview's `capabilityHash` the user approved; the install is refused if the installed
/// folder resolves to different executable capabilities.
#[serde(default)]
#[specta(optional)]
pub approved_capability_hash: Option<String>,
#[serde(default)]
pub confirm_warnings: bool,
#[serde(default)]
pub overwrite: bool,
}
/// Selection of one server from an external MCP configuration source to import.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
+31
Переглянути файл
@@ -1484,3 +1484,34 @@ async fn session_merges_skills_and_memory_into_claude_settings_and_add_dir_env()
"claude-md-and-agents-md"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn session_merges_memory_settings_without_plugin_dir_or_plugin_config_injection() {
let cli = replay_cli(load_fixture("simple"));
let (config, cwd) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let cwd_path = std::fs::canonicalize(cwd.path()).unwrap();
let h =
Harness::connect(cli.clone(), config.path().into(), config.path().join("pending"), cwd_path, Vec::new()).await;
let params = json!({
"cwd": h.cwd,
"mcpServers": [],
"_meta": {
"openidea": {
"memory": {
"claudeInstructionFiles": "claude-md-and-agents-md"
},
"plugins": { "activePlugins": ["azure", "linear@mkt"] }
}
}
});
h.request("session/new", params).await.unwrap();
let args = cli.launched.lock()[0].clone();
assert!(!args.iter().any(|a| a == "--plugin-dir"), "{args:?}");
let settings_idx = args.iter().position(|a| a == "--settings").expect("--settings flag");
let parsed: Value = serde_json::from_str(&args[settings_idx + 1]).unwrap();
assert_eq!(
parsed["pluginConfigs"]["cc-plugin-agents-md@builtin"]["options"]["instructionFiles"],
"claude-md-and-agents-md"
);
assert!(parsed["pluginConfigs"]["azure"].is_null());
}
+1 -5
Переглянути файл
@@ -25,11 +25,7 @@ use std::sync::Arc;
/// A path, or a name not found on `PATH`, is used as it is; a single match returns its
/// resolved path so Windows `PATHEXT` shims (`claude.cmd`, `codex.cmd`) start.
pub(crate) fn newest_install(command: &str) -> String {
let path = ide_core::process::host_var_os("PATH")
.or_else(|| ide_core::process::shell_env().find(|(k, _)| *k == "PATH").map(|(_, v)| v.to_owned()))
.unwrap_or_default();
// Windows: read afresh, so a tool the user installed since the IDE started is found too.
newest_install_in(command, &ide_core::process::with_user_path(&path))
newest_install_in(command, &ide_core::tool_path::search_path())
}
fn newest_install_in(command: &str, search: &std::ffi::OsStr) -> String {
File diff suppressed because it is too large. Load diff
+31 -11
Переглянути файл
@@ -114,7 +114,7 @@ impl ProviderSpec {
if !program.is_absolute() {
return self.login_hint.clone();
}
let search = ide_core::process::host_var_os("PATH").unwrap_or_default();
let search = ide_core::tool_path::search_path();
let builtin = builtin_spec(&self.id);
let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search));
render_login_hint(self, program, on_path.as_deref(), cfg!(windows))
@@ -623,7 +623,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
command_overridden: builtin.as_ref().is_some_and(|b| b.command != spec.command),
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed(&spec.command),
installed: installed_with_env(&spec.command, &spec.env),
can_sign_in: spec.can_sign_in(Path::new("."), None),
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
env: spec.env.iter().cloned().collect(),
@@ -1057,19 +1057,23 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
specs
}
/// Whether `command` resolves to an executable (a path, or a name on `PATH`).
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
#[cfg(test)]
pub(crate) fn installed(command: &str) -> bool {
installed_with_env(command, &[])
}
pub(crate) fn installed_with_env(command: &str, env: &[(String, String)]) -> bool {
let p = Path::new(command);
if p.components().count() > 1 {
if p.components().count() > 1 || p.is_absolute() {
return is_executable(p);
}
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[] };
std::env::var_os("PATH").is_some_and(|path| {
std::env::split_paths(&path).any(|dir| {
let c = dir.join(command);
is_executable(&c) || exts.iter().any(|e| is_executable(&c.with_extension(e)))
})
})
if let Some((_, path)) = env.iter().find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
&& ide_core::process::find_executable(command, std::ffi::OsStr::new(path)).is_some()
{
return true;
}
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
}
fn is_executable(p: &Path) -> bool {
@@ -1326,6 +1330,22 @@ mod tests {
assert!(installed("sh"));
}
#[test]
fn installed_with_env_resolves_executables_on_provider_path() {
let dir = tempfile::tempdir().unwrap();
let name = if cfg!(windows) { "fake-agent.cmd" } else { "fake-agent" };
let exe = dir.path().join(name);
std::fs::write(&exe, "").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert!(!installed("fake-agent"));
let env = vec![("PATH".to_owned(), dir.path().to_string_lossy().into_owned())];
assert!(installed_with_env("fake-agent", &env));
}
#[test]
fn set_builtin_env_writes_and_clears_the_environment() {
let dir = tempfile::tempdir().unwrap();
+5 -3
Переглянути файл
@@ -320,7 +320,7 @@ fn is_builtin(id: &str) -> bool {
}
fn on_path(command: &str) -> bool {
which::which(command).is_ok()
ide_core::process::find_executable(command, &ide_core::tool_path::search_path()).is_some()
}
/// `1.10.0` > `1.9.2`; a release is newer than its pre-releases.
@@ -708,7 +708,8 @@ fn install_npm(
emit: Emit,
) -> IdeResult<PathBuf> {
let (name, _) = split_npm_spec(&p.package);
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
let npm = ide_core::process::find_executable("npm", &ide_core::tool_path::search_path())
.ok_or_else(|| IdeError::unavailable(format!("npm is required to install {name}")))?;
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
}
@@ -789,7 +790,8 @@ fn install_uv(
_ => format!("{name}=={}", entry.version),
};
check_spec(&spec)?;
let uv = which::which("uv").map_err(|_| IdeError::unavailable(format!("uv is required to install {name}")))?;
let uv = ide_core::process::find_executable("uv", &ide_core::tool_path::search_path())
.ok_or_else(|| IdeError::unavailable(format!("uv is required to install {name}")))?;
let bin = dir.join("bin");
let mut cmd = Command::new(uv);
cmd.args(["tool", "install", "--force"])
+1 -16
Переглянути файл
@@ -185,22 +185,7 @@ pub(crate) fn recorder(out: PathBuf) -> Connector {
let file = Arc::new(Mutex::new(String::new()));
let connections = Arc::new(Mutex::new(0u32));
Arc::new(move |spec, cwd, client, on_stderr| {
let program = {
let path = Path::new(&spec.command);
if path.components().count() > 1 || path.is_absolute() {
path.to_path_buf()
} else {
let search = spec
.env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
ide_core::process::find_executable(&spec.command, &search).unwrap_or_else(|| path.to_path_buf())
}
};
let program = ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env);
let mut cmd = tokio::process::Command::new(&program);
ide_core::process::prepare(cmd.as_std_mut());
let mut child = cmd
+517 -47
Переглянути файл
@@ -163,6 +163,15 @@ pub struct RepoRef<'a> {
pub trait SkillSourceFetcher: Send + Sync {
fn default_branch(&self, owner: &str, repo: &str, cancel: &CancellationToken) -> IdeResult<String>;
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String>;
/// The root tree SHA recorded in commit `commit_sha`.
fn git_commit_tree_sha(
&self,
owner: &str,
repo: &str,
commit_sha: &str,
cancel: &CancellationToken,
) -> IdeResult<String>;
fn git_tree(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<GitTree>;
fn read_blob(
&self,
@@ -238,6 +247,63 @@ impl SkillSourceFetcher for GitHubHttpFetcher {
.map_err(|e| IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid Git tree: {e}")))
}
fn git_commit_sha(&self, target: RepoRef<'_>, cancel: &CancellationToken) -> IdeResult<String> {
#[derive(Deserialize)]
struct CommitMeta {
sha: String,
}
let RepoRef { owner, repo, git_ref } = target;
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
validate_git_ref(git_ref)?;
let encoded_ref = encode_url_segment(git_ref);
let url = format!("https://api.github.com/repos/{owner}/{repo}/commits/{encoded_ref}");
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
let meta: CommitMeta = serde_json::from_str(&body).map_err(|e| {
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{git_ref}: invalid GitHub commit: {e}"))
})?;
if !is_git_object_id(&meta.sha) {
return Err(IdeError::new(
ErrorKind::Protocol,
format!("{owner}/{repo}@{git_ref}: invalid GitHub commit SHA"),
));
}
Ok(meta.sha)
}
fn git_commit_tree_sha(
&self,
owner: &str,
repo: &str,
commit_sha: &str,
cancel: &CancellationToken,
) -> IdeResult<String> {
#[derive(Deserialize)]
struct TreeRef {
sha: String,
}
#[derive(Deserialize)]
struct GitCommit {
tree: TreeRef,
}
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
if !is_git_object_id(commit_sha) {
return Err(IdeError::invalid("Invalid commit SHA"));
}
let url = format!("https://api.github.com/repos/{owner}/{repo}/git/commits/{commit_sha}");
let body = self.get_github_json(&url, MAX_REPO_META_BYTES, cancel)?;
let commit: GitCommit = serde_json::from_str(&body).map_err(|e| {
IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid Git commit: {e}"))
})?;
if !is_git_object_id(&commit.tree.sha) {
return Err(IdeError::new(ErrorKind::Protocol, format!("{owner}/{repo}@{commit_sha}: invalid tree SHA")));
}
Ok(commit.tree.sha)
}
fn read_blob(
&self,
target: RepoRef<'_>,
@@ -616,6 +682,17 @@ fn sanitize_repo_as_skill_name(repo: &str) -> String {
out.trim_matches('-').to_owned()
}
pub(crate) struct FetchedSubtree {
pub tree_sha: String,
pub normalized_subpath: String,
pub files: Vec<RemoteSkillFile>,
pub scan_warnings: Vec<SkillScanWarning>,
/// `(relative_path, bytes, executable)` for safe non-symlink files to write on disk.
pub regular_files: Vec<(PathBuf, Vec<u8>, bool)>,
/// `(relative_path, relative_target)` for safe internal symlinks.
pub in_root_symlinks: Vec<(PathBuf, PathBuf)>,
}
struct PreparedSkillBundle {
tree_sha: String,
skill_name: String,
@@ -629,14 +706,19 @@ struct PreparedSkillBundle {
in_root_symlinks: Vec<(PathBuf, PathBuf)>,
}
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
fn fetch_and_scan_bundle(
/// Fetches `target`'s tree (or exactly `pinned_tree_sha` when set) and scans `subpath` with hardened
/// symlink-graph, executable-script, and hidden-Unicode checks.
#[allow(clippy::too_many_arguments)]
pub(crate) fn fetch_and_scan_subtree(
fetcher: &dyn SkillSourceFetcher,
target: RepoRef<'_>,
subpath: &str,
pinned_tree_sha: Option<&str>,
max_files: usize,
max_subtree_bytes: u64,
noun: &str,
cancel: &CancellationToken,
) -> IdeResult<PreparedSkillBundle> {
) -> IdeResult<FetchedSubtree> {
let RepoRef { owner, repo, git_ref } = target;
validate_repo_coord(owner, "owner")?;
validate_repo_coord(repo, "repository")?;
@@ -646,9 +728,8 @@ fn fetch_and_scan_bundle(
let tree = match pinned_tree_sha {
Some(sha) => {
if !is_git_object_id(sha) {
return Err(IdeError::invalid("Preview the skill again before installing it"));
return Err(IdeError::invalid(format!("Preview the {noun} again before installing it")));
}
// The Git trees API accepts a tree SHA in place of a ref.
let tree = fetcher.git_tree(RepoRef { owner, repo, git_ref: sha }, cancel)?;
if !tree.sha.eq_ignore_ascii_case(sha) {
return Err(IdeError::new(
@@ -660,6 +741,14 @@ fn fetch_and_scan_bundle(
}
None => fetcher.git_tree(target, cancel)?,
};
if tree.truncated {
return Err(IdeError::new(
ErrorKind::Protocol,
format!(
"{owner}/{repo}@{git_ref}: GitHub returned a truncated file listing; the {noun} cannot be verified"
),
));
}
let prefix = if normalized_subpath.is_empty() { String::new() } else { format!("{normalized_subpath}/") };
let subtree_entries: Vec<&GitTreeEntry> = tree
@@ -672,27 +761,32 @@ fn fetch_and_scan_bundle(
if subtree_entries.is_empty() {
return Err(IdeError::not_found(format!(
"Skill path {:?} was not found in {owner}/{repo}@{git_ref}",
"{} path {:?} was not found in {owner}/{repo}@{git_ref}",
capitalize(noun),
normalized_subpath
)));
}
if subtree_entries.len() > MAX_SKILL_FILES {
if subtree_entries.len() > max_files {
return Err(IdeError::invalid(format!(
"Skill exceeds maximum of {MAX_SKILL_FILES} files ({} found)",
"{} exceeds maximum of {max_files} files ({} found)",
capitalize(noun),
subtree_entries.len()
)));
}
let declared_total: u64 = subtree_entries.iter().map(|e| e.size.unwrap_or(0)).sum();
if declared_total > MAX_SKILL_SUBTREE_BYTES {
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
if declared_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
let mut files = Vec::with_capacity(subtree_entries.len());
let mut scan_warnings = Vec::new();
let mut regular_files = Vec::new();
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
let mut skill_markdown: Option<String> = None;
let mut actual_total = 0u64;
for entry in subtree_entries {
@@ -709,12 +803,16 @@ fn fetch_and_scan_bundle(
target,
&entry.path,
&entry.sha,
MAX_SINGLE_BLOB_BYTES.min(MAX_SKILL_SUBTREE_BYTES - actual_total),
MAX_SINGLE_BLOB_BYTES.min(max_subtree_bytes - actual_total),
cancel,
)?;
actual_total = actual_total.saturating_add(bytes.len() as u64);
if actual_total > MAX_SKILL_SUBTREE_BYTES {
return Err(IdeError::invalid(format!("Skill exceeds {} MiB size cap", MAX_SKILL_SUBTREE_BYTES >> 20)));
if actual_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
if is_symlink {
@@ -748,11 +846,15 @@ fn fetch_and_scan_bundle(
if let Ok(text) = std::str::from_utf8(&bytes) {
scan_hidden_unicode(rel_str, text, &mut scan_warnings);
if rel_str == "SKILL.md" {
skill_markdown = Some(text.to_owned());
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
for tool in frontmatter_shell_tools(text) {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: rel_str.to_owned(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
});
}
}
} else if rel_str == "SKILL.md" {
return Err(IdeError::invalid("SKILL.md is not valid UTF-8 text"));
}
files.push(RemoteSkillFile {
@@ -767,13 +869,12 @@ fn fetch_and_scan_bundle(
files.sort_by(|a, b| a.path.cmp(&b.path));
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
// Symlinks are judged together: one link may point through another, and an entry placed beneath
// a symlink would be written wherever that link points.
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
if let Some(link) = graph.symlink_ancestor(path) {
return Err(IdeError::invalid(format!(
"Skill entry {:?} is inside symlink {link:?}; the repository tree is malformed",
"{} entry {:?} is inside symlink {link:?}; the repository tree is malformed",
capitalize(noun),
path.display().to_string()
)));
}
@@ -786,26 +887,65 @@ fn fetch_and_scan_bundle(
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::OutOfRootSymlink,
file: rel_str,
message: format!("Symlink target {target_raw:?} leaves the skill folder (omitted on install)"),
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
});
}
}
in_root_symlinks.sort();
let Some(skill_markdown) = skill_markdown else {
return Err(IdeError::invalid("Selected folder does not contain a regular SKILL.md file"));
};
Ok(FetchedSubtree { tree_sha: tree.sha, normalized_subpath, files, scan_warnings, regular_files, in_root_symlinks })
}
let folder_hint = normalized_subpath
fn capitalize(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
/// Fetches `target`'s tree (or exactly the tree `pinned_tree_sha` when set) and scans the `subpath` subtree.
fn fetch_and_scan_bundle(
fetcher: &dyn SkillSourceFetcher,
target: RepoRef<'_>,
subpath: &str,
pinned_tree_sha: Option<&str>,
cancel: &CancellationToken,
) -> IdeResult<PreparedSkillBundle> {
let RepoRef { repo, .. } = target;
let mut sub = fetch_and_scan_subtree(
fetcher,
target,
subpath,
pinned_tree_sha,
MAX_SKILL_FILES,
MAX_SKILL_SUBTREE_BYTES,
"skill",
cancel,
)?;
let skill_bytes = sub
.regular_files
.iter()
.find(|(p, _, _)| p == Path::new("SKILL.md"))
.map(|(_, b, _)| b.as_slice())
.ok_or_else(|| IdeError::invalid("Selected folder does not contain a regular SKILL.md file"))?;
let skill_markdown =
std::str::from_utf8(skill_bytes).map_err(|_| IdeError::invalid("SKILL.md is not valid UTF-8 text"))?.to_owned();
let folder_hint = sub
.normalized_subpath
.rsplit('/')
.next()
.filter(|s| !s.is_empty())
.map(str::to_owned)
.unwrap_or_else(|| sanitize_repo_as_skill_name(repo));
// Strip any `SKILL.md` shell-tool warnings already collected so `parse_skill_markdown_metadata` emits them in order.
sub.scan_warnings.retain(|w| !(w.kind == SkillScanWarningKind::AllowedToolsShell && w.file == "SKILL.md"));
let parsed_meta = parse_skill_markdown_metadata(&folder_hint, &skill_markdown)?;
for tool in &parsed_meta.shell_tools {
scan_warnings.push(SkillScanWarning {
sub.scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: "SKILL.md".into(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
@@ -813,14 +953,14 @@ fn fetch_and_scan_bundle(
}
Ok(PreparedSkillBundle {
tree_sha: tree.sha,
tree_sha: sub.tree_sha,
skill_name: parsed_meta.name,
description: parsed_meta.description,
skill_markdown,
files,
scan_warnings,
regular_files,
in_root_symlinks,
files: sub.files,
scan_warnings: sub.scan_warnings,
regular_files: sub.regular_files,
in_root_symlinks: sub.in_root_symlinks,
})
}
@@ -1140,6 +1280,33 @@ fn create_parent_dirs_no_follow(root: &Path, rel: &Path) -> IdeResult<()> {
Ok(())
}
/// Creates `target` below the existing `anchor` (the home or project folder) without following a
/// symlink in any directory between them, the harness store root included.
fn create_dirs_below_anchor(anchor: &Path, target: &Path) -> IdeResult<()> {
if !anchor.is_dir() {
return Err(IdeError::not_found(format!("{} does not exist", anchor.display())));
}
let rel = target
.strip_prefix(anchor)
.map_err(|_| IdeError::invalid(format!("{} is outside {}", target.display(), anchor.display())))?;
let mut dir = anchor.to_path_buf();
for component in rel.components() {
if !matches!(component, Component::Normal(_)) {
return Err(IdeError::invalid(format!("{} is not a plain path below the store", target.display())));
}
dir.push(component);
match std::fs::symlink_metadata(&dir) {
Ok(meta) if meta.is_dir() => {}
Ok(_) => {
return Err(IdeError::invalid(format!("{} passes through a symlink or file", dir.display())));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => std::fs::create_dir(&dir)?,
Err(e) => return Err(e.into()),
}
}
Ok(())
}
/// Whether the symlink at `link` resolves strictly inside `root` (canonical), following links on disk.
/// Components that do not exist are resolved lexically.
#[cfg(unix)]
@@ -1220,15 +1387,16 @@ pub fn install_skill(
workspace_root: Option<&Path>,
cancel: &CancellationToken,
) -> IdeResult<PathBuf> {
let target_root = match req.scope {
// Anchored at the home or project folder: nothing below it may be a symlink, store included.
let (anchor, target_root) = match req.scope {
McpScope::User => {
let home = user_home.ok_or_else(|| IdeError::unavailable("Cannot locate user home directory"))?;
home.join(".agents").join("skills")
(home.to_path_buf(), home.join(".agents").join("skills"))
}
McpScope::Workspace => {
let ws = workspace_root
.ok_or_else(|| IdeError::invalid("Open a trusted project to install workspace skills"))?;
ws.join(".agents").join("skills")
(ws.to_path_buf(), ws.join(".agents").join("skills"))
}
};
@@ -1245,20 +1413,60 @@ pub fn install_skill(
));
}
std::fs::create_dir_all(&target_root)?;
let final_dir = target_root.join(&bundle.skill_name);
if final_dir.exists() && !req.overwrite {
write_staged_subtree(
&anchor,
&target_root,
&bundle.skill_name,
req.overwrite,
"Skill",
&bundle.regular_files,
&bundle.in_root_symlinks,
&[],
)
}
/// Atomically writes `regular_files`, `in_root_symlinks`, and `extra_files` into a staging folder
/// under `target_root`, verifies created symlinks stay inside the folder, and swaps into `<target_root>/<folder_name>`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn write_staged_subtree(
anchor: &Path,
target_root: &Path,
folder_name: &str,
overwrite: bool,
noun_cap: &str,
regular_files: &[(PathBuf, Vec<u8>, bool)],
in_root_symlinks: &[(PathBuf, PathBuf)],
extra_files: &[(&str, &[u8])],
) -> IdeResult<PathBuf> {
create_dirs_below_anchor(anchor, target_root)?;
if folder_name.is_empty() || !Path::new(folder_name).components().all(|c| matches!(c, Component::Normal(_))) {
return Err(IdeError::invalid(format!("Invalid {} folder name", noun_cap.to_ascii_lowercase())));
}
let final_dir = target_root.join(folder_name);
let existing = match std::fs::symlink_metadata(&final_dir) {
Ok(meta) if meta.is_dir() => true,
Ok(_) => {
return Err(IdeError::invalid(format!(
"{} is a symlink or file, not a {} folder",
final_dir.display(),
noun_cap.to_ascii_lowercase()
)));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
Err(e) => return Err(e.into()),
};
if existing && !overwrite {
return Err(IdeError::new(
ErrorKind::AlreadyExists,
format!("Skill `{}` is already installed in {}", bundle.skill_name, target_root.display()),
format!("{noun_cap} `{folder_name}` is already installed in {}", target_root.display()),
));
}
let nonce = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
let staging = target_root.join(format!(".staging-{}-{nonce}-{}", bundle.skill_name, std::process::id()));
let staging = target_root.join(format!(".staging-{folder_name}-{nonce}-{}", std::process::id()));
let write_res = (|| -> IdeResult<()> {
std::fs::create_dir_all(&staging)?;
for (rel_path, bytes, is_exec) in &bundle.regular_files {
for (rel_path, bytes, is_exec) in regular_files {
create_parent_dirs_no_follow(&staging, rel_path)?;
let dest = staging.join(rel_path);
std::fs::write(&dest, bytes)?;
@@ -1270,7 +1478,12 @@ pub fn install_skill(
#[cfg(not(unix))]
let _ = is_exec;
}
for (rel_link, target) in &bundle.in_root_symlinks {
for (rel_str, bytes) in extra_files {
let rel_path = validate_rel_skill_file(rel_str)?;
create_parent_dirs_no_follow(&staging, &rel_path)?;
std::fs::write(staging.join(&rel_path), bytes)?;
}
for (rel_link, target) in in_root_symlinks {
create_parent_dirs_no_follow(&staging, rel_link)?;
let dest = staging.join(rel_link);
#[cfg(unix)]
@@ -1288,17 +1501,18 @@ pub fn install_skill(
#[cfg(unix)]
{
let root = std::fs::canonicalize(&staging)?;
for (rel_link, _) in &bundle.in_root_symlinks {
for (rel_link, _) in in_root_symlinks {
if !link_resolves_inside(&root, &staging.join(rel_link)) {
return Err(IdeError::invalid(format!(
"Symlink {:?} leaves the skill folder",
rel_link.display().to_string()
"Symlink {:?} leaves the {} folder",
rel_link.display().to_string(),
noun_cap.to_ascii_lowercase()
)));
}
}
}
let backup = if final_dir.exists() {
let bak = target_root.join(format!(".old-{}-{nonce}", bundle.skill_name));
let backup = if existing {
let bak = target_root.join(format!(".old-{folder_name}-{nonce}"));
std::fs::rename(&final_dir, &bak)?;
Some(bak)
} else {
@@ -1323,6 +1537,179 @@ pub fn install_skill(
Ok(final_dir)
}
/// Scans a local directory on disk with the same symlink-graph, executable-script, and hidden-Unicode
/// checks used for remote GitHub subtrees.
/// Content digest of a scanned local folder, used to pin a local preview to its install.
fn local_subtree_digest(regular_files: &[(PathBuf, Vec<u8>, bool)], symlinks: &[(PathBuf, PathBuf)]) -> String {
let mut hasher = blake3::Hasher::new();
hasher.update(b"openidea-local-subtree-v1\0");
for (path, bytes, executable) in regular_files {
hasher.update(b"f\0");
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(&[0, u8::from(*executable)]);
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}
for (path, target) in symlinks {
hasher.update(b"l\0");
hasher.update(path.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(b"\0");
hasher.update(target.to_string_lossy().replace('\\', "/").as_bytes());
hasher.update(b"\0");
}
format!("local-blake3:{}", hasher.finalize().to_hex())
}
pub(crate) fn scan_local_subtree(
dir: &Path,
max_files: usize,
max_subtree_bytes: u64,
noun: &str,
) -> IdeResult<FetchedSubtree> {
if !dir.is_dir() {
return Err(IdeError::not_found(format!("Directory {} does not exist", dir.display())));
}
let mut files = Vec::new();
let mut scan_warnings = Vec::new();
let mut regular_files = Vec::new();
let mut symlinks: Vec<(PathBuf, String, String)> = Vec::new();
let mut actual_total = 0u64;
let mut stack = vec![(dir.to_path_buf(), String::new())];
while let Some((cur_dir, rel_prefix)) = stack.pop() {
let mut entries: Vec<_> = std::fs::read_dir(&cur_dir)?.filter_map(Result::ok).collect();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let name = entry.file_name();
let Some(name_str) = name.to_str() else {
return Err(IdeError::invalid(format!(
"{} contains a file name that is not valid UTF-8: {}",
capitalize(noun),
entry.path().display()
)));
};
if name_str == ".git" || name_str == "node_modules" || name_str == "target" {
continue;
}
let rel_str = if rel_prefix.is_empty() { name_str.to_owned() } else { format!("{rel_prefix}/{name_str}") };
let rel_path = validate_rel_skill_file(&rel_str)?;
let full = entry.path();
let meta = std::fs::symlink_metadata(&full)?;
if (meta.file_type().is_symlink() || meta.file_type().is_file())
&& regular_files.len() + symlinks.len() >= max_files
{
return Err(IdeError::invalid(format!("{} exceeds maximum of {max_files} files", capitalize(noun))));
}
if meta.file_type().is_symlink() {
let target_raw = std::fs::read_link(&full)?.to_string_lossy().replace('\\', "/");
symlinks.push((rel_path, rel_str.clone(), target_raw));
files.push(RemoteSkillFile { path: rel_str, size: 0, executable: false, symlink: true });
continue;
}
if meta.file_type().is_dir() {
stack.push((full, rel_str));
continue;
}
if !meta.file_type().is_file() {
continue;
}
if meta.len() > MAX_SINGLE_BLOB_BYTES {
return Err(IdeError::invalid(format!(
"File {rel_str:?} exceeds {} MiB size cap",
MAX_SINGLE_BLOB_BYTES >> 20
)));
}
let bytes = std::fs::read(&full)?;
actual_total = actual_total.saturating_add(bytes.len() as u64);
if actual_total > max_subtree_bytes {
return Err(IdeError::invalid(format!(
"{} exceeds {} MiB size cap",
capitalize(noun),
max_subtree_bytes >> 20
)));
}
#[cfg(unix)]
let is_exec_mode = {
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode() & 0o111 != 0
};
#[cfg(not(unix))]
let is_exec_mode = false;
let has_shebang = bytes.starts_with(b"#!");
let is_script_path = is_executable_or_script_path(&rel_path);
if is_exec_mode || has_shebang || is_script_path {
let reason = if is_exec_mode {
"executable file mode"
} else if has_shebang {
"script with `#!` interpreter header"
} else {
"bundled script or native binary"
};
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::ExecutableScript,
file: rel_str.clone(),
message: format!("Contains {reason}"),
});
}
if let Ok(text) = std::str::from_utf8(&bytes) {
scan_hidden_unicode(&rel_str, text, &mut scan_warnings);
if rel_str == "SKILL.md" || rel_str.ends_with("/SKILL.md") {
for tool in frontmatter_shell_tools(text) {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::AllowedToolsShell,
file: rel_str.clone(),
message: format!("`allowed-tools` grants shell/command execution (`{tool}`)"),
});
}
}
}
files.push(RemoteSkillFile {
path: rel_str,
size: bytes.len() as u64,
executable: is_exec_mode || has_shebang,
symlink: false,
});
regular_files.push((rel_path, bytes, is_exec_mode));
}
}
files.sort_by(|a, b| a.path.cmp(&b.path));
regular_files.sort_by(|a, b| a.0.cmp(&b.0));
let graph = SymlinkGraph::new(symlinks.iter().map(|(path, _, target)| (path.as_path(), target.as_str())));
for path in regular_files.iter().map(|(p, _, _)| p).chain(symlinks.iter().map(|(p, _, _)| p)) {
if let Some(link) = graph.symlink_ancestor(path) {
return Err(IdeError::invalid(format!(
"{} entry {:?} is inside symlink {link:?}",
capitalize(noun),
path.display().to_string()
)));
}
}
let mut in_root_symlinks = Vec::new();
for (rel_path, rel_str, target_raw) in symlinks {
if graph.stays_inside(&rel_path, &target_raw) {
in_root_symlinks.push((rel_path, PathBuf::from(target_raw)));
} else {
scan_warnings.push(SkillScanWarning {
kind: SkillScanWarningKind::OutOfRootSymlink,
file: rel_str,
message: format!("Symlink target {target_raw:?} leaves the {noun} folder (omitted on install)"),
});
}
}
in_root_symlinks.sort();
Ok(FetchedSubtree {
tree_sha: local_subtree_digest(&regular_files, &in_root_symlinks),
normalized_subpath: String::new(),
files,
scan_warnings,
regular_files,
in_root_symlinks,
})
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1374,6 +1761,25 @@ mod tests {
.cloned()
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
}
fn git_commit_sha(&self, target: RepoRef<'_>, _cancel: &CancellationToken) -> IdeResult<String> {
self.trees
.get(target.git_ref)
.map(|_| git_blob_id(format!("commit:{}", target.git_ref).as_bytes()))
.ok_or_else(|| IdeError::not_found(format!("unknown ref {}", target.git_ref)))
}
fn git_commit_tree_sha(
&self,
_owner: &str,
_repo: &str,
commit_sha: &str,
_cancel: &CancellationToken,
) -> IdeResult<String> {
self.trees
.iter()
.find(|(git_ref, _)| git_blob_id(format!("commit:{git_ref}").as_bytes()) == commit_sha)
.map(|(_, tree)| tree.sha.clone())
.ok_or_else(|| IdeError::not_found(format!("unknown commit {commit_sha}")))
}
fn read_blob(
&self,
@@ -1440,7 +1846,9 @@ mod tests {
let cancel = CancellationToken::new();
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let ws = tmp.path().join("ws");
std::fs::create_dir_all(&ws).unwrap();
// Bare `owner/repo` lists both skills; `owner/repo@clean-skill` falls back from ref lookup to skill filter!
let all = browse_skills(&fetcher, "acme/skills", &cancel).unwrap();
@@ -1796,4 +2204,66 @@ mod tests {
.unwrap();
assert!(dest.join("SKILL.md").is_file());
}
#[cfg(unix)]
#[test]
fn local_scan_counts_symlinks_toward_the_file_cap() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("SKILL.md"), "x").unwrap();
for i in 0..3 {
std::os::unix::fs::symlink("SKILL.md", tmp.path().join(format!("link-{i}"))).unwrap();
}
let Err(err) = scan_local_subtree(tmp.path(), 3, 1 << 20, "plugin") else { panic!("symlinks must count") };
assert!(err.to_string().contains("maximum of 3 files"), "{err}");
}
#[test]
fn truncated_tree_listings_are_rejected() {
let mut fetcher = FakeFetcher::new();
fetcher.add_tree("main", vec![("skills/a/SKILL.md", "100644", b"---\nname: a\ndescription: a\n---\n")]);
fetcher.trees.get_mut("main").unwrap().truncated = true;
let cancel = CancellationToken::new();
let target = RepoRef { owner: "o", repo: "r", git_ref: "main" };
let Err(err) = fetch_and_scan_subtree(&fetcher, target, "skills/a", None, 10, 1 << 20, "skill", &cancel) else {
panic!("a truncated listing cannot be verified")
};
assert!(err.to_string().contains("truncated"), "{err}");
}
#[cfg(unix)]
#[test]
fn staged_installs_do_not_follow_symlinks_below_the_store() {
let tmp = tempfile::tempdir().unwrap();
let store = tmp.path().join("store");
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&store).unwrap();
std::fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(&outside, store.join("mkt")).unwrap();
let files = vec![(PathBuf::from("plugin.json"), b"{}".to_vec(), false)];
let Err(err) = write_staged_subtree(&store, &store.join("mkt"), "plugin", false, "Plugin", &files, &[], &[])
else {
panic!("a symlinked marketplace folder must not be written through")
};
assert!(err.to_string().contains("symlink"), "{err}");
assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing was written outside the store");
// The store root itself (`<home>/.claude/plugins` → elsewhere) is checked as well.
let home = tmp.path().join("home");
std::fs::create_dir_all(home.join(".claude")).unwrap();
std::os::unix::fs::symlink(&outside, home.join(".claude/plugins")).unwrap();
let store_root = home.join(".claude/plugins/cache/mkt");
let Err(err) = write_staged_subtree(&home, &store_root, "plugin", false, "Plugin", &files, &[], &[]) else {
panic!("a symlinked store root must not be written through")
};
assert!(err.to_string().contains("symlink"), "{err}");
assert!(std::fs::read_dir(&outside).unwrap().next().is_none());
std::fs::create_dir_all(store.join("real")).unwrap();
std::os::unix::fs::symlink(&outside, store.join("real/plugin")).unwrap();
let Err(err) = write_staged_subtree(&store, &store.join("real"), "plugin", true, "Plugin", &files, &[], &[])
else {
panic!("an existing symlinked plugin folder must not be replaced through")
};
assert!(err.to_string().contains("symlink"), "{err}");
}
}
+34 -82
Переглянути файл
@@ -275,12 +275,27 @@ pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<Ag
}
/// [`discover_skills_in`] plus the `<dir>` skill folders contributed by enabled OpenIDEA
/// plugins (`[[contributes.skills]]`). Workspace and user skills take precedence on a name
/// clash; a plugin skill is never silently renamed.
/// plugins (`[[contributes.skills]]`) and unified agent plugin bundles (`plugins.rs`).
/// Workspace and user skills take precedence on a name clash; a plugin skill is never silently renamed.
pub fn discover_skills_with_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
) -> Vec<AgentSkill> {
let default_policy = crate::plugins::PluginsPolicy { workspace_roots: workspaces.to_vec(), ..Default::default() };
let states =
crate::plugins::resolve_plugins(crate::plugins::discover_plugins(workspaces, home), &default_policy, None);
let projected = crate::plugins::projected_skill_roots(&states, None);
discover_skills_with_agent_plugins(workspaces, home, plugin_skill_dirs, &projected)
}
/// Discovers skills across `workspaces`, `home`, OpenIDEA IDE-plugin skill folders (`plugin_skill_dirs`),
/// and resolved agent plugin bundle roots (`agent_plugin_roots`).
pub fn discover_skills_with_agent_plugins(
workspaces: &[PathBuf],
home: Option<&Path>,
plugin_skill_dirs: &[PathBuf],
agent_plugin_roots: &[crate::plugins::ProjectedSkillRoot],
) -> Vec<AgentSkill> {
let mut out: Vec<AgentSkill> = Vec::new();
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
@@ -338,9 +353,19 @@ pub fn discover_skills_with_plugins(
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
push_skill(parse_skill_file(dir, &folder, &text, AgentSkillSource::Plugin));
}
if let Some(home) = home {
for (root, source) in copilot_installed_plugin_roots(&home.join(".copilot")) {
for skill in skills_of(&root, source) {
for proj in agent_plugin_roots {
if proj.dir.join("SKILL.md").is_file() && proj.dir.file_name().and_then(|s| s.to_str()) != Some("skills") {
let Some(folder) = file_name(&proj.dir) else { continue };
if let Ok(text) = std::fs::read_to_string(proj.dir.join("SKILL.md")) {
let mut skill = parse_skill_file(&proj.dir, &folder, &text, proj.source);
skill.plugin_id = Some(proj.plugin_id.clone());
skill.plugin_name = Some(proj.plugin_name.clone());
push_skill(skill);
}
} else {
for mut skill in skills_of(&proj.dir, proj.source) {
skill.plugin_id = Some(proj.plugin_id.clone());
skill.plugin_name = Some(proj.plugin_name.clone());
push_skill(skill);
}
}
@@ -388,83 +413,6 @@ fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
out
}
/// Discovers skill roots inside `~/.copilot/installed-plugins`, supporting both Copilot CLI's
/// 2-level `<marketplace-or-_direct>/<plugin>` layout (and `config.json` `installedPlugins`
/// enablement) and flat 1-level `<plugin>` folders.
fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkillSource)> {
let mut disabled_paths: HashSet<PathBuf> = HashSet::new();
let mut plugin_dirs: Vec<PathBuf> = Vec::new();
let mut seen_dirs: HashSet<PathBuf> = HashSet::new();
let mut push_plugin = |dir: PathBuf, disabled: &HashSet<PathBuf>| {
if !dir.is_dir() {
return;
}
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
if disabled.contains(&canon) || !seen_dirs.insert(canon) {
return;
}
plugin_dirs.push(dir);
};
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text))
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
{
for entry in installed {
let Some(raw_cache) = entry.get("cache_path").and_then(serde_json::Value::as_str).map(str::trim) else {
continue;
};
if raw_cache.is_empty() {
continue;
}
let dir =
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
if entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(false) {
disabled_paths.insert(dunce::canonicalize(&dir).unwrap_or(dir));
} else {
push_plugin(dir, &disabled_paths);
}
}
}
let plugins_root = copilot_dir.join("installed-plugins");
for entry in sorted(&plugins_root) {
if !entry.is_dir() {
continue;
}
if looks_like_plugin_dir(&entry) {
push_plugin(entry, &disabled_paths);
} else {
// 2-level `<marketplace>/<plugin>` or `_direct/<plugin>`.
for sub in sorted(&entry) {
if sub.is_dir() {
push_plugin(sub, &disabled_paths);
}
}
}
}
let mut roots = Vec::new();
for plugin in plugin_dirs {
let skills_sub = plugin.join("skills");
if skills_sub.is_dir() {
roots.push((skills_sub, AgentSkillSource::CopilotUser));
} else {
roots.push((plugin, AgentSkillSource::CopilotUser));
}
}
roots
}
fn looks_like_plugin_dir(dir: &Path) -> bool {
dir.join("skills").is_dir()
|| dir.join("plugin.json").is_file()
|| dir.join(".plugin").is_dir()
|| dir.join(".claude-plugin").is_dir()
|| dir.join(".cursor-plugin").is_dir()
|| dir.join("SKILL.md").is_file()
}
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
/// category folders, validated.
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
@@ -544,6 +492,8 @@ fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSour
paths,
valid: warnings.is_empty(),
warnings,
plugin_id: None,
plugin_name: None,
}
}
@@ -1070,6 +1020,8 @@ mod tests {
paths: Vec::new(),
valid: true,
warnings: Vec::new(),
plugin_id: None,
plugin_name: None,
}
}
+74
Переглянути файл
@@ -426,6 +426,28 @@ impl Handler for FakeAgent {
self.say(&session, &format!("form {answer}"));
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "question form" {
// claude-agent-acp's `AskUserQuestion`, sent as a form.
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
.block_on(peer.request(
"elicitation/create",
json!({"sessionId": session, "mode": "form",
"message": "Please answer the following questions.",
"requestedSchema": {"type": "object", "properties": {
"question_0": {"type": "string", "title": "Layout", "description": "Which layout?",
"oneOf": [{"const": "List", "title": "List"}, {"const": "Grid", "title": "Grid"}]},
"question_0_custom": {"type": "string", "title": "Other"},
"question_1": {"type": "array", "title": "Checks", "description": "Which checks?",
"items": {"anyOf": [{"const": "Disk", "title": "Disk"},
{"const": "GPU", "title": "GPU"}]}},
"question_1_custom": {"type": "string", "title": "Other"}}}}),
None,
))
.unwrap();
self.say(&session, &format!("form {answer}"));
return Ok(json!({ "stopReason": "end_turn" }));
}
if text == "ask" {
let peer = self.latest();
let answer: Value = tokio::runtime::Handle::current()
@@ -3930,6 +3952,54 @@ async fn an_agent_form_is_answered_declined_or_cancelled_even_when_approvals_are
}
}
/// claude-agent-acp asks `AskUserQuestion` as a form: it is shown as the question card, one
/// question at a time, and the card's answers fill the form (#7359).
#[tokio::test(flavor = "multi_thread")]
async fn a_question_tool_form_is_asked_as_questions() {
let answers = json!({"question_0": ["Grid", "with thumbnails"], "question_1": ["Disk", "GPU"]}).to_string();
for (reply, said) in [
(
answers.as_str(),
r#"form {"action":"accept","content":{"question_0":"Grid","question_0_custom":"with thumbnails","question_1":["Disk","GPU"]}}"#,
),
("reject", r#"form {"action":"decline"}"#),
] {
let tmp = tempfile::tempdir().unwrap();
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
let task = mgr
.create(NewAgentTask {
project_root: None,
prompt: text("question form"),
provider: "cursor".into(),
isolation: Isolation::Local,
base: None,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
let (id, questions) = mgr
.entries(&task.id, None)
.unwrap()
.into_iter()
.find_map(|entry| match entry {
AgentEntry::Permission { id, questions, form: None, chosen: None, .. } if !questions.is_empty() => {
Some((id, questions))
}
_ => None,
})
.unwrap();
let asked: Vec<_> =
questions.iter().map(|q| (q.answer_key.as_deref(), q.question.as_str(), q.multi_select)).collect();
assert_eq!(asked, [(Some("question_0"), "Which layout?", false), (Some("question_1"), "Which checks?", true)]);
mgr.respond(&task.id, id, Some(reply.to_owned())).unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let entries = mgr.entries(&task.id, None).unwrap();
assert!(entries.iter().any(|e| matches!(e, AgentEntry::Agent { text } if text == said)), "{entries:?}");
mgr.shutdown();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn cursor_approval_choice_applies_before_first_prompt() {
let tmp = tempfile::tempdir().unwrap();
@@ -6056,6 +6126,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
},
McpServer {
id: "user::slack".into(),
@@ -6070,6 +6142,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
headers: Vec::new(),
agents: Vec::new(),
unapproved: false,
plugin_id: None,
plugin_name: None,
},
]
}));
+377 -7
Переглянути файл
@@ -9,12 +9,34 @@ use std::path::{Path, PathBuf};
use std::time::{Duration, UNIX_EPOCH};
pub(crate) struct Created {
#[cfg_attr(not(test), allow(dead_code))]
pub path: PathBuf,
pub cwd: PathBuf,
pub branch: String,
pub base: String,
pub base_commit: String,
}
const OWNERSHIP_MARKER: &str = "openidea-worktree.json";
const OWNERSHIP_TAG: &str = "openidea-agent";
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct WorktreeOwnership {
owner: String,
task_id: String,
worktree_root: PathBuf,
repo_root: PathBuf,
}
/// Returns the canonical root of the Git repository containing `project_root`, if any.
pub fn canonical_repo_root(project_root: &Path) -> IdeResult<Option<PathBuf>> {
match Repo::discover(project_root)? {
Some(repo) => Ok(Some(dunce::canonicalize(repo.root())?)),
None => Ok(None),
}
}
/// The repository of `path`, free to execute: the host runs every agent command that
/// reaches a repository only in a trusted project.
fn discover(path: &Path) -> IdeResult<Option<Repo>> {
@@ -157,9 +179,38 @@ pub(crate) fn head_commit(cwd: &Path) -> IdeResult<Option<String>> {
}
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
#[cfg(test)]
pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, base: Option<&str>) -> IdeResult<Created> {
create_for_task(project_root, worktrees_dir, "", title, base)
}
/// `git worktree add -b agent/<slug> <dir>/<slug> <base>`.
/// Records an ownership marker in the linked worktree's private `git_dir` and preserves any
/// project-relative subdirectory inside `project_root` when `project_root` is below `repo.root()`.
pub(crate) fn create_for_task(
project_root: &Path,
worktrees_dir: &Path,
task_id: &str,
title: &str,
base: Option<&str>,
) -> IdeResult<Created> {
let repo = repo_at(project_root)?;
let canon_repo = dunce::canonicalize(repo.root())?;
let canon_proj = dunce::canonicalize(project_root)?;
let rel_subdir = if canon_proj != canon_repo {
canon_proj
.strip_prefix(&canon_repo)
.map_err(|_| {
IdeError::invalid(format!(
"{} is outside git repository {}",
canon_proj.display(),
canon_repo.display()
))
})?
.to_path_buf()
} else {
PathBuf::new()
};
let (base, base_commit) = match base.map(str::trim).filter(|b| !b.is_empty()) {
Some(b) => {
let commit =
@@ -177,7 +228,125 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
let path = worktrees_dir.join(&slug);
let branch = format!("agent/{slug}");
repo.add_worktree(&path, &base_commit, Some(&branch))?;
Ok(Created { path, branch, base, base_commit })
let canon_wt = match dunce::canonicalize(&path) {
Ok(p) => p,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e.into());
}
};
let wt_repo = match repo_at(&canon_wt) {
Ok(r) => r,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
let [git_dir, common_dir] = match wt_repo.metadata_dirs() {
Ok(dirs) => dirs,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
if dunce::canonicalize(&git_dir).ok() == dunce::canonicalize(&common_dir).ok() {
let _ = repo.remove_worktree(&path, false);
return Err(IdeError::internal("linked worktree did not receive a separate git metadata directory"));
}
let marker = WorktreeOwnership {
owner: OWNERSHIP_TAG.to_owned(),
task_id: task_id.to_owned(),
worktree_root: canon_wt.clone(),
repo_root: canon_repo,
};
if let Err(e) = serde_json::to_vec_pretty(&marker)
.map_err(|e| IdeError::internal(e.to_string()))
.and_then(|bytes| ide_vfs::write_atomic(&git_dir.join(OWNERSHIP_MARKER), &bytes))
{
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
let raw_cwd = if rel_subdir.as_os_str().is_empty() { canon_wt.clone() } else { canon_wt.join(&rel_subdir) };
if !raw_cwd.is_dir() {
let _ = repo.remove_worktree(&path, false);
return Err(IdeError::invalid(format!(
"project folder {} does not exist in base revision {}",
rel_subdir.display(),
base
)));
}
let canon_cwd = match verify_confined_worktree_subdir(&canon_wt, &raw_cwd) {
Ok(c) => c,
Err(e) => {
let _ = repo.remove_worktree(&path, false);
return Err(e);
}
};
Ok(Created { path, cwd: canon_cwd, branch, base, base_commit })
}
fn verify_confined_worktree_subdir(canon_wt_root: &Path, target_cwd: &Path) -> IdeResult<PathBuf> {
let canon_cwd = dunce::canonicalize(target_cwd)?;
let real_wt = ide_core::real_path::resolve_real(canon_wt_root);
let real_cwd = ide_core::real_path::resolve_real(target_cwd);
if !canon_cwd.starts_with(canon_wt_root)
|| !real_cwd.starts_with(&real_wt)
|| ide_core::real_path::reaches_git_dir(&real_wt, &real_cwd)
{
return Err(IdeError::invalid(format!(
"worktree working directory {} resolves outside worktree {}",
target_cwd.display(),
canon_wt_root.display()
)));
}
Ok(canon_cwd)
}
/// Canonicalizes `cwd` of an existing `Isolation::Worktree` task and verifies that it still
/// resolves strictly inside its own worktree checkout root under `worktrees_dir` (preventing
/// symlink escapes on reused sessions/turns).
pub(crate) fn verify_confined_worktree_cwd(worktrees_dir: &Path, cwd: &Path) -> IdeResult<PathBuf> {
let (wt_root, wt_base) = worktree_checkout_root(worktrees_dir, cwd);
if !wt_root.starts_with(&wt_base) || wt_root == wt_base {
return Err(IdeError::invalid(format!(
"worktree working directory {} is outside managed worktrees directory {}",
cwd.display(),
worktrees_dir.display()
)));
}
let canon_wt_root = dunce::canonicalize(&wt_root)?;
let canon_wt_dir = dunce::canonicalize(worktrees_dir)?;
if !canon_wt_root.starts_with(&canon_wt_dir)
|| canon_wt_root == canon_wt_dir
|| canon_wt_root.parent() != Some(canon_wt_dir.as_path())
{
return Err(IdeError::invalid("worktree checkout root escaped managed worktrees directory"));
}
verify_confined_worktree_subdir(&canon_wt_root, cwd)
}
fn worktree_checkout_root(worktrees_dir: &Path, path: &Path) -> (PathBuf, PathBuf) {
if let Ok(rel) = path.strip_prefix(worktrees_dir)
&& let Some(first) = rel.components().next()
{
return (worktrees_dir.join(first), worktrees_dir.to_path_buf());
}
if let Ok(canon_wt_dir) = dunce::canonicalize(worktrees_dir) {
if let Ok(rel) = path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
{
return (canon_wt_dir.join(first), canon_wt_dir);
}
if let Ok(canon_path) = dunce::canonicalize(path)
&& let Ok(rel) = canon_path.strip_prefix(&canon_wt_dir)
&& let Some(first) = rel.components().next()
{
return (canon_wt_dir.join(first), canon_wt_dir);
}
}
(path.to_path_buf(), worktrees_dir.to_path_buf())
}
/// `git worktree remove --force -- <path>`. When git no longer recognizes the
@@ -186,19 +355,94 @@ pub(crate) fn create(project_root: &Path, worktrees_dir: &Path, title: &str, bas
/// ours, so it is removed directly to keep the task deletable (a stale
/// registration prunes later); anything else keeps git's error.
pub(crate) fn remove(project_root: &Path, worktrees_dir: &Path, path: &Path) -> IdeResult<()> {
let (target, wt_base) = worktree_checkout_root(worktrees_dir, path);
let repo = repo_at(project_root)?;
let err = match repo.remove_worktree(path, true) {
let err = match repo.remove_worktree(&target, true) {
Ok(()) => return Ok(()),
Err(e) => e,
};
if !path.exists() {
if !target.exists() {
return Ok(());
}
if !path.starts_with(worktrees_dir) || path == worktrees_dir {
if !target.starts_with(&wt_base) || target == wt_base {
return Err(err);
}
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(path))
.map_err(|e| IdeError::internal(format!("{}: {e}", path.display())))
retrying(REMOVE_ATTEMPTS, REMOVE_PAUSE, || std::fs::remove_dir_all(&target))
.map_err(|e| IdeError::internal(format!("{}: {e}", target.display())))
}
/// Safely removes an automation worktree ONLY after verifying its private `git_dir` ownership
/// marker (`openidea-worktree.json`) matches `task_id` and `worktrees_dir`.
///
/// - When `require_clean` is `true` (zero-diff GC): verifies `HEAD == base_commit` and both the
/// Git index (staged) and working tree (unstaged + untracked) are completely clean right before
/// running **non-forced** `git worktree remove` (`force = false`). Returns `Ok(false)` without
/// modifying disk if the worktree has any commits, staged changes, unstaged edits, or untracked
/// files.
/// - Never falls back to `remove_dir_all` on any ownership or Git error: any error keeps the
/// checkout intact.
pub(crate) fn remove_owned_automation_worktree(
project_root: &Path,
worktrees_dir: &Path,
cwd: &Path,
task_id: &str,
base_commit: Option<&str>,
require_clean: bool,
) -> IdeResult<bool> {
if !cwd.exists() || !worktrees_dir.exists() {
return Ok(false);
}
let canon_worktrees = dunce::canonicalize(worktrees_dir)?;
let canon_cwd = dunce::canonicalize(cwd)?;
if !canon_cwd.starts_with(&canon_worktrees) || canon_cwd == canon_worktrees {
return Err(IdeError::invalid("refusing to clean worktree outside managed worktrees directory"));
}
let main_repo = repo_at(project_root)?;
let wt_repo = repo_at(&canon_cwd)?;
let canon_wt_root = dunce::canonicalize(wt_repo.root())?;
if !canon_wt_root.starts_with(&canon_worktrees)
|| canon_wt_root == canon_worktrees
|| canon_wt_root.parent() != Some(canon_worktrees.as_path())
{
return Err(IdeError::invalid("worktree root does not match managed worktrees directory"));
}
let [git_dir, wt_common] = wt_repo.metadata_dirs()?;
let [_, main_common] = main_repo.metadata_dirs()?;
let canon_git_dir = dunce::canonicalize(&git_dir)?;
let canon_wt_common = dunce::canonicalize(&wt_common)?;
let canon_main_common = dunce::canonicalize(&main_common)?;
if canon_git_dir == canon_wt_common || canon_wt_common != canon_main_common {
return Err(IdeError::invalid("target checkout is not a linked worktree of this repository"));
}
let marker_bytes = std::fs::read(canon_git_dir.join(OWNERSHIP_MARKER))
.map_err(|_| IdeError::invalid("refusing to remove worktree without OpenIDEA ownership marker"))?;
let marker: WorktreeOwnership = serde_json::from_slice(&marker_bytes)
.map_err(|_| IdeError::invalid("corrupt OpenIDEA worktree ownership marker"))?;
let marker_root = dunce::canonicalize(&marker.worktree_root).unwrap_or(marker.worktree_root);
if marker.owner != OWNERSHIP_TAG || marker.task_id != task_id || marker_root != canon_wt_root {
return Err(IdeError::invalid("worktree ownership marker does not match task"));
}
if require_clean {
let Some(base) = base_commit else {
return Ok(false);
};
if wt_repo.head()?.1.as_deref() != Some(base) {
return Ok(false);
}
// `status()` checks BOTH HEAD↔index (staged) and index↔worktree (unstaged + untracked).
if !wt_repo.status()?.is_empty() {
return Ok(false);
}
if !wt_repo.diff_with_worktree(base)?.is_empty() {
return Ok(false);
}
main_repo.remove_worktree(&canon_wt_root, false)?;
return Ok(true);
}
main_repo.remove_worktree(&canon_wt_root, true)?;
Ok(true)
}
/// On Windows a folder can't be deleted while a process still has a file in it open
@@ -1944,4 +2188,130 @@ mod tests {
changed.sort();
assert_eq!(changed, ["edited", "new", "reverted"]);
}
#[test]
fn owned_worktree_cleanup_preserves_subproject_cwd_catches_staged_changes_and_verifies_ownership() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
let sub = repo.join("packages").join("subapp");
std::fs::create_dir_all(&sub).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
git(&repo, &["config", "core.autocrlf", "false"]);
std::fs::write(repo.join("root.txt"), "root\n").unwrap();
std::fs::write(sub.join("index.ts"), "export const x = 1;\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "init"]);
let wt_dir = tmp.path().join("wt");
let created = create_for_task(&sub, &wt_dir, "task-1", "Sub Audit", None).unwrap();
assert_eq!(
dunce::canonicalize(&created.cwd).unwrap(),
dunce::canonicalize(&created.path).unwrap().join("packages").join("subapp"),
"project-relative cwd inside parent repo must be preserved inside worktree"
);
// Wrong task_id is refused and keeps the checkout untouched.
assert!(
remove_owned_automation_worktree(
&sub,
&wt_dir,
&created.cwd,
"wrong-task",
Some(&created.base_commit),
true,
)
.is_err()
);
assert!(created.path.exists());
// Staged-only change (index differs from HEAD while working tree matches HEAD!) is NOT clean!
std::fs::write(created.cwd.join("index.ts"), "export const x = 2;\n").unwrap();
git(&created.path, &["add", "packages/subapp/index.ts"]);
std::fs::write(created.cwd.join("index.ts"), "export const x = 1;\n").unwrap();
let removed_staged =
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
.unwrap();
assert!(!removed_staged, "staged-only index change must prevent zero-diff worktree GC");
assert!(created.path.exists());
// Reset index back to HEAD -> zero-diff GC removes the worktree via non-forced `git worktree remove`.
git(&created.path, &["reset", "-q", "HEAD", "--", "packages/subapp/index.ts"]);
let removed_clean =
remove_owned_automation_worktree(&sub, &wt_dir, &created.cwd, "task-1", Some(&created.base_commit), true)
.unwrap();
assert!(removed_clean);
assert!(!created.path.exists());
// Foreign / manually created git worktree inside `wt_dir` without ownership marker is NEVER deleted.
let manual_wt = wt_dir.join("foreign");
git(&repo, &["worktree", "add", "-q", "-b", "manual-branch", manual_wt.to_str().unwrap(), "HEAD"]);
assert!(
remove_owned_automation_worktree(&repo, &wt_dir, &manual_wt, "task-2", Some(&created.base_commit), false,)
.is_err()
);
assert!(manual_wt.exists(), "worktree without OpenIDEA ownership marker must never be deleted");
}
#[cfg(unix)]
#[test]
fn symlinked_subproject_cwd_escaping_worktree_is_rejected_on_create_and_reuse() {
let tmp = tempfile::tempdir().unwrap();
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&outside).unwrap();
std::fs::write(outside.join("secret.txt"), "nope\n").unwrap();
let repo = tmp.path().join("repo");
let packages = repo.join("packages");
std::fs::create_dir_all(&packages).unwrap();
git(&repo, &["init", "-q", "-b", "main"]);
git(&repo, &["config", "core.autocrlf", "false"]);
// 1a. Direct symlink pointing outside git is rejected immediately.
let escape_link = packages.join("escape");
std::os::unix::fs::symlink(&outside, &escape_link).unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "symlink escape"]);
let wt_dir = tmp.path().join("wt");
assert!(create_for_task(&escape_link, &wt_dir, "task-escape-direct", "Escape", None).is_err());
// 1b. Committed symlink in `HEAD` (`packages/tricky -> ../../outside`) while the main
// checkout temporarily has a real directory at `packages/tricky`: `git worktree add`
// checks out `HEAD`'s symlink inside the worktree, and `verify_confined_worktree_subdir`
// must catch the escape and clean up the worktree!
let tricky = packages.join("tricky");
std::os::unix::fs::symlink(&outside, &tricky).unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "committed tricky symlink"]);
std::fs::remove_file(&tricky).unwrap();
std::fs::create_dir_all(&tricky).unwrap();
let Err(err) = create_for_task(&tricky, &wt_dir, "task-escape-head", "Tricky", None) else {
panic!("expected committed symlink escaping worktree root to be rejected");
};
assert!(
err.to_string().contains("outside worktree") || err.to_string().contains("escapes worktree root"),
"unexpected error for committed symlink cwd: {err}"
);
// 2. Normal directory at creation time, later replaced with an escaping symlink before reuse,
// must be rejected by `verify_confined_worktree_cwd`!
let legit_sub = packages.join("legit");
std::fs::create_dir_all(&legit_sub).unwrap();
std::fs::write(legit_sub.join("ok.txt"), "ok\n").unwrap();
git(&repo, &["add", "."]);
git(&repo, &["commit", "-q", "-m", "legit sub"]);
let created = create_for_task(&legit_sub, &wt_dir, "task-reuse", "Legit", None).unwrap();
let verified = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap();
assert!(verified.starts_with(dunce::canonicalize(&created.path).unwrap()));
std::fs::remove_dir_all(&created.cwd).unwrap();
std::os::unix::fs::symlink(&outside, &created.cwd).unwrap();
let reuse_err = super::verify_confined_worktree_cwd(&wt_dir, &created.cwd).unwrap_err();
assert!(
reuse_err.to_string().contains("outside worktree") || reuse_err.to_string().contains("escapes"),
"symlink swap on worktree reuse must be rejected: {reuse_err}"
);
}
}
+24
Переглянути файл
@@ -0,0 +1,24 @@
{
"version": 2,
"plugins": {
"evidence-plugin@evidence-mkt": [
{
"scope": "user",
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
"version": "1.2.3",
"installedAt": "2026-11-30T21:50:25.665Z",
"lastUpdated": "2026-11-30T21:50:25.665Z",
"gitCommitSha": "1111111111111111111111111111111111111111"
},
{
"scope": "project",
"projectPath": "$WORKSPACE",
"installPath": "$HOME/.claude/plugins/cache/evidence-mkt/evidence-plugin/1.2.3",
"version": "1.2.3",
"installedAt": "2026-11-30T21:50:25.665Z",
"lastUpdated": "2026-11-30T21:50:25.665Z",
"gitCommitSha": "1111111111111111111111111111111111111111"
}
]
}
}
+6
Переглянути файл
@@ -0,0 +1,6 @@
[marketplaces.evidence-mkt]
source_type = "local"
source = "$HOME/.codex/.tmp/marketplaces/evidence-mkt"
[plugins."evidence-plugin@evidence-mkt"]
enabled = false
+19
Переглянути файл
@@ -0,0 +1,19 @@
// This file is managed automatically.
{
"installedPlugins": [
{
"name": "evidence-plugin",
"marketplace": "evidence-mkt",
"installed_at": "2026-11-30T21:50:25.665Z",
"enabled": true,
"version": "1.2.3",
"cache_path": "$HOME/.copilot/installed-plugins/evidence-mkt/evidence-plugin",
"source": {
"source": "github",
"repo": "acme/plugins",
"sha": "1111111111111111111111111111111111111111",
"path": "plugins/evidence-plugin"
}
}
]
}
+8
Переглянути файл
@@ -0,0 +1,8 @@
{
"evidence-extension": {
"overrides": [
"$HOME/*",
"!$WORKSPACE/*"
]
}
}
+3 -1
Переглянути файл
@@ -1555,7 +1555,9 @@ pub fn load_with_linked_jdk(
.as_deref()
.or_else(|| managed.get(&d.key()).and_then(|m| m.system_path.as_deref()))?;
let path = i(path);
(!path.contains("${") && Path::new(&path).is_absolute()).then(|| PathBuf::from(path))
// Rebuilt from its components: `${pom.basedir}/lib/x.jar` on Windows mixes `\\` and `/`.
(!path.contains("${") && Path::new(&path).is_absolute())
.then(|| Path::new(&path).components().collect::<PathBuf>())
})
.collect();
+2
Переглянути файл
@@ -99,6 +99,8 @@ pub enum IdeEvent {
WindowGroupsChanged,
/// A project was loaded or unloaded for the MCP server without a window of its own.
McpBackgroundProjectsChanged,
/// Agent automations, run history, or session schedules changed on the host.
AutomationsChanged,
/// A window entered or left full screen, itself or as a member of a full-screen window group.
WindowFullscreenChanged,
/// This remote window's connection ended or another window took over the session.
+40
Переглянути файл
@@ -83,6 +83,24 @@ pub fn own_group(cmd: &mut Command) -> &mut Command {
cmd
}
/// Starts the child as the leader of a session of its own on Unix. Like [`own_group`] it leads
/// its process group, so [`kill_tree`] and [`terminate_tree`] reach what it starts; unlike it,
/// the child has no controlling terminal, so a tool that would ask on `/dev/tty` (and be
/// stopped there as a background job when the app was started from a shell) falls back to
/// its pipes. Use it in place of `own_group`: a group leader cannot start a session. A no-op
/// elsewhere.
pub fn own_session(cmd: &mut Command) -> &mut Command {
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// SAFETY: `setsid` is async-signal-safe and touches none of the parent's memory.
unsafe {
cmd.pre_exec(|| if libc::setsid() == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) });
}
}
cmd
}
/// Kills the child and everything it started, then reaps it.
///
/// - Unix: `SIGKILL` to its process group, so spawn it with [`own_group`].
@@ -970,6 +988,28 @@ fn append_path_entries(path: &OsStr, extra: &OsStr) -> OsString {
mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn own_session_leaves_the_controlling_terminal_behind() {
// `ps` prints `?` (Linux) or `??` (macOS) for a process without a controlling terminal.
let mut cmd = Command::new("sh");
cmd.args(["-c", "ps -o tty= -p $$"]);
let out = own_session(&mut cmd).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert!(String::from_utf8_lossy(&out.stdout).trim().chars().all(|c| c == '?'), "{:?}", out.stdout);
// Without a terminal (CI) the line above holds anyway: the child must lead a session
// of its own, which only `setsid` makes it.
let mut cmd = Command::new("sleep");
cmd.arg("5");
let mut child = own_session(&mut cmd).spawn().unwrap();
let pid = libc::pid_t::try_from(child.id()).unwrap();
// SAFETY: plain syscall on a child not reaped yet.
let session = unsafe { libc::getsid(pid) };
let _ = child.kill();
let _ = child.wait();
assert_eq!(session, pid, "the child leads its own session");
}
#[test]
fn process_alive_tells_live_from_dead_pids() {
assert!(process_alive(std::process::id()));
+24 -7
Переглянути файл
@@ -5,6 +5,29 @@ use std::path::{Component, Path, PathBuf};
pub const SEARCH_DEPTH: usize = 3;
/// Folders that hold dependencies or build output rather than the project's own builds: hidden
/// folders (`.build`, `.git`), package checkouts (`node_modules`, `SourcePackages`, `Pods`,
/// `Carthage`) and build products (`target`, `build`, `DerivedData`, …).
pub fn is_skipped_dir(name: &str) -> bool {
name.starts_with('.')
|| matches!(
name,
"node_modules"
| "target"
| "build"
| "dist"
| "vendor"
| "out"
| "bin"
| "obj"
| "venv"
| "SourcePackages"
| "Pods"
| "Carthage"
| "DerivedData"
)
}
pub fn children(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
let mut dirs: Vec<_> = entries
@@ -13,13 +36,7 @@ pub fn children(dir: &Path) -> Vec<PathBuf> {
if !entry.file_type().is_ok_and(|kind| kind.is_dir()) {
return false;
}
let name = entry.file_name();
let name = name.to_string_lossy();
!name.starts_with('.')
&& !matches!(
name.as_ref(),
"node_modules" | "target" | "build" | "dist" | "vendor" | "out" | "bin" | "obj" | "venv"
)
!is_skipped_dir(&entry.file_name().to_string_lossy())
})
.map(|entry| entry.path())
.collect();
+114
Переглянути файл
@@ -170,6 +170,15 @@ pub struct AgentSettings {
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentMemorySettings)]
pub memory: AgentMemorySettings,
/// Agent plugin bundle policies (`[agents.plugins]`): registered marketplaces and non-sensitive
/// config. Enablement lives in each harness's native config; capability consent is stored per machine.
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentPluginSettings)]
pub plugins: AgentPluginSettings,
/// Scheduled agent automations and headless scheduler host policies (`[agents.automations]`).
#[serde(deserialize_with = "or_default")]
#[specta(type = AgentAutomationSettings)]
pub automations: AgentAutomationSettings,
}
impl Default for AgentSettings {
@@ -202,6 +211,8 @@ impl Default for AgentSettings {
mcp_servers: BTreeMap::new(),
skills: BTreeMap::new(),
memory: AgentMemorySettings::default(),
plugins: AgentPluginSettings::default(),
automations: AgentAutomationSettings::default(),
}
}
}
@@ -358,6 +369,96 @@ pub struct AgentMemorySettings {
pub entries: BTreeMap<String, AgentMemoryEntryPolicy>,
}
/// One agent plugin bundle's policy in Settings › Agents › Plugins
/// (`[agents.plugins.entries."<harness>:<plugin>@<marketplace>"]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentPluginEntryPolicy {
/// Non-sensitive `userConfig` / `variables` key-value pairs; sensitive values live in OS Keychain.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub config: BTreeMap<String, String>,
}
/// Agent plugin bundle settings (`[agents.plugins]`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentPluginSettings {
/// Registered plugin marketplaces (`owner/repo[#ref]`, GitHub URL, or local directory/manifest path).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub marketplaces: Vec<String>,
/// Per-plugin non-sensitive native option hints, keyed by `<harness>:<plugin>@<marketplace>`.
#[serde(deserialize_with = "or_default", skip_serializing_if = "BTreeMap::is_empty")]
#[specta(type = BTreeMap<String, AgentPluginEntryPolicy>)]
pub entries: BTreeMap<String, AgentPluginEntryPolicy>,
}
/// When OpenIDEA holds an OS idle-sleep assertion during active automation turns.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutomationPreventSleep {
/// Prevent idle sleep while plugged into AC power.
#[default]
Ac,
/// Prevent idle sleep whenever an automated turn is running.
Always,
/// Never hold an idle-sleep assertion.
Never,
}
/// What the scheduler does when one or more scheduled occurrences fell due while asleep or offline.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum AutomationMisfirePolicy {
/// Coalesce all missed occurrences into at most one catch-up run once awake and online.
#[default]
RunOnce,
/// Skip missed occurrences and advance to the next future slot.
Skip,
}
/// Agent automation and headless scheduler settings (`[agents.automations]`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct AgentAutomationSettings {
/// Automatically register the headless login/boot scheduler service while at least one
/// automation is enabled, and unregister it when none remain enabled.
pub auto_start_service: bool,
/// Keep the local OpenIDEA host alive in the background when windows close while local
/// automations are enabled.
pub keep_alive_in_background: bool,
/// Prevent system idle sleep while an automated turn is running.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutomationPreventSleep)]
pub prevent_sleep: AutomationPreventSleep,
/// Default policy for scheduled occurrences missed during sleep, offline downtime, or reboot.
#[serde(deserialize_with = "or_default")]
#[specta(type = AutomationMisfirePolicy)]
pub misfire_policy: AutomationMisfirePolicy,
/// Keep `openidea-server --daemon` alive across disconnects while the remote host has
/// enabled scheduled automations.
pub keep_remote_daemon_alive: bool,
/// Automatically remove temporary automation worktrees when a run finishes with zero diff
/// and zero commits.
pub auto_clean_worktrees: bool,
/// Maximum retained non-clean automation worktrees per automation before pruning oldest
/// finished ones.
pub max_dirty_worktrees: u32,
}
impl Default for AgentAutomationSettings {
fn default() -> Self {
Self {
auto_start_service: false,
keep_alive_in_background: true,
prevent_sleep: AutomationPreventSleep::Ac,
misfire_policy: AutomationMisfirePolicy::RunOnce,
keep_remote_daemon_alive: true,
auto_clean_worktrees: true,
max_dirty_worktrees: 5,
}
}
}
/// A hand-edited value these settings don't know reads as the default, rather than
/// failing the whole settings file.
fn or_default<'de, D, T>(d: D) -> Result<T, D::Error>
@@ -1509,6 +1610,9 @@ pub struct MarkdownSettings {
pub preview_layout: MarkdownPreviewLayout,
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
pub preview_font_size: Option<u32>,
/// Whether `.mdx` previews ask before running JSX components/imports, run automatically in
/// trusted projects, or stay in static safe mode.
pub mdx_execution: MdxExecutionPolicy,
/// "Detect commands that can be run right from Markdown files": gutter run icons on
/// shell code blocks and on command lines in code blocks.
pub run_commands: bool,
@@ -1521,12 +1625,22 @@ impl Default for MarkdownSettings {
Self {
preview_layout: MarkdownPreviewLayout::default(),
preview_font_size: None,
mdx_execution: MdxExecutionPolicy::default(),
run_commands: true,
command_directory: None,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MdxExecutionPolicy {
#[default]
Ask,
Trusted,
Off,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum MarkdownPreviewLayout {
+8
Переглянути файл
@@ -296,6 +296,14 @@ pub struct OutlineItem {
#[serde(default)]
#[specta(optional)]
pub visibility: Option<Visibility>,
/// Rust `impl Trait for Type`: the trait's name in the header (its last path segment, where go-to-definition lands), from the syntax tree.
#[serde(default)]
#[specta(optional)]
pub implements: Option<Range>,
/// Rust `impl [Trait for] Type`: the implementing type's name (its last path segment), from the syntax tree.
#[serde(default)]
#[specta(optional)]
pub self_type: Option<Range>,
}
/// Fuzzy-match highlight: indices (in chars of the displayed string) that matched.
+30
Переглянути файл
@@ -27,6 +27,35 @@ pub struct VcsSettings {
pub mappings: VcsMappings,
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
pub github: GithubSettings,
/// Settings › Version Control › Subversion.
pub svn: SvnSettings,
}
/// Settings › Version Control › Subversion (`vcs.svn`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct SvnSettings {
/// Path to the svn executable; empty = auto-detect.
pub executable: String,
/// Run svn as if in a terminal: its password, passphrase and certificate prompts open
/// dialogs. Off, svn runs with `--non-interactive` and a rejected login asks once.
pub interactive: bool,
/// Pass `--config-dir config_dir` to every svn command.
pub use_custom_config_dir: bool,
pub config_dir: String,
}
impl Default for SvnSettings {
/// Interactive except on Windows: svn there asks on the console, which an IDE's child
/// process has hidden, so a prompt could not be answered (not verified on Windows yet).
fn default() -> Self {
Self {
executable: String::new(),
interactive: !cfg!(windows),
use_custom_config_dir: false,
config_dir: String::new(),
}
}
}
/// Settings › Version Control › GitHub (`vcs.github`).
@@ -80,6 +109,7 @@ impl Default for VcsSettings {
issue_navigation: Vec::new(),
mappings: VcsMappings::default(),
github: GithubSettings::default(),
svn: SvnSettings::default(),
}
}
}
+13 -2
Переглянути файл
@@ -508,6 +508,11 @@ fn child_name(configuration: &Value, parent: &str) -> String {
}
}
/// LLDB-based adapters, which debug native programs (and Swift on Apple platforms).
fn is_native(adapter: &str) -> bool {
matches!(adapter, "lldb-dap" | "codelldb")
}
/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the
/// adapter.
pub const RUN_LINK: &str = "__openideaRun";
@@ -1638,11 +1643,16 @@ impl DebugManager {
let _ = s.conn.request_timeout("terminate", json!({ "restart": false }), SHUTDOWN_TIMEOUT).await;
}
if !graceful && (!own_terminate || killed) {
// A native attach to a program a run started for the debugger (an Xcode app launched
// with `simctl launch --wait-for-debugger`) ends it too: detached, the app can be
// left stopped with the SIGTERM the run's Stop sent while it was traced, and the
// simulator then holds its launch (and the next one) forever.
let ends_debuggee = s.request == "launch" || (terminate && s.run.is_some() && is_native(&s.adapter));
let _ = s
.conn
.request_timeout(
"disconnect",
json!({ "restart": false, "terminateDebuggee": s.request == "launch" }),
json!({ "restart": false, "terminateDebuggee": ends_debuggee }),
SHUTDOWN_TIMEOUT,
)
.await;
@@ -1786,7 +1796,8 @@ impl DebugManager {
let mut states = self.states.lock();
let Some(slot) = states.get_mut(path).and_then(|v| v.get_mut(index)) else { return false };
let next = session::state_from(bp, slot.line);
let next = BreakpointState { message: next.message.or_else(|| slot.message.clone()), ..next };
let kept = slot.message.clone().filter(|m| !(next.verified && m == session::UNBOUND_NATIVE));
let next = BreakpointState { message: next.message.or(kept), ..next };
let changed = *slot != next;
*slot = next;
changed
+8
Переглянути файл
@@ -293,6 +293,11 @@ impl Suspension {
/// symlinked path (`/tmp/game` while the editor has `/private/tmp/game`).
const RESOLVES_PATHS: &[&str] = &["godot"];
/// LLDB answers a breakpoint it can't bind yet with no reason: the code may simply not be loaded.
const NATIVE_ADAPTERS: &[&str] = &["lldb-dap", "codelldb"];
/// One literal: the UI looks it up in the text catalogs to translate it.
pub(crate) const UNBOUND_NATIVE: &str = "No loaded code at this line yet. If it stays unbound after its module loads, the debug info may record this file under another path (through a symlink, or /tmp for /private/tmp): set a source map from that path to this one";
impl Session {
#[allow(clippy::too_many_arguments)]
pub fn new(
@@ -514,6 +519,9 @@ impl Session {
ids.insert(id, (path.to_path_buf(), i));
}
states[i] = state_from(r, breakpoints[i].line);
if !states[i].verified && states[i].message.is_none() && NATIVE_ADAPTERS.contains(&self.adapter.as_str()) {
states[i].message = Some(UNBOUND_NATIVE.to_owned());
}
}
Ok(states)
}
+48 -1
Переглянути файл
@@ -138,6 +138,8 @@ struct Script {
output_after_terminate: bool,
/// Advertise `supportsTerminateRequest` (java-debug does not, so Stop signals the program).
supports_terminate: bool,
/// Answer `setBreakpoints` with unverified breakpoints and no reason (LLDB before the code loads).
unbound_breakpoints: bool,
/// Answer `setBreakpoints` only once this many are waiting (a client that waits for each never gets one).
hold_set_breakpoints: usize,
/// Send a `continued` event right after the first `stopped` one.
@@ -220,6 +222,7 @@ impl Default for Script {
fn default() -> Self {
Self {
run_in_terminal: None,
unbound_breakpoints: false,
start_debugging: false,
child_request: None,
ignore_configuration_done: false,
@@ -414,7 +417,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
.unwrap()
.iter()
.enumerate()
.map(|(i, b)| json!({"id": i + 1, "verified": true, "line": b["line"]}))
.map(|(i, b)| json!({"id": i + 1, "verified": !script.unbound_breakpoints, "line": b["line"]}))
.collect();
ok!(msg, json!({"breakpoints": bps}));
}
@@ -4019,6 +4022,50 @@ async fn stop_detaches_from_an_attached_program() {
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// Xcode Debug: lldb-dap attaches to the app a run launched suspended. Stop ends the app through
/// the debugger; detaching would leave it stopped with the run's SIGTERM, holding the simulator.
#[tokio::test]
async fn stop_ends_a_native_program_a_run_started_for_the_debugger() {
let h = harness(Script::default());
let linked = |adapter: &str| LaunchConfig {
adapter: adapter.into(),
request: "attach".into(),
extra_json: Some(json!({ RUN_LINK: 7, "pid": 4242 }).to_string()),
..config()
};
let id = h.start(linked("lldb-dap")).await.unwrap();
h.manager.stop(id).await.unwrap();
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], true);
// Another adapter's attach to a run (a Gradle test worker JVM) still only detaches.
let h = harness(Script::default());
let id = h.start(linked("debugpy")).await.unwrap();
h.manager.stop(id).await.unwrap();
assert_eq!(h.request("disconnect")["arguments"]["terminateDebuggee"], false);
}
/// LLDB leaves a breakpoint it can't bind unverified without a reason: say what may be wrong
/// (#6665 E1b: Xcode's debug info had `/tmp/…` for a project under `/private/tmp`).
#[tokio::test]
async fn an_unbound_native_breakpoint_says_why() {
for (adapter, hint) in [("lldb-dap", true), ("codelldb", true), ("debugpy", false)] {
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
h.start(LaunchConfig { adapter: adapter.into(), ..config() }).await.unwrap();
let path = PathBuf::from("/private/tmp/app/Counter.swift");
let states = h.manager.set_breakpoints(&h.owner.key, path, vec![bp(6)]).await.unwrap();
assert!(!states[0].verified);
assert_eq!(states[0].message.as_deref() == Some(crate::session::UNBOUND_NATIVE), hint, "{adapter}");
}
// Bound once the module loads (lldb-dap's `breakpoint` event has no message): the hint goes.
let path = PathBuf::from("/private/tmp/app/Counter.swift");
let h = harness(Script { unbound_breakpoints: true, ..Script::default() });
h.start(LaunchConfig { adapter: "lldb-dap".into(), ..config() }).await.unwrap();
h.manager.set_breakpoints(&h.owner.key, path.clone(), vec![bp(6)]).await.unwrap();
assert!(h.manager.update_breakpoint_state(&path, 0, &json!({"id": 1, "verified": true, "line": 7})));
assert_eq!(h.manager.breakpoint_states(&path)[0].message, None);
}
#[tokio::test]
async fn cell_breakpoints_go_only_to_their_notebooks_kernel_session() {
use crate::jvm_memory::test_support::bare_session_of;
+1
Переглянути файл
@@ -28,6 +28,7 @@ ide-syntax.workspace = true
ide-search.workspace = true
ide-lsp.workspace = true
ide-vcs.workspace = true
ide-svn.workspace = true
ide-github.workspace = true
ide-dap.workspace = true
ide-heap.workspace = true
+18
Переглянути файл
@@ -111,6 +111,24 @@ impl AgentSecrets {
}
}
impl ide_agent::EnvSecrets for AgentSecrets {
fn get(&self, key: &str) -> Option<String> {
AgentSecrets::get(self, key)
}
fn set(&self, key: &str, value: &str) -> IdeResult<()> {
AgentSecrets::set(self, key, value).map(|_| ())
}
fn delete(&self, key: &str) {
AgentSecrets::delete(self, key);
}
fn keys(&self, prefix: &str) -> Vec<String> {
AgentSecrets::keys(self, prefix)
}
}
#[cfg(test)]
mod tests {
use super::*;
+775
Переглянути файл
@@ -0,0 +1,775 @@
//! Per-user OS login / boot service registration for `openidea-server --scheduler`
//! (or `<desktop-exe> --scheduler`).
//!
//! Off by default (`agents.automations.autoStartService = false`). When the user enables it
//! and at least one scheduled automation is active, registers the user login service; when
//! disabled or when zero scheduled automations remain (after any in-flight claimed runs finish),
//! stops and unregisters the service.
use ide_core::{IdeError, IdeResult, IpcPath};
use parking_lot::{Mutex, RwLock};
use std::path::{Path, PathBuf};
use std::sync::Arc;
pub const SERVICE_LABEL: &str = "ai.l0ng.openidea.scheduler";
pub const SYSTEMD_UNIT_NAME: &str = "openidea-scheduler.service";
const WINDOWS_SCRIPT_NAME: &str = "openidea-scheduler.cmd";
const OVERRIDE_ENV: &str = "OPENIDEA_BOOT_SERVICE_DIR";
const DISABLE_OS_CALLS_ENV: &str = "OPENIDEA_DISABLE_OS_SERVICE_CALLS";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ServicePlatform {
Macos,
Linux,
Windows,
Other,
}
impl ServicePlatform {
pub fn host() -> Self {
if cfg!(target_os = "macos") {
Self::Macos
} else if cfg!(target_os = "linux") {
Self::Linux
} else if cfg!(target_os = "windows") {
Self::Windows
} else {
Self::Other
}
}
}
pub type CommandRunner = Arc<dyn Fn(&str, &[&str]) -> std::io::Result<(i32, String, String)> + Send + Sync>;
#[derive(Default)]
pub struct BootServiceManager {
sync_lock: Mutex<()>,
override_dir: RwLock<Option<PathBuf>>,
executable_override: RwLock<Option<PathBuf>>,
platform_override: RwLock<Option<ServicePlatform>>,
command_runner: RwLock<Option<CommandRunner>>,
last_error: Mutex<Option<String>>,
}
#[derive(Clone, Debug)]
pub struct BootServiceState {
pub kind: String,
pub registered: bool,
pub path: Option<IpcPath>,
pub error: Option<String>,
pub linux_linger_enabled: Option<bool>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OsServicePresence {
RegisteredAndActive,
RegisteredIdle,
ActiveUnregistered,
Absent,
}
impl OsServicePresence {
fn is_registered(self) -> bool {
matches!(self, Self::RegisteredAndActive | Self::RegisteredIdle)
}
fn is_loaded_or_active(self) -> bool {
!matches!(self, Self::Absent)
}
}
impl BootServiceManager {
pub fn with_override_dir(dir: Option<PathBuf>) -> Self {
Self {
sync_lock: Mutex::new(()),
override_dir: RwLock::new(dir),
executable_override: RwLock::new(None),
platform_override: RwLock::new(None),
command_runner: RwLock::new(None),
last_error: Mutex::new(None),
}
}
pub fn set_override_dir(&self, dir: Option<PathBuf>) {
*self.override_dir.write() = dir;
}
pub fn set_executable_override(&self, exe: Option<PathBuf>) {
*self.executable_override.write() = exe;
}
pub fn set_command_runner_for_test(&self, platform: ServicePlatform, runner: Option<CommandRunner>) {
*self.platform_override.write() = runner.as_ref().map(|_| platform);
*self.command_runner.write() = runner;
}
fn effective_platform(&self) -> ServicePlatform {
self.platform_override.read().unwrap_or_else(ServicePlatform::host)
}
fn effective_override_dir(&self) -> Option<PathBuf> {
self.override_dir
.read()
.clone()
.or_else(|| std::env::var_os(OVERRIDE_ENV).filter(|v| !v.is_empty()).map(PathBuf::from))
}
fn uses_os_commands(&self) -> bool {
if self.command_runner.read().is_some() {
return true;
}
self.effective_override_dir().is_none() && std::env::var_os(DISABLE_OS_CALLS_ENV).is_none_or(|v| v != "1")
}
fn run_command(&self, program: &str, args: &[&str]) -> IdeResult<(i32, String, String)> {
if let Some(runner) = self.command_runner.read().clone() {
return runner(program, args).map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")));
}
let out = std::process::Command::new(program)
.args(args)
.output()
.map_err(|e| IdeError::internal(format!("{program} failed to spawn: {e}")))?;
let code = out.status.code().unwrap_or(-1);
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
Ok((code, stdout, stderr))
}
fn run_checked(&self, program: &str, args: &[&str]) -> IdeResult<String> {
let (code, stdout, stderr) = self.run_command(program, args)?;
if code == 0 {
return Ok(stdout);
}
let detail = stderr.trim();
let msg = if detail.is_empty() { stdout.trim() } else { detail };
Err(IdeError::internal(format!("{program} {} exited with {code}: {msg}", args.join(" "))))
}
fn scheduler_executable(&self) -> Option<PathBuf> {
self.executable_override.read().clone().or_else(|| std::env::current_exe().ok())
}
pub fn service_kind_for(platform: ServicePlatform, remote: bool) -> &'static str {
if remote && platform == ServicePlatform::Linux {
"systemdUser"
} else {
match platform {
ServicePlatform::Macos => "launchAgent",
ServicePlatform::Linux => "systemdUser",
ServicePlatform::Windows => "windowsStartup",
ServicePlatform::Other => "backgroundHost",
}
}
}
pub fn service_kind(remote: bool) -> &'static str {
Self::service_kind_for(ServicePlatform::host(), remote)
}
pub fn service_file_path(&self, home_dir: Option<&Path>) -> Option<PathBuf> {
let platform = self.effective_platform();
if let Some(dir) = self.effective_override_dir() {
let filename = match platform {
ServicePlatform::Macos => format!("{SERVICE_LABEL}.plist"),
ServicePlatform::Windows => WINDOWS_SCRIPT_NAME.to_owned(),
ServicePlatform::Linux | ServicePlatform::Other => SYSTEMD_UNIT_NAME.to_owned(),
};
return Some(dir.join(filename));
}
let home = home_dir?;
match platform {
ServicePlatform::Macos => {
Some(home.join("Library").join("LaunchAgents").join(format!("{SERVICE_LABEL}.plist")))
}
ServicePlatform::Linux => Some(home.join(".config").join("systemd").join("user").join(SYSTEMD_UNIT_NAME)),
ServicePlatform::Windows => {
let appdata = std::env::var_os("APPDATA")
.map(PathBuf::from)
.unwrap_or_else(|| home.join("AppData").join("Roaming"));
Some(
appdata
.join("Microsoft")
.join("Windows")
.join("Start Menu")
.join("Programs")
.join("Startup")
.join(WINDOWS_SCRIPT_NAME),
)
}
ServicePlatform::Other => None,
}
}
fn macos_domain() -> String {
#[cfg(target_os = "macos")]
{
format!("gui/{}", rustix::process::getuid().as_raw())
}
#[cfg(not(target_os = "macos"))]
{
"gui/501".to_owned()
}
}
/// Queries the OS service manager, distinguishing confirmed `Absent` from `Err(...)` (unknown
/// status, e.g. D-Bus / launchd unreachable) so `sync(..., false)` never deletes the service
/// file when status cannot be determined.
fn query_os_presence(&self, platform: ServicePlatform) -> IdeResult<OsServicePresence> {
if !self.uses_os_commands() {
return Ok(OsServicePresence::Absent);
}
match platform {
ServicePlatform::Macos => {
let job = format!("{}/{SERVICE_LABEL}", Self::macos_domain());
let (code, stdout, stderr) = self.run_command("launchctl", &["print", &job])?;
if code == 0 {
return Ok(OsServicePresence::RegisteredAndActive);
}
let combined = format!("{stdout}\n{stderr}");
if code == 113 || combined.contains("Could not find service") {
return Ok(OsServicePresence::Absent);
}
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
Err(IdeError::internal(format!("launchctl print {job} returned unknown status {code}: {detail}")))
}
ServicePlatform::Linux => {
let (en_code, en_out, en_err) =
self.run_command("systemctl", &["--user", "is-enabled", SYSTEMD_UNIT_NAME])?;
let en_state = en_out.trim();
let enabled = if en_code == 0 && matches!(en_state, "enabled" | "enabled-runtime") {
true
} else if matches!(
en_state,
"disabled" | "not-found" | "static" | "indirect" | "masked" | "linked" | "generated"
) {
false
} else {
let detail = if en_err.trim().is_empty() { en_state } else { en_err.trim() };
return Err(IdeError::internal(format!(
"systemctl --user is-enabled {SYSTEMD_UNIT_NAME} returned unknown status {en_code}: {detail}"
)));
};
let (ac_code, ac_out, ac_err) =
self.run_command("systemctl", &["--user", "is-active", SYSTEMD_UNIT_NAME])?;
let ac_state = ac_out.trim();
let active = if ac_code == 0 && matches!(ac_state, "active" | "activating" | "reloading") {
true
} else if matches!(ac_state, "inactive" | "failed" | "deactivating") {
false
} else {
let detail = if ac_err.trim().is_empty() { ac_state } else { ac_err.trim() };
return Err(IdeError::internal(format!(
"systemctl --user is-active {SYSTEMD_UNIT_NAME} returned unknown status {ac_code}: {detail}"
)));
};
Ok(match (enabled, active) {
(true, true) => OsServicePresence::RegisteredAndActive,
(true, false) => OsServicePresence::RegisteredIdle,
(false, true) => OsServicePresence::ActiveUnregistered,
(false, false) => OsServicePresence::Absent,
})
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(OsServicePresence::Absent),
}
}
fn is_os_registered(&self, platform: ServicePlatform, path: &Path) -> bool {
if !path.is_file() {
return false;
}
if !self.uses_os_commands() {
return true;
}
match platform {
ServicePlatform::Macos | ServicePlatform::Linux => {
self.query_os_presence(platform).is_ok_and(OsServicePresence::is_registered)
}
ServicePlatform::Windows => std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.len() > 0),
ServicePlatform::Other => false,
}
}
pub fn status(&self, home_dir: Option<&Path>, remote: bool) -> BootServiceState {
let platform = self.effective_platform();
let path = self.service_file_path(home_dir);
let registered = path.as_ref().is_some_and(|p| self.is_os_registered(platform, p));
let linux_linger_enabled = if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None };
BootServiceState {
kind: Self::service_kind_for(platform, remote).to_owned(),
registered,
path: path.map(IpcPath),
error: self.last_error.lock().clone(),
linux_linger_enabled,
}
}
/// Synchronizes the OS user service file and service manager state to match
/// `(should_register, base_dir)`. Checks command results, retries activation even when the
/// unit/plist file on disk is unchanged, and stops + unloads the worker BEFORE deleting the
/// unit/plist file (keeping the file when status is unknown) so failed unregistrations retry.
pub fn sync(&self, home_dir: Option<&Path>, base_dir: &Path, should_register: bool) -> IdeResult<BootServiceState> {
let _guard = self.sync_lock.lock();
let result = self.sync_locked(home_dir, base_dir, should_register);
match &result {
Ok(_) => *self.last_error.lock() = None,
Err(err) => *self.last_error.lock() = Some(err.to_string()),
}
result
}
fn sync_locked(
&self,
home_dir: Option<&Path>,
base_dir: &Path,
should_register: bool,
) -> IdeResult<BootServiceState> {
let platform = self.effective_platform();
let Some(target) = self.service_file_path(home_dir) else {
return Ok(self.status(home_dir, false));
};
let use_os = self.uses_os_commands();
if should_register {
let exe = self
.scheduler_executable()
.ok_or_else(|| IdeError::unavailable("cannot locate OpenIDEA executable for --scheduler"))?;
let content = render_service_file_for(platform, &exe, base_dir)?;
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent)?;
}
let file_changed = std::fs::read_to_string(&target).ok().as_deref() != Some(content.as_str());
if file_changed {
ide_vfs::write_atomic(&target, content.as_bytes())?;
}
if use_os {
let already_registered = self.is_os_registered(platform, &target);
if file_changed || !already_registered {
self.activate_os_service(platform, &target)?;
}
}
} else {
if use_os {
// Propagate unknown status BEFORE touching `target` so the file stays for retry!
let presence = self.query_os_presence(platform)?;
if presence.is_loaded_or_active() || target.exists() {
self.deactivate_os_service(platform, presence)?;
}
}
if target.exists() {
match std::fs::remove_file(&target) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
}
}
Ok(BootServiceState {
kind: Self::service_kind_for(platform, false).to_owned(),
registered: self.is_os_registered(platform, &target),
path: Some(IpcPath(target)),
error: None,
linux_linger_enabled: if platform == ServicePlatform::Linux { Some(check_linux_linger()) } else { None },
})
}
fn activate_os_service(&self, platform: ServicePlatform, path: &Path) -> IdeResult<()> {
let path_str = path
.to_str()
.ok_or_else(|| IdeError::invalid(format!("service file path is not valid UTF-8: {}", path.display())))?;
match platform {
ServicePlatform::Macos => {
let domain = Self::macos_domain();
let job = format!("{domain}/{SERVICE_LABEL}");
if self.query_os_presence(platform).is_ok_and(OsServicePresence::is_loaded_or_active) {
let _ = self.run_command("launchctl", &["bootout", &job]);
}
self.run_checked("launchctl", &["bootstrap", &domain, path_str])?;
Ok(())
}
ServicePlatform::Linux => {
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
self.run_checked("systemctl", &["--user", "enable", SYSTEMD_UNIT_NAME])?;
Ok(())
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
}
}
fn deactivate_os_service(&self, platform: ServicePlatform, presence: OsServicePresence) -> IdeResult<()> {
match platform {
ServicePlatform::Macos => {
let domain = Self::macos_domain();
let job = format!("{domain}/{SERVICE_LABEL}");
if presence.is_loaded_or_active() {
let (code, stdout, stderr) = self.run_command("launchctl", &["bootout", &job])?;
let after = self.query_os_presence(platform)?;
if code != 0 && after.is_loaded_or_active() {
let detail = if stderr.trim().is_empty() { stdout.trim() } else { stderr.trim() };
return Err(IdeError::internal(format!(
"launchctl bootout {job} exited with {code}: {detail}"
)));
}
}
Ok(())
}
ServicePlatform::Linux => {
match presence {
OsServicePresence::RegisteredAndActive | OsServicePresence::RegisteredIdle => {
self.run_checked("systemctl", &["--user", "disable", "--now", SYSTEMD_UNIT_NAME])?;
}
OsServicePresence::ActiveUnregistered => {
self.run_checked("systemctl", &["--user", "stop", SYSTEMD_UNIT_NAME])?;
}
OsServicePresence::Absent => {}
}
self.run_checked("systemctl", &["--user", "daemon-reload"])?;
Ok(())
}
ServicePlatform::Windows | ServicePlatform::Other => Ok(()),
}
}
}
pub fn render_service_file(exe: &Path, base_dir: &Path) -> IdeResult<String> {
render_service_file_for(ServicePlatform::host(), exe, base_dir)
}
pub fn render_service_file_for(platform: ServicePlatform, exe: &Path, base_dir: &Path) -> IdeResult<String> {
match platform {
ServicePlatform::Macos => render_macos_plist(exe, base_dir),
ServicePlatform::Windows => render_windows_cmd(exe, base_dir),
ServicePlatform::Linux | ServicePlatform::Other => render_systemd_unit(exe, base_dir),
}
}
fn validate_roundtrip_path<'a>(path: &'a Path, label: &str) -> IdeResult<&'a str> {
let s = path.to_str().ok_or_else(|| IdeError::invalid(format!("{label} path is not valid UTF-8")))?;
if s.is_empty() {
return Err(IdeError::invalid(format!("{label} path cannot be empty")));
}
let has_root = path.is_absolute() || s.starts_with('/') || (s.len() >= 3 && s.as_bytes()[1] == b':');
if !has_root {
return Err(IdeError::invalid(format!("{label} path must be absolute: {s}")));
}
if s.chars().any(char::is_control) {
return Err(IdeError::invalid(format!(
"{label} path contains control characters or line breaks that cannot round-trip in a service file"
)));
}
Ok(s)
}
pub fn render_macos_plist(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_str = validate_roundtrip_path(exe, "scheduler executable")?;
let home_str = validate_roundtrip_path(base_dir, "scheduler data")?;
let log_path = base_dir.join("logs").join("scheduler.log");
let log_str = validate_roundtrip_path(&log_path, "scheduler log")?;
let exe_esc = xml_escape(exe_str);
let home_esc = xml_escape(home_str);
let log_esc = xml_escape(log_str);
Ok(format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>{SERVICE_LABEL}</string>
<key>AssociatedBundleIdentifiers</key>
<array>
<string>ai.l0ng.openidea</string>
</array>
<key>LimitLoadToSessionType</key>
<string>Aqua</string>
<key>ProgramArguments</key>
<array>
<string>{exe_esc}</string>
<string>--scheduler</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>OPENIDEA_SERVER_HOME</key>
<string>{home_esc}</string>
</dict>
<key>RunAtLoad</key>
<true/>
<key>StandardErrorPath</key>
<string>{log_esc}</string>
</dict>
</plist>
"#
))
}
pub fn render_systemd_unit(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
// Both `Environment=` and the executable path (`argv[0]`) of `ExecStart=` are resolved before
// `$` variable expansion (`systemd.exec(5)`, `systemd.service(5)`), so `$` stays literal!
let exe_str = systemd_escape_literal_quoted(exe_raw);
let home_str = systemd_escape_literal_quoted(home_raw);
Ok(format!(
"[Unit]\n\
Description=OpenIDEA Headless Agent Automation Scheduler\n\
After=network-online.target\n\
\n\
[Service]\n\
Type=simple\n\
Environment=\"OPENIDEA_SERVER_HOME={home_str}\"\n\
ExecStart=\"{exe_str}\" --scheduler\n\
Restart=on-failure\n\
RestartSec=10\n\
\n\
[Install]\n\
WantedBy=default.target\n"
))
}
pub fn render_windows_cmd(exe: &Path, base_dir: &Path) -> IdeResult<String> {
let exe_raw = validate_roundtrip_path(exe, "scheduler executable")?;
let home_raw = validate_roundtrip_path(base_dir, "scheduler data")?;
if exe_raw.contains('"') || home_raw.contains('"') {
return Err(IdeError::invalid("Windows Startup script path cannot contain '\"'"));
}
let home_esc = cmd_escape(home_raw);
let exe_esc = cmd_escape(exe_raw);
Ok(format!("@echo off\r\nset \"OPENIDEA_SERVER_HOME={home_esc}\"\r\nstart \"\" /B \"{exe_esc}\" --scheduler\r\n"))
}
/// Escapes a double-quoted systemd value where `$` is literal (`Environment="KEY=VALUE"` and
/// `ExecStart="EXECUTABLE"` `argv[0]`): specifiers (`%` -> `%%`) and C escapes (`\` -> `\\`,
/// `"` -> `\"`) are interpreted, while `$` must remain literal.
fn systemd_escape_literal_quoted(s: &str) -> String {
s.replace('\\', "\\\\").replace('"', "\\\"").replace('%', "%%")
}
fn cmd_escape(s: &str) -> String {
s.replace('%', "%%")
}
fn xml_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&apos;")
}
fn check_linux_linger() -> bool {
if let Ok(user) = std::env::var("USER").or_else(|_| std::env::var("LOGNAME"))
&& !user.is_empty()
&& Path::new("/var/lib/systemd/linger").join(user).exists()
{
return true;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
fn unescape_systemd_quoted(s: &str, expand_dollars: bool) -> String {
let after_specifiers = s.replace("%%", "%");
let after_dollars = if expand_dollars { after_specifiers.replace("$$", "$") } else { after_specifiers };
let mut out = String::new();
let mut chars = after_dollars.chars();
while let Some(c) = chars.next() {
if c == '\\' {
if let Some(next) = chars.next() {
out.push(next);
}
} else {
out.push(c);
}
}
out
}
#[test]
fn systemd_unit_encodes_environment_and_exec_start_with_distinct_rules_and_rejects_bad_paths() {
let exe = Path::new("/opt/openidea$bin/with \"quotes\"\\slash/open%idea");
let home = Path::new("/home/dev&co/100%data$dir/\"sub\"\\path");
let plist = render_macos_plist(exe, home).unwrap();
assert!(plist.contains("dev&amp;co"));
let unit = render_systemd_unit(exe, home).unwrap();
let env_line = unit.lines().find(|l| l.starts_with("Environment=")).unwrap();
let exec_line = unit.lines().find(|l| l.starts_with("ExecStart=")).unwrap();
// Both Environment= and ExecStart= argv[0] keep `$` literal while escaping `\`, `"`, and `%`.
assert!(env_line.contains("100%%data$dir"));
assert!(!env_line.contains("data$$dir"));
let env_inner =
env_line.strip_prefix("Environment=\"OPENIDEA_SERVER_HOME=").unwrap().strip_suffix('"').unwrap();
assert_eq!(unescape_systemd_quoted(env_inner, false), home.to_str().unwrap());
assert!(exec_line.contains("openidea$bin"));
assert!(!exec_line.contains("openidea$$bin"));
assert!(exec_line.contains("open%%idea"));
let exec_inner = exec_line.strip_prefix("ExecStart=\"").unwrap().strip_suffix("\" --scheduler").unwrap();
assert_eq!(unescape_systemd_quoted(exec_inner, false), exe.to_str().unwrap());
// Windows .cmd rejects embedded quotes and round-trips `%` and `$`.
assert!(render_windows_cmd(exe, home).is_err());
let win_ok = render_windows_cmd(
Path::new(r"C:\Program Files\OpenIDEA\open%idea$1.exe"),
Path::new(r"C:\Users\dev&co\100%data$dir"),
)
.unwrap();
assert!(win_ok.contains("100%%data$dir"));
assert!(win_ok.contains("open%%idea$1.exe"));
// Line breaks, NULs, and relative paths are rejected across all platforms.
assert!(render_systemd_unit(Path::new("/opt/openidea\nExecStart=/bin/sh"), home).is_err());
assert!(render_systemd_unit(exe, Path::new("/home/user\r\nBad=1")).is_err());
assert!(render_systemd_unit(Path::new("relative/openidea"), home).is_err());
assert!(render_macos_plist(Path::new("/Applications/OpenIDEA\nBad"), home).is_err());
}
#[cfg(unix)]
#[test]
fn systemd_unit_rejects_non_utf8_paths() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let bad = Path::new(OsStr::from_bytes(b"/tmp/openidea-\xff"));
assert!(render_systemd_unit(bad, Path::new("/tmp/home")).is_err());
}
#[test]
fn boot_service_checks_real_registration_retries_unchanged_file_and_stops_on_disable() {
let tmp = tempfile::tempdir().unwrap();
let mgr = BootServiceManager::with_override_dir(Some(tmp.path().join("units")));
mgr.set_executable_override(Some(PathBuf::from("/usr/local/bin/openidea-server")));
let enabled = Arc::new(AtomicBool::new(false));
let active = Arc::new(AtomicBool::new(false));
let fail_next_enable = Arc::new(AtomicBool::new(true));
let fail_next_disable = Arc::new(AtomicBool::new(true));
let disable_now_calls = Arc::new(AtomicUsize::new(0));
let enabled_c = enabled.clone();
let active_c = active.clone();
let fail_en_c = fail_next_enable.clone();
let fail_dis_c = fail_next_disable.clone();
let dis_calls_c = disable_now_calls.clone();
mgr.set_command_runner_for_test(
ServicePlatform::Linux,
Some(Arc::new(move |prog, args| {
assert_eq!(prog, "systemctl");
match args {
["--user", "is-enabled", u] if *u == SYSTEMD_UNIT_NAME => {
if enabled_c.load(Ordering::Acquire) {
Ok((0, "enabled\n".into(), String::new()))
} else {
Ok((1, "disabled\n".into(), String::new()))
}
}
["--user", "is-active", u] if *u == SYSTEMD_UNIT_NAME => {
if active_c.load(Ordering::Acquire) {
Ok((0, "active\n".into(), String::new()))
} else {
Ok((3, "inactive\n".into(), String::new()))
}
}
["--user", "daemon-reload"] => Ok((0, String::new(), String::new())),
["--user", "enable", u] if *u == SYSTEMD_UNIT_NAME => {
if fail_en_c.swap(false, Ordering::AcqRel) {
Ok((1, String::new(), "dbus unavailable".into()))
} else {
enabled_c.store(true, Ordering::Release);
active_c.store(true, Ordering::Release);
Ok((0, String::new(), String::new()))
}
}
["--user", "disable", "--now", u] if *u == SYSTEMD_UNIT_NAME => {
dis_calls_c.fetch_add(1, Ordering::AcqRel);
if fail_dis_c.swap(false, Ordering::AcqRel) {
Ok((1, String::new(), "unit busy".into()))
} else {
enabled_c.store(false, Ordering::Release);
active_c.store(false, Ordering::Release);
Ok((0, String::new(), String::new()))
}
}
other => panic!("unexpected systemctl args: {other:?}"),
}
})),
);
let home = tmp.path();
let data = tmp.path().join("data");
std::fs::create_dir_all(&data).unwrap();
// 1. First sync writes the unit file, `systemctl enable` fails -> returns Err and status is NOT registered
// even though the unit file already exists on disk!
assert!(mgr.sync(Some(home), &data, true).is_err());
let st_failed = mgr.status(Some(home), true);
assert!(!st_failed.registered, "file exists alone must not report registered when systemctl failed");
assert!(st_failed.error.as_deref().unwrap_or_default().contains("dbus unavailable"));
// 2. Second sync with identical parameters (unchanged file on disk!) retries `systemctl enable` and succeeds.
let st_ok = mgr.sync(Some(home), &data, true).unwrap();
assert!(st_ok.registered);
assert!(st_ok.error.is_none());
// 3. Disabling when `systemctl disable --now` fails preserves the unit file and retryability.
assert!(mgr.sync(Some(home), &data, false).is_err());
assert!(mgr.service_file_path(Some(home)).unwrap().is_file(), "unit file kept so unregister can retry");
assert!(mgr.status(Some(home), true).registered);
// 4. Retrying disable runs `systemctl --user disable --now` (stopping the worker), removes the file, and clears status.
let st_off = mgr.sync(Some(home), &data, false).unwrap();
assert!(!st_off.registered);
assert!(!active.load(Ordering::Acquire), "running worker stopped on disable");
assert_eq!(disable_now_calls.load(Ordering::Acquire), 2);
assert!(!mgr.service_file_path(Some(home)).unwrap().exists());
// 5. Unknown OS query status (e.g. D-Bus unreachable) MUST NOT treat worker as absent or delete unit file!
let status_unknown = Arc::new(AtomicBool::new(false));
let status_unknown_c = status_unknown.clone();
let macos_loaded = Arc::new(AtomicBool::new(false));
let macos_loaded_c = macos_loaded.clone();
mgr.set_command_runner_for_test(
ServicePlatform::Macos,
Some(Arc::new(move |prog, args| {
assert_eq!(prog, "launchctl");
match args {
["print", _] => {
if status_unknown_c.load(Ordering::Acquire) {
Ok((1, String::new(), "IPC transport error".into()))
} else if macos_loaded_c.load(Ordering::Acquire) {
Ok((0, "state = running\n".into(), String::new()))
} else {
Ok((113, String::new(), "Could not find service\n".into()))
}
}
["bootstrap", _, _] => {
macos_loaded_c.store(true, Ordering::Release);
Ok((0, String::new(), String::new()))
}
["bootout", _] => {
macos_loaded_c.store(false, Ordering::Release);
Ok((0, String::new(), String::new()))
}
other => panic!("unexpected launchctl args: {other:?}"),
}
})),
);
mgr.sync(Some(home), &data, true).unwrap();
let plist_path = mgr.service_file_path(Some(home)).unwrap();
assert!(plist_path.is_file());
// Simulate transient launchd query failure on disable -> keeps plist file on disk for retry!
status_unknown.store(true, Ordering::Release);
assert!(mgr.sync(Some(home), &data, false).is_err());
assert!(plist_path.is_file(), "plist must be preserved when OS status is unknown");
assert!(macos_loaded.load(Ordering::Acquire));
// Restore launchd query -> retry succeeds, unloads worker, and deletes plist!
status_unknown.store(false, Ordering::Release);
mgr.sync(Some(home), &data, false).unwrap();
assert!(!macos_loaded.load(Ordering::Acquire));
assert!(!plist_path.exists());
}
}
File diff suppressed because it is too large. Load diff
+577
Переглянути файл
@@ -0,0 +1,577 @@
//! Cross-process owner locks, abandonment detection, and authenticated loopback RPC bridge
//! so live runs owned by `openidea --scheduler` (or `ChatOnly` / headless `AgentManager`s)
//! stream `AgentEvent`s to open windows and accept permission approvals (`agent_respond`,
//! `agent_answer_question`, `agent_cancel`, `agent_entries`, etc.).
use ide_agent::{AgentEntry, AgentEvent, AgentManager, AgentPrompt, AgentTask};
use ide_core::{CancellationToken, IdeError, IdeResult};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::broadcast;
const OWNERS_DIR: &str = "owners";
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OwnerEndpoint {
pub instance_id: String,
pub pid: u32,
pub addr: String,
pub token: String,
}
#[derive(Clone, Debug)]
pub struct RoutedAgentEvent {
pub project_root: Option<PathBuf>,
pub event: AgentEvent,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "camelCase", rename_all_fields = "camelCase")]
enum PeerRequest {
Subscribe { token: String, allowed_roots: Vec<PathBuf>, include_chat_only: bool },
Entries { token: String, task: String, subagent: Option<String> },
Respond { token: String, task: String, permission: u32, option: Option<String> },
AnswerQuestion { token: String, task: String, question: String, answer: Option<String> },
Cancel { token: String, task: String, subagent: Option<String> },
StopBackground { token: String, task: String, background: String },
Prompt { token: String, task: String, prompt: AgentPrompt, now: bool },
StopIdleWorker { token: String },
}
pub type ResolveManagerFn = Arc<dyn Fn(&str) -> Option<Arc<AgentManager>> + Send + Sync>;
pub type ListLiveTasksFn = Arc<dyn Fn(&[PathBuf], bool) -> Vec<AgentTask> + Send + Sync>;
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")]
enum PeerStreamItem {
Snapshot { tasks: Vec<AgentTask> },
Event { event: Box<AgentEvent> },
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "camelCase")]
enum PeerReply<T> {
Ok { value: T },
Err { error: String },
}
pub fn owners_dir(automations_dir: &Path) -> PathBuf {
automations_dir.join(OWNERS_DIR)
}
/// Checks whether `owner_id` holds an active OS lock in `automations_dir/owners/`.
/// If the lock can be acquired immediately, that process has exited/crashed and its stale
/// lock/endpoint files are cleaned up.
pub fn is_owner_alive(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> bool {
if owner_id.is_empty() {
return false;
}
if owner_id == self_instance_id {
return true;
}
let dir = owners_dir(automations_dir);
let lock_path = dir.join(format!("{owner_id}.lock"));
let Ok(file) = std::fs::OpenOptions::new().read(true).write(true).open(&lock_path) else {
return false;
};
if file.try_lock().is_ok() {
let _ = file.unlock();
drop(file);
let _ = std::fs::remove_file(&lock_path);
let _ = std::fs::remove_file(dir.join(format!("{owner_id}.json")));
false
} else {
true
}
}
pub fn read_live_endpoint(automations_dir: &Path, self_instance_id: &str, owner_id: &str) -> Option<OwnerEndpoint> {
if !is_owner_alive(automations_dir, self_instance_id, owner_id) {
return None;
}
let path = owners_dir(automations_dir).join(format!("{owner_id}.json"));
let bytes = std::fs::read(path).ok()?;
serde_json::from_slice(&bytes).ok()
}
pub fn list_live_peer_endpoints(automations_dir: &Path, self_instance_id: &str) -> Vec<OwnerEndpoint> {
let dir = owners_dir(automations_dir);
let Ok(entries) = std::fs::read_dir(&dir) else {
return Vec::new();
};
let mut out = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if path.extension().is_none_or(|e| e != "json") {
continue;
}
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
continue;
};
if stem == self_instance_id {
continue;
}
if let Some(ep) = read_live_endpoint(automations_dir, self_instance_id, stem) {
out.push(ep);
}
}
out
}
pub struct OwnerNode {
pub instance_id: String,
lock_file: Mutex<Option<std::fs::File>>,
endpoint_path: Mutex<Option<PathBuf>>,
pub events_tx: broadcast::Sender<RoutedAgentEvent>,
worker_stop_requested: std::sync::atomic::AtomicBool,
subscriptions: Mutex<HashMap<String, CancellationToken>>,
}
impl OwnerNode {
pub fn new(instance_id: String) -> Self {
let (events_tx, _) = broadcast::channel(512);
Self {
instance_id,
lock_file: Mutex::new(None),
endpoint_path: Mutex::new(None),
events_tx,
worker_stop_requested: std::sync::atomic::AtomicBool::new(false),
subscriptions: Mutex::new(HashMap::new()),
}
}
pub fn worker_stop_requested(&self) -> bool {
self.worker_stop_requested.load(std::sync::atomic::Ordering::Acquire)
}
/// Acquires `owners/<instance_id>.lock` (idempotent) so any peer can tell this process is alive.
pub fn ensure_lock(&self, automations_dir: &Path) -> IdeResult<()> {
let mut guard = self.lock_file.lock();
if guard.is_some() {
return Ok(());
}
let dir = owners_dir(automations_dir);
std::fs::create_dir_all(&dir)?;
let lock_path = dir.join(format!("{}.lock", self.instance_id));
let file = std::fs::OpenOptions::new().create(true).read(true).write(true).truncate(false).open(&lock_path)?;
file.try_lock()
.map_err(|e| IdeError::internal(format!("cannot acquire owner lock {}: {e}", lock_path.display())))?;
*guard = Some(file);
Ok(())
}
/// Starts the authenticated loopback RPC server for live run events and approvals.
pub fn start_server(
&self,
automations_dir: &Path,
runtime: &tokio::runtime::Handle,
shutdown: CancellationToken,
resolve_mgr: ResolveManagerFn,
list_live_tasks: ListLiveTasksFn,
node_ref: Arc<OwnerNode>,
) {
if self.ensure_lock(automations_dir).is_err() {
return;
}
if self.endpoint_path.lock().is_some() {
return;
}
let dir = owners_dir(automations_dir);
let token = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
let Ok(std_listener) = std::net::TcpListener::bind("127.0.0.1:0") else {
return;
};
if std_listener.set_nonblocking(true).is_err() {
return;
}
let Ok(local_addr) = std_listener.local_addr() else {
return;
};
let instance_id = self.instance_id.clone();
let json_path = dir.join(format!("{instance_id}.json"));
let ep = OwnerEndpoint {
instance_id: instance_id.clone(),
pid: std::process::id(),
addr: local_addr.to_string(),
token: token.clone(),
};
if let Ok(bytes) = serde_json::to_vec_pretty(&ep) {
let _ = write_private_file(&json_path, &bytes);
}
*self.endpoint_path.lock() = Some(json_path.clone());
runtime.spawn(async move {
let Ok(listener) = TcpListener::from_std(std_listener) else {
let _ = std::fs::remove_file(&json_path);
return;
};
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
accepted = listener.accept() => {
let Ok((stream, _)) = accepted else { continue };
let token_c = token.clone();
let resolve_c = resolve_mgr.clone();
let list_c = list_live_tasks.clone();
let shutdown_c = shutdown.clone();
let node_c = node_ref.clone();
tokio::spawn(async move {
handle_peer_conn(stream, token_c, resolve_c, list_c, shutdown_c, node_c).await;
});
}
}
}
let _ = std::fs::remove_file(&json_path);
});
}
pub fn stop(&self, automations_dir: &Path) {
for (_, cancel) in self.subscriptions.lock().drain() {
cancel.cancel();
}
if let Some(ep_path) = self.endpoint_path.lock().take() {
let _ = std::fs::remove_file(ep_path);
}
if let Some(file) = self.lock_file.lock().take() {
let _ = file.unlock();
}
let _ = std::fs::remove_file(owners_dir(automations_dir).join(format!("{}.lock", self.instance_id)));
}
pub fn replace_subscriber(&self, subscriber: &str) -> CancellationToken {
let token = CancellationToken::new();
if let Some(prev) = self.subscriptions.lock().insert(subscriber.to_owned(), token.clone()) {
prev.cancel();
}
token
}
pub fn unsubscribe(&self, subscriber: &str) {
if let Some(prev) = self.subscriptions.lock().remove(subscriber) {
prev.cancel();
}
}
}
fn write_private_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let mut f = std::fs::OpenOptions::new().create(true).write(true).truncate(true).mode(0o600).open(path)?;
f.write_all(bytes)?;
f.sync_all()
}
#[cfg(not(unix))]
{
std::fs::write(path, bytes)
}
}
async fn handle_peer_conn(
stream: TcpStream,
expected_token: String,
resolve_mgr: ResolveManagerFn,
list_live_tasks: ListLiveTasksFn,
shutdown: CancellationToken,
node: Arc<OwnerNode>,
) {
let (reader, mut writer) = stream.into_split();
let mut lines = BufReader::new(reader).lines();
let Ok(Some(first_line)) = lines.next_line().await else {
return;
};
let Ok(req) = serde_json::from_str::<PeerRequest>(&first_line) else {
return;
};
let req_token = match &req {
PeerRequest::Subscribe { token, .. }
| PeerRequest::Entries { token, .. }
| PeerRequest::Respond { token, .. }
| PeerRequest::AnswerQuestion { token, .. }
| PeerRequest::Cancel { token, .. }
| PeerRequest::StopBackground { token, .. }
| PeerRequest::Prompt { token, .. }
| PeerRequest::StopIdleWorker { token } => token,
};
if req_token != &expected_token {
let _ = write_json_line(&mut writer, &PeerReply::<()>::err("unauthorized")).await;
return;
}
match req {
PeerRequest::Subscribe { allowed_roots, include_chat_only, .. } => {
let mut rx = node.events_tx.subscribe();
let canon_allowed: Vec<PathBuf> =
allowed_roots.into_iter().map(|p| dunce::canonicalize(&p).unwrap_or(p)).collect();
let initial = list_live_tasks(&canon_allowed, include_chat_only);
if write_json_line(&mut writer, &PeerStreamItem::Snapshot { tasks: initial }).await.is_err() {
return;
}
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
recv = rx.recv() => {
match recv {
Ok(routed) => {
let matches = match &routed.project_root {
None => include_chat_only,
Some(actual) => {
let cand = dunce::canonicalize(actual).unwrap_or_else(|_| actual.clone());
canon_allowed.iter().any(|w| w == &cand)
}
};
if matches
&& write_json_line(
&mut writer,
&PeerStreamItem::Event { event: Box::new(routed.event) },
)
.await
.is_err()
{
break;
}
}
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(broadcast::error::RecvError::Closed) => break,
}
}
}
}
}
PeerRequest::Entries { task, subagent, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => tokio::task::spawn_blocking(move || mgr.entries(&task, subagent))
.await
.map_err(|e| IdeError::internal(e.to_string()))
.and_then(|r| r),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Respond { task, permission, option, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.respond(&task, permission, option),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::AnswerQuestion { task, question, answer, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.answer_question(&task, &question, answer).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Cancel { task, subagent, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.cancel(&task, subagent),
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::StopBackground { task, background, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.stop_background(&task, &background).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::Prompt { task, prompt, now, .. } => {
let res = match resolve_mgr(&task) {
Some(mgr) => mgr.prompt(&task, prompt, now).await,
None => Err(IdeError::not_found(format!("unknown task {task}"))),
};
let _ = write_json_line(&mut writer, &PeerReply::from_res(res)).await;
}
PeerRequest::StopIdleWorker { .. } => {
node.worker_stop_requested.store(true, std::sync::atomic::Ordering::Release);
let _ = write_json_line(&mut writer, &PeerReply::from_res(Ok(()))).await;
}
}
}
impl<T> PeerReply<T> {
fn from_res(res: IdeResult<T>) -> Self {
match res {
Ok(value) => Self::Ok { value },
Err(e) => Self::Err { error: e.to_string() },
}
}
fn err(msg: &str) -> Self {
Self::Err { error: msg.to_owned() }
}
}
async fn write_json_line<W: AsyncWriteExt + Unpin, T: Serialize>(writer: &mut W, msg: &T) -> std::io::Result<()> {
let mut line = serde_json::to_vec(msg).map_err(std::io::Error::other)?;
line.push(b'\n');
writer.write_all(&line).await?;
writer.flush().await
}
async fn call_peer<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
let mut stream = TcpStream::connect(&ep.addr)
.await
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
write_json_line(&mut stream, req)
.await
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
let mut lines = BufReader::new(stream).lines();
let raw = lines
.next_line()
.await
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?
.ok_or_else(|| IdeError::unavailable("automation worker closed connection without replying"))?;
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
PeerReply::Ok { value } => Ok(value),
PeerReply::Err { error } => Err(IdeError::internal(error)),
}
}
fn call_peer_sync<T: for<'de> Deserialize<'de>>(ep: &OwnerEndpoint, req: &PeerRequest) -> IdeResult<T> {
use std::io::{BufRead, Write};
let addr: std::net::SocketAddr = ep
.addr
.parse()
.map_err(|e| IdeError::internal(format!("invalid automation worker address {}: {e}", ep.addr)))?;
let mut stream = std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_secs(3))
.map_err(|e| IdeError::unavailable(format!("cannot reach live automation worker at {}: {e}", ep.addr)))?;
let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5)));
let _ = stream.set_write_timeout(Some(std::time::Duration::from_secs(5)));
let mut line = serde_json::to_vec(req).map_err(|e| IdeError::internal(e.to_string()))?;
line.push(b'\n');
stream
.write_all(&line)
.and_then(|()| stream.flush())
.map_err(|e| IdeError::unavailable(format!("failed sending request to automation worker: {e}")))?;
let mut reader = std::io::BufReader::new(stream);
let mut raw = String::new();
reader
.read_line(&mut raw)
.map_err(|e| IdeError::unavailable(format!("failed reading automation worker reply: {e}")))?;
if raw.trim().is_empty() {
return Err(IdeError::unavailable("automation worker closed connection without replying"));
}
match serde_json::from_str::<PeerReply<T>>(&raw).map_err(|e| IdeError::internal(e.to_string()))? {
PeerReply::Ok { value } => Ok(value),
PeerReply::Err { error } => Err(IdeError::internal(error)),
}
}
pub async fn peer_entries(ep: &OwnerEndpoint, task: String, subagent: Option<String>) -> IdeResult<Vec<AgentEntry>> {
call_peer(ep, &PeerRequest::Entries { token: ep.token.clone(), task, subagent }).await
}
pub fn peer_respond(
_runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
task: String,
permission: u32,
option: Option<String>,
) -> IdeResult<()> {
let token = ep.token.clone();
call_peer_sync(&ep, &PeerRequest::Respond { token, task, permission, option })
}
pub async fn peer_answer_question(
ep: &OwnerEndpoint,
task: String,
question: String,
answer: Option<String>,
) -> IdeResult<()> {
call_peer(ep, &PeerRequest::AnswerQuestion { token: ep.token.clone(), task, question, answer }).await
}
pub fn peer_cancel(
_runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
task: String,
subagent: Option<String>,
) -> IdeResult<()> {
let token = ep.token.clone();
call_peer_sync(&ep, &PeerRequest::Cancel { token, task, subagent })
}
pub async fn peer_stop_background(ep: &OwnerEndpoint, task: String, background: String) -> IdeResult<()> {
call_peer(ep, &PeerRequest::StopBackground { token: ep.token.clone(), task, background }).await
}
pub async fn peer_prompt(ep: &OwnerEndpoint, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
call_peer(ep, &PeerRequest::Prompt { token: ep.token.clone(), task, prompt, now }).await
}
pub fn notify_peers_stop_if_headless(runtime: &tokio::runtime::Handle, endpoints: Vec<OwnerEndpoint>) {
for ep in endpoints {
runtime.spawn(async move {
let token = ep.token.clone();
let _: IdeResult<()> = call_peer(&ep, &PeerRequest::StopIdleWorker { token }).await;
});
}
}
/// Connects to `ep`, fetches its initial live task snapshot synchronously (with a short timeout),
/// and spawns an async forwarder streaming subsequent `AgentEvent`s until `cancel` triggers.
pub fn attach_peer_stream(
runtime: &tokio::runtime::Handle,
ep: OwnerEndpoint,
allowed_roots: Vec<PathBuf>,
include_chat_only: bool,
cancel: CancellationToken,
on_event: Arc<dyn Fn(AgentEvent) + Send + Sync>,
) -> Vec<AgentTask> {
let (snap_tx, snap_rx) = std::sync::mpsc::channel();
runtime.spawn(async move {
let connect_fut = TcpStream::connect(&ep.addr);
let Ok(Ok(mut stream)) = tokio::time::timeout(std::time::Duration::from_secs(2), connect_fut).await else {
let _ = snap_tx.send(Vec::new());
return;
};
let req = PeerRequest::Subscribe { token: ep.token.clone(), allowed_roots, include_chat_only };
if write_json_line(&mut stream, &req).await.is_err() {
let _ = snap_tx.send(Vec::new());
return;
}
let mut lines = BufReader::new(stream).lines();
match tokio::time::timeout(std::time::Duration::from_secs(2), lines.next_line()).await {
Ok(Ok(Some(first))) => match serde_json::from_str::<PeerStreamItem>(&first) {
Ok(PeerStreamItem::Snapshot { tasks }) => {
let _ = snap_tx.send(tasks);
}
_ => {
let _ = snap_tx.send(Vec::new());
return;
}
},
_ => {
let _ = snap_tx.send(Vec::new());
return;
}
}
loop {
tokio::select! {
_ = cancel.cancelled() => break,
next = lines.next_line() => {
match next {
Ok(Some(line)) => {
if let Ok(PeerStreamItem::Event { event }) = serde_json::from_str::<PeerStreamItem>(&line) {
on_event(*event);
}
}
_ => break,
}
}
}
}
});
snap_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap_or_default()
}
+86 -17
Переглянути файл
@@ -18,6 +18,7 @@ use std::sync::{Arc, OnceLock};
enum Mode {
Stdio,
Scheduler,
#[cfg(unix)]
Daemon(PathBuf, ide_host::daemon::BuildId),
}
@@ -29,6 +30,7 @@ usage:
openidea-server --web [options] [<project>]
openidea-server --stdio
openidea-server --attach <project-path>
openidea-server --scheduler
openidea-server --mcp-stdio [--project <path>]
openidea-server --connect <host> <port>
openidea-server --version
@@ -233,6 +235,7 @@ fn main() {
}
#[cfg(not(unix))]
[flag, _] if flag == "--attach" => Mode::Stdio,
_ if args.iter().any(|a| a == "--scheduler") => Mode::Scheduler,
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
_ => {
print_usage();
@@ -292,17 +295,21 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
let peer = Arc::new(OnceLock::new());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
let host = Arc::new(
Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
})
// The client answers no svn prompts here: svn runs non-interactively.
.with_subversion(false),
);
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
@@ -312,23 +319,85 @@ async fn run(base: PathBuf, mode: Mode) -> i32 {
shutdown_all(&host, plugins.as_ref()).await;
0
}
#[cfg(unix)]
Mode::Daemon(socket, build) => {
let peer = Arc::new(rpc::PeerSlot::default());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
Mode::Scheduler => {
let host = Arc::new(Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
sink_for: Box::new(|_| Arc::new(ide_core::NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
}));
start_mcp(&host, &base);
inherit_trust(&host);
host.automations.set_headless_worker_mode(true);
host.automations.start(&host);
tracing::info!("openidea-server {} headless scheduler started", env!("CARGO_PKG_VERSION"));
let mut idle_ticks = 0u32;
let mut check = tokio::time::interval(std::time::Duration::from_secs(5));
#[cfg(unix)]
let mut terminate =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("SIGTERM listener");
loop {
#[cfg(unix)]
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
_ = terminate.recv() => break,
_ = check.tick() => {}
}
#[cfg(not(unix))]
tokio::select! {
_ = tokio::signal::ctrl_c() => break,
_ = check.tick() => {}
}
let service_enabled = ide_workspace::SettingsStore::load(&host.config_dir, None)
.effective()
.agents
.automations
.auto_start_service;
let running = host.automations.has_running_runs();
if host.automations.worker_stop_requested() || !service_enabled {
if !running {
tracing::info!("headless scheduler login service disabled; exiting");
break;
}
} else if host.automations.has_enabled_schedules() || running {
idle_ticks = 0;
} else {
idle_ticks += 1;
if idle_ticks >= 3 {
tracing::info!("no enabled automations remain; headless scheduler exiting");
break;
}
}
}
shutdown_all(&host, None).await;
0
}
#[cfg(unix)]
Mode::Daemon(socket, build) => {
let peer = Arc::new(rpc::PeerSlot::default());
let sink_peer = peer.clone();
let plugins_data = data_dir.clone();
let host = Arc::new(
Host::new(HostConfig {
config_dir,
local_data_dir: data_dir.clone(),
data_dir,
languages,
syntax: Arc::default(),
sink_for: Box::new(move |window| rpc::event_sink(sink_peer.clone(), Some(window.to_owned()))),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: true,
})
// The client answers no svn prompts here: svn runs non-interactively.
.with_subversion(false),
);
start_mcp(&host, &base);
let plugins = start_plugins(&plugins_data, &host, peer.clone());
inherit_trust(&host);
tracing::info!("openidea-server {} daemon ready at {}", env!("CARGO_PKG_VERSION"), socket.display());
+2
Переглянути файл
@@ -398,6 +398,7 @@ pub async fn serve(
};
let shutdown = CancellationToken::new();
host.automations.start(&host);
let idle_policy = RemoteIdlePolicy { override_seconds: idle_override() };
let mut check = tokio::time::interval(Duration::from_secs(idle_policy.override_seconds.unwrap_or(5).min(5)));
let mut idle = None;
@@ -541,6 +542,7 @@ fn has_live_work(host: &Host) -> bool {
!host.terminals.list().is_empty()
|| host.processes.has_live_runs()
|| !host.debugger.sessions(None).is_empty()
|| host.automations.keeps_remote_daemon_alive(host)
|| host
.projects()
.iter()
+29 -1
Переглянути файл
@@ -4,6 +4,7 @@
//! runs one on a remote machine and serves it over JSON-RPC ([`rpc`]).
pub mod agent_secrets;
pub mod automations;
pub mod catalogue;
#[cfg(unix)]
pub mod daemon;
@@ -27,6 +28,7 @@ pub mod relay;
mod requests;
pub mod rpc;
pub mod shell_env;
pub mod svn;
mod swiftlint;
pub mod trust;
mod ts_code_style;
@@ -92,6 +94,8 @@ pub struct Host {
local_database_tunnels: bool,
/// Finders of non-Git working copies ([`Host::with_vcs_provider`]); Git is built in.
pub(crate) vcs_providers: Vec<Arc<dyn ide_vcs::BackendProvider>>,
/// Subversion is on ([`Host::with_subversion`]); `Some(true)` shows svn's prompts in dialogs.
pub(crate) subversion: Option<bool>,
pub(crate) mcp_executable: Arc<RwLock<Option<PathBuf>>>,
pub mcp: mcp::McpService,
plugin_host: RwLock<std::sync::Weak<plugins::PluginHost>>,
@@ -104,9 +108,12 @@ pub struct Host {
pub mcp_agent_runs: mcp::AgentRuns,
/// Projects the MCP server serves without a window.
pub mcp_background: mcp::BackgroundProjects,
/// Host-owned scheduled agent automations and in-session follow-up timers.
pub automations: Arc<automations::AutomationService>,
pub(crate) agent_catalogs: Arc<ide_agent::AgentCatalogs>,
pub trust: std::sync::Arc<trust::TrustStore>,
pub(crate) mcp_approvals: Arc<trust::McpServerApprovals>,
pub(crate) plugin_approvals: Arc<trust::PluginCapabilityApprovals>,
pub config_dir: PathBuf,
/// Persistent user state, including credentials and recovery history.
pub data_dir: PathBuf,
@@ -218,6 +225,14 @@ impl Host {
self
}
/// Adds Subversion: every project gets its own svn settings ([`svn`]) and finds its
/// working copies. `prompts` routes svn's login and certificate prompts to the project's
/// window (the desktop app, which answers them with `ssh_askpass_answer`).
pub fn with_subversion(mut self, prompts: bool) -> Self {
self.subversion = Some(prompts);
self
}
/// User home directory used by agent memory discovery.
pub fn home_dir(&self) -> Option<PathBuf> {
self.home_dir.clone()
@@ -243,10 +258,13 @@ impl Host {
let migration = ssh.clone();
runtime.spawn_blocking(move || migration.start_password_migration());
ssh.set_configs(global_settings.effective().ssh.configs);
let boot_override = if cfg!(test) { Some(data_dir.join("boot-services-test")) } else { None };
let automations = automations::AutomationService::new(&data_dir, boot_override);
let host = Self {
plugin_host: RwLock::default(),
local_database_tunnels: false,
vcs_providers: Vec::new(),
subversion: None,
mcp_executable: Arc::default(),
mcp: Default::default(),
diagnostics,
@@ -254,9 +272,11 @@ impl Host {
mcp_requests: Default::default(),
mcp_agent_runs: Default::default(),
mcp_background: Default::default(),
automations,
agent_catalogs: Arc::default(),
trust: std::sync::Arc::new(trust::TrustStore::load(&config_dir, &data_dir)),
mcp_approvals: Arc::new(trust::McpServerApprovals::load(&data_dir)),
plugin_approvals: Arc::new(trust::PluginCapabilityApprovals::load(&data_dir)),
proxy_password: ide_ssh::secrets::SecretFile::new(data_dir.join("proxy-password.json")),
jupyter_tokens: ide_ssh::secrets::SecretFile::new(data_dir.join("jupyter-tokens.json")),
proxy_session_password: Mutex::default(),
@@ -492,13 +512,20 @@ impl Host {
let processes = self.processes.detach_project_kills(&project.root);
let terminals = self.terminals.detach_key(self.owner_window(window));
let root = (!project.light).then(|| project.root.clone());
let shutdown_agents = if !project.light
&& self.automations.retain_on_window_close(self, &project.root, &project.agents, agent_reason)
{
Vec::new()
} else {
vec![project.agents.clone()]
};
let handle = self.spawn_project_shutdown(ShutdownWork {
notebooks: vec![project.notebooks.clone()],
bridges: project.kotlin_bridge.iter().cloned().collect(),
lsp: Some(project.lsp.clone()),
// Debug sessions under the root belong to windows: a project served without one starts none.
debug: Some((self.debugger.clone(), window.to_owned(), (!background).then(|| project.root.clone()))),
agents: vec![project.agents.clone()],
agents: shutdown_agents,
agent_reason,
terminals: Some(terminals),
processes: Some(processes),
@@ -627,6 +654,7 @@ impl Host {
}
pub fn shutdown_notebooks_on_exit_with(&self, agent_reason: ide_agent::AgentShutdownReason) {
self.automations.stop();
let projects = self.projects();
let mut pending: Vec<_> = self.closing.lock().drain(..).map(|entry| entry.handle).collect();
if !projects.is_empty() {
+1 -1
Переглянути файл
@@ -444,7 +444,7 @@ impl BackgroundProjects {
impl Host {
/// The window, and its project, that has `root` open as a project (not in LightEdit).
fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
pub(crate) fn window_project(&self, root: &Path) -> Option<(String, Arc<Project>)> {
let projects = self.projects.read();
let windows = projects.iter().filter(|(w, p)| !BackgroundProjects::is_key(w) && !p.light && p.root == root);
windows.min_by_key(|(w, _)| w.as_str()).map(|(w, p)| (w.clone(), p.clone()))
+40 -3
Переглянути файл
@@ -242,7 +242,11 @@ marked directory are not marked again.",
},
)
.param(Param::required("directoryPath", ParamType::String, RELATIVE_PATH_IN_PROJECT_DESCRIPTION))
.param(Param::optional("maxDepth", ParamType::Integer, "Maximum recursion depth"))
.param(Param::optional(
"maxDepth",
ParamType::Integer,
"Levels to list below the directory: 1 lists its entries, 2 their entries too, and so on (default 5)",
))
.param(Param::optional("limit", ParamType::Integer, "Entries to return at most (default 100)"))
.param(Param::optional("offset", ParamType::Integer, OFFSET))
.param(Param::optional("timeout", ParamType::Integer, TIMEOUT_MILLISECONDS_DESCRIPTION))
@@ -306,6 +310,7 @@ fn marker(git_ignored: bool, ide_excluded: bool) -> &'static str {
}
impl TreeRender {
/// `max_depth`: the levels to list below the entry (0 lists the entry alone);
/// `mark`: the entry's marker; `marked`: it or a directory above it is marked.
#[allow(clippy::too_many_arguments)]
fn render(
@@ -318,7 +323,7 @@ impl TreeRender {
mark: &str,
marked: bool,
) {
if max_depth <= 0 || self.timed_out || self.cancel.is_cancelled() {
if self.timed_out || self.cancel.is_cancelled() {
return;
}
if Instant::now() >= self.deadline {
@@ -343,7 +348,7 @@ impl TreeRender {
} else {
self.entry(&line)
};
if !is_dir {
if !is_dir || max_depth <= 0 {
return;
}
// Without exclusions, `ignored` is what `.gitignore` says.
@@ -482,6 +487,38 @@ mod tests {
assert_eq!(render(0, 100).0, " ├── a/\n │ ├── x.txt\n │ └── y.txt\n └── b.txt\n");
}
#[test]
fn max_depth_counts_the_levels_below_the_directory() {
let tmp = tempfile::tempdir().unwrap();
for file in ["a/b/c.txt", "d.txt"] {
let path = tmp.path().join(file);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "").unwrap();
}
let render = |max_depth| {
let mut tree = TreeRender {
out: String::new(),
errors: Vec::new(),
timed_out: false,
deadline: Instant::now() + Duration::from_secs(10),
cancel: CancellationToken::new(),
page: Page { offset: 0, limit: 100 },
seen: 0,
above: Vec::new(),
marks: Marks { root: tmp.path().to_path_buf(), excludes: None },
};
tree.render(tmp.path(), "", true, max_depth, true, "", false);
let root = format!("{}/\n", tmp.path().display());
(tree.out.strip_prefix(&root).unwrap().to_owned(), tree.seen)
};
assert_eq!(render(0), (String::new(), 0), "0 lists the directory alone");
assert_eq!(render(1), (" ├── a/\n └── d.txt\n".to_owned(), 2), "1 lists its entries");
assert_eq!(render(2), (" ├── a/\n │ └── b/\n └── d.txt\n".to_owned(), 3));
let full = " ├── a/\n │ └── b/\n │ └── c.txt\n └── d.txt\n".to_owned();
assert_eq!(render(3), (full.clone(), 4));
assert_eq!(render(5), (full, 4), "a depth beyond the tree lists all of it");
}
#[test]
fn what_the_project_leaves_out_is_marked_once() {
let tmp = tempfile::tempdir().unwrap();
+2
Переглянути файл
@@ -668,6 +668,8 @@ mod tests {
selection_range: Range::new(range.start, range.start),
children,
visibility: None,
implements: None,
self_type: None,
};
let method = outline(
"total",
+29 -1
Переглянути файл
@@ -264,7 +264,22 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("file.save", "Save All"),
act("templates.saveFileAsTemplate", "Save File as Template…"),
act("file.reloadAllFromDisk", "Reload All from Disk"),
sub("fileProperties", "File Properties", vec![act("file.toggleReadOnly", "Make File Read-only / Writable")]),
sub(
"fileProperties",
"File Properties",
vec![
sub(
"lineSeparators",
"Line Separators",
vec![
act("file.lineSeparators.crLf", "CRLF - Windows (\\r\\n)"),
act("file.lineSeparators.lf", "LF - Unix and macOS (\\n)"),
act("file.lineSeparators.cr", "CR - Classic Mac OS (\\r)"),
],
),
act("file.toggleReadOnly", "Make File Read-only / Writable"),
],
),
SEP,
act("file.projectStructure", "Project Structure…"),
SEP,
@@ -735,6 +750,18 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("vcs.syncSubmodules", "Sync Submodule URLs"),
],
),
// What only a Subversion working copy has; disabled for a Git repository.
sub(
"subversion",
"Subversion",
vec![
act("svn.cleanup", "Cleanup"),
act("svn.lock", "Lock…"),
act("svn.unlock", "Unlock"),
act("svn.relocate", "Relocate…"),
act("svn.properties", "Properties…"),
],
),
SEP,
act("vcs.showLog", "Show Git Log"),
sub(
@@ -903,6 +930,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("editor.moveToOppositeGroup", "Move to Opposite Group"),
act("editor.openInOppositeGroup", "Open in Opposite Group"),
act("editor.changeSplitOrientation", "Change Splitter Orientation"),
act("editor.maximizeInSplit", "Maximize Editor / Normalize Splits"),
act("editor.unsplitAll", "Unsplit All"),
act("editor.nextSplitter", "Go to Next Splitter"),
act("editor.prevSplitter", "Go to Previous Splitter"),
+774 -69
Переглянути файл
@@ -5,14 +5,17 @@ use crate::Host;
use crate::agent_secrets::{AgentSecrets, Kept};
use ide_agent::registry::{AgentRegistry, RegistryPaths};
use ide_agent::{
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentMemoryCatalog,
AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides, AgentMemorySettings, AgentModelCatalog, AgentProbe,
AcpImportOutcome, AgentAcceptOutcome, AgentAutomation, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent,
AgentMarketplaceBrowseResult, AgentMemoryCatalog, AgentMemoryEntryPolicy, AgentMemoryMode, AgentMemoryOverrides,
AgentMemorySettings, AgentModelCatalog, AgentPluginCatalog, AgentPluginPreview, AgentPluginSettings, AgentProbe,
AgentPrompt, AgentProvider, AgentProviderMemoryPolicy, AgentQueued, AgentRecoveryReport, AgentSkillMode,
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, CopilotAuthStatus, CreateAgentMemoryInput,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput,
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, AutomationRun, AutomationRunsPage,
AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus, CreateAgentMemoryInput,
CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest,
InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope,
McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput, RemoteSkillBrowseResult,
RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -30,18 +33,47 @@ pub fn agent_subscribe(
on_event: Channel<AgentEvent>,
subscriber: String,
) -> IdeResult<Vec<AgentTask>> {
Ok(host.project(window)?.agents.subscribe_as(
&subscriber,
std::sync::Arc::new(move |e| {
let _ = on_event.send(e);
}),
))
let sink: ide_agent::AgentSink = std::sync::Arc::new(move |e| {
let _ = on_event.send(e);
});
let scope = crate::automations::AutomationTaskScope::for_window(host, window);
let mut by_id: std::collections::HashMap<String, AgentTask> = std::collections::HashMap::new();
match host.project(window) {
Ok(proj) => {
for t in proj.agents.subscribe_as(&subscriber, sink.clone()) {
by_id.insert(t.id.clone(), t);
}
}
Err(e) => {
// Without an open project, `scope.allowed_roots` is empty (no wildcard!) so ONLY
// `ChatOnly` tasks may be subscribed if any exist.
let extras = host.automations.subscribe_window_extras(host, &scope, &subscriber, sink);
if extras.is_empty() {
return Err(e);
}
for t in extras {
by_id.insert(t.id.clone(), t);
}
let mut list: Vec<AgentTask> = by_id.into_values().collect();
list.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
return Ok(list);
}
}
for extra in host.automations.subscribe_window_extras(host, &scope, &subscriber, sink) {
by_id.insert(extra.id.clone(), extra);
}
let mut list: Vec<AgentTask> = by_id.into_values().collect();
list.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
Ok(list)
}
/// Stops the events of a window that closed.
#[command(trust = always)]
pub fn agent_unsubscribe(host: &Host, window: &str, subscriber: String) -> IdeResult<()> {
host.project(window)?.agents.unsubscribe(&subscriber);
host.automations.unsubscribe_window_extras(&subscriber);
if let Ok(proj) = host.project(window) {
proj.agents.unsubscribe(&subscriber);
}
Ok(())
}
@@ -422,8 +454,7 @@ pub async fn agent_entries(
task: String,
subagent: Option<String>,
) -> IdeResult<Vec<AgentEntry>> {
let agents = host.project(window)?.agents.clone();
host.blocking(move || agents.entries(&task, subagent)).await
host.automations.route_entries(host, window, task, subagent).await
}
/// Sessions of the project on this machine that no task holds yet, newest first.
@@ -478,8 +509,8 @@ pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> I
/// Sends a message; while the agent works it is queued, or with `now` it interrupts the turn.
#[command(trust = trusted)]
pub async fn agent_prompt(host: &Host, window: &str, task: String, prompt: AgentPrompt, now: bool) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.prompt(&task, prompt, now).await
host.require_trust_if_project(window)?;
host.automations.route_prompt(host, window, task, prompt, now).await
}
/// Runs a `!` line of the composer in the task's folder with the user's shell, without
@@ -509,8 +540,8 @@ pub async fn agent_answer_question(
question: String,
answer: Option<String>,
) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.answer_question(&task, &question, answer).await
host.require_trust_if_project(window)?;
host.automations.route_answer_question(host, window, task, question, answer).await
}
/// Drops a queued message and returns it (to edit it).
@@ -615,7 +646,7 @@ pub async fn agent_context_usage(host: &Host, window: &str, task: String) -> Ide
/// Stops the task's current turn, or with `subagent` only that subagent's work.
#[command(trust = always)]
pub fn agent_cancel(host: &Host, window: &str, task: String, subagent: Option<String>) -> IdeResult<()> {
host.project(window)?.agents.cancel(&task, subagent)
host.automations.route_cancel(host, window, task, subagent)
}
/// Resumes an interrupted task with a continuation turn (or immediately wakes a task waiting
@@ -645,7 +676,10 @@ pub async fn agent_dismiss_interrupted(host: &Host, window: &str, task: String)
/// Marks a task as read (`unread = false`) when viewed by the user.
#[command(trust = always)]
pub async fn agent_mark_read(host: &Host, window: &str, task: String) -> IdeResult<()> {
let agents = host.project(window)?.agents.clone();
let agents = match host.automations.authorized_local_manager(host, window, &task, false)? {
Some(mgr) => mgr,
None => host.project(window)?.agents.clone(),
};
host.blocking(move || agents.mark_read(&task)).await
}
@@ -689,7 +723,7 @@ pub async fn agent_reconcile_interrupted(host: &Host, window: &str) -> IdeResult
/// Stops one of the task's background tasks.
#[command(trust = always)]
pub async fn agent_stop_background(host: &Host, window: &str, task: String, background: String) -> IdeResult<()> {
host.project(window)?.agents.stop_background(&task, &background).await
host.automations.route_stop_background(host, window, task, background).await
}
/// Answers a permission request; `option: null` cancels it.
@@ -701,29 +735,48 @@ pub fn agent_respond(
permission: u32,
option: Option<String>,
) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.respond(&task, permission, option)
host.require_trust_if_project(window)?;
host.automations.route_respond(host, window, task, permission, option)
}
#[command(trust = always)]
pub fn agent_archive(host: &Host, window: &str, task: String) -> IdeResult<()> {
host.project(window)?.agents.archive(&task)
match host.automations.authorized_local_manager(host, window, &task, false)? {
Some(mgr) => mgr.archive(&task),
None => host.project(window)?.agents.archive(&task),
}
}
#[command(trust = always)]
pub fn agent_unarchive(host: &Host, window: &str, task: String) -> IdeResult<()> {
host.project(window)?.agents.unarchive(&task)
match host.automations.authorized_local_manager(host, window, &task, false)? {
Some(mgr) => mgr.unarchive(&task),
None => host.project(window)?.agents.unarchive(&task),
}
}
#[command(trust = trusted)]
pub fn agent_rename(host: &Host, window: &str, task: String, title: String) -> IdeResult<()> {
host.project(window)?.agents.rename(&task, &title)
host.require_trust_if_project(window)?;
match host.automations.authorized_local_manager(host, window, &task, true)? {
Some(mgr) => mgr.rename(&task, &title),
None => {
host.require_trust(window)?;
host.project(window)?.agents.rename(&task, &title)
}
}
}
#[command(trust = trusted)]
pub async fn agent_delete(host: &Host, window: &str, task: String, remove_worktree: bool) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.delete(&task, remove_worktree).await
host.require_trust_if_project(window)?;
match host.automations.authorized_local_manager(host, window, &task, true)? {
Some(mgr) => mgr.delete(&task, remove_worktree).await,
None => {
host.require_trust(window)?;
host.project(window)?.agents.delete(&task, remove_worktree).await
}
}
}
/// The task's changed files as `view` compares them (without: since it started).
@@ -956,7 +1009,20 @@ fn listed(
}
}
}
out
let plug_policy = host_plugins_policy(host, project.map(|p| p.as_ref()));
let home = host.home_dir();
let plug_states = ide_agent::plugins::resolve_plugins(
ide_agent::plugins::discover_plugins(&plug_policy.workspace_roots, home.as_deref()),
&plug_policy,
Some(&*host.agent_secrets),
);
let projected = ide_agent::plugins::projected_mcp_servers(
&plug_states,
&plug_policy,
home.as_deref(),
Some(&*host.agent_secrets),
);
ide_agent::mcp::merge_projected_servers(out, projected)
}
/// The MCP servers agent sessions of the project at `root` get: the user's, values filled in, and
@@ -1315,27 +1381,43 @@ pub fn agent_set_memory_overrides(
host.project(window)?.agents.set_memory_overrides(&task, overrides)
}
fn resolve_skills_with_host_plugins(
policy: &SkillsPolicy,
plug_policy: &ide_agent::plugins::PluginsPolicy,
home: Option<&std::path::Path>,
secrets: Option<&dyn ide_agent::EnvSecrets>,
) -> Vec<AgentSkillState> {
let plug_states = ide_agent::plugins::resolve_plugins(
ide_agent::plugins::discover_plugins(&policy.workspace_roots, home),
plug_policy,
secrets,
);
let projected = ide_agent::plugins::projected_skill_roots(&plug_states, None);
ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_agent_plugins(
&policy.workspace_roots,
home,
&policy.plugin_dirs,
&projected,
),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
)
}
/// Every skill discovered in the project, the user's folders and enabled plugins, with
/// the mode a session runs it with (without any session's own overrides).
#[command(trust = always)]
pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<AgentSkillState>> {
let project = host.project(window).ok().filter(|p| !p.light);
let policy = host_skills_policy(host, project.as_deref());
let home = dirs::home_dir();
blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
home.as_deref(),
&policy.plugin_dirs,
),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
let plug_policy = host_plugins_policy(host, project.as_deref());
let home = host.home_dir();
let secrets = host.agent_secrets.clone();
blocking(move || Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*secrets))))
.await
}
/// Sets how `name` may run in `scope`, in the settings file of that scope, and returns the
@@ -1380,14 +1462,9 @@ pub fn agent_skills_set_mode(
}
}
let policy = host_skills_policy(host, project.as_deref());
let home = dirs::home_dir();
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(&policy.workspace_roots, home.as_deref(), &policy.plugin_dirs),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
let plug_policy = host_plugins_policy(host, project.as_deref());
let home = host.home_dir();
Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*host.agent_secrets)))
}
/// Resolves a GitHub `owner/repo[/path][@ref]` source and lists the `SKILL.md` skills in it.
@@ -1478,20 +1555,10 @@ pub async fn agent_skills_install(
}
let policy = host_skills_policy(host, project.as_deref());
blocking(move || {
Ok(ide_agent::skills::resolve(
ide_agent::skills::discover_skills_with_plugins(
&policy.workspace_roots,
home.as_deref(),
&policy.plugin_dirs,
),
None,
&policy.workspace,
&policy.user,
policy.workspace_trusted,
))
})
.await
let plug_policy = host_plugins_policy(host, project.as_deref());
let secrets = host.agent_secrets.clone();
blocking(move || Ok(resolve_skills_with_host_plugins(&policy, &plug_policy, home.as_deref(), Some(&*secrets))))
.await
}
/// The user's and the workspace's skill policies (`[agents.skills.<name>]`).
@@ -1650,9 +1717,18 @@ fn persist_memory_settings(
async fn current_memory_catalog(host: &Host, project: Option<&crate::Project>) -> IdeResult<AgentMemoryCatalog> {
let policy = host_memory_policy(host, project);
let plug_policy = host_plugins_policy(host, project);
let home = host.home_dir();
let secrets = host.agent_secrets.clone();
blocking(move || {
let entries = ide_agent::memory::discover_memories(&policy.workspace_roots, home.as_deref());
let plug_states = ide_agent::plugins::resolve_plugins(
ide_agent::plugins::discover_plugins(&policy.workspace_roots, home.as_deref()),
&plug_policy,
Some(&*secrets),
);
let projected = ide_agent::plugins::projected_memory_entries(&plug_states);
let entries =
ide_agent::memory::discover_memories_with_plugins(&policy.workspace_roots, home.as_deref(), projected);
Ok(ide_agent::memory::resolve_catalog(entries, None, &policy, home.as_deref()))
})
.await
@@ -1852,6 +1928,307 @@ pub async fn agent_memory_reset_provider(host: &Host, window: &str, provider: St
current_memory_catalog(host, project.as_deref()).await
}
fn host_plugins_policy(host: &Host, project: Option<&crate::Project>) -> ide_agent::plugins::PluginsPolicy {
match project {
Some(project) => ide_agent::plugins::PluginsPolicy {
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.plugins.clone(),
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.plugins.clone(),
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
workspace_roots: workspace_skill_roots(&project.root),
approved_capabilities: host.plugin_approvals.snapshot(),
},
None => ide_agent::plugins::PluginsPolicy {
user: host.global_settings.effective().agents.plugins.clone(),
workspace: Default::default(),
workspace_trusted: true,
workspace_roots: Vec::new(),
approved_capabilities: host.plugin_approvals.snapshot(),
},
}
}
fn plugins_settings_layers(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
) -> (AgentPluginSettings, Option<AgentPluginSettings>) {
let user = host.global_settings.effective().agents.plugins.clone();
let workspace =
project.map(|p| p.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.plugins.clone());
(user, workspace)
}
fn is_default_plugin_settings(s: &AgentPluginSettings) -> bool {
s.marketplaces.is_empty() && s.entries.is_empty()
}
fn persist_plugin_settings(
host: &Host,
project: Option<&std::sync::Arc<crate::Project>>,
scope: McpScope,
settings: &AgentPluginSettings,
) -> IdeResult<()> {
let value = if is_default_plugin_settings(settings) {
serde_json::Value::Null
} else {
serde_json::to_value(settings).map_err(|e| IdeError::invalid(e.to_string()))?
};
match scope {
McpScope::User => {
host.global_settings.set(ide_workspace::settings::SettingsScope::Global, "agents.plugins", value)?;
for p in host.projects() {
p.settings.reload();
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
}
McpScope::Workspace => {
let p = project.ok_or_else(|| IdeError::invalid("Open a project to configure workspace agent plugins"))?;
p.settings.set(ide_workspace::settings::SettingsScope::Project, "agents.plugins", value)?;
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
}
Ok(())
}
fn emit_plugin_projection_events(sink: &SharedSink) {
for key in ["agents.plugins", "agents.skills", "agents.mcpServers", "agents.memory"] {
sink.emit(IdeEvent::SettingsChanged { key: key.into() });
}
}
async fn current_plugins_catalog(host: &Host, project: Option<&crate::Project>) -> IdeResult<AgentPluginCatalog> {
let policy = host_plugins_policy(host, project);
let home = host.home_dir();
let secrets = host.agent_secrets.clone();
blocking(move || {
let discovered = ide_agent::plugins::discover_plugins(&policy.workspace_roots, home.as_deref());
Ok(ide_agent::plugins::resolve_catalog(discovered, &policy, home.as_deref(), Some(&*secrets)))
})
.await
}
/// Lists all discovered agent plugin bundles, registered/discovered marketplaces, and projection counts.
#[command(trust = always)]
pub async fn agent_plugins_list(host: &Host, window: &str) -> IdeResult<AgentPluginCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
current_plugins_catalog(host, project.as_deref()).await
}
/// Enables or disables an installed plugin in that harness's native configuration.
#[command(trust = always)]
pub async fn agent_plugins_set_enabled(
host: &Host,
window: &str,
id: String,
scope: McpScope,
enabled: bool,
approve_capabilities: bool,
capability_hash: Option<String>,
) -> IdeResult<AgentPluginCatalog> {
let id = id.trim().to_owned();
if id.is_empty() {
return Err(IdeError::invalid("Plugin ID is required"));
}
let project = host.project(window).ok().filter(|p| !p.light);
let project_root = project.as_ref().map(|p| p.root.clone());
let policy = host_plugins_policy(host, project.as_deref());
let home = host.home_dir();
let lookup_id = id.clone();
let home_for_discovery = home.clone();
let found_plugin = blocking(move || {
let discovered = ide_agent::plugins::discover_plugins(&policy.workspace_roots, home_for_discovery.as_deref());
// Ids are owner-qualified and stable, so only an exact match may be toggled.
Ok(discovered.into_iter().find(|p| p.scope == scope && p.id == lookup_id))
})
.await?;
let plugin = found_plugin.ok_or_else(|| IdeError::not_found(format!("Plugin `{id}` not found")))?;
if plugin.scope == McpScope::Workspace {
host.require_trust(window)?;
}
let approval_key = ide_agent::plugins::capability_approval_key(&plugin);
let already_approved = approval_key.as_ref().is_some_and(|key| host.plugin_approvals.snapshot().contains(key));
if enabled && plugin.capabilities.requires_consent && !approve_capabilities && !already_approved {
return Err(IdeError::invalid("Approve the plugin's executable capabilities before enabling it"));
}
if approve_capabilities && let Some(key) = approval_key {
// Approve only the capabilities the user was shown; re-inspection may have found others.
if capability_hash.as_deref() != plugin.capabilities.capability_hash.as_deref() {
return Err(IdeError::invalid(
"The plugin's executable capabilities changed since they were shown; review them again",
));
}
host.plugin_approvals.approve(key)?;
}
let plugin_for_write = plugin.clone();
let home_for_write = home.clone();
blocking(move || {
ide_agent::plugins::set_plugin_enabled(
&plugin_for_write,
enabled,
home_for_write.as_deref(),
project_root.as_deref(),
)
})
.await?;
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
current_plugins_catalog(host, project.as_deref()).await
}
/// Registers a marketplace source (`owner/repo[#ref]`, GitHub URL, or local path) in `scope`.
#[command(trust = always)]
pub async fn agent_plugins_add_marketplace(
host: &Host,
window: &str,
scope: McpScope,
source: String,
) -> IdeResult<AgentPluginCatalog> {
let clean = source.trim().to_owned();
if clean.is_empty() {
return Err(IdeError::invalid("Enter a marketplace repository or local path"));
}
if scope == McpScope::Workspace {
host.require_trust(window)?;
}
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = plugins_settings_layers(host, project.as_ref());
let target = match scope {
McpScope::User => &mut user,
McpScope::Workspace => {
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace marketplaces"))?
}
};
if !target.marketplaces.iter().any(|m| m == &clean) {
target.marketplaces.push(clean);
let to_save = target.clone();
persist_plugin_settings(host, project.as_ref(), scope, &to_save)?;
}
current_plugins_catalog(host, project.as_deref()).await
}
/// Removes a registered marketplace source from `scope`.
#[command(trust = always)]
pub async fn agent_plugins_remove_marketplace(
host: &Host,
window: &str,
scope: McpScope,
source: String,
) -> IdeResult<AgentPluginCatalog> {
let clean = source.trim();
if scope == McpScope::Workspace {
host.require_trust(window)?;
}
let project = host.project(window).ok().filter(|p| !p.light);
let (mut user, mut workspace) = plugins_settings_layers(host, project.as_ref());
let target = match scope {
McpScope::User => &mut user,
McpScope::Workspace => {
workspace.as_mut().ok_or_else(|| IdeError::invalid("Open a project to configure workspace marketplaces"))?
}
};
let before = target.marketplaces.len();
target.marketplaces.retain(|m| m != clean);
if target.marketplaces.len() != before {
let to_save = target.clone();
persist_plugin_settings(host, project.as_ref(), scope, &to_save)?;
}
current_plugins_catalog(host, project.as_deref()).await
}
/// Browses installable plugins inside a marketplace (`owner/repo[#ref]`, GitHub URL, or local directory/manifest).
#[command(trust = always)]
pub async fn agent_plugins_browse_marketplace(
host: &Host,
window: &str,
source: String,
request: RequestId,
) -> IdeResult<AgentMarketplaceBrowseResult> {
let cancel = host.begin_request(request);
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = host.home_dir();
let search_path = ide_core::tool_path::search_path();
let res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::plugins::browse_marketplace(&fetcher, &source, home.as_deref(), ws_root.as_deref(), &cancel)
})
.await;
host.end_request(request);
res
}
/// Previews an agent plugin bundle from GitHub or a local folder before installation, scanning files and capabilities.
#[command(trust = always)]
pub async fn agent_plugins_preview(
host: &Host,
window: &str,
source: String,
subpath: Option<String>,
marketplace: Option<String>,
request: RequestId,
) -> IdeResult<AgentPluginPreview> {
let cancel = host.begin_request(request);
let ws_root = host.project(window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let home = host.home_dir();
let search_path = ide_core::tool_path::search_path();
let res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::plugins::preview_plugin(
&fetcher,
&source,
subpath.as_deref(),
marketplace.as_deref(),
home.as_deref(),
ws_root.as_deref(),
&cancel,
)
})
.await;
host.end_request(request);
res
}
/// Atomically installs a previewed agent plugin into the selected harness's native plugin directory.
#[command(trust = always)]
pub async fn agent_plugins_install(
host: &Host,
window: &str,
input: InstallAgentPluginRequest,
request: RequestId,
) -> IdeResult<AgentPluginCatalog> {
let project = host.project(window).ok().filter(|p| !p.light);
if input.scope == McpScope::Workspace || input.source_kind == "local" {
host.require_trust(window)?;
}
let ws_root = project.as_ref().map(|p| p.root.clone());
let home = host.home_dir();
let cancel = host.begin_request(request);
let search_path = ide_core::tool_path::search_path();
let req_clone = input.clone();
let install_res = blocking(move || {
let fetcher = ide_agent::skill_installer::GitHubHttpFetcher::new(&search_path)?;
ide_agent::plugins::install_plugin(&fetcher, &req_clone, home.as_deref(), ws_root.as_deref(), &cancel)
})
.await;
host.end_request(request);
let (_, approval_key) = install_res?;
if input.approve_capabilities
&& let Some(key) = approval_key
{
host.plugin_approvals.approve(key)?;
}
for p in host.projects() {
p.agents.notify_mcp_servers_changed();
emit_plugin_projection_events(&p.sink);
}
current_plugins_catalog(host, project.as_deref()).await
}
fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::Path>) -> IdeResult<std::path::PathBuf> {
let Some(requested) = requested else {
return Ok(root.to_path_buf());
@@ -1869,6 +2246,312 @@ fn validate_project_root(root: &std::path::Path, requested: Option<&std::path::P
Err(IdeError::invalid("Agent project must be the window project or a workspace member"))
}
// ---------------------------------------------------------------------------
// Agent Automations & In-Session Schedules
// ---------------------------------------------------------------------------
fn host_label_for(remote: bool) -> String {
std::env::var("HOSTNAME")
.ok()
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| if remote { "Remote Server".into() } else { "Local Host".into() })
}
fn window_automation_scope(host: &Host, window: &str) -> (Option<Vec<std::path::PathBuf>>, bool) {
if let Some(p) = host.project(window).ok().filter(|p| !p.light) {
let trusted = host.trust.window_trusted(&p.root).unwrap_or(false);
let mut roots = vec![dunce::canonicalize(&p.root).unwrap_or_else(|_| p.root.clone())];
if let Ok(Some(ws)) = ide_workspace::workspace::Workspace::load(&p.root) {
for member in ws.projects {
let canon = dunce::canonicalize(&member).unwrap_or(member);
if !roots.contains(&canon) {
roots.push(canon);
}
}
}
(Some(roots), trusted)
} else {
(Some(Vec::new()), true)
}
}
fn require_window_trust_if_project(host: &Host, window: &str) -> IdeResult<()> {
if let Some(p) = host.project(window).ok().filter(|p| !p.light) {
p.require_trust()?;
}
Ok(())
}
fn ensure_window_owns_automation(host: &Host, window: &str, id: &str) -> IdeResult<AgentAutomation> {
require_window_trust_if_project(host, window)?;
let auto = host.automations.get(id).ok_or_else(|| IdeError::not_found(format!("unknown automation '{id}'")))?;
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
if let Some(roots) = allowed_roots {
match &auto.workspace {
AutomationWorkspace::ChatOnly if include_chat_only => {}
AutomationWorkspace::ChatOnly => {
return Err(IdeError::invalid("Trust the project before accessing automations"));
}
AutomationWorkspace::Project { root, .. } => {
let cand = dunce::canonicalize(&root.0).unwrap_or_else(|_| root.0.clone());
if !roots.contains(&cand) {
return Err(IdeError::invalid("Automation belongs to a different project"));
}
}
}
}
Ok(auto)
}
fn ensure_window_owns_session_schedule(host: &Host, window: &str, id: &str) -> IdeResult<()> {
host.require_trust(window)?;
let (allowed_roots, _) = window_automation_scope(host, window);
if let Some(roots) = allowed_roots {
let schedules = host.automations.list_session_schedules_scoped(Some(&roots), None);
if !schedules.iter().any(|s| s.id == id) {
return Err(IdeError::not_found(format!("unknown session schedule '{id}'")));
}
}
Ok(())
}
/// Returns the current project's automations, first page of run history, active session schedules,
/// and scheduler/boot-service status.
#[command(trust = always)]
pub async fn agent_automation_snapshot(
host: &std::sync::Arc<Host>,
window: &str,
remote: bool,
) -> IdeResult<AutomationSnapshot> {
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
let h = host.clone();
host.blocking(move || {
Ok(h.automations.snapshot_scoped(
&h,
allowed_roots.as_deref(),
include_chat_only,
remote,
host_label_for(remote),
))
})
.await
}
/// Creates or updates an [`AgentAutomation`]. Project-scoped automations require a trusted project.
#[command(trust = trusted)]
pub async fn agent_automation_save(
host: &std::sync::Arc<Host>,
window: &str,
mut input: SaveAutomationInput,
) -> IdeResult<AgentAutomation> {
require_window_trust_if_project(host, window)?;
if let Some(existing_id) = input.id.as_deref() {
let _ = ensure_window_owns_automation(host, window, existing_id)?;
}
if let AutomationWorkspace::Project { root, isolation, base, auto_clean_worktree } = input.workspace {
let project = host.project(window).ok().filter(|p| !p.light);
let validated = match &project {
Some(p) => {
p.require_trust()?;
validate_project_root(&p.root, Some(&root.0))?
}
None => {
if !host.trust.window_trusted(&root.0)? {
return Err(IdeError::invalid("Trust the project before creating an automation in it"));
}
dunce::canonicalize(&root.0)?
}
};
input.workspace =
AutomationWorkspace::Project { root: IpcPath(validated), isolation, base, auto_clean_worktree };
}
let h = host.clone();
host.blocking(move || h.automations.save(&h, input)).await
}
/// Enables or pauses an automation schedule.
#[command(trust = trusted)]
pub async fn agent_automation_set_enabled(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
enabled: bool,
) -> IdeResult<AgentAutomation> {
let _ = ensure_window_owns_automation(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.set_enabled(&h, &id, enabled)).await
}
/// Pauses all enabled schedules (for the current window's project, or across all projects when `all_projects` is true).
#[command(trust = trusted)]
pub async fn agent_automation_pause_all(
host: &std::sync::Arc<Host>,
window: &str,
all_projects: bool,
) -> IdeResult<u32> {
require_window_trust_if_project(host, window)?;
let (allowed_roots, include_chat_only) =
if all_projects { (None, true) } else { window_automation_scope(host, window) };
let h = host.clone();
host.blocking(move || h.automations.pause_all_scoped(&h, allowed_roots.as_deref(), include_chat_only)).await
}
/// Deletes an automation and its run history entries.
#[command(trust = trusted)]
pub async fn agent_automation_delete(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
let _ = ensure_window_owns_automation(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.delete(&h, &id)).await
}
/// Immediately triggers a manual run of automation `id`.
#[command(trust = trusted)]
pub async fn agent_automation_run_now(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
) -> IdeResult<AutomationRun> {
let _ = ensure_window_owns_automation(host, window, &id)?;
host.automations.clone().run_now(host, &id).await
}
/// Lists paginated automation run history.
#[command(trust = always)]
pub async fn agent_automation_runs(
host: &std::sync::Arc<Host>,
window: &str,
automation_id: Option<String>,
cursor: Option<u32>,
limit: Option<u32>,
) -> IdeResult<AutomationRunsPage> {
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
let h = host.clone();
host.blocking(move || {
Ok(h.automations.runs_scoped(
allowed_roots.as_deref(),
include_chat_only,
automation_id.as_deref(),
cursor,
limit,
))
})
.await
}
/// Marks one run, one automation's runs, or all runs in the current window's scope as read.
#[command(trust = trusted)]
pub async fn agent_automation_mark_read(
host: &std::sync::Arc<Host>,
window: &str,
run_id: Option<String>,
automation_id: Option<String>,
) -> IdeResult<()> {
require_window_trust_if_project(host, window)?;
let (allowed_roots, include_chat_only) = window_automation_scope(host, window);
let h = host.clone();
host.blocking(move || {
h.automations.mark_read_scoped(
&h,
allowed_roots.as_deref(),
include_chat_only,
run_id.as_deref(),
automation_id.as_deref(),
)
})
.await
}
/// Previews the next `count` firing timestamps (epoch ms) for a schedule trigger.
#[command(trust = always)]
pub async fn agent_automation_preview_schedule(
host: &std::sync::Arc<Host>,
trigger: AutomationTrigger,
count: Option<u32>,
) -> IdeResult<Vec<f64>> {
let h = host.clone();
host.blocking(move || h.automations.preview_schedule(&trigger, count)).await
}
/// Exports automation `id` into portable `.automation.md` text.
#[command(trust = trusted)]
pub async fn agent_automation_export_markdown(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
) -> IdeResult<String> {
let _ = ensure_window_owns_automation(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.export_markdown(&id)).await
}
/// Imports a `.automation.md` template into the current project (or as ChatOnly) with `enabled = false`.
#[command(trust = trusted)]
pub async fn agent_automation_import_markdown(
host: &std::sync::Arc<Host>,
window: &str,
markdown: String,
chat_only: bool,
provider: String,
) -> IdeResult<AgentAutomation> {
require_window_trust_if_project(host, window)?;
let workspace = if chat_only {
AutomationWorkspace::ChatOnly
} else {
host.require_trust(window)?;
let project = host.project(window)?;
AutomationWorkspace::Project {
root: IpcPath(project.root.clone()),
isolation: Isolation::Worktree,
base: None,
auto_clean_worktree: true,
}
};
let h = host.clone();
host.blocking(move || h.automations.import_markdown(&h, &markdown, workspace, provider)).await
}
/// Attaches a `Send Later` one-shot or `/loop` recurring schedule to an existing task session.
#[command(trust = trusted)]
pub async fn agent_session_schedule_create(
host: &std::sync::Arc<Host>,
window: &str,
input: CreateSessionScheduleInput,
) -> IdeResult<SessionSchedule> {
host.require_trust(window)?;
let project = host.project(window)?;
let root = project.root.clone();
let h = host.clone();
host.blocking(move || h.automations.create_session_schedule(&h, root, input)).await
}
/// Pauses or resumes an in-session `/loop` or `Send Later` schedule.
#[command(trust = trusted)]
pub async fn agent_session_schedule_set_paused(
host: &std::sync::Arc<Host>,
window: &str,
id: String,
paused: bool,
) -> IdeResult<SessionSchedule> {
ensure_window_owns_session_schedule(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.set_session_schedule_paused(&h, &id, paused)).await
}
/// Sends a queued `Send Later` prompt or fires a `/loop` iteration immediately.
#[command(trust = trusted)]
pub async fn agent_session_schedule_run_now(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
ensure_window_owns_session_schedule(host, window, &id)?;
host.automations.clone().run_session_schedule_now(host, &id).await
}
/// Cancels and deletes an in-session `Send Later` or `/loop` schedule.
#[command(trust = trusted)]
pub async fn agent_session_schedule_delete(host: &std::sync::Arc<Host>, window: &str, id: String) -> IdeResult<()> {
ensure_window_owns_session_schedule(host, window, &id)?;
let h = host.clone();
host.blocking(move || h.automations.delete_session_schedule(&h, &id)).await
}
#[cfg(test)]
mod tests {
use super::*;
@@ -2111,6 +2794,17 @@ ide_command::domain!(
agent_context_usage,
agent_changes,
agent_cli_update,
agent_automation_delete,
agent_automation_export_markdown,
agent_automation_import_markdown,
agent_automation_mark_read,
agent_automation_pause_all,
agent_automation_preview_schedule,
agent_automation_run_now,
agent_automation_runs,
agent_automation_save,
agent_automation_set_enabled,
agent_automation_snapshot,
agent_cli_update_check,
agent_commands,
agent_copilot_auth_status,
@@ -2143,6 +2837,13 @@ ide_command::domain!(
agent_memory_reset_provider,
agent_memory_set_auto,
agent_memory_set_mode,
agent_plugins_add_marketplace,
agent_plugins_browse_marketplace,
agent_plugins_install,
agent_plugins_list,
agent_plugins_preview,
agent_plugins_remove_marketplace,
agent_plugins_set_enabled,
agent_poke_network,
agent_preview_copilot_models,
agent_probe,
@@ -2160,6 +2861,10 @@ ide_command::domain!(
agent_rollback,
agent_rollback_changes,
agent_send_queued_now,
agent_session_schedule_create,
agent_session_schedule_delete,
agent_session_schedule_run_now,
agent_session_schedule_set_paused,
agent_set_additional_args,
agent_set_auto_resume_once,
agent_set_command,
+5 -1
Переглянути файл
@@ -1314,7 +1314,11 @@ mod build_tool_settings_tests {
let configure = config("configure", &["-S", ".", "-B", "release", "-G", "Ninja"]);
let mut build =
config("target", &["--build", "release", "--target", "hello", "--config", "Release", "-j", "8"]);
build.extras.before_launch.push(ide_run::BeforeLaunchTask { kind: "build".into(), target: "configure".into() });
build.extras.before_launch.push(ide_run::BeforeLaunchTask {
kind: "build".into(),
target: "configure".into(),
..Default::default()
});
let configs = [configure, build];
for kind in [BuildKind::Build, BuildKind::Rebuild] {
let plan = cmake_plan(root.path(), kind, &configs, "target").unwrap();
+1
Переглянути файл
@@ -160,6 +160,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
let syntax = syntax();
ide_language::merge_visibility(&mut items, &syntax);
ide_language::merge_kinds(&mut items, &syntax);
ide_language::merge_impl_traits(&mut items, &syntax);
}
items
}
+139 -7
Переглянути файл
@@ -15,6 +15,52 @@ pub async fn fs_entry_kind(host: &Host, path: PathBuf) -> IdeResult<ide_vfs::Ent
.await
}
/// Rejects relative paths and any `..` parent traversal without touching the filesystem.
fn reject_parent_traversal(path: &Path) -> Option<PathBuf> {
use std::path::Component;
if !path.is_absolute() {
return None;
}
let mut out = PathBuf::new();
for comp in path.components() {
match comp {
Component::Prefix(p) => out.push(p.as_os_str()),
Component::RootDir => out.push(comp.as_os_str()),
Component::CurDir => {}
Component::ParentDir => return None,
Component::Normal(c) => out.push(c),
}
}
Some(out)
}
/// Resolves symlinks for a path inside the window's project roots and returns its canonical path.
/// Rejects relative paths, `..` parent traversal, and paths outside those roots before touching
/// the filesystem, and rejects symlink targets that canonicalize outside those roots.
#[command(trust = always)]
pub async fn fs_canonicalize(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
let project = host.project(window)?;
host.blocking(move || {
let Some(clean) = reject_parent_traversal(&path) else {
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
};
let raw_roots: Vec<PathBuf> = std::iter::once(project.root.clone()).chain(project.content_roots()).collect();
let canonical_roots: Vec<PathBuf> = raw_roots.iter().filter_map(|r| dunce::canonicalize(r).ok()).collect();
let mut allowed_lexical: Vec<PathBuf> = raw_roots.iter().filter_map(|r| reject_parent_traversal(r)).collect();
allowed_lexical.extend(canonical_roots.iter().cloned());
if !inside_any_root(&clean, &allowed_lexical) {
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
}
let real = dunce::canonicalize(&clean)
.map_err(|_| IdeError::not_found(format!("{}: no such file", path.display())))?;
if !inside_any_root(&real, &canonical_roots) {
return Err(IdeError::invalid(format!("{}: outside the project", path.display())));
}
Ok(real.into())
})
.await
}
#[command(trust = always)]
pub async fn fs_compare_directories(
host: &Host,
@@ -243,10 +289,13 @@ pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
/// state). Returns whether the file is read-only now.
/// Off the main thread: opening a file for edit can ask a server (`svn lock`, `p4 edit`) and
/// wait for a login.
#[command(trust = always)]
pub fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) -> IdeResult<bool> {
match host.project(window) {
Ok(p) => {
pub async fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool) -> IdeResult<bool> {
let project = host.project(window).ok();
host.blocking(move || match project {
Some(p) => {
// A checkout backend keeps files read-only until opened for edit (`p4 edit`), so
// its server learns about the change to come. `backend_of` is empty unless trusted.
if writable
@@ -257,8 +306,9 @@ pub fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool)
}
p.documents.set_writable(&path, writable)
}
Err(_) => ide_vfs::set_writable(&path, writable).map(|()| !writable),
}
None => ide_vfs::set_writable(&path, writable).map(|()| !writable),
})
.await
}
/// Moving to the trash can take a while (large trees): kept off the main thread.
@@ -301,7 +351,34 @@ fn delete_recorded(project: Option<&Project>, path: &Path, undoable: bool) -> Id
#[command(trust = always)]
pub async fn fs_undo_delete(host: &Host, window: &str, undo: DeletionUndo) -> IdeResult<Vec<ide_core::IpcPath>> {
let project = host.project(window)?;
host.blocking(move || Ok(project.history.restore_deletion_undo(undo))).await
host.blocking(move || {
let wanted = undo.paths();
let skipped = project.history.restore_deletion_undo(undo);
// The Delete scheduled the files for deletion in a working copy (`files_deleted`): Undo
// takes that back, keeping the restored content. Git records deletions at commit time.
// One call per working copy: its first folder takes the tree below with it anyway.
let mut by_backend: Vec<(std::sync::Arc<dyn ide_vcs::Backend>, Vec<PathBuf>)> = Vec::new();
for path in wanted.iter().filter(|p| !skipped.iter().any(|s| s.0 == **p)) {
let Some(backend) = project.backend_of(path) else { continue };
match by_backend.iter_mut().find(|(b, _)| b.root() == backend.root()) {
Some((_, paths)) => paths.push(path.clone()),
None => by_backend.push((backend, vec![path.clone()])),
}
}
for (backend, paths) in by_backend {
// The files are back either way; still scheduled for deletion, they would go at commit.
if let Err(e) = backend.unstage(&paths) {
tracing::warn!("undo of delete in {}: {e}", backend.root().display());
project.sink.emit(ide_core::IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Warning,
title: "The restored files are still scheduled for deletion".into(),
body: Some(e.message),
});
}
}
Ok(skipped)
})
.await
}
#[command(trust = always)]
@@ -377,7 +454,9 @@ pub(crate) fn inside_any_root(path: &Path, roots: &[PathBuf]) -> bool {
#[cfg(test)]
mod tests {
use super::inside_any_root;
use super::{fs_canonicalize, inside_any_root};
use crate::{Host, HostConfig};
use ide_core::error::ErrorKind;
use std::path::{Path, PathBuf};
#[test]
@@ -390,10 +469,63 @@ mod tests {
assert!(!inside_any_root(Path::new("/home/me/.ssh/id_rsa"), &roots));
assert!(!inside_any_root(Path::new("/work/spec.pdf"), &[]));
}
#[tokio::test]
async fn fs_canonicalize_enforces_window_project_roots() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let root = base.join("project");
let outside = base.join("outside");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let inside = root.join("guide.mdx");
std::fs::write(&inside, "# Guide").unwrap();
let secret = outside.join("secret.ts");
std::fs::write(&secret, "export const secret = 1;").unwrap();
let host = Host::new(HostConfig { local_data_dir: base.join("local"), ..HostConfig::for_test(&base) });
host.open_project("main", &root).unwrap();
// Valid path inside the window's project root succeeds with its canonical path.
let resolved = fs_canonicalize(&host, "main", inside.clone()).await.unwrap();
assert_eq!(resolved.0, dunce::canonicalize(&inside).unwrap());
// Path outside the project (existing or nonexistent) is rejected with InvalidInput before touching disk.
let outside_existing = fs_canonicalize(&host, "main", secret.clone()).await.unwrap_err();
assert_eq!(outside_existing.kind, ErrorKind::InvalidInput);
let outside_missing = fs_canonicalize(&host, "main", outside.join("does-not-exist.ts")).await.unwrap_err();
assert_eq!(outside_missing.kind, ErrorKind::InvalidInput);
// Parent traversal (`..`) is rejected even when lexically inside the project root.
let traversal = fs_canonicalize(&host, "main", root.join("../outside/secret.ts")).await.unwrap_err();
assert_eq!(traversal.kind, ErrorKind::InvalidInput);
let in_root_parent = fs_canonicalize(&host, "main", root.join("sub/../guide.mdx")).await.unwrap_err();
assert_eq!(in_root_parent.kind, ErrorKind::InvalidInput);
// Symlink inside the project pointing outside (directly or via `..`) is rejected.
#[cfg(unix)]
{
let link = root.join("link.ts");
std::os::unix::fs::symlink(&secret, &link).unwrap();
let escaped = fs_canonicalize(&host, "main", link).await.unwrap_err();
assert_eq!(escaped.kind, ErrorKind::InvalidInput);
let dir_link = root.join("dir-link");
std::os::unix::fs::symlink(&outside, &dir_link).unwrap();
let symlink_parent =
fs_canonicalize(&host, "main", dir_link.join("../outside/secret.ts")).await.unwrap_err();
assert_eq!(symlink_parent.kind, ErrorKind::InvalidInput);
}
// Unknown window with no open project is rejected.
assert!(fs_canonicalize(&host, "other", inside).await.is_err());
}
}
ide_command::domain!(
fs:
fs_canonicalize,
fs_compare_directories,
fs_copy,
fs_copy_merge,
+1 -1
Переглянути файл
@@ -1292,7 +1292,7 @@ mod tests {
fn java_server_launch_classpath_includes_local_maven_system_jars() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let jar = root.join("src/main/resources/lib/offline.jar");
let jar = ["src", "main", "resources", "lib", "offline.jar"].iter().fold(root.clone(), |p, c| p.join(c));
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
std::fs::write(
+37 -7
Переглянути файл
@@ -722,16 +722,15 @@ pub async fn lsp_move_to_file_targets(
Ok(result?.into_iter().map(ide_core::IpcPath::from).collect())
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_implementations(
/// One `kind` of go-to request at each of `positions` (grouped by the document that answers
/// them), one list per position. Cancel with `cancel_request(request)`.
async fn goto_each(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
positions: Vec<Pos>,
kind: GotoKind,
positions: &[Pos],
) -> IdeResult<Vec<Vec<Location>>> {
let lsp = host.project(window)?.lsp.clone();
let (_, cancel) =
@@ -747,7 +746,7 @@ pub async fn lsp_implementations(
let (lsp, cancel) = (lsp.clone(), cancel.clone());
async move {
let positions: Vec<_> = entries.iter().map(|(_, p)| *p).collect();
(entries, lsp.implementations(target, &positions, cancel).await)
(entries, lsp.goto_each(kind, target, &positions, cancel).await)
}
}))
.await;
@@ -775,6 +774,21 @@ pub async fn lsp_implementations(
Err(error.expect("at least one request"))
};
host.end_request(request);
result
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_implementations(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
positions: Vec<Pos>,
) -> IdeResult<Vec<Vec<Location>>> {
let result = goto_each(host, window, request, doc, GotoKind::Implementation, &positions).await;
if let Some((plugins, d)) = plugin_providers(host, window, doc, ProviderKind::Implementation) {
let count = positions.len();
let found = plugin_call(move || {
@@ -792,6 +806,21 @@ pub async fn lsp_implementations(
result
}
/// Go-to `kind` (declaration, definition) of the symbols at `positions`, one list per position:
/// the editor's "implements" gutter markers for languages without a type hierarchy (Rust).
/// Cancel with `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_gotos(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
kind: GotoKind,
positions: Vec<Pos>,
) -> IdeResult<Vec<Vec<Location>>> {
goto_each(host, window, request, doc, kind, &positions).await
}
/// Refines the implementations `targets` of the method at `pos` to their declarations (Java
/// dependencies' class files point at the start of the class). Cancel with
/// `cancel_request(request)`.
@@ -3402,6 +3431,7 @@ ide_command::domain!(
lsp_source_action_text,
lsp_goto,
lsp_goto_implementation,
lsp_gotos,
lsp_hierarchy_members,
lsp_hierarchy_refactor,
lsp_hover,
+2
Переглянути файл
@@ -45,6 +45,7 @@ pub mod settings_sync;
pub mod spell;
pub mod ssh;
pub mod stream_trace;
pub mod svn;
pub mod syntax;
pub mod term;
pub mod thread_dump;
@@ -133,6 +134,7 @@ ide_command::domains!(
search_commands: crate::ops::search::commands,
spell: crate::ops::spell,
ssh: crate::ops::ssh,
svn: crate::ops::svn,
stream_trace: crate::ops::stream_trace,
syntax: crate::ops::syntax,
term: crate::ops::term,
+10 -1
Переглянути файл
@@ -116,6 +116,13 @@ pub fn apply_setting(host: &Arc<Host>, window: &str, key: &str) {
if key == "mcpServer" || key.starts_with("mcpServer.") {
host.mcp.apply(host);
}
if key == "agents" || key == "agents.automations" || key.starts_with("agents.automations.") {
let h = host.clone();
host.runtime.spawn_blocking(move || {
h.automations.sync_boot_service(&h);
h.automations.broadcast_changed(&h);
});
}
if key == "terminal" || key.starts_with("terminal.") {
super::term::apply_output_rate(host, window);
}
@@ -489,12 +496,14 @@ pub fn set_settings(
project.agents.notify_mcp_servers_changed();
}
}
// A skill or memory policy change re-resolves the modes; an idle session restarts to pick them up.
// A skill, memory, or agent-plugin policy change re-resolves the modes; an idle session restarts to pick them up.
if key == "agents"
|| key == "agents.skills"
|| key.starts_with("agents.skills.")
|| key == "agents.memory"
|| key.starts_with("agents.memory.")
|| key == "agents.plugins"
|| key.starts_with("agents.plugins.")
{
for project in affected() {
project.agents.notify_mcp_servers_changed();
+54 -1
Переглянути файл
@@ -553,9 +553,13 @@ async fn start_inner(
.flatten();
if config.kind == "xcode" {
let dir = run_dir.clone();
let say = on_output.clone();
config = host
.blocking(move || {
ide_run::xcode::prepare(&dir, &mut config)?;
// Reading build settings can take a minute on a large workspace: say what's going on.
ide_run::xcode::prepare(&dir, &mut config, &|text| {
say(OutputChunk::System { text: format!("{text}\n") })
})?;
Ok(config)
})
.await?;
@@ -623,6 +627,8 @@ async fn start_inner(
}
let on_output = match xcode_container {
Some(container) => {
let on_output =
if config.kind == "xcode" { split_build_log(&project, &config, on_output) } else { on_output };
let (output, problems) = xcodebuild_problems(&project, &config.id, &run_dir, container, on_output, sink);
sink = problems;
output
@@ -642,6 +648,53 @@ fn xcode_container(config: &RunConfig) -> Option<String> {
const XCODEBUILD_SOURCE: &str = "xcodebuild";
/// Sends an Xcode run's build output to a log file instead of the console, which keeps the app's
/// own output ([`ide_run::xcode::RunOutputSplit`]). Each run of the configuration replaces the
/// file. It is in the temporary folder: the console links a path only without spaces, and the
/// project's cache is under `Application Support`. Problems still sees all of the output: this
/// wraps the console, after [`xcodebuild_problems`] has read it.
fn split_build_log(
project: &crate::project::Project,
config: &RunConfig,
on_output: Emit<OutputChunk>,
) -> Emit<OutputChunk> {
use std::io::Write;
let name: String =
config.id.chars().map(|c| if c.is_ascii_alphanumeric() || "._-".contains(c) { c } else { '_' }).collect();
let project_key = project.cache_dir.file_name().unwrap_or_default();
let path = std::env::temp_dir().join("openidea-xcode-build").join(project_key).join(format!("{name}.log"));
let file = std::fs::create_dir_all(path.parent().unwrap_or(&path))
.and_then(|()| std::fs::File::create(&path))
.map(std::io::BufWriter::new);
let file = match file {
Ok(file) => Some(file),
Err(e) => {
on_output(OutputChunk::System { text: format!("Cannot write the build log {}: {e}\n", path.display()) });
None
}
};
let wait = config.extras.params.get(ide_run::xcode::WAIT_FOR_DEBUGGER_PARAM).is_some_and(|v| !v.trim().is_empty());
let split = ide_run::xcode::RunOutputSplit::new(&path, wait);
let state = parking_lot::Mutex::new((split, file));
Arc::new(move |chunk: OutputChunk| {
let mut guard = state.lock();
let (split, file) = &mut *guard;
let out = split.feed(chunk);
if let Some(f) = file.as_mut()
&& !out.log.is_empty()
{
let _ = f.write_all(out.log.as_bytes());
if !split.building() {
let _ = f.flush();
}
}
drop(guard);
for chunk in out.console {
on_output(chunk);
}
})
}
/// Sends the compiler messages in an Xcode configuration's `xcodebuild` output to Problems as they
/// arrive, after clearing the ones its previous run reported. Messages without a location (linker
/// errors) are listed on the project file (`project.pbxproj` / `contents.xcworkspacedata`).
+12 -9
Переглянути файл
@@ -204,15 +204,15 @@ pub fn sdk_php_effective(host: &Host, window: &str) -> IdeResult<Option<ide_core
}
/// The version of the PHP interpreter `php` and of the Xdebug it loads, run in `cwd` (default: the
/// project root).
#[command(trust = trusted)]
/// project root). Also from Settings on the Welcome screen.
#[command(trust = outside_restricted)]
pub async fn sdk_php_xdebug(
host: &Host,
window: &str,
php: PathBuf,
cwd: Option<PathBuf>,
) -> IdeResult<ide_sdk::php::PhpXdebug> {
host.require_trust(window)?;
host.require_trust_if_project(window)?;
let cwd = cwd.or_else(|| host.project(window).ok().map(|p| p.root.clone()));
blocking(move || ide_sdk::php::xdebug(&php, cwd.as_deref())).await
}
@@ -349,14 +349,15 @@ pub async fn sdk_project_libraries(
}
/// Looks up `names` (bare command names): `node_modules/.bin` above `near`, then the search path.
#[command(trust = trusted)]
/// Also from Settings on the Welcome screen (the PHP interpreter).
#[command(trust = outside_restricted)]
pub async fn sdk_locate_tools(
host: &Host,
window: &str,
names: Vec<String>,
near: Option<PathBuf>,
) -> IdeResult<LocatedTools> {
host.require_trust(window)?;
host.require_trust_if_project(window)?;
blocking_value(move || LocatedTools {
tools: ide_sdk::locate::locate_tools(&names, near.as_deref()),
compile_dir: ide_sdk::locate::compile_dir().into(),
@@ -475,16 +476,18 @@ pub async fn sdk_python_pip(
result
}
/// The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home.
#[command(trust = trusted)]
/// The JDK whose home is `path`, as the SDK list shows it; `None` when it is no JDK home. SDKs
/// are IDE-wide, so Add JDK from Disk works from the Welcome screen as well (#7361).
#[command(trust = outside_restricted)]
pub async fn sdk_jdk_at(path: String) -> IdeResult<Option<Sdk>> {
// A macOS bundle too (Add JDK from Disk…).
blocking_value(move || ide_sdk::java::jdk_at(std::path::Path::new(&path)).map(|j| ide_sdk::jdk_sdk(&j))).await
}
/// `flutter --version --machine` of the Flutter SDK at `path`, or of the `flutter` on the
/// search path when `path` is empty; `None` when there is no Flutter SDK.
#[command(trust = trusted)]
/// search path when `path` is empty; `None` when there is no Flutter SDK. Also from Settings on
/// the Welcome screen, as the SDK list.
#[command(trust = outside_restricted)]
pub async fn sdk_flutter_at(
host: &Host,
window: &str,
+12 -7
Переглянути файл
@@ -9,7 +9,11 @@ use std::path::{Path, PathBuf};
struct DocumentsHost<'a>(&'a Documents);
impl ReplaceHost for DocumentsHost<'_> {
fn edit_file(&self, path: &Path, compute: &mut dyn FnMut(&str) -> IdeResult<Vec<TextEdit>>) -> IdeResult<u32> {
fn edit_file(
&self,
path: &Path,
compute: &mut dyn FnMut(&str) -> IdeResult<Vec<TextEdit>>,
) -> IdeResult<(u32, bool)> {
let docs = self.0;
let (doc, transient) = match docs.by_path(path) {
Some(doc) => (doc, false),
@@ -24,7 +28,7 @@ impl ReplaceHost for DocumentsHost<'_> {
let snap = docs.text_snapshot(doc)?;
let edits = compute(&snap.text)?;
if edits.is_empty() {
return Ok(0);
return Ok((0, false));
}
if docs.text_snapshot(doc)?.version != snap.version {
continue;
@@ -33,12 +37,13 @@ impl ReplaceHost for DocumentsHost<'_> {
// An open tab's file may have changed on disk before the watcher reported it:
// autosave keeps that change and leaves the replacement unsaved. A file opened
// just for this was read now.
if transient {
let disk_conflict = if transient {
docs.save(doc)?;
} else if save {
docs.autosave(doc)?;
}
return Ok(edits.len() as u32);
false
} else {
save && !docs.autosave(doc)?
};
return Ok((edits.len() as u32, disk_conflict));
}
Err(ide_core::IdeError::unavailable("the file kept changing during Replace"))
})();
+265
Переглянути файл
@@ -0,0 +1,265 @@
//! What only Subversion has (VCS › Subversion): Cleanup, Lock / Unlock,
//! Relocate, Properties, and Checkout from URL. Everything else a Subversion
//! working copy does goes through the shared `vcs_*` commands and
//! [`ide_vcs::Backend`].
use crate::Host;
use crate::Project;
use crate::ops::blocking;
use ide_command::command;
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_svn::WorkingCopy;
use ide_vcs::Backend;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// The working copy a Subversion backend is, if it is one.
pub(crate) fn as_svn(backend: &dyn Backend) -> Option<&WorkingCopy> {
(backend as &dyn std::any::Any).downcast_ref::<WorkingCopy>()
}
/// Runs `f` with the Subversion working copy `at` names (its root), or the one holding `path`.
fn with_working_copy<T>(
project: &Project,
at: Option<&Path>,
f: impl FnOnce(&WorkingCopy) -> IdeResult<T>,
) -> IdeResult<T> {
let backend: Option<Arc<dyn Backend>> = match at {
Some(path) => project.backend_of(path),
None => project.backend_at(None),
};
match backend.as_deref().and_then(as_svn) {
Some(wc) => f(wc),
None => Err(IdeError::invalid("not in a Subversion working copy")),
}
}
/// VCS › Subversion › Cleanup: finishes or undoes an interrupted operation and
/// releases the working copy's lock.
#[command(trust = trusted)]
pub async fn svn_cleanup(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
with_working_copy(&project, repo.as_deref(), |wc| wc.cleanup(&CancellationToken::new()))?;
project.vcs_changed();
Ok(())
})
.await
}
/// VCS › Subversion › Lock: `svn lock` with a comment; `steal` takes a lock someone else holds.
#[command(trust = trusted)]
pub async fn svn_lock(host: &Host, window: &str, paths: Vec<PathBuf>, comment: String, steal: bool) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
let first = paths.first().cloned().ok_or_else(|| IdeError::invalid("nothing to lock"))?;
with_working_copy(&project, Some(&first), |wc| wc.lock(&paths, &comment, steal, &CancellationToken::new()))?;
project.vcs_changed();
Ok(())
})
.await
}
/// VCS › Subversion › Unlock; `force` breaks a lock this working copy does not hold.
#[command(trust = trusted)]
pub async fn svn_unlock(host: &Host, window: &str, paths: Vec<PathBuf>, force: bool) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
let first = paths.first().cloned().ok_or_else(|| IdeError::invalid("nothing to unlock"))?;
with_working_copy(&project, Some(&first), |wc| wc.unlock(&paths, force, &CancellationToken::new()))?;
project.vcs_changed();
Ok(())
})
.await
}
/// Where a working copy points: VCS › Subversion › Relocate shows the current URL.
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SvnRepositoryInfo {
pub url: String,
pub root_url: String,
pub revision: Option<u32>,
}
#[command(trust = trusted)]
pub async fn svn_repository_info(host: &Host, window: &str, repo: Option<PathBuf>) -> IdeResult<SvnRepositoryInfo> {
let project = host.project(window)?;
blocking(move || {
with_working_copy(&project, repo.as_deref(), |wc| {
let r = wc.repository();
Ok(SvnRepositoryInfo {
url: r.url,
root_url: r.root_url,
revision: r.revision.and_then(|r| u32::try_from(r).ok()),
})
})
})
.await
}
/// VCS › Subversion › Relocate: the same repository at a new URL (another host or scheme).
#[command(trust = trusted)]
pub async fn svn_relocate(host: &Host, window: &str, repo: Option<PathBuf>, url: String) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
with_working_copy(&project, repo.as_deref(), |wc| wc.relocate(&url, &CancellationToken::new()))?;
project.vcs_changed();
Ok(())
})
.await
}
/// The conflicts dialog's Accept Deletion on a tree conflict whose incoming change deleted
/// `path`: the conflict is resolved and the local item removed.
#[command(trust = trusted)]
pub async fn svn_accept_incoming_delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
project.with_backend_recorded(
project.backend_of(&path).as_deref().map(|b| b.root()),
Some("Accept deletion"),
|b| {
as_svn(b)
.ok_or_else(|| IdeError::invalid("not in a Subversion working copy"))?
.accept_incoming_delete(&path)
},
)?;
project.vcs_changed();
Ok(())
})
.await
}
/// One versioned property (`svn:ignore`, `svn:needs-lock`, or the user's own).
#[derive(Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SvnProperty {
pub name: String,
pub value: String,
}
/// VCS › Subversion › Properties: the properties of a file or folder.
#[command(trust = trusted)]
pub async fn svn_properties(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<SvnProperty>> {
let project = host.project(window)?;
blocking(move || {
with_working_copy(&project, Some(&path), |wc| {
Ok(wc.properties(&path)?.into_iter().map(|(name, value)| SvnProperty { name, value }).collect())
})
})
.await
}
/// Sets property `name` of `path`, or deletes it when `value` is `None`.
#[command(trust = trusted)]
pub async fn svn_set_property(
host: &Host,
window: &str,
path: PathBuf,
name: String,
value: Option<String>,
) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
with_working_copy(&project, Some(&path), |wc| wc.set_property(&path, &name, value.as_deref()))?;
project.vcs_changed();
Ok(())
})
.await
}
/// Settings › Version Control › Subversion: the svn found on `PATH` or in a usual
/// install folder, and the version of `executable` (that one when empty).
#[derive(Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SvnVersion {
pub detected: Option<String>,
pub version: Option<String>,
pub error: Option<String>,
}
/// Settings › Subversion › Test. Auto-detection runs anywhere; a path of the user's or the
/// project's choosing runs only in a trusted project (as Git's Test does).
#[command(trust = always)]
pub async fn svn_version(host: &Host, window: &str, executable: String) -> IdeResult<SvnVersion> {
if !executable.trim().is_empty() {
host.require_trust_if_project(window)?;
}
blocking(move || {
let detected = ide_svn::detected_executable().map(|p| p.display().to_string());
let settings = ide_svn::Settings {
executable: (!executable.trim().is_empty()).then(|| PathBuf::from(executable.trim())),
..ide_svn::Settings::default()
};
let (version, error) = match ide_svn::SvnContext::new(settings).version() {
Ok((major, minor)) if (major, minor) < ide_svn::MIN_VERSION => (
Some(format!("{major}.{minor}")),
Some(format!(
"OpenIDEA needs Subversion {}.{} or later",
ide_svn::MIN_VERSION.0,
ide_svn::MIN_VERSION.1
)),
),
Ok((major, minor)) => (Some(format!("{major}.{minor}")), None),
Err(e) => (None, Some(e.message)),
};
Ok(SvnVersion { detected, version, error })
})
.await
}
/// Get from Version Control › Subversion: `svn checkout` of `url` into `dest`, with the
/// window's project settings when it has a project, the global ones otherwise. svn's progress
/// lines go to `on_output`; `cancel_request(request)` stops it (as Git's clone).
#[command(trust = always)]
pub async fn svn_checkout(
host: &Host,
window: &str,
request: ide_core::RequestId,
url: String,
dest: PathBuf,
on_output: crate::ops::Channel<String>,
) -> IdeResult<()> {
let project = host.project(window).ok();
let ctx = match project.as_ref().and_then(|p| p.svn.clone()) {
Some(ctx) => {
if let Some(p) = &project {
p.apply_svn_settings();
}
ctx
}
None => {
// No project yet: the global settings, and prompts in the window that asked.
let ctx = crate::svn::context(&(host.sink_for)(window), host.subversion == Some(true));
ctx.set_settings(crate::svn::settings(&host.global_settings.read_effective(|s| s.vcs.svn.clone())));
ctx
}
};
let cancel = host.begin_request(request);
let result = blocking(move || {
let report = |line: String| {
let _ = on_output.send(line);
};
WorkingCopy::checkout_reporting(&url, None, &dest, ide_svn::Depth::Infinity, ctx, &cancel, &report).map(|_| ())
})
.await;
host.end_request(request);
result
}
ide_command::domain!(
svn:
svn_accept_incoming_delete,
svn_checkout,
svn_cleanup,
svn_lock,
svn_properties,
svn_relocate,
svn_repository_info,
svn_set_property,
svn_unlock,
svn_version,
);
+15
Переглянути файл
@@ -37,6 +37,10 @@ pub async fn vcs_status_paths(host: &Host, window: &str, paths: Vec<std::path::P
/// by the backend [`crate::Project::backend_of`] routes it to. `paths` narrows them (empty:
/// everything). A working copy that cannot answer (an unreachable server) is logged and
/// skipped while another backend answered, so it never hides the Git changes.
/// The last status failure said for each working copy root (see [`merged_status`]).
static STATUS_FAILURES: parking_lot::Mutex<std::collections::BTreeMap<std::path::PathBuf, String>> =
parking_lot::Mutex::new(std::collections::BTreeMap::new());
fn merged_status(project: &crate::Project, paths: Option<&[std::path::PathBuf]>) -> IdeResult<Vec<FileStatus>> {
let settings = project.settings.effective();
let repos = project.repos();
@@ -80,9 +84,20 @@ fn merged_status(project: &crate::Project, paths: Option<&[std::path::PathBuf]>)
Ok(changes) => {
answered = true;
status.extend(changes.into_iter().filter(|f| owner(f) == Some(backend.root())));
STATUS_FAILURES.lock().remove(backend.root());
}
Err(e) => {
tracing::warn!("status of {}: {e}", backend.root().display());
// Said once per root and message, not on every refresh: the Changes view would
// otherwise show that root as unchanged without a word.
let root = backend.root().to_path_buf();
if STATUS_FAILURES.lock().insert(root.clone(), e.message.clone()).as_ref() != Some(&e.message) {
project.sink.emit(ide_core::IdeEvent::Notify {
level: ide_core::event::NotifyLevel::Warning,
title: format!("Changes of {} could not be read", root.display()),
body: Some(e.message.clone()),
});
}
failure = Some(e);
}
}
+64 -10
Переглянути файл
@@ -584,6 +584,7 @@ fn unavailable_vcs_root(root: &Path) -> VcsRoot {
VcsRoot {
root: root.into(),
branch_root: root.into(),
// Only Git repositories are mapped (Directory Mappings).
kind: VcsKind::Git,
operation: None,
interactive_rebase: false,
@@ -1113,6 +1114,20 @@ pub async fn vcs_commit_files(
blocking(move || project.with_log_backend_at(repo.as_deref(), |r| r.commit_files(&commit))).await
}
/// What `commit` did to one file (`path`, relative to the repository), without listing the
/// commit's other changes; `None` when it left the file as it was.
#[command(trust = always)]
pub async fn vcs_commit_file_change(
host: &Host,
window: &str,
repo: Option<PathBuf>,
commit: String,
path: String,
) -> IdeResult<Option<ChangedFile>> {
let project = LogAccess::new(host, window, repo.as_deref());
blocking(move || project.with_log_backend_at(repo.as_deref(), |r| r.commit_file_change(&commit, &path))).await
}
#[command(trust = trusted)]
pub async fn vcs_preview_partial_commit(host: &Host, window: &str, file: PartialCommitFile) -> IdeResult<String> {
let project = host.project(window)?;
@@ -1189,9 +1204,12 @@ pub async fn vcs_commit_selection_changes(
) -> IdeResult<Vec<RevisionChange>> {
let project = LogAccess::new(host, window, repo.as_deref());
let cancel = host.begin_project_read_request(window, request);
let result =
blocking(move || project.with_log_repo_at(repo.as_deref(), |r| r.commit_selection_changes(&commits, &cancel)))
.await;
let result = blocking(move || match project.backend(repo.as_deref()) {
// Post-commit checks read what a commit changed, in a working copy of another system too.
Some(backend) => backend.commits_changes(&commits),
None => project.with_log_repo_at(repo.as_deref(), |r| r.commit_selection_changes(&commits, &cancel)),
})
.await;
host.end_request(request);
result
}
@@ -1421,10 +1439,21 @@ pub async fn vcs_checkout(
with_shelf_batch(&project, shelf_batch, || {
// A non-Git working copy switches to another line of development (`svn switch`).
if project.backend_at(repo.as_deref()).is_some() {
if create {
return Err(ide_core::IdeError::unavailable("creating a branch is not supported here"));
}
return project.with_backend_recorded(repo.as_deref(), Some("Switch"), |b| {
if create {
// New Branch in a Subversion working copy: Create Branch or Tag (`svn copy` on
// the server) to `branches/<name>`, or `tags/<name>` as typed, then switch to it.
let wc = crate::ops::svn::as_svn(b).ok_or_else(|| {
ide_core::IdeError::unavailable("creating a branch is not supported here")
})?;
let line = if branch.starts_with("branches/") || branch.starts_with("tags/") {
branch.clone()
} else {
format!("branches/{branch}")
};
wc.create_line(&line, &format!("Create {line}"), &ide_core::CancellationToken::new())?;
return b.switch_to(&line).map(|()| CheckoutOutcome::Done);
}
b.switch_to(&branch).map(|()| CheckoutOutcome::Done)
});
}
@@ -2066,8 +2095,14 @@ pub async fn vcs_update_branches(
#[command(trust = always)]
pub async fn vcs_conflict_versions(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_vcs::MergeVersions> {
let project = host.project(window)?;
blocking(move || project.with_repo_of(&path, |r| r.merge_versions(&path, project.vcs_encoding(&path, Some(":2"))?)))
.await
blocking(move || {
project.with_backend_of(&path, |b| {
// Git reads the user's side from the index; a working copy without one, from the file.
let rev = if b.as_git().is_some() { ":2" } else { "WT" };
b.conflict_versions(&path, project.vcs_encoding(&path, Some(rev))?)
})
})
.await
}
#[command(trust = trusted)]
@@ -2083,8 +2118,7 @@ pub async fn vcs_accept_conflict_side(
ide_vcs::ConflictSide::Ours => "Accept yours",
ide_vcs::ConflictSide::Theirs => "Accept theirs",
};
blocking(move || per_repo(&project, &paths, Some(label), |repo, paths| repo.accept_conflict_side(paths, side)))
.await
blocking(move || per_backend(&project, &paths, Some(label), |b, paths| b.accept_conflict_side(paths, side))).await
}
#[command(trust = trusted)]
@@ -2095,6 +2129,23 @@ pub async fn vcs_revert_resolved(host: &Host, window: &str, paths: Vec<PathBuf>)
.await
}
/// Marks the conflicts of `paths` resolved with the files as they are (the merge editor
/// saved its result): `git add`, `svn resolve --accept working`.
#[command(trust = trusted)]
pub async fn vcs_mark_resolved(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
host.require_trust(window)?;
let project = host.project(window)?;
blocking(move || per_backend(&project, &paths, Some("Mark resolved"), |b, paths| b.mark_resolved(paths))).await
}
/// The conflicts of `path` the merge editor does not show (property and tree conflicts of
/// a Subversion working copy); none for a Git repository.
#[command(trust = always)]
pub async fn vcs_conflict_details(host: &Host, window: &str, path: PathBuf) -> IdeResult<Vec<ide_vcs::ConflictDetail>> {
let project = host.project(window)?;
blocking(move || project.with_backend_of(&path, |b| b.conflict_details(&path))).await
}
#[command(trust = always)]
pub async fn vcs_diff_text(host: &Host, window: &str, path: PathBuf, staged: bool) -> IdeResult<String> {
let project = host.project(window)?;
@@ -3563,6 +3614,7 @@ ide_command::domain!(
vcs_commit,
vcs_keep_amend_commit,
vcs_commit_crlf_paths,
vcs_commit_file_change,
vcs_commit_files,
vcs_commit_large_files,
vcs_preview_partial_commit,
@@ -3582,6 +3634,8 @@ ide_command::domain!(
vcs_conflict_versions,
vcs_accept_conflict_side,
vcs_revert_resolved,
vcs_mark_resolved,
vcs_conflict_details,
vcs_create_branch,
vcs_undo_branch_creation,
vcs_create_patch,
+39 -6
Переглянути файл
@@ -15,14 +15,35 @@ use std::process::{Command, Stdio};
/// The generators, in order of preference, and their arguments for `container`.
const TOOLS: [&str; 2] = ["xcode-build-server", "sourcekit-xcode-bsp"];
fn tool_args(tool: &str, container: &str) -> Vec<String> {
fn tool_args(tool: &str, container: &str, build_root: Option<&Path>) -> Vec<String> {
if tool == "sourcekit-xcode-bsp" {
// Detects the workspace or project in the working directory itself.
return vec!["init".into()];
}
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
// Without `-scheme` it binds the scheme built last.
vec!["config".into(), flag.into(), container.into()]
let mut args: Vec<String> = vec!["config".into(), flag.into(), container.into()];
if let Some(dir) = build_root {
args.extend(["--build_root".into(), dir.to_string_lossy().into_owned()]);
}
args
}
/// The DerivedData folder Xcode (and a run) builds `container` in, read from the build settings of
/// the first scheme in `root`'s projects. Without it xcode-build-server reads the build settings of
/// the workspace's first scheme, which may be a package's with none (an `IndexError` on a Tuist
/// workspace whose first scheme is a Swift package). `None` leaves it to xcode-build-server.
fn build_root(root: &Path, container: &str) -> Option<std::path::PathBuf> {
let scheme = ide_run::xcode::schemes(root).into_iter().next()?.name;
let flag = if container.ends_with(".xcworkspace") { "-workspace" } else { "-project" };
let mut cmd = Command::new("xcodebuild");
ide_core::process::prepare(&mut cmd)
.args([flag, container, "-scheme", &scheme, "-showBuildSettings", "-json"])
.current_dir(root)
.stdin(Stdio::null())
.stderr(Stdio::null());
let out = cmd.output().ok().filter(|o| o.status.success())?;
ide_run::xcode_clean::derived_data_of(&String::from_utf8_lossy(&out.stdout))
}
/// The config `tool` writes at the project root.
@@ -121,7 +142,8 @@ pub async fn xcode_bsp_generate(host: &Host, window: &str, tool: String, contain
.ok_or_else(|| IdeError::unavailable(format!("{tool} is not installed")))?;
let mut cmd = Command::new(exe);
ide_core::process::prepare(&mut cmd)
.args(tool_args(&tool, &container))
// An absolute path: with `--build_root` it is written to the config as given.
.args(tool_args(&tool, &root.join(&container).to_string_lossy(), build_root(&root, &container).as_deref()))
.current_dir(&root)
.env("PATH", &search)
.stdin(Stdio::null());
@@ -169,9 +191,20 @@ mod tests {
#[test]
fn passes_the_container_to_xcode_build_server() {
assert_eq!(tool_args("xcode-build-server", "A.xcworkspace"), ["config", "-workspace", "A.xcworkspace"]);
assert_eq!(tool_args("xcode-build-server", "A.xcodeproj"), ["config", "-project", "A.xcodeproj"]);
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj"), ["init"]);
assert_eq!(tool_args("xcode-build-server", "A.xcworkspace", None), ["config", "-workspace", "A.xcworkspace"]);
assert_eq!(tool_args("xcode-build-server", "A.xcodeproj", None), ["config", "-project", "A.xcodeproj"]);
let dd = Path::new("/Users/me/Library/Developer/Xcode/DerivedData/A-abc");
assert_eq!(
tool_args("xcode-build-server", "A.xcworkspace", Some(dd)),
[
"config",
"-workspace",
"A.xcworkspace",
"--build_root",
"/Users/me/Library/Developer/Xcode/DerivedData/A-abc"
]
);
assert_eq!(tool_args("sourcekit-xcode-bsp", "A.xcodeproj", Some(dd)), ["init"]);
}
fn git_in(dir: &Path, args: &[&str]) {
+2
Переглянути файл
@@ -447,6 +447,8 @@ pub(crate) fn outline(items: Vec<DocumentSymbol>) -> Vec<ide_core::OutlineItem>
selection_range: i.selection_range,
children: vec![],
visibility: None,
implements: None,
self_type: None,
})
})
.collect();
+10 -5
Переглянути файл
@@ -3008,11 +3008,16 @@ impl PluginHost {
{
let mut plugins = self.plugins.write();
if let Some(existing) = plugins.get(&id) {
tracing::warn!(
"plugin {id:?} at {} ignored: already loaded from {}",
dir.display(),
existing.dir().display()
);
// Every rescan meets the same duplicate again: say it once per directory, not on each scan.
static WARNED: std::sync::LazyLock<Mutex<std::collections::HashSet<(String, PathBuf)>>> =
std::sync::LazyLock::new(Default::default);
if WARNED.lock().insert((id.clone(), dir.to_path_buf())) {
tracing::warn!(
"plugin {id:?} at {} ignored: already loaded from {}",
dir.display(),
existing.dir().display()
);
}
return (id, None);
}
plugins.insert(id.clone(), plugin.clone());
+169 -8
Переглянути файл
@@ -49,6 +49,13 @@ pub struct Project {
/// Held for a whole scan of `backends`, so overlapping scans (project open, trust change)
/// finish in turn and the last one reads the current trust.
backend_scan: Arc<Mutex<()>>,
/// Folders with a working-copy marker that a scan did not make roots (svn missing, a format
/// it cannot read), with the marker's time then: saving files there does not scan again
/// until the marker or the svn settings change.
unresolved_markers: Arc<Mutex<HashMap<PathBuf, Option<std::time::SystemTime>>>>,
/// How svn runs for this project (Settings › Version Control › Subversion, its prompts);
/// `None` without Subversion support.
pub svn: Option<Arc<ide_svn::SvnContext>>,
/// Explicitly opened external logs remain read-only and outside project indexing.
pub(crate) external_log_repos: RwLock<Vec<Arc<Repo>>>,
/// Incrementally maintained syntax trees of the open documents.
@@ -59,6 +66,9 @@ pub struct Project {
pub detected_roots: Arc<RwLock<Vec<SourceFolder>>>,
/// The excluded folders of the workspace's other projects; see [`member_excludes`].
pub(crate) member_excludes: MemberExcludes,
/// Last reported trust state of attached workspace members, so trust changes on an
/// attached-only root still emit `ProjectTrustChanged` for the workspace window.
pub(crate) member_trust: RwLock<BTreeMap<PathBuf, bool>>,
/// Per-project cache directory (build tool sync results…).
pub cache_dir: PathBuf,
/// Pending launches and retained snapshots, scoped to each workspace project.
@@ -156,6 +166,20 @@ impl Host {
ide_build::gradle::forget_build_dirs(&root);
let detected_roots = Arc::new(RwLock::new(ide_workspace::roots::detect(&root)));
let member_excludes: MemberExcludes = Arc::new(RwLock::new(member_excludes(&settings, &root)));
let initial_member_trust: BTreeMap<PathBuf, bool> = ide_workspace::workspace::Workspace::load(&root)
.ok()
.flatten()
.map(|ws| {
ws.projects
.into_iter()
.filter(|p| p != &root)
.map(|p| {
let t = self.trust.trusted(&p).unwrap_or(false);
(p, t)
})
.collect()
})
.unwrap_or_default();
let excludes = exclude_globs(&root, &settings.effective(), &detected_roots.read(), &member_excludes.read());
let build_cache = self.local_data_dir.join("cache").join(project_key(&root)).join("build");
let extra_roots = content_roots(&settings.effective(), &root, &build_cache, trusted.load(Ordering::Acquire));
@@ -438,8 +462,18 @@ impl Host {
documents.add_observer(tsc_watch.clone());
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
let backends: Arc<RwLock<Vec<Arc<dyn Backend>>>> = Arc::default();
let vcs_providers: Arc<[Arc<dyn BackendProvider>]> = self.vcs_providers.clone().into();
// Subversion's settings and prompts belong to this project (and its window).
let svn = self.subversion.map(|prompts| crate::svn::context(&sink, prompts));
if let Some(ctx) = &svn {
ctx.set_settings(crate::svn::settings(&settings.read_effective(|s| s.vcs.svn.clone())));
}
let mut providers = self.vcs_providers.clone();
if let Some(ctx) = &svn {
providers.push(Arc::new(ide_svn::Provider::new(ctx.clone())));
}
let vcs_providers: Arc<[Arc<dyn BackendProvider>]> = providers.into();
let backend_scan: Arc<Mutex<()>> = Arc::default();
let unresolved_markers: Arc<Mutex<HashMap<PathBuf, Option<std::time::SystemTime>>>> = Arc::default();
for repo in repos.read().all() {
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
}
@@ -478,8 +512,8 @@ impl Host {
let build_cache = build_cache.clone();
let notify_watch_exhausted = notify_watch_exhausted.clone();
let watcher_weak = watcher_weak.clone();
let (backends, vcs_providers, backend_scan) =
(backends.clone(), vcs_providers.clone(), backend_scan.clone());
let (backends, vcs_providers, backend_scan, unresolved_markers) =
(backends.clone(), vcs_providers.clone(), backend_scan.clone(), unresolved_markers.clone());
let markers: Vec<String> = vcs_providers.iter().filter_map(|p| p.marker().map(str::to_owned)).collect();
Watcher::start(
&root.clone(),
@@ -629,13 +663,17 @@ impl Host {
let is_marker = p.file_name().is_some_and(|n| markers.iter().any(|m| n == m.as_str()));
folders.extend(if !is_marker && p.is_dir() { Some(p.as_path()) } else { p.parent() });
}
let appeared = folders
let fresh: Vec<PathBuf> = folders
.iter()
.any(|d| !known.iter().any(|r| r == d) && markers.iter().any(|m| d.join(m).exists()));
.filter(|d| !known.iter().any(|r| r == *d) && markers.iter().any(|m| d.join(m).exists()))
.filter(|d| unresolved_markers.lock().get(**d) != Some(&marker_time(d, &markers)))
.map(|d| d.to_path_buf())
.collect();
let gone = batch.removed.iter().any(|p| known.iter().any(|r| r.starts_with(p)));
if appeared || gone {
if !fresh.is_empty() || gone {
let (backends, providers, lock, trust) =
(backends.clone(), vcs_providers.clone(), backend_scan.clone(), trusted.clone());
let (unresolved, markers) = (unresolved_markers.clone(), markers.clone());
let (root, settings, sink, cache) =
(root.clone(), settings.clone(), sink.clone(), build_cache.clone());
let rescan = move || {
@@ -646,6 +684,14 @@ impl Host {
trusted: &trust,
};
scan.run(&root, &settings, &sink, &cache);
// Still no root there: not asked again until its marker changes.
let known: Vec<PathBuf> =
backends.read().iter().map(|b| b.root().to_path_buf()).collect();
let mut unresolved = unresolved.lock();
for d in fresh.into_iter().filter(|d| !known.contains(d)) {
let time = marker_time(&d, &markers);
unresolved.insert(d, time);
}
};
if let Err(e) = std::thread::Builder::new().name("openidea-vcs-roots".into()).spawn(rescan)
{
@@ -785,11 +831,14 @@ impl Host {
backends,
vcs_providers,
backend_scan,
unresolved_markers,
svn,
external_log_repos: RwLock::default(),
structure: Arc::new(StructureService::new(syntax.clone())),
syntax,
detected_roots,
member_excludes,
member_trust: RwLock::new(initial_member_trust),
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
@@ -906,7 +955,21 @@ impl Host {
.with_local_external_tunnels(self.local_database_tunnels),
);
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(
let agents = self.automations.take_or_build_project_agents(self, root, project_key, settings, sink);
(db, http_history, agents)
}
pub(crate) fn create_agent_manager(
&self,
root: &Path,
project_key: &str,
settings: &Arc<SettingsStore>,
sink: &SharedSink,
force_git_enabled: Option<bool>,
) -> Arc<ide_agent::AgentManager> {
let live_external =
self.automations.live_external_task_ids_for((project_key != "__chat_automations__").then_some(root));
let agents = Arc::new(ide_agent::AgentManager::new_with_live_tasks(
ide_agent::AgentPaths {
project_root: root.to_path_buf(),
store_dir: self.data_dir.join("agents").join(project_key),
@@ -929,12 +992,60 @@ impl Host {
})),
},
self.runtime.clone(),
&live_external,
));
let settings = settings.clone();
{
let settings = settings.clone();
agents.set_security_hook(Arc::new(move || settings.effective().agent_security));
}
{
let settings = settings.clone();
agents.set_new_task_approvals_hook(Arc::new(move || settings.effective().agents.new_task_approvals));
}
{
let trust = self.trust.clone();
agents.set_repo_trust_hook(Arc::new(move |repo_root| {
let _ = trust.reload();
trust.window_trusted(repo_root).unwrap_or(false)
}));
}
if project_key != "__chat_automations__" {
let trust = self.trust.clone();
agents.set_dispatch_trust_hook(Arc::new(move |proj_root, isolation| {
let _ = trust.reload();
if !trust.window_trusted(proj_root).unwrap_or(false) {
return Err(format!("Paused: project {} is not trusted (Restricted Mode).", proj_root.display()));
}
if isolation == ide_agent::Isolation::Worktree
&& let Ok(Some(canon_repo)) = ide_agent::canonical_repo_root(proj_root)
&& !trust.window_trusted(&canon_repo).unwrap_or(false)
{
return Err(format!(
"Paused: Git repository {} is not trusted (trust the repository root before running worktree automations).",
canon_repo.display()
));
}
Ok(())
}));
}
{
let automations = self.automations.clone();
let config_dir = self.config_dir.clone();
let data_dir = self.data_dir.clone();
let home_dir = self.home_dir();
let sink_c = sink.clone();
agents.set_scheduled_blocked_hook(Arc::new(move |meta, reason| {
automations.pause_blocked_scheduled_turn_raw(
&config_dir,
&data_dir,
home_dir.as_deref(),
Some(&sink_c),
meta,
reason,
);
}));
}
{
let settings = settings.clone();
agents.set_recovery_settings_hook(Arc::new(move || {
@@ -942,6 +1053,12 @@ impl Host {
(effective.agents.network_retry_window, effective.agents.resume_interrupted)
}));
}
if let Some(git_on) = force_git_enabled {
agents.set_git_enabled_hook(Arc::new(move || git_on));
} else {
let settings = settings.clone();
agents.set_git_enabled_hook(Arc::new(move || settings.effective().vcs.git.enabled));
}
let approvals = self.mcp_approvals.clone();
let secrets = self.agent_secrets.clone();
let root = root.to_path_buf();
@@ -979,6 +1096,21 @@ impl Host {
workspace_roots: crate::ops::agent::workspace_skill_roots(&mem_root),
}
}));
let plug_settings = settings.clone();
let plug_root = root.clone();
let plug_trust = self.trust.clone();
let plug_approvals = self.plugin_approvals.clone();
agents.set_plugins_policy_hook(Box::new(move || {
let layer = |scope| plug_settings.layer(scope).agents.plugins.clone();
let workspace_trusted = plug_trust.window_trusted(&plug_root).unwrap_or(false);
ide_agent::plugins::PluginsPolicy {
user: layer(ide_workspace::settings::SettingsScope::Global),
workspace: layer(ide_workspace::settings::SettingsScope::Project),
workspace_trusted,
workspace_roots: crate::ops::agent::workspace_skill_roots(&plug_root),
approved_capabilities: plug_approvals.snapshot(),
}
}));
agents.set_mcp_servers_hook(Box::new(move || {
crate::ops::agent::session_mcp_servers(&settings, &approvals, &secrets, &root)
}));
@@ -986,7 +1118,7 @@ impl Host {
let mcp_executable = self.mcp_executable.clone();
agents.set_mcp_executable_hook(Box::new(move || mcp_executable.read().clone()));
}
(db, http_history, agents)
agents
}
}
@@ -1089,11 +1221,14 @@ impl Host {
backends: Arc::default(),
vcs_providers: Arc::new([]),
backend_scan: Arc::default(),
unresolved_markers: Arc::default(),
svn: None,
external_log_repos: RwLock::default(),
structure: Arc::new(StructureService::new(syntax.clone())),
syntax,
detected_roots: Arc::default(),
member_excludes: Arc::default(),
member_trust: RwLock::default(),
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
@@ -1294,6 +1429,11 @@ fn repository_searched(root: &Path, dir: &Path, settings: &ide_core::settings::S
&& Repos::searched(root, dir, &repository_scan_skips(settings))
}
/// When `dir`'s working-copy marker last changed.
fn marker_time(dir: &Path, markers: &[String]) -> Option<std::time::SystemTime> {
markers.iter().find_map(|m| dir.join(m).metadata().and_then(|m| m.modified()).ok())
}
/// Asks `providers` in order about `folder`; the first to answer adds its working copy to
/// `found`, unless one with the same root is there already.
fn ask_providers<'a>(
@@ -1405,6 +1545,8 @@ impl Project {
/// Looks for the non-Git working copies again: they are found in a trusted project only,
/// so trusting it (or restricting it) changes the answer.
pub fn refresh_backends(&self) {
self.apply_svn_settings();
self.unresolved_markers.lock().clear();
let scan = BackendScan {
backends: &self.backends,
providers: &self.vcs_providers,
@@ -1414,6 +1556,24 @@ impl Project {
scan.run(&self.root, &self.settings, &self.sink, &self.build_cache_dir());
}
/// Settings › Version Control › Subversion as this project has them, for its next svn
/// command. An untrusted project's own svn settings never run (as with its Git executable):
/// the global ones apply. Written only when they changed.
pub fn apply_svn_settings(&self) {
let Some(ctx) = &self.svn else { return };
let svn = if self.is_trusted() {
self.settings.read_effective(|s| s.vcs.svn.clone())
} else {
self.settings.layer(ide_workspace::settings::SettingsScope::Global).vcs.svn
};
let next = crate::svn::settings(&svn);
if ctx.settings() != next {
ctx.set_settings(next);
// Another svn may read the folders this one could not.
self.unresolved_markers.lock().clear();
}
}
/// Tells the UI that what version control reports changed without a file event (a file
/// was opened for edit).
pub fn vcs_changed(&self) {
@@ -1427,6 +1587,7 @@ impl Project {
if !self.is_trusted() {
return Vec::new();
}
self.apply_svn_settings();
let repos = self.repos.read();
self.backends.read().iter().filter(|b| repos.at_root(b.root()).is_none()).cloned().collect()
}
+1
Переглянути файл
@@ -364,6 +364,7 @@ pub fn client_accepts(event: &IdeEvent, trusted: bool) -> bool {
| IdeEvent::UpdateAvailable { .. } => false,
IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. } => trusted,
IdeEvent::DbSourcesChanged
| IdeEvent::AutomationsChanged
| IdeEvent::PlotAdded { .. }
| IdeEvent::ProjectTrustChanged { .. }
| IdeEvent::Direnv { .. }
+147
Переглянути файл
@@ -0,0 +1,147 @@
//! Subversion in a project: its [`SvnContext`] (Settings › Version Control ›
//! Subversion as the project has them) and svn's prompts shown in the
//! project's window through the askpass dialog (`IdeEvent::Askpass`, answered
//! with `ssh_askpass_answer`).
use ide_core::IdeEvent;
use ide_core::event::{AskpassKind, SharedSink};
use ide_svn::{Prompt, PromptHandler, Settings, SvnContext};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, mpsc};
use std::time::Duration;
/// Prompt ids of svn, apart from those the askpass server hands out (counting from 1).
static NEXT_ID: AtomicU64 = AtomicU64::new(1 << 48);
static PENDING: Mutex<Option<HashMap<u64, mpsc::Sender<Option<String>>>>> = Mutex::new(None);
/// How long a prompt waits for the user before the command is cancelled.
const ANSWER_TIMEOUT: Duration = Duration::from_secs(10 * 60);
/// Delivers the answer to svn prompt `id`; false when no svn command waits for it.
pub fn answer_prompt(id: u64, answer: Option<String>) -> bool {
match PENDING.lock().as_mut().and_then(|p| p.remove(&id)) {
Some(tx) => tx.send(answer).is_ok(),
None => false,
}
}
/// The context of a new project: prompts open in its window when `prompts`.
pub(crate) fn context(sink: &SharedSink, prompts: bool) -> Arc<SvnContext> {
let ctx = Arc::new(SvnContext::new(Settings::default()));
if prompts {
ctx.set_prompt_handler(Some(Arc::new(WindowPrompts { sink: sink.clone() })));
}
ctx
}
/// The svn run settings from a project's `vcs.svn`; `svn+ssh://` passphrases go to
/// the app's askpass like git's.
pub(crate) fn settings(svn: &ide_core::workflow_settings::SvnSettings) -> Settings {
let path = |s: &str| (!s.trim().is_empty()).then(|| PathBuf::from(s.trim()));
Settings {
executable: path(&svn.executable),
interactive: svn.interactive,
config_dir: if svn.use_custom_config_dir { path(&svn.config_dir) } else { None },
env: ide_vcs::askpass_env(),
}
}
struct WindowPrompts {
sink: SharedSink,
}
impl PromptHandler for WindowPrompts {
fn answer(&self, prompt: &Prompt) -> Option<String> {
let (text, kind) = describe(prompt);
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = mpsc::channel();
PENDING.lock().get_or_insert_default().insert(id, tx);
self.sink.emit(IdeEvent::Askpass { id, prompt: text, kind, remember: false });
let answer = rx.recv_timeout(ANSWER_TIMEOUT).ok().flatten();
if let Some(pending) = PENDING.lock().as_mut() {
pending.remove(&id);
}
self.sink.emit(IdeEvent::AskpassDone { id });
reply(prompt, answer?)
}
}
/// The dialog's text and input for a prompt.
pub(crate) fn describe(prompt: &Prompt) -> (String, AskpassKind) {
let realm = |realm: &str| if realm.is_empty() { String::new() } else { format!(" ({realm})") };
match prompt {
Prompt::Username { realm: r } => (format!("Subversion username{}:", realm(r)), AskpassKind::Text),
Prompt::Password { realm: r, username } => {
(format!("Subversion password for '{username}'{}:", realm(r)), AskpassKind::Secret)
}
Prompt::ClientCertificate { realm: r } => (format!("Client certificate file{}:", realm(r)), AskpassKind::Text),
Prompt::ClientCertificatePassphrase { file, .. } => {
(format!("Passphrase for client certificate '{file}':"), AskpassKind::Secret)
}
Prompt::ServerCertificate { details, permanent, .. } => {
let keep = if *permanent { "Trust it and remember the choice?" } else { "Trust it for this command?" };
(format!("{details}\n\n{keep}"), AskpassKind::Confirm)
}
Prompt::StorePlaintext { details } => {
(format!("{details}\n\nStore the password unencrypted?"), AskpassKind::Confirm)
}
}
}
/// What svn reads for the dialog's answer: a confirmation is `yes` / `no`.
pub(crate) fn reply(prompt: &Prompt, answer: String) -> Option<String> {
let yes = answer == "yes";
Some(match prompt {
Prompt::ServerCertificate { permanent: true, .. } if yes => "p".into(),
Prompt::ServerCertificate { .. } if yes => "t".into(),
Prompt::ServerCertificate { .. } => "R".into(),
Prompt::StorePlaintext { .. } => if yes { "yes" } else { "no" }.into(),
_ => answer,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_prompts_to_the_askpass_dialog() {
let cert =
Prompt::ServerCertificate { url: "https://h".into(), details: "Fingerprint: AB".into(), permanent: true };
assert_eq!(describe(&cert).1, AskpassKind::Confirm);
assert_eq!(reply(&cert, "yes".into()).as_deref(), Some("p"));
assert_eq!(reply(&cert, "no".into()).as_deref(), Some("R"));
let temporary = Prompt::ServerCertificate { url: String::new(), details: String::new(), permanent: false };
assert_eq!(reply(&temporary, "yes".into()).as_deref(), Some("t"));
let password = Prompt::Password { realm: "<svn://h:3690> Test".into(), username: "ann".into() };
assert_eq!(
describe(&password),
("Subversion password for 'ann' (<svn://h:3690> Test):".into(), AskpassKind::Secret)
);
assert_eq!(reply(&password, "secret".into()).as_deref(), Some("secret"));
}
#[test]
fn answers_reach_only_waiting_prompts() {
assert!(!answer_prompt(7, None));
let events: Arc<Mutex<Vec<u64>>> = Arc::default();
let seen = events.clone();
let sink: SharedSink = Arc::new(move |e: IdeEvent| {
if let IdeEvent::Askpass { id, .. } = e {
seen.lock().push(id);
}
});
let handler = WindowPrompts { sink };
let asked = std::thread::spawn(move || handler.answer(&Prompt::Username { realm: String::new() }));
let id = loop {
if let Some(id) = events.lock().first().copied() {
break id;
}
std::thread::sleep(Duration::from_millis(5));
};
assert!(answer_prompt(id, Some("ann".into())));
assert_eq!(asked.join().unwrap().as_deref(), Some("ann"));
}
}
+64
Переглянути файл
@@ -87,6 +87,21 @@ impl TrustStore {
self.state.lock().clone()
}
/// Re-reads persisted `project-trust.json` from disk so trust revocations made by another
/// OpenIDEA process (e.g. desktop revoking trust while `--scheduler` or `--daemon` runs)
/// take effect immediately before scheduled execution.
pub fn reload(&self) -> IdeResult<()> {
let loaded = match std::fs::read(&self.file) {
Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| IdeError::invalid(e.to_string())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(TrustDecisions::default()),
Err(e) => Err(e.into()),
};
let mut state = self.state.lock();
let res = loaded.as_ref().map(|_| ()).map_err(Clone::clone);
*state = loaded;
res
}
pub fn trusted(&self, path: &Path) -> IdeResult<bool> {
let root = dunce::canonicalize(path)?;
let decisions = self.decisions()?;
@@ -237,6 +252,38 @@ impl McpServerApprovals {
}
}
/// Agent plugin capability approvals ([`ide_agent::plugins::capability_approval_key`]) the user
/// granted on this machine. Kept out of settings: enablement lives in each harness's own
/// configuration, and approving what a plugin runs is a per-machine decision.
pub struct PluginCapabilityApprovals {
file: PathBuf,
approved: Mutex<std::collections::BTreeSet<String>>,
}
impl PluginCapabilityApprovals {
pub fn load(data: &Path) -> Self {
let file = data.join("agent-plugin-approvals.json");
let approved = std::fs::read(&file).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();
Self { file, approved: Mutex::new(approved) }
}
pub fn snapshot(&self) -> std::collections::BTreeSet<String> {
self.approved.lock().clone()
}
pub fn approve(&self, key: String) -> IdeResult<()> {
let mut approved = self.approved.lock();
if approved.contains(&key) {
return Ok(());
}
let mut next = approved.clone();
next.insert(key);
persist(&self.file, &next)?;
*approved = next;
Ok(())
}
}
impl crate::Host {
pub async fn set_project_trust(&self, path: &Path, trusted: bool, folder: bool) -> IdeResult<()> {
self.trust.decide(path, trusted, folder)?;
@@ -251,6 +298,23 @@ impl crate::Host {
let trusted = self.trust.window_trusted(&project.root).unwrap_or(false);
let roots = project.content_roots();
let previous = project.trusted.swap(trusted, std::sync::atomic::Ordering::AcqRel);
// Notify workspace windows when an attached-only member's trust changes, even if the
// container window's own `window_trusted` boolean did not flip.
if let Ok(Some(workspace)) = ide_workspace::workspace::Workspace::load(&project.root) {
let mut known = project.member_trust.write();
let current_members: std::collections::BTreeSet<PathBuf> =
workspace.projects.into_iter().filter(|m| m != &project.root).collect();
known.retain(|k, _| current_members.contains(k));
for member in current_members {
let member_trusted = self.trust.trusted(&member).unwrap_or(false);
if known.insert(member.clone(), member_trusted) != Some(member_trusted) {
project.sink.emit(ide_core::IdeEvent::ProjectTrustChanged {
root: member.into(),
trusted: member_trusted,
});
}
}
}
if previous == trusted {
continue;
}
File diff suppressed because it is too large. Load diff
+298
Переглянути файл
@@ -0,0 +1,298 @@
//! Subversion roots a project finds inside a working copy (externals, inner checkouts) and one
//! IDE commit across them, through the shared `vcs_*` commands. Follows IntelliJ's svn4idea
//! SvnExternalTest, SvnExternalCommitNoticedTest and SvnCommitTest (scenarios only); the
//! working copies themselves are checked in crates/ide-svn/tests/ij_files.rs.
//! Skipped when `svn` or `svnadmin` is not installed (a failure in CI).
mod common;
use ide_host::Host;
use ide_host::ops::vcs;
use ide_vcs::{ChangeKind, CommitOptions, FileStatus, VcsKind};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;
fn which(name: &str) -> Option<PathBuf> {
let names = [name.to_owned(), format!("{name}.exe")];
std::env::split_paths(&std::env::var_os("PATH")?)
.flat_map(|dir| names.iter().map(move |n| dir.join(n)))
.find(|p| p.is_file())
}
/// Whether svn is installed: skipped locally without it, a failure in CI (`CI` set).
fn have_svn() -> bool {
let missing: Vec<&str> = ["svn", "svnadmin"].into_iter().filter(|t| which(t).is_none()).collect();
if missing.is_empty() {
return true;
}
// Windows CI runners have no Subversion from a trusted source: the tests skip there.
if !cfg!(windows) && std::env::var_os("CI").is_some_and(|v| !v.is_empty() && v != "false") {
panic!("CI must install {missing:?} for the Subversion tests");
}
false
}
/// `path` as a `file://` URL, `file:///C:/…` on Windows.
fn file_url(path: &Path) -> String {
let text = path.to_string_lossy().replace('\\', "/");
if text.starts_with('/') { format!("file://{text}") } else { format!("file:///{text}") }
}
/// A repository with `trunk`, `branches/shared/part.txt` (an external's target) and a second
/// repository holding `lib/inside.txt`.
struct Fixture {
_temp: tempfile::TempDir,
base: PathBuf,
url: String,
another: String,
}
/// A configuration folder of svn's for the test (no password stores, nothing remembered), and
/// global settings of the test's host (`<base>/config`) that point svn at it.
fn private_svn_config(base: &Path) {
let svn = base.join("svn-config");
std::fs::create_dir_all(&svn).unwrap();
std::fs::write(svn.join("config"), "[auth]\npassword-stores =\n").unwrap();
std::fs::write(svn.join("servers"), "[global]\nstore-passwords = no\nstore-auth-creds = no\n").unwrap();
std::fs::create_dir_all(base.join("config")).unwrap();
std::fs::write(
base.join("config/settings.toml"),
format!("[vcs.svn]\nuseCustomConfigDir = true\nconfigDir = {:?}\n", svn.to_string_lossy()),
)
.unwrap();
}
fn fixture() -> Option<Fixture> {
if !have_svn() {
return None;
}
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
// The hosts below read svn's configuration and logins from here, never ~/.subversion.
private_svn_config(&base);
for name in ["repo", "another"] {
assert!(Command::new("svnadmin").arg("create").arg(base.join(name)).status().unwrap().success());
}
let fx = Fixture { url: file_url(&base.join("repo")), another: file_url(&base.join("another")), base, _temp: temp };
fx.svn(&fx.base, &["mkdir", "-q", "-m", "layout", &format!("{}/trunk", fx.url), &format!("{}/branches", fx.url)]);
fx.import("part.txt", "shared part\n", &format!("{}/branches/shared", fx.url));
fx.import("inside.txt", "from another repository\n", &format!("{}/lib", fx.another));
Some(fx)
}
impl Fixture {
fn svn(&self, cwd: &Path, args: &[&str]) -> String {
let out = Command::new("svn")
.args(args)
.args(["--non-interactive", "--config-dir"])
.arg(self.base.join("svn-config"))
.current_dir(cwd)
.env_remove("LC_ALL")
.env("LC_MESSAGES", "C")
.output()
.unwrap();
assert!(out.status.success(), "svn {args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).into_owned()
}
fn import(&self, name: &str, text: &str, url: &str) {
let dir = self.base.join(format!("import-{name}"));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join(name), text).unwrap();
self.svn(&self.base, &["import", "-q", "-m", "import", dir.to_str().unwrap(), url]);
}
/// `trunk` checked out at `name` with `main.txt` committed.
fn checkout(&self, name: &str) -> PathBuf {
let dest = self.base.join(name);
self.svn(&self.base, &["checkout", "-q", &format!("{}/trunk", self.url), dest.to_str().unwrap()]);
std::fs::write(dest.join("main.txt"), "main\n").unwrap();
self.svn(&dest, &["add", "-q", "main.txt"]);
self.svn(&dest, &["commit", "-q", "-m", "main"]);
self.svn(&dest, &["update", "-q"]);
dest
}
/// The externals definition of both kinds: this repository's and the other one's.
fn externals(&self) -> String {
format!("^/branches/shared ext-same\n{}/lib ext-other\n", self.another)
}
}
async fn until(what: &str, done: impl Fn() -> bool) {
for _ in 0..1000 {
if done() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("timed out waiting for {what}");
}
/// A trusted project at `root`, with its working copy found.
async fn open(base: &Path, root: &Path) -> (Host, Arc<ide_host::Project>) {
let host = Host::new(common::host_config(base)).with_subversion(false);
host.trust.decide(root, true, false).unwrap();
let project = host.open_project("main", root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
(host, project)
}
/// The project's version-control roots, relative to `root` (`.` for itself), sorted.
async fn roots(host: &Host, project: &ide_host::Project, root: &Path) -> Vec<(VcsKind, String)> {
project.refresh_repositories();
let mut out: Vec<(VcsKind, String)> = vcs::vcs_roots(host, "main")
.await
.unwrap()
.into_iter()
.map(|r| {
let rel = r.root.0.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
(r.kind, if rel.is_empty() { ".".to_owned() } else { rel })
})
.collect();
out.sort_by(|a, b| a.1.cmp(&b.1));
out
}
fn svn_roots(names: &[&str]) -> Vec<(VcsKind, String)> {
names.iter().map(|n| (VcsKind::Subversion, (*n).to_owned())).collect()
}
fn rows(status: &[FileStatus], root: &Path) -> Vec<String> {
let mut out: Vec<String> = status
.iter()
.map(|f| {
let rel = f.path.0.strip_prefix(root).unwrap().to_string_lossy().replace('\\', "/");
format!("{rel}:{:?}", f.unstaged.unwrap_or(ChangeKind::Modified))
})
.collect();
out.sort();
out
}
/// Externals from this repository and from another one, their definition committed, are
/// version-control roots of their own next to the working copy holding them.
/// IntelliJ SvnExternalTest.testExternalCopyIsDetected, testExternalCopyIsDetectedAnotherRepo.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn externals_are_roots_of_their_own() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("source");
fx.svn(&root, &["propset", "-q", "svn:externals", &fx.externals(), "."]);
fx.svn(&root, &["commit", "-q", "-m", "externals"]);
fx.svn(&root, &["update", "-q"]);
assert!(root.join("ext-same/part.txt").exists() && root.join("ext-other/inside.txt").exists());
let (host, project) = open(&fx.base, &root).await;
assert_eq!(roots(&host, &project, &root).await, svn_roots(&[".", "ext-other", "ext-same"]));
}
/// A definition set and not committed, fetched by the IDE's Update Project: the externals the
/// update brings become roots. IntelliJ SvnExternalTest.testUncommittedExternalCopyIsDetected,
/// testUncommittedExternalCopyIsDetectedAnother.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn externals_an_update_brings_become_roots() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("source");
fx.svn(&root, &["propset", "-q", "svn:externals", &fx.externals(), "."]);
let (host, project) = open(&fx.base, &root).await;
assert_eq!(roots(&host, &project, &root).await, svn_roots(&["."]));
let channel = ide_host::ops::Channel::new(|_: String| {});
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap();
assert!(root.join("ext-same/part.txt").exists() && root.join("ext-other/inside.txt").exists());
assert_eq!(roots(&host, &project, &root).await, svn_roots(&[".", "ext-other", "ext-same"]));
}
/// A checkout made deep inside a working copy (`inner1/inner2/inner`), from this repository or
/// from another one, is a root of its own. IntelliJ SvnExternalTest.testInnerCopyDetected.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn inner_checkouts_are_roots_of_their_own() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("source");
let inner = root.join("inner1/inner2/inner");
fx.svn(&fx.base, &["checkout", "-q", &format!("{}/branches/shared", fx.url), inner.to_str().unwrap()]);
let other = root.join("other-repo");
fx.svn(&fx.base, &["checkout", "-q", &format!("{}/lib", fx.another), other.to_str().unwrap()]);
let (host, project) = open(&fx.base, &root).await;
assert_eq!(roots(&host, &project, &root).await, svn_roots(&[".", "inner1/inner2/inner", "other-repo"]));
}
/// Edits in a working copy, in checkouts inside it (same and another repository) and in its
/// externals show in the Changes view; one IDE commit (one `vcs_commit` per root, as the
/// Commit window sends it) commits them all. IntelliJ SvnCommitTest.testSameRepoPlusInnerCopyCommit,
/// testAnotherRepoPlusInnerCopyCommit, testPlusExternalCopyCommit; SvnExternalTest
/// testSimpleExternalsStatus at the host; SvnExternalCommitNoticedTest.testExternalCommitInExternals.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn one_commit_across_a_working_copy_and_the_ones_inside_it() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("source");
fx.svn(&root, &["propset", "-q", "svn:externals", &fx.externals(), "."]);
fx.svn(&root, &["commit", "-q", "-m", "externals"]);
fx.svn(&root, &["update", "-q"]);
// Checkouts of folders of their own: two working copies of one file would make the
// second commit out of date, as svn rightly says.
fx.import("part.txt", "inner part\n", &format!("{}/branches/inner", fx.url));
fx.import("inside.txt", "other inside\n", &format!("{}/lib2", fx.another));
let inner = root.join("inner1/inner2/inner");
fx.svn(&fx.base, &["checkout", "-q", &format!("{}/branches/inner", fx.url), inner.to_str().unwrap()]);
let other = root.join("other-repo");
fx.svn(&fx.base, &["checkout", "-q", &format!("{}/lib2", fx.another), other.to_str().unwrap()]);
let (host, _project) = open(&fx.base, &root).await;
let files = [
root.join("main.txt"),
root.join("ext-same/part.txt"),
root.join("ext-other/inside.txt"),
inner.join("part.txt"),
other.join("inside.txt"),
];
for file in &files {
std::fs::write(file, "edited\n").unwrap();
}
let expected = [
"ext-other/inside.txt:Modified",
"ext-same/part.txt:Modified",
"inner1/inner2/inner/part.txt:Modified",
"main.txt:Modified",
"other-repo/inside.txt:Modified",
];
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert_eq!(rows(&status, &root), expected);
// The Commit window: each path goes to the deepest root holding it.
let all: Vec<PathBuf> = vcs::vcs_roots(&host, "main").await.unwrap().into_iter().map(|r| r.root.0).collect();
let root_of = |p: &Path| all.iter().filter(|r| p.starts_with(r)).max_by_key(|r| r.components().count()).cloned();
for repo in &all {
let stage: Vec<PathBuf> = files.iter().filter(|f| root_of(f).as_ref() == Some(repo)).cloned().collect();
let options = CommitOptions { stage: stage.into_iter().map(Into::into).collect(), ..Default::default() };
vcs::vcs_commit(&host, "main", Some(repo.clone()), "everywhere".into(), options).await.unwrap();
}
assert!(vcs::vcs_status(&host, "main").await.unwrap().is_empty());
for url in [
format!("{}/branches/shared/part.txt", fx.url),
format!("{}/branches/inner/part.txt", fx.url),
format!("{}/lib/inside.txt", fx.another),
format!("{}/lib2/inside.txt", fx.another),
] {
assert_eq!(fx.svn(&fx.base, &["cat", &url]), "edited\n", "{url}");
}
}
/// The project's working copy switched to a branch from a terminal: the branch widget shows
/// the branch once the roots are looked at again. IntelliJ SvnExternalCommitNoticedTest
/// .testExternalRootSwitch.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_root_switched_in_a_terminal_shows_its_new_line() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
fx.svn(&fx.base, &["copy", "-q", "-m", "branch", &format!("{}/trunk", fx.url), &format!("{}/branches/b", fx.url)]);
let (host, project) = open(&fx.base, &root).await;
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("trunk"));
fx.svn(&root, &["switch", "-q", &format!("{}/branches/b", fx.url)]);
project.refresh_repositories();
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("branches/b"));
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
assert_eq!(roots[0].head.as_deref(), Some("branches/b"));
}
+225
Переглянути файл
@@ -2291,3 +2291,228 @@ async fn debugger_breakpoints_update_by_id_and_clear_by_file() {
let removed = h.json("xdebug_remove_breakpoint", json!({"owner": "agent"})).await;
assert_eq!(removed["count"], 2);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn agent_plugins_ipc_installs_for_a_harness_and_projects_native_children() {
ide_ssh::secrets::testing::use_memory_store();
let h = Harness::new();
// Prepare a local marketplace directory outside the workspace with 1 plugin (`cloud-kit`)
let local_mkt = h.tmp.path().join("local-mkt");
let plug_src = local_mkt.join("plugins/cloud-kit");
std::fs::create_dir_all(local_mkt.join(".claude-plugin")).unwrap();
std::fs::create_dir_all(plug_src.join(".claude-plugin")).unwrap();
std::fs::create_dir_all(plug_src.join("skills/cloud-diag")).unwrap();
std::fs::create_dir_all(plug_src.join("rules")).unwrap();
std::fs::write(
local_mkt.join(".claude-plugin/marketplace.json"),
r#"{"name":"local-mkt","owner":{"name":"Test"},"plugins":[{"name":"cloud-kit","source":"./plugins/cloud-kit","description":"Cloud diagnostics"}]}"#,
)
.unwrap();
std::fs::write(
plug_src.join(".claude-plugin/plugin.json"),
r#"{"name":"cloud-kit","version":"1.0.0","description":"Cloud diagnostics","userConfig":{"region":{"type":"string","default":"us-west-2"},"apiKey":{"type":"string","sensitive":true}}}"#,
)
.unwrap();
std::fs::write(
plug_src.join("skills/cloud-diag/SKILL.md"),
"---\nname: cloud-diag\ndescription: Diagnose cloud health\n---\n",
)
.unwrap();
std::fs::write(
plug_src.join("rules/cloud.mdc"),
"---\nglobs: infra/**/*.tf\n---\nTag all cloud resources with owner.\n",
)
.unwrap();
std::fs::write(
plug_src.join(".mcp.json"),
r#"{"mcpServers":{"cloud-mcp":{"command":"node","args":["${CLAUDE_PLUGIN_ROOT}/index.js","--region=${user_config.region}"],"env":{"CLOUD_KEY":"${user_config.apiKey}"}}}}"#,
)
.unwrap();
// 1. Untrusted workspace rejects Workspace-scope plugin installation:
let mkt_str = local_mkt.to_string_lossy().into_owned();
let browsed = ide_host::ops::agent::agent_plugins_browse_marketplace(
&h.host,
"main",
mkt_str.clone(),
ide_core::RequestId(1),
)
.await
.unwrap();
assert_eq!(browsed.candidates.len(), 1);
assert_eq!(browsed.candidates[0].name, "cloud-kit");
let preview = ide_host::ops::agent::agent_plugins_preview(
&h.host,
"main",
browsed.candidates[0].source_spec.clone(),
None,
Some("local-mkt".into()),
ide_core::RequestId(2),
)
.await
.unwrap();
assert!(preview.capabilities.requires_consent);
assert_eq!(preview.marketplace_source.as_deref(), dunce::canonicalize(&local_mkt).unwrap().to_str());
let untrusted_err = ide_host::ops::agent::agent_plugins_install(
&h.host,
"main",
ide_agent::InstallAgentPluginRequest {
source_kind: "local".into(),
owner: None,
repo: None,
git_ref: None,
tree_sha: preview.tree_sha.clone(),
commit_sha: None,
subpath: String::new(),
local_path: preview.local_path.clone(),
marketplace: Some("local-mkt".into()),
marketplace_source: preview.marketplace_source.clone(),
scope: ide_agent::McpScope::Workspace,
harness: "claude".into(),
approve_capabilities: true,
approved_capability_hash: None,
confirm_warnings: true,
overwrite: false,
},
ide_core::RequestId(3),
)
.await;
assert!(untrusted_err.is_err(), "untrusted workspace cannot install workspace plugins");
let untrusted_user_err = ide_host::ops::agent::agent_plugins_install(
&h.host,
"main",
ide_agent::InstallAgentPluginRequest {
source_kind: "local".into(),
owner: None,
repo: None,
git_ref: None,
tree_sha: preview.tree_sha.clone(),
commit_sha: None,
subpath: String::new(),
local_path: preview.local_path.clone(),
marketplace: Some("local-mkt".into()),
marketplace_source: preview.marketplace_source.clone(),
scope: ide_agent::McpScope::User,
harness: "claude".into(),
approve_capabilities: true,
approved_capability_hash: None,
confirm_warnings: true,
overwrite: false,
},
ide_core::RequestId(30),
)
.await;
assert!(untrusted_user_err.is_err(), "local install from an untrusted workspace requires trust");
assert!(
ide_host::ops::agent::agent_plugins_remove_marketplace(
&h.host,
"main",
ide_agent::McpScope::Workspace,
"acme/plugins".into(),
)
.await
.is_err(),
"an untrusted workspace cannot edit workspace marketplaces"
);
// 2. Trust the workspace, install with capability approval, and verify live projection across Skills, MCP, and Memory!
h.trust().await;
let cat = ide_host::ops::agent::agent_plugins_install(
&h.host,
"main",
ide_agent::InstallAgentPluginRequest {
source_kind: "local".into(),
owner: None,
repo: None,
git_ref: None,
tree_sha: preview.tree_sha.clone(),
commit_sha: None,
subpath: String::new(),
local_path: preview.local_path.clone(),
marketplace: Some("local-mkt".into()),
marketplace_source: preview.marketplace_source.clone(),
scope: ide_agent::McpScope::Workspace,
harness: "claude".into(),
approve_capabilities: true,
approved_capability_hash: preview.capabilities.capability_hash.clone(),
confirm_warnings: true,
overwrite: true,
},
ide_core::RequestId(4),
)
.await
.unwrap();
let installed = cat.plugins.iter().find(|s| s.plugin.name == "cloud-kit").expect("cloud-kit in catalog");
assert!(installed.enabled);
assert!(!installed.consent_required);
let plug_id = installed.plugin.id.clone();
let native_settings: Value =
serde_json::from_str(&std::fs::read_to_string(h.root.join(".claude/settings.json")).unwrap()).unwrap();
assert_eq!(native_settings["enabledPlugins"]["cloud-kit@local-mkt"], true);
assert_eq!(native_settings["extraKnownMarketplaces"]["local-mkt"]["source"]["source"], "directory");
assert_eq!(
native_settings["extraKnownMarketplaces"]["local-mkt"]["source"]["path"],
dunce::canonicalize(&local_mkt).unwrap().to_string_lossy().as_ref()
);
// Projected into Skills, MCP Connections, and Memory for inspectability:
let skills = ide_host::ops::agent::agent_skills_list(&h.host, "main").await.unwrap();
assert!(
skills.iter().any(|s| s.skill.name == "cloud-diag" && s.skill.plugin_id.as_deref() == Some(plug_id.as_str()))
);
let mcps = ide_host::ops::agent::agent_mcp_list(&h.host, "main").unwrap();
let cloud_mcp = mcps.iter().find(|m| m.name == "cloud-mcp").expect("projected MCP server");
assert_eq!(cloud_mcp.plugin_id.as_deref(), Some(plug_id.as_str()));
assert!(cloud_mcp.args.iter().any(|a| a == "--region=us-west-2"));
let mems = ide_host::ops::agent::agent_memory_list(&h.host, "main").await.unwrap();
assert!(mems.entries.iter().any(|e| e.entry.plugin_id.as_deref() == Some(plug_id.as_str())));
// 3. Disabling the parent bundle atomically drops its projected skill, MCP server, and rule!
ide_host::ops::agent::agent_plugins_set_enabled(
&h.host,
"main",
plug_id.clone(),
ide_agent::McpScope::Workspace,
false,
false,
None,
)
.await
.unwrap();
assert!(
!ide_host::ops::agent::agent_skills_list(&h.host, "main")
.await
.unwrap()
.iter()
.any(|s| s.skill.name == "cloud-diag")
);
assert!(!ide_host::ops::agent::agent_mcp_list(&h.host, "main").unwrap().iter().any(|m| m.name == "cloud-mcp"));
assert!(
!ide_host::ops::agent::agent_memory_list(&h.host, "main").await.unwrap().entries.iter().any(|e| e
.entry
.plugin_id
.as_deref()
== Some(plug_id.as_str()))
);
// 4. Approving capabilities other than the ones shown is refused.
let stale = ide_host::ops::agent::agent_plugins_set_enabled(
&h.host,
"main",
plug_id.clone(),
ide_agent::McpScope::Workspace,
true,
true,
Some("0000".into()),
)
.await
.unwrap_err();
assert!(stale.message.contains("changed since they were shown"), "{stale:?}");
}
+11 -1
Переглянути файл
@@ -165,6 +165,8 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
std::fs::write(&stale_path, "TOKEN\nexternal\n").unwrap();
let mut search = query("TOKEN", false);
search.scope = SearchScope::Directory { path: scope.into() };
let summary = Arc::new(Mutex::new(None));
let out = summary.clone();
ops::search::replace_in_files(
&host,
"main",
@@ -174,10 +176,18 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() {
false,
vec![],
true,
ops::Channel::new(|_| {}),
ops::Channel::new(move |e| {
if let ReplaceEvent::Done { summary } = e {
*out.lock().unwrap() = Some(summary);
}
}),
)
.await
.unwrap();
let summary = summary.lock().unwrap().take().expect("Done");
// #7273: the stale tab is replaced (counted in `files`) and reported as not saved; the
// user's own unsaved buffer is not.
assert_eq!((summary.files, summary.replacements, summary.failed, summary.unsaved), (4, 4, 0, 1));
let disk = |name: &str| std::fs::read_to_string(root.join(name)).unwrap();
assert_eq!(disk("previewed.txt"), "DONE\n");
assert_eq!(disk("closed.txt"), "DONE\n");
+793
Переглянути файл
@@ -0,0 +1,793 @@
//! Subversion working copies through the shared `vcs_*` commands and the
//! `svn_*` ones, against throwaway `svnadmin` repositories (`file://` URLs).
//! Skipped when `svn` or `svnadmin` is not installed.
mod common;
use ide_core::CancellationToken;
use ide_host::Host;
use ide_host::ops::{svn, vcs};
use ide_vcs::{ChangeKind, CommitOptions, FileStatus, LogQuery, VcsKind};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;
fn which(name: &str) -> Option<PathBuf> {
let names = [name.to_owned(), format!("{name}.exe")];
std::env::split_paths(&std::env::var_os("PATH")?)
.flat_map(|dir| names.iter().map(move |n| dir.join(n)))
.find(|p| p.is_file())
}
/// Whether svn is installed: skipped locally without it, a failure in CI (`CI` set).
fn have_svn() -> bool {
have(&["svn", "svnadmin"])
}
/// Whether `tools` are installed, likewise.
fn have(tools: &[&str]) -> bool {
let missing: Vec<&str> = tools.iter().copied().filter(|t| which(t).is_none()).collect();
if missing.is_empty() {
return true;
}
// Windows CI runners have no Subversion from a trusted source: the tests skip there.
if !cfg!(windows) && std::env::var_os("CI").is_some_and(|v| !v.is_empty() && v != "false") {
panic!("CI must install {missing:?} for the Subversion tests");
}
false
}
/// `path` as a `file://` URL, `file:///C:/…` on Windows.
fn file_url(path: &Path) -> String {
let text = path.to_string_lossy().replace('\\', "/");
if text.starts_with('/') { format!("file://{text}") } else { format!("file:///{text}") }
}
struct Fixture {
_temp: tempfile::TempDir,
base: PathBuf,
url: String,
}
/// A configuration folder of svn's for the test (no password stores, nothing remembered), and
/// global settings of the test's host (`<base>/config`) that point svn at it.
fn private_svn_config(base: &Path) {
let svn = base.join("svn-config");
std::fs::create_dir_all(&svn).unwrap();
std::fs::write(svn.join("config"), "[auth]\npassword-stores =\n").unwrap();
std::fs::write(svn.join("servers"), "[global]\nstore-passwords = no\nstore-auth-creds = no\n").unwrap();
std::fs::create_dir_all(base.join("config")).unwrap();
std::fs::write(
base.join("config/settings.toml"),
format!("[vcs.svn]\nuseCustomConfigDir = true\nconfigDir = {:?}\n", svn.to_string_lossy()),
)
.unwrap();
}
/// A repository with `trunk` and `branches`, and an `svn` that never reads the user's own
/// configuration or stores a login.
fn fixture() -> Option<Fixture> {
if !have_svn() {
return None;
}
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
// The hosts below read svn's configuration and logins from here, never ~/.subversion.
private_svn_config(&base);
assert!(Command::new("svnadmin").arg("create").arg(base.join("repo")).status().unwrap().success());
let fixture = Fixture { url: file_url(&base.join("repo")), base, _temp: temp };
let (trunk, branches) = (format!("{}/trunk", fixture.url), format!("{}/branches", fixture.url));
fixture.svn(&fixture.base, &["mkdir", "-q", "-m", "layout", &trunk, &branches]);
Some(fixture)
}
impl Fixture {
fn svn(&self, cwd: &Path, args: &[&str]) -> String {
let out = Command::new("svn")
.args(args)
.args(["--non-interactive", "--config-dir"])
.arg(self.base.join("svn-config"))
.current_dir(cwd)
.env_remove("LC_ALL")
.env("LC_MESSAGES", "C")
.output()
.unwrap();
assert!(out.status.success(), "svn {args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).into_owned()
}
fn checkout(&self, name: &str) -> PathBuf {
let dest = self.base.join(name);
self.svn(&self.base, &["checkout", "-q", &format!("{}/trunk", self.url), dest.to_str().unwrap()]);
dest
}
}
async fn until(what: &str, done: impl Fn() -> bool) {
for _ in 0..1000 {
if done() {
return;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("timed out waiting for {what}");
}
/// A trusted project at `root`, with its working copy found.
async fn open(base: &Path, root: &Path) -> (Host, Arc<ide_host::Project>) {
let host = Host::new(common::host_config(base)).with_subversion(false);
host.trust.decide(root, true, false).unwrap();
let project = host.open_project("main", root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
(host, project)
}
fn kinds(status: &[FileStatus]) -> Vec<(String, ChangeKind)> {
let mut out: Vec<_> = status.iter().map(|f| (f.rel_path.clone(), f.unstaged.unwrap())).collect();
out.sort_by(|a, b| a.0.cmp(&b.0));
out
}
/// Get from Version Control › Subversion, its progress lines dropped.
async fn checkout(host: &Host, url: String, dest: PathBuf) -> ide_core::IdeResult<()> {
let channel = ide_host::ops::Channel::new(|_: String| {});
svn::svn_checkout(host, "main", ide_core::RequestId::next(), url, dest, channel).await
}
fn commit_options(paths: &[PathBuf]) -> CommitOptions {
CommitOptions { stage: paths.iter().cloned().map(Into::into).collect(), ..Default::default() }
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_through_the_shared_commands() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
let (host, _project) = open(&fx.base, &root).await;
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
assert_eq!((roots.len(), roots[0].kind, roots[0].head.as_deref()), (1, VcsKind::Subversion, Some("trunk")));
// svn reads the test's own configuration, never the user's ~/.subversion.
let svn_settings = _project.svn.as_ref().unwrap().settings();
assert_eq!(svn_settings.config_dir, Some(fx.base.join("svn-config")));
// Add, commit, log.
let a = root.join("a.txt");
std::fs::write(&a, "one\n").unwrap();
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("a.txt".into(), ChangeKind::Untracked)]);
vcs::vcs_stage(&host, "main", vec![a.clone()]).await.unwrap();
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("a.txt".into(), ChangeKind::Added)]);
let rev = vcs::vcs_commit(&host, "main", None, "add a 中文".into(), commit_options(std::slice::from_ref(&a)))
.await
.unwrap();
assert_eq!(rev, "2");
let log = vcs::vcs_log(&host, "main", None, LogQuery { limit: 10, ..Default::default() }).await.unwrap();
assert_eq!(log.iter().map(|c| c.summary.as_str()).collect::<Vec<_>>(), ["add a 中文", "layout"]);
assert_eq!(vcs::vcs_log_details(&host, "main", None, "2".into()).await.unwrap().message, "add a 中文");
// What the post-commit checks read of the new revision (they name the root).
let changes = vcs::vcs_commit_selection_changes(
&host,
"main",
Some(root.clone()),
vec![rev.clone()],
ide_core::RequestId::next(),
)
.await
.unwrap();
assert_eq!(
changes.iter().map(|c| (c.path.as_str(), c.after.as_deref())).collect::<Vec<_>>(),
[("a.txt", Some("2"))]
);
// New Branch is Create Branch or Tag, then a switch; the widget lists trunk and branches.
let outcome = vcs::vcs_checkout(&host, "main", None, "feature".into(), true, None, None).await.unwrap();
assert_eq!(outcome, ide_vcs::CheckoutOutcome::Done);
assert_eq!(vcs::vcs_branch_info(&host, "main", None).await.unwrap().head.as_deref(), Some("branches/feature"));
let branches = vcs::vcs_branches(&host, "main", None).await.unwrap();
let names: Vec<(&str, bool)> = branches.iter().map(|b| (b.name.as_str(), b.current)).collect();
assert_eq!(names, [("trunk", false), ("branches/feature", true)]);
vcs::vcs_checkout(&host, "main", None, "trunk".into(), false, None, None).await.unwrap();
// Update Project with a conflict, resolved in the merge editor (which stages the result).
let other = fx.checkout("other");
std::fs::write(other.join("a.txt"), "theirs\n").unwrap();
fx.svn(&other, &["commit", "-q", "-m", "theirs"]);
std::fs::write(&a, "mine\n").unwrap();
let channel = ide_host::ops::Channel::new(|_: String| {});
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap();
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("a.txt".into(), ChangeKind::Conflicted)]);
let versions = vcs::vcs_conflict_versions(&host, "main", a.clone()).await.unwrap();
assert_eq!((versions.ours.as_deref(), versions.theirs.as_deref()), (Some("mine\n"), Some("theirs\n")));
assert_eq!(versions.base.as_deref(), Some("one\n"));
assert!(versions.merged.unwrap().contains("<<<<<<< .mine"));
std::fs::write(&a, "merged\n").unwrap();
vcs::vcs_stage(&host, "main", vec![a.clone()]).await.unwrap();
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("a.txt".into(), ChangeKind::Modified)]);
vcs::vcs_commit(&host, "main", None, "merged".into(), commit_options(std::slice::from_ref(&a))).await.unwrap();
// VCS › Subversion: properties, locks, repository info, cleanup.
svn::svn_set_property(&host, "main", a.clone(), "review".into(), Some("yes".into())).await.unwrap();
let props = svn::svn_properties(&host, "main", a.clone()).await.unwrap();
assert_eq!(props.iter().map(|p| (p.name.as_str(), p.value.as_str())).collect::<Vec<_>>(), [("review", "yes")]);
svn::svn_lock(&host, "main", vec![a.clone()], "editing".into(), false).await.unwrap();
svn::svn_unlock(&host, "main", vec![a.clone()], false).await.unwrap();
let info = svn::svn_repository_info(&host, "main", None).await.unwrap();
assert!(info.url.ends_with("/repo/trunk"), "{}", info.url);
svn::svn_cleanup(&host, "main", None).await.unwrap();
assert!(svn::svn_version(&host, "main", String::new()).await.unwrap().version.is_some());
let fresh = fx.base.join("fresh");
checkout(&host, format!("{}/trunk", fx.url), fresh.clone()).await.unwrap();
assert_eq!(std::fs::read_to_string(fresh.join("a.txt")).unwrap(), "merged\n");
let _ = CancellationToken::new();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn svn_changelists_through_the_backend_changelist_commands() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
for name in ["a.txt", "b.txt"] {
std::fs::write(root.join(name), "base\n").unwrap();
}
fx.svn(&root, &["add", "-q", "a.txt", "b.txt"]);
fx.svn(&root, &["commit", "-q", "-m", "base"]);
// A nested Git repository keeps the IDE's own lists.
let git = root.join("tool");
std::fs::create_dir(&git).unwrap();
assert!(Command::new("git").arg("init").arg("-q").arg(&git).status().unwrap().success());
std::fs::write(git.join("g.txt"), "g\n").unwrap();
let (host, project) = open(&fx.base, &root).await;
until("the nested Git repository", || !project.repos().is_empty()).await;
let (a, b) = (root.join("a.txt"), root.join("b.txt"));
let lists = || async {
let lists = vcs::vcs_backend_changelists(&host, "main", Some(root.clone())).await.unwrap().unwrap();
lists.into_iter().map(|l| (l.name, l.files.into_iter().map(|f| f.0).collect::<Vec<_>>())).collect::<Vec<_>>()
};
// A list made with the svn CLI shows up.
std::fs::write(&a, "a\n").unwrap();
std::fs::write(&b, "b\n").unwrap();
fx.svn(&root, &["changelist", "-q", "from cli", "a.txt"]);
assert_eq!(lists().await, [("from cli".to_owned(), vec![a.clone()])]);
assert_eq!(vcs::vcs_backend_changelists(&host, "main", Some(git.clone())).await.unwrap(), None);
// A move in the Commit window is `svn changelist`; so are renames and deletions.
let id = vcs::vcs_backend_changelist_create(&host, "main", Some(root.clone()), "ui".into(), String::new())
.await
.unwrap();
vcs::vcs_backend_changelist_move(&host, "main", vec![b.clone()], id.clone()).await.unwrap();
let status = fx.svn(&root, &["status"]);
assert!(status.contains("--- Changelist 'ui':") && status.contains("b.txt"), "{status}");
vcs::vcs_backend_changelist_edit(&host, "main", Some(root.clone()), id, "UI".into(), String::new()).await.unwrap();
assert!(fx.svn(&root, &["status"]).contains("--- Changelist 'UI':"));
let default = ide_vcs::changelists::DEFAULT_ID.to_owned();
vcs::vcs_backend_changelist_move(&host, "main", vec![b.clone()], default).await.unwrap();
assert!(!fx.svn(&root, &["status", "b.txt"]).contains("Changelist"));
vcs::vcs_backend_changelist_delete(&host, "main", Some(root.clone()), "list:from cli".into()).await.unwrap();
assert!(lists().await.is_empty());
// A Git file is not the working copy's to list.
assert!(vcs::vcs_backend_changelist_move(&host, "main", vec![git.join("g.txt")], "list:ui".into()).await.is_err());
// A commit drops the committed file's list.
fx.svn(&root, &["changelist", "-q", "ui", "a.txt"]);
vcs::vcs_commit(&host, "main", Some(root.clone()), "a".into(), commit_options(std::slice::from_ref(&a)))
.await
.unwrap();
assert!(lists().await.is_empty());
}
/// An executable script `name` in `dir` (unix).
#[cfg(unix)]
fn script(dir: &Path, name: &str, text: &str) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let path = dir.join(name);
std::fs::write(&path, text).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
path
}
/// A project nobody trusted runs no svn at all, not even the one its own
/// `.openidea/settings.toml` names; trusting it looks for working copies again, with that svn.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_untrusted_project_runs_no_svn() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
let log = fx.base.join("runs.log");
let real = which("svn").unwrap();
let svn = script(
&fx.base,
"project-svn",
&format!("#!/bin/sh\necho \"$*\" >> '{}'\nexec '{}' \"$@\"\n", log.display(), real.display()),
);
std::fs::create_dir(root.join(".openidea")).unwrap();
std::fs::write(
root.join(".openidea/settings.toml"),
format!("[vcs.svn]\nexecutable = {:?}\n", svn.to_string_lossy()),
)
.unwrap();
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
let project = host.open_project("main", &root).unwrap();
tokio::time::sleep(Duration::from_millis(1500)).await;
assert!(project.backends().is_empty());
assert!(vcs::vcs_roots(&host, "main").await.unwrap().is_empty());
assert!(!log.exists(), "svn ran: {}", std::fs::read_to_string(&log).unwrap_or_default());
// Get from Version Control in its window checks out with the global settings' svn.
let fresh = fx.base.join("fresh");
checkout(&host, format!("{}/trunk", fx.url), fresh.clone()).await.unwrap();
assert!(fresh.join(".svn").is_dir());
assert!(
!log.exists(),
"the project's svn ran for a checkout: {}",
std::fs::read_to_string(&log).unwrap_or_default()
);
// Settings › Subversion › Test with the project's svn is refused; auto-detection works.
assert!(svn::svn_version(&host, "main", svn.to_string_lossy().into_owned()).await.is_err());
assert!(svn::svn_version(&host, "main", String::new()).await.unwrap().version.is_some());
assert!(!log.exists());
host.set_project_trust(&root, true, false).await.unwrap();
until("the working copy", || !project.backends().is_empty()).await;
let roots = vcs::vcs_roots(&host, "main").await.unwrap();
assert_eq!(roots.iter().map(|r| r.kind).collect::<Vec<_>>(), [VcsKind::Subversion]);
assert!(std::fs::read_to_string(&log).unwrap().contains("info"), "the project's own svn runs once trusted");
// Restricted again: nothing of it is reported.
host.set_project_trust(&root, false, false).await.unwrap();
until("no working copy", || project.backends().is_empty()).await;
}
/// A running `svnserve`, ended when dropped (also when a test fails).
#[cfg(unix)]
struct Svnserve(std::process::Child);
#[cfg(unix)]
impl Drop for Svnserve {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
/// `svnserve` on a free port that asks every client for alice / secret.
#[cfg(unix)]
fn serve_with_login(fx: &Fixture) -> (Svnserve, String) {
let repo = fx.base.join("repo");
std::fs::write(
repo.join("conf/svnserve.conf"),
"[general]\nanon-access = none\nauth-access = write\npassword-db = passwd\nrealm = Test\n",
)
.unwrap();
std::fs::write(repo.join("conf/passwd"), "[users]\nalice = secret\n").unwrap();
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let child = Command::new("svnserve")
.args([
"-d",
"--foreground",
"--threads",
"--listen-host",
"127.0.0.1",
"--listen-port",
&port.to_string(),
"-r",
])
.arg(&repo)
.spawn()
.unwrap();
let started = std::time::Instant::now();
while std::net::TcpStream::connect(("127.0.0.1", port)).is_err() {
assert!(started.elapsed() < Duration::from_secs(10), "svnserve did not start");
std::thread::sleep(Duration::from_millis(50));
}
(Svnserve(child), format!("svn://127.0.0.1:{port}"))
}
/// Two projects with their own Settings › Subversion: each runs its own svn, and svn's
/// prompts open in the window of the project whose command asked, answered there.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn two_projects_keep_their_settings_and_prompts() {
let Some(fx) = fixture() else { return };
if !have(&["svnserve"]) {
return;
}
let (_server, url) = serve_with_login(&fx);
let checkout = |name: &str| {
let dest = fx.base.join(name);
fx.svn(
&fx.base,
&[
"checkout",
"-q",
"--username",
"alice",
"--password",
"secret",
"--no-auth-cache",
&format!("{url}/trunk"),
dest.to_str().unwrap(),
],
);
dest
};
let (one, two) = (checkout("one"), checkout("two"));
// Project one runs its svn through a wrapper of its own.
let log = fx.base.join("one.log");
let real = which("svn").unwrap();
let wrapper = script(
&fx.base,
"one-svn",
&format!("#!/bin/sh\necho \"$*\" >> '{}'\nexec '{}' \"$@\"\n", log.display(), real.display()),
);
for (root, settings) in [
(
&one,
format!(
"[vcs.svn]\nexecutable = {:?}\nuseCustomConfigDir = true\nconfigDir = {:?}\n",
wrapper.to_string_lossy(),
fx.base.join("cfg-one").to_string_lossy()
),
),
(
&two,
format!(
"[vcs.svn]\nuseCustomConfigDir = true\nconfigDir = {:?}\n",
fx.base.join("cfg-two").to_string_lossy()
),
),
] {
std::fs::create_dir(root.join(".openidea")).unwrap();
fx.svn(root, &["propset", "-q", "svn:ignore", ".openidea", "."]);
std::fs::write(root.join(".openidea/settings.toml"), settings).unwrap();
}
for name in ["cfg-one", "cfg-two"] {
std::fs::create_dir(fx.base.join(name)).unwrap();
std::fs::write(fx.base.join(name).join("config"), "[auth]\npassword-stores =\n").unwrap();
std::fs::write(fx.base.join(name).join("servers"), "[global]\nstore-passwords = no\nstore-auth-creds = no\n")
.unwrap();
}
// Each window's prompts, answered as a user there would.
type Asked = Arc<parking_lot::Mutex<Vec<(String, String)>>>;
let asked: Asked = Arc::default();
let mut config = common::host_config(&fx.base);
let seen = asked.clone();
config.sink_for = Box::new(move |window: &str| {
let (seen, window) = (seen.clone(), window.to_owned());
Arc::new(move |event: ide_core::IdeEvent| {
if let ide_core::IdeEvent::Askpass { id, prompt, .. } = event {
seen.lock().push((window.clone(), prompt.clone()));
let answer = if prompt.contains("username") { "alice" } else { "secret" };
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(20));
ide_host::svn::answer_prompt(id, Some(answer.into()));
});
}
})
});
let host = Host::new(config).with_subversion(true);
for (window, root) in [("w1", &one), ("w2", &two)] {
host.trust.decide(root, true, false).unwrap();
let project = host.open_project(window, root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
}
let ran_before = std::fs::read_to_string(&log).unwrap_or_default().lines().count();
assert!(ran_before > 0, "project one's svn found its working copy");
let update = |window: &'static str| {
let channel = ide_host::ops::Channel::new(|_: String| {});
let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false };
vcs::vcs_remote(&host, window, None, ide_core::RequestId::next(), op, channel, None)
};
update("w2").await.unwrap();
let prompts = asked.lock().clone();
assert!(!prompts.is_empty() && prompts.iter().all(|(w, _)| w == "w2"), "{prompts:?}");
assert_eq!(
std::fs::read_to_string(&log).unwrap_or_default().lines().count(),
ran_before,
"project two used its own svn"
);
asked.lock().clear();
update("w1").await.unwrap();
let prompts = asked.lock().clone();
assert!(!prompts.is_empty() && prompts.iter().all(|(w, _)| w == "w1"), "{prompts:?}");
assert!(
std::fs::read_to_string(&log).unwrap().lines().any(|l| l.starts_with("update")),
"project one used its wrapper"
);
}
fn git_init(dir: &Path) {
assert!(Command::new("git").arg("init").arg("-q").arg(dir).status().unwrap().success());
}
/// A folder that is both a Git repository and an svn working copy is reported once, as Git;
/// a Git repository inside a working copy keeps its own files.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn git_and_svn_in_one_folder_or_nested() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
git_init(&root.join("tool"));
std::fs::write(root.join("tool/g.txt"), "g\n").unwrap();
std::fs::write(root.join("s.txt"), "s\n").unwrap();
let (host, project) = open(&fx.base, &root).await;
until("the nested Git repository", || !project.repos().is_empty()).await;
let mut roots: Vec<(VcsKind, String)> = vcs::vcs_roots(&host, "main")
.await
.unwrap()
.into_iter()
.map(|r| (r.kind, r.root.0.file_name().unwrap().to_string_lossy().into_owned()))
.collect();
roots.sort_by(|a, b| a.1.cmp(&b.1));
assert_eq!(roots, [(VcsKind::Git, "tool".to_owned()), (VcsKind::Subversion, "wc".to_owned())]);
let status = vcs::vcs_status(&host, "main").await.unwrap();
let mut rows: Vec<String> =
status.iter().map(|f| f.path.0.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/")).collect();
rows.sort();
let rows: Vec<&str> = rows.iter().map(String::as_str).collect();
assert!(rows.contains(&"s.txt") && rows.contains(&"tool/g.txt"), "{rows:?}");
assert!(!rows.contains(&"tool"), "the Git repository is no unversioned folder of the working copy: {rows:?}");
// Both in one folder.
let both = fx.checkout("both");
git_init(&both);
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
host.trust.decide(&both, true, false).unwrap();
let project = host.open_project("both", &both).unwrap();
until("the Git repository", || !project.repos().is_empty()).await;
tokio::time::sleep(Duration::from_millis(500)).await;
let kinds: Vec<VcsKind> = vcs::vcs_roots(&host, "both").await.unwrap().into_iter().map(|r| r.kind).collect();
assert_eq!(kinds, [VcsKind::Git]);
}
/// A working copy inside a Git project's folder is found, as a nested Git repository is.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_inside_a_git_project() {
let Some(fx) = fixture() else { return };
let root = fx.base.join("gitproject");
std::fs::create_dir(&root).unwrap();
git_init(&root);
// Not `vendor/`: dependency folders are skipped, for nested Git repositories too.
fx.svn(&root, &["checkout", "-q", &format!("{}/trunk", fx.url), "parts"]);
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
assert_eq!(project.backends()[0].root(), root.join("parts"));
}
/// The project tree's Delete schedules a file for deletion; its Undo brings the file back and
/// takes the deletion back, keeping the restored content. (Review A4.)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn undo_of_a_delete_takes_the_deletion_back() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
let file = root.join("notes.txt");
std::fs::write(&file, "base\n").unwrap();
std::fs::create_dir(root.join("docs")).unwrap();
std::fs::write(root.join("docs/a.txt"), "a\n").unwrap();
std::fs::write(root.join("docs/b.txt"), "b\n").unwrap();
fx.svn(&root, &["add", "-q", "notes.txt", "docs"]);
fx.svn(&root, &["commit", "-q", "-m", "notes"]);
std::fs::write(&file, "edited before the delete\n").unwrap();
let (host, project) = open(&fx.base, &root).await;
// What Delete does (`delete_recorded`: the same paths, history, removal and backend hook),
// without the system Trash `fs_delete_with_undo` moves things to.
let delete = |path: &Path| {
let paths = ide_workspace::file_ops::deletion_paths(path).unwrap();
let undo = project.history.capture_deletion_undo(&paths, 1 << 20);
if path.is_dir() {
std::fs::remove_dir_all(path).unwrap()
} else {
std::fs::remove_file(path).unwrap()
}
project.with_backend_of(path, |b| b.files_deleted(&paths)).unwrap();
undo
};
let undo = delete(&file);
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("notes.txt".into(), ChangeKind::Deleted)]);
ide_host::ops::fs::fs_undo_delete(&host, "main", undo).await.unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), "edited before the delete\n");
assert_eq!(kinds(&vcs::vcs_status(&host, "main").await.unwrap()), [("notes.txt".into(), ChangeKind::Modified)]);
assert!(fx.svn(&root, &["status", "notes.txt"]).starts_with('M'), "no longer scheduled for deletion");
// A folder: every file in it comes back, none scheduled for deletion.
let undo = delete(&root.join("docs"));
assert!(fx.svn(&root, &["status", "docs"]).lines().all(|l| l.starts_with('D')));
ide_host::ops::fs::fs_undo_delete(&host, "main", undo).await.unwrap();
assert_eq!(std::fs::read_to_string(root.join("docs/b.txt")).unwrap(), "b\n");
assert_eq!(fx.svn(&root, &["status", "docs"]), "", "the folder is as committed");
}
/// In a project with a Git repository and a working copy, a working copy that cannot report
/// its changes does not hide the Git ones, and the window is told once. (Review A13.)
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_working_copy_that_cannot_report_is_told() {
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
git_init(&root.join("tool"));
std::fs::write(root.join("tool/g.txt"), "g\n").unwrap();
// svn as the project has it: fails `status` once told to.
let broken = fx.base.join("broken");
let real = which("svn").unwrap();
let svn = script(
&fx.base,
"flaky-svn",
&format!(
"#!/bin/sh\nif [ -e '{}' ] && [ \"$1\" = status ]; then echo 'svn: E155036: format too old' >&2; exit 1; fi\nexec '{}' \"$@\"\n",
broken.display(),
real.display()
),
);
std::fs::create_dir(root.join(".openidea")).unwrap();
fx.svn(&root, &["propset", "-q", "svn:ignore", ".openidea\ntool", "."]);
std::fs::write(
root.join(".openidea/settings.toml"),
format!("[vcs.svn]\nexecutable = {:?}\n", svn.to_string_lossy()),
)
.unwrap();
let told: Arc<parking_lot::Mutex<Vec<String>>> = Arc::default();
let mut config = common::host_config(&fx.base);
let seen = told.clone();
config.sink_for = Box::new(move |_: &str| {
let seen = seen.clone();
Arc::new(move |event: ide_core::IdeEvent| {
if let ide_core::IdeEvent::Notify { title, .. } = event {
seen.lock().push(title);
}
})
});
let host = Host::new(config).with_subversion(false);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the working copy", || !project.backends().is_empty()).await;
until("the Git repository", || !project.repos().is_empty()).await;
std::fs::write(&broken, "").unwrap();
for _ in 0..3 {
let status = vcs::vcs_status(&host, "main").await.unwrap();
assert!(status.iter().any(|f| f.path.0.ends_with("tool/g.txt")), "{status:?}");
}
let told = told.lock().clone();
assert_eq!(told.iter().filter(|t| t.starts_with("Changes of ")).count(), 1, "{told:?}");
}
/// Get from Version Control › Subversion reports svn's progress line by line, and its Cancel
/// stops a checkout the server holds up. (Review A7, F3.)
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_checkout_reports_progress_and_can_be_cancelled() {
let Some(fx) = fixture() else { return };
if !have(&["svnserve"]) {
return;
}
let seed = fx.checkout("seed");
for name in ["a.txt", "b.txt"] {
std::fs::write(seed.join(name), "x\n").unwrap();
}
fx.svn(&seed, &["add", "-q", "a.txt", "b.txt"]);
fx.svn(&seed, &["commit", "-q", "-m", "files"]);
let host = Host::new(common::host_config(&fx.base)).with_subversion(false);
let lines: Arc<parking_lot::Mutex<Vec<String>>> = Arc::default();
let seen = lines.clone();
let channel = ide_host::ops::Channel::new(move |line: String| seen.lock().push(line));
let dest = fx.base.join("fresh");
svn::svn_checkout(&host, "main", ide_core::RequestId::next(), format!("{}/trunk", fx.url), dest.clone(), channel)
.await
.unwrap();
let lines = lines.lock().clone();
assert!(lines.iter().any(|l| l.ends_with("a.txt")) && lines.iter().any(|l| l.ends_with("b.txt")), "{lines:?}");
// A server that stops answering: Cancel returns at once.
std::fs::write(fx.base.join("repo/conf/svnserve.conf"), "[general]\nanon-access = read\n").unwrap();
let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let server = Svnserve(
Command::new("svnserve")
.args([
"-d",
"--foreground",
"--threads",
"--listen-host",
"127.0.0.1",
"--listen-port",
&port.to_string(),
"-r",
])
.arg(fx.base.join("repo"))
.spawn()
.unwrap(),
);
while std::net::TcpStream::connect(("127.0.0.1", port)).is_err() {
std::thread::sleep(Duration::from_millis(50));
}
let pid = server.0.id().to_string();
assert!(Command::new("kill").args(["-STOP", &pid]).status().unwrap().success());
let request = ide_core::RequestId::next();
let host = Arc::new(host);
let running = {
let host = host.clone();
let channel = ide_host::ops::Channel::new(|_: String| {});
let url = format!("svn://127.0.0.1:{port}/trunk");
let dest = fx.base.join("stuck");
tokio::spawn(async move { svn::svn_checkout(&host, "main", request, url, dest, channel).await })
};
tokio::time::sleep(Duration::from_millis(1500)).await;
let started = std::time::Instant::now();
host.cancel_request(request);
let result = tokio::time::timeout(Duration::from_secs(20), running).await;
let _ = Command::new("kill").args(["-CONT", &pid]).status();
drop(server);
let err = result.expect("cancel stops the checkout").unwrap().unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled, "{err:?}");
assert!(started.elapsed() < Duration::from_secs(10));
}
/// What `smoke/svn.test.ts` checks, through `openidea-server`'s protocol (in-memory, as
/// `tests/rpc.rs` does) so that CI's Rust job runs it: the server finds the working copy of a
/// trusted project and lists, commits and logs it with svn non-interactive. (Review T2.)
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_working_copy_through_the_server_protocol() {
use ide_host::rpc::{self, Dispatcher, Invoke};
use serde_json::{Value, json};
struct Client;
impl ide_jsonrpc::Handler for Client {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, _: Value) -> Result<Value, (i64, String)> {
Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned()))
}
}
let Some(fx) = fixture() else { return };
let root = fx.checkout("wc");
let slot = Arc::new(std::sync::OnceLock::new());
let sink_peer = slot.clone();
// As openidea-server builds its host: svn without prompts.
let host = Arc::new(
Host::new(ide_host::HostConfig {
sink_for: Box::new(move |w| rpc::event_sink(sink_peer.clone(), Some(w.to_owned()))),
..common::host_config(&fx.base)
})
.with_subversion(false),
);
let (client_io, server_io) = tokio::io::duplex(1 << 20);
let (sr, sw) = tokio::io::split(server_io);
tokio::spawn(rpc::serve(host.clone(), Dispatcher::standard(), slot, sr, sw));
let (cr, cw) = tokio::io::split(client_io);
let peer = ide_jsonrpc::Peer::connect(cr, cw, Arc::new(Client));
let _: Value = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
let invoke = |cmd: &str, args: Value| {
let call = Invoke { window: "main".into(), cmd: cmd.into(), args };
let peer = &peer;
async move { peer.request::<_, Value>("invoke", call, None).await.map_err(rpc::error_from_reply) }
};
invoke("open_project", json!({ "path": root })).await.unwrap();
invoke("project_trust_set", json!({ "path": root, "trusted": true, "folder": false })).await.unwrap();
let mut kinds = Value::Null;
for _ in 0..500 {
kinds = invoke("vcs_roots", json!({})).await.unwrap();
if kinds.as_array().is_some_and(|r| !r.is_empty()) {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert_eq!(kinds[0]["kind"], "subversion", "{kinds}");
assert_eq!(invoke("vcs_branch_info", json!({ "repo": null })).await.unwrap()["head"], "trunk");
let notes = root.join("notes.txt");
std::fs::write(&notes, "first\n").unwrap();
let status = invoke("vcs_status", json!({})).await.unwrap();
assert_eq!(status[0]["relPath"], "notes.txt");
assert_eq!(status[0]["unstaged"], "untracked");
let options = json!({ "amend": false, "signOff": false, "author": null, "runHooks": true, "stage": [notes] });
let revision =
invoke("vcs_commit", json!({ "repo": null, "message": "Add notes", "options": options })).await.unwrap();
assert_eq!(revision, "2");
assert_eq!(invoke("vcs_status", json!({})).await.unwrap(), json!([]));
let query = json!({ "branch": null, "path": null, "author": null, "text": null, "skip": 0, "limit": 10 });
let log = invoke("vcs_log", json!({ "repo": null, "query": query })).await.unwrap();
let summaries: Vec<&str> = log.as_array().unwrap().iter().filter_map(|c| c["summary"].as_str()).collect();
assert_eq!(summaries, ["Add notes", "layout"]);
}
+54
Переглянути файл
@@ -417,3 +417,57 @@ async fn a_project_created_with_new_project_is_trusted() {
std::fs::create_dir(&sibling).unwrap();
assert!(!host.trust.status(&sibling).unwrap().trusted);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn attached_container_member_trust_change_emits_event_for_workspace() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let container = base.join("ws");
let member_a = base.join("member-a");
let member_b = base.join("member-b");
for path in [&container, &member_a, &member_b] {
std::fs::create_dir_all(path).unwrap();
}
ide_workspace::workspace::Workspace::save(&container, "WS", vec![member_a.clone(), member_b.clone()], true)
.unwrap();
let events = Arc::new(parking_lot::Mutex::new(Vec::<ide_core::IdeEvent>::new()));
let captured = events.clone();
let mut cfg = common::host_config(&base.join("app"));
cfg.sink_for = Box::new(move |_window| {
let captured = captured.clone();
Arc::new(move |ev| captured.lock().push(ev))
});
let host = Arc::new(Host::new(cfg));
host.trust.decide(&container, true, false).unwrap();
host.trust.decide(&member_a, true, false).unwrap();
host.trust.decide(&member_b, true, false).unwrap();
host.open_project("main", &container).unwrap();
events.lock().clear();
// Revoking trust on an attached-only member keeps the container window trusted, yet still emits
// ProjectTrustChanged for that member so open previews recheck its trust immediately.
host.set_project_trust(&member_b, false, false).await.unwrap();
assert!(
events.lock().iter().any(|ev| matches!(
ev,
ide_core::IdeEvent::ProjectTrustChanged { root, trusted: false } if root.0 == member_b
)),
"expected ProjectTrustChanged(member_b, false), got {:?}",
*events.lock()
);
events.lock().clear();
host.set_project_trust(&member_b, true, false).await.unwrap();
assert!(
events.lock().iter().any(|ev| matches!(
ev,
ide_core::IdeEvent::ProjectTrustChanged { root, trusted: true } if root.0 == member_b
)),
"expected ProjectTrustChanged(member_b, true), got {:?}",
*events.lock()
);
host.shutdown().await;
}
+11
Переглянути файл
@@ -246,10 +246,16 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
call!("vcs_revision_files", "", vcs::vcs_revision_files(host, w, root(), project.head.clone())),
call!("vcs_revision_files", "missing tree", vcs::vcs_revision_files(host, w, root(), project.promised.clone())),
call!("vcs_commit_files", "", vcs::vcs_commit_files(host, w, root(), project.head.clone())),
call!(
"vcs_commit_file_change",
"",
vcs::vcs_commit_file_change(host, w, root(), project.head.clone(), "src/a.txt".into())
),
call!("vcs_commits_changes", "", vcs::vcs_commits_changes(host, w, root(), vec![project.head.clone()])),
call!("vcs_branches", "", vcs::vcs_branches(host, w, root())),
call!("vcs_stashes", "", vcs::vcs_stashes(host, w, root())),
call!("vcs_conflict_versions", "", vcs::vcs_conflict_versions(host, w, file.clone())),
call!("vcs_conflict_details", "", vcs::vcs_conflict_details(host, w, file.clone())),
call!("vcs_diff_text", "", vcs::vcs_diff_text(host, w, file.clone(), false)),
call!("vcs_config_get", "", vcs::vcs_config_get(host, w, root(), "user.name".into())),
call!("vcs_config_get_bool", "", vcs::vcs_config_get_bool(host, w, root(), "log.showSignature".into())),
@@ -325,6 +331,11 @@ async fn restricted_vcs_commands_run_no_program_of_the_repository() {
),
call!("vcs_revision_files", "external", vcs::vcs_revision_files(host, w, log(), external.head.clone())),
call!("vcs_commit_files", "external", vcs::vcs_commit_files(host, w, log(), external.head.clone())),
call!(
"vcs_commit_file_change",
"external",
vcs::vcs_commit_file_change(host, w, log(), external.head.clone(), "src/a.txt".into())
),
(
"vcs_review_apply_commit",
"paused cherry-pick",
+34 -1
Переглянути файл
@@ -329,7 +329,7 @@ async fn a_working_copy_answers_the_shared_vcs_commands() {
vcs::vcs_stage(&host, "main", vec![file.clone()]).await.unwrap();
assert_eq!(*fake.staged.lock(), std::slice::from_ref(&file));
fs::fs_set_writable(&host, "main", file.clone(), true).unwrap();
fs::fs_set_writable(&host, "main", file.clone(), true).await.unwrap();
assert_eq!(*fake.opened.lock(), std::slice::from_ref(&file));
// Rollback rewrites the file: Local History keeps the text from before, between labels.
@@ -605,3 +605,36 @@ async fn a_working_copy_checked_out_in_the_open_project_shows_up_and_goes() {
std::fs::remove_dir_all(&checkout).unwrap();
until("the removed working copy to go", || project.backends().is_empty()).await;
}
/// A folder with a marker that never becomes a working copy (svn missing, an old format) is
/// asked about once, not again on every file saved in it, until its marker changes. (Review N3.)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_folder_that_is_no_working_copy_is_not_asked_about_on_every_save() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir_all(&root).unwrap();
let provider = Arc::new(Provider::default());
let host = host(&base, &provider);
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
until("the opening scan", || provider.answered.load(Ordering::Acquire) > 0).await;
// The fake provider finds working copies by a marker file; a marker folder is none.
let broken = root.join("broken");
std::fs::create_dir_all(broken.join(".fake-vcs")).unwrap();
std::fs::write(broken.join("a.txt"), "a\n").unwrap();
let asked = || provider.asked.load(Ordering::Acquire);
until("the folder to be asked about", || asked() > 1).await;
// Let the scan finish, then save there again and again.
until("the scan's answers", || provider.answered.load(Ordering::Acquire) == asked()).await;
tokio::time::sleep(Duration::from_millis(300)).await;
let after_first = asked();
for i in 0..5 {
std::fs::write(broken.join(format!("b{i}.txt")), "b\n").unwrap();
tokio::time::sleep(Duration::from_millis(150)).await;
}
tokio::time::sleep(Duration::from_millis(500)).await;
assert_eq!(asked(), after_first, "saving in it scans no more");
assert!(project.backends().is_empty());
}
+55 -16
Переглянути файл
@@ -46,6 +46,20 @@ const SNAPSHOT_DELAY: Duration = Duration::from_millis(50);
const SNAPSHOT_EVERY: Duration = Duration::from_secs(10);
#[cfg(test)]
const SNAPSHOT_EVERY: Duration = Duration::ZERO;
/// A refresh waits this many times as long as the last one took, up to [`SNAPSHOT_EVERY_MAX`]: in
/// a project of 160 000 files a write takes seconds and holds the disk, and a build writing into
/// it would otherwise have it rewritten every few seconds for minutes (#7363).
const SNAPSHOT_COST_FACTOR: u32 = 30;
const SNAPSHOT_EVERY_MAX: Duration = Duration::from_secs(300);
/// The shortest gap after a snapshot write that took `cost` (none in tests, as [`SNAPSHOT_EVERY`]).
fn snapshot_gap(cost: Duration) -> Duration {
if cfg!(test) { SNAPSHOT_EVERY } else { gap_after(cost, SNAPSHOT_EVERY) }
}
fn gap_after(cost: Duration, every: Duration) -> Duration {
every.max(cost.saturating_mul(SNAPSHOT_COST_FACTOR).min(SNAPSHOT_EVERY_MAX))
}
/// A subtree scan with fewer files to parse runs without showing "Indexing" (see `scan`).
const QUIET_SCAN_FILES: usize = 200;
pub(crate) const MAX_RECENT: usize = 50;
@@ -87,8 +101,9 @@ pub(crate) struct Shared {
idle: Condvar,
/// Coalesced post-update snapshot refresh.
snapshot_due: Mutex<Option<Instant>>,
/// When the snapshot was last refreshed (see [`SNAPSHOT_EVERY`]).
snapshot_saved: Mutex<Option<Instant>>,
/// When the snapshot was last refreshed, and how long the next one waits after it
/// (see [`snapshot_gap`]).
snapshot_saved: Mutex<Option<(Instant, Duration)>>,
/// Directories whose watcher events still need reconciliation before a
/// refreshed snapshot can be trusted.
pending_dirs: Mutex<HashSet<PathBuf>>,
@@ -683,18 +698,19 @@ impl Shared {
let durable = durable_started.elapsed();
let update_elapsed = update_started.elapsed();
let snapshot_started = Instant::now();
let mut deferred_snapshot = false;
if let Some(store) = &self.store {
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
// process() may already have applied the change and deleted the snapshot;
// a follow-up reconcile scan can have scheduled=0 and still need to write it.
// A full scan writes it at once; a subtree scan within the gap after the last
// write leaves it to the scheduled refresh.
if index_changed || !store.snapshot_exists() {
let d = self.data.read();
let snapshot_started = Instant::now();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
if dirs.is_none() || self.snapshot_may_refresh() {
self.write_snapshot(store, &filter, guard);
} else {
deferred_snapshot = true;
}
tracing::info!("index snapshot: written in {:?}", snapshot_started.elapsed());
*self.snapshot_saved.lock() = Some(Instant::now());
}
if let Err(e) = store.save_recent_file(&recent) {
tracing::warn!("index recent snapshot: {e}");
@@ -702,6 +718,9 @@ impl Shared {
}
let snapshot_elapsed = snapshot_started.elapsed();
*self.snapshot_due.lock() = None;
if deferred_snapshot {
self.schedule_snapshot();
}
if let Some(task) = task {
self.indexing.store(false, Ordering::SeqCst);
self.sink.emit(IdeEvent::Task {
@@ -856,11 +875,27 @@ impl Shared {
}
let mut due = self.snapshot_due.lock();
if due.is_none() {
let soonest = self.snapshot_saved.lock().map(|saved| saved + SNAPSHOT_EVERY);
let soonest = self.snapshot_saved.lock().map(|(saved, gap)| saved + gap);
*due = Some((Instant::now() + SNAPSHOT_DELAY).max(soonest.unwrap_or(Instant::now())));
}
}
/// Whether the gap after the last snapshot write has passed.
fn snapshot_may_refresh(&self) -> bool {
self.snapshot_saved.lock().is_none_or(|(saved, gap)| saved.elapsed() >= gap)
}
fn write_snapshot(&self, store: &Store, filter: &PathFilter, guard: SystemTime) {
let d = self.data.read();
let started = Instant::now();
if let Err(e) = store.save_snapshot(&d, filter, guard) {
tracing::warn!("index snapshot: {e}");
}
let cost = started.elapsed();
tracing::info!("index snapshot: written in {cost:?}");
*self.snapshot_saved.lock() = Some((Instant::now(), snapshot_gap(cost)));
}
/// Reconciles the folders the watcher reported since the last snapshot, then refreshes it.
/// A folder the index already has files below is listed one level deep: its own files, plus
/// any subfolder that appeared (walked whole) or is gone (its files dropped). A folder it
@@ -920,15 +955,9 @@ impl Shared {
return;
}
if let Some(store) = &self.store {
let filter = self.filter();
let guard = SystemTime::now();
let d = self.data.read();
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
tracing::warn!("index snapshot: {e}");
}
self.write_snapshot(store, &self.filter(), SystemTime::now());
}
*self.snapshot_due.lock() = None;
*self.snapshot_saved.lock() = Some(Instant::now());
}
fn persist(&self, puts: &[(String, FileRecord)], deletes: &[String], durable: bool) {
@@ -1704,6 +1733,16 @@ mod metric_tests {
#[cfg(test)]
mod tests {
#[test]
fn a_costly_snapshot_waits_longer_before_the_next() {
use super::{SNAPSHOT_EVERY_MAX, gap_after};
use std::time::Duration;
let every = Duration::from_secs(10);
assert_eq!(gap_after(Duration::from_millis(120), every), every);
assert_eq!(gap_after(Duration::from_secs(4), every), Duration::from_secs(120));
assert_eq!(gap_after(Duration::from_secs(11), every), SNAPSHOT_EVERY_MAX);
}
use crate::data::safe_rel;
#[test]
+12 -6
Переглянути файл
@@ -369,14 +369,20 @@ pub fn resolve_spawn_program(command: &str, env: &[(String, String)]) -> std::pa
if path.components().count() > 1 || path.is_absolute() {
return path.to_path_buf();
}
let search = env
if let Some(found) = env
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
.map(|(_, v)| std::ffi::OsString::from(v))
.or_else(|| ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v))
.or_else(|| ide_core::process::host_var_os("PATH"))
.unwrap_or_default();
ide_core::process::find_executable(command, &search).unwrap_or_else(|| path.to_path_buf())
.and_then(|(_, v)| ide_core::process::find_executable(command, std::ffi::OsStr::new(v)))
{
return found;
}
if let Some(shell_path) = ide_core::process::shell_env().find(|(k, _)| k == "PATH").map(|(_, v)| v)
&& let Some(found) = ide_core::process::find_executable(command, &shell_path)
{
return found;
}
ide_core::process::find_executable(command, &ide_core::tool_path::search_path())
.unwrap_or_else(|| path.to_path_buf())
}
impl Peer {
+2 -2
Переглянути файл
@@ -25,8 +25,8 @@ pub use syntax::{
CSS_CLASS, CSS_ID, CSS_VARIABLE, ClassBases, ConfigurationKey, ExternalFold, ExternalSymbol, ExternalSyntax,
ExternalToken, FileReference, Literal, LiteralKind, MAX_CACHED_TREES, MAX_PARSE_BYTES, ParsedTree, SpellingKind,
SpellingRegion, Syntax, SyntaxCache, SyntaxCacheStats, SyntaxHighlightKind, SyntaxHighlights, TreeError,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_kinds, merge_visibility,
set_external_syntax, shift_pos, shift_range,
VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_impl_traits, merge_kinds,
merge_visibility, set_external_syntax, shift_pos, shift_range,
};
pub use syntax::{
MethodBody, PhpAlignment, PytestFixture, PytestFixtureSlot, PytestFixtureUse, PytestFixtureUseKind, PytestImport,
+2
Переглянути файл
@@ -125,6 +125,8 @@ pub(crate) fn outline(lang: &LanguageId, text: &str) -> Option<Vec<OutlineItem>>
selection_range: lines.range(name_start, name_end),
children: Vec::new(),
visibility: None,
implements: None,
self_type: None,
}));
parents.push(s.parent.map(|p| p as usize).filter(|&p| p < i));
}
+1 -1
Переглянути файл
@@ -34,7 +34,7 @@ use ide_core::{LanguageId, OutlineItem, Pos, Range};
pub use inheritance::ClassBases;
pub use lines::{shift_pos, shift_range};
pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion};
pub use outline::{merge_kinds, merge_visibility};
pub use outline::{merge_impl_traits, merge_kinds, merge_visibility};
pub use php_align::PhpAlignment;
pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts, PythonSuppression};
pub use python_fixtures::{
+55
Переглянути файл
@@ -143,6 +143,10 @@ struct Raw {
visibility: Option<Visibility>,
/// Rust `impl Trait for Type`: members take the trait's visibility.
trait_impl: bool,
/// Rust `impl Trait for Type`: the trait's own name in the header.
implements: Option<ide_core::Range>,
/// Rust `impl [Trait for] Type`: the implementing type's own name in the header.
self_type: Option<ide_core::Range>,
/// Base names of a class definition (empty where the grammar has none).
bases: Vec<String>,
}
@@ -227,6 +231,12 @@ fn collect(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Vec<Built>
detail: detail.map(|d| clean(node_text(&d, text), 80)).filter(|d| !d.is_empty()),
visibility: explicit_visibility(&node, text),
trait_impl,
implements: trait_.map(|t| trait_name(t)).map(|n| idx.range(n.start_byte(), n.end_byte())),
self_type: (kind == ItemKind::Impl)
.then(|| node.child_by_field_name("type"))
.flatten()
.map(|t| trait_name(t))
.map(|n| idx.range(n.start_byte(), n.end_byte())),
// The index needs every class's bases; Python is the grammar that has them.
bases: match kind {
ItemKind::Symbol(SymbolKind::Class) if g.spec.name == "python" => {
@@ -304,6 +314,8 @@ pub(crate) fn outline(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) ->
selection_range: b.raw.sel,
children: b.children.into_iter().map(convert).collect(),
visibility: b.visibility,
implements: b.raw.implements,
self_type: b.raw.self_type,
}
}
collect(g, q, tree, text).into_iter().map(convert).collect()
@@ -398,6 +410,21 @@ pub(crate) fn tags(g: &Grammar, q: &OutlineQuery, tree: &Tree, text: &str) -> Ve
out
}
/// The innermost name of a trait or type path: `fmt::Display<T>` -> `Display`, `&mut Foo<T>` -> `Foo`.
fn trait_name(mut node: Node) -> Node {
loop {
let next = match node.kind() {
"generic_type" | "reference_type" => node.child_by_field_name("type"),
"scoped_type_identifier" | "scoped_identifier" => node.child_by_field_name("name"),
_ => None,
};
match next {
Some(n) => node = n,
None => return node,
}
}
}
/// Visibility spelled out by a modifier child (`visibility_modifier`, `modifiers`,
/// `accessibility_modifier`, ...) of the declaration.
fn explicit_visibility(node: &Node, text: &str) -> Option<Visibility> {
@@ -499,6 +526,34 @@ pub fn merge_visibility(target: &mut [OutlineItem], source: &[OutlineItem]) {
}
}
/// Copies the trait and self type ranges of syntax-tree `impl` items onto language-server
/// items starting at the same identifier (rust-analyzer selects the self type).
pub fn merge_impl_traits(target: &mut [OutlineItem], source: &[OutlineItem]) {
type Ranges = (Option<ide_core::Range>, Option<ide_core::Range>);
fn index(items: &[OutlineItem], out: &mut HashMap<ide_core::Pos, Ranges>) {
for i in items {
if i.implements.is_some() || i.self_type.is_some() {
out.insert(i.selection_range.start, (i.implements, i.self_type));
}
index(&i.children, out);
}
}
fn apply(items: &mut [OutlineItem], map: &HashMap<ide_core::Pos, Ranges>) {
for i in items {
if let Some((implements, self_type)) = map.get(&i.selection_range.start) {
i.implements = i.implements.or(*implements);
i.self_type = i.self_type.or(*self_type);
}
apply(&mut i.children, map);
}
}
let mut map = HashMap::new();
index(source, &mut map);
if !map.is_empty() {
apply(target, &map);
}
}
/// Takes the syntax tree's kind where a server reported a declared type as a value or a type
/// parameter: LSP has no kind for type aliases, so servers fall back to one of those
/// (typescript-language-server: Variable; rust-analyzer, sourcekit-lsp: TypeParameter).
+2
Переглянути файл
@@ -125,6 +125,8 @@ fn nest(heads: &[Heading], i: &mut usize, parent: Option<usize>, text: &str, ind
selection_range: index.range(h.name_start, h.name_end),
children: nest(heads, i, Some(h.level), text, index),
visibility: None,
implements: None,
self_type: None,
});
}
items
+51
Переглянути файл
@@ -2110,3 +2110,54 @@ fn outline_restructuredtext_unicode_crlf_and_cached_edits() {
assert_eq!(updated[0].children[0].selection_range.end, Pos::new(4, 5));
assert_ne!(items, updated);
}
fn rust_impl_traits(src: &str) -> Vec<(String, Option<Range>)> {
syntax().outline(&lang("rust"), src).into_iter().map(|i| (i.name, i.implements)).collect()
}
#[test]
fn outline_rust_impl_names_the_trait_in_the_header() {
let at = |l, a, b| Some(Range::new(Pos::new(l, a), Pos::new(l, b)));
assert_eq!(rust_impl_traits("impl<T> fmt::Display for Foo<T> {}\n")[0].1, at(0, 13, 20));
assert_eq!(rust_impl_traits("impl<T: Clone> Shape<T> for\n Holder<T>\nwhere T: Copy\n{}\n")[0].1, at(0, 15, 20));
assert_eq!(rust_impl_traits("impl Trait<{ N }> for Arr {}\n")[0].1, at(0, 5, 10));
assert_eq!(rust_impl_traits("impl Foo {}\n")[0].1, None);
}
#[test]
fn outline_rust_impl_names_the_self_type_in_the_header() {
let text_of = |src: &str| {
let item = syntax().outline(&lang("rust"), src).remove(0);
let at = |r: Option<Range>| {
r.map(|r| {
src.lines().nth(r.start.line as usize).unwrap()[r.start.col as usize..r.end.col as usize].to_owned()
})
};
(at(item.implements), at(item.self_type))
};
let some = |a: &str, b: &str| (Some(a.to_owned()), Some(b.to_owned()));
assert_eq!(text_of("impl Trait<{ 2 > 1 }> for Holder {}\n"), some("Trait", "Holder"));
let bounds = (0..12).map(|i| format!(" T: B{i},\n")).collect::<String>();
assert_eq!(text_of(&format!("impl<T> Shape<T> for Holder<T>\nwhere\n{bounds}{{}}\n")), some("Shape", "Holder"));
assert_eq!(text_of("impl<'a> Tr for &'a mut Foo<u8> {}\n"), some("Tr", "Foo"));
assert_eq!(text_of("impl a::Foo<u8> {}\n"), (None, Some("Foo".to_owned())));
}
#[test]
fn merge_impl_traits_marks_server_impls_by_their_self_type() {
let src = "trait Shape {}\nimpl<T> Shape for\n Holder<T> {\n fn area(&self) {}\n}\n";
let ts = syntax().outline(&lang("rust"), src);
let ts_impl = ts.iter().find(|i| i.implements.is_some()).unwrap();
let mut server = ts_impl.clone();
server.name = "impl Shape for Holder<T>".into();
server.kind = SymbolKind::Variable;
server.implements = None;
server.self_type = None;
server.selection_range = Range::new(Pos::new(2, 4), Pos::new(2, 13));
let mut lsp = vec![server];
crate::merge_impl_traits(&mut lsp, &ts);
assert_eq!(lsp[0].implements, ts_impl.implements);
assert_eq!(lsp[0].implements.unwrap().start, Pos::new(1, 8));
assert_eq!(lsp[0].self_type, ts_impl.self_type);
assert_eq!(lsp[0].self_type.unwrap().start, Pos::new(2, 4));
}
+4
Переглянути файл
@@ -814,6 +814,8 @@ pub fn document_symbols(conv: &Conv, path: &Path, r: lsp::DocumentSymbolResponse
selection_range: range,
children: Vec::new(),
visibility: None,
implements: None,
self_type: None,
}
})
.collect();
@@ -833,6 +835,8 @@ fn document_symbol(conv: &Conv, path: &Path, s: lsp::DocumentSymbol) -> OutlineI
selection_range: conv.range(path, s.selection_range),
children: s.children.unwrap_or_default().into_iter().map(|c| document_symbol(conv, path, c)).collect(),
visibility: None,
implements: None,
self_type: None,
}
}
+11 -1
Переглянути файл
@@ -67,7 +67,17 @@ fn item(conv: &Conv, path: &Path, node: Node) -> OutlineItem {
),
None => (node.class_name.or(node.label).unwrap_or(node.kind), detail, SymbolKind::Widget, range),
};
OutlineItem { name, detail, kind, range, selection_range, children, visibility: None }
OutlineItem {
name,
detail,
kind,
range,
selection_range,
children,
visibility: None,
implements: None,
self_type: None,
}
}
/// What follows a widget's class, as the Flutter plugin's outline shows it: the variable holding
+19 -2
Переглянути файл
@@ -1874,11 +1874,28 @@ impl LspManager {
positions: &[Pos],
cancel: CancellationToken,
) -> IdeResult<Vec<Vec<Location>>> {
let (method, cap, feature) = goto_method(GotoKind::Implementation);
self.goto_each(GotoKind::Implementation, doc, positions, cancel).await
}
/// The same `kind` of go-to request at each of `positions`, with the answers of
/// [`Self::implementations`] (the ↑ gutter markers of languages without a type hierarchy).
pub async fn goto_each(
&self,
kind: GotoKind,
doc: DocId,
positions: &[Pos],
cancel: CancellationToken,
) -> IdeResult<Vec<Vec<Location>>> {
let (method, cap, feature) = goto_method(kind);
let (snap, targets) = self.doc_targets(doc, feature, |c| c.has(cap)).await?;
let requests = positions.iter().copied().map(|pos| {
let (snap, targets, cancel) = (&snap, &targets, &cancel);
async move { self.goto_in(snap, targets, method, pos, Some(cancel), None).await }
async move {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
self.goto_in(snap, targets, method, pos, Some(cancel), None).await
}
});
let results: Vec<IdeResult<Vec<Location>>> =
futures::stream::iter(requests).buffered(IMPLEMENTATION_CONCURRENCY).collect().await;
+42
Переглянути файл
@@ -4313,6 +4313,48 @@ async fn implementations_per_position() {
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
}
/// Rust's ↑ gutter markers: the trait of an impl block (definition) and the trait method of an impl
/// method (declaration) are asked per position, each with its own request method.
#[tokio::test(flavor = "multi_thread")]
async fn goto_each_asks_the_requested_method_per_position() {
let caps = json!({ "textDocumentSync": 1, "declarationProvider": true });
let h = harness(&[("mock", caps)]);
let (doc, path) = h.open("a.mk", "trait A { fn f(); }\nimpl A for B { fn f() {} }\n");
h.wait_status("mock", ServerStatus::Ready).await;
let s = h.launcher.state("mock");
let uri = uri_of(&path);
*s.responder.lock() = Some(Arc::new(move |_, method, params| {
if method != "textDocument/declaration" {
return None;
}
// The method on line 1 is declared on line 0; nothing else is.
Some(match params["position"]["line"].as_u64() {
Some(1) => {
json!([{ "uri": uri, "range": {"start":{"line":0,"character":14},"end":{"line":0,"character":15}} }])
}
_ => json!([]),
})
}));
let found = h
.mgr
.goto_each(GotoKind::Declaration, doc, &[Pos::new(1, 20), Pos::new(0, 14)], Default::default())
.await
.unwrap();
assert_eq!(found.len(), 2);
assert_eq!(found[0].iter().map(|l| l.range.start.line).collect::<Vec<_>>(), vec![0]);
assert!(found[1].is_empty());
assert_eq!(s.requested("textDocument/declaration").len(), 2);
// A cancelled pass asks nothing more.
let cancelled = CancellationToken::new();
cancelled.cancel();
let err = h.mgr.goto_each(GotoKind::Declaration, doc, &[Pos::new(1, 20)], cancelled).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
assert_eq!(s.requested("textDocument/declaration").len(), 2);
// The server does not advertise definitions: an unavailable server is not "no declarations".
let err = h.mgr.goto_each(GotoKind::Definition, doc, &[Pos::new(1, 20)], Default::default()).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
}
#[tokio::test]
async fn implementation_progress_ends_on_cancel_without_server_end() {
implementation_progress_ends_with_request(false).await;
+20 -2
Переглянути файл
@@ -68,6 +68,16 @@ fn yes() -> bool {
true
}
/// A before launch task as the configuration file writes it (`project-dir` in kebab case).
#[derive(Deserialize)]
struct FileTask {
kind: String,
#[serde(default)]
target: String,
#[serde(default, alias = "projectDir", alias = "project-dir")]
project_dir: Option<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
struct FileConfig {
@@ -100,7 +110,7 @@ struct FileConfig {
#[serde(alias = "outputFile")]
output_file: Option<String>,
#[serde(default, alias = "beforeLaunch")]
before_launch: Vec<BeforeLaunchTask>,
before_launch: Vec<FileTask>,
#[serde(alias = "buildPolicy")]
build_policy: Option<BuildPolicy>,
#[serde(default)]
@@ -177,7 +187,12 @@ fn convert(configs: Vec<FileConfig>, local: bool) -> Vec<RunConfig> {
env_files: c.env_files.into_iter().filter(|f| !f.trim().is_empty()).collect(),
stdin_file: non_empty(c.stdin_file),
output_file: non_empty(c.output_file),
before_launch: c.before_launch.into_iter().filter(|t| !t.kind.is_empty()).collect(),
before_launch: c
.before_launch
.into_iter()
.filter(|t| !t.kind.is_empty())
.map(|t| BeforeLaunchTask { kind: t.kind, target: t.target, project_dir: t.project_dir })
.collect(),
build_policy: c.build_policy,
compound: c.compound,
show_on_stdout: c.show_on_stdout,
@@ -276,6 +291,9 @@ fn to_table(c: &RunConfig) -> Table {
if !task.target.is_empty() {
it.insert("target", task.target.as_str().into());
}
if let Some(dir) = &task.project_dir {
it.insert("project-dir", dir.as_str().into());
}
tasks.push(it);
}
t.insert("before-launch", value(tasks));
+30
Переглянути файл
@@ -1846,4 +1846,34 @@ mod tests {
assert!(configs.iter().all(|c| c.command == "UE/UnrealEditor.exe" && c.cwd.is_none()));
assert!(configs.iter().all(|c| c.debug_adapter.as_deref() == Some("lldb-dap") && c.kind == "unreal"));
}
#[test]
fn dependency_and_build_folders_contribute_no_configurations() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let write = |path: &str, text: &str| {
let path = root.join(path);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
};
let scheme = fs::read_to_string(
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/xcode/App.xcodeproj/xcshareddata/xcschemes/App.xcscheme"),
)
.unwrap();
let package = "// swift-tools-version:5.9\nimport PackageDescription\nlet package = Package(\n name: \"Tool\",\n products: [.executable(name: \"tool\", targets: [\"Tool\"])],\n targets: [.executableTarget(name: \"Tool\")]\n)\n";
write("App.xcodeproj/xcshareddata/xcschemes/App.xcscheme", &scheme);
write("Packages/Tool/Package.swift", package);
write("SourcePackages/checkouts/lib/Rakefile", "task :build do\nend\n");
write("SourcePackages/checkouts/lib/Package.swift", package);
write("Pods/Pods.xcodeproj/xcshareddata/xcschemes/Pod.xcscheme", &scheme);
write("Carthage/Checkouts/lib/Makefile", "all:\n\ttrue\n");
write("DerivedData/App/SourcePackages/checkouts/lib/Package.swift", package);
let mut ids: Vec<_> = detect(root).into_iter().map(|c| c.id).collect();
ids.sort();
assert_eq!(
ids,
["swiftpm:run:tool:Packages/Tool", "xcode:run:App.xcodeproj:App", "xcode:test:App.xcodeproj:App"]
);
}
}
+5 -1
Переглянути файл
@@ -18,7 +18,11 @@ fn reply_file(reply: &Path, name: &str) -> Option<Value> {
}
fn before(config: &mut RunConfig, id: &str) {
config.extras.before_launch.push(BeforeLaunchTask { kind: "build".into(), target: id.into() });
config.extras.before_launch.push(BeforeLaunchTask {
kind: "build".into(),
target: id.into(),
..Default::default()
});
}
#[derive(Default)]
+1 -1
Переглянути файл
@@ -100,7 +100,7 @@ fn detected(project: &str, name: &str, profile: &str, params: BTreeMap<String, S
config.debug_adapter = (!test).then(|| "netcoredbg".into());
config.extras.params = params;
if !test {
config.extras.before_launch.push(crate::BeforeLaunchTask { kind: "dotnetBuild".into(), target: String::new() });
config.extras.before_launch.push(crate::BeforeLaunchTask { kind: "dotnetBuild".into(), ..Default::default() });
}
config
}
+5 -3
Переглянути файл
@@ -19,9 +19,11 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
&["run", "--skip-build", &product],
)
.debug("lldb-dap");
c.extras
.before_launch
.push(BeforeLaunchTask { kind: "command".into(), target: format!("swift build --product {product}") });
c.extras.before_launch.push(BeforeLaunchTask {
kind: "command".into(),
target: format!("swift build --product {product}"),
..Default::default()
});
let exe = if cfg!(windows) { ".exe" } else { "" };
c.extras.params.insert("program".into(), format!(".build/debug/{product}{exe}"));
c.extras.params.insert("product".into(), product);
+5 -1
Переглянути файл
@@ -41,7 +41,11 @@ pub(super) fn detect(dir: &Path, out: &mut Vec<RunConfig>) {
};
let mut c = config(format!("zig:exe:{}", exe.name), exe.name.clone(), "zig-application", &binary, &[])
.debug("codelldb");
c.extras.before_launch.push(BeforeLaunchTask { kind: "run".into(), target: BUILD_ID.into() });
c.extras.before_launch.push(BeforeLaunchTask {
kind: "run".into(),
target: BUILD_ID.into(),
..Default::default()
});
if let Some(source) = exe.source {
c.extras.params.insert("source".into(), source);
}
+8 -2
Переглянути файл
@@ -98,10 +98,16 @@ impl BuildPolicy {
pub struct BeforeLaunchTask {
/// `run` (another configuration id) | `build` (project, or `target` = CMake build id) |
/// `tool` (external tool id) |
/// `command` (a shell command line) | `toolWindow` (tool window id).
/// `command` (a shell command line) | `toolWindow` (tool window id) |
/// `maven` / `gradle` (goals or tasks command line).
pub kind: String,
#[specta(optional)]
#[serde(default)]
pub target: String,
/// Build tool project directory, relative to the opened project when possible.
#[specta(optional)]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub project_dir: Option<String>,
}
fn yes() -> bool {
@@ -231,7 +237,7 @@ impl Default for RunExtras {
}
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum OutputChunk {
Stdout {
+26 -3
Переглянути файл
@@ -112,8 +112,9 @@ enum Line {
/// one). The part of a line after its first non-ASCII byte is held until the line ends or
/// turns out not to be UTF-8; [`Self::release`] decodes a held prompt when no more output comes.
///
/// A read with NUL bytes, which text in the others never has, is UTF-16LE (ASCII characters
/// and line ends in it have them); UTF-16 goes on until one of its lines has ended and a read
/// A read with NUL bytes is UTF-16LE when they are many (every ASCII character in it has one)
/// or one follows a line feed (every line end has one): a stray NUL in a line of other text, such
/// as a binary payload a program logs, leaves the read as it is (#7362). UTF-16 goes on until one of its lines has ended and a read
/// without NUL bytes comes, or at once when a read without NUL bytes is text in UTF-8 again:
/// a program that writes a buffer whose tail is NULs leaves a UTF-16 line that never ends.
pub struct MixedDecoder {
@@ -147,7 +148,7 @@ impl MixedDecoder {
u.decode(bytes, out);
return;
}
if nul {
if nul && looks_utf16(bytes) {
self.end_line(out);
let mut u = Utf16::new();
u.decode(utf16_aligned(bytes), out);
@@ -259,6 +260,13 @@ impl Utf16 {
}
}
/// Whether a read with NUL bytes is UTF-16LE rather than text with a stray NUL: at least one byte
/// in eight is NUL, or a line feed is followed by one.
fn looks_utf16(bytes: &[u8]) -> bool {
let nuls = bytes.iter().filter(|b| **b == 0).count();
nuls * 8 >= bytes.len() || bytes.windows(2).any(|w| w == [b'\n', 0])
}
/// `bytes` from the first byte of a UTF-16LE code unit. NUL bytes are mostly the high bytes of
/// ASCII characters, at odd offsets from it; at even ones, the first byte is the high byte of a
/// character whose low byte came before (and was shown as ASCII).
@@ -468,6 +476,21 @@ mod encoding_tests {
assert!(out.ends_with("after-0: hello 正常输出\nafter-1: hello 正常输出\n"), "{out:?}");
}
/// A Spring Boot log line with ANSI colours whose logged payload ends in a NUL byte stays
/// UTF-8; taken for UTF-16LE, the whole read came out as CJK-looking garbage (#7362).
#[test]
fn a_stray_nul_in_a_utf8_line_is_not_utf16() {
let line = "\x1b[2m2026-12-02 10:55:31.427\x1b[0;39m \x1b[32m INFO\x1b[0;39m 28176 --- [ntContainer#1-5] \
\x1b[36mo.s.modules.data.ConsumerService\x1b[0;39m : Received LC message::: payload \
{\"funcId\":\"Log\",\"seq\":18004,\"messages\":[]}\0\r\n";
let next = "2026-12-02 10:55:31.493 INFO 28176 --- 处理完成 - 耗时: 66ms\r\n";
let mut d = mixed(936);
let mut out = String::new();
d.decode_into(format!("{line}{next}").as_bytes(), &mut out);
out.push_str(&d.finish());
assert_eq!(out, format!("{line}{next}"));
}
/// `水` is `34 6C` in UTF-16LE, which reads as `4l` in UTF-8: a read that short is not
/// taken for text again.
#[test]
Loaded 100 of 517 files, more files were not shown because too many files have changed in this diff. Show more