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

...
Автор SHA1 Повідомлення Дата
Deng Liu 14e13220d7 fix(agents): pick Linux Copilot archive from host dynamic linker
openidea-server on Linux is compiled as a static musl binary (*-unknown-linux-musl) so it runs across distributions, while GitHub Copilot CLI's Linux release archives dynamically link either glibc (copilot-linux-*.tar.gz) or musl (copilot-linuxmusl-*.tar.gz). Checking compile-time cfg!(target_env = "musl") caused remote servers on glibc hosts (such as Ubuntu) to install the musl Copilot binary, which failed to spawn with ENOENT (os error 2) when /lib/ld-musl-*.so.1 was absent.

Inspect the host's runtime ELF dynamic linker paths per architecture instead, using copilot-linuxmusl-* only when /lib/ld-musl-{x86_64,aarch64}.so.1 exists and glibc's loader (/lib64/ld-linux-x86-64.so.2 or /lib/ld-linux-aarch64.so.1) does not.
2026-11-26 23:50:52 -08:00
Deng Liuтаdengliu 7ecccb3b75 feat(agents): preview Copilot subscription models immediately on account switch (#6346)
Switching Sign In > GitHub account for GitHub Copilot used to hide New Tasks models behind an Apply step. A new trusted command, agent_preview_copilot_models, probes Copilot's model catalog for the staged account in memory without touching copilot.toml, models.json or active sessions, so the account and default model can be chosen together and saved with one Apply / OK, and Cancel discards both. Account logins are validated before they reach gh, and applying the account refreshes the stored catalog.

Co-authored-by: dengliu <[email protected]>
2026-11-27 15:45:27 +08:00
Muuтаmuutot 7cbf17b10e feat(vcs): drag the Unversioned Files group and multi-selections onto a changelist (#6299)
In the Commit tool window the Unversioned Files group header is now a drag source whose files are the payload, and a selection of unversioned files drags together. The drag gate in ChangesTree excluded every group row without a changelist id; it now also allows the unversioned group. Dropping reuses addToChangelist, which adds the files to Git and assigns the list; ignored rows stay non-draggable.

Co-authored-by: muutot <[email protected]>
2026-11-27 15:41:46 +08:00
LU XIANGRUIтаwildcatDownstairs cb0d02620d feat(python): run unittest tests without pytest (#6385)
Adds a Python unittest run configuration and Settings > Python > Testing > Default test runner (Autodetect / pytest / unittest). Autodetect keeps pytest for projects that use it; projects whose test modules import unittest and not pytest get a detected python -m unittest configuration, and gutter / context runs of such modules use unittest. Runs go through a stdlib-only reporter that wraps unittest's main() and prints one record per test and subtest, so the tree shows passed, failed, error, skipped, expected failure and unexpected success, subtests as children, captured output, failure locations, import and setUpClass failures; project, folder (discover), module, class and method targets and Rerun Failed (-k) are supported. PyCharm Unittests configurations import as this type. Jump to Source and MCP run / select-tests also handle unittest configurations (file and dotted-name narrowing) instead of falling back to pytest.

Closes #6361

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:40:08 +08:00
LU XIANGRUIтаwildcatDownstairs d6ca43cba4 feat(mdx): add MDX language support through @mdx-js/language-server (#6355)
Adds an mdx language backed by @mdx-js/language-server and moves .mdx out of markdown.toml; the prose keeps Markdown highlighting, outline and folding. The server needs typescript.tsdk, which the launcher fills with the TypeScript vtsls uses (selected version, else vtsls' bundled one, else the one installed with the server, else the project's); an explicit tsdk setting wins, and the managed install adds typescript@6. Places keyed on markdown (live rendering, large-file outline, spell checking as prose, auto-indent, Surround With, colour preview) now include mdx. Formatting follows the Markdown entry of the Prettier / oxfmt language lists so saved lists keep formatting .mdx, and Prettier gets --parser mdx from mdx.toml instead of an extension special case.

Closes #6340

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:33:09 +08:00
l0ng-ai 165d4f7d76 test(plugins): record the plain HTTP request before replying (#6396)
The local server in net_http_setting_grants_reach_plain_http_per_transport recorded a served request only after writing the response, so the client could read it and assert seen.len() == 2 before the second push (1 != 2 on ubuntu CI). The request is now recorded before the reply.
2026-11-27 15:29:03 +08:00
LU XIANGRUIтаwildcatDownstairs 5785ebadd8 feat(typescript): import style code style settings, sent to tsserver (#6342)
Editor > Code Style > JavaScript and TypeScript get an Imports tab: import paths (shortest / relative / non-relative / relative within the project), import path ending (automatic / minimal / index / .js), and glob and regex lists of what not to auto-import. They are stored with the code style, added to the servers' typescript/javascript preferences under both vtsls and typescript-language-server key names, and sent to running servers with didChangeConfiguration; a server's own Language Servers settings still win. The two exclusion lists are always sent (as [] when unset) so clearing one takes effect without a restart. Adds the typescript_import_style language smoke test.

Closes #6072

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:26:29 +08:00
LU XIANGRUIтаwildcatDownstairs 0c67a4eea2 feat(typescript): load the tsserver plugins a project's tsconfig declares (#6353)
tsserver only looks for tsconfig plugins next to the TypeScript it runs from, so with vtsls' bundled TypeScript plugins such as Next.js' were never found. When a tsconfig.json / jsconfig.json under the server root declares compilerOptions.plugins (directly or through extends), vtsls now gets one extra tsserver pluginPaths entry: a folder under the IDE data dir with a small re-exporting package per declared plugin. Plugins the IDE registers globally are left out so they keep resolving to the IDE's copies; missing plugins are logged and skipped; only valid npm package names are used. Changes to tsconfig/jsconfig files trigger a reconfigure, and the probe folder is keyed by the declaring configurations' text, so vtsls restarts instead of stacking plugin instances. Untrusted projects start no language servers, so no project plugin loads there.

Closes #6336

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:23:33 +08:00
LU XIANGRUIтаwildcatDownstairs 5e2deed81e feat(new-project): add Expo, Electron and create-vue generators (#6351)
New Project gains three JavaScript generators that run the official packages through the chosen package manager: Vue (create-vue) with TypeScript, Vue Router, Pinia, Vitest and ESLint options; Expo (React Native) with blank, blank TypeScript and tabs templates; and Electron (Electron Forge) with Vite, Vite + TypeScript and webpack + TypeScript. create-vue gets a kebab-case folder renamed to the project name and a no-op flag when every option is off so it never prompts. Electron always installs, since Forge writes the dependencies by installing them. Static Website moves to the end of the group. Brand icons and en/zh strings added.

Closes #6338

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:21:11 +08:00
LU XIANGRUIтаwildcatDownstairs cae7c05fb1 feat(sass): language server for indented Sass files (#6348)
Indented .sass files now run some-sass-language-server (MIT, installed through npm from the Tools list): completion for variables and mixins across @use, Go to Declaration, hover with SassDoc comments and syntax diagnostics. vscode-css-language-server does not parse the indented syntax; SCSS, CSS and Less stay on it. The server throws on a null somesass configuration, so the definition passes an empty settings table to keep its defaults.

Closes #6339

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:18:58 +08:00
LU XIANGRUIтаwildcatDownstairs be83458161 feat(run): choose the Python interpreter of a run configuration from a list (#6382)
Python and Django test run configurations get an Interpreter dropdown: Project default, each detected interpreter (minus those removed on All Interpreters), or Custom command, which shows the Command field for runners such as uv or poetry. The chosen interpreter's path is stored as the command, so command lines, the backend and .run.xml import are unchanged; existing configurations open with the choice their command stands for, and a missing interpreter is shown as not found. With a run-target project interpreter only Project default and Custom command are offered. RunConfigTypeField gains an optional set(value, params) so a select can stand for other params.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:17:30 +08:00
LU XIANGRUIтаwildcatDownstairs 661124d0d4 fix(run): group pytest parametrized cases under their test (#6384)
Parametrized pytest cases now appear as children of their test, with the combined status on the parent, and Run / Rerun Failed on either runs exactly that node id. The parser split node ids at every :: and failure titles at every dot and only matched ids without spaces, so cases were flat siblings, cases with spaces were missing, and a failing [v1.2 ...] case became a bogus chain under the run root. The [id] part is now kept whole. Tests without a failure line, and the grouping node, now navigate to the test's def.

Closes #6360

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:15:04 +08:00
LU XIANGRUIтаwildcatDownstairs 0dae111b2d feat(navigation): Related Symbol for JS/TS components, templates, styles, tests and stories (#6347)
Navigate > Related Symbol now switches between a JS/TS component and the same-named files beside it: an Angular component, directive, pipe or service and its template, styles and spec (also following templateUrl / styleUrl / styleUrls), and Button.tsx with Button.module.css, Button.test.tsx and Button.stories.tsx. Targets are grouped as Source File, Template, Styles, Test and Stories. It reads only the folder listing and the open file's text; two same-named sources (Button.ts and a compiled Button.js) are not offered for each other.

Closes #6337

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 15:13:19 +08:00
Mansur Akhmadiтаmansur-akhmadi 61d269045b feat(vcs): Compare File with Editor action (#6364)
Adds Compare File with Editor: the file selected in the Project view (or passed as the argument) is diffed against the active editor's file, opened at the editor's caret line, with swappable sides. The Project view context menu offers it right after Compare With… for a single file other than the editor's; virtual documents, folders, multiple files and the editor's own file get an explanatory notification instead. It is unbound in the presets and mapped from imported keymaps via CompareFileWithEditor.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:12:02 +08:00
Mansur Akhmadiтаmansur-akhmadi 266d85fa1a feat(run): Search with Google in the console context menu (#6358)
Adds Search with Google to the Run console context menu: it opens a web search for the trimmed, URL-encoded selected output in the browser, and is disabled when nothing (or only whitespace) is selected.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:08:59 +08:00
Mansur Akhmadiтаmansur-akhmadi f964d79e10 feat(terminal): Close All Tabs in the session tab menu (#6344)
Adds Close All Tabs to the terminal tab context menu. Close Tab / Close Other Tabs / Close All Tabs now share requestCloseTabs, which closes the tabs in order, confirms each running command like Close Tab, stops at a tab the user keeps open, and skips tabs whose shell already exited.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:07:43 +08:00
Mansur Akhmadiтаmansur-akhmadi 4a3eacff62 feat(code-insight): Export to Text File in the Find Usages tool window (#6292)
Adds Export to Text File… to the Find Usages toolbar and Find Action. It writes the active search as shown (access filter applied, excluded usages left out) as an indented text report to a file picked in the save dialog, and reports write errors as a notification.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:06:50 +08:00
Mansur Akhmadiтаmansur-akhmadi aebc2fe02d feat(templates): Save as Live Template from the editor selection (#6305)
Adds Tools > Save as Live Template…: with a selection in a text editor it adds a User live template whose text is the selection (dedented like $SELECTION$, with $ escaped as $$), in the file's language, and opens Settings > Live Templates on it. The page now accepts a focus target and selects that template.

The action is unbound in the presets and is reachable from imported keymaps and IdeaVim via SaveAsTemplate.

Closes #6304

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:05:34 +08:00
Mansur Akhmadiтаmansur-akhmadi 9b63aa9526 feat(editor): Increase / Decrease Font Size in All Editors actions (#6350)
Adds Increase / Decrease Font Size in All Editors actions that change the editor font size setting for every open editor, next to the existing single-editor zoom actions.

The default keymaps bind Alt+Shift+. / Alt+Shift+, (Ctrl+Shift+. / Ctrl+Shift+, on macOS) to the All Editors actions; the single-editor actions stay available from Find Action and can be bound in Keymap settings. Docs and keymap tests updated.

Closes #6349

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 15:00:39 +08:00
Mansur Akhmadiтаmansur-akhmadi df07073886 feat(editor): Delete Duplicate Lines action (#6323)
IDEA's Edit > Delete Duplicate Lines (EditorUniqueLines): in the selected lines, or the whole file without a selection, keeps the first of each repeated line and deletes the later ones.

Closes #6322

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:55:06 +08:00
Mansur Akhmadiтаmansur-akhmadi 3433ee951b feat(editor): Scroll Left / Scroll Right actions (#6303)
IDEA's Scroll Left / Scroll Right: move the editor viewport by one column without moving the caret, counted in whole columns. Unbound by default, as in IDEA.

Closes #6302

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:53:36 +08:00
Mansur Akhmadiтаmansur-akhmadi 8f5b281486 feat(editor): Kill to Word Start / Kill to Word End actions (#6294)
IDEA's Kill to Word Start / Kill to Word End: cut from each caret back to the previous word start or on to the next word end, across blank lines, by hump with CamelHumps on. Repeated kills at the same caret collect into one clipboard entry like Cut up to Line End, backward kills before the collected text. Unbound by default, as in IDEA's default keymaps.

Closes #6293

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:52:04 +08:00
Mansur Akhmadiтаmansur-akhmadi 43aee8058c feat(editor): Toggle Sticky Selection action (#6325)
IDEA's Toggle Sticky Selection: while on, every caret move (keys, IDE actions, clicks, Find) extends the selection from its anchor. Turning it off, Esc, an edit of the document or a copy end it and remove the selection, as in IDEA. Swap Selection Boundaries keeps it going from the other end. No default shortcut, as in IDEA's default keymaps.

Closes #6324

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 14:49:18 +08:00
audichuang 4016c3c905 fix(vcs): show the merge result in a background tab of the file (#6378)
After Apply in the merge editor, a tab of the file behind the merge editor kept showing the conflict markers although disk and index held the result. Without an editor view, writeFileText edited a transient doc_open/doc_edit/doc_save reference; doc_edit is not echoed to the document's other references, so the background tab never got the change. The write now goes through the file's document (attachDocument), so every tab of the file follows; the file is still saved as is. Get from Revision in the log uses the same helper.

Closes #5567

Co-authored-by: audichuang <[email protected]>
2026-11-27 14:40:00 +08:00
audichuang e6cb7df653 fix(run): count every test when JUnit runs them in parallel (#6377)
With JUnit's parallel concurrent mode, OpenIDEA's JUnit runner could report fewer tests than finished: the listener is called from several worker threads, Reporter's counters were plain ints incremented without a lock and PlatformRunner's start times a HashMap. The counting methods are synchronized now and the start times a ConcurrentHashMap. build.py --test runs a 4000-invocation parallel sample and expects the exact summary.

Closes #6334

Co-authored-by: audichuang <[email protected]>
2026-11-27 14:37:21 +08:00
Muuтаmuutot 2a26c82357 fix(vcs): the Git Log branch filter follows a branch rename (#6341)
Renaming a branch left the Git Log filtering the old name: the Branch chip kept it and the query failed with unknown revision. renameBranchInLogFilters now rewrites the shown view's branch filter, parked log views, the per-repository remembered choice and Log: <branch> tab targets, and reloads the log when the shown view filtered by the old name. A batch rename follows only when every repository was renamed.

Co-authored-by: muutot <[email protected]>
2026-11-27 14:27:05 +08:00
eclix-del 66f0bce92f fix(editor): keep a re-dropped file saveable (#6328)
A file from outside the project, dropped into the editor again, stopped saving after the first save, silently. Three paths led there:
- onLocal set the dirty flag after updating the touched ranges, so an exception there left the buffer clean and every save a no-op. Dirty is now set first, and a failure to map the ranges falls back to treating the whole document as touched.
- A reused model kept the touched ranges of the previous tab; they are cleared when a clean model is reacquired.
- A file opened under its native Windows spelling (E:\code\a.sql) and the editor's E:/code/a.sql got two models sharing one backend document, and dirty/patch/language events reached only one. Events now go to every model of the document, and dropped paths are normalized with ipcPath (extended-length paths too).
save() also writes when the dirty flag lags but edits are still pending.

Refs #5528

Co-authored-by: eclix-del <[email protected]>
2026-11-27 14:24:00 +08:00
Mollo-i dfbd13e2af fix(run): keep console soft wrap across run tabs (#6331)
The Run/Services and Debug console toolbars kept soft wrap in component state, so switching run tabs reset it to the Settings default. The toolbar toggle now writes Settings > Console > Use soft wraps in console (console.softWrap) and every console reads it, so one toggle applies to all consoles and survives a restart. The e2e settings-write stub moves into the shared fixtures.

Co-authored-by: Greenker <[email protected]>
2026-11-27 14:19:24 +08:00
aconeshanaтаaconeshana 944b57dead fix(run): open a stack frame's file from the run module's scope (#6366)
Clicking a stack frame in the Run console opened another module's copy of a class when several modules of a multi-module Maven build declare the same package and class: the lookup went by file name, and the package check cannot tell same-package copies apart.

Candidates are now narrowed to the run configuration's module and the modules it depends on (transitively, all scopes) before the name and package checks. The module reaches the Run console links, the test tree's Jump to Source and the Debug console links. Without a Maven model, for an unlisted module, or when the scope matches no candidate, the lookup behaves as before.

Closes #6313

Co-authored-by: aconeshana <[email protected]>
2026-11-27 14:16:59 +08:00
LU XIANGRUIтаwildcatDownstairs 5bcb37492f fix(run): print each line of a JUnit test's output once (#6333)
With Run tests using: OpenIDEA, every line a JUnit Platform test printed showed twice: the runner enabled JUnit's output capture, whose StreamInterceptor also writes each line to the original System.out, and then reported the captured text again as testStdOut.

The runner now captures System.out / System.err per thread itself, as Junit4Runner does: a thread's lines while it runs a test or a class's set-up go only into that test's or class's testStdOut / testStdErr, other output passes through, and JUnit's capture is turned off explicitly. The console now shows testStdErr as stderr, and "Show console when a message is printed to stderr" fires for it (also for Junit4Runner and the Gradle test init script).

Fixes #6332

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 14:14:49 +08:00
Yann d5bde9af67 fix(agents): preserve Codex failure diagnostics (#6354)
Codex turns blocked under cyberPolicy were turned into a successful ACP refusal, dropping the server's explanation and showing only "The agent declined to continue." They now fail like other turns, and a failed turn's message carries Codex's additional details, its diagnostic code and any reported HTTP status. Authentication and usage-limit classification are unchanged.

Co-authored-by: YannABC <[email protected]>
2026-11-27 14:13:03 +08:00
Deng Liuтаdengliu 5b3e2b7a3d fix(editor): skip whitespace-only selections in selection match highlighting (#6318)
Selecting indentation (spaces or tabs) flooded the editor with occurrence highlights, because CodeMirror's highlightSelectionMatches matches whitespace-only selections verbatim. heavyExtension now uses a selectionMatches view plugin with the same bounds (min length 2, max length 200, at most 500 visible matches) that skips whitespace-only selections, as the terminal and Markdown preview already do.

Co-authored-by: dengliu <[email protected]>
2026-11-27 14:11:22 +08:00
薛纪克таxuejike dbb6fa51c3 fix(database): start new query consoles in the selected schema (#6375)
New Query Console and Query Console opened from a schema, folder or table node started in the connection's default schema: the commands passed only the node's data source id, and bindConsole clears the console schema when the binding changes. The commands now pass the invoking node's schema (else the selected tree node's on the same connection) and the console switches to it after binding.

Closes #6329

Co-authored-by: xuejike <[email protected]>
2026-11-27 14:09:04 +08:00
l0ng-ai 3d1769ef00 chore(plugins): rebuild the net-setting test fixture from its sources 2026-11-27 12:28:25 +08:00
l0ng-ai c966429f92 chore: v0.1.54 2026-11-27 11:40:15 +08:00
l0ng-ai dfcc05dd41 fix(vcs): keep the combined diff's stuck file header flush with the top (#6326)
A stuck file header left a gap the size of the list's top padding and showed
the diff scrolling by through it and outside its rounded corners. It now sticks
past the padding, draws its own top border, and covers the area behind it.
2026-11-27 10:53:31 +08:00
Fabio Nunes d41feefc07 feat(editor): remember the encoding chosen for a file or folder (#5510)
The encoding chosen for a file from the status bar (Reload or Convert) is remembered for that file across reopening and restarts, and a folder can have an encoding its files inherit (project settings). A converted file keeps its new encoding once saved. Precedence: a file's own choice, then the .editorconfig charset, then the folder mapping.

Co-authored-by: LittleGuava <[email protected]>
2026-11-27 10:43:43 +08:00
l0ng-ai f0fe910017 fix(agents): use a declared radius token for the sign-in terminal (#6320) 2026-11-27 10:37:24 +08:00
l0ng-ai b932220b41 fix(plugins): color Java annotations from a theme plugin's annotation key (#6317)
Java annotations are drawn with --syn-decorator, but a theme plugin's
ANNOTATION_NAME_ATTRIBUTES only set --syn-annotation, so they kept the
DEFAULT_METADATA color. The annotation key now sets both, and
DEFAULT_METADATA applies only when neither the file nor its bundled parent
(Default, Darcula) defines the annotation key, as for imported schemes.
2026-11-27 10:35:42 +08:00
l0ng-ai bcad8f61cb fix(debugger): don't sync the closed project's breakpoint files (#6315)
Closing a project reloads the breakpoints with no project, which rescheduled
every file the project had breakpoints in with an empty list. Each sync then
failed in the backend (no project in the window) and logged
debugSetBreakpoints failed. Per-file syncs now wait for a project as well.
2026-11-27 10:35:32 +08:00
l0ng-ai 2cdcb888cf fix(viewers): update the SVG preview's size when the typed source changes it (#6314)
WebKit keeps the natural size of an <img> that has a CSS size when its src
changes to another SVG, so editing the root's width or height left the live
preview and its dimension readout at the old size. The preview now measures
each typed source with a detached image.
2026-11-27 10:35:22 +08:00
l0ng-ai 9ed0fd9fa7 fix(ci): format the API 1.18 run output test and fit the commit chooser's macOS Close button (#6319)
The Plugins job's rustfmt check failed on `sdk/rust/openidea-plugin/tests/api18_run_output_mode.rs`. Since dialogs on macOS show as sheets (#6208), a dialog without footer buttons gets a Close button and a taller title, so the Git Log commit chooser is taller than `e2e/gitLogCommitChooser.spec.ts` allowed.
2026-11-27 10:35:14 +08:00
Vladislav Kuzmin fe76dc4573 test(viewers): select SVG source with the fixture keymap (#6297)
The browser fixture uses macOS shortcuts on every host. Playwright resolves `ControlOrMeta+A` to Ctrl+A on Linux, so the test inserts the new SVG without replacing the existing source. Use `Meta+A` to match the fixture's keymap.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:55 +08:00
Vladislav Kuzmin 45a75f782a fix(ci): scope the managed gh test helper to Unix (#6287)
Windows Clippy fails because the managed GitHub CLI accessor is compiled on every test target and its only caller is Unix-only. Give the accessor the same test and Unix conditions as its caller.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:47 +08:00
Vladislav Kuzmin bd1fd011e4 test(editor): include File Color in tab menu groups (#6280)
The editor tab menu gained a File Color group in #6105. The layout test still expected Copy Path/Reference in that position and compared four groups, so it failed before it could check splitting and pinning. Include File Color and compare all five original and new groups in order.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:38 +08:00
Vladislav Kuzmin b44015b2ce fix(frontend): remove unused VCS and Markdown exports (#6279)
Remove the unused VCS date wrapper and the Markdown layout-mode alias left behind after their callers moved to the shared formatting and viewer code. The VCS model also drops its unused import. The author-hint comment now describes the shared formatting behavior without pointing to a removed function.

Co-authored-by: principalwater <[email protected]>
2026-11-27 10:34:30 +08:00
l0ng-ai 0cce0a9840 fix(problems): start TypeScript Project Errors when the option is turned on (#6316)
The desktop app's settings_set has its own copy of the side effects of a
changed setting, and the tsc --watch watcher was only started from the host
command's copy, so turning on Problems › TypeScript Project Errors did
nothing until the project was reopened. Both commands now share
apply_setting, which also applies the terminal frame rate on desktop.
2026-11-27 10:28:13 +08:00
l0ng-ai db8224f74e perf(agents): stop a running task's Changes tab from reloading every diff on each update (#6298)
While a task runs, it is published again with every token count. The Changes tab rebuilt its
diff items from the whole task object, so each update re-read the base text of every changed
file over IPC, hashed all of them, and handed the view a new array that rendered every mounted
diff block and every row of the file tree again. The diffs now depend only on the task fields
they use (id, base, isolation, branch, cwd), an unchanged list keeps its array, and the file
tree is memoized. The all-in-one diff also works out each diff's key once per list instead of
hashing every file's text on every scroll frame (autosave off).
2026-11-27 10:03:35 +08:00
Fabio Nunes b075f5de2a feat(editorconfig): apply charset to existing files and accept the listed encodings (#5509)
An .editorconfig charset now applies to existing files when they are opened and decoded, not only to new ones, and every charset EditorConfig lists is accepted (latin1, utf-8, utf-8-bom, utf-16be, utf-16le). Find in Files decodes closed files with that charset too, so a Latin-1 file is found by its accented text.

Co-authored-by: LittleGuava <[email protected]>
2026-11-27 09:51:49 +08:00
Nguyen Thinh 3240164840 feat(database): warn before running a statement that changes a whole table (#1496)
Before the SQL console runs a statement that changes or clears a whole table (a DELETE or UPDATE without WHERE, and similar cases), it shows a warning banner with Execute, Execute and Suppress (no more warnings in this console) and close; nothing runs until the user chooses. The statement also gets a squiggle, a gutter icon and a hover. The check runs on the text after parameter substitution, and works with the console's streaming execution.

Co-authored-by: kidp2h <[email protected]>
2026-11-27 09:39:21 +08:00
l0ng-ai f70f362a3d feat(ui): open New Project, Get from VCS and Remote Development in their own windows (#6208)
* feat(ui): open New Project, Get from VCS and Remote Development in their own windows

Each dialog gets a native window over its project window: a full-height
sidebar under the traffic lights, the title heading the content and the
buttons in its corner. The windows hand their result back to the project
window, which opens the created or cloned project or makes the remote
connection and reports its progress. Remote windows and the browser build
keep the dialogs in the page.

* feat(ui): show dialogs in the page as sheets without window buttons on macOS

The title heads the content instead of a title bar with drawn traffic
lights; Esc and Cancel close the dialog, and the title dims while the
window is inactive.

* fix(ui): give a macOS dialog without footer buttons a Close button

A sheet has no window buttons, so a dialog with neither buttons nor a
footer could only be closed with Esc. The Extract Interface members
table may shrink to two rows so the dialog still fits a short window
under the taller sheet title.
2026-11-27 08:59:33 +08:00
l0ng-ai 806bb4c78d ci(homebrew): push the cask to the tap with a deploy key (#6205) 2026-11-27 08:59:26 +08:00
Mansur Akhmadiтаmansur-akhmadi 57094bc285 feat(run): Track Running Test in Test Runner Options (#6285)
Test Runner Options gets Track Running Test (also in Find Action as run.toggleTrackRunningTest), remembered with the other test tree options and on by default. While a run is in progress, each test that starts is selected, its collapsed suites opened and its output shown; when several start together the last in tree order wins. A test finishing doesn't move the selection, so a test picked by hand stays selected until the next one starts, and focus doesn't move.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 08:18:37 +08:00
Deng Liuтаdengliu a5e0c41663 feat(github): add project-scoped GitHub CLI account selection (#6277)
A project can pin a GitHub CLI account in vcs.github.account (.openidea/settings.toml, a login, never a token), chosen in Settings > Version Control > GitHub or from the Pull Requests tool window header. With an account chosen, its token is resolved through gh and set as GH_TOKEN in the project environment for the project root and its agent worktrees; a .envrc GH_TOKEN still wins, and the token is cleared when the project closes or loses trust. Copilot keeps billing to its own account through COPILOT_GITHUB_TOKEN.

Automatic (the default) sets no GH_TOKEN and makes no GitHub calls on project open. When the settings page or the Pull Requests window asks for the status with several gh accounts signed in, the project's GitHub remote is probed to suggest a non-active account with access ("Use <login> for this project").

New commands: gh_project_account_status, gh_set_project_account. The gh account listing is shared with the Copilot account selector.

Co-authored-by: dengliu <[email protected]>
2026-11-27 08:16:10 +08:00
audichuang 77071238a0 fix(gradle): keep absolute owner for synced builds outside the project (#6260)
After a Gradle sync, an included build outside the project root (includeBuild('../svc')) was missing from Find in Files > Module: with_gradle_roots stamped plain Gradle as its owner, which the UI reads as the project root. Such builds now keep their absolute owner (<dir>/Gradle), which projectModules, the Module scope and changeModules already treat as an absolute module.

An ancestor of the opened folder (opening composite/app while Gradle reports composite) and a filesystem or drive root keep plain Gradle, so they can't claim every in-project file. Reported project dirs are canonicalized like the opened root, and moduleOf also recognises drive-letter module paths.

Co-authored-by: audichuang <[email protected]>
2026-11-27 07:56:28 +08:00
Deng Liuтаdengliu 64097d3c20 feat(agents): unify Copilot GitHub account selector and gate models on auth (#6269)
Copilot's Sign In notice and the free-text Launch > GitHub account field become one Sign In section: a GitHub account selector listing Copilot CLI's own default login (with its status from auth.getStatus) and the github.com accounts signed in to GitHub CLI (gh auth status, ignoring ambient token variables), plus Sign In... and an in-IDE Add account... that runs gh auth login in the sign-in dialog and selects the new account.

New Tasks model controls wait until the selected account is signed in and applied, and load that account's model catalog instead of showing a cached one from another account or subscription; changing the account evicts the idle Copilot catalog probe.

New commands: agent_copilot_auth_status, agent_gh_login_spawn.

Co-authored-by: dengliu <[email protected]>
2026-11-27 07:34:47 +08:00
Deng Liuтаdengliu cf0e57e5df fix(agents): advance history batching past long folded process runs (#6278)
A session's history paints from the end in batches of ENTRY_BATCH, and the first painted entry moves back over a leading run of tool calls so a folded process row is never split. Since all consecutive tool calls fold into one run, a run longer than a batch made the next batch end inside the same run, so start never moved: the background batches and loading earlier messages at the top both stalled, and earlier turns never appeared (also after a hidden tab trimmed its history).

The next batch now steps past what is actually painted. A conversation scrolled away from the end also keeps loading while its rows don't fill the viewport or it sits near the top.

Co-authored-by: dengliu <[email protected]>
2026-11-27 07:20:55 +08:00
l0ng-ai 703cf23296 fix(workspace): don't let refactoring undo overwrite an external write under an unsaved buffer (#6281)
Fingerprints hash an unsaved buffer in place of its file, so a file another
program wrote after a refactoring went unnoticed while its buffer had unsaved
changes, and undo (or redo) wrote the snapshot over it.

Each document now counts the disk conflicts it has seen (external writes while
the buffer had unsaved changes). The undo record keeps the counts as of the
refactoring; undo and redo first check unsaved buffers' files for a write the
watcher hasn't reported yet, then refuse when a count moved. The IDE's own
saves don't count, so saving and undoing typing before undoing the refactoring
still works, and a conflict from before the refactoring doesn't block it.

Fixes #6264
2026-11-27 07:16:02 +08:00
Deng Liuтаdengliu a88073d6fb fix(macos): disable Apple Intelligence Writing Tools in WKWebView (#6274)
macOS 15+ shows the Apple Intelligence Writing Tools affordance over selections in Markdown previews, Quick Documentation and editors. Every webview window now gets a WKWebViewConfiguration with writingToolsBehavior = none (when the selector exists), merged with the debug-only user-font override.

Windows built off the main thread (secondary project windows, auxiliary windows such as Settings) create the configuration on the AppKit main thread via run_on_main_thread and fall back to the default builder if that fails or times out, instead of panicking.

Tests: writing tools disabled on the configuration; off-main-thread creation falls back without panicking and builds the configuration through the main-thread dispatch.

Co-authored-by: dengliu <[email protected]>
2026-11-27 07:12:30 +08:00
Deng Liuтаdengliu 4b5745c1b6 feat(agents): sign in to coding agents in an IDE terminal (#6263)
Agents can be signed in from the IDE: Sign In... in Settings > Agents > Agent
Setup and on a sign-in error in the chat opens a dialog running the agent's own
login flow (copilot login, codex login, claude, an ACP terminal-auth method) in
an IDE-managed PTY with the real program and arguments, no shell quoting. The
Settings window's boot provides the embedded terminal, so the dialog works there
without importing the terminal feature. Sign-in clears a failed model-catalog
cooldown and refreshes the agent's models. Copilot's login runs with ambient
GitHub token variables cleared, and copied login hints quote paths with spaces.
A test pins that every built-in login hint yields the arguments Sign In runs.

Co-authored-by: dengliu <[email protected]>
2026-11-27 06:36:26 +08:00
Mansur Akhmadiтаmansur-akhmadi 4667c81e6b feat(project-view): Show Scratches and Consoles option (#6273)
Adds the Project view's Show Scratches and Consoles option (Options >
Appearance, and a Find Action toggle), on by default. Off, the Project / Unity /
Unreal panes leave out the Scratches and Consoles root and scratch paths outside
the project; the Scratches and Consoles pane and the path-based panes are
unchanged. Select In > Project View then switches to the Scratches and Consoles
pane for a scratch the Project pane hides.

Closes #6272

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 06:29:14 +08:00
Deng Liuтаdengliu cea9d863f9 feat(github): install the GitHub CLI as a managed tool (#6271)
Registers the GitHub CLI as a managed tool (cli/cli release archives for
macOS / Linux / Windows on arm64 and x64, verified against the release's
checksums file), and offers Install GitHub CLI next to Download manually in
Pull Requests and Clone Repository > GitHub when gh is missing. An existing gh
(OPENIDEA_GH, PATH, Homebrew, Program Files, Snap) counts as installed, so no
duplicate is offered. gh is now looked up on each use instead of once per
process, so a copy installed while the IDE runs is picked up without a restart;
ide-github drops its `which` dependency for the shared tool_path lookup.

Co-authored-by: dengliu <[email protected]>
2026-11-27 06:21:21 +08:00
Vladislav Kuzmin 5fa953eddd fix(ci): scope Unix-only integration test declarations for Windows Clippy (#6259)
Windows Clippy (-D warnings) built two integration-test declarations whose only
users are Unix-only tests: tsc_errors in language_smoke.rs (used by the
TypeScript project-errors test) and the file-level Duration import in
plugin_workbench.rs (used by the PTY run-output test). Scope tsc_errors to unix
and move the import into the Unix-only test.

Fixes #6258

Co-authored-by: principalwater <[email protected]>
2026-11-27 06:06:41 +08:00
Mansur Akhmadiтаmansur-akhmadi 031f1acd07 feat(editor): Move Up / Down and Scroll actions (#6268)
Adds Move Up / Down and Scroll and their with-Selection variants as Editor
Actions (IDEA's EditorMoveUpAndScroll family, reachable from Find Action,
imported keymaps and IdeaVim :action). The carets move one line from the head,
dropping a selection unless extending, and the view scrolls by the distance the
primary caret moved (text line top below block widgets, or the visual row with
soft wrap), so the caret keeps its place on screen. Unbound by default, as in
IDEA's keymaps.

Closes #6267

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 06:04:03 +08:00
l0ng-ai add23fe97f feat(viewers): open SVG files as source with a live image preview (#6266)
SVG files open in the text editor with the image viewer beside it and the
Editor Only / Editor and Preview / Preview Only switch Markdown has. The preview
is redrawn from the source as it is typed, reports invalid SVG and recovers once
it is valid; it is drawn as an image, so scripts never run. The SVG layout is
remembered apart from Markdown's, raster images keep the image viewer, and text
editor wrappers gain `fallback` so a plugin's editor for a more specific SVG
pattern still wins.

Fixes #6234
2026-11-27 05:32:32 +08:00
l0ng-ai 3d2b0946de fix(debugger): don't sync breakpoints to the backend while no project is open (#6215)
Before a project opens (a web page booting, a welcome window) and after one
closes, loadBreakpoints(null) asked the backend to replace this window's
breakpoints; with no project the call failed with "no project is open in this
window" and logged debugReplaceBreakpoints failed on every such load. Without a
project the backend holds no breakpoints for the window, so the sync now waits
until a project root is loaded.
2026-11-27 05:18:36 +08:00
Muuтаmuutot 6c7282b442 feat(editor): choose sibling symbols from a code breadcrumb (#6106)
Clicking a code breadcrumb still navigates to its symbol. Right-clicking a crumb
offers "Choose Symbol..." and Alt+Down on a focused crumb opens the same
chooser: the existing Navigation Bar children popup, anchored on the crumb and
listing the symbol's siblings (children of the enclosing symbol, or of the file
for a top-level symbol).

Co-authored-by: muutot <[email protected]>
2026-11-27 05:17:28 +08:00
Muuтаmuutot 1f79a7f805 feat(editor): File Color submenu in the editor tab context menu (#6105)
The editor tab context menu gains the Project view's File Color submenu for
files inside the project. Its rows are action items (file.<colour>,
file.clearColor, file.editColors, registered by the project view) carrying the
path, so the editor never imports the feature and the colour is written to the
same scope + File Colors entry: the tab, the Project view and Settings > File
Colors always agree, and the choice travels with the project settings.

Co-authored-by: muutot <[email protected]>
2026-11-27 05:15:51 +08:00
Muuтаmuutot 3d1eaf71e4 feat(java): pass the import-on-demand thresholds to jdtls (#6117)
Adds Settings > Code Style > Java > Imports with "Class count to use import
with '*'" and "Names count to use static import with '*'", passed to jdtls as
java.sources.organizeImports.starThreshold / staticStarThreshold.

Organize imports used to collapse imports into wildcards on jdtls's defaults
(99, but jdtls keeps the last value it was sent). The thresholds are now always
sent, defaulting to 5 and 3 when the code style leaves them unset; an explicit
value in the server's own settings still wins.

Fixes #6026

Co-authored-by: muutot <[email protected]>
2026-11-27 05:13:37 +08:00
Muuтаmuutot 138209c627 feat(vcs): show Today / Yesterday in the annotate gutter with pretty dates (#6110)
The annotate gutter now shows Today / Yesterday when the global date format's "Use pretty formatting" is on, as IDEA's annotate does (FileAnnotation.formatDate -> DateFormatUtil.formatPrettyDate); older dates, and all dates with pretty formatting off, keep the short date. New formatPrettyDay next to formatTimestamp.

Co-authored-by: muutot <[email protected]>
2026-11-27 05:09:25 +08:00
Mansur Akhmadiтаmansur-akhmadi b283d352b7 feat(editor): Scroll Up / Scroll Down and Move if Necessary actions (#6256)
Adds IDEA's EditorScrollUpAndMove / EditorScrollDownAndMove: scroll by one line, then move each caret that left the fully visible lines to the first or last of them, keeping its visual column; carets still in view keep their place and selection. Reachable from Find Action, imported keymaps and IdeaVim :action; unbound by default as in IDEA. The column logic of Move Caret to Page Top / Bottom is shared through a small helper.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 05:06:05 +08:00
audichuang f7f9dabe2b fix(documents): don't treat a rewrite of the same bytes as a disk conflict (#6195)
With unsaved edits, a touch, a tool rewriting the file unchanged, or a git stash/pop the watcher missed was reported as a disk change and stopped autosave, because both the watcher and autosave's check compared only the (mtime, length) stamp. When the mtime moved but the length did not, the file's bytes are now compared with what the clean text encodes to (encoding, BOM, line endings); identical bytes adopt the new stamp. Equal text in other bytes still conflicts, and without a clean text a moved stamp still counts.

Co-authored-by: audichuang <[email protected]>
2026-11-27 05:04:18 +08:00
l0ng-ai 787d4fbcfa feat(ssh): apply LocalForward and RemoteForward from the SSH config (#6262)
Fixes #6031

`~/.ssh/config`'s `RemoteForward` and `LocalForward` were ignored by the IDE's own SSH client (remote development, SFTP, tunnels), so a forward that works with `ssh <alias>` did nothing in a remote window.

- `ide-ssh` config parsing reads `RemoteForward` / `LocalForward` as OpenSSH does: `[bind_address:]port host:hostport` or the one-argument colon form, IPv6 in brackets, `*` for every address, `localhost` by default; `ClearAllForwardings yes` drops them. Only the target's forwards apply, not a jump host's. Unix socket and dynamic (SOCKS) forwards are skipped with a debug log.
- The shared session of an SSH configuration starts them when it connects (so a reconnect restores them, and they stop when the session closes): each `RemoteForward` is a `tcpip-forward` request, and the client accepts forwarded connections only for the ports it asked for, connecting each to `host:hostport` here; each `LocalForward` listens here and opens a `direct-tcpip` channel per connection. A port that can't be forwarded (in use, refused by the server) is logged and skipped, as `ssh` warns and continues.

Tests: config parsing (forms, jump hosts, `ClearAllForwardings`), and an end-to-end test against the in-process SSH server where both forwards carry data and the local listener goes away with the session. `cargo test -p ide-ssh --all-features`, clippy on `ide-ssh`, `ide-remote`, `openidea`. Not run against a real remote host.
2026-11-27 05:02:12 +08:00
l0ng-ai 3fbd0e05a5 feat(java): suggest variable names from the declared type (#6261)
Fixes #6002

Typing the name of a Java declaration now lists names derived from its type, the way IntelliJ's code style manager suggests them:

- The type's name and its shorter endings: `IMesCheckStandardService` → `iMesCheckStandardService`, `mesCheckStandardService`, `checkStandardService`, `standardService`, `service`; an `Impl` suffix is dropped and an `Entity` one also offered without it.
- Collections and arrays by their contents (`List<Order>` → `orders`, …, `orderList`, `list`; `Order[]` → `orders`), `Optional<User>` → `user`, `optionalUser`, and generic types by their arguments (`Map<String, Order>` → `stringOrderMap`, `orderMap`, `map`).
- Locals and parameters also get the short names (`String` → `s`, `int` → `i`), and an exception parameter `e`.

At such a name only names fit, so the lookup there shows just these: no live templates (`psf` after `MesProductPlan p`), and not jdtls' own name proposals, which repeat the type (`orderBookOrderBook`). Detection is textual on the line (a type, then the name being typed), skipping `new`, `class`, `extends`, `throws`, `return` and similar contexts, annotations, comments and strings.

Tests: `variableNames.test.ts` (names per type kind, declaration detection and its negatives), `src/editor` vitest, typecheck, `codeCompletionSettingsLayout` e2e. Checked in the app on a Maven project with jdtls: `OrderBook b` lists `book`; `java.util.List<OrderBook> o` lists `orderBooks`, `orderBookList`.
2026-11-27 04:54:15 +08:00
l0ng-ai 2d021a3414 feat(database): read and edit table and column comments in Modify Table (#6257)
Fixes #6129

The Modify Table dialog now reads and edits table and column comments on PostgreSQL, MySQL, Oracle and Snowflake.

- `ide-db`: `TableDetails.comment` and `ColumnInfo.comment` (optional). Read from `obj_description` / `col_description` (PostgreSQL), `information_schema` (MySQL; a view's `VIEW` placeholder is not a comment), `all_tab_comments` / `all_col_comments` (Oracle), `DESCRIBE TABLE` and `SHOW TABLES` (Snowflake), and `system.tables` / `system.columns` (ClickHouse, read only: it has no Modify Table).
- Modify Table / Create Table: a Comment field under the table name and a Column comment field per column. Statements go into the Preview:
  - PostgreSQL / Oracle / Snowflake: `comment on table|column … is '…'`; clearing is `is null` (PostgreSQL), `is ''` (Oracle), `unset comment` (Snowflake).
  - MySQL: `alter table … comment = '…'`; a column's comment is part of its definition, so `change column` now carries it. Before, changing a MySQL column's type, default or nullability silently dropped its comment.
  - Columns are commented by their new name; the table rename still comes last.
- After OK the table's details (and, after a rename or a create, the schema's tables) are reloaded, so the tree and the next Modify Table show the table as it now is. Before, reopening Modify Table showed the columns as they were.

Tests: `objects.test.ts` (statements per engine, MySQL comment kept on change, new table), `modifyTableGroups.test.tsx` (fields and preview, no fields on SQLite), `cargo test -p ide-db` incl. the PostgreSQL 17 and MySQL 8.4 integration tests with comments, full vitest, typecheck. Checked in the app against PostgreSQL: existing comments shown, set / changed / cleared through OK, values reloaded, light and dark.
2026-11-27 04:46:32 +08:00
l0ng-ai cd7582c5e5 fix(plugins): keep plugin secrets in the OS credential store on Windows and Linux (#6240)
Part of #6142.

Plugin secrets (`secrets` grant) were stored in plain text in `plugin-secrets.json` everywhere except macOS, where the keychain was already used.

- New `CredentialSecretStore` in `ide-host`: stores each secret in the OS credential store (`ide_ssh::secrets::SecretFile`, the same store as SSH and database passwords) under `<plugin>/<name>`.
- Values still in the old file are read as a fallback and removed from it on the next write or delete.
- Without a usable credential store (e.g. headless Linux with no secret service) it keeps using the file and logs a warning.
- `src-tauri` switches to it on non-macOS platforms.

Tests: `cargo test -p ide-host --lib secret`, clippy on `ide-host` and `openidea`. Not run on a real Windows/Linux machine.

No Windows/Linux runner was available; the platform switch is one cfg line in src-tauri, the store itself is covered by tests on every platform.
2026-11-27 04:13:26 +08:00
l0ng-ai d16b852054 fix(java): don't block a resolved launch on a busy jdtls (#6253)
Fixes #6122

When the IDE's Java build serves a Maven or Gradle module, it already resolves the whole launch classpath. The launch still asked jdtls for its launch info (only the JDK it compiles against and the Java project root are kept) and waited for it unbounded. While jdtls imports a large Maven project ("Update project … Resolve plugin dependency") that request blocks for minutes, so Run sat on "Resolving the classpath" and finally failed with `jdtls: workspace/executeCommand timed out after 120 s`.

Now that call waits at most 5 s. When jdtls is busy or fails, the launch goes on without its extras: `finish_launch` already picks the project JDK, or an installed JDK that matches the module's Java version, and the debugger falls back to the module directory as the project root. Cancellation still propagates.

Tests: `cargo test -p ide-host --lib ops::java` (new test covers a busy, failing, answering and cancelled server), `cargo clippy -p ide-host --all-targets`.
2026-11-27 04:11:11 +08:00
l0ng-ai 06223d9bd7 feat(database): copy selected rows as SQL INSERT, UPDATE and DELETE (#6252)
The grid's Copy as submenu gets SQL INSERT, SQL UPDATE and SQL DELETE for
the whole selected rows, and the data extractors get SQL Updates, SQL
Deletes and Where Clause beside SQL Inserts. A row is matched by its primary
key, which the exported columns now carry; without one, by every column,
which the copied text says first. A NULL value is matched with IS NULL. The
SQL literal rule lives in one helper for One-Row and the SQL formats.

Fixes #6143
2026-11-27 04:06:20 +08:00
l0ng-ai dcd81d601b feat(tools): option to use only the configured package registries (#6249)
Settings > Tools > Download Mirrors > Use only the configured package
registries (off by default). When on, npm and pnpm installs of tools and
agents and the tools' update checks never retry against registry.npmjs.org
when the configured registry refuses or misses a package; the JUnit Platform
launcher is not downloaded from Maven Central; and dependency version
completion and PyPI lookups don't ask Maven Central, npm, PyPI or crates.io.

Fixes #6141
2026-11-27 04:02:19 +08:00
l0ng-ai 762ebecd86 fix(database): build the Modify Table index detail without a UI-text template (#6250)
A template literal holding "UNIQUE " read as untranslated UI text to the
catalog check (textCatalog.test.ts failed on main after #6248).
2026-11-27 04:01:45 +08:00
l0ng-ai fd4efff6e3 feat(database): group and filter the Modify Table list (#6248)
The Modify Table / Create Table list was one flat list of columns. It now
groups Columns, Keys (the primary key as edited), Foreign Keys, Indexes and
Triggers, each collapsible with its count, and a filter on its toolbar
narrows the rows by name or type. The statements the dialog runs are
unchanged.

Fixes #6128
2026-11-27 03:54:09 +08:00
l0ng-ai 8968974f42 feat(database): side panels, data extractor and Export Table to Clipboard in the grid's context menu (#6247)
The grid's context menu gets Show Record View, Open in Value Editor and Show
Aggregate View (checked while shown; the shown one hides it), the toolbar's
data extractor as a submenu, and Export Table to Clipboard, which copies the
whole result or table page through that extractor (whole values, as Export).

Part of #6144
2026-11-27 03:50:44 +08:00
l0ng-ai 5f083ae47c docs(plugins): quote the <name> and <title> placeholders of executors (#6245)
A bare <title> in Markdown is an HTML title element that swallows the rest
of the file in the preview, which also broke the markdown render test that
reads this README. The executor and interpreter placeholders are now quoted.
2026-11-27 03:40:47 +08:00
l0ng-ai 83b14b4329 feat(project): Copy Path/Reference… in the Project view opens the previewing chooser (#6242)
The Project view's Copy Path/Reference... opened a submenu of names only. It
now opens the editor's chooser at the menu's position, previewing what each
row copies for the selection (several paths one per line): absolute path,
file name, path from content root and source root, plus the contributed rows
(repository path, remote link, agent reference). The chooser is provided to
@/editor/api by editor/core, so the API module stays free of popup imports.

Fixes #6032
2026-11-27 03:37:15 +08:00
l0ng-ai 74eefd6116 feat(agents): Send to Agent from the editor tab menu and editor tab drops on the composer (#6241)
The editor tab context menu gets Send to Agent, which adds the tab's file as
an @ reference to the agent message typed last. Dragging a file tab onto the
agent composer adds the same reference; session and virtual tabs are not
accepted there.

Fixes #6036
2026-11-27 03:22:21 +08:00
l0ng-ai a96c70f2a7 fix(ui): show the JSON icon for .uproject and .uplugin files (#6239)
#5444 associated .uproject and .uplugin with JSON but left them on the
generic file icon, which failed icons.test on main. They now use the JSON
file icon.
2026-11-27 03:15:01 +08:00
l0ng-ai 304503b9f1 feat(vcs): submenu aim on repository rows of the multi-repository branch popup (#6238)
Moving the pointer from a repository row toward its open branch list no
longer swaps the list for each repository row it crosses: like submenus of a
menu (menuAim), a row reached while heading for the list waits 300 ms, and
the list stays when the pointer enters it. The repository the window works
on is listed first; the others keep their order and colours.

Fixes #6152
2026-11-27 03:14:15 +08:00
l0ng-ai 06cf8fb16a fix(deps): update gix to 0.90 for GHSA-q54r-jf2p-rfr2 (#6237)
gix 0.88-0.89 let an untrusted .git/config turn off the protectNTFS /
protectHFS path checks (GHSA-q54r-jf2p-rfr2); 0.90.0 fixes it. The IDE opens
arbitrary repositories with gix, so it takes the fixed release. No API
changes were needed.
2026-11-27 03:09:19 +08:00
l0ng-ai 521e00d075 feat(vcs): Checkout and Update for a local branch with an upstream (#6236)
The branch popup and the Branches pane offer Checkout and Update next to
Checkout for a local branch that is not checked out: it checks the branch out,
then updates it with the configured update method, in each repository where
the checkout took place (the common-branch menu of a multi-repository project
acts in all of them). Disabled without a tracked branch.

Fixes #6222
2026-11-27 03:07:37 +08:00
l0ng-ai b4cad6ec1b feat(run): Pause Output in the console context menu (#6235)
The Run/Debug console's context menu gets a Pause Output toggle. While it is
on, the output shown so far stays put and new output (including the rest of the
open line) is held back; turning it off shows everything that arrived
meanwhile. Clear All also resumes.

Fixes #5998
2026-11-27 03:03:15 +08:00
Jesse 62e26fa7e3 feat(unreal): support Unreal Engine projects (#5444)
A folder whose top level holds a .uproject is now an Unreal project. The
Project tool window switches to an Unreal view: Source is a source root,
Config a resources root, and Binaries, Intermediate, Saved and
DerivedDataCache are excluded from the tree, index, search and file watching
even before Unreal creates them. The root label names the engine the
project's EngineAssociation resolves to (HKCU Builds / HKLM InstalledDirectory
on Windows; a registered directory that no longer exists is dropped), and
three run configurations start UnrealEditor with the project as the editor,
as a game (-game) or as a dedicated server (-server), debugged through
lldb-dap. Nested projects are detected like Godot and Flutter ones, and the
.NET detector skips the same generated directories case-insensitively.

Also sets the new field in the remote_dev test ProjectInfo and keeps
"Unreal Engine" and the .uproject placeholder in English in the catalogs.

Co-authored-by: fengling375 <[email protected]>
2026-11-27 02:49:18 +08:00
Vadim LazukтаInf1mum 1119467ab4 feat(plugins): network grants from a settings key, approved when it is set (#6233)
A manifest can now declare net:setting:<key> / net.http:setting:<key> (plugin
API 1.18): the plugin may connect to the host the user typed into its own
string setting <key> (a bare host or a URL), so plugins for self-hosted
servers (GitLab, Jira Server, Gitea) can reach an intranet instance.

- The key must name a string setting of the plugin's own schema, checked at
  install and start; value hosts follow the manifest host rules, '*' refused.
- Applying the value in Settings asks once, naming plugin, setting and host
  (Deny by default; the net.http variant says the connection is unencrypted).
  A value that changes any other way shows as pending with an Approve action
  in the plugin's permissions, next to the net:ask hosts, and is revocable.
- The approval is recorded per plugin and grant in the ledger and
  materializes as net:<host> / net.http:<host> only while the setting still
  holds it, so the request path (net_capability, redirects) is unchanged.
  Remote hosts keep it for the session only, like net:ask. net:ask prompts
  never fire for a setting-derived host.
- Approving takes the host the user was shown and is refused when the
  setting no longer holds it, so a value the plugin writes after the dialog
  opens is never approved in its place.

Fixes #3809

Co-authored-by: Inf1mum <[email protected]>
2026-11-27 02:41:26 +08:00
George Mukha e1ce850a29 feat(vcs): compare image revisions and highlight changed pixels (#6232)
Image files in Git diffs (Local Changes, commit details, file history) now
open in an image diff instead of a binary notice: both revisions side by side
with their sizes, plus an optional third pane that highlights changed pixels
and counts them. Revisions are read through a new vcs_image_at command backed
by Repo::file_bytes_at_bounded, which falls back to a bounded git cat-file like
the existing blob reader.

Fixes #6229

Co-authored-by: themukha <[email protected]>
2026-11-27 02:34:33 +08:00
Mansur Akhmadiтаmansur-akhmadi 3e39368d43 feat(editor): word moves and deletes in Different "CamelHumps" Mode (#6226)
Adds Move Caret to Next / Previous Word in Different "CamelHumps" Mode (with and without Selection) and Delete to Word Start / End in Different "CamelHumps" Mode. Each runs the word move or delete of the mode opposite to Use "CamelHumps" words, picked from the same CodeMirror commands the editor keys already use, and reads the setting when it runs. Unbound by default, as in IDEA, and reachable from Find Action, imported keymaps and IdeaVim :action.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 02:10:32 +08:00
Vadim LazukтаInf1mum b2a5ea1594 fix(notebook): editor shortcuts work while a notebook cell has focus (#6228)
Editor-scoped shortcuts (Reformat Code, Show Context Actions, column selection, multi-caret and the rest) did nothing while a notebook cell had focus. The focused cell editor is now published through @/editor/api, the notebook sets textEditorActive / editorTextFocus for it the way a text tab does, and the core, LSP and inline-completion action resolvers run in that cell instead of the last text tab. Actions that cannot target a notebook yet (read-only toggle, rendered doc comments, soft wrap, bookmarks, Show History for Selection) decline rather than act on another tab. Cell editors also get the text editor's multi-caret mouse handling.

Co-authored-by: Inf1mum <[email protected]>
2026-11-27 01:58:07 +08:00
Delaruno20таDelaruno20 902d8ca257 fix(notebook): theme HTML output frames instead of a fixed white page (#6223)
Rich HTML outputs (a pandas DataFrame, for example) rendered in a sandboxed frame whose document hard-coded a white page, leaving a bright block in dark themes. staticOutputDocument takes an optional palette (text, background, table border and header colours, color-scheme), validated before it goes into the CSS; the output view reads it from the theme tokens and the root's data-theme, follows theme changes, and the frame uses the notebook's editor background. Raster images keep their own background.

Co-authored-by: Delaruno20 <[email protected]>
2026-11-27 01:52:29 +08:00
Mansur Akhmadiтаmansur-akhmadi 92b5b5306f feat(workbench): Enter / Exit Zen Mode (#6039)
View › Appearance › Enter Zen Mode turns on Distraction Free Mode and full screen with one action. Zen Mode is on while both are on; the action sets both to the opposite, touching only the one that differs, and a second run while one is in progress joins it. Full screen is tracked from the window's events (macOS) or resizes (Windows, Linux), and the title flips between Enter and Exit Zen Mode. The item is in the native View › Appearance menu after Enter Distraction Free Mode and in Quick Switch Scheme › View Mode.

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 01:49:04 +08:00
ambersariya 707cee9b0b fix(vcs): scope Git Log to the selected branch repository (#6227)
Activating a branch under a repository group in the Git Log's Branches pane passed only the branch name, so the log also listed commits from other repositories with a branch of the same name. The filter now keeps the repository of each activated branch (branchTargets), the log queries only those repositories for it, and the branch tree and Paths filter keep their scope. Clearing the branch filter restores the log of every repository Paths allows.

Co-authored-by: ambersariya <[email protected]>
2026-11-27 01:46:44 +08:00
Alexanderтаformiat d64be035c6 fix(vcs): a branch without an upstream shows no outgoing commits (#6211)
A branch without an upstream showed an outgoing count against the remote branch of the same name, for example an old origin/feature-search left from earlier work, so a new feature-search made from origin/main showed main's commits as outgoing. outgoing_commits used the default Push destination, which falls back to that same-named branch; it now counts only towards a destination the branch is set up with, its upstream or a push refspec. The Push dialog still proposes the same-named branch.

Co-authored-by: formiat <[email protected]>
2026-11-27 01:43:48 +08:00
LU XIANGRUIтаwildcatDownstairs cb60c742fc feat(typescript): code style for semicolons, quotes and spaces, sent to tsserver (#6045)
Only tabSize and insertSpaces reached the TypeScript server, so quick fixes, auto-imports, refactorings and Reformat Code used tsserver's own style. Editor › Code Style › JavaScript and TypeScript get Spaces (tsserver's insertSpace* options) and Punctuation (semicolons, quote style) tabs, stored with the per-language code style settings and passed to vtsls and typescript-language-server. A project's own Prettier, oxfmt or Biome configuration still takes over formatting once the tool is installed, and Format on save keeps running it.

Merged main in and combined this with the dprint formatter that landed meanwhile: dprint is chosen before the project-formatter check and also runs on save.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 01:43:28 +08:00
l0ng-ai b245335cc6 test(e2e): put the caret on a query line by clicking it, not with Cmd+Up (#6231)
The result tab rename e2e test pressed Cmd+Up to move the caret to the first line, but in the IntelliJ macOS keymap Cmd+Up is Jump to Navigation Bar. The following Cmd+Backspace only deleted the editor line because editor text actions ran while a popup was open; since #6187 a key pressed in a popup belongs to the popup, so the test failed. Click the first line instead.
2026-11-27 01:43:00 +08:00
Deng Liuтаdengliu e13ed093ec fix(workbench): skip hidden tool-window focus targets and track plugin iframe focus (#6094)
Activating a tool window focused its first [data-autofocus] or focusable descendant without checking visibility, so a hidden file input or an inactive tab panel took the focus as a no-op and left it in the previous window. Activation now skips hidden, inert and display:none / visibility:hidden targets and falls back to the tool window body.

Focus inside a sandboxed plugin iframe doesn't bubble focusin to the host, so focus scopes, toolWindowFocus / activeToolWindow and auto-hide of unpinned tool windows stayed stale. The frame bridge now reports activation, accepted only while the host document has focus and the frame is its active element, and window blur into an iframe is tracked too.

Co-authored-by: dengliu <[email protected]>
2026-11-27 01:37:36 +08:00
LU XIANGRUIтаwildcatDownstairs aa0f8105af feat(run): run Cypress tests with a test tree and Rerun Failed Tests (#6044)
Cypress specs only ran as an npm script. A package.json script that runs cypress run is now a test configuration, and a package that depends on cypress or has a cypress.config.* gets a Cypress configuration (npx cypress run) whose form chooses the testing type, browser and specs. Test runs report through Cypress's built-in teamcity reporter into the test tree (spec › describe chain › test, with durations and failure details), with gutter icons, navigation to source and Rerun Failed Tests selecting the failed specs.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 01:32:57 +08:00
LU XIANGRUIтаwildcatDownstairs 0adc816a56 feat(problems): list TypeScript project errors from the project's tsc --watch (#6097)
The TypeScript server reports errors only for open files, so a change that breaks an unopened file went unnoticed until Build. Problems › ⋮ gets TypeScript Project Errors (tsc --watch), off by default (project setting languages.typescript.watchProblems). When on, the IDE runs the project's own node_modules/.bin/tsc in watch mode for each root tsconfig.json and lists its errors under source tsc, parsed by Build's tsc parser. The watcher never writes into the project: build info goes to a temporary folder, and an error that Build and the watcher both report is listed once.

The language smoke workflow step from the original branch is left to a separate change.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 01:32:29 +08:00
LU XIANGRUIтаwildcatDownstairs ea29339b6b feat(css): complete var(--…) custom properties from the whole project (#6043)
var(-- completion offered only the custom properties of the current stylesheet, because the CSS language server sees one file. The project index now stores each --name declaration's value, and a web_css_variables command returns the document's own declarations (from its unsaved text) followed by the index's. The editor uses it for completion inside var( (document's own first, value in the type column, a swatch for colors), hover and Go to Declaration across CSS, SCSS, Less and <style> blocks.

Also keeps the fallback doc comment on fallback() in completion.ts.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 01:27:56 +08:00
l0ng-ai 84854bed0e test(i18n): accept the DuckDB source's untranslated catalog entries (#6230)
The DuckDB data source (#6181) added zh catalog entries that are the same as English (DuckDB, JDBC URL and the path/to/database.duckdb placeholder), which src/platform/i18n.test.ts rejects for locales with another script. List them as same-as-English.
2026-11-27 01:26:36 +08:00
Vladislav Kuzmin 81b6cb7af6 feat(database): add a named DuckDB JDBC data source (#6181)
DuckDB gets its own data source preset on top of the JDBC driver profiles: register the official DuckDB JDBC JAR once, then choose a database file, an in-memory database or a JDBC URL. Opening a .duckdb file or importing a jdbc:duckdb: URL leads to the same dialog.

Read-only file connections ask DuckDB for read-only access when the database opens (duckdb.read_only), and reject URL or property options that conflict with it, so a read-only connection can no longer create a missing file. In-memory databases require write access. The source type picker also keeps a visible option in place while it is clicked, so the first click selects it.

Co-authored-by: principalwater <[email protected]>
2026-11-27 01:13:34 +08:00
LU XIANGRUIтаwildcatDownstairs ffe96c2ca2 feat(format): format with the project's dprint (#6049)
Reformat Code and format on save run the project's own dprint (dprint fmt --stdin <path>) for files its plugins cover when a dprint config or a project-local dprint is found below the project root. The covered files come from dprint editor-info, cached per config file and modification time (failures included, so an offline plugin download doesn't time out on every format). Files no plugin covers, and every file when dprint can't run, keep their usual formatter.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 00:54:33 +08:00
LU XIANGRUIтаwildcatDownstairs 33bd5372b6 feat(run): run Jasmine tests with a test tree and Rerun Failed Tests (#6050)
Jasmine test configurations report results to the test tree through a reporter, so specs show up as they run, navigate to source, and Rerun Failed Tests selects the failed specs with --filter=. A suite whose afterAll failed is rerun by its specs.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 00:54:16 +08:00
Mr0Bread 44aeb95993 feat(agents): configure additional launch arguments for built-in ACP agents (#6199) (#6199)
Agent Setup gets an Additional arguments field for built-in ACP agents that launch directly. The arguments are stored as an argv array and appended to the agent's existing launch command; Reset clears only that suffix and keeps the executable, environment and the agent's own arguments. Registry, package-runner, custom ACP and native-driver entries don't show the field.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-27 00:51:24 +08:00
LU XIANGRUIтаwildcatDownstairs fa6b4be6f5 feat(js): resolve path aliases from Vite, Rollup and esbuild configs (#6033) (#6033)
TypeScript and JavaScript import resolution reads path aliases from Vite, Rollup and esbuild configs (resolve.alias, @rollup/plugin-alias, esbuild alias), so imports like `@/components/Button` resolve, complete and navigate without a duplicate tsconfig `paths` entry. Aliases are scoped to the package that declares them, and tsconfig `paths` still win when both define a prefix.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 00:51:02 +08:00
LU XIANGRUIтаwildcatDownstairs 144cd90175 feat(run): watch mode for Jest and Vitest test runs (#6102) (#6102)
Jest and Vitest test run configurations get a watch option. A watched run keeps the runner alive, re-runs on file changes and ends each cycle in the test tree like a finished run; derived runs (rerun failed, run at cursor) run once.

Merged main in and combined the RunExtras watch field with the executor field that landed on main.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 00:42:53 +08:00
Mansur Akhmadiтаmansur-akhmadi da3b621345 feat(run): run a Go package folder's tests from the Project view (#6218)
A Go package folder or the module root in the Project view had no Run / Debug: produceDirectory only knew folders with a test-like name or marked test roots, which Go packages rarely are. Now any folder of a Go module gets Run 'go test <dir>/...' (./... at the module root), Debug, and the More Run/Debug entries, as GoLand does. The configuration's flags and -args are kept and its package arguments replaced. A Go Test form configuration gets scope: directory and the target. Folders go test skips (testdata, vendor, names starting with . or _) and folders outside the module get nothing. _test.go files get a Go test file icon.

Closes #6217

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 00:40:53 +08:00
Orion b301e2bbe1 fix(agents): expose and apply native Codex Fast mode (#5064)
The composer shows Codex's native service tier as a Fast toggle and sends it with each turn: Fast sends the runtime's advertised fast tier, an explicit Off sends `default`, and an untouched toggle inherits the runtime's default. The tier is a per-model option, and an explicit Fast choice survives a reconnect on a model that only offers Standard, applying again once a model that supports it is selected.

Co-authored-by: Dream-Winter <[email protected]>
2026-11-27 00:40:03 +08:00
Alexanderтаformiat feac919a1b feat(vcs): grow an opened branch filter group down to the window edge (#6220)
In Git Log > Branch filter, an opened Local or Remote group now lengthens the popup down to the window's bottom edge, instead of scrolling everything past 320 px in a small box. The popup measures its room once on open (anchor to window edge, minus Popup's offset and margin and its own search field and footer) and uses that as the list's limit, so it never outgrows the room below or flips. With less room than 320 px, the old cap stays.

Closes #6219

Co-authored-by: formiat <[email protected]>
2026-11-27 00:38:36 +08:00
LU XIANGRUIтаwildcatDownstairs 0155d74084 feat(debugger): reconnect Attach to Node.js automatically when the process restarts (#6103)
Attach to Node.js ended the debug session as soon as the inspected process exited, so with nodemon, node --watch or tsx watch the attach had to be restarted after every save. The configuration gets Reconnect automatically, which passes js-debug's `restart: true`. js-debug waits for the inspector to come back and attaches the new process as a new child session with the same breakpoints. While it waits, the Frames pane says so. The restarted process's tab replaces the finished one and keeps its console output. VS Code attach configurations with `restart` (true or a policy object) import with the option on.

Closes #6084

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 00:32:02 +08:00
l0ng-ai 130f75e7e8 fix(agents): keep Generate Commit Message tasks out of the task list (#6221)
Generate Commit Message runs a throwaway agent task. The task was saved when it was created and deleted only by the frontend afterwards, so a delete that never ran left it (and the agent's own session history) behind after a restart. NewAgentTask gets `ephemeral`. An ephemeral task is never written to disk, and its session/new carries `_meta.openidea.ephemeral`, so Claude Code starts with --no-session-persistence and Codex starts an ephemeral thread.

Fixes #6132
2026-11-27 00:30:58 +08:00
Deng Liuтаdengliu 2abd65aedd feat(editor): track non-file editor tabs and split panes in Back / Forward (#5986)
Navigate › Back / Forward now records editor tabs without a file path (agent chats, terminal editor tabs, other custom editor tabs) as places, and remembers the split pane of each place, so Back returns to the same pane while it still holds the tab. Entries an editor kind reports as no longer navigable are skipped, and duplicates they expose collapse. Moving focus between tool windows is still never a history step.

Co-authored-by: dengliu <[email protected]>
2026-11-27 00:26:45 +08:00
LU XIANGRUIтаwildcatDownstairs 1b3e4fac6a feat(profiler): open .cpuprofile files as snapshots (#6101)
.cpuprofile files saved outside the IDE (node --cpu-prof, Chrome DevTools, CI) open in the Profiler tool window. Run > Open Profiler Snapshot…, the Profiler header and its empty state pick one or more files. The Project view, editor and tab menus offer Open in Profiler on .cpuprofile files, and a banner shows above one opened in the editor. Each file becomes its own snapshot, and reopening a file replaces it. ProfileSpec::CpuProfileFile reads it with the existing V8 parser. Unreadable, non-profile and sample-less files are errors. Frames whose source isn't on this machine keep their name but drop the location. The menu item now lives in ide-host's menu spec.

Closes #6086

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 00:20:40 +08:00
LU XIANGRUIтаwildcatDownstairs 72b0c7c48c feat(refactor): Extract Type Alias and Extract Interface for TypeScript (#6040)
tsserver's "Extract to type alias" and "Extract to interface" were reachable only as unnamed server items in Refactor This, and Refactor > Extract Interface… worked only in Java. In TS/JS files, Extract Interface… now runs tsserver's "Extract to interface" (Java keeps the jdtls dialog). The new Refactor > Extract Type Alias… runs "Extract to type alias" ("Extract to typedef" in JavaScript). The new type is then renamed in place, as Introduce Variable does. When tsserver offers no such action, a hint says why. classifyAction maps these tsserver titles so Refactor This lists them under Extract/Introduce. The menu item now lives in ide-host's menu spec.

Closes #6014

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 00:09:52 +08:00
Charlie.Weiтаcharli117 25d1046af0 feat(agents): fork a recorded native session into a new task (API 1.18) (#5131)
A recorded native Claude Code or Codex session can be forked into a new task, from the Agents view's session list and from Import Sessions (one or several at once). The fork starts from the recorded conversation and leaves the original session untouched; the host validates the session and builds the fork invocation itself.

Plugins get the same through the grant-scoped `agents.fork-session` (API 1.18, `agents` capability, trusted projects only).

Co-authored-by: charli117 <[email protected]>
2026-11-27 00:05:44 +08:00
Alexanderтаformiat 1cdb998532 feat(search): match - and _ interchangeably in Go to File queries (#6063)
In Go to File and the Files tab of Search Everywhere, a `-` or `_` in the query now matches either separator in file and folder names (`bit_matcher` finds `bit-matcher/`). File needles fold `_` to `-` one character for one, so highlight indices stay correct. ASCII candidates keep nucleo's ASCII path through a reused per-thread buffer. The `char_mask` pre-filter gives both separators one bit. Exact and prefix boosts still compare the original spelling, so the exact name ranks first. Class and symbol matching is unchanged.

Closes #5942

Co-authored-by: formiat <[email protected]>
2026-11-27 00:01:39 +08:00
l0ng-ai b1ab5afa67 feat(plugins): Services menus on the IDE's own nodes and plugin executors (API 1.18) (#6216)
services.context and services.toolbar menus let plugins act on the IDE's own Services nodes (run configurations, Docker containers): when keys per selected service (serviceProvider, serviceKind, serviceId, serviceName, serviceRunning, runConfigurationId, serviceSelectionCount) and the selection as the command's JSON argument, through a new workbench registerServiceSelectionItems registry fed by ServiceProviderContribution.context.

executor = "<title>" on [[contributes.javaAgents]] binds the agent to a plugin executor: Run/Debug '<name>' with <title> beside Run and Debug (run widget, gutter, context menus, Services), the only launches that get the agent. The launch carries the plugin id (RunConfig.executor, or executor in the debug launch extras); the java.agent grant and jar pin are unchanged; without the grant the IDE asks instead of launching. The Services menu of a run configuration now also lists its executors (Coverage, Profile).

Fixes #4528
2026-11-27 00:00:19 +08:00
l0ng-ai 0101d11ac9 feat(plugins): complete the Arguments field of a plugin's own run configurations (API 1.18) (#6213)
The optional run-configuration-completion export receives the project, the configuration's id, the field (arguments), its text and a UTF-16 caret, and answers items that each replace one UTF-16 range, so other options, quoted values and the arguments after -- stay as typed.

The host completes only configurations the plugin currently provides for the window's project (also a user's override of one), keeps 200 items and gives the plugin 300 ms. In Run | Edit Configurations the field asks while typing and on Ctrl+Space, applies an item with Enter or Tab, closes the popup on Escape without closing the dialog, drops answers for text that has changed, and stays usable when the plugin fails.

Fixes #4753
2026-11-26 23:34:36 +08:00
l0ng-ai 07d26722b1 feat(plugins): watch files outside the project within fs.read grants (API 1.18) (#6212)
events.watch-paths watches files and directories outside the invoking window's project that an fs.read grant covers, checked where they really are (a link out of the grant is denied; project paths are refused; at most 32). A file is watched through its parent directory so atomic saves and re-creation keep working; a directory is watched flat, never recursively. Changes arrive as watched-files-changed events to the window that asked, through the same queue as project file changes.

Watches belong to (plugin, project) and end when the project or its window closes or the plugin stops (disabled, updated, a grant revoked); idle reclaim keeps them. Watcher threads only queue changes, and delivery re-checks that the set, its window and its project are still current. Nothing remote is watched.

Fixes #4761
2026-11-26 23:33:04 +08:00
Muuтаmuutot df48d9271b feat(editor): complete paths on bare lines in ignore files (#6007)
Path completion only triggered inside quoted strings, HTML attributes, url()
and Markdown links, so it never fired in .gitignore-style files. Each
non-comment line of an ignore file (.gitignore, .dockerignore, ...) is now a
path prefix completed eagerly from the file system, after an optional `!`.
Glob patterns and comment lines are left alone.

Co-authored-by: muutot <[email protected]>
2026-11-26 23:31:47 +08:00
LU XIANGRUIтаwildcatDownstairs cb6b7ccd3f feat(run): suggest installing dependencies when package.json or the lockfile changes (#6100)
A Node.js project now gets a notification when node_modules is missing
("Dependencies are not installed") or out of date ("Dependencies changed since
the last install"), with Install (npm / pnpm / yarn / bun install by the
detected package manager, in the Run tool window) and Ignore.

Stale means a lockfile newer than the last install, or a package.json whose
dependency fields changed since the last up-to-date check and is newer than the
install; scripts-only edits never count. The last install is the newest install
marker (.package-lock.json, .modules.yaml, .yarn-integrity, .yarn-state.yml,
.pnp.cjs, .yarn/install-state.gz) or, for bun, the newest package folder. In
workspaces one notification is shown for the workspace root. The project root
and the folders right under it are checked on open. Shown once per state; Ignore
lasts until the dependencies change again, across restarts; only in trusted
projects. Also available as Install Node.js Dependencies for the active file's
package.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 23:28:37 +08:00
Muuтаmuutot 13c0e8aa8d feat(settings): breadcrumb links back up the tree and mouse side-button page history (#6163)
Settings breadcrumb parents are links back up the page tree, and the dialog keeps a page history in its store: the header Back / Forward buttons, ⌘[ / ⌘] (and ⌘⌥← / ⌘⌥→) and the mouse side buttons all walk it.

While Settings is open it takes over navigate.back / navigate.forward through overrideActions, which puts the editor's own registrations back when Settings closes, so their owners can still dispose them. In the standalone Settings window the history keys listen in the capture phase: the window's browser guards cancel ⌘[ / ⌘] in the bubble phase.

Co-authored-by: muutot <[email protected]>
2026-11-26 23:24:02 +08:00
Luis Felipeтаluisfelipe18 9f643af069 feat(web): openidea-server --web serves the IDE to a browser (#5134)
`openidea-server --web` serves the built frontend and the IDE backend over one HTTP + WebSocket port, directly or behind a reverse proxy that strips or keeps its path prefix.

- The rpc dispatcher gains an async `invoke` with a channel sink, so project-host commands, streaming channels and IDE events run over WebSockets as they do over `--stdio`.
- Token auth is on by default (a random token unless `--token` or `--no-auth`), binds 127.0.0.1 by default, and WebSocket upgrades must be same-origin.
- The browser serves the desktop shell commands with the trust classes the desktop declares (a test keeps them in step), and the desktop menu spec, now in `ide_host::menu`. Recent-project recording and project rename are shared ide-host ops.
- WebSocket output is queued without dropping channel data or events. A reloaded page gets back the project its window still has open; after a server restart the page reloads. One tab per window, with Take Over.
- Browser fallbacks for the title bar menu, path chooser, clipboard, dialogs, Settings and external links; a reconnecting banner and an unsaved-changes guard.
- `scripts/start-web.sh` and the guide (English and Chinese).

Co-authored-by: luisfelipe18 <[email protected]>
2026-11-26 23:00:28 +08:00
LU XIANGRUIтаwildcatDownstairs 0c02a9e467 feat(run): complete npx / pnpm exec / bunx / yarn commands in Run Anything (#6099)
Typing npx (or pnpm exec, bunx, yarn) in Run Anything lists the executables
installed in node_modules/.bin from the current file's package up to the project
root, the current package first and its direct dependencies' bins first within
a package. Typing filters, Tab completes, and Enter runs the command as an
npm-kind configuration in that package folder. A typed line with arguments runs
in the first package that has the executable; an executable that isn't installed
or a line with shell syntax still goes to the shell. Yarn 2+ offers only direct
dependencies' bins; Bun .bunx shims and dangling links are skipped.

Only the disk is read. The provider uses Run Anything's subscribe() to refresh
the open popup when its background read finishes; reads are cached and dropped
when node_modules or a package.json changes.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 22:43:33 +08:00
LU XIANGRUIтаwildcatDownstairs 8c7bdc9bf2 feat(run): add a Node.js run configuration type (#6098)
node configurations had no type of their own, so they were edited as a bare
command line and Add Configuration had no Node.js entry. The existing node kind
gets a Node.js type with Node interpreter, Node options, JavaScript file and
application arguments; working directory and environment are the shared fields.

Configurations from the gutter or imported from VS Code / JetBrains carry only a
command line; the type splits it into options, file and arguments, and opens it
in the form only when that reproduces exactly what runs today (npx tsx, test
runs, node --test and node -e keep their plain command). An empty interpreter
runs the project's node. js-debug already passes the options as runtimeArgs.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 22:41:16 +08:00
LU XIANGRUIтаwildcatDownstairs a3f6d82391 feat(run): update Jest and Vitest snapshots from a failed test (#6093)
A Jest or Vitest snapshot mismatch now offers Update Snapshot: in the test tree
context menu (on the test, or on a file/suite for every snapshot failure under
it), above the failure output, and in the editor gutter run menu when the newest
finished run with a result for that test has a mismatch.

It reruns only those tests in the same Run tab with the existing test-name
filter plus -u. The tab then keeps the selection without -u, so Rerun runs the
tests instead of rewriting snapshots. For Jest, whose -u deletes every obsolete
.snap file regardless of filters, the update also passes a
--testPathIgnorePatterns that keeps the other files. The update always runs once
(watch cleared). Mismatches are recognised from Jest's toMatchSnapshot /
toMatchInlineSnapshot / toThrowErrorMatching(Inline)Snapshot headers and
Vitest's "Snapshot ... mismatched"; other runners are unaffected.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 22:39:41 +08:00
LU XIANGRUIтаwildcatDownstairs bfde0ffc34 feat(templates): add React component live templates rfc, rfce, rafce and rcc (#6030)
React files only had the useState / useEffect live templates. Four component
templates are added for .jsx and .tsx files in the JavaScript / TypeScript
group: rfc (export default function), rfce (function + export default), rafce
(arrow const + export default) and rcc (class component extending
React.Component). The name comes from the file through a new componentName()
template function (user-card.tsx -> UserCard, PascalCase names kept, a leading
digit gets a Component prefix), and the caret lands inside the returned <div>.
The TSX variants declare `type Props = {}` and take `{}: Props`.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 22:38:07 +08:00
LU XIANGRUIтаwildcatDownstairs 9067abf0cf feat(editor): JSDoc @param / @returns stubs for JavaScript and TypeScript (#6025)
Typing /** + Enter above a JavaScript or TypeScript function fills in the JSDoc
stub: @param for each parameter (rest parameters as ...args, destructured ones
as options), and in .js/.jsx files the type of a default value ({string},
{number}, {boolean}, {Array}, {Object}, {Map} for new Map()). @returns is added
when a declared result isn't void, or with no declared result when the body
returns a value (not counting nested functions) or an arrow has an expression
body; constructors and setters get none. Function expressions and
single-parameter arrows assigned to a variable are handled too.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-26 22:36:31 +08:00
faysouтаfaysou 4939b63c88 feat(markdown): extract embedded images to files (#6171)
Extract Embedded Images... in the Markdown editor context menu and Find Action
lists the image count and the sibling output folder, then writes each supported
data: URL image (JPEG, PNG, GIF, WebP, checked against its file signature) from
inline Markdown and quoted HTML <img src> to that folder and replaces the
destinations in one undoable edit. Alt text, titles and other attributes stay as
they are; literal HTML (code, pre, script, ...) is skipped.

If a write fails or the document changes during extraction, no link changes and
the notification reports how many files were already written.

Co-authored-by: faysou <[email protected]>
2026-11-26 22:35:33 +08:00
l0ng-ai 78d34af971 fix(plugins): gutter actions know the editor's project and go inert after an edit (#6204)
Gutter and hover action providers ran with an empty invocation, so they could not tell which project the editor belongs to, and markers kept running actions computed for text that had since changed.

The host now passes the editor window's project into gutter-actions and hover-actions calls, and the new API 1.18 function workspace.invoking-project returns the project of the window a call serves (the invoking window for commands and events, the editor's window for gutter and hover actions). project-of keeps answering the innermost open project. Actions record the document they were computed for; after an edit, gutter markers are dimmed and gutter and hover actions ignore clicks until the plugin answers for the new text.

Fixes #4762
2026-11-26 22:34:41 +08:00
Alexis d47c9eb347 feat(color-scheme): add a C/C++ page (#6203)
Settings > Editor > Color Scheme gets a C/C++ page between C# and Go. Like the
C#, Go and Java pages it is generated from Language Defaults; its overrides
apply to C and C++ editors only, and anything unset falls back to Language
Defaults. The preview covers a namespace and std, size_t, cout, a macro, a
field and nullptr, and clicking a token selects its attribute.

The page id is editor.colorScheme.c-cpp: `+` reads as a space and `/` splits
a settings link.

Co-authored-by: Rhombicdodecahedron <[email protected]>
2026-11-26 22:34:06 +08:00
faysouтаfaysou 5348e42c59 feat(markdown): copy code from preview fences (#6173)
Fenced code blocks in the Markdown preview, including Mermaid source, get a Copy
Code button in their upper-left corner. It shows on hover or keyboard focus,
copies the fence's text and shows a check for 1.5 s. Indented code, raw HTML
<pre> and rendered math are unchanged.

The copied text drops the blank lines around the code but keeps the first
line's indentation.

Co-authored-by: faysou <[email protected]>
2026-11-26 22:33:34 +08:00
Gabriel Gondim a42eee29f4 fix(vcs): keep the commit message left in the field across a restart (#6189)
After a commit with "Clear initial commit message" off, the message stayed in the
field but was deleted from the saved draft, so a restart brought back an empty
Commit message. The message left in the field is now saved as that changelist's
draft and restored after a restart; with Clear on, the draft is still dropped.

Inclusion stays in memory: after a restart the active changelist's changes are
included again, and a file that should stay out of commits goes in another
changelist, which is saved with the project.

Co-authored-by: GGVidal <[email protected]>
2026-11-26 22:30:10 +08:00
Aevion a3e7142e4c fix(vcs): Show Diff targets the editor's file, not the Project view selection (#6202)
With a file open in the editor, VCS Operations › Show Diff (and Show Diff in New Window) opened
the file the Project view still had selected, because the target resolver preferred the Project
view's retained selection even while the editor owned the context.

Show Diff, Show Diff in New Window and Compare with Branch now take the Project view selection
only while the tree has focus or owns the context (its lead), the same rule Show History, Add to
VCS and Add to .gitignore already use; over the editor the active file wins. The resolver still
goes through the commit-window guards, so an amend row or an ignored-only selection there does
not fall back to the editor's file.

Co-authored-by: aevioni <[email protected]>
2026-11-26 22:23:31 +08:00
audichuang d21fd65341 fix(search): Replace in Files keeps an external change to a clean open file (#6089)
Replace in Files saves open files that have no unsaved changes through
`Documents::save`, which writes unconditionally. If such a file changed
on disk (git checkout, another editor, a formatter) before the watcher
delivered the event, Replace All overwrote the external change with the
replaced old text.

Open tabs now save through `autosave`, which compares the disk stamp
first: on a mismatch the replacement stays unsaved in the editor and the
usual disk-conflict prompt appears. Files Replace opens only for itself
were read moments before and still save directly.

Co-authored-by: audichuang <[email protected]>
2026-11-26 22:18:06 +08:00
l0ng-ai 422f424b60 fix(vcs): drop the second scrollbar beside the Changes file list (#6201)
The split panels kept the library's overflow: auto, so a sub-pixel overflow drew a native
scrollbar next to the file tree's own. Both panels now clip; the tree and the diff list
scroll themselves.
2026-11-26 22:10:23 +08:00
Alexis c10862b1a6 fix(vcs): load the amend message from the included files' repository (#6180)
In a project with several repositories, ticking Amend loaded no message
(since #6175) or, before that, the last message of the repository
selected elsewhere in the app, not of the one the included files belong
to.

Amend now takes the HEAD message of each repository the included files
belong to, using the same plan as the commit itself; distinct messages
are joined by a line break, and nothing is loaded while nothing is
included. A single-root project keeps loading its HEAD message and the
amend preview as before.

Co-authored-by: Rhombicdodecahedron <[email protected]>
2026-11-26 22:03:11 +08:00
Aevion d4db49689e fix(vcs): act on the Commit dialog's changes-tree selection (#6192)
With the modal commit interface, selecting files or a folder in the Commit
Changes dialog and pressing a selection shortcut (Add to VCS, Rollback,
Show Diff) did nothing or acted on the active editor: the dialog keeps the
previously focused window as the active tool window, so the actions never
read the dialog's changes tree.

The dialog's changes tree now publishes its own selection, and the
selection-based actions use it while focus is inside that tree, with an
empty selection taken as final. The shared commit selection is not used
there, so a leftover Local Changes selection cannot leak into the dialog;
Rollback targets the dialog's selection and never widens to the checked
changes.

Co-authored-by: aevioni <[email protected]>
2026-11-26 21:55:41 +08:00
shanyuea 36ab40797c fix(java): keep excluded folders out of the jdtls import (#6179)
In a project whose folder holds checkouts of the same repository in an
excluded folder (such as `.worktrees`), jdtls still scanned that folder.
Its Maven builds repeat the coordinates of the project's own builds, jdtls
keeps one Eclipse project per name, and whichever it found first won, so
Go to Definition and implementations could land in a checkout or miss the
project's own module.

The project's excluded folders now become `java.import.exclusions` (the
folder and everything below it, glob characters escaped), and the jdtls
workspace directory changes with them, so projects imported before the
folder was excluded do not linger. A project with excluded folders gets
a new jdtls workspace once.

Co-authored-by: shanyuea <[email protected]>
2026-11-26 21:52:50 +08:00
l0ng-ai de7d62dce8 fix(ui): show data in tabs, menus and selects as written (#6198)
Tab, menu and select labels that hold data (file, session, branch, author and connection names, plugin setting titles) were looked up in the UI catalog, so a run configuration named Test or an SSH host named dev showed translated in other UI languages.

Tabs and action menu items take a verbatim flag, and the tab overflow menu no longer translates a label twice. Data tabs (editor, run/debug/coverage/profiler sessions, database results, renamed terminal tabs, agent questions, Flutter devices, pull request repository) and data entries in menus and selects (SSH configs, WSL distros, Docker connections, run targets, SDKs, keymaps, plugin formatters and icon themes, changelists, TODO scopes, author filters, file masks, debug history, scope views) show as written. A plugin's setting controls render below VerbatimTextContext.
2026-11-26 21:51:01 +08:00
l0ng-ai e3f9049e26 feat(plugins): Run Anything entries and terminals in a project directory (API 1.18) (#6197)
[[contributes.runAnything]] declares a command word (task, just...). While Run Anything's text starts with it, the IDE asks the plugin's new optional run-anything-provider export for entries; the answer arrives asynchronously, the popup re-renders when it does and drops answers for older text (300 ms budget, 100 entries). Lines starting with the word run through the plugin in the invoking window. A line the plugin claims never falls back to the shell, also when the call fails; a line it leaves goes on to the other providers and the shell.

views.open-terminal-session-in opens a keyed terminal in a directory of the project, given relative to its root. The directory must exist and stay inside the project once symlinks are resolved; trust and the approved program remain the project's.

Fixes #4758
Fixes #4754
2026-11-26 21:50:47 +08:00
János Kranczlerтаjanoskranczler 3e9f018cf4 fix(python): count calls through the base as usages of an override (#6182)
With basedpyright (and pyrefly), Find Usages, Show Usages and the usages
lens found nothing for a Python method that overrides a base-class
method, and Safe Delete removed it without asking. The server binds a
call to the declaration on the receiver's static type, so `repo.save()`
with `repo: Repository` is a reference of `Repository.save` only.

Usages of an override now also include the references of the methods it
overrides, found through the IDE's Python inheritance graph (as Super
Method and the override gutter do). `super()` calls are left out, since
they run the base method from an override; constructors are not
included. The extra searches run one after another under the caller's
request id, so cancelling stops them; a failed base search keeps the own
usages and marks the result incomplete, and Safe Delete refuses then.
Other languages take no new path.

Co-authored-by: janoskranczler <[email protected]>
2026-11-26 21:45:52 +08:00
solhovoy e44d7fd396 fix(java): support launch classpaths from Maven POM modules (#6184)
An Application configuration whose classpath module is a dependency-only
Maven module (packaging=pom, such as a distribution or assembly module)
could not launch: launch preparation required the POM to be a Java
project in jdtls, and the Maven fallback rejected aggregators outright.

Such a module now resolves its launch classpath from its dependencies:
reactor modules (including runtime-scoped ones, which are now built as
upstream projects for every launch) and external libraries, without a
Java language server and without its own output directory. NoBuild
reuses the last resolved classpath instead of running the compile
lifecycle, and a launch from such a POM leaves the Java project to
java-debug instead of naming a non-Java project; a JDWP attach at an
aggregator root still names the root project.

Co-authored-by: solhovoy <[email protected]>
2026-11-26 21:39:53 +08:00
l0ng-ai dc490f1017 fix(ui): show agent and user-defined option labels as written (#6193)
Option labels that come from agents, databases, build tools and user settings matched UI catalog keys by accident, so some were translated and others were not (reasoning effort showed 高 next to Extra high; an HTTP client environment named test showed as 测试 while prod stayed English).

Mark these labels and descriptions verbatim: agent config values, model names and providers, the approval switch label, HTTP client environments, dependency scopes and Gradle configurations, chart columns, database schemas, data sources, warehouses and roles, custom scopes, and plugin setting options. Option headings stay localized.

Fixes #6191
2026-11-26 21:39:30 +08:00
Mr0Bread 5289f44620 fix(lsp): negotiate TypeScript 7 local semantic tokens (#6186)
The native TypeScript 7 server only sends semantic-token modifiers the
client advertises, and the client capabilities did not list `local`. Its
legend therefore had no `local`, so module-level function calls could not
be told apart from local ones and lost the Global function style that
tsserver-based servers get. The client now advertises `local`, which the
editor already maps; no styles or palette change.

Adds an ignored real-server test comparing native TypeScript 7, vtsls and
typescript-language-server on the same sample, and documents the shared
colour-scheme entries.

Closes #6185

Co-authored-by: Mr0Bread <[email protected]>
2026-11-26 21:34:14 +08:00
l0ng-ai 81aac31cc7 fix(ui): use a shared Windows font fallback stack (#6190)
On Windows the UI font stack keeps Inter first and then falls back to Windows CJK faces: Microsoft YaHei UI for Han, Yu Gothic UI for kana, Microsoft JhengHei UI for bopomofo and Malgun Gothic for Hangul. Kana and bopomofo use unicode-range faces because YaHei also covers them. A custom interface font falls back to the same stack. The window boot marks the root with data-os.
2026-11-26 21:31:15 +08:00
Gabriel Gondim 026163af9e fix(keymap): let Ctrl+Enter commit and push instead of splitting a line (#6187)
Ctrl/Cmd+Enter in the commit message inserted a line break in the editor
behind the Commit dialog, and the same key in the Push dialog did nothing.
While a popup is open, editor text actions stay enabled so Find Action
can run them, and Split Line is bound to Ctrl+Enter (Cmd+Enter on macOS),
so the keymap took the key before the dialog saw it.

A key pressed outside the editor (in a plain text field or a popup) no
longer satisfies the editor-focus part of an action's when clause; keyWhen
still sees the real context. Find Action still runs text actions because
it runs the action rather than the key, and keys inside the editor are
unchanged.

Closes #6137

Co-authored-by: GGVidal <[email protected]>
2026-11-26 21:31:11 +08:00
Ainul YaqinтаAkin01 ce03ae7c0f feat(plugins): plugin run configurations can ask for PTY or piped output (API 1.18) (#5014)
Plugin-owned run configurations can choose how the Run console gets the process output: separate stdout and stderr pipes (the default) or a pseudo-terminal, the same as Emulate terminal in output console. Static [[contributes.runDetectors]] take outputMode = "pty" or "pipes"; dynamic configurations come from the new optional execution-configurations export (a launch configuration plus its output mode, used instead of launch- and run-configurations when exported); run.start-with-options overrides the mode for one launch. A mode the user saved on the configuration wins over the per-launch override, which wins over the plugin's default. PTY is refused for test configurations, debug launches, remote run targets and redirected stdin files.

On top of the contributor's work: merged main (API 1.18 was already open), rebuilt the components, and fixed the end-to-end PTY test, which didn't compile and then started configurations before they were loaded.

Closes #4757

Co-authored-by: Akin01 <[email protected]>
2026-11-26 21:24:42 +08:00
l0ng-ai 1cd8e8def5 fix(debug): expand variables by the current stop's references after a step (#6188)
Adapters such as CodeLLDB keep a frame's id across stops while every
variable reference changes. The Variables view matched the scope data to
the frame id only, so right after a step it showed the last stop's
variables under the new stop and re-expanded the kept-open nodes by
their old references: the adapter either returned nothing ("No
variables" until the next stop) or formatted the node again, and then
the fresh reference was never asked for. With a large array open each
step serialized it twice.

Scope and watch data now carry the stop they were fetched for and are
shown only for that stop. Inline values and the Variables view also
share one scopes/variables request per stop instead of asking for the
frame's locals twice.

Fixes #6170
2026-11-26 21:21:22 +08:00
l0ng-ai a0b9fba2f2 fix(window): restore a full-screen window from the caption button on Windows and Linux (#6114)
Refs #6029.

On Windows and Linux (X11) the frameless title bar keeps its caption buttons and drag region in full screen. Full screen is restored on start (window-state's `FULLSCREEN` flag) and the IntelliJ Windows keymap binds no key to Toggle Full Screen, so a window that comes back in full screen covers the taskbar with no obvious way out. There:

- **Maximize** called `toggleMaximize()`, which only flipped the maximized flag under the full-screen frame: the icon changed to Restore Down and nothing else happened.
- **Dragging** the title bar (Tauri's drag-region script) moved a full-screen window, and a **double click** toggled maximize, leaving the window in a broken frame (a thin strip, the page not resized).

Changes:
- In full screen the caption button shows Restore Down and leaves full screen (`window_toggle_fullscreen`).
- `installFullscreenDragGuard`: while the window is in full screen, presses on a `data-tauri-drag-region` stop in the capture phase before Tauri's drag script sees them. Installed on Windows and Linux only; macOS keeps its own drag handling.

Tests: `WindowControls.test.tsx` (full screen → Restore Down leaves full screen; otherwise maximize), `window-drag.test.ts` (guard on/off), `src/workbench` vitest, `pnpm typecheck`.

**Not run on Windows or Linux** (macOS uses native title bar buttons, so none of this runs there). Needs a real-machine check on Windows:
1. Open a project, run Toggle Full Screen (Ctrl+Shift+A → Toggle Full Screen).
2. The maximize caption shows Restore Down; clicking it returns to the previous (maximized or normal) window with the taskbar visible.
3. In full screen, dragging or double-clicking the empty title bar does nothing.
4. Outside full screen: maximize / restore / drag / double-click behave as before.
2026-11-26 20:58:49 +08:00
l0ng-ai 1f6a3bbf0d fix(agents): simplify the Agents settings pages and match the other settings pages (#6154)
## Summary

The Agents settings pages had long multi-line hints and web-style layouts (page headings, a blue primary button, rounded cards, two framed dropdowns per row). They now use the same form and list patterns as the rest of Settings.

```diff
 IDE MCP Server
-  one flat list, 3–4 line hints
+  ─ (enable, run without confirmation, status / endpoint)
+  ─ Connection        listen address, fixed port, keep token
+  ─ Agent Tabs        finished / archived tab limits
+  ─ Background Projects
 Skills / MCP Connections
-  <h2> + primary button + lead paragraph + rounded cards
+  short hint line, toolbar beside the search field, one framed list
 Skills row
-  name, chips (mode, origin, ↗ sources, paths, fork) / description / [Global ▾] [Auto ▾] ●
+  name · description … Auto ▾          (scope, sources, paths, fork → expanded details)
 MCP Connections
-  Add Server · Add from JSON · Import from Project · Browse
+  Add Server… · ⋯ (Add from JSON…, Import from Project, Browse MCP Servers)
-  blue "Detected N servers…" banner with a button
+  hint line with a Review & Import link
 Command Rules
-  two custom bordered columns with input + Add
+  Allowed / Blocked sections with the settings list editor (+ / − / edit)
 Chat, Agent Setup
   shorter hints
```

Locale catalogs (9 languages) are rekeyed for the new text, and the old entries are removed.

## Evidence

- `npx vitest run src/features/agents src/features/settings src/platform/locales` → 119 files, 1615 passed. The Command Rules, Skills and MCP Connections tests now cover the new controls: the list editor toolbar, the scope picker in the details, and the "⋯" menu.
- `tsrs --noEmit`, `oxfmt --check` and `oxlint` are clean on the changed files.
- Checked in the dev app (Islands Light): IDE MCP Server, Skills (collapsed and expanded rows), MCP Connections, Command Rules and Agent Setup.

## Merge Danger

**Door:** two-way

Presentation and copy only. Setting keys, stored values and backend calls are unchanged.

**Blast Radius:** settings-UI

The shared `SettingsPage.module.css` list styles now render one framed list instead of separate cards. They are used by Skills, MCP Connections and the Install Skill dialog (tags and errors only). Skill scope is now picked in the expanded row; the default scope logic is unchanged.
2026-11-26 20:56:32 +08:00
l0ng-ai 5265455313 fix(mcp): let stop_run stop a run execute_run_configuration left running (#6183)
A run execute_run_configuration started and left running had no handle: it is not an agent
tab, so stop_run, get_run_status and list_runs could not reach it, and only killing the process
ended it. While it runs, the result now carries runId, and stop_run accepts that id (only for
runs this tool started, not the user's own).

Fixes #6127
2026-11-26 20:48:40 +08:00
l0ng-ai 64cc72ba2e fix(agent): resume Claude sessions recorded under another CLAUDE_CONFIG_DIR (#6091) 2026-11-26 20:48:37 +08:00
l0ng-ai b79dbae83f feat(agents): support drag-and-drop reordering in the Agents list (#6140)
## Summary
- Add manual drag-and-drop reordering for tasks within `Pinned`, custom groups, and status groups (`Running`, `Ready to Review`, `Archived`, etc.), with before/after insertion indicators and edge auto-scrolling.
- Support dropping tasks onto exact slots across compatible sections (pinning, moving into custom groups, or returning pinned/grouped tasks back to their matching status group), while rejecting incompatible status groups and disabling row reordering while searching.
- Support drag-and-drop reordering between custom group headers (`GROUP_DRAG`).
- Persist per-section manual order in `localStorage` (`TaskOrganize.order`), keeping manually ordered tasks stable across activity updates while placing newly added tasks at the top of the section.
- Open tasks on click release instead of `mousedown` so starting a drag does not open the dragged task's chat history, and allow initiating drag from anywhere on the 24px row.

## Testing
- `vitest run src/features/agents/organize.test.ts src/features/agents/AgentsView.test.tsx src/features/agents/unread.test.tsx` (90 passed)
- `oxlint` & `oxfmt` clean on all changed files
- `tsc --noEmit` passed

Made with [Cursor](https://cursor.com)
2026-11-26 20:46:14 +08:00
l0ng-ai e909c50fe4 fix(ui): use default arrow cursors on non-link controls across the IDE (#6167)
## Summary
- Align non-link UI controls across the IDE with desktop IDE cursor conventions (`cursor: default` for controls, reserving `cursor: pointer` for links and editor canvas/gutter jump markers), matching `src/styles/global.css`.
- **VCS / Diff / Merge**: switch split diff divider apply arrows (`>>` / `<<`), hunk gutter buttons, hover Revert button, commit-inclusion checkboxes (`.cm-include-hunk`), collapsed-lines toggle, PR review gutter `+` button, three-way merge op buttons, branch star button, and merge/rebase widget buttons to `default`; add `var(--bg-toolbar-hover)` hover background to diff divider arrows so interactivity stays clear.
- **Workbench / Tool Windows / Popups**: remove `cursor: pointer` from buttons, checkboxes, tabs, list items, sortable table headers, and disclosure toggles across Settings, Tools, Plugins, Deployment, Search, Todo, Run, Services (keeping `pointer` on `.portChipLink`), Database, GitHub, Notebook, Viewers, Debugger, and LSP popups.

## Test plan
- [x] Verified formatting and lint via `oxfmt` / `oxlint`
- [x] Ran `pnpm vitest run src/features/vcs src/editor/lsp` (245 test files, 3330 tests passing)

Made with [Cursor](https://cursor.com)
2026-11-26 20:43:02 +08:00
l0ng-ai da7125a944 fix(workbench): show ghost and insertion indicator when dragging project tabs (#6135)
## What and why

Reordering project window tabs in `WindowGroupTabs` previously gave almost no visual feedback: the dragged tab only dimmed in place (`opacity: 0.55`) with no drag ghost, no drop-target indicator, no grabbing cursor or `Escape` cancel, and it waited for the backend IPC round-trip before updating the tab order.

This switches `WindowGroupTabs` onto the shared pointer drag-and-drop pipeline (`startPointerDrag`, `registerDropTarget`, and `dropIndex`) matching tool window stripes and tab strips:
- Shows a translucent ghost following the pointer (dimming when outside the tab bar) while keeping the source tab dimmed in place (`opacity: 0.4`) and hiding hover close/detach buttons during the drag.
- Marks the exact drop target with a 2px `var(--accent)` vertical insertion line (omitted on adjacent no-op slots).
- Optimistically applies the new tab order on drop (rolling back via `refreshWindowGroup()` on failure), swallows the trailing `click`, cancels cleanly on `Escape`, and respects `dragRequiresAlt()`.

## How it was verified

- `pnpm vitest run src/workbench/WindowGroupTabs.test.tsx src/platform/windowGroups.test.ts` — 2 test files, 13 tests passed.
- `OPENIDEA_E2E_PORT=1459 pnpm e2e e2e/windowGroupTabDrag.spec.ts e2e/windowGroupTabColor.spec.ts` — 2 Playwright E2E specs passed (both new drag feedback/reorder/cancel coverage and existing tinted-tab hover regression).
- `pnpm typecheck` — passed across all workspace tsconfigs including `e2e`.
- `pnpm exec oxfmt --check src/workbench/WindowGroupTabs.tsx src/workbench/WindowGroupTabs.module.css src/workbench/WindowGroupTabs.test.tsx e2e/windowGroupTabDrag.spec.ts` — passed.

## Review focus

- `projectTabDropTarget` mapping between `dropIndex` (`0..count`) and `reorderedTabs` target indices in `src/workbench/WindowGroupTabs.tsx`.
- `.dropBefore::before` / `.dropAfter::after` styling in `src/workbench/WindowGroupTabs.module.css` alongside the existing tab separator rule.

Made with [Cursor](https://cursor.com)
2026-11-26 20:42:49 +08:00
l0ng-ai e54e309d61 feat(plugins): add select-all for optional permissions in consent dialog (#6162)
## Summary
- Add a tri-state "Allow all optional permissions" checkbox (with selected count, e.g. `1/3`) at the top of the plugin install/grant consent dialog when a plugin declares two or more optional capabilities.
- Clicking toggles all optional permissions on/off in one click and automatically updates the high-risk warning state.
- Hide the select-all header when there is at most one optional permission.
- Add translations across all text locale catalogs and unit tests covering indeterminate/checked/unchecked transitions and single-optional hiding.

## Testing
- `vitest run src/features/plugins/__tests__/plugins.test.tsx src/platform/locales/textCatalog.test.ts` (153 passed)
- `oxfmt --check` on all changed files
- `tsc --noEmit`

Made with [Cursor](https://cursor.com)
2026-11-26 20:42:40 +08:00
l0ng-ai 8c3371212c fix(agents): remove icon from Pinned group header (#6161)
## Summary
- Remove the `pin` icon from the `Pinned` group header in the Agents task list so it aligns cleanly with the other group headers (`Ready to Review`, `Archived`, and custom groups).
- Clean up the now-unused `icon` prop on `GroupRow` and the unused `IconName` import.

## Test plan
- [x] `pnpm test src/features/agents/AgentsView.test.tsx` (41 passed)

Made with [Cursor](https://cursor.com)
2026-11-26 20:42:31 +08:00
Ainul YaqinтаAkin01 e08531c458 feat(plugins): project-scoped debounce and supersession for plugin refresh work (API 1.18) (#5002)
events.subscribe-paths-with-options adds an optional debounce-ms (up to 5 s) that coalesces files-changed deltas on the host, so bursts of edits don't run a plugin's discovery again and again. workspace.project.generation returns a project's state generation, which moves on every file change; FilesChanged carries the project root and generation. Registering run targets or run configurations computed for a superseded generation fails with Error::Stale. A new project-closed event tells subscribed plugins a project closed after its queued events are dropped and its run targets and configurations are withdrawn.

On top of the contributor's work: closing one project no longer cancels a plugin instance's in-flight work for other projects (an instance serves every project; results for the closed one are refused because its generation moved on), the generation is bumped on close, the generation is attached only for plugins declaring API 1.18 so older plugins' registrations are never refused, and the API now ships as part of 1.18 with the components rebuilt.

Closes #4760

Co-authored-by: Akin01 <[email protected]>
2026-11-26 20:41:06 +08:00
l0ng-ai 9c9e0e59cb feat(plugins): dialogs, package web pages in a modal IDE dialog (API 1.18) (#6178)
[[contributes.dialogs]] declares a package web page shown in a modal IDE dialog with the platform title bar, a declared size (320-1600 x 200-1200) and a title. The plugin's code opens it with views.reveal(id) in the invoking window, with no new capability. The user resizes it (remembered per dialog) and closes it with the close button or Escape, also from inside the page; the page can close it with openidea.dialog.close(). The plugin hears of the close as a closed view event. Dialog ids can't collide with the plugin's view ids.

With overlays (#6046) for non-modal pages, this covers #6012.

Fixes #6012
2026-11-26 20:18:01 +08:00
l0ng-ai 1d5d33cf76 fix(vcs): use text cursor in read-only diff and merge viewer panes (#6131)
Read-only diff, merge and revision viewer panes showed the arrow cursor over code text: the
viewer theme made .cm-content selectable but left the body's default cursor. It now sets
cursor: text there, keeping the arrow on scrollbars and gutters.
2026-11-26 20:11:10 +08:00
Anka Tamaтаxirf 2bbba9b945 feat(plugins): overlays, web pages floating over the workbench (API 1.18) (#6046)
[[contributes.overlays]] declares a package web page that floats over the workbench at one of nine anchors while its when clause holds. It never takes the keyboard focus when shown (out of the tab order), sits under dialogs, popups and notifications, and can let every click through (interactive = false). The page moves and resizes itself with openidea.overlay.get() / place({ anchor, width, height }); sizes are clamped to 40-800 px. It needs no code and no capability, since the page sees nothing of the IDE.

Overlays are gated on plugin API 1.18.0 (package openidea:[email protected].0, engine, SDK, api_compat, rebuilt components); 1.17 is listed as shipped with 0.1.53.

Part of #6012

Co-authored-by: xirf <[email protected]>
2026-11-26 20:11:03 +08:00
l0ng-ai 14f143b703 fix(vcs): load no Amend message with several repositories (#6175)
With several roots, Amend loaded the HEAD message of the repository last selected in the branch
widget, log or push dialog, whatever the included files were, and the commit then amended every
included repository with it. The commit to amend is ambiguous there: no message is loaded, and
the typed one amends each repository's HEAD.

Fixes #6149
2026-11-26 20:09:19 +08:00
Alexis f2a372428c fix(vcs): select a Push dialog repository row without unticking it (#6169)
In the multi-repository Push dialog, clicking a repository row to see its outgoing files also
unticked it, because the row's click toggled the checkbox. A click on the row or its name now
only selects it; the checkbox, or Space on the selected row, includes or excludes it.

Closes #6151

Co-authored-by: Rhombicdodecahedron <[email protected]>
2026-11-26 19:32:33 +08:00
faysouтаfaysou 89524bd583 fix(markdown): show Structure for large files (#6164)
Markdown files above the 5 MiB large-file threshold showed no symbols in Structure: the
large-file outline returned nothing when no language server supplied symbols. Large Markdown
files now get the heading outline from the syntax parser, within its own 16 MiB limit; other
large-file limits stay in place.

Co-authored-by: faysou <[email protected]>
2026-11-26 19:31:03 +08:00
l0ng-ai f90d94538d fix(debugger): use the spacing token for the frames error gap (#6172)
#6158 added a raw 6px gap to the frames error note, which the spacing scale test rejects on main; it now uses var(--space-1-5).
2026-11-26 19:27:47 +08:00
1192 змінених файлів з 58333 додано та 6058 видалено

No files matched your search

+7 -6
Переглянути файл
@@ -3,7 +3,8 @@ name: Homebrew
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
# and without the HOMEBREW_TAP_DEPLOY_KEY secret (the private half of a write deploy key on
# l0ng-ai/homebrew-tap).
on:
workflow_call:
inputs:
@@ -27,17 +28,17 @@ jobs:
env:
TAG: ${{ inputs.tag }}
TAP: l0ng-ai/homebrew-tap
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
GH_TOKEN: ${{ github.token }}
steps:
- name: Check tag and token
- name: Check tag and deploy key
id: check
run: |
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "::notice::$TAG is not a stable release: the cask stays as is"
echo "skip=true" >> "$GITHUB_OUTPUT"
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
elif [ -z "$HOMEBREW_TAP_DEPLOY_KEY" ]; then
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v5
@@ -47,7 +48,7 @@ jobs:
if: steps.check.outputs.skip != 'true'
with:
repository: ${{ env.TAP }}
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
path: tap
- uses: actions/setup-node@v5
if: steps.check.outputs.skip != 'true'
+1 -1
Переглянути файл
@@ -179,7 +179,7 @@ jobs:
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
secrets: inherit
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
homebrew:
needs: publish
uses: ./.github/workflows/homebrew.yml
Створено
+254 -197
File diff suppressed because it is too large. Load diff
+2 -2
Переглянути файл
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
exclude = ["sdk", "plugins"]
[workspace.package]
version = "0.1.53"
version = "0.1.54"
edition = "2024"
rust-version = "1.96"
license = "Apache-2.0"
@@ -108,7 +108,7 @@ jupyter-zmq-client = { version = "=2.0.0", default-features = false, features =
jupyter-protocol = "=2.0.3"
zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] }
lsp-types = "0.97"
gix = { version = "0.89", default-features = false }
gix = { version = "0.90", default-features = false }
portable-pty = "0.9"
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
+7
Переглянути файл
@@ -6,6 +6,12 @@
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## DuckDB symbol
DuckDB is a trademark of the DuckDB Foundation. The data source icon uses the
light and dark symbols from the [DuckDB Design Manual](https://duckdb.org/design/manual/#logo-usage).
The SVG paths and colors are preserved. See the [DuckDB trademark guidelines](https://duckdb.org/trademark_guidelines.html).
## Agent logos
The `src/ui/openidea/agents/` logos of agents listed in the
@@ -149,6 +155,7 @@ languages whose JetBrains icons are not open source (Go, Ruby, Dart, Lua, Zig,
Svelte, …). Those using the page-with-corner-badge layout (`goMod`, `goWork`,
`dotenv`, `readme`, `lock`, `license`) reuse the page outline of the Apache-2.0
expui `fileTypes/h.svg`; that outline is modified from the original by JetBrains.
`goTest` adds a scaled copy of the Apache-2.0 expui `nodes/test.svg` as its badge.
`src/ui/openidea/runConfigurations/springBoot*.svg` (the Spring Boot run configuration
leaf) is OpenIDEA's own drawing.
+1 -1
Переглянути файл
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
Err(err)
if !prefer_stored
&& crate::provider::is_copilot_provider(&spec.id)
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
&& super::auth_required(0, &err) =>
{
let retry = run_once(shared, spec, true, model).await;
+48
Переглянути файл
@@ -283,6 +283,20 @@ impl AgentCatalogs {
}
}
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
let key = Self::key(shared, provider);
let mut state = self.state.lock();
if let Some(entry) = state.entries.get_mut(&key)
&& entry.flight.is_none()
&& entry.error.is_some()
{
entry.completed = None;
entry.retry_at_ms = None;
entry.error = None;
}
}
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
let catalog = entry.catalog.clone().unwrap_or_default();
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
@@ -613,6 +627,40 @@ impl crate::AgentManager {
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
}
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
.into_iter()
.find(|p| p.id == "copilot")
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
let account = account.trim();
if !account.is_empty() {
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
}
match discover(&self.shared, spec, model).await {
Ok(found) => Ok(AgentModelCatalog {
provider: "copilot".into(),
config: self.shared.config_for_new_task(found.config, "copilot"),
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
refreshing: false,
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
retry_at_ms: None,
error: None,
}),
Err(error) => Ok(AgentModelCatalog {
provider: "copilot".into(),
config: Vec::new(),
thought_levels: BTreeMap::new(),
refreshing: false,
refreshed_at_ms: None,
retry_at_ms: None,
error: Some(error),
}),
}
}
}
async fn discover(
+11 -1
Переглянути файл
@@ -155,13 +155,14 @@ pub(crate) fn is_fast_option(id: &str) -> bool {
}
/// Whether an option's available values and default belong to the selected model
/// (`thought_level`, `context_tier`, and `model_config` options like `context` and `fast`)
/// (`thought_level`, `context_tier`, and `model_config` options like `context`, `fast` and `service_tier`)
/// rather than the provider as a whole.
pub(crate) fn is_per_model_option(o: &AgentConfigOption) -> bool {
matches!(o.category.as_deref(), Some("thought_level" | "context_tier" | "model_config"))
|| matches!(o.id.as_str(), "effort" | "reasoning_effort" | "thinking" | "reasoning")
|| is_fast_option(&o.id)
|| is_context_option(&o.id)
|| o.id == "service_tier"
}
/// A `configOptions` array; only select options are kept (the UI shows them as dropdowns).
@@ -531,6 +532,15 @@ mod tests {
assert_eq!(ids(&c), [("allow_all", Some("off")), ("approval", Some("ask"))]);
}
#[test]
fn service_tier_is_per_model() {
let options = options_of(&json!({ "configOptions": [
{ "id": "service_tier", "type": "select", "currentValue": "false",
"options": [{ "value": "false" }, { "value": "true" }] }
] }));
assert!(is_per_model_option(&options[0]));
}
#[test]
fn effort_context_and_fast_are_per_model_options() {
let mut c = options_of(&json!({
+379 -53
Переглянути файл
@@ -33,6 +33,7 @@ pub use catalogs::AgentCatalogs;
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
pub use external::ExternalSession;
pub use model::*;
pub use provider::{LoginLaunch, gh_authenticated_accounts, gh_login_launch};
pub use skill_installer::{
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
SkillScanWarning, SkillScanWarningKind,
@@ -53,6 +54,49 @@ use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Weak};
use std::time::Duration;
/// Resolves agent `id`'s interactive sign-in command without an open project.
pub fn login_launch_without_project(
custom_agents_dir: Option<&Path>,
secrets: Option<&dyn EnvSecrets>,
cwd: &Path,
id: &str,
) -> IdeResult<LoginLaunch> {
let spec = provider::load(custom_agents_dir, secrets)
.into_iter()
.find(|p| p.id == id)
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
spec.login_launch(cwd, None)
.ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name)))
}
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
pub async fn copilot_auth_status_with(
custom_agents_dir: Option<&Path>,
secrets: Option<&dyn EnvSecrets>,
cwd: &Path,
) -> CopilotAuthStatus {
let copilot_spec = provider::load(custom_agents_dir, secrets).into_iter().find(|p| p.id == "copilot");
let cwd_buf = cwd.to_path_buf();
let cli_fut = async move {
let spec = copilot_spec?;
native::copilot::probe_auth_status(spec, cwd_buf).await
};
let gh_fut = tokio::task::spawn_blocking(provider::gh_authenticated_accounts);
let (cli, gh) = tokio::join!(cli_fut, gh_fut);
let (gh_installed, gh_accounts) = gh.unwrap_or((false, Vec::new()));
match cli {
Some(cli) => CopilotAuthStatus {
authenticated: cli.authenticated,
login: cli.login,
auth_type: cli.auth_type,
status_message: cli.status_message,
gh_installed,
gh_accounts,
},
None => CopilotAuthStatus { gh_installed, gh_accounts, ..CopilotAuthStatus::default() },
}
}
/// Receives the events of one project's tasks.
pub type AgentSink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
@@ -201,6 +245,8 @@ struct Shared {
providers: RwLock<Vec<provider::ProviderSpec>>,
/// Last probe of each provider.
probes: Mutex<HashMap<String, AgentProbe>>,
/// `type: "terminal"` login arguments reported during `initialize`, by provider id.
terminal_auth_args: RwLock<HashMap<String, Vec<String>>>,
/// Copilot CLI installs where `--headless` failed and fell back to `--acp`.
copilot_acp_fallback: Mutex<HashSet<CopilotBinaryKey>>,
/// [`IDLE_RELEASE`], in milliseconds (shorter in tests).
@@ -450,10 +496,42 @@ struct TaskFile {
/// The user named the task: its agent's own title updates no longer replace it.
#[serde(default, skip_serializing_if = "is_false")]
title_renamed: bool,
/// [`NewAgentTask::ephemeral`]: the task file is never written, and new sessions ask the
/// agent not to save their history.
#[serde(default, skip_serializing_if = "is_false")]
ephemeral: bool,
/// Start the first session as a fork of a recorded native one (once).
#[serde(default, skip_serializing_if = "Option::is_none")]
pending_native_fork: Option<ForkStart>,
}
/// A session to start as a fork of the recorded one: its source, and the id the host
/// chooses for the fork (claude); codex assigns its own.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ForkStart {
source: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
target: Option<String>,
}
/// A canonical lowercase UUID, the only session id shape either native agent writes.
fn canonical_uuid(value: &str) -> bool {
value.len() == 36
&& value.bytes().enumerate().all(|(index, byte)| {
if matches!(index, 8 | 13 | 18 | 23) {
byte == b'-'
} else {
byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)
}
})
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct PendingModel {
/// Native Codex intent, including when this model cannot expose a Fast control.
#[serde(default, skip_serializing_if = "Option::is_none")]
retained_service_tier: Option<AgentConfigChoice>,
model: AgentConfigChoice,
candidate: Option<AgentConfigValue>,
options: Vec<AgentConfigOption>,
@@ -469,6 +547,11 @@ impl PendingModel {
});
wanted.push(self.model.clone());
wanted.extend(self.choices.iter().cloned());
if let Some(choice) = &self.retained_service_tier
&& !wanted.iter().any(|c| c.id == choice.id)
{
wanted.push(choice.clone());
}
}
}
@@ -502,6 +585,10 @@ struct TaskState {
pending_rollback: u32,
/// The user named the task; see `TaskFile::title_renamed`.
title_renamed: bool,
/// [`NewAgentTask::ephemeral`].
ephemeral: bool,
/// See `TaskFile::pending_native_fork`: cleared once a session is established.
pending_native_fork: Option<ForkStart>,
/// A turn is running or about to (prompts arriving now are queued).
busy: bool,
/// Background tasks the agent reported as running (`run_in_background` commands and
@@ -527,7 +614,12 @@ impl TaskState {
}
task.config.retain(|o| !config::is_per_model_option(o));
task.config.extend(pending.options.iter().cloned().map(|mut option| {
if let Some(choice) = pending.choices.iter().find(|choice| choice.id == option.id) {
if let Some(choice) = pending
.choices
.iter()
.chain(pending.retained_service_tier.iter())
.find(|choice| choice.id == option.id)
{
option.current = Some(choice.value.clone());
}
option
@@ -660,6 +752,7 @@ impl AgentManager {
known,
providers,
probes: Mutex::new(HashMap::new()),
terminal_auth_args: RwLock::new(HashMap::new()),
copilot_acp_fallback: Mutex::new(HashSet::new()),
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
mcp_servers_hook: RwLock::new(None),
@@ -739,16 +832,24 @@ impl AgentManager {
*self.shared.git_executable.write() = Some(hook);
}
/// Directory holding linked Git worktrees created for agent tasks of this project.
pub fn worktrees_dir(&self) -> &Path {
&self.shared.paths.worktrees_dir
}
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
pub fn providers(&self) -> Vec<AgentProvider> {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
let in_use: std::collections::HashSet<String> =
self.tasks.read().values().map(|t| t.state.lock().task.provider.clone()).collect();
let terminal_auth = self.shared.terminal_auth_args.read();
let list = specs
.iter()
.filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id))
.map(|p| {
let mut info = provider::describe(p);
info.can_sign_in =
p.can_sign_in(&self.shared.paths.project_root, terminal_auth.get(&p.id).map(Vec::as_slice));
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
@@ -756,6 +857,7 @@ impl AgentManager {
info
})
.collect();
drop(terminal_auth);
let mut prev = self.shared.providers.write();
let mut probes = self.shared.probes.lock();
probes.retain(|id, _| {
@@ -769,6 +871,35 @@ impl AgentManager {
list
}
/// Resolves the interactive sign-in command for agent `id`.
pub fn login_launch(&self, id: &str) -> IdeResult<LoginLaunch> {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
let spec = specs
.into_iter()
.find(|p| p.id == id)
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
let terminal_args = self.shared.terminal_auth_args.read().get(id).cloned();
let launch = spec.login_launch(&self.shared.paths.project_root, terminal_args.as_deref()).ok_or_else(|| {
IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name))
})?;
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, id);
Ok(launch)
}
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
pub async fn copilot_auth_status(&self) -> CopilotAuthStatus {
let status = copilot_auth_status_with(
self.shared.paths.custom_agents_dir.as_deref(),
self.shared.env_secrets(),
&self.shared.paths.project_root,
)
.await;
if status.authenticated || !status.gh_accounts.is_empty() {
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, "copilot");
}
status
}
/// Overrides built-in `id`'s command with `command` (the driver and arguments stay
/// the built-in's) through its agent file, or returns it to auto-detection with `None`.
pub fn set_builtin_command(&self, id: &str, command: Option<String>) -> IdeResult<()> {
@@ -778,12 +909,22 @@ impl AgentManager {
provider::set_builtin_command(&dir, self.shared.env_secrets(), id, command.as_deref())
}
/// Sets the extra arguments of a directly launched built-in ACP agent; empty resets them.
pub fn set_builtin_additional_args(&self, id: &str, args: Vec<String>) -> IdeResult<()> {
let Some(dir) = self.shared.paths.custom_agents_dir.as_deref() else {
return Err(IdeError::unavailable("there is no custom agents directory"));
};
provider::set_builtin_additional_args(dir, self.shared.env_secrets(), id, args)
}
/// Sets the environment variables built-in `id` starts with; empty clears them.
pub fn set_builtin_env(&self, id: &str, env: std::collections::BTreeMap<String, String>) -> IdeResult<()> {
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
return Err(IdeError::unavailable("there is no custom agents directory"));
};
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)?;
self.shared.paths.catalogs.evict_if_idle(&self.shared, id);
Ok(())
}
/// Saves a new custom ACP agent through its agent file.
@@ -1023,6 +1164,94 @@ impl AgentManager {
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: true,
ephemeral: false,
pending_native_fork: None,
};
let handle = Task::restore(file, self.shared.clone());
self.tasks.write().insert(task.id.clone(), handle.clone());
handle.emit_task();
handle.persist();
Ok(task)
}
/// Forks a recorded external session into a new task: its first turn continues the
/// recording as the agent's own fork, under an id the host chooses. The session must
/// belong to this project and have been recorded in `cwd`.
pub fn fork_session(&self, provider: &str, session_id: &str, cwd: &Path) -> IdeResult<AgentTask> {
if !matches!(provider, "claude" | "codex") {
return Err(IdeError::invalid(format!("cannot fork {provider} sessions")));
}
if !canonical_uuid(session_id) {
return Err(IdeError::invalid("the recorded session has no canonical id"));
}
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
if self.imported_session_ids().contains(session_id) {
return Err(IdeError::invalid("that session is already a task"));
}
let found = self
.external_sessions()
.into_iter()
.find(|s| s.provider == provider && s.session_id == session_id)
.ok_or_else(|| IdeError::not_found(format!("unknown {provider} session {session_id}")))?;
let recorded = found
.cwd
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.ok_or_else(|| IdeError::invalid("the recorded session has no working directory"))?;
let canonical = |p: &Path| dunce::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
if canonical(cwd) != canonical(&recorded) {
return Err(IdeError::invalid("the session was recorded in another directory"));
}
let root = self.shared.paths.project_root.clone();
let config = self.shared.known_config(&spec.id);
let now = now_ms();
let id = uuid::Uuid::new_v4().simple().to_string();
// The host names the fork's session id for claude; codex assigns its own.
let target = (provider == "claude").then(|| uuid::Uuid::new_v4().to_string());
let task = AgentTask {
project_root: Some(IpcPath(root)),
id,
title: found.title,
provider: spec.id.clone(),
model: model_of(&config),
status: AgentStatus::Ready,
isolation: Isolation::Local,
cwd: IpcPath(recorded),
branch: None,
base: None,
base_commit: None,
error: None,
created_ms: now,
updated_ms: now,
config,
commands: self.shared.known_commands(&spec.id),
usage: None,
queue: Vec::new(),
capabilities: self.shared.probes.lock().get(&spec.id).map(|p| p.capabilities).unwrap_or_default(),
resets_ms: None,
retry: None,
background: Box::default(),
mcp_overrides: BTreeMap::new(),
skill_overrides: BTreeMap::new(),
stats: Box::default(),
};
let file = TaskFile {
task: task.clone(),
session_id: target.clone(),
entries: Vec::new(),
wanted: Vec::new(),
pending_model: None,
pending_switch: None,
before: BTreeMap::new(),
saved: None,
touched: Some(BTreeSet::new()),
turn: None,
turns: Vec::new(),
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: true,
ephemeral: false,
pending_native_fork: Some(ForkStart { source: session_id.to_owned(), target }),
};
let handle = Task::restore(file, self.shared.clone());
self.tasks.write().insert(task.id.clone(), handle.clone());
@@ -1151,6 +1380,8 @@ impl AgentManager {
subagents: Vec::new(),
pending_rollback: 0,
title_renamed: false,
ephemeral: req.ephemeral,
pending_native_fork: None,
};
let handle = Task::restore(file, self.shared.clone());
handle.state.lock().busy = !req.idle;
@@ -1516,6 +1747,8 @@ impl AgentManager {
subagents: s.conversation.saved_subagents(),
pending_rollback: total - keep,
title_renamed: s.title_renamed,
ephemeral: s.ephemeral,
pending_native_fork: None,
}
};
// Copying may have started the source's agent: it stops again once idle.
@@ -2386,7 +2619,7 @@ impl Task {
turns.push(Some(Arc::new(last)));
}
let mut wanted = file.wanted;
let pending_model = file.pending_switch.or_else(|| {
let mut pending_model = file.pending_switch.or_else(|| {
let id = file.pending_model?;
let index = wanted.iter().position(|choice| choice.id == id)?;
let model = wanted.remove(index);
@@ -2401,8 +2634,14 @@ impl Task {
.and_then(|o| o.values.iter().find(|v| v.value == model.value))
.cloned();
let options = catalog.thought_levels.get(&model.value).cloned().unwrap_or_default();
Some(PendingModel { model, candidate, options, choices: Vec::new() })
Some(PendingModel { model, candidate, options, choices: Vec::new(), retained_service_tier: None })
});
if let Some(pending) = &mut pending_model
&& pending.retained_service_tier.is_none()
&& shared.spec(&task.provider).is_some_and(|spec| spec.driver == provider::Driver::Codex)
{
pending.retained_service_tier = wanted.iter().find(|c| c.id == "service_tier").cloned();
}
Arc::new(Self {
id: task.id.clone(),
shared,
@@ -2420,6 +2659,8 @@ impl Task {
turns,
pending_rollback: file.pending_rollback,
title_renamed: file.title_renamed,
ephemeral: file.ephemeral,
pending_native_fork: file.pending_native_fork,
busy: false,
background_tasks: Vec::new(),
shell_context: Vec::new(),
@@ -2675,7 +2916,9 @@ impl Task {
let mut file = self.file.lock();
// Read before the copy: whatever was asked for up to now is in it.
let asked = self.saves_asked.load(Ordering::Acquire);
if file.deleted || file.saved >= asked {
// A throwaway task is never written: one its caller couldn't delete (a window closed
// while it ran) is gone after a restart.
if file.deleted || file.saved >= asked || self.state.lock().ephemeral {
return;
}
let copy = {
@@ -2695,6 +2938,8 @@ impl Task {
subagents: s.conversation.saved_subagents(),
pending_rollback: s.pending_rollback,
title_renamed: s.title_renamed,
ephemeral: s.ephemeral,
pending_native_fork: s.pending_native_fork.clone(),
}
};
let bytes = serde_json::to_vec(&copy);
@@ -2975,7 +3220,13 @@ impl Task {
.filter(|pending| pending.model.value == value)
.map(|pending| pending.choices)
.unwrap_or_default();
let retained_service_tier = self
.shared
.spec(&provider)
.filter(|spec| spec.driver == provider::Driver::Codex)
.and_then(|_| s.wanted.iter().find(|c| c.id == "service_tier").cloned());
s.pending_model = Some(PendingModel {
retained_service_tier,
model: AgentConfigChoice { id: target.id, value },
candidate: Some(candidate),
options,
@@ -3345,6 +3596,14 @@ impl Task {
let is_auth = matches!(&e, RpcError::Server { code, message, .. } if acp::auth_required(*code, message));
SessionOpenError { message: self.describe(e), allow_acp_fallback: !is_auth }
})?;
if let Some(args) = init.auth_methods.iter().find_map(|method| {
if method.get("type").and_then(Value::as_str) != Some("terminal") {
return None;
}
method.get("args")?.as_array()?.iter().map(|v| v.as_str().map(str::to_owned)).collect::<Option<Vec<_>>>()
}) {
self.shared.terminal_auth_args.write().insert(provider_id.to_owned(), args);
}
let sign_in_message = spec.sign_in_message(&init.auth_methods);
let can_load = init.load_session();
let (capabilities, embedded) = capabilities_of(&init);
@@ -3357,66 +3616,116 @@ impl Task {
let skills_delivery = self.stage_skills(stage_key(spec.driver), cwd).await;
// Agents that compare canonical paths fail in a symlinked directory (macOS `/tmp`).
let cwd_s = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf()).to_string_lossy().into_owned();
let pending_native_fork = self.state.lock().pending_native_fork.clone();
let mut opening_params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
if spec.driver == provider::Driver::Codex {
let s = self.state.lock();
let mut wanted = s.wanted.clone();
if let Some(pending) = pending_model {
pending.apply(&mut wanted, &s.task.config);
}
// Restore intent even when the resumed model cannot expose the Fast control.
if let Some(fast) =
wanted.iter().find(|c| c.id == "service_tier").and_then(|c| c.value.parse::<bool>().ok())
{
opening_params["_meta"]["openidea"]["codexFast"] = json!(fast);
}
}
let mut tried_auth = false;
let mut session = None;
let start_fresh = self.start_fresh.load(Ordering::Acquire);
if pending_model.is_some() && (saved.is_none() || !can_load || start_fresh) {
return Err(SessionOpenError {
message: "The agent does not support resuming this session.".into(),
allow_acp_fallback: false,
});
}
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
// The replay goes before what this turn already showed (the user's message).
let shown = self.adopts_replay().then(|| self.take_entries());
self.replaying.store(true, Ordering::Release);
let mut params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
params["sessionId"] = json!(&id);
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
tokio::time::sleep(REPLAY_GRACE).await;
self.replaying.store(false, Ordering::Release);
if let Some(shown) = shown {
if loaded.is_ok() {
self.adopting_replay.store(false, Ordering::Release);
let changed = self.state.lock().conversation.end_turn(None);
self.mark_dirty(changed);
} else {
// A failed load may still have replayed part of it.
self.take_entries();
}
for entry in shown {
self.push_entry(entry);
if let Some(fork) = pending_native_fork {
if !capabilities.fork {
return Err(SessionOpenError {
message: "the agent can't continue a recorded session".into(),
allow_acp_fallback: false,
});
}
let mut params = opening_params.clone();
params["sessionId"] = json!(&fork.source);
if let Some(target) = &fork.target {
match params["_meta"].as_object_mut() {
Some(meta) => {
if let Some(openidea) = meta.entry("openidea").or_insert_with(|| json!({})).as_object_mut() {
openidea.insert("forkSessionId".into(), json!(target));
}
}
None => params["_meta"] = json!({ "openidea": { "forkSessionId": target } }),
}
}
match loaded {
Ok(v) => session = Some((id, v)),
// Not silently: a new session would lose the conversation and replace the saved id.
Err(e) => {
tracing::info!("agent task {}: session/load failed: {e}", self.id);
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
return Err(SessionOpenError { message, allow_acp_fallback: false });
let reply = self
.request_with_auth(&peer, &init, &mut tried_auth, "session/fork", params)
.await
.map_err(|e| SessionOpenError { message: self.describe(e), allow_acp_fallback: false })?;
let id = reply
.get("sessionId")
.and_then(Value::as_str)
.ok_or_else(|| SessionOpenError {
message: "the agent returned no session".into(),
allow_acp_fallback: false,
})?
.to_owned();
session = Some((id, reply));
} else {
let start_fresh = self.start_fresh.load(Ordering::Acquire);
if pending_model.is_some() && (saved.is_none() || !can_load || start_fresh) {
return Err(SessionOpenError {
message: "The agent does not support resuming this session.".into(),
allow_acp_fallback: false,
});
}
if let (Some(id), true, false) = (saved, can_load, start_fresh) {
// The replay goes before what this turn already showed (the user's message).
let shown = self.adopts_replay().then(|| self.take_entries());
self.replaying.store(true, Ordering::Release);
let mut params = opening_params.clone();
params["sessionId"] = json!(&id);
let loaded = self.request_with_auth(&peer, &init, &mut tried_auth, "session/load", params).await;
tokio::time::sleep(REPLAY_GRACE).await;
self.replaying.store(false, Ordering::Release);
if let Some(shown) = shown {
if loaded.is_ok() {
self.adopting_replay.store(false, Ordering::Release);
let changed = self.state.lock().conversation.end_turn(None);
self.mark_dirty(changed);
} else {
// A failed load may still have replayed part of it.
self.take_entries();
}
if pending_model.is_some() {
for entry in shown {
self.push_entry(entry);
}
}
match loaded {
Ok(v) => session = Some((id, v)),
// Not silently: a new session would lose the conversation and replace the saved id.
Err(e) => {
tracing::info!("agent task {}: session/load failed: {e}", self.id);
if let Some(message) = self.sign_in_error(&e, Some(&sign_in_message)) {
return Err(SessionOpenError { message, allow_acp_fallback: false });
}
if pending_model.is_some() {
return Err(SessionOpenError {
message: format!(
"Couldn't reopen this conversation's {} session: {}",
spec.name,
self.describe(e)
),
allow_acp_fallback: false,
});
}
self.start_fresh.store(true, Ordering::Release);
return Err(SessionOpenError {
message: format!(
"Couldn't reopen this conversation's {} session: {}",
"Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \
continue in a new session. The agent won't see the earlier conversation.",
spec.name,
self.describe(e)
),
allow_acp_fallback: false,
});
}
self.start_fresh.store(true, Ordering::Release);
return Err(SessionOpenError {
message: format!(
"Couldn't reopen this conversation's {} session: {}\n\nSend the message again to \
continue in a new session. The agent won't see the earlier conversation.",
spec.name,
self.describe(e)
),
allow_acp_fallback: false,
});
}
}
}
@@ -3424,7 +3733,10 @@ impl Task {
let (session_id, result) = match session {
Some(s) => s,
None => {
let params = session_params(&cwd_s, &mcp_servers, skills_delivery.as_ref(), &roots);
let mut params = opening_params;
if self.state.lock().ephemeral {
mark_ephemeral(&mut params);
}
let v = self.request_with_auth(&peer, &init, &mut tried_auth, "session/new", params).await.map_err(
|e| match self.sign_in_error(&e, Some(&sign_in_message)) {
Some(msg) => SessionOpenError { message: msg, allow_acp_fallback: false },
@@ -3535,7 +3847,10 @@ impl Task {
if config::is_per_model_option(&o) && !model_options {
continue;
}
let already = (known || explicit) && o.current.as_deref() == Some(choice.value.as_str());
// A displayed tier can be inherited. Preserve an explicit Fast/Standard choice
// even when it currently looks the same, so subsequent turns receive the override.
let already =
o.id != "service_tier" && (known || explicit) && o.current.as_deref() == Some(choice.value.as_str());
if already || !o.values.iter().any(|v| v.value == choice.value) {
continue;
}
@@ -3604,6 +3919,8 @@ impl Task {
s.pending_model = None;
s.task.capabilities = capabilities;
s.session_id = Some(session_id.clone());
// The recorded session is forked (or the fork resumed): the one-shot intent is spent.
s.pending_native_fork = None;
self.start_fresh.store(false, Ordering::Release);
// The (re)started process runs nothing yet: whatever it reports next is all of it.
s.background_tasks = Vec::new();
@@ -4482,6 +4799,15 @@ fn session_params(cwd: &str, mcp: &McpForSession, skills: Option<&skills::Delive
params
}
/// `_meta.openidea.ephemeral` of `session/new`: the native drivers start the session without
/// saving it (Claude Code `--no-session-persistence`, Codex `ephemeral` threads).
fn mark_ephemeral(params: &mut Value) {
if !params["_meta"]["openidea"].is_object() {
params["_meta"]["openidea"] = json!({});
}
params["_meta"]["openidea"]["ephemeral"] = json!(true);
}
fn is_false(b: &bool) -> bool {
!*b
}
+38
Переглянути файл
@@ -612,6 +612,9 @@ pub struct AgentProvider {
/// Executable and arguments actually launched, without flattening paths containing spaces.
pub program: String,
pub args: Vec<String>,
/// Settings-managed suffix of `args`; absent for launches that cannot be edited.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub additional_args: Option<Vec<String>>,
pub default_program: Option<String>,
pub default_args: Vec<String>,
pub login_hint: Option<String>,
@@ -620,6 +623,9 @@ pub struct AgentProvider {
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
/// Whether the command was found (on `PATH`).
pub installed: bool,
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
#[serde(default)]
pub can_sign_in: bool,
/// The built-in command can be owned by a global npm package.
#[serde(default)]
pub can_check_cli_update: bool,
@@ -644,6 +650,34 @@ pub enum AgentCommandReadOnlyReason {
CustomAgent,
}
/// An authenticated `github.com` account stored in GitHub CLI (`gh`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct GhAuthAccount {
pub login: String,
pub active: bool,
}
/// GitHub Copilot's default sign-in status alongside the accounts available through `gh`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CopilotAuthStatus {
pub authenticated: bool,
pub login: Option<String>,
pub auth_type: Option<String>,
pub status_message: Option<String>,
pub gh_installed: bool,
pub gh_accounts: Vec<GhAuthAccount>,
}
/// Output and completion of an interactive sign-in PTY started by the IDE.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum AgentLoginEvent {
Output { data: String },
Exited { code: Option<i32> },
}
/// Where an agent comes from.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
@@ -700,6 +734,10 @@ pub struct NewAgentTask {
/// `!` command runs in it first.
#[serde(default)]
pub idle: bool,
/// A throwaway task (Generate Commit Message): it isn't saved, so it doesn't outlive a
/// restart, and the agent keeps no session history of its own for it.
#[serde(default)]
pub ephemeral: bool,
}
/// A file the task changed: against [`AgentTask::base_commit`], or against `HEAD` in the
+81
Переглянути файл
@@ -30,6 +30,67 @@ pub(super) fn transcript(config_dir: &Path, cwd: &Path, id: &str) -> PathBuf {
.unwrap_or(direct)
}
/// Brings session `id` into `config_dir` when it is missing there but another Claude Code
/// configuration directory beside it (`~/.claude`, `~/.claude-work`...) has it: switching
/// `CLAUDE_CONFIG_DIR` (another account) would otherwise lose every earlier conversation.
/// Copies the transcript and its folder (subagents, tool results) under the same project
/// directory name. Returns whether the session is in `config_dir` now.
pub(super) fn adopt(config_dir: &Path, cwd: &Path, id: &str) -> bool {
if transcript(config_dir, cwd, id).exists() {
return true;
}
let file = format!("{id}.jsonl");
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
let mut homes: Vec<PathBuf> = config_dir
.parent()
.into_iter()
.chain(home.as_deref())
.flat_map(|dir| std::fs::read_dir(dir).into_iter().flatten().flatten())
.filter(|d| d.file_name().to_string_lossy().starts_with(".claude"))
.map(|d| d.path())
.filter(|p| p != config_dir && p.join("projects").is_dir())
.collect();
homes.sort();
homes.dedup();
let found = homes.iter().find_map(|other| {
let projects = other.join("projects");
let direct = projects.join(escape(cwd));
std::iter::once(direct.clone())
.chain(std::fs::read_dir(&projects).into_iter().flatten().flatten().map(|d| d.path()))
.find(|dir| dir.join(&file).is_file())
});
let Some(source) = found else { return false };
let Some(name) = source.file_name() else { return false };
let target = config_dir.join("projects").join(name);
let copied = std::fs::create_dir_all(&target)
.and_then(|()| copy_tree(&source.join(id), &target.join(id)))
.and_then(|()| std::fs::copy(source.join(&file), target.join(&file)).map(drop));
match copied {
Ok(()) => true,
Err(e) => {
tracing::warn!("claude session {id}: copying it from {}: {e}", source.display());
false
}
}
}
fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {
if !from.is_dir() {
return Ok(());
}
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let dest = to.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy_tree(&entry.path(), &dest)?;
} else if !dest.exists() {
std::fs::copy(entry.path(), dest)?;
}
}
Ok(())
}
/// The project directory name Claude Code uses for `cwd`.
pub(crate) fn escape(cwd: &Path) -> String {
cwd.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()
@@ -207,6 +268,26 @@ mod tests {
json!({"type": "assistant", "uuid": id, "parentUuid": parent, "message": {"role": "assistant", "content": content}})
}
#[test]
fn a_session_from_another_config_dir_is_copied_in() {
let root = tempfile::tempdir().unwrap();
let (old, new) = (root.path().join(".claude-2"), root.path().join(".claude-3"));
let cwd = Path::new("/work/app");
let project = old.join("projects").join(escape(cwd));
std::fs::create_dir_all(project.join("s1/subagents")).unwrap();
std::fs::write(project.join("s1.jsonl"), "{}\n").unwrap();
std::fs::write(project.join("s1/subagents/a.jsonl"), "{}\n").unwrap();
std::fs::create_dir_all(new.join("projects")).unwrap();
assert!(!adopt(&new, cwd, "missing"));
assert!(adopt(&new, cwd, "s1"));
let copied = new.join("projects").join(escape(cwd));
assert_eq!(transcript(&new, cwd, "s1"), copied.join("s1.jsonl"));
assert!(copied.join("s1/subagents/a.jsonl").is_file());
assert!(project.join("s1.jsonl").is_file(), "the original stays");
assert!(adopt(&new, cwd, "s1"));
}
#[test]
fn the_newest_branch_is_the_conversation() {
let entries = vec![
+53 -19
Переглянути файл
@@ -178,6 +178,8 @@ struct Session {
additional_dirs: Vec<String>,
/// The staged skills' `--settings` JSON (`skillOverrides` for the native ones too).
skills_settings: Option<String>,
/// `_meta.openidea.ephemeral`: `--no-session-persistence`, nothing saved under `~/.claude`.
ephemeral: bool,
shim: Weak<Shim>,
st: Mutex<State>,
/// Serializes (re)starting the process.
@@ -334,6 +336,12 @@ impl Shim {
Some(history::transcript(self.config.config_dir.as_deref()?, cwd, id))
}
/// Whether session `id` is in the configuration directory, copied there from another one
/// if need be (see [`history::adopt`]).
fn adopt(&self, cwd: &Path, id: &str) -> bool {
self.config.config_dir.as_deref().is_some_and(|dir| history::adopt(dir, cwd, id))
}
/// The conversation a session started with `start` begins with.
fn base_chain(&self, cwd: &Path, start: &Start) -> Result<Vec<Value>, String> {
let (id, at) = match start {
@@ -370,6 +378,7 @@ impl Shim {
skills_add_dir: skills.and_then(|s| s.get("claudeAddDir")).and_then(Value::as_str).map(PathBuf::from),
additional_dirs: additional_dirs(params),
skills_settings: skills.and_then(|s| s.get("claudeSettings")).and_then(Value::as_str).map(str::to_owned),
ephemeral: params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool).unwrap_or(false),
shim: Arc::downgrade(self),
st: Mutex::new(State {
proc: None,
@@ -435,10 +444,13 @@ impl Shim {
let id = params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
let cwd = self.cwd_of(&params);
let (start, pending) = match self.load_pending(id) {
Some(s) => (s, true),
None if self.transcript(&cwd, id).is_some_and(|p| p.exists()) => {
(Start::Resume { id: id.to_owned(), at: None }, false)
Some(s) => {
if let Start::Resume { id: from, .. } | Start::Fork { from, .. } = &s {
self.adopt(&cwd, from);
}
(s, true)
}
None if self.adopt(&cwd, id) => (Start::Resume { id: id.to_owned(), at: None }, false),
None => return Err(invalid(format!("no Claude Code session {id} in {}", cwd.display()))),
};
let chain = self.base_chain(&cwd, &start).map_err(internal)?;
@@ -451,24 +463,43 @@ impl Shim {
Ok(json!({ "configOptions": session.st.lock().settings.options() }))
}
"session/fork" => {
let source = self.session(&params)?;
let id = new_uuid(false);
let (start, settings) = {
let st = source.st.lock();
let start = match &st.start {
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
}
Start::New { .. } => Start::New { id: id.clone() },
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
}
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
};
(start, st.settings.clone())
let source_id =
params.get("sessionId").and_then(Value::as_str).ok_or_else(|| invalid("no sessionId"))?;
let source = self.sessions.lock().get(source_id).cloned();
// The host names the fork's session id so the task knows it before the CLI
// starts; only a canonical UUID is accepted.
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
if let Some(target) = requested
&& !crate::canonical_uuid(target)
{
return Err(invalid("A fork session id must be a canonical UUID"));
}
let id = requested.map_or_else(|| new_uuid(false), str::to_owned);
if self.sessions.lock().contains_key(&id) {
return Err(invalid(format!("session {id} is already open")));
}
let cwd = source.as_ref().map_or_else(|| self.cwd_of(&params), |session| session.cwd.clone());
let (start, settings) = match &source {
Some(source) => {
let st = source.st.lock();
let start = match &st.start {
Start::New { .. } if !st.pending && st.titled_or_prompted() => {
Start::Fork { from: source.id.clone(), id: id.clone(), at: None }
}
Start::New { .. } => Start::New { id: id.clone() },
Start::Resume { id: from, at } | Start::Fork { from, at, .. } if st.pending => {
Start::Fork { from: from.clone(), id: id.clone(), at: at.clone() }
}
_ => Start::Fork { from: source.id.clone(), id: id.clone(), at: None },
};
(start, st.settings.clone())
}
// A recorded session is not open in this connection: the CLI forks it
// from its transcript on disk when the task's first prompt starts it.
None => (Start::Fork { from: source_id.to_owned(), id: id.clone(), at: None }, Settings::default()),
};
self.save_pending(&id, Some(&start));
let session = self.add_session(&id, source.cwd.clone(), start, true, &params);
let session = self.add_session(&id, cwd, start, true, &params);
session.st.lock().settings = settings;
let options = session.st.lock().settings.options();
Ok(json!({ "sessionId": id, "configOptions": options }))
@@ -703,6 +734,9 @@ impl Session {
if let Some(settings) = &self.skills_settings {
args.extend(["--settings".to_owned(), settings.clone()]);
}
if self.ephemeral {
args.push("--no-session-persistence".to_owned());
}
args.extend(start.args());
let launch =
Launch { program: shim.config.program.clone(), args, cwd: self.cwd.clone(), env: shim.config.env.clone() };
+92
Переглянути файл
@@ -464,6 +464,7 @@ async fn replay_simple() {
let args = r.cli.launched.lock()[0].clone();
assert!(args.windows(2).any(|w| w == ["--session-id", r.session.as_str()]), "{args:?}");
assert!(args.contains(&"--permission-prompt-tool".to_owned()));
assert!(!args.contains(&"--no-session-persistence".to_owned()));
let user = r.sent(0).into_iter().find(|m| m["type"] == "user").unwrap();
assert_eq!(user["message"]["content"][0]["text"], "Reply with exactly: hello there");
}
@@ -652,6 +653,84 @@ async fn replay_resume() {
assert!(args.windows(2).any(|w| w == ["--resume", r.session.as_str()]), "{args:?}");
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_can_start_a_recorded_session_under_the_hosts_id() {
/// Registering a fork must not start a process: its first prompt does.
struct NoLaunch;
impl Cli for NoLaunch {
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
panic!("session/fork must not launch the CLI")
}
}
let config = tempfile::tempdir().unwrap();
let pending = tempfile::tempdir().unwrap();
let h = Harness::connect(
Arc::new(NoLaunch),
config.path().to_path_buf(),
pending.path().to_path_buf(),
std::env::temp_dir(),
Vec::new(),
)
.await;
let source = "11111111-1111-4111-8111-111111111111";
let target = "22222222-2222-4222-8222-222222222222";
let reply = h
.request(
"session/fork",
json!({
"sessionId": source,
"cwd": h.cwd,
"mcpServers": [],
"_meta": { "openidea": { "forkSessionId": target } }
}),
)
.await
.unwrap();
assert_eq!(reply["sessionId"], target);
// The host chose this id for the fork: the next process must fork the recorded
// session under exactly it.
let saved: Value =
serde_json::from_slice(&std::fs::read(pending.path().join(format!("{target}.json"))).unwrap()).unwrap();
assert_eq!(saved, json!({ "fork": source, "id": target, "at": null }));
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_rejects_a_requested_id_that_is_not_canonical() {
struct NoLaunch;
impl Cli for NoLaunch {
fn launch(&self, _: &Launch, _: OnStderr) -> std::io::Result<cli::CliIo> {
panic!("no process")
}
}
let config = tempfile::tempdir().unwrap();
let pending = tempfile::tempdir().unwrap();
let h = Harness::connect(
Arc::new(NoLaunch),
config.path().to_path_buf(),
pending.path().to_path_buf(),
std::env::temp_dir(),
Vec::new(),
)
.await;
for rejected in ["../../x", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", ""] {
let error = h
.request(
"session/fork",
json!({
"sessionId": "11111111-1111-4111-8111-111111111111",
"cwd": h.cwd,
"mcpServers": [],
"_meta": { "openidea": { "forkSessionId": rejected } }
}),
)
.await
.expect_err("only a canonical id may name the fork");
assert!(error.to_string().contains("canonical"), "{rejected}: {error}");
}
}
// ---------- recording ----------
/// Passes the real CLI's stdio through, keeping what went over it.
@@ -1350,3 +1429,16 @@ fn additional_directories_are_read_from_the_session_params() {
assert_eq!(additional_dirs(&params), ["/w/web", "/w/docs"]);
assert!(additional_dirs(&json!({ "cwd": "/w/api" })).is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn an_ephemeral_session_is_not_saved() {
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": { "ephemeral": true } } });
h.request("session/new", params).await.unwrap();
let args = cli.launched.lock()[0].clone();
assert!(args.contains(&"--no-session-persistence".to_owned()), "{args:?}");
}
+18 -5
Переглянути файл
@@ -108,7 +108,7 @@ pub(crate) async fn discover(
let options = translate::config_options(&models, &settings);
let levels = crate::config::options_of(&json!({ "configOptions": options }))
.into_iter()
.filter(|o| o.category.as_deref() == Some("thought_level"))
.filter(|o| matches!(o.category.as_deref(), Some("thought_level" | "model_config")))
.collect();
(model.id.clone(), levels)
})
@@ -492,8 +492,14 @@ impl CodexShim {
self.prepare_project_trust(params).await;
let mut request = json!({ "cwd": params.get("cwd") });
apply_thread_config(params, &mut request);
// Not written to `~/.codex/sessions`, so it isn't listed among the past threads.
if params.pointer("/_meta/openidea/ephemeral").and_then(Value::as_bool) == Some(true) {
request["ephemeral"] = json!(true);
}
let result = self.call("thread/start", request).await?;
let (id, options) = self.open_thread(&result, &models, None);
let mut settings = Settings::of(&result, &models);
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
let (id, options) = self.open_thread(&result, &models, Some(settings));
if id.is_empty() {
return Err(error(codes::INTERNAL_ERROR, "codex started no thread"));
}
@@ -510,7 +516,9 @@ impl CodexShim {
let mut request = json!({ "threadId": id, "cwd": params.get("cwd") });
apply_thread_config(params, &mut request);
let result = self.call("thread/resume", request).await?;
let (_, options) = self.open_thread(&result, &models, None);
let mut settings = Settings::of(&result, &models);
settings.fast_override = params.pointer("/_meta/openidea/codexFast").and_then(Value::as_bool);
let (_, options) = self.open_thread(&result, &models, Some(settings));
let cwd = self.state.lock().threads.get(id).and_then(|t| t.cwd.clone());
let thread = result.get("thread").unwrap_or(&Value::Null);
for update in translate::history(thread, cwd.as_deref()) {
@@ -613,6 +621,9 @@ impl CodexShim {
if let Some(effort) = &s.effort {
request["effort"] = json!(effort);
}
if let Some(tier) = s.service_tier_override(&models) {
request["serviceTier"] = json!(tier);
}
}
self.call("turn/start", request).await
}
@@ -1470,14 +1481,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
let message = translate::error_message(&e);
return match translate::classify(&e, rate_limits) {
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
Failure::UsageLimit(resets) => Err(ResponseError {
code: codes::INTERNAL_ERROR,
message,
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
}),
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
};
}
_ => "end_turn",
@@ -1595,3 +1605,6 @@ fn mcp_text(response: &Value) -> String {
.collect::<Vec<_>>();
format!("MCP servers:\n{}", lines.join("\n"))
}
#[cfg(test)]
mod reconnect_tests;
+217
Переглянути файл
@@ -0,0 +1,217 @@
//! User-facing task operations through the native shim, with a local app-server stand-in.
use super::*;
use crate::{AgentManager, AgentPrompt, AgentStatus, Isolation, NewAgentTask};
#[derive(Default)]
struct Runtime {
models: Mutex<HashMap<String, String>>,
hide_a: std::sync::atomic::AtomicBool,
turns: Mutex<Vec<Value>>,
tiers: Mutex<HashMap<String, Value>>,
servers: Mutex<Vec<Peer>>,
}
struct Connection {
runtime: Arc<Runtime>,
peer: OnceLock<Peer>,
}
impl Handler for Connection {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, p: Value) -> Result<Value, (i64, String)> {
match method {
"initialize" => Ok(json!({})),
"model/list" => {
let mut data = vec![json!({"id":"b", "model":"b", "serviceTiers":[]})];
if !self.runtime.hide_a.swap(false, std::sync::atomic::Ordering::SeqCst) {
data.insert(0, json!({"id":"a", "model":"a", "isDefault":true, "serviceTiers":[{"id":"fast"}]}));
}
Ok(json!({"data":data}))
}
"config/read" => Ok(json!({"layers":[]})),
"skills/list" => Ok(json!({"data":[]})),
"thread/start" | "thread/resume" => {
let mut models = self.runtime.models.lock();
let id = p["threadId"].as_str().map(str::to_owned).unwrap_or_else(|| format!("s{}", models.len()));
let model = models.entry(id.clone()).or_insert_with(|| "a".into()).clone();
Ok(json!({"thread":{"id":id,"name":"fixture","turns":[]}, "model":model,
"serviceTier":self.runtime.tiers.lock().get(&id).cloned().unwrap_or(json!("fast"))}))
}
"turn/start" => {
let id = p["threadId"].as_str().unwrap();
self.runtime.models.lock().insert(id.into(), p["model"].as_str().unwrap().into());
if let Some(tier) = p.get("serviceTier") {
self.runtime.tiers.lock().insert(id.into(), tier.clone());
}
self.runtime.turns.lock().push(p.clone());
self.peer
.get()
.unwrap()
.notify(
"turn/completed",
json!({"threadId":id,
"turn":{"id":"t","status":"completed"}}),
)
.unwrap();
Ok(json!({"turn":{"id":"t"}}))
}
_ => Err((codes::METHOD_NOT_FOUND, method.into())),
}
}
}
fn manager(dir: &Path, runtime: Arc<Runtime>) -> AgentManager {
let agents = dir.join("agents");
crate::provider::set_builtin_command(&agents, None, "codex", Some("/missing/fixture-codex")).unwrap();
AgentManager::with_connector(
crate::AgentPaths {
project_root: dir.into(),
store_dir: dir.join("store"),
worktrees_dir: dir.join("worktrees"),
models_file: dir.join("models.json"),
custom_agents_dir: Some(agents),
home_dir: Some(dir.into()),
env_secrets: None,
catalogs: Arc::default(),
},
tokio::runtime::Handle::current(),
Arc::new(move |spec, _, client, _| {
assert_eq!(spec.driver, crate::provider::Driver::Codex);
let handler = Arc::new(Connection { runtime: runtime.clone(), peer: OnceLock::new() });
let (a, b) = tokio::io::duplex(1 << 20);
let (r, w) = tokio::io::split(b);
let server = Peer::connect_framed(r, w, handler.clone(), Framing::Lines);
handler.peer.set(server.clone()).ok().unwrap();
runtime.servers.lock().push(server);
attach(client, |events| {
let (r, w) = tokio::io::split(a);
Ok(Peer::connect_framed(r, w, events, Framing::Lines))
})
}),
)
}
fn prompt() -> AgentPrompt {
AgentPrompt { text: "fixture".into(), ..Default::default() }
}
async fn ready(mgr: &AgentManager, id: &str) {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let task = mgr.task(id).unwrap();
let (status, busy) = {
let s = task.state.lock();
(s.task.status, s.busy)
};
assert_ne!(status, AgentStatus::Failed);
if status == AgentStatus::Ready && !busy {
break;
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
})
.await
.unwrap();
}
async fn send(mgr: &AgentManager, id: &str) {
mgr.prompt(id, prompt(), false).await.unwrap();
ready(mgr, id).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn explicit_tier_survives_standard_only_reconnect_before_immediate_prompt() {
for late_model in [0, 1, 2, 3] {
for choice in [Some("true"), Some("false"), None] {
let tmp = tempfile::tempdir().unwrap();
let runtime = Arc::new(Runtime::default());
let mgr = manager(tmp.path(), runtime.clone());
let task = mgr
.create(NewAgentTask {
provider: "codex".into(),
prompt: prompt(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
ready(&mgr, &task.id).await;
let catalog_config = mgr.task(&task.id).unwrap().state.lock().task.config.clone();
if let Some(value) = choice {
mgr.set_config(&task.id, "service_tier", value.into()).await.unwrap();
}
send(&mgr, &task.id).await;
assert_eq!(
runtime.turns.lock().last().unwrap().get("serviceTier"),
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
);
mgr.set_config(&task.id, "model", "b".into()).await.unwrap();
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
send(&mgr, &task.id).await;
assert_eq!(
runtime.turns.lock().last().unwrap().get("serviceTier"),
choice.map(|_| json!("default")).as_ref()
);
mgr.shutdown();
drop(mgr);
runtime.hide_a.store(late_model >= 2, std::sync::atomic::Ordering::SeqCst);
let mut mgr = manager(tmp.path(), runtime.clone());
send(&mgr, &task.id).await; // Reconnect while still on Standard-only B.
assert!(!mgr.task(&task.id).unwrap().state.lock().task.config.iter().any(|o| o.id == "service_tier"));
assert_eq!(
runtime.turns.lock().last().unwrap().get("serviceTier"),
choice.map(|_| json!("default")).as_ref()
);
if late_model != 0 {
// Catalog knows A, but the session's picker has not received it yet.
let current = mgr.task(&task.id).unwrap();
let mut s = current.state.lock();
let catalog = serde_json::from_value(
json!({"fingerprint":"fixture", "schema":2, "config":catalog_config, "thoughtLevels":{"a":catalog_config.iter().filter(|o|crate::config::is_per_model_option(o)).collect::<Vec<_>>() }}),
)
.unwrap();
mgr.shared
.known
.lock()
.entry("codex".into())
.or_default()
.catalogs
.insert(mgr.shared.root_key(), catalog);
s.task.config.iter_mut().find(|o| o.id == "model").unwrap().values.retain(|v| v.value != "a");
}
mgr.set_config(&task.id, "model", "a".into()).await.unwrap();
if late_model == 3 {
// An older saved pending switch has no retained intent field.
mgr.task(&task.id).unwrap().state.lock().pending_model.as_mut().unwrap().retained_service_tier = None;
mgr.shutdown();
mgr = manager(tmp.path(), runtime.clone());
}
let displayed = mgr
.task(&task.id)
.unwrap()
.state
.lock()
.snapshot()
.config
.iter()
.find(|o| o.id == "service_tier")
.unwrap()
.current
.clone();
assert_eq!(displayed.as_deref(), Some(choice.unwrap_or("true")));
send(&mgr, &task.id).await; // No sleeps/retries between selecting A and submitting.
assert_eq!(
runtime.turns.lock().last().unwrap().get("serviceTier"),
choice.map(|v| json!(if v == "true" { "fast" } else { "default" })).as_ref()
);
let other = mgr
.create(NewAgentTask {
provider: "codex".into(),
prompt: prompt(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
ready(&mgr, &other.id).await;
assert!(
runtime.turns.lock().last().unwrap().get("serviceTier").is_none(),
"choices must not leak to another task"
);
mgr.shutdown();
}
}
}
+245 -1
Переглянути файл
@@ -110,7 +110,8 @@ for line in sys.stdin:
cursor = request['params']['cursor']
model = 'one' if cursor is None else 'two'
result = {'data': [{'id': model, 'isDefault': cursor is None,
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}]}],
'defaultReasoningEffort': 'low', 'supportedReasoningEfforts': [{'reasoningEffort': 'low'}],
'serviceTiers': [{'id': 'fast', 'name': 'Fast', 'description': ''}] if cursor is None else []}],
'nextCursor': 'second-page' if cursor is None else None}
else:
raise RuntimeError('must not create a thread or prompt: ' + method)
@@ -125,6 +126,7 @@ for line in sys.stdin:
driver: crate::provider::Driver::Codex,
command: script.to_string_lossy().into_owned(),
args: Vec::new(),
additional_args_len: 0,
env: Vec::new(),
login_hint: String::new(),
source: crate::AgentSource::Builtin,
@@ -138,6 +140,9 @@ for line in sys.stdin:
.collect();
assert_eq!(models, ["one", "two"]);
assert_eq!(found.levels.keys().map(String::as_str).collect::<Vec<_>>(), ["one", "two"]);
assert!(found.config.iter().any(|o| o.id == SERVICE_TIER));
assert!(found.levels["one"].iter().any(|o| o.id == SERVICE_TIER));
assert!(found.levels["two"].iter().all(|o| o.id != SERVICE_TIER));
let requests = std::fs::read_to_string(tmp.path().join("requests")).unwrap();
let requests: Vec<Value> = requests.lines().map(|line| serde_json::from_str(line).unwrap()).collect();
assert_eq!(
@@ -162,6 +167,72 @@ for line in sys.stdin:
// ---- Pure translations -------------------------------------------------------------
#[test]
fn fast_is_offered_only_when_the_model_advertises_it() {
for capability in [
json!({ "additionalSpeedTiers": ["fast"] }),
json!({ "serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }] }),
json!({ "serviceTiers": [{ "id": "priority", "name": "Fast", "description": "" }] }),
] {
let mut model = json!({ "id": "supported", "isDefault": true });
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
let models = models_of(&json!({ "data": [model, { "id": "unsupported" }] }));
let mut settings = Settings::of(&json!({}), &models);
let options = config_options(&models, &settings);
let fast = options.as_array().unwrap().iter().find(|o| o["id"] == "service_tier").expect("Fast option");
assert_eq!(fast["category"], "model_config");
assert_eq!(fast["currentValue"], "false");
assert!(settings.set(&models, "service_tier", "true").is_ok());
assert!(settings.set(&models, "service_tier", "invalid").is_err());
let selected = settings.service_tier_override(&models).map(str::to_owned);
settings.set(&models, "model", "unsupported").unwrap();
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
assert!(settings.set(&models, "service_tier", "true").is_err());
assert_eq!(settings.service_tier_override(&models), Some("default"));
settings.set(&models, "model", "supported").unwrap();
assert_eq!(settings.service_tier_override(&models), selected.as_deref());
let options = config_options(&models, &settings);
assert_eq!(
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
"true"
);
}
for capability in [json!({}), json!({ "additionalSpeedTiers": [] }), json!({ "serviceTiers": [] })] {
let mut model = json!({ "id": "old", "isDefault": true });
model.as_object_mut().unwrap().extend(capability.as_object().unwrap().clone());
let models = models_of(&json!({ "data": [model] }));
let settings = Settings::of(&json!({}), &models);
assert!(config_options(&models, &settings).as_array().unwrap().iter().all(|o| o["id"] != "service_tier"));
}
}
#[test]
fn fast_defaults_do_not_become_user_overrides() {
let models = models_of(&json!({ "data": [{
"id": "m", "isDefault": true, "defaultServiceTier": "fast",
"serviceTiers": [{ "id": "fast", "name": "Fast", "description": "" }]
}] }));
for (reported, current) in [
(json!({}), "true"),
(json!({ "serviceTier": null }), "false"),
(json!({ "serviceTier": "fast" }), "true"),
(json!({ "serviceTier": "priority" }), "true"),
(json!({ "serviceTier": "default" }), "false"),
] {
let mut settings = Settings::of(&reported, &models);
let options = config_options(&models, &settings);
assert_eq!(
options.as_array().unwrap().iter().find(|o| o["id"] == SERVICE_TIER).unwrap()["currentValue"],
current
);
assert_eq!(settings.service_tier_override(&models), None);
settings.set(&models, SERVICE_TIER, "true").unwrap();
assert_eq!(settings.service_tier_override(&models), Some("fast"));
settings.set(&models, SERVICE_TIER, "false").unwrap();
assert_eq!(settings.service_tier_override(&models), Some("default"));
}
}
fn models() -> Vec<ModelInfo> {
models_of(&json!({"data": [
{"id": "big", "model": "big", "displayName": "Big", "description": "d", "hidden": false, "isDefault": true,
@@ -185,6 +256,8 @@ fn settings_follow_the_thread_and_the_models() {
Settings {
model: "big".into(),
effort: Some("low".into()),
service_tier: None,
fast_override: None,
mode: Mode::Ask,
collaboration_mode: DEFAULT_COLLABORATION_MODE.into(),
collaboration_mode_override: None,
@@ -382,6 +455,90 @@ fn failures_are_classified() {
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
}
#[test]
fn failed_turns_preserve_codex_error_diagnostics() {
let policy = json!({
"message": "This content was flagged for possible cybersecurity risk.",
"additionalDetails": "Contact support if this is unexpected.",
"codexErrorInfo": "cyberPolicy"
});
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
assert_eq!(failure.code, codes::INTERNAL_ERROR);
assert_eq!(failure.message, expected);
}
// A completed turn's own error wins over an older error notification.
let failure = stop_reason(
&json!({ "status": "failed", "error": policy }),
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
None,
)
.unwrap_err();
assert_eq!(failure.message, expected);
}
#[test]
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
for (value, expected) in [
(
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
"Context is full.\nCodex error: contextWindowExceeded",
),
(
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
),
(
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
"Failed\nbecause",
),
(
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
"Codex failed\nDetails\nCodex error: cyberPolicy",
),
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
(json!({}), "Codex failed"),
] {
assert_eq!(error_message(&value), expected);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
for notification_only in [false, true] {
let mut transcript = load(Scenario::UsageLimit.file());
let policy = json!({
"message": "This content was flagged for possible cybersecurity risk.",
"additionalDetails": "Contact support if this is unexpected.",
"codexErrorInfo": "cyberPolicy"
});
for (out, frame) in &mut transcript.frames {
if *out {
continue;
}
match frame["method"].as_str() {
Some("error") => frame["params"]["error"] = policy.clone(),
Some("turn/completed") => {
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
}
_ => {}
}
}
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
match result(&results, "prompt") {
Err(RpcError::Server { code, message, .. }) => {
assert_eq!(*code, codes::INTERNAL_ERROR);
assert_eq!(
message,
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
);
}
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
}
}
}
#[test]
fn approvals_offer_what_codex_offers_and_always_a_decline() {
let params = json!({"availableDecisions": ["accept",
@@ -648,6 +805,7 @@ enum Scenario {
Steer,
Simple,
MultiTurn,
ServiceTier { first: Option<bool>, second: Option<bool> },
Approvals,
UsageLimit,
Subagent,
@@ -666,6 +824,7 @@ impl Scenario {
Scenario::Steer => "steer",
Scenario::Simple => "simple",
Scenario::MultiTurn => "multi_turn",
Scenario::ServiceTier { .. } => "multi_turn",
Scenario::Approvals => "approvals",
Scenario::UsageLimit => "usage_limit",
Scenario::Subagent => "subagent",
@@ -772,6 +931,16 @@ async fn drive(scenario: Scenario, acp: &Peer, client: &Client, cwd: &str, threa
out.push(("effort", request(acp, "session/set_config_option", set(EFFORT, "high")).await));
out.push(("second", request(acp, "session/prompt", prompt("Reply with: two")).await));
}
Scenario::ServiceTier { first, second } => {
for (label, choice) in [("first", first), ("second", second)] {
if let Some(fast) = choice {
request(acp, "session/set_config_option", set(SERVICE_TIER, if fast { "true" } else { "false" }))
.await
.expect("the model advertises Fast");
}
out.push((label, request(acp, "session/prompt", prompt("Reply with: hi")).await));
}
}
Scenario::Approvals => {
client.answers.lock().extend([Some("accept"), None]);
out.push(("prompt", request(acp, "session/prompt", prompt("Run `touch b.txt`, then write a.txt.")).await));
@@ -1304,6 +1473,44 @@ fn thread_names_are_the_first_line_of_the_reply() {
assert_eq!(thread_name(&"x".repeat(100)).map(|n| n.chars().count()), Some(80));
}
#[tokio::test(flavor = "multi_thread")]
async fn fast_selection_reaches_the_first_and_next_turn_and_standard_clears_it() {
for (first, second, expected) in [
(Some(true), Some(false), [Some("fast"), Some("default")]),
(Some(false), Some(true), [Some("default"), Some("fast")]),
(Some(true), None, [Some("fast"), Some("fast")]),
(None, None, [None, None]),
] {
let scenario = Scenario::ServiceTier { first, second };
let mut transcript = load(scenario.file());
for (out, frame) in &mut transcript.frames {
if *out {
continue;
}
if let Some(models) = frame.pointer_mut("/result/data").and_then(Value::as_array_mut) {
for model in models {
model["serviceTiers"] = json!([{ "id": "fast", "name": "Fast", "description": "" }]);
model["defaultServiceTier"] = json!("fast");
}
}
if frame.pointer("/result/thread").is_some() {
frame["result"]["serviceTier"] = json!("fast");
}
}
let (results, _client, frames, _meta, _codex) = replay_transcript(scenario, transcript).await;
assert!(result(&results, "first").is_ok());
assert!(result(&results, "second").is_ok());
let starts = sent(&frames, "turn/start");
assert_eq!(starts.len(), 2);
for (start, expected) in starts.iter().zip(expected) {
assert_eq!(start["params"].get("serviceTier"), expected.map(|value| json!(value)).as_ref());
assert!(start["params"].get("serviceTierForTurn").is_none());
}
assert!(sent(&frames, "turn/settings/update").is_empty());
assert!(sent(&frames, "config/value/write").is_empty());
}
}
#[tokio::test(flavor = "multi_thread")]
async fn settings_apply_to_the_next_turn() {
let (results, client, frames, _) = replay(Scenario::MultiTurn).await;
@@ -1891,3 +2098,40 @@ fn workspace_roots_join_the_thread_roots() {
apply_thread_config(&json!({ "cwd": "/w/api", "mcpServers": [] }), &mut request);
assert!(request.get("runtimeWorkspaceRoots").is_none());
}
#[tokio::test(flavor = "multi_thread")]
async fn an_ephemeral_session_starts_an_ephemeral_thread() {
for ephemeral in [true, false] {
let tmp = tempfile::tempdir().unwrap();
let cwd = tmp.path().to_string_lossy().into_owned();
let server = Arc::new(TrustServer {
cwd: cwd.clone(),
disabled: false,
other_project: false,
write_error: false,
overridden: false,
calls: Mutex::default(),
});
let client = Arc::new(Client::default());
let (ours, theirs) = tokio::io::duplex(1 << 16);
let (read, write) = tokio::io::split(theirs);
let native = Peer::connect_framed(read, write, server.clone(), Framing::Lines);
let acp = attach(client.clone(), |events| {
let (read, write) = tokio::io::split(ours);
Ok(Peer::connect_framed(read, write, events, Framing::Lines))
})
.unwrap();
request(&acp, "initialize", json!({})).await.unwrap();
let mut params = json!({"cwd": cwd, "mcpServers": []});
if ephemeral {
params["_meta"] = json!({"openidea": {"ephemeral": true}});
}
request(&acp, "session/new", params).await.unwrap();
let calls = server.calls.lock();
let (_, start) = calls.iter().find(|(m, _)| m == "thread/start").unwrap();
assert_eq!(start.get("ephemeral"), ephemeral.then_some(&Value::Bool(true)), "{start}");
drop(calls);
acp.kill();
native.kill();
}
}
+84 -7
Переглянути файл
@@ -97,6 +97,8 @@ pub(super) struct ModelInfo {
/// `(effort, description)`.
pub efforts: Vec<(String, String)>,
pub default_effort: Option<String>,
pub fast_tier: Option<String>,
pub default_service_tier: Option<String>,
pub is_default: bool,
pub hidden: bool,
}
@@ -123,6 +125,22 @@ pub(super) fn models_of(list: &Value) -> Vec<ModelInfo> {
})
.collect(),
default_effort: str_of(m, "defaultReasoningEffort"),
fast_tier: m
.get("serviceTiers")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|tier| tier.get("id").and_then(Value::as_str))
.chain(
m.get("additionalSpeedTiers")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str),
)
.find(|tier| is_fast_tier(tier))
.map(str::to_owned),
default_service_tier: str_of(m, "defaultServiceTier"),
is_default: m.get("isDefault").and_then(Value::as_bool) == Some(true),
hidden: m.get("hidden").and_then(Value::as_bool) == Some(true),
id,
@@ -137,6 +155,9 @@ pub(super) struct Settings {
/// A model id from `model/list`, or the one the thread reported.
pub model: String,
pub effort: Option<String>,
pub service_tier: Option<String>,
/// No choice preserves the runtime's default; false explicitly selects Standard.
pub fast_override: Option<bool>,
pub mode: Mode,
/// Codex's Default/Plan collaboration mode. It is sent with each turn because it is
/// part of the turn contract rather than the sandbox permission mode above.
@@ -158,6 +179,12 @@ impl Settings {
let mut s = Settings {
model,
effort: str_of(result, "reasoningEffort"),
service_tier: match result.get("serviceTier") {
// A live thread can explicitly report Standard even when the catalog defaults to Fast.
Some(Value::Null) => Some("default".into()),
_ => str_of(result, "serviceTier"),
},
fast_override: None,
mode: Mode::of(
result.get("approvalPolicy").unwrap_or(&Value::Null),
result.get("sandbox").unwrap_or(&Value::Null),
@@ -205,6 +232,16 @@ impl Settings {
}
self.effort = Some(value.to_owned());
}
SERVICE_TIER => {
if !models.iter().any(|m| m.id == self.model && m.fast_tier.is_some()) {
return Err(format!("{} has no Fast mode", self.model));
}
self.fast_override = Some(match value {
"true" => true,
"false" => false,
_ => return Err(format!("unknown Fast mode {value}")),
});
}
MODE => self.mode = Mode::parse(value).ok_or_else(|| format!("unknown mode {value}"))?,
COLLABORATION_MODE => {
if !matches!(value, DEFAULT_COLLABORATION_MODE | PLAN_COLLABORATION_MODE) {
@@ -217,16 +254,32 @@ impl Settings {
}
Ok(())
}
/// `turn/start.serviceTier`: omission inherits; "default" explicitly resets Fast.
pub fn service_tier_override<'a>(&self, models: &'a [ModelInfo]) -> Option<&'a str> {
match self.fast_override {
Some(true) => Some(
models.iter().find(|m| m.id == self.model).and_then(|m| m.fast_tier.as_deref()).unwrap_or("default"),
),
Some(false) => Some("default"),
None => None,
}
}
}
pub(super) const MODEL: &str = "model";
pub(super) const EFFORT: &str = "reasoning_effort";
pub(super) const SERVICE_TIER: &str = "service_tier";
pub(super) const MODE: &str = "mode";
pub(super) const COLLABORATION_MODE: &str = "collaboration_mode";
pub(super) const DEFAULT_COLLABORATION_MODE: &str = "default";
pub(super) const PLAN_COLLABORATION_MODE: &str = "plan";
/// ACP `configOptions`: model, reasoning effort (for models that have it) and mode.
fn is_fast_tier(tier: &str) -> bool {
matches!(tier, "fast" | "priority")
}
/// ACP `configOptions`: model, its supported settings and session modes.
pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
let mut model_values: Vec<Value> = models
.iter()
@@ -253,6 +306,16 @@ pub(super) fn config_options(models: &[ModelInfo], s: &Settings) -> Value {
"currentValue": effort, "options": values,
}));
}
if let Some(model) = models.iter().find(|m| m.id == s.model && m.fast_tier.is_some()) {
let fast = s.fast_override.unwrap_or_else(|| {
s.service_tier.as_deref().or(model.default_service_tier.as_deref()).is_some_and(is_fast_tier)
});
out.push(json!({
"id": SERVICE_TIER, "name": "Fast", "category": "model_config", "type": "select",
"currentValue": if fast { "true" } else { "false" },
"options": [select_value("false", "Standard", None), select_value("true", "Fast", None)],
}));
}
out.push(json!({
"id": MODE, "name": "Mode", "category": "mode", "type": "select", "currentValue": s.mode.id(),
"options": Mode::ALL.iter().map(|m| select_value(m.id(), m.name(), Some(m.description()))).collect::<Vec<_>>(),
@@ -677,7 +740,7 @@ pub(super) enum Failure {
UsageLimit(Option<f64>),
/// Signed out or refused.
Auth,
/// The model declined.
/// The server blocked the turn under a safety policy.
Refusal,
Other,
}
@@ -717,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
exhausted.map(|s| s * 1000.0)
}
/// The text a failed turn reports: codex's message, with its details.
/// The text a failed turn reports: Codex's message, details and diagnostic code.
pub(super) fn error_message(error: &Value) -> String {
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
_ => message.to_owned(),
let original =
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
let mut message = original.to_owned();
if let Some(details) =
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
&& !original.contains(details)
{
message.push('\n');
message.push_str(details);
}
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
message.push_str(&format!("\nCodex error: {code}"));
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
message.push_str(&format!(" (HTTP {status})"));
}
}
message
}
/// One choice of an approval: what ACP shows and what codex gets back.
+73 -1
Переглянути файл
@@ -114,7 +114,7 @@ pub(crate) fn is_missing_binary_error(err: &std::io::Error) -> bool {
pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discovered, DiscoverError> {
tokio::time::timeout(DISCOVER_TIMEOUT, async move {
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
match discover_once(spec.clone(), cwd.clone(), prefer_stored).await {
Err(err)
if !prefer_stored
@@ -185,6 +185,78 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
res
}
#[derive(Clone, Debug, Default)]
pub(crate) struct CliAuthStatus {
pub authenticated: bool,
pub login: Option<String>,
pub auth_type: Option<String>,
pub status_message: Option<String>,
}
/// Queries `auth.getStatus` on Copilot's headless server (ignoring any IDE-selected `gh`
/// account override so the UI can show what the "Default" account resolves to).
pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> Option<CliAuthStatus> {
spec.env.retain(|(name, _)| name != crate::provider::COPILOT_GITHUB_ACCOUNT_ENV);
tokio::time::timeout(Duration::from_secs(8), async move {
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await;
if !prefer_stored
&& has_ambient
&& first.as_ref().is_none_or(|s| !s.authenticated)
&& let Some(retry) = probe_auth_once(spec, cwd, true).await
{
if retry.authenticated {
crate::provider::mark_prefer_stored_copilot_auth();
}
return Some(retry);
}
first
})
.await
.ok()
.flatten()
}
async fn probe_auth_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) -> Option<CliAuthStatus> {
let launch = tokio::task::spawn_blocking({
let cwd = cwd.clone();
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
})
.await
.ok()?
.ok()?;
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
let args = headless_args(&launch.args);
let peer = Peer::spawn_framed(
&launch.command,
&args,
&cwd,
&launch.env,
Arc::new(ide_jsonrpc::NoopHandler),
Box::new(|_| {}),
Framing::ContentLength,
)
.ok()?;
let res = async {
handshake(&peer).await.ok()?;
let auth: Value = peer.request("auth.getStatus", json!({}), None).await.ok()?;
let authenticated = auth.get("isAuthenticated").and_then(Value::as_bool).unwrap_or(false);
let str_field = |key: &str| {
auth.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
};
Some(CliAuthStatus {
authenticated,
login: str_field("login"),
auth_type: str_field("authType"),
status_message: str_field("statusMessage"),
})
}
.await;
peer.kill();
res
}
#[cfg(test)]
pub(super) fn attach(
client: Arc<dyn Handler>,
+442 -27
Переглянути файл
@@ -2,7 +2,10 @@
//! `<config>/agents/<id>.toml` (written by hand, or by installing one from the ACP
//! Registry, see `registry`).
use crate::{AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets};
use crate::{
AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets,
GhAuthAccount,
};
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -33,6 +36,8 @@ pub(crate) struct ProviderSpec {
pub driver: Driver,
pub command: String,
pub args: Vec<String>,
/// Number of trailing arguments added by the built-in agent's settings.
pub additional_args_len: usize,
pub env: Vec<(String, String)>,
/// How to sign in when the agent reports it needs authentication.
pub login_hint: String,
@@ -71,7 +76,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
"GitHub Copilot",
Driver::Copilot,
&["copilot", "--headless", "--no-auto-update", "--stdio"],
"Run `copilot` in a terminal and sign in.",
"Run `copilot login` in a terminal.",
),
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
@@ -96,6 +101,7 @@ fn builtins() -> Vec<ProviderSpec> {
driver: *driver,
command: cmd[0].into(),
args: cmd[1..].iter().map(|a| (*a).to_owned()).collect(),
additional_args_len: 0,
env: Vec::new(),
login_hint: (*hint).into(),
source: AgentSource::Builtin,
@@ -148,12 +154,26 @@ impl ProviderSpec {
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
let is_copilot = is_copilot_provider(&self.id);
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
let explicit_copilot_token =
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
if let Some(account) = account {
let token = github_token_for_account(&account)?;
// Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's
// shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`.
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
} else if is_copilot
&& !strip_ambient_tokens
&& !explicit_copilot_token
&& ide_core::project_env::github_token(cwd).is_some()
&& let Some(default_token) = default_github_token()
{
// A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model
// billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present.
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token));
}
Ok(resolved)
}
@@ -163,7 +183,7 @@ impl ProviderSpec {
self.command = crate::native::newest_install(&self.command);
}
if is_copilot_provider(&self.id) {
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
}
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
@@ -173,6 +193,80 @@ impl ProviderSpec {
.into_owned();
self
}
/// Resolves the executable, arguments, and environment to run this agent's interactive
/// sign-in flow directly in an IDE PTY without shell quoting.
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
let search = ide_core::tool_path::search_path();
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
let candidate =
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
if candidate.is_absolute() && is_executable(&candidate) {
return Some(candidate);
}
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
};
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
"claude-acp" => Some(("claude", &[][..])),
"codex-acp" => Some(("codex", &["login"][..])),
"vibe" => Some(("vibe", &[][..])),
_ => None,
} {
let program = resolve_exe(separate_cmd, &self.env)?;
return Some(LoginLaunch {
program,
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
env: self.env.iter().cloned().collect(),
});
}
if let Some(builtin) = builtin_spec(&self.id) {
let args = terminal_auth_args
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
.map(<[String]>::to_vec)
.or_else(|| builtin_login_args(&builtin))?;
let resolved = self.clone().resolve_for_launch_base(cwd, true);
let program = resolve_exe(&resolved.command, &resolved.env)?;
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
if is_copilot_provider(&self.id) {
for key in AMBIENT_COPILOT_AUTH_VARS {
env.insert(key.to_owned(), String::new());
}
}
return Some(LoginLaunch { program, args, env });
}
let args = terminal_auth_args?.to_vec();
let resolved = self.clone().resolve_for_launch_base(cwd, true);
let program = resolve_exe(&resolved.command, &resolved.env)?;
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
}
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
self.login_launch(cwd, terminal_auth_args).is_some()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LoginLaunch {
pub program: PathBuf,
pub args: Vec<String>,
pub env: BTreeMap<String, String>,
}
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
let prefix = format!("Run `{}", builtin.command);
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
match rest {
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
let (args, _) = after_space.split_once('`')?;
Some(args.split_whitespace().map(str::to_owned).collect())
}
Some(_) => Some(Vec::new()),
None => None,
}
}
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
@@ -191,16 +285,26 @@ pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String>
.map(str::to_owned)
}
fn find_gh_executable() -> Option<PathBuf> {
ide_core::tool_path::find_gh_executable()
}
fn is_valid_github_login(account: &str) -> bool {
let bytes = account.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 39
&& bytes[0].is_ascii_alphanumeric()
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
}
fn github_token_for_account(account: &str) -> Result<String, String> {
let path = ide_core::process::shell_env()
.find(|(name, _)| name == "PATH")
.map(|(_, value)| value)
.or_else(|| ide_core::process::host_var_os("PATH"));
let program = path
.as_deref()
.and_then(|path| ide_core::process::find_executable("gh", path))
if !is_valid_github_login(account) {
return Err(format!("Invalid GitHub account login: {account}"));
}
let program = find_gh_executable()
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
let mut command = std::process::Command::new(program);
ide_core::process::prepare(&mut command);
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
@@ -226,6 +330,140 @@ fn github_token_for_account(account: &str) -> Result<String, String> {
Ok(token.to_owned())
}
/// Interactive `gh auth login` launch for adding/switching GitHub CLI accounts in-IDE,
/// with ambient `GITHUB_TOKEN` / `GH_TOKEN` cleared so `gh` does not refuse to run.
pub fn gh_login_launch() -> IdeResult<LoginLaunch> {
let program = find_gh_executable().ok_or_else(|| IdeError::unavailable("GitHub CLI (`gh`) is not installed"))?;
let mut env = BTreeMap::new();
for key in AMBIENT_COPILOT_AUTH_VARS {
env.insert(key.to_owned(), String::new());
}
Ok(LoginLaunch {
program,
args: vec!["auth".into(), "login".into(), "--hostname".into(), "github.com".into()],
env,
})
}
/// Returns `(gh_installed, authenticated_accounts)` for `github.com` from `gh auth status`,
/// ignoring ambient token environment variables so keyring accounts remain visible.
pub fn gh_authenticated_accounts() -> (bool, Vec<GhAuthAccount>) {
let Some(program) = find_gh_executable() else {
return (false, Vec::new());
};
let run_gh = |args: &[&str]| -> Option<std::process::Output> {
let mut command = std::process::Command::new(&program);
ide_core::process::prepare(&mut command);
command
.args(args)
.envs(ide_core::process::shell_env())
.env("GH_PROMPT_DISABLED", "1")
.env("GH_NO_UPDATE_NOTIFIER", "1")
.env("NO_COLOR", "1");
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
}
command.output().ok()
};
if let Some(output) = run_gh(&["auth", "status", "--json", "hosts"]) {
let stdout = String::from_utf8_lossy(&output.stdout);
if let Some(accounts) = parse_gh_auth_status_json(&stdout) {
return (true, accounts);
}
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.contains("unknown flag: --json") {
return (true, Vec::new());
}
}
let fallback = run_gh(&["auth", "status", "--hostname", "github.com"])
.map(|out| format!("{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
.map(|text| parse_gh_auth_status_text(&text))
.unwrap_or_default();
(true, fallback)
}
fn parse_gh_auth_status_json(text: &str) -> Option<Vec<GhAuthAccount>> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Entry {
#[serde(default)]
state: Option<String>,
#[serde(default)]
active: bool,
#[serde(default)]
login: String,
#[serde(default)]
token_source: Option<String>,
}
#[derive(Deserialize)]
struct Response {
#[serde(default)]
hosts: BTreeMap<String, Vec<Entry>>,
}
let parsed: Response = serde_json::from_str(text.trim()).ok()?;
let mut accounts: Vec<GhAuthAccount> = Vec::new();
if let Some(entries) = parsed.hosts.get("github.com") {
for entry in entries {
let login = entry.login.trim();
if login.is_empty() {
continue;
}
if entry.state.as_deref().is_some_and(|s| s != "success") {
continue;
}
// Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts.
if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") {
continue;
}
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
existing.active |= entry.active;
} else {
accounts.push(GhAuthAccount { login: login.to_owned(), active: entry.active });
}
}
}
Some(accounts)
}
fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
let mut accounts: Vec<GhAuthAccount> = Vec::new();
let mut current: Option<usize> = None;
for line in text.lines() {
let trimmed = line.trim();
if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") {
let login = rest.split_whitespace().next().unwrap_or("").trim();
current = None;
if !login.is_empty() && !rest.contains("_TOKEN") {
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
current = Some(idx);
} else {
accounts.push(GhAuthAccount { login: login.to_owned(), active: false });
current = Some(accounts.len() - 1);
}
}
} else if trimmed.starts_with("- Active account: true")
&& let Some(idx) = current
{
accounts[idx].active = true;
}
}
accounts
}
fn default_github_token() -> Option<String> {
let program = find_gh_executable()?;
let mut command = std::process::Command::new(program);
ide_core::process::prepare(&mut command);
command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env());
for name in AMBIENT_COPILOT_AUTH_VARS {
command.env_remove(name);
}
let output = command.output().ok().filter(|out| out.status.success())?;
let token = String::from_utf8(output.stdout).ok()?;
let token = token.trim();
(!token.is_empty()).then(|| token.to_owned())
}
pub(crate) fn prefer_stored_copilot_auth() -> bool {
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
}
@@ -234,18 +472,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() {
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
}
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool {
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
})
}
fn ambient_copilot_env_value(key: &str) -> Option<String> {
ide_core::process::shell_env()
.find(|(k, _)| *k == key)
.map(|(_, v)| v.to_string_lossy().into_owned())
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option<String> {
ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| {
ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned())
})
}
/// Builds child environment overrides for `copilot`:
@@ -256,9 +493,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
pub(crate) fn sanitized_copilot_env(
spec_env: &[(String, String)],
cwd: &Path,
strip_ambient_tokens: bool,
) -> Vec<(String, String)> {
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd))
}
pub(crate) fn sanitize_copilot_env_with(
@@ -347,16 +585,28 @@ pub(crate) fn is_unlisted(spec: &ProviderSpec) -> bool {
UNLISTED.contains(&spec.id.as_str()) && builtin_spec(&spec.id).as_ref() == Some(spec)
}
fn uses_package_runner(command: &str) -> bool {
matches!(command, "npx" | "bunx" | "uvx")
}
fn allows_additional_args(builtin: &ProviderSpec, driver: Driver) -> bool {
builtin.driver == Driver::Acp && driver == Driver::Acp && !uses_package_runner(&builtin.command)
}
/// Public launch metadata, keeping the built-in defaults separate from agent-file overrides.
pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
let builtin = builtin_spec(&spec.id);
let reason = if matches!(spec.source, AgentSource::Registry { .. }) {
Some(AgentCommandReadOnlyReason::Registry)
} else if let Some(default) = &builtin {
matches!(default.command.as_str(), "npx" | "bunx" | "uvx").then_some(AgentCommandReadOnlyReason::PackageRunner)
uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner)
} else {
Some(AgentCommandReadOnlyReason::CustomAgent)
};
let additional_args = builtin
.as_ref()
.filter(|b| reason.is_none() && allows_additional_args(b, spec.driver))
.map(|_| spec.args[spec.args.len() - spec.additional_args_len..].to_vec());
AgentProvider {
id: spec.id.clone(),
name: spec.name.clone(),
@@ -366,6 +616,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
.join(" "),
program: spec.command.clone(),
args: spec.args.clone(),
additional_args,
default_program: builtin.as_ref().map(|b| b.command.clone()),
default_args: builtin.as_ref().map(|b| b.args.clone()).unwrap_or_default(),
login_hint: Some(spec.login_hint(&ide_jsonrpc::resolve_spawn_program(&spec.command, &spec.env))),
@@ -373,6 +624,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
command_editable: reason.is_none(),
command_read_only_reason: reason,
installed: installed(&spec.command),
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(),
config: vec![],
@@ -391,7 +643,24 @@ pub(crate) fn set_builtin_command(
command: Option<&str>,
) -> IdeResult<()> {
update_builtin(custom_dir, secrets, id, |agent, builtin| {
agent.command = command.unwrap_or(&builtin.command).to_owned()
agent.command = command.unwrap_or(&builtin.command).to_owned();
Ok(())
})
}
/// Appends arguments to a directly launched built-in ACP agent; an empty list resets them.
pub(crate) fn set_builtin_additional_args(
custom_dir: &Path,
secrets: Option<&dyn EnvSecrets>,
id: &str,
args: Vec<String>,
) -> IdeResult<()> {
update_builtin(custom_dir, secrets, id, |agent, builtin| {
if !allows_additional_args(builtin, agent.driver) {
return Err(IdeError::invalid(format!("{id} does not support additional arguments")));
}
agent.additional_args = args;
Ok(())
})
}
@@ -427,7 +696,10 @@ pub(crate) fn set_builtin_env(
return agent.write(&file).map_err(Into::into);
}
}
update_builtin(custom_dir, secrets, id, |agent, _| agent.env = env)
update_builtin(custom_dir, secrets, id, |agent, _| {
agent.env = env;
Ok(())
})
}
/// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed.
@@ -435,7 +707,7 @@ fn update_builtin(
custom_dir: &Path,
secrets: Option<&dyn EnvSecrets>,
id: &str,
change: impl FnOnce(&mut CustomAgent, &ProviderSpec),
change: impl FnOnce(&mut CustomAgent, &ProviderSpec) -> IdeResult<()>,
) -> IdeResult<()> {
let Some(builtin) = builtin_spec(id) else {
return Err(IdeError::invalid(format!("{id} is not a built-in agent")));
@@ -449,6 +721,7 @@ fn update_builtin(
driver: builtin.driver,
command: builtin.command.clone(),
args: builtin.args.clone(),
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: None,
}
@@ -456,11 +729,12 @@ fn update_builtin(
if agent.registry.is_some() {
return Err(IdeError::invalid(format!("{id} is installed from the ACP Registry")));
}
change(&mut agent, &builtin);
change(&mut agent, &builtin)?;
if agent.command == builtin.command
&& agent.name.as_deref() == Some(builtin.name.as_str())
&& agent.driver == builtin.driver
&& agent.args == builtin.args
&& agent.additional_args.is_empty()
&& agent.env.is_empty()
{
match std::fs::remove_file(&file) {
@@ -502,6 +776,7 @@ pub(crate) fn save_custom(
driver: Driver::Acp,
command: input.command.clone(),
args: input.args.clone(),
additional_args: Vec::new(),
env: input.env.clone(),
registry: None,
}
@@ -572,6 +847,7 @@ pub(crate) fn import_acp(
driver: Driver::Acp,
command: server.command,
args: server.args,
additional_args: Vec::new(),
env: server.env,
registry: None,
}
@@ -615,6 +891,9 @@ pub(crate) struct CustomAgent {
pub command: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub args: Vec<String>,
/// Kept separate from `args` so Settings reset does not erase a hand-written launch line.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub additional_args: Vec<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub env: BTreeMap<String, String>,
/// Set when the agent was installed from the ACP Registry.
@@ -746,6 +1025,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
driver: agent.driver,
command: agent.command,
args: agent.args,
additional_args_len: 0,
env,
login_hint: "Sign in with the agent's own command line first.".into(),
source,
@@ -763,6 +1043,10 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
spec.args = crate::native::copilot::headless_args(&spec.args);
}
if spec.source == AgentSource::Custom {
if allows_additional_args(existing, spec.driver) {
spec.additional_args_len = agent.additional_args.len();
spec.args.extend(agent.additional_args);
}
spec.source = AgentSource::Builtin;
}
*existing = spec;
@@ -853,6 +1137,22 @@ mod tests {
assert_eq!(reset.env, custom.env);
}
#[test]
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
for spec in builtins() {
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
continue;
}
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
}
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
assert_eq!(args("copilot"), ["login"]);
assert_eq!(args("goose"), ["configure"]);
assert_eq!(args("hermes"), ["model"]);
assert!(args("qwen").is_empty());
}
#[test]
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
for spec in builtins() {
@@ -1043,6 +1343,53 @@ mod tests {
set_builtin_env(dir.path(), None, "not-a-builtin", env).unwrap_err();
}
#[test]
fn additional_args_append_and_reset_without_replacing_agent_file_overrides() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let omp = || load(Some(root), None).into_iter().find(|spec| spec.id == "omp").unwrap();
assert_eq!(describe(&omp()).additional_args, Some(vec![]));
set_builtin_additional_args(root, None, "omp", vec!["--extra".into()]).unwrap();
assert_eq!(omp().args, ["acp", "--extra"]);
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
assert!(!root.join("omp.toml").exists());
let file = root.join("omp.toml");
std::fs::write(
&file,
"name = \"My OMP\"\ncommand = \"/opt/my tools/omp\"\nargs = [\"acp\", \"--manual\"]\n[env]\nKEEP = \"value\"\n",
)
.unwrap();
let original = omp();
let extra = vec!["--label".into(), "two words".into(), String::new()];
set_builtin_additional_args(root, None, "omp", extra.clone()).unwrap();
let configured = omp();
assert_eq!(configured.args, ["acp", "--manual", "--label", "two words", ""]);
assert_eq!(describe(&configured).additional_args, Some(extra));
set_builtin_additional_args(root, None, "omp", vec![]).unwrap();
assert_eq!(omp(), original);
}
#[test]
fn additional_args_cannot_modify_managed_or_non_acp_launches() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::write(
root.join("gemini.toml"),
"command = \"gemini\"\nargs = [\"--experimental-acp\"]\n[registry]\nid = \"gemini\"\nversion = \"1\"\n",
)
.unwrap();
std::fs::write(root.join("mine.toml"), "command = \"mine\"\n").unwrap();
std::fs::write(root.join("omp.toml"), "command = \"omp\"\ndriver = \"codex\"\n").unwrap();
let before = load(Some(root), None);
for id in ["gemini", "mine", "omp", "codex", "claude-acp"] {
let spec = before.iter().find(|spec| spec.id == id).unwrap();
assert!(describe(spec).additional_args.is_none());
assert!(set_builtin_additional_args(root, None, id, vec!["--extra".into()]).is_err());
}
assert_eq!(load(Some(root), None), before);
}
#[test]
fn registry_copilot_allows_only_the_github_account_override() {
let dir = tempfile::tempdir().unwrap();
@@ -1052,6 +1399,7 @@ mod tests {
driver: Driver::Acp,
command: "/tools/copilot".into(),
args: vec!["--acp".into()],
additional_args: Vec::new(),
env: BTreeMap::from([("REGISTRY_SETTING".into(), "kept".into())]),
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.0".into() }),
}
@@ -1064,12 +1412,12 @@ mod tests {
"copilot",
BTreeMap::from([
("REGISTRY_SETTING".into(), "kept".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()),
]),
)
.unwrap();
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("alice-work"));
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
.unwrap_err();
@@ -1078,7 +1426,7 @@ mod tests {
#[test]
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
let mut spec = builtin_spec("copilot").unwrap();
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()));
let resolved = spec.resolve_for_launch(Path::new("."));
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
@@ -1108,6 +1456,7 @@ mod tests {
driver: Driver::Acp,
command: "amp".into(),
args: vec![],
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: Some(RegistryRef { id: "amp-acp".into(), version: "1.0.0".into() }),
}
@@ -1133,6 +1482,7 @@ mod tests {
driver: Driver::Claude,
command: "/old/claude".into(),
args: vec![],
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: None,
};
@@ -1186,6 +1536,7 @@ mod tests {
driver: Driver::Acp,
command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(),
args: vec!["acp".into()],
additional_args: Vec::new(),
env: BTreeMap::from([("K".to_owned(), "v".to_owned())]),
registry: Some(RegistryRef { id: "amp-acp".into(), version: "0.10.0".into() }),
};
@@ -1359,4 +1710,68 @@ mod tests {
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
);
}
#[test]
fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() {
let raw = r#"{
"hosts": {
"github.com": [
{"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"},
{"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"},
{"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"},
{"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"}
],
"ghe.example.com": [
{"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"}
]
}
}"#;
assert_eq!(
parse_gh_auth_status_json(raw),
Some(vec![
GhAuthAccount { login: "alice".into(), active: true },
GhAuthAccount { login: "alice-work".into(), active: false },
])
);
let text = "\
github.com
✓ Logged in to github.com account env_user (GH_TOKEN)
- Active account: true
✓ Logged in to github.com account alice (keyring)
- Active account: false
✓ Logged in to github.com account alice-work (keyring)
- Active account: true
";
assert_eq!(
parse_gh_auth_status_text(text),
vec![
GhAuthAccount { login: "alice".into(), active: false },
GhAuthAccount { login: "alice-work".into(), active: true },
]
);
}
#[test]
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
let dir = tempfile::tempdir().unwrap();
let app_support = dir.path().join("Application Support/copilot");
std::fs::create_dir_all(&app_support).unwrap();
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let mut spec = builtin_spec("copilot").unwrap();
spec.command = bin.to_string_lossy().into_owned();
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
let launch = spec.login_launch(dir.path(), None).unwrap();
assert_eq!(launch.program, bin);
assert_eq!(launch.args, ["login"]);
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
}
}
+159 -11
Переглянути файл
@@ -189,6 +189,11 @@ fn parse(text: &str) -> IdeResult<Vec<Entry>> {
/// `github/copilot-cli` publishes standalone archives and `SHA256SUMS.txt` on every GitHub
/// release. Supplying them installs Copilot without Node.js, npm, `~/.npmrc`, or mirror lag.
fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
let sys_root = if cfg!(target_os = "linux") { Some(Path::new("/")) } else { None };
add_copilot_release_binaries_with_root(entry, release_base, sys_root);
}
fn add_copilot_release_binaries_with_root(entry: &mut Entry, release_base: &str, sys_root: Option<&Path>) {
let tag = format!("v{}", entry.version.trim_start_matches('v'));
let base = format!("{}/{}", release_base.trim_end_matches('/'), tag);
let sha256_url = format!("{base}/SHA256SUMS.txt");
@@ -196,9 +201,12 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
Some(p) => (p.args.clone(), p.env.clone()),
None => (vec!["--acp".into()], BTreeMap::new()),
};
let linux = if cfg!(target_env = "musl") { "linuxmusl" } else { "linux" };
let linux_arm = format!("copilot-{linux}-arm64.tar.gz");
let linux_x64 = format!("copilot-{linux}-x64.tar.gz");
let linux_arm = format!(
"copilot-{}-arm64.tar.gz",
sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::Arm64))
);
let linux_x64 =
format!("copilot-{}-x64.tar.gz", sys_root.map_or("linux", |root| copilot_linux_variant_at(root, Arch::X64)));
let targets = [
("darwin-aarch64", "copilot-darwin-arm64.tar.gz", "./copilot"),
("darwin-x86_64", "copilot-darwin-x64.tar.gz", "./copilot"),
@@ -219,6 +227,22 @@ fn add_copilot_release_binaries(entry: &mut Entry, release_base: &str) {
}
}
/// Picks `linux` (glibc) or `linuxmusl` from the host's runtime dynamic linker rather than
/// `cfg!(target_env = "musl")`: `openidea-server` on Linux is built as static musl so it runs
/// on every distro, while Copilot's Linux archives dynamically link glibc or musl.
fn copilot_linux_variant_at(root: &Path, arch: Arch) -> &'static str {
let (glibc_rel, musl_rel) = match arch {
Arch::Arm64 => ("lib/ld-linux-aarch64.so.1", "lib/ld-musl-aarch64.so.1"),
Arch::X64 => ("lib64/ld-linux-x86-64.so.2", "lib/ld-musl-x86_64.so.1"),
};
let glibc = root.join(glibc_rel);
let has_musl_name = |p: PathBuf| p.file_name().is_some_and(|n| n.to_string_lossy().contains("musl"));
let points_to_musl =
fs::read_link(&glibc).is_ok_and(has_musl_name) || fs::canonicalize(&glibc).is_ok_and(has_musl_name);
let has_glibc = glibc.exists() && !points_to_musl;
if !has_glibc && root.join(musl_rel).exists() { "linuxmusl" } else { "linux" }
}
fn safe_segment(s: &str) -> bool {
!s.is_empty()
&& !s.starts_with('.')
@@ -443,7 +467,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
/// Installs (or updates to) the registry's current version of `id`, streaming progress
/// through `emit`, and points the agent file at it.
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
/// Installs agent `id`; an npm package retries against the public npm registry when the
/// configured one misses it only with `public_npm_fallback`.
pub fn install(
paths: &RegistryPaths,
id: &str,
public_npm_fallback: bool,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let id = canonical_id(id);
// The saved index is what the user picked from; fetch only when there is none.
let text = match fs::read_to_string(&paths.cache_file) {
@@ -455,9 +487,14 @@ pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit
.iter()
.find(|e| e.id == id)
.ok_or_else(|| IdeError::not_found(format!("{id} is not in the ACP Registry")))?;
install_entry(paths, entry, Platform::current(), &on_path, cancel, emit)
let npm_installer =
move |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
install_npm(p, entry, dir, platform, public_npm_fallback, cancel, emit)
};
install_entry_with(paths, entry, Platform::current(), &on_path, &npm_installer, cancel, emit)
}
#[cfg(test)]
fn install_entry(
paths: &RegistryPaths,
entry: &Entry,
@@ -466,7 +503,10 @@ fn install_entry(
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
let npm_installer = |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
install_npm(p, entry, dir, platform, true, cancel, emit)
};
install_entry_with(paths, entry, platform, on_path, &npm_installer, cancel, emit)
}
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
@@ -550,6 +590,7 @@ fn install_entry_with(
driver: Driver::Acp,
command: exe.to_string_lossy().into_owned(),
args,
additional_args: Vec::new(),
env,
registry: Some(RegistryRef { id: entry.id.clone(), version: entry.version.clone() }),
};
@@ -662,20 +703,23 @@ fn install_npm(
entry: &Entry,
dir: &Path,
platform: Platform,
public_fallback: bool,
cancel: &CancellationToken,
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}")))?;
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
}
#[allow(clippy::too_many_arguments)]
fn install_npm_with(
npm: &Path,
p: &Package,
entry: &Entry,
dir: &Path,
platform: Platform,
public_fallback: bool,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<PathBuf> {
@@ -703,6 +747,7 @@ fn install_npm_with(
},
&specs,
false,
public_fallback,
cancel,
emit,
)?;
@@ -941,6 +986,7 @@ mod tests {
driver: Driver::Acp,
command: "/x".into(),
args: vec![],
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: Some(RegistryRef { id: id.into(), version: version.into() }),
};
@@ -1002,7 +1048,7 @@ mod tests {
#[cfg(unix)]
#[test]
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss_unless_registries_are_configured_only() {
let dir = tempfile::tempdir().unwrap();
let install_dir = dir.path().join("acme/1.2.0");
fs::create_dir_all(&install_dir).unwrap();
@@ -1041,8 +1087,8 @@ esac
]}"#;
let entry = parse(index).unwrap().remove(0);
let pkg = entry.distribution.npx.as_ref().unwrap();
let exe =
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
let exe = install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, true, &CancellationToken::new(), &|_| {})
.unwrap();
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
assert_eq!(calls.len(), 2, "{calls:?}");
assert!(!calls[0].contains("--registry="), "{calls:?}");
@@ -1050,6 +1096,15 @@ esac
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
assert!(exe.is_file());
// Only the configured registries: the miss is the error, and npmjs is never asked.
let only = dir.path().join("acme-only/1.2.0");
fs::create_dir_all(&only).unwrap();
let err =
install_npm_with(&npm, pkg, &entry, &only, MAC_ARM, false, &CancellationToken::new(), &|_| {}).unwrap_err();
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
assert_eq!(calls.len(), 3, "{calls:?}");
assert!(!calls[2].contains("--registry="), "{calls:?}");
assert!(err.message.contains("notarget"), "{err:?}");
}
#[test]
@@ -1168,6 +1223,7 @@ esac
driver: Driver::Acp,
command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(),
args: vec!["--acp".into()],
additional_args: Vec::new(),
env: BTreeMap::new(),
registry: Some(RegistryRef { id: "copilot".into(), version: "1.0.104".into() }),
}
@@ -1180,7 +1236,7 @@ esac
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
assert_eq!(spec.name, "GitHub Copilot");
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
let mut providers = vec![provider::describe(&spec)];
@@ -1272,4 +1328,96 @@ esac
assert!(npm_bin.is_file());
assert_eq!(CustomAgent::read(&p.agent_file("copilot")).unwrap().command, npm_bin.to_string_lossy());
}
#[test]
fn selects_copilot_linux_archive_from_runtime_dynamic_linker() {
let index = r#"{"agents":[
{"id":"github-copilot-cli","name":"Copilot","version":"1.0.116",
"distribution":{"npx":{"package":"@github/[email protected]","args":["--acp"]}}}
]}"#;
let archives_for = |root: &Path| -> (String, String) {
let mut entry = parse(index).unwrap().remove(0);
entry.distribution.binary.clear();
add_copilot_release_binaries_with_root(&mut entry, "https://example.invalid/releases", Some(root));
(
entry.distribution.binary["linux-x86_64"].archive.clone(),
entry.distribution.binary["linux-aarch64"].archive.clone(),
)
};
let touch = |path: PathBuf| {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, b"").unwrap();
};
// 1. Non-FHS root (neither loader present) defaults to glibc archives.
let empty = tempfile::tempdir().unwrap();
assert_eq!(
archives_for(empty.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
// 2. Standard glibc host (and glibc host with musl-tools also installed) uses `copilot-linux-*`,
// even when `openidea-server` itself is compiled for `*-unknown-linux-musl`.
let glibc = tempfile::tempdir().unwrap();
touch(glibc.path().join("lib64/ld-linux-x86-64.so.2"));
touch(glibc.path().join("lib/ld-linux-aarch64.so.1"));
assert_eq!(
archives_for(glibc.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
touch(glibc.path().join("lib/ld-musl-x86_64.so.1"));
touch(glibc.path().join("lib/ld-musl-aarch64.so.1"));
assert_eq!(
archives_for(glibc.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linux-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linux-arm64.tar.gz".into(),
)
);
// 3. musl-only host (e.g. Alpine) uses `copilot-linuxmusl-*`.
let musl = tempfile::tempdir().unwrap();
touch(musl.path().join("lib/ld-musl-x86_64.so.1"));
touch(musl.path().join("lib/ld-musl-aarch64.so.1"));
assert_eq!(
archives_for(musl.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
)
);
// 4. Alpine `libc6-compat` / `gcompat` symlinking `ld-linux` to `ld-musl` still picks `linuxmusl`.
#[cfg(unix)]
{
fs::create_dir_all(musl.path().join("lib64")).unwrap();
std::os::unix::fs::symlink("../lib/ld-musl-x86_64.so.1", musl.path().join("lib64/ld-linux-x86-64.so.2"))
.unwrap();
std::os::unix::fs::symlink("ld-musl-aarch64.so.1", musl.path().join("lib/ld-linux-aarch64.so.1")).unwrap();
assert_eq!(
archives_for(musl.path()),
(
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-x64.tar.gz".into(),
"https://example.invalid/releases/v1.0.116/copilot-linuxmusl-arm64.tar.gz".into(),
)
);
}
#[cfg(target_os = "linux")]
{
let parsed = parse(index).unwrap().remove(0);
let expected_x64 = format!("copilot-{}-x64.tar.gz", copilot_linux_variant_at(Path::new("/"), Arch::X64));
assert!(
parsed.distribution.binary["linux-x86_64"].archive.ends_with(&expected_x64),
"unexpected linux-x86_64 archive: {}",
parsed.distribution.binary["linux-x86_64"].archive
);
}
}
}
+202 -1
Переглянути файл
@@ -63,6 +63,8 @@ struct FakeAgent {
session_steering: bool,
/// Records the `mcpServers` array passed to `session/new`, `session/load`, and `session/fork`.
mcp_calls: Mutex<Vec<(String, Vec<String>)>>,
/// The params of every `session/fork`, in order.
forks: Mutex<Vec<Value>>,
/// The content blocks of each `session/prompt`.
prompts: Mutex<Vec<Value>>,
}
@@ -175,6 +177,9 @@ impl Handler for FakeAgent {
})
.unwrap_or_default();
self.mcp_calls.lock().push((method.to_owned(), names));
if params.pointer("/_meta/openidea/ephemeral") == Some(&json!(true)) {
self.calls.lock().push("ephemeral".into());
}
}
let session = params.get("sessionId").and_then(Value::as_str).unwrap_or("s1").to_owned();
match method {
@@ -203,7 +208,11 @@ impl Handler for FakeAgent {
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]},
"configOptions": options}))
}
"session/fork" => Ok(json!({"sessionId": "s2"})),
"session/fork" => {
self.forks.lock().push(params.clone());
let requested = params.pointer("/_meta/openidea/forkSessionId").and_then(Value::as_str);
Ok(json!({ "sessionId": requested.unwrap_or("s2") }))
}
"_openidea/stop_task" => {
self.calls.lock().push(format!("{method} {}", params["taskId"]));
Ok(json!({}))
@@ -642,6 +651,32 @@ async fn saved_conversation_reads_do_not_start_or_load_the_agent() {
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn an_ephemeral_task_is_not_saved_and_asks_for_an_unsaved_session() {
let tmp = tempfile::tempdir().unwrap();
for ephemeral in [true, false] {
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("Write a commit message"),
provider: "claude".into(),
isolation: Isolation::Local,
ephemeral,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::NeedsInput).await;
assert_eq!(agent.calls.lock().iter().any(|c| c == "ephemeral"), ephemeral);
mgr.shutdown();
// The caller never deleted it (its window closed): only a saved task comes back.
let restored = manager(tmp.path(), Arc::new(FakeAgent::default()));
assert_eq!(restored.task(&task.id).is_ok(), !ephemeral);
restored.shutdown();
}
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn claude_commands_share_catalog_discovery_and_persist_results() {
@@ -2773,6 +2808,128 @@ async fn forks_rollbacks_and_steering() {
restored.shutdown();
}
const NATIVE_SOURCE: &str = "11111111-1111-4111-8111-111111111111";
const NATIVE_TARGET: &str = "22222222-2222-4222-8222-222222222222";
/// Plants a recorded claude transcript for `session_id` under the project's escaped folder.
fn plant_claude_session(mgr: &AgentManager, root: &Path, session_id: &str) {
let config = root.join("claude-config");
mgr.set_builtin_env(
"claude",
[("CLAUDE_CONFIG_DIR".to_string(), config.to_string_lossy().into_owned())].into_iter().collect(),
)
.unwrap();
mgr.reload_providers();
let escaped: String =
root.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
let transcript = config.join("projects").join(escaped).join(format!("{session_id}.jsonl"));
std::fs::create_dir_all(transcript.parent().unwrap()).unwrap();
std::fs::write(
&transcript,
format!(
"{}\n",
json!({
"type": "user",
"uuid": "u1",
"parentUuid": null,
"message": {"role": "user", "content": "fix the login bug"},
"cwd": root.to_string_lossy(),
})
),
)
.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_starts_a_ready_task_as_the_recorded_session_s_fork() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE);
let task = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap();
assert_eq!(task.provider, "claude");
assert_eq!(task.status, AgentStatus::Ready);
assert_eq!(task.isolation, Isolation::Local);
mgr.prompt(&task.id, text("again"), true).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let forks = agent.forks.lock().clone();
assert_eq!(forks.len(), 1, "one fork start");
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
let target = forks[0]["_meta"]["openidea"]["forkSessionId"].as_str().unwrap();
assert!(canonical_uuid(target), "the host chooses a canonical fork id: {target}");
assert_ne!(target, NATIVE_SOURCE);
assert!(
!agent.calls.lock().iter().any(|call| call == "session/new" || call == "session/load"),
"the task forks the recorded session instead of starting or loading another"
);
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some(target));
mgr.shutdown();
}
/// Plants a recorded codex rollout for `session_id` under the home `.codex/sessions` tree.
fn plant_codex_session(root: &Path, session_id: &str) {
let dir = root.join(".codex").join("sessions").join("2026").join("11").join("23");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(
dir.join(format!("rollout-{session_id}.jsonl")),
format!(
"{}\n{}\n",
json!({"type": "session_meta", "payload": {"id": session_id, "cwd": root.to_string_lossy()}}),
json!({"type": "event_msg", "payload": {"type": "user_message", "message": "fix the login bug"}})
),
)
.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_uses_the_id_codex_assigns() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_codex_session(tmp.path(), NATIVE_SOURCE);
let task = mgr.fork_session("codex", NATIVE_SOURCE, tmp.path()).unwrap();
assert_eq!(task.status, AgentStatus::Ready);
mgr.prompt(&task.id, text("again"), true).await.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let forks = agent.forks.lock().clone();
assert_eq!(forks.len(), 1);
assert_eq!(forks[0]["sessionId"], NATIVE_SOURCE);
assert!(forks[0].pointer("/_meta/openidea/forkSessionId").is_none(), "codex names its own fork");
assert_eq!(mgr.task(&task.id).unwrap().state.lock().session_id.as_deref(), Some("s2"));
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn fork_session_rejects_invalid_input_before_starting() {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
let mgr = manager(tmp.path(), agent.clone());
plant_claude_session(&mgr, tmp.path(), NATIVE_SOURCE);
// Non-native provider, malformed id, unknown session, wrong directory.
let cases: [(&str, &str, &Path, ide_core::error::ErrorKind); 4] = [
("gemini", NATIVE_SOURCE, tmp.path(), ide_core::error::ErrorKind::InvalidInput),
("claude", "not-a-uuid", tmp.path(), ide_core::error::ErrorKind::InvalidInput),
("claude", NATIVE_TARGET, tmp.path(), ide_core::error::ErrorKind::NotFound),
("claude", NATIVE_SOURCE, Path::new("/elsewhere"), ide_core::error::ErrorKind::InvalidInput),
];
for (index, (provider, id, cwd, kind)) in cases.into_iter().enumerate() {
let error = mgr.fork_session(provider, id, cwd).unwrap_err();
assert_eq!(error.kind, kind, "case {index}: {error}");
}
// A session already held by a task cannot be forked again.
mgr.import_session("claude", NATIVE_SOURCE).unwrap();
let error = mgr.fork_session("claude", NATIVE_SOURCE, tmp.path()).unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput, "{error}");
assert!(agent.calls.lock().is_empty(), "no process may start");
mgr.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn usage_limits_and_late_settings() {
let tmp = tempfile::tempdir().unwrap();
@@ -3045,6 +3202,46 @@ async fn rapid_idle_model_switches_share_discovery_and_never_apply_a_stale_compl
restored.shutdown();
}
#[tokio::test(flavor = "multi_thread")]
async fn explicit_service_tier_reaches_the_session_even_when_it_matches_the_reported_default() {
for value in [None, Some("false"), Some("true")] {
let tmp = tempfile::tempdir().unwrap();
let agent = Arc::new(FakeAgent::default());
*agent.extra_options.lock() = vec![json!({
"id": "service_tier", "name": "Fast", "category": "model_config", "type": "select",
"currentValue": value.unwrap_or("true"),
"options": [{"value": "false"}, {"value": "true"}]
})];
let mgr = manager(tmp.path(), agent.clone());
let task = mgr
.create(NewAgentTask {
prompt: text("again"),
provider: "codex".into(),
config: value
.map(|value| vec![AgentConfigChoice { id: "service_tier".into(), value: value.into() }])
.unwrap_or_default(),
isolation: Isolation::Local,
..Default::default()
})
.await
.unwrap();
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
let calls = agent.calls.lock();
let prompt = calls.iter().position(|call| call == "session/prompt").unwrap();
if let Some(value) = value {
let setting = calls
.iter()
.position(|call| call == &format!("session/set_config_option \"{value}\""))
.expect("an explicit tier must not be mistaken for an inherited default");
assert!(setting < prompt);
} else {
assert!(!calls.iter().any(|call| call == "session/set_config_option"));
}
drop(calls);
mgr.shutdown();
}
}
#[tokio::test(flavor = "multi_thread")]
async fn upfront_effort_is_validated_after_changing_model_before_the_prompt() {
for (effort, applied) in [("medium", true), ("high", false)] {
@@ -5421,6 +5618,7 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
mcp_overrides: BTreeMap::from([("slack".into(), false)]),
idle: false,
skill_overrides: BTreeMap::new(),
ephemeral: false,
})
.await
.unwrap();
@@ -5483,6 +5681,7 @@ async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idl
("tdd".into(), AgentSkillMode::Auto),
("noisy".into(), AgentSkillMode::Off),
]),
ephemeral: false,
})
.await
.unwrap();
@@ -5626,6 +5825,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
ephemeral: false,
})
.await
.unwrap();
@@ -5652,6 +5852,7 @@ async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails()
mcp_overrides: BTreeMap::new(),
idle: false,
skill_overrides: BTreeMap::new(),
ephemeral: false,
})
.await
.unwrap();
+11 -3
Переглянути файл
@@ -9,6 +9,7 @@ mod modules;
mod parse;
mod single;
mod structure;
mod tsc_watch;
mod up_to_date;
pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint};
@@ -16,12 +17,14 @@ pub use launch_resources::process_launch_resources;
pub use modules::record_module_build;
pub use single::{
SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan,
has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target,
has_gradle_file_target, javac_step, module_classpath, module_classpath_without_build, module_classpaths,
single_file_classpath, single_file_target,
};
pub use structure::{
StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan,
structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts,
};
pub use tsc_watch::{tsc_watch, tsc_watch_roots};
pub use up_to_date::{menu_up_to_date, record_menu_build};
use crate::process::{self, Stream};
@@ -811,6 +814,11 @@ pub fn run(
/// Per-file editor / Problems diagnostics of the messages that have a position.
pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
diagnostics_from(messages, DIAGNOSTICS_SOURCE)
}
/// [`diagnostics`] reported by `source`.
pub fn diagnostics_from(messages: &[BuildMessage], source: &str) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
let mut out: BTreeMap<PathBuf, Vec<Diagnostic>> = BTreeMap::new();
for m in messages {
let (Some(path), Some(range)) = (&m.path, m.range) else { continue };
@@ -818,11 +826,11 @@ pub fn diagnostics(messages: &[BuildMessage]) -> BTreeMap<PathBuf, Vec<Diagnosti
range,
severity: m.severity,
message: m.text.clone(),
source: Some(DIAGNOSTICS_SOURCE.to_owned()),
source: Some(source.to_owned()),
code: m.code.clone(),
unnecessary: false,
deprecated: false,
server: Some(DIAGNOSTICS_SOURCE.to_owned()),
server: Some(source.to_owned()),
});
}
out
+104 -8
Переглянути файл
@@ -94,12 +94,12 @@ pub(super) fn build_javac_step(
Ok(step)
}
/// The resolved dependency classpath for one module and scope, tied to the same
/// inputs as its launch build so POM, JDK, settings and profile changes invalidate it.
/// The last resolved dependency classpath for one module and scope. A fingerprint
/// permits reuse during a build; NoBuild also uses records without one.
#[derive(Debug, Deserialize, Serialize)]
struct CachedClasspath {
version: u32,
fingerprint: LaunchFingerprint,
fingerprint: Option<LaunchFingerprint>,
classpath: String,
}
@@ -162,9 +162,6 @@ fn module_target(root: &Path, model: &BuildModel, module: &Path, test: bool) ->
.iter()
.find(|p| root.join(&p.dir) == module)
.ok_or_else(|| IdeError::not_found("no linked Maven project found for module"))?;
if project.packaging == "pom" {
return Err(IdeError::not_found("the launch module is a Maven aggregator without sources"));
}
let top = maven_reactor(m, &project.dir)
.ok_or_else(|| IdeError::not_found("no linked Maven reactor found for module"))?;
let top_dir = subdir(root, &top.dir);
@@ -217,6 +214,30 @@ pub fn module_classpath(
module_classpaths(root, model, &[module.to_path_buf()], test, local_repo, cache, cancel)
}
/// Uses the last launch classpath, or probes dependencies without invoking the compile lifecycle.
pub fn module_classpath_without_build(
root: &Path,
model: &BuildModel,
module: &Path,
test: bool,
cache: &Path,
cancel: &CancellationToken,
) -> IdeResult<String> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let target = module_target(root, model, module, test)?;
if let Some(path) = classpath_cache_path(root, cache, module, test)
&& let Ok(bytes) = fs::read(path)
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
&& cached.version == CLASSPATH_CACHE_VERSION
&& classpath_entries_exist(root, &cached.classpath)
{
return Ok(cached.classpath);
}
classpath(root, model, &target, if test { "test" } else { "runtime" }, false, cancel)
}
/// [`module_classpath`] of `modules[0]`. The other modules, launched together with it
/// (#3971), share its Maven probe when they have no cached classpath, which leaves
/// theirs cached for their own launches.
@@ -245,7 +266,7 @@ pub fn module_classpaths(
&& let Ok(bytes) = fs::read(path)
&& let Ok(cached) = serde_json::from_slice::<CachedClasspath>(&bytes)
&& cached.version == CLASSPATH_CACHE_VERSION
&& cached.fingerprint == *fingerprint
&& cached.fingerprint.as_ref() == Some(fingerprint)
&& classpath_entries_exist(root, &cached.classpath)
{
if i == 0 {
@@ -269,7 +290,7 @@ pub fn module_classpaths(
return Err(IdeError::cancelled());
}
for (Probe(_, fingerprint, cache_path), classpath) in probes.into_iter().zip(&classpaths) {
if let (Some(fingerprint), Some(path)) = (fingerprint, cache_path) {
if let Some(path) = cache_path {
let cached =
CachedClasspath { version: CLASSPATH_CACHE_VERSION, fingerprint, classpath: classpath.clone() };
if let Err(error) = cache_classpath(&path, &cached) {
@@ -675,6 +696,81 @@ mod tests {
assert!(single_file_target(root, &model, &root.join("other/Main.java")).is_err());
}
#[cfg(unix)]
#[test]
fn pom_launch_resolves_dependencies_without_compiling_for_no_build() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
fixture(&root);
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
write(
&root,
"app/pom.xml",
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
);
let script = root.join("mvnw");
write(
&root,
"mvnw",
"#!/bin/sh\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target\nprintf '/repo/runtime.jar' > app/target/ide-compile-cp.txt\n",
);
fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
let model = crate::load(&root, &root.join("cache"), None);
let cancel = CancellationToken::new();
let cp = module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
.unwrap();
let paths: Vec<_> = std::env::split_paths(&cp).collect();
assert!(paths.contains(&root.join("lib/target/classes")), "{cp}");
assert!(paths.contains(&root.join("shared/target/classes")), "{cp}");
assert!(paths.contains(&PathBuf::from("/repo/runtime.jar")), "{cp}");
assert!(!paths.contains(&root.join("app/target/classes")), "{cp}");
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(!args.lines().any(|a| matches!(a, "compile" | "package" | "test-compile")), "{args}");
assert!(args.lines().any(|a| a == "-Dmdep.includeScope=runtime"), "{args}");
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
let args = fs::read_to_string(root.join("args.txt")).unwrap();
assert!(args.lines().any(|a| a == "compile"), "{args}");
}
#[cfg(unix)]
#[test]
fn no_build_keeps_the_last_launch_classpath_after_a_pom_change() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
fixture(&root);
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
write(
&root,
"app/pom.xml",
&pom.replace("<artifactId>app</artifactId>", "<artifactId>app</artifactId><packaging>pom</packaging>"),
);
write(
&root,
"mvnw",
"#!/bin/sh\necho called >> calls.txt\nprintf '%s\\n' \"$@\" > args.txt\nmkdir -p app/target repo\ntouch repo/runtime.jar repo/runtime-v2.jar\nif grep -q changed app/pom.xml; then printf \"$PWD/repo/runtime-v2.jar\" > app/target/ide-compile-cp.txt; else printf \"$PWD/repo/runtime.jar\" > app/target/ide-compile-cp.txt; fi\n",
);
fs::set_permissions(root.join("mvnw"), fs::Permissions::from_mode(0o755)).unwrap();
let model = crate::load(&root, &root.join("cache"), None);
let cancel = CancellationToken::new();
let previous =
module_classpath(&root, &model, &root.join("app"), false, None, &root.join("cache"), &cancel).unwrap();
assert!(previous.contains("repo/runtime.jar"), "{previous}");
let pom = fs::read_to_string(root.join("app/pom.xml")).unwrap();
write(&root, "app/pom.xml", &pom.replace("</project>", "<description>changed</description></project>"));
let launch =
module_classpath_without_build(&root, &model, &root.join("app"), false, &root.join("cache"), &cancel)
.unwrap();
assert!(launch.contains("repo/runtime.jar"), "{launch}");
assert!(!launch.contains("runtime-v2.jar"), "{launch}");
assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap().lines().count(), 1);
}
#[test]
fn javac_prefers_the_module_jdk_and_scopes_test_sources() {
let dir = tempfile::tempdir().unwrap();
+450
Переглянути файл
@@ -0,0 +1,450 @@
//! Problems › TypeScript project errors: the project's own `tsc --watch` on each root
//! `tsconfig.json`, its output parsed like Build's tsc step, one compilation at a time.
//!
//! A background check never writes into the project. A plain project runs `tsc --noEmit -p`
//! with its `.tsbuildinfo` (written by `composite` / `incremental` even without emit) moved to a
//! scratch folder. `tsc -b` cannot check without emitting (`--noEmit` fails with TS6310 on
//! composite references), and plain `tsc -p` on a project with references needs their built
//! `.d.ts` (TS6305). So a solution runs `tsc -b` on scratch copies of its configurations: each
//! `extends` the real one and only sends the outputs and `.tsbuildinfo` to the scratch folder,
//! keeping every option, file list and source position of the project.
use super::parse::{Format, OutputParser, RawMessage};
use super::{BuildMessage, Lines, PathMap, resolve};
use crate::process;
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
// ponytail: one `tsc` per root; past this the shallowest roots win. Raise it, or watch
// on demand, if monorepos without a solution tsconfig need more.
const MAX_ROOTS: usize = 8;
/// The configurations among `found` (the `tsconfig.json` files of the project) that no other
/// one references: the ones a watcher runs on. Referenced projects are checked by their solution.
pub fn tsc_watch_roots(found: Vec<PathBuf>) -> Vec<PathBuf> {
let referenced: BTreeSet<PathBuf> = found.iter().flat_map(|c| references(c)).collect();
let mut roots: Vec<PathBuf> = found.into_iter().filter(|c| !referenced.contains(c)).collect();
roots.sort_by_key(|c| (c.components().count(), c.clone()));
roots.truncate(MAX_ROOTS);
roots
}
fn read_json(path: &Path) -> Option<Value> {
let text = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&ide_core::jsonc::strip(&text)).ok()
}
/// The configurations `config` lists in `references` (a folder means its `tsconfig.json`).
fn references(config: &Path) -> Vec<PathBuf> {
let Some(json) = read_json(config) else { return Vec::new() };
let dir = config.parent().unwrap_or(Path::new(""));
let refs = json.get("references").and_then(|r| r.as_array()).into_iter().flatten();
refs.filter_map(|r| r.get("path")?.as_str())
.map(|p| {
let p = super::normalize(&dir.join(p));
if p.extension().is_some_and(|e| e == "json") { p } else { p.join("tsconfig.json") }
})
.collect()
}
/// A configuration and the ones it `extends`, most derived first, each with its folder (the
/// base of its relative paths). A package base (`@tsconfig/node20/tsconfig.json`) is looked up
/// in `node_modules` above the configuration.
fn chain(config: &Path) -> Vec<(PathBuf, Value)> {
let mut out = Vec::new();
let mut next = vec![config.to_path_buf()];
// A cycle or a deep chain ends here.
while let Some(path) = next.pop().filter(|_| out.len() < 16) {
let Some(json) = read_json(&path) else { continue };
let dir = path.parent().unwrap_or(Path::new("")).to_path_buf();
let bases: Vec<String> = match json.get("extends") {
Some(Value::String(s)) => vec![s.clone()],
Some(Value::Array(a)) => a.iter().filter_map(|v| v.as_str().map(str::to_owned)).collect(),
_ => Vec::new(),
};
// Later bases override earlier ones: visit them first.
next.extend(bases.iter().filter_map(|b| resolve_base(&dir, b)));
out.push((dir, json));
}
out
}
fn resolve_base(dir: &Path, base: &str) -> Option<PathBuf> {
let with_json = |p: PathBuf| {
if p.is_dir() {
p.join("tsconfig.json")
} else if p.extension().is_some_and(|e| e == "json") {
p
} else {
let mut s = p.into_os_string();
s.push(".json");
PathBuf::from(s)
}
};
if base.starts_with('.') || Path::new(base).is_absolute() {
return Some(with_json(super::normalize(&dir.join(base))));
}
dir.ancestors().map(|a| with_json(a.join("node_modules").join(base))).find(|p| p.is_file())
}
/// The first value of `key` (a top-level key, or `compilerOptions.<key>`) along `chain`, with the
/// folder it is relative to.
fn lookup<'a>(chain: &'a [(PathBuf, Value)], key: &str) -> Option<(&'a Path, &'a Value)> {
chain.iter().find_map(|(dir, json)| {
let value = match key.strip_prefix("compilerOptions.") {
Some(option) => json.get("compilerOptions")?.get(option)?,
None => json.get(key)?,
};
Some((dir.as_path(), value))
})
}
/// The scratch copy of `config` for `tsc -b`: the real configuration with its outputs and
/// `.tsbuildinfo` in `scratch` (file `<n>`), referencing the scratch copies `refs`. Settings that
/// default relative to the configuration's own folder are spelled out, since the copy lives
/// elsewhere: the files (`**/*`), their exclusions (`node_modules`, the output folder) and the
/// `rootDir` of a composite project.
fn scratch_config(config: &Path, scratch: &Path, n: usize, refs: &[PathBuf]) -> Value {
let chain = chain(config);
let dir = config.parent().unwrap_or(Path::new(""));
let out = scratch.join(n.to_string());
let mut options = json!({ "outDir": out, "tsBuildInfoFile": scratch.join(format!("{n}.tsbuildinfo")) });
if lookup(&chain, "compilerOptions.declarationDir").is_some() {
options["declarationDir"] = json!(out);
}
if lookup(&chain, "compilerOptions.outFile").is_some() {
options["outFile"] = json!(out.join("out.js"));
}
if lookup(&chain, "compilerOptions.composite").is_some_and(|(_, v)| v == &json!(true))
&& lookup(&chain, "compilerOptions.rootDir").is_none()
{
options["rootDir"] = json!(dir);
}
let mut copy = json!({
"extends": config,
"compilerOptions": options,
"references": refs.iter().map(|r| json!({ "path": r })).collect::<Vec<_>>(),
});
if lookup(&chain, "include").is_none() && lookup(&chain, "files").is_none() {
copy["include"] = json!([dir.join("**/*")]);
}
if lookup(&chain, "exclude").is_none() {
let mut exclude = vec![dir.join("node_modules")];
if let Some((base, Value::String(out_dir))) = lookup(&chain, "compilerOptions.outDir") {
exclude.push(super::normalize(&base.join(out_dir)));
}
copy["exclude"] = json!(exclude);
}
copy
}
/// The `tsc` arguments that watch `config` without writing into the project, writing the
/// scratch configurations a solution needs into `scratch`.
fn watch_args(config: &Path, scratch: &Path) -> std::io::Result<Vec<String>> {
let path = |p: &Path| p.to_string_lossy().into_owned();
let mut args: Vec<String> = if references(config).is_empty() {
let name = config.file_name().map_or_else(|| "tsconfig.json".into(), |n| n.to_string_lossy().into_owned());
let info = path(&scratch.join("tsconfig.tsbuildinfo"));
["--noEmit", "-p", &name, "--incremental", "--tsBuildInfoFile", &info].map(String::from).to_vec()
} else {
// Every configuration the solution reaches gets a number: the solution 0, then in order.
let mut numbers: BTreeMap<PathBuf, usize> = BTreeMap::from([(config.to_path_buf(), 0)]);
let mut queue = vec![config.to_path_buf()];
let mut i = 0;
while i < queue.len() {
let current = queue[i].clone();
let refs: Vec<PathBuf> = references(&current)
.into_iter()
.map(|r| {
let next = numbers.len();
let n = *numbers.entry(r.clone()).or_insert_with(|| {
queue.push(r);
next
});
scratch.join(format!("{n}.json"))
})
.collect();
let copy = scratch_config(&current, scratch, numbers[&current], &refs);
std::fs::write(scratch.join(format!("{}.json", numbers[&current])), copy.to_string())?;
i += 1;
}
vec!["-b".into(), path(&scratch.join("0.json"))]
};
args.extend(["--watch", "--pretty", "false", "--preserveWatchOutput"].map(String::from));
Ok(args)
}
/// The project's own `tsc` (`node_modules/.bin` from the configuration's folder up to `root`).
fn local_tsc(root: &Path, dir: &Path) -> Option<PathBuf> {
dir.ancestors()
.take_while(|d| d.starts_with(root))
.find_map(|d| ide_core::tool_path::find_command("tsc", d.join("node_modules/.bin").as_os_str(), dir))
}
/// The messages of one compilation at a time: tsc ends each with
/// `… - Found 2 errors. Watching for file changes.` `tsc -b` reports the errors of every
/// project of the solution that has some, rebuilt this time or not ("out of date because it had
/// errors"), so each compilation's list replaces the last.
#[derive(Default)]
struct Compilations {
parser: Option<OutputParser>,
raws: Vec<RawMessage>,
}
impl Compilations {
fn feed(&mut self, line: &str) -> Option<Vec<RawMessage>> {
let parser = self.parser.get_or_insert_with(|| OutputParser::new(Format::Tsc));
if line.contains("Watching for file changes.") {
self.raws.extend(parser.finish());
return Some(std::mem::take(&mut self.raws));
}
self.raws.extend(parser.feed(line).messages);
None
}
}
/// A scratch folder of this process for `config`, removed when dropped.
struct Scratch(PathBuf);
impl Scratch {
fn new(config: &Path) -> std::io::Result<Self> {
use std::hash::{Hash, Hasher};
let mut hash = std::collections::hash_map::DefaultHasher::new();
config.hash(&mut hash);
let dir = std::env::temp_dir().join("openidea-tsc-watch").join(format!(
"{}-{:016x}",
std::process::id(),
hash.finish()
));
// Fresh: a `.tsbuildinfo` left by an earlier run would make tsc skip unchanged projects.
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir)?;
Ok(Scratch(dir))
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Runs the project's `tsc --watch` on `config` until `cancel` fires or tsc exits, handing the
/// messages of every finished compilation (all of them, an empty list when it passes) to
/// `on_compilation`. Not found when the project has no TypeScript of its own.
pub fn tsc_watch(
root: &Path,
config: &Path,
cancel: &CancellationToken,
mut on_compilation: impl FnMut(Vec<BuildMessage>),
) -> IdeResult<()> {
let dir = config.parent().ok_or_else(|| IdeError::invalid("no tsconfig folder"))?;
let tsc = local_tsc(root, dir).ok_or_else(|| IdeError::not_found("no local typescript"))?;
let scratch = Scratch::new(config)?;
let args = watch_args(config, &scratch.0)?;
let paths = PathMap::new(root);
let mut compilations = Compilations::default();
let program = tsc.to_string_lossy();
process::run_bounded(&program, &args, dir, &BTreeMap::new(), cancel, |_, line| {
if let Some(raws) = compilations.feed(line) {
// Fresh file texts each time: the files changed since the last compilation.
let mut lines = Lines::default();
on_compilation(raws.into_iter().map(|r| resolve(r, dir, &paths, &mut lines)).collect());
}
})?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn write(dir: &Path, rel: &str, text: &str) {
let p = dir.join(rel);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, text).unwrap();
}
#[test]
fn roots_are_the_configurations_no_other_one_references() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
// A solution with references (one by folder, one by file), plus an unrelated package.
write(
root,
"tsconfig.json",
r#"{ "files": [], // solution
"references": [{ "path": "./packages/a" }, { "path": "packages/b/tsconfig.json" },] }"#,
);
write(root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
write(root, "packages/b/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
write(root, "tools/cli/tsconfig.json", "{}");
let found = ["tools/cli", "packages/b", "", "packages/a"].map(|d| root.join(d).join("tsconfig.json"));
assert_eq!(tsc_watch_roots(found.to_vec()), [root.join("tsconfig.json"), root.join("tools/cli/tsconfig.json")]);
}
#[test]
fn a_solution_is_checked_through_scratch_copies_of_its_configurations() {
let tmp = tempfile::tempdir().unwrap();
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
std::fs::create_dir_all(&scratch).unwrap();
write(
&root,
"tsconfig.json",
r#"{"files": [], "references": [{"path": "./packages/a"}, {"path": "./packages/b"}]}"#,
);
// a: composite, every setting by default.
write(&root, "packages/a/tsconfig.json", r#"{"compilerOptions": {"composite": true}}"#);
// b: references a, settles its files, outputs and root in a shared base.
write(
&root,
"packages/b/tsconfig.json",
r#"{"extends": "../../tsconfig.base", "references": [{"path": "../a"}], "compilerOptions": {"outFile": "b.js"}}"#,
);
write(
&root,
"tsconfig.base.json",
r#"{"compilerOptions": {"composite": true, "rootDir": ".", "outDir": "dist", "declarationDir": "types"},
"include": ["packages/*/src"]}"#,
);
let args = watch_args(&root.join("tsconfig.json"), &scratch).unwrap();
let s = |p: &str| scratch.join(p).to_string_lossy().into_owned();
assert_eq!(args, ["-b", &s("0.json"), "--watch", "--pretty", "false", "--preserveWatchOutput"]);
let copy = |n: usize| read_json(&scratch.join(format!("{n}.json"))).unwrap();
let path = |p: &Path| json!(p);
assert_eq!(
copy(0),
json!({
"extends": path(&root.join("tsconfig.json")),
"compilerOptions": {"outDir": path(&scratch.join("0")), "tsBuildInfoFile": s("0.tsbuildinfo")},
"references": [{"path": s("1.json")}, {"path": s("2.json")}],
"exclude": [path(&root.join("node_modules"))],
})
);
let a = root.join("packages/a");
assert_eq!(
copy(1),
json!({
"extends": path(&a.join("tsconfig.json")),
"compilerOptions": {
"outDir": path(&scratch.join("1")), "tsBuildInfoFile": s("1.tsbuildinfo"), "rootDir": path(&a),
},
"references": [],
"include": [path(&a.join("**/*"))],
"exclude": [path(&a.join("node_modules"))],
})
);
let b = root.join("packages/b");
assert_eq!(
copy(2),
json!({
"extends": path(&b.join("tsconfig.json")),
"compilerOptions": {
"outDir": path(&scratch.join("2")), "tsBuildInfoFile": s("2.tsbuildinfo"),
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2/out.js")),
},
"references": [{"path": s("1.json")}],
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
})
);
}
#[test]
fn a_composite_package_base_gets_its_root_folder() {
let tmp = tempfile::tempdir().unwrap();
let (root, scratch) = (tmp.path().join("p"), tmp.path().join("scratch"));
write(&root, "node_modules/@acme/tsconfig/base.json", r#"{"compilerOptions": {"composite": true}}"#);
write(&root, "app/tsconfig.json", r#"{"extends": "@acme/tsconfig/base", "include": ["src"]}"#);
let copy = scratch_config(&root.join("app/tsconfig.json"), &scratch, 3, &[]);
assert_eq!(copy["compilerOptions"]["rootDir"], json!(root.join("app")));
assert_eq!(copy.get("include"), None, "the files come from the real configuration");
}
#[test]
fn each_compilation_reports_its_own_messages() {
// `tsc --noEmit --watch --pretty false --preserveWatchOutput`, as printed.
let output = "\
2:14:08 PM - Starting compilation in watch mode...
2:14:09 PM - Found 0 errors. Watching for file changes.
2:14:12 PM - File change detected. Starting incremental compilation...
src/b.ts(1,37): error TS2322: Type 'string' is not assignable to type 'number'.
src/c.ts(2,1): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
Type 'string' is not assignable to type 'number'.
2:14:12 PM - Found 2 errors. Watching for file changes.
2:14:15 PM - File change detected. Starting incremental compilation...
2:14:15 PM - Found 0 errors. Watching for file changes.";
let mut compilations = Compilations::default();
let found: Vec<Vec<(String, Option<String>)>> = output
.lines()
.filter_map(|l| compilations.feed(l))
.map(|raws| raws.into_iter().map(|r| (r.path.unwrap_or_default(), r.code)).collect())
.collect();
assert_eq!(
found,
[
vec![],
vec![("src/b.ts".into(), Some("TS2322".into())), ("src/c.ts".into(), Some("TS2345".into()))],
vec![]
]
);
}
#[cfg(unix)]
#[test]
fn the_projects_tsc_reports_until_cancelled() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write(root, "app/tsconfig.json", "{}");
write(root, "app/src/b.ts", "export const b: number = a;\n");
// A watcher that prints one compilation and keeps running, like `tsc --watch`.
write(
root,
"node_modules/.bin/tsc",
"#!/bin/sh\necho \"$@\" > args.txt\n\
echo 'src/b.ts(1,26): error TS2322: Type string is not assignable to type number.'\n\
echo '1:00:00 PM - Found 1 error. Watching for file changes.'\nexec sleep 30\n",
);
let bin = root.join("node_modules/.bin/tsc");
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
let cancel = CancellationToken::new();
let mut compilations = Vec::new();
let started = std::time::Instant::now();
let result = tsc_watch(root, &root.join("app/tsconfig.json"), &cancel, |messages| {
compilations.push(messages);
cancel.cancel();
});
assert_eq!(result.unwrap_err().kind, ide_core::error::ErrorKind::Cancelled);
assert!(started.elapsed().as_secs() < 10, "cancelling stops the watcher");
let [messages] = &compilations[..] else { panic!("{compilations:?}") };
let paths: Vec<_> = messages.iter().map(|m| (m.path.clone().map(PathBuf::from), m.range)).collect();
let at = |l, c| ide_core::Pos::new(l, c);
assert_eq!(paths, [(Some(root.join("app/src/b.ts")), Some(ide_core::Range::new(at(0, 25), at(0, 26))))]);
let args = std::fs::read_to_string(root.join("app/args.txt")).unwrap();
let (check, rest) = args.trim().split_once(" --tsBuildInfoFile ").unwrap();
assert_eq!(check, "--noEmit -p tsconfig.json --incremental");
let (info, watch) = rest.split_once(' ').unwrap();
assert_eq!(watch, "--watch --pretty false --preserveWatchOutput");
// The `.tsbuildinfo` goes to a scratch folder outside the project, gone with the watcher.
let scratch = Path::new(info).parent().unwrap();
assert!(scratch.starts_with(std::env::temp_dir()) && !scratch.starts_with(root), "{info}");
assert!(!scratch.exists());
}
#[test]
fn no_local_typescript_runs_nothing() {
let tmp = tempfile::tempdir().unwrap();
write(tmp.path(), "tsconfig.json", "{}");
let err = tsc_watch(tmp.path(), &tmp.path().join("tsconfig.json"), &CancellationToken::new(), |_| {
panic!("no compilation without typescript")
})
.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::NotFound);
}
}
+7 -5
Переглянути файл
@@ -441,7 +441,7 @@ impl JavaBuild<'_> {
let record = model::load_record(&model::reactor_dir(self.cache, &top.key()))?;
let project = record.model.projects.iter().find(|p| p.dir == module)?;
let paths = class_paths(project, test);
paths.first().is_some_and(|p| p.is_dir()).then_some(paths)
paths.first().is_some_and(|p| p.exists()).then_some(paths)
}
/// Builds `target`. A launch gets the classpath to run with; the others an empty one.
@@ -1039,7 +1039,7 @@ fn launch_projects<'a>(model: &'a ReactorModel, target: &'a ProjectModel, test:
if test {
visit(project, false, by_output, by_test_output, seen, out);
}
for entry in &project.set(test).classpath {
for entry in project.set(test).classpath.iter().chain(&project.set(test).runtime_classpath) {
if let Some(upstream) = by_output.get(entry.as_path()).filter(|p| p.dir != project.dir) {
visit(upstream, false, by_output, by_test_output, seen, out);
} else if let Some(upstream) = by_test_output.get(entry.as_path()).filter(|p| p.dir != project.dir) {
@@ -1061,10 +1061,12 @@ fn class_paths(target: &ProjectModel, test: bool) -> Vec<PathBuf> {
out.push(p.clone());
}
};
if test {
push(&target.test.output);
if target.packaging != "pom" {
if test {
push(&target.test.output);
}
push(&target.main.output);
}
push(&target.main.output);
for entry in &target.set(test).runtime_classpath {
push(entry);
}
+71
Переглянути файл
@@ -486,6 +486,38 @@ pub struct LanguageCodeStyle {
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier_case: Option<String>,
/// Java: organize imports switches to a wildcard import once this many
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
/// 5; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub class_count_to_use_import_with_star: Option<u32>,
/// Java: organize imports switches to a wildcard static import once this
/// many statically imported names are used (jdtls `staticStarThreshold`;
/// IDEA's default 3; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub names_count_to_use_static_import_with_star: Option<u32>,
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
#[serde(skip_serializing_if = "Option::is_none")]
pub semicolons: Option<String>,
/// JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`.
#[serde(skip_serializing_if = "Option::is_none")]
pub quotes: Option<String>,
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub spaces: BTreeMap<String, bool>,
/// JavaScript / TypeScript › Imports › Import paths:
/// `shortest` | `relative` | `non-relative` | `project-relative`.
#[serde(skip_serializing_if = "Option::is_none")]
pub import_module_specifier: Option<String>,
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
#[serde(skip_serializing_if = "Option::is_none")]
pub import_module_specifier_ending: Option<String>,
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub auto_import_file_exclude_patterns: Vec<String>,
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub auto_import_specifier_exclude_regexes: Vec<String>,
}
/// Editor › Code Style (General tab + per-language overrides).
@@ -543,6 +575,25 @@ pub struct EncodingSettings {
pub native_to_ascii: bool,
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
pub utf8_bom: String,
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
/// relative to the project with `/` separators. The status bar's choice is kept here.
#[serde(deserialize_with = "labels")]
#[specta(type = BTreeMap<String, String>)]
pub mappings: BTreeMap<String, String>,
}
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
return Ok(BTreeMap::new());
};
Ok(entries
.into_iter()
.filter_map(|(path, label)| match label {
serde_json::Value::String(label) => Some((path, label)),
_ => None,
})
.collect())
}
impl Default for EncodingSettings {
@@ -553,10 +604,30 @@ impl Default for EncodingSettings {
properties: "iso-8859-1".into(),
native_to_ascii: false,
utf8_bom: "never".into(),
mappings: BTreeMap::new(),
}
}
}
#[cfg(test)]
mod encoding_mappings_tests {
use super::EncodingSettings;
#[test]
fn encoding_mappings_keep_the_entries_that_are_labels() {
let json = serde_json::json!({
"project": "gbk",
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
});
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
assert_eq!(settings.project, "gbk");
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
assert!(not_a_table.mappings.is_empty());
assert!(EncodingSettings::default().mappings.is_empty());
}
}
#[cfg(test)]
mod auto_import_tests {
use super::{AutoImportSettings, ImportsOnPaste};
+124 -11
Переглянути файл
@@ -14,10 +14,33 @@ pub type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
struct Entry {
root: PathBuf,
direnv: Vec<(OsString, Option<OsString>)>,
github_token: Option<OsString>,
changes: Changes,
loading: bool,
}
impl Entry {
fn new(root: PathBuf) -> Self {
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
}
fn rebuild(&mut self) {
let mut combined = Vec::with_capacity(self.direnv.len() + usize::from(self.github_token.is_some()));
if let Some(token) = &self.github_token {
combined.push(("GH_TOKEN".into(), Some(token.clone())));
}
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
combined.extend(self.direnv.iter().cloned());
self.changes = Arc::new(combined);
}
fn is_idle_empty(&self) -> bool {
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
}
}
static ENTRIES: Mutex<Vec<Entry>> = Mutex::new(Vec::new());
static SETTLED: Condvar = Condvar::new();
@@ -31,35 +54,103 @@ pub fn begin_loading(root: &Path) {
let mut entries = entries();
match entries.iter_mut().find(|e| e.root == root) {
Some(entry) => entry.loading = true,
None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }),
None => {
let mut entry = Entry::new(root.to_path_buf());
entry.loading = true;
entries.push(entry);
}
}
}
/// What children started in `root` (or below it) get on top of the IDE's own environment
/// (`None`: removed). Ends a [`begin_loading`].
/// What children started in `root` (or below it) get from direnv on top of the IDE's own
/// environment (`None`: removed). Ends a [`begin_loading`].
pub fn set(root: &Path, changes: Vec<(OsString, Option<OsString>)>) {
let mut entries = entries();
let changes = Arc::new(changes);
match entries.iter_mut().find(|e| e.root == root) {
Some(entry) => {
entry.changes = changes;
match entries.iter_mut().position(|e| e.root == root) {
Some(idx) => {
let entry = &mut entries[idx];
entry.direnv = changes;
entry.loading = false;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
}
None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }),
None if !changes.is_empty() => {
let mut entry = Entry::new(root.to_path_buf());
entry.direnv = changes;
entry.rebuild();
entries.push(entry);
}
None => {}
}
SETTLED.notify_all();
}
/// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays.
pub fn settle(root: &Path) {
if let Some(entry) = entries().iter_mut().find(|e| e.root == root) {
entry.loading = false;
let mut entries = entries();
if let Some(idx) = entries.iter().position(|e| e.root == root) {
entries[idx].loading = false;
if entries[idx].is_idle_empty() {
entries.remove(idx);
}
}
SETTLED.notify_all();
}
/// `root` has no environment of its own any more (closed, or not trusted).
/// `root` has no direnv environment of its own any more (no `.envrc`, closed, or not trusted).
/// Preserves any project-scoped GitHub token until [`remove_all`] or [`set_github_token`].
pub fn remove(root: &Path) {
let mut entries = entries();
if let Some(idx) = entries.iter().position(|e| e.root == root) {
let entry = &mut entries[idx];
entry.direnv.clear();
entry.loading = false;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
}
SETTLED.notify_all();
}
/// Sets or clears the project-scoped `GH_TOKEN` injected for children started in `root`
/// (unless overridden by `root`'s direnv `.envrc`). Returns whether the effective token changed.
pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
let token = token.filter(|t| !t.is_empty());
let mut entries = entries();
match entries.iter().position(|e| e.root == root) {
Some(idx) => {
if entries[idx].github_token == token {
return false;
}
let entry = &mut entries[idx];
entry.github_token = token;
entry.rebuild();
if entry.is_idle_empty() {
entries.remove(idx);
}
true
}
None => {
let Some(token) = token else { return false };
let mut entry = Entry::new(root.to_path_buf());
entry.github_token = Some(token);
entry.rebuild();
entries.push(entry);
true
}
}
}
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
pub fn github_token(dir: &Path) -> Option<OsString> {
find(&entries(), dir).and_then(|e| e.github_token.clone())
}
/// Removes both direnv and project GitHub token entries for `root` (project closed or untrusted).
pub fn remove_all(root: &Path) {
entries().retain(|e| e.root != root);
SETTLED.notify_all();
}
@@ -135,4 +226,26 @@ mod tests {
assert_eq!(*for_dir(root), [change("NEW", Some("2"))]);
remove(root);
}
#[test]
fn github_token_survives_direnv_absence_and_yields_to_explicit_envrc_override() {
let root = Path::new("/openidea-test-env/gh-project");
let worktrees = Path::new("/openidea-test-env/gh-project.worktrees");
assert!(set_github_token(root, Some("gho_work".into())));
assert!(!set_github_token(root, Some("gho_work".into())), "idempotent");
assert!(set_github_token(worktrees, Some("gho_work".into())));
remove(root); // no `.envrc` in `root`
assert_eq!(*for_dir(&root.join("src")), [change("GH_TOKEN", Some("gho_work"))]);
assert_eq!(*for_dir(&worktrees.join("task-1")), [change("GH_TOKEN", Some("gho_work"))]);
assert_eq!(github_token(&worktrees.join("task-1")), Some("gho_work".into()));
// An explicit `.envrc` GH_TOKEN overrides the project GitHub account token.
set(root, vec![change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
assert_eq!(*for_dir(root), [change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
remove_all(root);
remove_all(worktrees);
assert!(for_dir(root).is_empty());
assert!(for_dir(worktrees).is_empty());
}
}
+22 -3
Переглянути файл
@@ -432,6 +432,12 @@ pub struct ToolDownloadSettings {
/// commas or whitespace and tried in order before the official host; empty keeps every
/// download on its official host.
pub github_mirror: String,
/// Package registries only as configured (a company Nexus or Artifactory): npm and pnpm
/// installs and update checks never retry against the public npm registry, and the IDE
/// fetches nothing from public package registries itself (the JUnit Platform launcher from
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
/// crates.io). Off by default.
pub configured_registries_only: bool,
}
/// Absent profiles retain automatic discovery for existing projects.
@@ -1212,6 +1218,8 @@ pub struct LanguagesSettings {
pub prettier: ExternalFormatterSettings,
pub oxfmt: ExternalFormatterSettings,
pub biome: ExternalFormatterSettings,
/// dprint formats every file its configuration covers: `languages` is unused.
pub dprint: ExternalFormatterSettings,
pub ruff: ExternalFormatterSettings,
pub black: ExternalFormatterSettings,
pub java: JavaSettings,
@@ -1238,6 +1246,7 @@ impl Default for LanguagesSettings {
languages: BIOME_LANGUAGES.iter().map(|&l| l.into()).collect(),
..ExternalFormatterSettings::default()
},
dprint: ExternalFormatterSettings { languages: Vec::new(), ..ExternalFormatterSettings::default() },
ruff: ExternalFormatterSettings {
languages: vec!["python".into()],
..ExternalFormatterSettings::default()
@@ -1315,6 +1324,7 @@ impl LanguagesSettings {
ExternalFormatter::Prettier => &self.prettier,
ExternalFormatter::Oxfmt => &self.oxfmt,
ExternalFormatter::Biome => &self.biome,
ExternalFormatter::Dprint => &self.dprint,
ExternalFormatter::Ruff => &self.ruff,
ExternalFormatter::Black => &self.black,
}
@@ -1328,6 +1338,7 @@ pub enum ExternalFormatter {
Prettier,
Oxfmt,
Biome,
Dprint,
Ruff,
Black,
}
@@ -1339,6 +1350,7 @@ impl ExternalFormatter {
Self::Prettier => "prettier",
Self::Oxfmt => "oxfmt",
Self::Biome => "biome",
Self::Dprint => "dprint",
Self::Ruff => "ruff",
Self::Black => "black",
}
@@ -1349,11 +1361,11 @@ impl ExternalFormatter {
pub const BIOME_LANGUAGES: [&str; 8] =
["css", "graphql", "javascript", "javascriptreact", "typescript", "typescriptreact", "json", "jsonc"];
/// An external formatter (Prettier, oxfmt, Biome, Ruff, Black) and the languages it formats.
/// An external formatter (Prettier, oxfmt, Biome, dprint, Ruff, Black) and the languages it formats.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct ExternalFormatterSettings {
/// Empty path: project node_modules (Prettier/oxfmt/Biome), managed installation, then PATH.
/// Empty path: project node_modules (Prettier/oxfmt/Biome/dprint), managed installation, then PATH.
pub path: String,
/// Ruff only: directory containing its configuration, or a configuration file.
pub configuration_directory: String,
@@ -1414,6 +1426,9 @@ pub struct PythonSettings {
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
/// by interpreter executable; absolute or `~/`.
pub interpreter_paths: BTreeMap<String, Vec<String>>,
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
/// it, else unittest), `pytest` or `unittest`.
pub test_runner: String,
}
impl Default for PythonSettings {
@@ -1426,6 +1441,7 @@ impl Default for PythonSettings {
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
test_runner: "auto".into(),
}
}
}
@@ -1724,11 +1740,14 @@ pub struct TypeScriptSettings {
/// plugin (hybrid mode; a Vue project's program alone needs ~3 GiB, and the
/// vtsls default 3072 dies in a GC death spiral), else unset (vtsls default).
pub tsserver_max_memory: u32,
/// Problems › TypeScript project errors: the project's own `tsc --watch` per root
/// `tsconfig.json` reports the errors of files that are not open.
pub watch_problems: bool,
}
impl Default for TypeScriptSettings {
fn default() -> Self {
Self { version: "bundled".into(), tsserver_max_memory: 0 }
Self { version: "bundled".into(), tsserver_max_memory: 0, watch_problems: false }
}
}
+32
Переглянути файл
@@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
}
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
&[r"C:\Program Files\GitHub CLI\gh.exe"]
} else {
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
};
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
/// only when installed, then the user's `PATH`), and standard OS install locations.
pub fn find_gh_executable() -> Option<PathBuf> {
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
}
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
return Some(explicit);
}
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
}
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
return Some(explicit.to_path_buf());
}
if let Some(found) = find_command("gh", search, Path::new("")) {
return Some(found);
}
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
}
fn is_executable(path: &Path) -> bool {
let Ok(metadata) = path.metadata() else { return false };
#[cfg(unix)]
+12
Переглянути файл
@@ -25,6 +25,17 @@ pub struct VcsSettings {
pub issue_navigation: Vec<IssueLink>,
/// Directory Mappings: repository roots added to or excluded from the detected ones.
pub mappings: VcsMappings,
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
pub github: GithubSettings,
}
/// Settings › Version Control › GitHub (`vcs.github`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct GithubSettings {
/// GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project.
/// Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected).
pub account: String,
}
/// Directory Mappings on top of repository detection. Paths are relative to the project
@@ -68,6 +79,7 @@ impl Default for VcsSettings {
shelf: ShelfSettings::default(),
issue_navigation: Vec::new(),
mappings: VcsMappings::default(),
github: GithubSettings::default(),
}
}
}
+28 -3
Переглянути файл
@@ -157,6 +157,10 @@ pub struct ColumnInfo {
pub nullable: bool,
pub default: Option<String>,
pub primary_key: bool,
/// `None` when it has none, or the engine keeps no comments.
#[serde(default)]
#[specta(optional)]
pub comment: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
@@ -172,6 +176,10 @@ pub struct IndexInfo {
#[serde(rename_all = "camelCase")]
#[serde(rename = "DbTableDetails")]
pub struct TableDetails {
/// The table's comment; `None` when it has none, or the engine keeps no comments.
#[serde(default)]
#[specta(optional)]
pub comment: Option<String>,
pub columns: Vec<ColumnInfo>,
pub indexes: Vec<IndexInfo>,
pub foreign_keys: Vec<ForeignKey>,
@@ -1119,11 +1127,18 @@ impl DbManager {
let nullable = flag(&it.next().flatten());
let default = it.next().flatten();
let primary_key = flag(&it.next().flatten());
Some(ColumnInfo { name, data_type, nullable, default, primary_key })
let comment = it.next().flatten().filter(|c| !c.is_empty());
Some(ColumnInfo { name, data_type, nullable, default, primary_key, comment })
})
.collect();
if driver == DbDriver::Jdbc {
return Ok(TableDetails { columns, indexes: vec![], foreign_keys: vec![], triggers: vec![] });
return Ok(TableDetails {
comment: None,
columns,
indexes: vec![],
foreign_keys: vec![],
triggers: vec![],
});
}
let mut indexes: Vec<IndexInfo> = Vec::new();
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
@@ -1175,7 +1190,17 @@ impl DbManager {
Some(TriggerInfo { name, timing, events })
})
.collect();
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
let comment = match sql::table_comment(driver, schema, table) {
Some(q) => pool.rows(&q, 1).await.map_or_else(
|e| {
tracing::warn!("table comment: {}", e.message);
None
},
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
),
None => None,
};
Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers })
}
/// The object privileges granted on `table`; empty, without a query, on the engines
+11 -1
Переглянути файл
@@ -132,6 +132,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
nullable: yes(r.get("null?")),
default: r.get("default").filter(|d| !d.is_empty()).map(str::to_owned),
primary_key: yes(r.get("primary key")),
comment: r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned),
})
})
.collect();
@@ -140,7 +141,16 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
Ok(keys) => foreign_keys(&keys),
Err(_) => Vec::new(),
};
Ok(TableDetails { columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
// `LIKE` matches without case and with wildcards: the exact name picks the row.
let like = format!("SHOW TABLES LIKE {} IN SCHEMA {}", quote_literal(DRIVER, table), schema_path(pool, schema));
let comment = match show(pool, &like).await {
Ok(shown) => shown
.records()
.find(|r| r.get("name") == Some(table))
.and_then(|r| r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned)),
Err(_) => None,
};
Ok(TableDetails { comment, columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
}
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
+47 -5
Переглянути файл
@@ -145,7 +145,8 @@ const SNOWFLAKE_TYPE: &str = "CASE WHEN data_type = 'NUMBER' THEN 'NUMBER(' || n
WHEN data_type = 'TEXT' THEN 'VARCHAR(' || character_maximum_length || ')' \
WHEN data_type LIKE 'TIME%' THEN data_type || '(' || datetime_precision || ')' ELSE data_type END";
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`.
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`, and the column's
/// comment on the engines that keep one (PostgreSQL, MySQL, Oracle, ClickHouse).
pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
@@ -153,7 +154,7 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
DbDriver::Clickhouse => format!(
"SELECT name, type, CASE WHEN startsWith(type, 'Nullable(') \
OR startsWith(type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, \
if(default_kind = '', NULL, default_expression), is_in_primary_key \
if(default_kind = '', NULL, default_expression), is_in_primary_key, comment \
FROM system.columns WHERE database = {s} AND table = {t} ORDER BY position"
),
DbDriver::Sqlite => format!(
@@ -166,13 +167,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
col_description(format('%I.%I', c.table_schema, c.table_name)::regclass, c.ordinal_position::int) \
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
ORDER BY c.ordinal_position"
),
DbDriver::Mysql => format!(
"SELECT column_name, column_type, is_nullable, column_default, \
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END \
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END, column_comment \
FROM information_schema.columns WHERE table_schema = {s} AND table_name = {t} \
ORDER BY ordinal_position"
),
@@ -192,8 +194,10 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
),
DbDriver::Oracle => format!(
"SELECT c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), c.data_default, \
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END \
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
FROM all_tab_columns c \
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
AND cc.column_name = c.column_name \
LEFT JOIN (SELECT kc.column_name FROM all_constraints con \
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
AND kc.constraint_name = con.constraint_name \
@@ -204,6 +208,28 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
}
}
/// One row, one column: the table's comment (`NULL` or empty for none). `None` for the
/// engines whose comments the IDE doesn't read here (Snowflake reads it with `SHOW`).
pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
match driver {
DbDriver::Postgres => Some(format!(
"SELECT obj_description(c.oid, 'pg_class') FROM pg_class c \
JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = {s} AND c.relname = {t}"
)),
// A view's `table_comment` is the word `VIEW`.
DbDriver::Mysql => Some(format!(
"SELECT CASE WHEN table_type = 'VIEW' THEN NULL ELSE table_comment END \
FROM information_schema.tables WHERE table_schema = {s} AND table_name = {t}"
)),
DbDriver::Oracle => {
Some(format!("SELECT comments FROM all_tab_comments WHERE owner = {s} AND table_name = {t}"))
}
DbDriver::Clickhouse => Some(format!("SELECT comment FROM system.tables WHERE database = {s} AND name = {t}")),
_ => None,
}
}
/// Rows: `index name, unique (0/1), column` (one row per indexed column, in order).
// Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the
// most columns an index or key has): unlike a series per catalog row, it lets the planner find the
@@ -956,6 +982,22 @@ mod tests {
assert_eq!(quote_literal(DbDriver::Mysql, "it's \\"), "'it''s \\\\'");
}
#[test]
fn comments_are_read_where_the_engine_keeps_them() {
assert!(columns(DbDriver::Postgres, "public", "t").contains("col_description("));
assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment"));
assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments"));
assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment"));
let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap();
assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}");
assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment"));
assert!(table_comment(DbDriver::Oracle, "S", "T").unwrap().contains("all_tab_comments"));
assert!(table_comment(DbDriver::Clickhouse, "db", "t").unwrap().contains("system.tables"));
for driver in [DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Snowflake] {
assert_eq!(table_comment(driver, "s", "t"), None);
}
}
#[test]
fn clickhouse_escapes_backslashes_and_delimiters() {
let driver = DbDriver::Clickhouse;
+110 -8
Переглянути файл
@@ -1,5 +1,5 @@
use ide_core::{CancellationToken, IdeResult};
use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, SortKey};
use ide_db::{DataSource, DbDriver, DbJdbcDriver, DbManager, DbProperty, SortKey};
use std::{path::Path, sync::Arc};
fn manager(dir: &Path) -> DbManager {
@@ -89,21 +89,25 @@ async fn named_jdbc_sources_persist_the_type_and_reject_a_profile_for_another_ty
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
fn register_duckdb(db: &DbManager, vendor: Option<&str>) -> IdeResult<()> {
let jar = std::env::var("DUCKDB_JDBC_JAR").expect("DUCKDB_JDBC_JAR");
assert_eq!(ide_db::jdbc_driver_classes(std::slice::from_ref(&jar))?, ["org.duckdb.DuckDBDriver"]);
db.save_jdbc_driver(DbJdbcDriver {
id: "duck".into(),
name: "DuckDB".into(),
vendor: None,
vendor: vendor.map(str::to_owned),
jars: vec![jar],
class_name: "org.duckdb.DuckDBDriver".into(),
url_template: "jdbc:duckdb:".into(),
})?;
})
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
register_duckdb(&db, None)?;
let source = DataSource {
id: "test".into(),
name: "DuckDB".into(),
@@ -157,6 +161,104 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_named_file_enforces_read_only_at_open() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
register_duckdb(&db, Some("duckdb"))?;
let file = tmp.path().join("example.duckdb");
let mut source = DataSource {
id: "test".into(),
name: "DuckDB".into(),
driver: DbDriver::Jdbc,
vendor: "duckdb".into(),
global: true,
jdbc_driver: "duck".into(),
url: format!("jdbc:duckdb:{}", file.display()),
file: Some(file.clone().into()),
read_only: true,
..Default::default()
};
let cancel = CancellationToken::new();
let err = db.test(&source, None, None).await.unwrap_err();
assert!(err.message.contains("existing database file"), "{}", err.message);
assert!(!file.exists());
source.read_only = false;
db.save_sources(vec![source.clone()]).await?;
db.execute("test", "create table items (id int)", 1, &cancel).await?;
db.execute("test", "insert into items values (1)", 1, &cancel).await?;
db.disconnect("test").await;
source.read_only = true;
let reopened = manager(tmp.path());
assert!(reopened.test(&source, None, None).await?.to_lowercase().contains("duckdb"));
let mut conflicting = source.clone();
for options in ["; access_mode = READ_WRITE", "; duckdb.read_only = false"] {
conflicting.url = format!("{}{options}", source.url);
let err = reopened.test(&conflicting, None, None).await.unwrap_err();
assert!(err.message.contains("conflicts with Read-only"), "{}", err.message);
}
conflicting.url = source.url.clone();
conflicting.properties.push(DbProperty { name: "ACCESS_MODE".into(), value: "READ_WRITE".into() });
let err = reopened.test(&conflicting, None, None).await.unwrap_err();
assert!(err.message.contains("conflicts with Read-only"), "{}", err.message);
reopened.save_sources(vec![source.clone()]).await?;
assert_eq!(reopened.source("test")?.vendor, "duckdb");
assert_eq!(reopened.execute("test", "select id from items", 1, &cancel).await?.rows, [vec![Some("1".into())]]);
for query in ["insert into items values (2)", "create table added (id int)"] {
let err = reopened.execute("test", query, 1, &cancel).await.unwrap_err();
assert!(err.message.to_lowercase().contains("read-only"), "{}", err.message);
}
assert!(!reopened.tables("test", "main").await?.iter().any(|table| table.name == "added"));
reopened.disconnect("test").await;
source.read_only = false;
reopened.save_sources(vec![source]).await?;
reopened.execute("test", "insert into items values (2)", 1, &cancel).await?;
assert_eq!(
reopened.execute("test", "select count(*) from items", 1, &cancel).await?.rows,
[vec![Some("2".into())]]
);
reopened.disconnect("test").await;
Ok(())
}
#[tokio::test]
#[ignore = "requires DUCKDB_JDBC_JAR and a local Java 17+ runtime"]
async fn duckdb_named_memory_lives_until_disconnect() -> IdeResult<()> {
let tmp = tempfile::tempdir()?;
let db = manager(tmp.path());
register_duckdb(&db, Some("duckdb"))?;
let mut source = DataSource {
id: "test".into(),
name: "DuckDB (memory)".into(),
driver: DbDriver::Jdbc,
vendor: "duckdb".into(),
global: true,
jdbc_driver: "duck".into(),
url: "jdbc:duckdb:".into(),
..Default::default()
};
let cancel = CancellationToken::new();
db.save_sources(vec![source.clone()]).await?;
db.execute("test", "create table session_items as select 42 as id", 1, &cancel).await?;
assert_eq!(db.execute("test", "select id from session_items", 1, &cancel).await?.rows, [vec![Some("42".into())]]);
db.disconnect("test").await;
assert!(!db.tables("test", "main").await?.iter().any(|table| table.name == "session_items"));
db.disconnect("test").await;
source.read_only = true;
for url in ["jdbc:duckdb:", "jdbc:duckdb::memory:"] {
source.url = url.into();
let err = db.test(&source, None, None).await.unwrap_err();
assert!(err.message.contains("existing database file"), "{}", err.message);
}
Ok(())
}
#[tokio::test]
#[ignore = "requires CLICKHOUSE_JDBC_CLASSPATH and a loopback ClickHouse fixture on CLICKHOUSE_JDBC_TEST_PORT"]
async fn clickhouse_vendor_driver_reads_catalog_and_results() -> IdeResult<()> {
+5 -1
Переглянути файл
@@ -40,7 +40,8 @@ async fn create_schemas(db: &DbManager) {
format!("DROP DATABASE IF EXISTS `{s}`"),
format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"),
format!(
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin, raw VARBINARY(4))"
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin COMMENT '名字', \
raw VARBINARY(4)) COMMENT = '用户表'"
),
format!("CREATE INDEX `名字` ON `{s}`.`用户` (name)"),
format!("INSERT INTO `{s}`.`用户` VALUES (1, 'ann', 0xCAFE)"),
@@ -59,6 +60,9 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
let d = db.table_details("m", s, "用户").await?;
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
assert_eq!(cols, ["id", "name", "raw"]);
assert_eq!(d.comment.as_deref(), Some("用户表"));
let comments: Vec<_> = d.columns.iter().map(|c| c.comment.as_deref()).collect();
assert_eq!(comments, [None, Some("名字"), None]);
assert!(d.indexes.iter().any(|i| i.name == "名字"), "{:?}", d.indexes);
assert!(db.ddl("m", s, "用户").await?.contains("CREATE TABLE `用户`"));
}
+6
Переглянути файл
@@ -338,6 +338,8 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
"CREATE TABLE oi_meta.lines (n INT PRIMARY KEY, o_region INT, o_id INT, \
FOREIGN KEY (o_region, o_id) REFERENCES oi_meta.orders (region, id))",
"CREATE INDEX lines_order ON oi_meta.lines (o_id, o_region)",
"COMMENT ON TABLE oi_meta.orders IS 'Customer''s orders'",
"COMMENT ON COLUMN oi_meta.orders.note IS 'Free text'",
"CREATE FUNCTION oi_meta.twice(v INT) RETURNS INT AS 'SELECT v * 2' LANGUAGE sql",
] {
db.execute("p", stmt, 10, &c).await?;
@@ -350,6 +352,10 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
assert_eq!(details.foreign_keys[0].columns, ["o_region", "o_id"]);
assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]);
let orders = db.table_details("p", "oi_meta", "orders").await?;
assert_eq!(orders.comment.as_deref(), Some("Customer's orders"));
let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect();
assert_eq!(comments, [None, None, Some("Free text")]);
assert_eq!(details.comment, None);
let key = orders.indexes.iter().find(|i| i.unique).expect("primary key index");
assert_eq!(key.columns, ["region", "id"]);
+126 -16
Переглянути файл
@@ -46,6 +46,13 @@ pub enum Capability {
/// the manifest does not list; each answer applies to one host. Plain
/// HTTP elsewhere always needs `net.http:<host>`.
NetAsk,
/// The host of the `string` setting `key`, approved when the user applies
/// its value in Settings (`net:setting:server`, `net.http:setting:server`).
/// HTTPS (and loopback HTTP) unless `http`.
NetSetting {
http: bool,
key: String,
},
/// Unencrypted HTTP to one host.
NetHttp(String),
/// A local socket or named pipe on the project machine.
@@ -62,6 +69,8 @@ pub enum Capability {
/// Load the plugin's Java agent into the JVMs of Java run configurations. Never
/// declared: it comes from `[[contributes.javaAgents]]`.
JavaAgent,
/// Fork a recorded native agent session into a new task in the open project (API 1.18).
Agents,
}
/// How a grant is presented (plan 4.2).
@@ -87,11 +96,13 @@ impl Capability {
| Self::VcsWrite
| Self::Net(_)
| Self::NetAsk
| Self::NetSetting { .. }
| Self::NetHttp(_)
| Self::Secrets
| Self::InputEvents
| Self::Clipboard
| Self::ClipboardRead => Risk::Medium,
| Self::ClipboardRead
| Self::Agents => Risk::Medium,
// A trusted project's own files name the programs the IDE starts (its settings, its
// build scripts), so writing them is running code.
Self::ProjectWrite
@@ -136,6 +147,12 @@ impl Capability {
"Ask to connect to a host that is not on the list the first time it tries; you allow or refuse each host, and can revoke the allowed ones"
.into()
}
Self::NetSetting { http, key } if *http => {
format!("Connect to the host set in the `{key}` setting over unencrypted HTTP (from the machine the project is on)")
}
Self::NetSetting { http: _, key } => {
format!("Connect to the host set in the `{key}` setting (from the machine the project is on)")
}
Self::NetHttp(host) => {
format!("Connect to {host} over unencrypted HTTP (from the machine the project is on)")
}
@@ -149,6 +166,7 @@ impl Capability {
Self::FsRead(path) => format!("Read files under {path}, outside the project"),
Self::FsWrite(path) => format!("Change files under {path}, outside the project"),
Self::JavaAgent => "Run code inside the Java applications you start".into(),
Self::Agents => "Fork a recorded agent session into a new task in the open project".into(),
}
}
@@ -180,6 +198,19 @@ pub fn host_matches(pattern: &str, host: &str) -> bool {
}
}
/// Validates a manifest-style host (letters, digits and `-` labels, at most 253
/// bytes) and returns it lowercased. A `*` is never valid here — only a
/// `net:`/`net.http:` grant itself may carry the `*.` subdomain pattern, and a
/// host taken from a setting value never does.
pub fn manifest_host(host: &str) -> Result<String, String> {
let valid = !host.is_empty()
&& host.len() <= 253
&& host.split('.').all(|label| {
!label.is_empty() && label.len() <= 63 && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
});
valid.then(|| host.to_ascii_lowercase()).ok_or_else(|| "invalid host".into())
}
/// Validates a socket path; a grant may use `*` in its last segment only.
pub fn validate_ipc_name(name: &str, pattern: bool) -> Result<(), String> {
let pipe = name.starts_with(r"\\.\pipe\");
@@ -269,6 +300,8 @@ impl fmt::Display for Capability {
Self::ClipboardRead => f.write_str("clipboard.read"),
Self::Net(h) => write!(f, "net:{h}"),
Self::NetAsk => f.write_str("net:ask"),
Self::NetSetting { http, key } if *http => write!(f, "net.http:setting:{key}"),
Self::NetSetting { http: _, key } => write!(f, "net:setting:{key}"),
Self::NetHttp(h) => write!(f, "net.http:{h}"),
Self::Ipc(p) => write!(f, "ipc:{p}"),
Self::Process(b) => write!(f, "process:{b}"),
@@ -276,6 +309,7 @@ impl fmt::Display for Capability {
Self::FsRead(p) => write!(f, "fs.read:{p}"),
Self::FsWrite(p) => write!(f, "fs.write:{p}"),
Self::JavaAgent => f.write_str("java.agent"),
Self::Agents => f.write_str("agents"),
}
}
}
@@ -295,23 +329,27 @@ impl FromStr for Capability {
if kind == "net" && arg == "ask" {
return Ok(Self::NetAsk);
}
let host = arg.strip_prefix("*.").unwrap_or(arg);
let valid = !host.is_empty()
&& host.len() <= 253
&& host.split('.').all(|label| {
!label.is_empty()
&& label.len() <= 63
&& label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
});
if valid {
Ok(if kind == "net" {
Self::Net(arg.to_ascii_lowercase())
// `net:setting:<key>` names the plugin's `string` setting the
// host comes from; the same key rule as a settings schema.
if let Some(key) = arg.strip_prefix("setting:") {
let valid_key = !key.is_empty()
&& key.len() <= 64
&& key.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));
return if valid_key {
Ok(Self::NetSetting { http: kind == "net.http", key: key.to_owned() })
} else {
Self::NetHttp(arg.to_ascii_lowercase())
})
} else {
Err(format!("invalid host in {s:?}"))
Err(format!("invalid setting key in {s:?}"))
};
}
manifest_host(arg.strip_prefix("*.").unwrap_or(arg))
.map(|_| {
if kind == "net" {
Self::Net(arg.to_ascii_lowercase())
} else {
Self::NetHttp(arg.to_ascii_lowercase())
}
})
.map_err(|_| format!("invalid host in {s:?}"))
}
"ipc" => {
validate_ipc_name(arg, true)?;
@@ -355,6 +393,7 @@ impl FromStr for Capability {
"clipboard" => Self::Clipboard,
"clipboard.read" => Self::ClipboardRead,
"java.agent" => Self::JavaAgent,
"agents" => Self::Agents,
_ => return Err(format!("unknown capability {s:?}")),
})
}
@@ -549,6 +588,77 @@ mod net_ask_tests {
}
}
#[cfg(test)]
mod net_setting_tests {
use super::*;
/// `net:setting:<key>` names a settings key instead of a host: the host
/// comes from the setting's value and is approved when the user sets it
/// (#3809).
#[test]
fn setting_derived_grants_parse_and_print() {
for s in ["net:setting:server", "net.http:setting:server"] {
let cap: Capability = s.parse().unwrap();
assert_eq!(cap.to_string(), s, "{s}");
assert_eq!(cap.risk(), Risk::Medium, "{s}");
}
assert_eq!(
"net:setting:server".parse::<Capability>().unwrap(),
Capability::NetSetting { http: false, key: "server".into() }
);
assert_eq!(
"net.http:setting:server".parse::<Capability>().unwrap(),
Capability::NetSetting { http: true, key: "server".into() }
);
assert!(!"net:setting:server".parse::<Capability>().unwrap().auto_migrates());
let derived = "net:setting:server".parse::<Capability>().unwrap();
assert!(derived.describe().contains("`server`"));
assert!("net.http:setting:server".parse::<Capability>().unwrap().describe().contains("unencrypted"));
}
#[test]
fn setting_derived_grants_stay_strict() {
for s in ["net:setting:", "net:setting:a b", "net:setting:a:b", "net.http:setting:"] {
assert!(s.parse::<Capability>().is_err(), "{s}");
}
}
/// The derivation covers nothing by itself: a literal-host grant and a
/// setting-derived grant are different grants, and the host materializes
/// only after the user approves the setting's value.
#[test]
fn derived_grants_do_not_cover_literal_hosts() {
let derived: Capability = "net:setting:server".parse().unwrap();
let literal: Capability = "net:gitlab.intranet.example".parse().unwrap();
assert!(!derived.covers(&literal));
assert!(!literal.covers(&derived));
assert!(!derived.covers(&"net.http:gitlab.intranet.example".parse().unwrap()));
assert!(!derived.covers(&"net:setting:other".parse().unwrap()));
}
/// The host of a setting value passes the same rules as a manifest host,
/// and a `*` is refused (`net:*` stays impossible).
#[test]
fn value_hosts_follow_the_manifest_host_rules() {
assert_eq!(manifest_host("GitLab.Intranet.Example").unwrap(), "gitlab.intranet.example");
for bad in
["", "*", "*.example.com", "a b", "under_score.example", "gitlab.intranet.example.", &"a".repeat(254)]
{
assert!(manifest_host(bad).is_err(), "{bad}");
}
let long = ["a".repeat(61), "b".repeat(61), "c".repeat(61), "d".repeat(61)].join(".");
assert_eq!(long.len(), 247);
assert!(manifest_host(&long).is_ok());
assert!(
manifest_host(&["a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(63)].join(".")).is_err(),
"over 253 bytes"
);
assert!(manifest_host(&"a".repeat(64)).is_err(), "over 63 bytes per label");
// Pattern grants keep working: only a value (and a bare host) refuses `*`.
assert!("net:*.github.com".parse::<Capability>().is_ok());
}
}
#[cfg(test)]
mod database_tests {
use super::*;
+89
Переглянути файл
@@ -58,6 +58,10 @@ pub struct Grant {
/// Exact hosts approved through `net:ask`, separate from manifest grants.
#[serde(default)]
pub net_hosts: BTreeSet<String>,
/// Hosts approved for `net:setting:<key>` / `net.http:setting:<key>`
/// grants, keyed by the grant: the user approved the value in Settings.
#[serde(default)]
pub setting_hosts: BTreeMap<String, String>,
/// Optional capabilities the user declined (not asked again until re-confirmed).
#[serde(default)]
pub declined: BTreeSet<String>,
@@ -209,6 +213,7 @@ impl Ledger {
if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) {
grant.net_hosts.clear();
}
retain_setting_hosts(grant, req);
if !grant.confirmed {
return Decision::NeedsConfirmation { new: req.required.clone(), first_time: true };
}
@@ -236,6 +241,7 @@ impl Ledger {
if !req.required.iter().chain(&req.optional).any(|c| c == &Capability::NetAsk) {
grant.net_hosts.clear();
}
retain_setting_hosts(grant, req);
grant.plugin_id = req.plugin_id.to_owned();
grant.version = req.version.to_owned();
grant.package_hash = req.package_hash.to_owned();
@@ -269,6 +275,9 @@ impl Ledger {
if cap == &Capability::NetAsk {
grant.net_hosts.clear();
}
if matches!(cap, Capability::NetSetting { .. }) {
grant.setting_hosts.remove(&s);
}
if let Capability::Process(_) | Capability::JavaAgent = cap {
grant.binaries.remove(&s);
for binaries in grant.project_binaries.values_mut() {
@@ -292,6 +301,21 @@ impl Ledger {
self.grants.get_mut(subject).is_some_and(|g| g.net_hosts.remove(host))
}
/// Remembers the host the user approved for a `net:setting:` grant: it
/// covers requests only while the setting still holds it.
pub fn remember_setting_host(&mut self, subject: &Subject, cap: &Capability, host: &str) -> bool {
let Some(grant) = self.grants.get_mut(subject) else { return false };
if !grant.confirmed || !grant.has(cap) || host.contains('*') {
return false;
}
grant.setting_hosts.insert(cap.to_string(), host.to_owned());
true
}
pub fn forget_setting_host(&mut self, subject: &Subject, cap: &Capability) -> bool {
self.grants.get_mut(subject).is_some_and(|g| g.setting_hosts.remove(&cap.to_string()).is_some())
}
/// Records the program approved for a `process:` grant (or the jar of a `java.agent` one).
pub fn set_binary(&mut self, subject: &Subject, cap: &Capability, binary: BinaryGrant) {
if let Some(grant) = self.grants.get_mut(subject) {
@@ -393,6 +417,19 @@ pub fn by_risk(caps: &[Capability]) -> Vec<(Risk, Vec<Capability>)> {
groups.into_iter().map(|(r, v)| (r.0, v)).collect()
}
/// Drops setting-derived hosts the manifest no longer asks for, like
/// `net_hosts` are dropped when `net:ask` is removed.
fn retain_setting_hosts(grant: &mut Grant, req: &Request<'_>) {
let declared: Vec<String> = req
.required
.iter()
.chain(&req.optional)
.filter(|c| matches!(c, Capability::NetSetting { .. }))
.map(|c| c.to_string())
.collect();
grant.setting_hosts.retain(|cap, _| declared.contains(cap));
}
/// Pins an explicitly selected executable, retaining a multicall shim's filename.
pub fn approve_program(path: &Path) -> Result<BinaryGrant, String> {
if !path.is_absolute() || !is_executable(path) {
@@ -589,6 +626,58 @@ mod tests {
assert!(l.get(&r.subject).unwrap().net_hosts.is_empty());
}
/// A setting-derived host is approved per grant, survives re-confirmation,
/// is replaced by the next approval, and goes when the grant or the
/// manifest declaration goes (#3809).
#[test]
fn setting_hosts_are_approved_per_grant_and_drop_with_it() {
let mut l = Ledger::in_memory();
let r = req("1.0.0", "h", &["project.read"], &["net:setting:server", "net.http:setting:server"]);
l.confirm(
&r,
&["net:setting:server".parse().unwrap(), "net.http:setting:server".parse().unwrap()],
BTreeMap::new(),
);
let cap: Capability = "net:setting:server".parse().unwrap();
let other: Capability = "net.http:setting:server".parse().unwrap();
// Not granted (declined optional, or not confirmed): refused.
let declined = req("1.0.0", "h", &["project.read"], &["net:setting:server"]);
let mut l2 = Ledger::in_memory();
l2.confirm(&declined, &[], BTreeMap::new());
assert!(!l2.remember_setting_host(&declined.subject, &cap, "jira.corp.example"), "declined optional");
let never = req("1.0.0", "h", &["project.read"], &[]);
let mut l3 = Ledger::in_memory();
assert!(!l3.remember_setting_host(&never.subject, &cap, "jira.corp.example"), "never confirmed");
assert!(l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example"));
assert!(!l.remember_setting_host(&r.subject, &cap, "*"), "a wildcard value is refused");
assert_eq!(
l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
Some("gitlab.intranet.example")
);
// The other transport is its own record; the derived grant itself covers no host.
assert!(l.remember_setting_host(&r.subject, &other, "jira.corp.example"));
assert!(!l.get(&r.subject).unwrap().has(&Capability::Net("gitlab.intranet.example".into())));
// Re-confirmation keeps the approval; a manifest that drops the grant drops the record.
l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new());
assert_eq!(
l.get(&r.subject).unwrap().setting_hosts.get("net:setting:server").map(String::as_str),
Some("gitlab.intranet.example")
);
let without = req("2.0.0", "h2", &["project.read"], &[]);
assert!(matches!(l.decide(&without), Decision::Allowed { .. }), "same or fewer needs: silent");
assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty(), "records follow the manifest");
// Revoking the capability clears its record.
l.confirm(&r, &["net:setting:server".parse().unwrap()], BTreeMap::new());
l.remember_setting_host(&r.subject, &cap, "gitlab.intranet.example");
assert!(l.set(&r.subject, &cap, false));
assert!(l.get(&r.subject).unwrap().setting_hosts.is_empty());
// Forgetting without a record is an error.
assert!(!l.forget_setting_host(&r.subject, &cap));
}
#[test]
fn migration_grants_low_risk_only() {
let tmp = tempfile::tempdir().unwrap();
+3 -1
Переглянути файл
@@ -26,7 +26,9 @@ mod resolve;
mod ui;
mod when;
pub use capability::{Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, validate_ipc_name};
pub use capability::{
Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, manifest_host, validate_ipc_name,
};
pub use index::ContributionIndex;
pub use manifest::{
ActivationEvent, CATEGORIES, Capabilities, ENGINE_VERSION, EVENT_KINDS, LEGACY_API, MANIFEST_FILE, MAX_CATEGORIES,
+44 -1
Переглянути файл
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
pub const MANIFEST_FILE: &str = "plugin.toml";
/// The plugin API (engine) version this host implements.
pub const ENGINE_VERSION: &str = "1.17.0";
pub const ENGINE_VERSION: &str = "1.18.0";
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
pub const LEGACY_API: &str = "0.1";
/// Marketplace categories, in the order they are shown.
@@ -168,6 +168,8 @@ pub const EVENT_KINDS: &[&str] = &[
"action-performed",
"vcs-changed",
"problems-changed",
"project-closed",
"watched-files-changed",
];
impl std::fmt::Display for ActivationEvent {
@@ -367,6 +369,12 @@ impl Manifest {
if matches!(cap, Capability::ClipboardRead) {
self.needs_api(&format!("capability `{cap}`"), 11)?;
}
if matches!(cap, Capability::Agents) {
self.needs_api(&format!("capability `{cap}`"), 18)?;
}
if matches!(cap, Capability::NetSetting { .. }) {
self.needs_api(&format!("capability `{cap}`"), 18)?;
}
if matches!(cap, Capability::JavaAgent) {
return Err(
"`java.agent` comes from `[[contributes.javaAgents]]`: remove it from [capabilities]".into()
@@ -403,6 +411,10 @@ impl Manifest {
if matches!(event, ActivationEvent::Event(kind) if kind == "files-changed") {
self.needs_api("`on-event:files-changed`", 3)?;
}
if matches!(event, ActivationEvent::Event(kind) if kind == "project-closed" || kind == "watched-files-changed")
{
self.needs_api(&format!("`{event}`"), 18)?;
}
if !seen.insert(event) {
return Err(format!("duplicate activation event {event}"));
}
@@ -758,6 +770,20 @@ required = [\"lsp:phoxite\"]
assert_eq!(m.capabilities.optional, [Capability::ClipboardRead]);
}
#[test]
fn setting_derived_net_capabilities_need_the_current_api_minor() {
for cap in ["net:setting:server", "net.http:setting:server"] {
let caps = format!("[capabilities]\noptional = [\"{cap}\"]\n");
assert!(
err(&format!("{}{caps}", BASE.replace("^1.2", "^1.17"))).contains("new in plugin API 1.18"),
"{cap}"
);
let m = Manifest::parse(&format!("{}{caps}", BASE.replace("^1.2", "^1.18"))).unwrap();
assert_eq!(m.capabilities.optional.len(), 1, "{cap}");
assert_eq!(m.capabilities.optional[0].to_string(), cap);
}
}
#[test]
fn java_agent_capability_is_not_declared() {
for list in ["required", "optional"] {
@@ -962,4 +988,21 @@ mod net_ask_api_tests {
}
}
}
#[test]
fn project_closed_and_watched_files_events_require_api_1_18() {
for kind in ["project-closed", "watched-files-changed"] {
for engine in ["^1.17", "^1.18"] {
let manifest = format!(
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nwasm = 'plugin.wasm'\nengines.openidea = '{engine}'\nactivation = [\"on-event:{kind}\"]\n"
);
let parsed = Manifest::parse(&manifest);
if engine == "^1.18" {
parsed.unwrap();
} else {
assert!(parsed.unwrap_err().contains("new in plugin API 1.18"), "{kind} {engine}");
}
}
}
}
}
-1
Переглянути файл
@@ -12,4 +12,3 @@ serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
which = "8"
+37 -18
Переглянути файл
@@ -16,30 +16,15 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
use std::time::Duration;
/// API calls normally answer within a few seconds.
const QUICK: Duration = Duration::from_secs(60);
/// Locates the gh executable once per process (GUI apps on macOS have a minimal `PATH`).
/// Locates the gh executable (GUI apps on macOS have a minimal `PATH`, and the IDE can
/// install or remove a managed copy in its tools directory at runtime).
pub fn gh_executable() -> Option<PathBuf> {
static GH: OnceLock<Option<PathBuf>> = OnceLock::new();
GH.get_or_init(|| {
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| p.is_file()) {
return Some(explicit);
}
if let Ok(found) = which::which("gh") {
return Some(found);
}
let candidates: &[&str] = if cfg!(windows) {
&[r"C:\Program Files\GitHub CLI\gh.exe"]
} else {
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
};
candidates.iter().map(PathBuf::from).find(|p| p.is_file())
})
.clone()
ide_core::tool_path::find_gh_executable()
}
fn command(root: &Path, args: &[&str]) -> IdeResult<Command> {
@@ -386,3 +371,37 @@ pub fn prepare_diff(
let files = repo.diff_files(&base, head_oid)?;
Ok(PrDiffRevisions { base, head: head_oid.to_owned(), files, root: ide_core::IpcPath(repo.root().to_path_buf()) })
}
#[cfg(test)]
mod tests {
#[test]
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let search = std::env::join_paths([&dir]).unwrap();
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
let gh = dir.join(if cfg!(windows) { "gh.exe" } else { "gh" });
std::fs::write(&gh, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), Some(gh.clone()));
let explicit = dir.join(if cfg!(windows) { "custom-gh.exe" } else { "custom-gh" });
std::fs::write(&explicit, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&explicit, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert_eq!(ide_core::tool_path::find_gh_in(Some(&explicit), &search, &[]), Some(explicit));
std::fs::remove_file(&gh).unwrap();
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
let _ = std::fs::remove_dir_all(&dir);
}
}
+6 -1
Переглянути файл
@@ -66,7 +66,12 @@ serde_json = { workspace = true, features = ["raw_value"] }
toml.workspace = true
specta.workspace = true
specta-typescript.workspace = true
tokio = { workspace = true, features = ["io-std"] }
bytes = "1"
flate2.workspace = true
http-body-util = "0.1"
hyper = { version = "1", features = ["http1", "server"] }
hyper-util = { version = "0.1", default-features = false, features = ["tokio"] }
tokio = { workspace = true, features = ["io-std", "net", "signal"] }
tracing.workspace = true
url = "2"
tracing-subscriber.workspace = true
+172 -12
Переглянути файл
@@ -1,11 +1,16 @@
//! `openidea-server`: the IDE backend for remote development, either serving one
//! desktop client over stdin / stdout (`--stdio`) or running as a persistent
//! per-project daemon (`--attach <project>`).
//! `openidea-server`: the headless IDE backend.
//!
//! * `--stdio`: JSON-RPC over stdin/stdout for SSH / remote development clients.
//! * `--attach <project>`: persistent per-project remote development daemon.
//! * `--web`: HTTP + WebSocket server exposing the full OpenIDEA web interface on a configurable port.
//! * `--mcp-stdio`: MCP stdio bridge.
//! * `--connect <host> <port>`: TCP relay over stdin/stdout.
use ide_host::catalogue::TrustClass;
use ide_host::plugins::remote::{RemotePluginLanguages, SYNC_COMMAND};
use ide_host::plugins::remote_host::RemotePlugins;
use ide_host::rpc::{self, Dispatcher};
use ide_host::web_server::{self, WebServerConfig};
use ide_host::{Host, HostConfig};
use ide_language::LanguageRegistry;
use std::path::PathBuf;
@@ -17,6 +22,126 @@ enum Mode {
Daemon(PathBuf, ide_host::daemon::BuildId),
}
fn print_usage() {
eprintln!(
"\
usage:
openidea-server --web [options] [<project>]
openidea-server --stdio
openidea-server --attach <project-path>
openidea-server --mcp-stdio [--project <path>]
openidea-server --connect <host> <port>
openidea-server --version
web mode options:
--host <addr> Bind address (default: $OPENIDEA_HOST or 127.0.0.1)
--port <port> Listen port (default: $OPENIDEA_PORT or 8080)
--base-path <prefix> Optional reverse-proxy URL prefix (default: $OPENIDEA_BASE_PATH)
--web-dir <dir> Built frontend directory (default: $OPENIDEA_WEB_DIR or auto-detected dist/)
--project <path> Workspace directory to open on startup (default: $OPENIDEA_WORKSPACE_DIR)
--home <dir> Persistent config/data directory (default: $OPENIDEA_SERVER_HOME or ~/.openidea)
--token <secret|auto> Access token ($OPENIDEA_WEB_TOKEN; default: auto-generated random token)
--no-auth Disable token auth ($OPENIDEA_WEB_NO_AUTH=1; use only behind an authenticating proxy)
--no-trust-project Prompt before trusting --project instead of trusting it automatically"
);
}
struct ParsedWebArgs {
config: WebServerConfig,
home_override: Option<PathBuf>,
}
fn env_truthy(name: &str) -> bool {
std::env::var(name).ok().is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes"))
}
fn parse_web_args(args: &[String]) -> Result<ParsedWebArgs, String> {
let mut host = std::env::var("OPENIDEA_HOST").unwrap_or_else(|_| "127.0.0.1".into());
let mut port: u16 = match std::env::var("OPENIDEA_PORT") {
Ok(raw) if !raw.trim().is_empty() => {
raw.trim().parse::<u16>().map_err(|_| format!("invalid OPENIDEA_PORT value: {raw}"))?
}
_ => 8080,
};
let mut base_path = std::env::var("OPENIDEA_BASE_PATH").ok().filter(|s| !s.trim().is_empty());
let mut web_dir = web_server::default_web_dir();
let mut project = std::env::var_os("OPENIDEA_WORKSPACE_DIR")
.or_else(|| std::env::var_os("OPENIDEA_PROJECT"))
.filter(|s| !s.is_empty())
.map(PathBuf::from);
let mut trust_project = true;
let mut no_auth = env_truthy("OPENIDEA_WEB_NO_AUTH");
let mut auth_token = std::env::var("OPENIDEA_WEB_TOKEN").ok().filter(|s| !s.trim().is_empty());
let mut home_override: Option<PathBuf> = None;
let mut i = 0;
while i < args.len() {
let arg = args[i].as_str();
let next_val = |i: &mut usize, flag: &str| -> Result<String, String> {
*i += 1;
args.get(*i).cloned().ok_or_else(|| format!("missing value for {flag}"))
};
if arg == "--web" {
i += 1;
continue;
} else if arg == "--host" {
host = next_val(&mut i, "--host")?;
} else if let Some(v) = arg.strip_prefix("--host=") {
host = v.to_owned();
} else if arg == "--port" || arg == "-p" {
let v = next_val(&mut i, arg)?;
port = v.parse::<u16>().map_err(|_| format!("invalid port: {v}"))?;
} else if let Some(v) = arg.strip_prefix("--port=") {
port = v.parse::<u16>().map_err(|_| format!("invalid port: {v}"))?;
} else if arg == "--base-path" {
base_path = Some(next_val(&mut i, "--base-path")?);
} else if let Some(v) = arg.strip_prefix("--base-path=") {
base_path = Some(v.to_owned());
} else if arg == "--web-dir" {
web_dir = PathBuf::from(next_val(&mut i, "--web-dir")?);
} else if let Some(v) = arg.strip_prefix("--web-dir=") {
web_dir = PathBuf::from(v);
} else if arg == "--project" || arg == "--workspace" {
project = Some(PathBuf::from(next_val(&mut i, arg)?));
} else if let Some(v) = arg.strip_prefix("--project=").or_else(|| arg.strip_prefix("--workspace=")) {
project = Some(PathBuf::from(v));
} else if arg == "--home" {
home_override = Some(PathBuf::from(next_val(&mut i, "--home")?));
} else if let Some(v) = arg.strip_prefix("--home=") {
home_override = Some(PathBuf::from(v));
} else if arg == "--token" {
auth_token = Some(next_val(&mut i, "--token")?);
no_auth = false;
} else if let Some(v) = arg.strip_prefix("--token=") {
auth_token = Some(v.to_owned());
no_auth = false;
} else if arg == "--no-auth" {
auth_token = None;
no_auth = true;
} else if arg == "--no-trust-project" {
trust_project = false;
} else if arg.starts_with('-') {
return Err(format!("unknown option: {arg}"));
} else if project.is_none() {
project = Some(PathBuf::from(arg));
} else {
return Err(format!("unexpected positional argument: {arg}"));
}
i += 1;
}
if no_auth {
auth_token = None;
} else if auth_token.is_none() || auth_token.as_deref() == Some("auto") {
auth_token = Some(web_server::generate_token());
}
Ok(ParsedWebArgs {
config: WebServerConfig { host, port, base_path, web_dir, project, trust_project, auth_token },
home_override,
})
}
fn main() {
let raw_args: Vec<String> = std::env::args().collect();
if let Some(project) = ide_mcp::stdio_request(&raw_args) {
@@ -28,6 +153,10 @@ fn main() {
println!("openidea-server {} (protocol {})", env!("CARGO_PKG_VERSION"), rpc::PROTOCOL_VERSION);
return;
}
if args.iter().any(|a| a == "--help" || a == "-h") {
print_usage();
return;
}
if args.first().is_some_and(|a| a == "--connect") {
// One forwarded connection (see `ide_host::relay`): stdout carries its bytes.
let code = match ide_host::relay::parse_args(&args[1..]).and_then(|(host, port)| {
@@ -42,6 +171,7 @@ fn main() {
};
std::process::exit(code);
}
let base = server_home();
#[cfg(unix)]
if args.first().is_some_and(|a| a == "--attach") {
@@ -68,6 +198,30 @@ fn main() {
};
std::process::exit(code);
}
if args.iter().any(|a| a == "--web") {
let parsed = match parse_web_args(&args) {
Ok(p) => p,
Err(e) => {
eprintln!("error: {e}");
print_usage();
std::process::exit(2);
}
};
init_tracing();
let base = parsed.home_override.unwrap_or(base);
init_process_env(&base);
let worker_threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(2).clamp(2, 8);
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(worker_threads)
.max_blocking_threads(32)
.enable_all()
.build()
.expect("tokio runtime");
let code = runtime.block_on(web_server::run(parsed.config, base));
std::process::exit(code);
}
let mode = match args.as_slice() {
#[cfg(unix)]
[flag, sock, build] if flag == "--daemon" => {
@@ -81,27 +235,33 @@ fn main() {
[flag, _] if flag == "--attach" => Mode::Stdio,
_ if args.iter().any(|a| a == "--stdio") => Mode::Stdio,
_ => {
eprintln!(
"usage: openidea-server --stdio | --attach <project-path> | --mcp-stdio [--project <path>] | --connect <host> <port> | --version"
);
print_usage();
std::process::exit(2);
}
};
// stdout carries the protocol: logs go to stderr.
init_tracing();
init_process_env(&base);
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
let code = runtime.block_on(run(base, mode));
std::process::exit(code);
}
fn init_tracing() {
// stdout carries the protocol in --stdio mode: logs always go to stderr.
tracing_subscriber::fmt()
.with_writer(std::io::stderr)
.with_env_filter(tracing_subscriber::EnvFilter::try_from_env("OPENIDEA_LOG").unwrap_or_else(|_| "info".into()))
.init();
// An SSH exec channel gets a minimal environment: take the login shell's, read
// afresh on every start, plus the IDE-managed tools. Before any other thread starts.
}
fn init_process_env(base: &std::path::Path) {
// An SSH exec channel or container entrypoint gets a minimal environment: inherit login shell
// env plus IDE-managed tools before any other thread starts.
ide_host::shell_env::inherit_login_shell_env("openidea-server");
let data_dir = base.join("data");
ide_tools::extend_process_path(&data_dir);
ide_dap::adapter::set_tools_root(ide_tools::tools_dir(&data_dir));
ide_sdk::java::add_jdk_root(&ide_tools::jdk::jdks_dir(&data_dir));
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().expect("tokio runtime");
let code = runtime.block_on(run(base, mode));
std::process::exit(code);
}
fn server_home() -> PathBuf {
+327 -13
Переглянути файл
@@ -15,6 +15,52 @@ const OXFMT_CONFIGS: [&str; 4] = [".oxfmtrc.json", ".oxfmtrc.jsonc", "oxfmt.conf
/// A Biome configuration, or Biome installed as a project dependency (it then uses its defaults).
const BIOME_MARKERS: [&str; 3] = ["biome.json", "biome.jsonc", "node_modules/@biomejs/biome/package.json"];
/// dprint's configuration files, and dprint installed as a project dependency.
const DPRINT_MARKERS: [&str; 5] =
["dprint.json", ".dprint.json", "dprint.jsonc", ".dprint.jsonc", "node_modules/dprint/package.json"];
/// The nearest of `names` in `file`'s folder or above, up to the project `root` (none outside it).
fn find_in_project(file: &Path, root: &Path, names: &[&str]) -> Option<PathBuf> {
file.parent()?
.ancestors()
.take_while(|dir| dir.starts_with(root))
.find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| p.is_file()))
}
fn dprint_project(file: &Path, root: &Path) -> bool {
find_in_project(file, root, &DPRINT_MARKERS).is_some()
}
/// `dprint editor-info` results by configuration file (the project root without one) and the
/// configuration's modification time. Failures are kept too: an offline plugin download would
/// otherwise time out again on every format.
// ponytail: `extends` files and a configuration outside the project are not watched; editing one needs a change of the project's file (or a restart).
type EditorInfo = (Option<std::time::SystemTime>, IdeResult<String>);
static DPRINT_EDITOR_INFO: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<PathBuf, EditorInfo>>> =
std::sync::LazyLock::new(Default::default);
/// Whether the dprint configuration found for `file` (from its folder, as dprint finds it) has a
/// plugin for it. `retry` runs `editor-info` again after a remembered failure.
fn dprint_covers(tools: &Tools, custom: Option<&Path>, file: &Path, root: &Path, retry: bool) -> IdeResult<bool> {
let dir = file.parent().ok_or_else(|| IdeError::invalid("dprint: file has no directory"))?;
let config = find_in_project(file, root, &DPRINT_MARKERS[..4]);
let modified = config.as_ref().and_then(|c| std::fs::metadata(c).and_then(|m| m.modified()).ok());
let key = config.unwrap_or_else(|| root.to_path_buf());
let cached = {
let cache = DPRINT_EDITOR_INFO.lock().unwrap_or_else(|e| e.into_inner());
cache.get(&key).filter(|(at, info)| *at == modified && !(retry && info.is_err())).map(|(_, info)| info.clone())
};
let info = cached.unwrap_or_else(|| {
let info = tools.formatter_command("dprint", file, custom).and_then(|mut command| {
command.current_dir(dir);
formatter::dprint_editor_info(command)
});
DPRINT_EDITOR_INFO.lock().unwrap_or_else(|e| e.into_inner()).insert(key, (modified, info.clone()));
info
})?;
formatter::dprint_covers(&info, file)
}
/// Reformat Code uses Biome below a Biome configuration or installation, unless the nearest
/// configuration turns its formatter off (Biome lints, another tool formats).
fn biome_formats(file: &Path) -> bool {
@@ -31,6 +77,69 @@ fn biome_formats(file: &Path) -> bool {
}
}
const PRETTIER_CONFIGS: [&str; 18] = [
".prettierrc",
".prettierrc.json",
".prettierrc.json5",
".prettierrc.yaml",
".prettierrc.yml",
".prettierrc.toml",
".prettierrc.js",
".prettierrc.cjs",
".prettierrc.mjs",
".prettierrc.ts",
".prettierrc.cts",
".prettierrc.mts",
"prettier.config.js",
"prettier.config.cjs",
"prettier.config.mjs",
"prettier.config.ts",
"prettier.config.cts",
"prettier.config.mts",
];
/// A Prettier configuration applies to `file`: a configuration file or a `prettier` key in a
/// `package.json` above it.
fn prettier_configured(file: &Path) -> bool {
PRETTIER_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some())
|| file.ancestors().skip(1).any(|dir| {
std::fs::read_to_string(dir.join("package.json"))
.ok()
.and_then(|text| serde_json::from_str::<serde_json::Value>(&text).ok())
.is_some_and(|v| v.get("prettier").is_some())
})
}
/// The languages whose server formats in the IDE's code style (`ts_code_style`).
const CODE_STYLE_LANGUAGES: [&str; 4] = ["javascript", "javascriptreact", "typescript", "typescriptreact"];
/// In Automatic mode, the project's own configuration of `tool` wins over the TypeScript server,
/// whose output follows the IDE's code style. Not before the tool is installed (`resolves`): a fresh
/// clone keeps formatting with the server until `npm install`.
fn project_takes_over(tool: ExternalFormatter, language: &str, file: &Path, resolves: impl FnOnce() -> bool) -> bool {
CODE_STYLE_LANGUAGES.contains(&language) && project_configured(tool, file) && resolves()
}
/// Format on save runs the external tool: its own setting, or the editor's when the tool takes over
/// from the language server (Black, dprint, or a project configuration), so saving keeps formatting.
fn runs_on_save(tool: ExternalFormatter, run_on_save: bool, takes_over: bool, format_on_save: bool) -> bool {
run_on_save
|| ((matches!(tool, ExternalFormatter::Black | ExternalFormatter::Dprint) || takes_over) && format_on_save)
}
/// The project configures `tool`. Every formatter needs an arm. dprint is chosen before this check
/// (`dprint_project`), so it never reaches it.
fn project_configured(tool: ExternalFormatter, file: &Path) -> bool {
match tool {
ExternalFormatter::Prettier => prettier_configured(file),
ExternalFormatter::Oxfmt => {
OXFMT_CONFIGS.iter().any(|name| formatter::find_up(file, Path::new(name)).is_some())
}
ExternalFormatter::Biome => biome_formats(file),
ExternalFormatter::Ruff | ExternalFormatter::Black | ExternalFormatter::Dprint => false,
}
}
/// The `pyproject.toml` Black reads for `file`, in the project root Black finds: the nearest folder
/// with `.git`, `.hg`, or a `pyproject.toml` that has `[tool.black]` (one without it is skipped).
/// `None` when that root has no `pyproject.toml`: Black then reads the user's configuration.
@@ -152,6 +261,12 @@ fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter)
}
}
/// The entry of the formatters' language lists that covers `language`. MDX was part of Markdown
/// and follows its entry, so lists saved before it had its own language keep formatting it.
fn formatter_language(language: &str) -> &str {
if language == "mdx" { "markdown" } else { language }
}
/// The external formatter of a file, for a language with an external formatter.
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
@@ -186,7 +301,8 @@ fn external_tool(
)))
};
}
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
let id = formatter_language(language.id.as_str());
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == id);
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
Some(Black)
@@ -533,18 +649,58 @@ async fn provider_edits(
}
return Ok(Some(edits));
}
let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
// dprint formats what its configuration covers, before the language's own formatters.
let dprint = &settings.languages.dprint;
let forced_dprint = options.tool == Some(ExternalFormatter::Dprint);
let auto_dprint = options.tool.is_none()
&& (dprint.prefer || dprint_project(&snap.path, &project.root))
&& project.require_trust().is_ok();
let mut selected = None;
if forced_dprint || auto_dprint {
host.require_trust(window)?;
let tools = Tools::new(&host.local_data_dir);
let custom = ide_sdk::apply::setting_path(&project.root, &dprint.path);
let (path, root) = (snap.path.clone(), project.root.clone());
let covers =
tokio::task::spawn_blocking(move || dprint_covers(&tools, custom.as_deref(), &path, &root, forced_dprint))
.await
.map_err(|e| IdeError::internal(e.to_string()))?;
match covers {
Ok(true) => selected = Some(ExternalFormatter::Dprint),
Ok(false) if forced_dprint => {
return Err(
IdeError::invalid("The dprint configuration has no plugin for this file").with_tool("dprint")
);
}
Ok(false) => {}
Err(e) if forced_dprint => return Err(e.with_tool("dprint")),
// Not installed, no configuration, plugins not downloadable: the usual formatter.
Err(e) => tracing::warn!("dprint editor-info failed, using the usual formatter: {}", e.message),
}
}
if selected.is_none() {
selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
}
let mut takes_over = false;
// Black is selected only when configured or preferred: the Ruff server's formatting doesn't replace it.
if let Some(tool) = selected
&& options.tool.is_none()
&& tool != ExternalFormatter::Dprint
&& tool != ExternalFormatter::Black
&& !settings.languages.formatter(tool).prefer
&& match doc {
Some(doc) => project.lsp.can_format(doc).await?,
None => project.lsp.can_format_text(&snap.path, &snap.language).await,
}
{
selected = None;
takes_over = project_takes_over(tool, snap.language.as_str(), &snap.path, || {
let custom = ide_sdk::apply::setting_path(&project.root, &settings.languages.formatter(tool).path);
Tools::new(&host.local_data_dir).formatter_command(tool.name(), &snap.path, custom.as_deref()).is_ok()
});
if !takes_over
&& match doc {
Some(doc) => project.lsp.can_format(doc).await?,
None => project.lsp.can_format_text(&snap.path, &snap.language).await,
}
{
selected = None;
}
}
let Some(selected) = selected else {
if options.on_save && !settings.editor.format_on_save {
@@ -566,17 +722,24 @@ async fn provider_edits(
.map_err(|e| IdeError::internal(e.to_string()));
};
let tool_settings = settings.languages.formatter(selected);
// Black takes over from the language server in its projects, so Format on save runs it too.
let runs_on_save =
tool_settings.run_on_save || (selected == ExternalFormatter::Black && settings.editor.format_on_save);
if options.on_save && !runs_on_save {
if options.on_save && !runs_on_save(selected, tool_settings.run_on_save, takes_over, settings.editor.format_on_save)
{
return Ok(None);
}
host.require_trust(window)?;
if snap.read_only {
return Err(IdeError::invalid("The file is read-only"));
}
let config = language.and_then(|l| l.formatter).expect("external_tool selects languages with a formatter");
let config = language
.and_then(|l| l.formatter)
.or_else(|| {
(selected == ExternalFormatter::Dprint).then(|| ide_language::FormatterConfig {
tool: "dprint".into(),
parser: String::new(),
range: false,
})
})
.expect("external_tool selects languages with a formatter");
let tool = selected.name();
let name = formatter::display_name(tool);
let mut custom = ide_sdk::apply::setting_path(&project.root, &tool_settings.path);
@@ -727,7 +890,7 @@ pub async fn python_import_edits(
#[cfg(test)]
mod tests {
use super::*;
use ExternalFormatter::{Biome, Black, Oxfmt, Prettier, Ruff};
use ExternalFormatter::{Biome, Black, Dprint, Oxfmt, Prettier, Ruff};
use ide_core::LanguageId;
use ide_language::LanguageRegistry;
@@ -741,6 +904,24 @@ mod tests {
external_tool(forced, language.as_ref(), file, settings)
}
#[test]
fn mdx_follows_the_markdown_entry_of_saved_language_lists() {
// Saved before MDX had its own language: the whole list, with no `mdx` in it.
let old: ide_core::settings::Settings = serde_json::from_str(
r#"{"languages":{"prettier":{"languages":["markdown","css"]},"oxfmt":{"languages":["css"]}}}"#,
)
.unwrap();
let file = Path::new("/project/docs/intro.mdx");
assert_eq!(tool(None, "mdx", file, &old.languages).unwrap(), Some(Prettier));
let mut no_markdown = old.languages.clone();
no_markdown.prettier.languages.retain(|l| l != "markdown");
assert_eq!(tool(None, "mdx", file, &no_markdown).unwrap(), None);
let mut oxfmt = old.languages.clone();
oxfmt.oxfmt.languages.push("markdown".into());
oxfmt.oxfmt.prefer = true;
assert_eq!(tool(None, "mdx", file, &oxfmt).unwrap(), Some(Oxfmt));
}
#[test]
fn default_settings_use_ruff_for_python_and_prettier_for_the_web() {
let settings = LanguagesSettings::default();
@@ -945,6 +1126,90 @@ mod tests {
assert_eq!(black_pyproject(&file), Some(repo.join("pkg/pyproject.toml")));
}
#[test]
fn a_dprint_configuration_or_dependency_in_the_project_marks_a_dprint_project() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("home/project");
let file = root.join("web/src/app.ts");
assert!(!dprint_project(&file, &root));
for marker in DPRINT_MARKERS {
let path = root.join("web").join(marker);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, "{}").unwrap();
assert!(dprint_project(&file, &root), "{marker}");
assert!(!dprint_project(&root.join("api/main.ts"), &root), "{marker}");
// A file outside the project is not below the project's dprint.
assert!(!dprint_project(&dir.path().join("elsewhere/web/src/app.ts"), &root), "{marker}");
std::fs::remove_file(&path).unwrap();
}
// dprint installed above the project (a stray `~/node_modules/dprint`) doesn't count.
let stray = dir.path().join("home/node_modules/dprint/package.json");
std::fs::create_dir_all(stray.parent().unwrap()).unwrap();
std::fs::write(&stray, "{}").unwrap();
std::fs::write(dir.path().join("home/dprint.json"), "{}").unwrap();
assert!(!dprint_project(&file, &root));
}
#[cfg(unix)]
#[test]
fn dprint_coverage_comes_from_editor_info_cached_per_configuration() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join("src")).unwrap();
let config = root.join("dprint.json");
std::fs::write(&config, "{}").unwrap();
// Shell builtins only: the command runs with the tools' empty PATH.
let info = r#"{"plugins":[{"fileExtensions":["ts"],"fileNames":["Dockerfile"]}]}"#;
let fake = root.join("fake-dprint");
let script = format!(
"#!/bin/sh\necho run >> \"$0.runs\"\n[ -f fail ] && {{ echo 'bad config' >&2; exit 1; }}\nprintf '%s' '{info}'\n"
);
std::fs::write(&fake, script).unwrap();
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
let tools = Tools::with_paths(root.join("tools"), Default::default(), ide_tools::platform::Platform::current());
let runs = || std::fs::read_to_string(root.join("fake-dprint.runs")).unwrap_or_default().lines().count();
let covers = |file: &str, retry| dprint_covers(&tools, Some(&fake), &root.join(file), root, retry);
assert!(covers("src/app.ts", false).unwrap());
assert!(covers("src/Dockerfile", false).unwrap());
// Not covered: the usual formatter takes the file.
assert!(!covers("src/main.py", false).unwrap());
assert_eq!(runs(), 1);
// A changed configuration is read again, and its error is dprint's.
std::fs::write(root.join("src/fail"), "").unwrap();
let later = std::fs::metadata(&config).unwrap().modified().unwrap() + std::time::Duration::from_secs(5);
std::fs::File::options().write(true).open(&config).unwrap().set_modified(later).unwrap();
let error = covers("src/app.ts", false).unwrap_err();
assert!(error.message.contains("bad config"), "{}", error.message);
assert_eq!(error.data, Some(ide_core::error::ErrorData::Tool { tool: "dprint".into(), missing: false }));
assert_eq!(runs(), 2);
// The failure is remembered (an offline download would time out again), unless retried.
assert!(covers("src/app.ts", false).is_err());
assert_eq!(runs(), 2);
std::fs::remove_file(root.join("src/fail")).unwrap();
assert!(covers("src/app.ts", true).unwrap());
assert_eq!(runs(), 3);
}
#[cfg(unix)]
#[test]
fn dprint_without_a_project_configuration_runs_once_per_project() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join("a/b")).unwrap();
let fake = root.join("fake-dprint");
std::fs::write(&fake, "#!/bin/sh\necho run >> \"$0.runs\"\nprintf '%s' '{\"plugins\":[]}'\n").unwrap();
std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
let tools = Tools::with_paths(root.join("tools"), Default::default(), ide_tools::platform::Platform::current());
for file in ["a/x.ts", "a/b/y.ts", "z.ts"] {
assert!(!dprint_covers(&tools, Some(&fake), &root.join(file), root, false).unwrap());
}
assert_eq!(std::fs::read_to_string(root.join("fake-dprint.runs")).unwrap().lines().count(), 1);
}
#[test]
fn biome_config_or_dependency_selects_biome_for_its_languages() {
let dir = tempfile::tempdir().unwrap();
@@ -1011,6 +1276,55 @@ mod tests {
assert_eq!(tool(None, "typescript", file, &settings).unwrap(), None);
}
#[test]
fn a_project_configuration_of_the_formatter_wins_over_the_language_server() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir_all(root.join("a/src")).unwrap();
std::fs::create_dir_all(root.join("b/src")).unwrap();
std::fs::create_dir_all(root.join("c/src")).unwrap();
std::fs::write(root.join("a/.prettierrc.json"), "{}").unwrap();
std::fs::write(root.join("b/package.json"), r#"{ "prettier": { "semi": false } }"#).unwrap();
std::fs::write(root.join("c/package.json"), r#"{ "name": "c" }"#).unwrap();
std::fs::write(root.join("c/biome.json"), "{}").unwrap();
assert!(project_configured(Prettier, &root.join("a/src/app.ts")));
assert!(project_configured(Prettier, &root.join("b/src/app.ts")));
assert!(!project_configured(Prettier, &root.join("c/src/app.ts")));
assert!(project_configured(Biome, &root.join("c/src/app.ts")));
assert!(!project_configured(Oxfmt, &root.join("c/src/app.ts")));
std::fs::write(root.join("c/.oxfmtrc.json"), "{}").unwrap();
assert!(project_configured(Oxfmt, &root.join("c/src/app.ts")));
}
#[test]
fn only_the_typescript_server_languages_give_way_to_an_installed_project_formatter() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join(".prettierrc"), "{}").unwrap();
let file = |name: &str| dir.path().join(name);
for language in ["typescript", "typescriptreact", "javascript", "javascriptreact"] {
assert!(project_takes_over(Prettier, language, &file("a.ts"), || true), "{language}");
}
for language in ["json", "css", "html", "yaml", "markdown", "vue"] {
assert!(!project_takes_over(Prettier, language, &file("a.json"), || true), "{language}");
}
// Configured but not installed yet (before `npm install`): the language server formats.
assert!(!project_takes_over(Prettier, "typescript", &file("a.ts"), || false));
// No configuration: the tool isn't even looked up.
assert!(!project_takes_over(Biome, "typescript", &file("a.ts"), || panic!("resolved")));
}
#[test]
fn format_on_save_keeps_running_when_the_project_formatter_takes_over() {
// Format on save formatted with the language server before; the tool that replaces it does too.
assert!(runs_on_save(Prettier, false, true, true));
assert!(!runs_on_save(Prettier, false, true, false));
assert!(runs_on_save(Black, false, false, true));
assert!(runs_on_save(Dprint, false, false, true));
// Selected by the settings, not taking over: only its own Run on save.
assert!(!runs_on_save(Prettier, false, false, true));
assert!(runs_on_save(Prettier, true, false, false));
}
#[test]
fn forced_tool_runs_that_formatter_or_reports_why_not() {
let dir = tempfile::tempdir().unwrap();
+340
Переглянути файл
@@ -0,0 +1,340 @@
//! Project-scoped GitHub CLI (`gh`) account selection and opt-in `GH_TOKEN` injection.
//!
//! Each project may pin a GitHub login in `vcs.github.account` (`.openidea/settings.toml`) or
//! leave it empty (`Automatic`). `Automatic` leaves `gh`'s own behaviour untouched—no `GH_TOKEN`
//! is injected into [`ide_core::project_env`] and opening a project makes no GitHub API calls.
//! When the user inspects GitHub settings or Pull Requests with multiple `gh` keyring accounts,
//! OpenIDEA probes the repository remote (`owner/repo`) to suggest a matching non-active account
//! ("Use <login> for this project"). Only when an account is explicitly chosen does OpenIDEA
//! resolve its token into [`ide_core::project_env`] (for both `project.root` and `.worktrees`).
use crate::Project;
use ide_agent::GhAuthAccount;
use ide_core::cli_process::{CliTool, Decoding};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::LazyLock;
use std::time::{Duration, Instant};
const AMBIENT_GH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
const GH_TOOL: CliTool = CliTool::new("gh", Decoding::Utf8Lossy);
const LOCAL_TIMEOUT: Duration = Duration::from_secs(5);
const PROBE_TIMEOUT: Duration = Duration::from_secs(6);
const CACHE_TTL: Duration = Duration::from_secs(10 * 60);
/// GitHub CLI accounts available on this machine and which one applies to the project.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct GhProjectAccountStatus {
pub gh_installed: bool,
pub accounts: Vec<GhAuthAccount>,
/// Value of `vcs.github.account` (`""` = Automatic).
pub configured_account: String,
/// Account login currently used (`configured_account` if signed in, else `gh`'s active account).
pub effective_account: Option<String>,
/// Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty.
pub suggested_account: Option<String>,
}
#[derive(Clone)]
struct CachedAutoAccount {
login: Option<String>,
at: Instant,
}
type AutoCacheMap = HashMap<(String, Vec<String>), CachedAutoAccount>;
static AUTO_CACHE: LazyLock<Mutex<AutoCacheMap>> = LazyLock::new(|| Mutex::new(HashMap::new()));
pub(crate) fn is_valid_github_login(login: &str) -> bool {
let bytes = login.as_bytes();
!bytes.is_empty()
&& bytes.len() <= 39
&& bytes[0].is_ascii_alphanumeric()
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
}
fn find_gh_executable() -> Option<PathBuf> {
ide_core::tool_path::find_gh_executable()
}
fn clean_gh_command(program: &Path, args: &[&str]) -> Command {
let mut cmd = Command::new(program);
cmd.current_dir(std::env::temp_dir())
.args(args)
.env("GH_PROMPT_DISABLED", "1")
.env("GH_NO_UPDATE_NOTIFIER", "1")
.env("NO_COLOR", "1")
.env("CLICOLOR", "0");
// Strip ambient tokens by setting empty then removing after `prepare`: `CliTool::run` calls
// `ide_core::process::prepare`, which skips keys already present in `cmd.get_envs()`.
for key in AMBIENT_GH_VARS {
cmd.env_remove(key);
}
cmd
}
fn gh_token_for_account(program: &Path, login: &str) -> Option<String> {
if !is_valid_github_login(login) {
return None;
}
let cmd = clean_gh_command(program, &["auth", "token", "--hostname", "github.com", "--user", login]);
let out = GH_TOOL.run(cmd, LOCAL_TIMEOUT, None).ok().filter(|o| o.success)?;
let token = out.stdout.trim();
(!token.is_empty()).then(|| token.to_owned())
}
/// Access level of an account for a specific `owner/repo` on `github.com`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum RepoAccess {
None = 0,
Read = 1,
Push = 2,
}
fn probe_repo_access(program: &Path, token: &str, owner: &str, name: &str) -> RepoAccess {
let endpoint = format!("repos/{owner}/{name}");
let mut cmd =
clean_gh_command(program, &["api", "--hostname", "github.com", &endpoint, "--jq", ".permissions.push"]);
cmd.env("GH_TOKEN", token);
let Ok(out) = GH_TOOL.run(cmd, PROBE_TIMEOUT, None) else {
return RepoAccess::None;
};
if !out.success {
return RepoAccess::None;
}
if out.stdout.trim() == "true" { RepoAccess::Push } else { RepoAccess::Read }
}
fn pick_best_account(candidates: &[(GhAuthAccount, RepoAccess)]) -> Option<(&GhAuthAccount, bool)> {
let active_access =
candidates.iter().find(|(a, _)| a.active).map(|(_, access)| *access).unwrap_or(RepoAccess::None);
// Prefer higher RepoAccess; break ties in favor of the globally active account.
let (best, best_access) = candidates.iter().max_by_key(|(acc, access)| (*access, acc.active))?;
if *best_access == RepoAccess::None {
// Nobody could reach the repo (offline or SSO required): keep the active account.
return candidates.iter().find(|(a, _)| a.active).or_else(|| candidates.first()).map(|(a, _)| (a, false));
}
let auto_detected = !best.active && *best_access > active_access;
Some((best, auto_detected))
}
/// Parses `github.com` `(owner, repo)` from HTTPS, SSH, or SCP-style remote URLs.
pub(crate) fn parse_github_owner_repo(url: &str) -> Option<(String, String)> {
let url = url.trim();
let path = if let Some(rest) =
url.strip_prefix("https://github.com/").or_else(|| url.strip_prefix("http://github.com/"))
{
rest
} else if let Some(rest) = url.strip_prefix("ssh://") {
rest.strip_prefix("[email protected]/").or_else(|| rest.strip_prefix("github.com/"))?
} else {
url.strip_prefix("[email protected]:")?
};
let path = path.trim_matches('/');
let (owner, rest) = path.split_once('/')?;
let repo = rest.split('/').next()?;
let repo = repo.strip_suffix(".git").unwrap_or(repo);
if owner.is_empty() || repo.is_empty() {
return None;
}
Some((owner.to_owned(), repo.to_owned()))
}
fn primary_github_repo(project: &Project) -> Option<(String, String)> {
let repos = project.repos();
let mut ordered = Vec::new();
if let Some(primary) = repos.primary() {
ordered.push(primary);
}
for repo in repos.all() {
if ordered.first().is_none_or(|p| p.root() != repo.root()) {
ordered.push(repo);
}
}
for repo in ordered {
let Ok(mut remotes) = repo.remotes() else { continue };
remotes.sort_by_key(|r| r.name != "origin");
for remote in remotes {
let url = remote.resolved_url.as_deref().unwrap_or(&remote.url);
if let Some(coords) = parse_github_owner_repo(url) {
return Some(coords);
}
}
}
None
}
fn auto_detect_account(program: &Path, accounts: &[GhAuthAccount], owner: &str, repo: &str) -> Option<(String, bool)> {
// Fast path: the repository owner matches one of the signed-in accounts directly.
if let Some(matched) = accounts.iter().find(|a| a.login.eq_ignore_ascii_case(owner)) {
return Some((matched.login.clone(), !matched.active));
}
let key_repo = format!("{}/{}", owner.to_ascii_lowercase(), repo.to_ascii_lowercase());
let key_logins: Vec<String> = accounts.iter().map(|a| format!("{}:{}", a.login, a.active)).collect();
let cache_key = (key_repo, key_logins);
if let Some(cached) = AUTO_CACHE.lock().get(&cache_key).cloned()
&& cached.at.elapsed() < CACHE_TTL
{
if let Some(login) = cached.login {
let is_active = accounts.iter().any(|a| a.login == login && a.active);
return Some((login, !is_active));
}
return None;
}
let tokens: Vec<(GhAuthAccount, Option<String>)> =
accounts.iter().map(|acc| (acc.clone(), gh_token_for_account(program, &acc.login))).collect();
let results: Vec<(GhAuthAccount, RepoAccess)> = std::thread::scope(|s| {
let handles: Vec<_> = tokens
.into_iter()
.map(|(acc, token)| {
s.spawn(move || {
let access = match token {
Some(tok) => probe_repo_access(program, &tok, owner, repo),
None => RepoAccess::None,
};
(acc, access)
})
})
.collect();
handles.into_iter().filter_map(|h| h.join().ok()).collect()
});
let picked = pick_best_account(&results).map(|(acc, auto)| (acc.login.clone(), auto));
AUTO_CACHE
.lock()
.insert(cache_key, CachedAutoAccount { login: picked.as_ref().map(|(l, _)| l.clone()), at: Instant::now() });
picked
}
/// Resolves global status when no project is open.
pub fn global_status(configured_account: String) -> GhProjectAccountStatus {
let configured_account = configured_account.trim().to_owned();
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
let effective_account = if !configured_account.is_empty() {
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
} else {
accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone())
};
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account: None }
}
/// Applies the project's explicit `vcs.github.account` setting to [`ide_core::project_env`]
/// without making any network requests. `Automatic` (`""`) clears any injected `GH_TOKEN` so
/// processes use `gh`'s own behaviour.
pub fn apply_to_project(project: &Project) {
if project.light || !project.is_trusted() {
clear_project_env(project);
return;
}
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
if configured_account.is_empty() {
set_project_token(project, None);
return;
}
let token = find_gh_executable().and_then(|program| gh_token_for_account(&program, &configured_account));
set_project_token(project, token);
}
/// Applies the project's explicit account setting and returns the full account status,
/// probing the project's GitHub remote to suggest a matching non-active `gh` account when
/// `vcs.github.account` is `Automatic` (`""`) and multiple `gh` accounts are signed in.
pub fn project_status(project: &Project) -> GhProjectAccountStatus {
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
if project.light || !project.is_trusted() {
clear_project_env(project);
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
}
apply_to_project(project);
let Some(program) = find_gh_executable() else {
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
};
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
let active_login = accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone());
let effective_account = if !configured_account.is_empty() {
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
} else {
active_login
};
let suggested_account = if configured_account.is_empty() && accounts.len() >= 2 {
primary_github_repo(project)
.and_then(|(owner, repo)| auto_detect_account(&program, &accounts, &owner, &repo))
.and_then(|(login, non_active_match)| non_active_match.then_some(login))
} else {
None
};
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account }
}
fn set_project_token(project: &Project, token: Option<String>) {
let os_tok = token.map(std::ffi::OsString::from);
let changed_root = ide_core::project_env::set_github_token(&project.root, os_tok.clone());
let changed_wt = ide_core::project_env::set_github_token(project.agents.worktrees_dir(), os_tok);
if changed_root || changed_wt {
project.agents.notify_mcp_servers_changed();
}
}
pub fn clear_project_env(project: &Project) {
ide_core::project_env::remove_all(&project.root);
ide_core::project_env::remove_all(project.agents.worktrees_dir());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_github_owner_repo_across_https_ssh_and_scp_remotes() {
assert_eq!(
parse_github_owner_repo("https://github.com/l0ng-ai/openidea.git"),
Some(("l0ng-ai".into(), "openidea".into()))
);
assert_eq!(
parse_github_owner_repo("[email protected]:acme-corp/payments.git"),
Some(("acme-corp".into(), "payments".into()))
);
assert_eq!(parse_github_owner_repo("ssh://[email protected]/alice/demo/"), Some(("alice".into(), "demo".into())));
assert_eq!(parse_github_owner_repo("https://gitlab.com/foo/bar.git"), None);
}
#[test]
fn validates_github_logins_against_flag_injection() {
assert!(is_valid_github_login("alice"));
assert!(is_valid_github_login("alice-work"));
assert!(is_valid_github_login("l0ng-ai"));
assert!(!is_valid_github_login(""));
assert!(!is_valid_github_login("--hostname"));
assert!(!is_valid_github_login("bad space"));
}
#[test]
fn picks_account_with_push_or_private_access_and_preserves_active_on_ties() {
let personal = GhAuthAccount { login: "alice".into(), active: true };
let work = GhAuthAccount { login: "alice-work".into(), active: false };
// Private org repo: personal gets 404 (None), work gets Push -> auto-detects work.
let private_org = vec![(personal.clone(), RepoAccess::None), (work.clone(), RepoAccess::Push)];
let (picked, auto) = pick_best_account(&private_org).unwrap();
assert_eq!(picked.login, "alice-work");
assert!(auto);
// Public org repo: personal gets Read, work gets Push -> auto-detects work.
let public_org = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Push)];
let (picked, auto) = pick_best_account(&public_org).unwrap();
assert_eq!(picked.login, "alice-work");
assert!(auto);
// Third-party public repo: both get Read -> keeps active personal account without auto flag.
let oss = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Read)];
let (picked, auto) = pick_best_account(&oss).unwrap();
assert_eq!(picked.login, "alice");
assert!(!auto);
}
}
+24 -4
Переглянути файл
@@ -12,9 +12,11 @@ pub mod diagnostics_store;
mod direnv;
pub mod environment;
mod formatter;
pub mod github_auth;
mod java_runtime;
mod kotlin_bridge;
pub mod mcp;
pub mod menu;
pub mod notebook;
pub mod ops;
mod phpstan;
@@ -26,6 +28,9 @@ mod requests;
pub mod rpc;
pub mod shell_env;
pub mod trust;
mod ts_code_style;
mod tsc_watch;
pub mod web_server;
pub use project::{Project, history_retention};
@@ -386,10 +391,12 @@ impl Host {
// After the cancels: a capture or open still running then discards what it registers.
ops::heap::close_window_snapshots(self, window);
let project = self.projects.write().remove(window)?;
if self.windows_for_root(&project.root).is_empty()
&& let Some(plugins) = self.plugin_host()
{
plugins.withdraw_project_run_targets(&project.root);
if let Some(plugins) = self.plugin_host() {
if self.windows_for_root(&project.root).is_empty() {
plugins.project_closed(&project.root, window);
} else {
plugins.forget_client(window);
}
}
project.files_events_active.store(false, std::sync::atomic::Ordering::Release);
project.plugin_diagnostics.close();
@@ -413,6 +420,7 @@ impl Host {
self.environment.project_closed();
if self.windows_for_root(&project.root).is_empty() {
self.environment.direnv_closed(&project.root);
crate::github_auth::clear_project_env(&project);
}
}
if let Some(bridge) = &project.kotlin_bridge {
@@ -421,6 +429,9 @@ impl Host {
if let Some(phpstan) = &project.phpstan {
phpstan.stop();
}
if let Some(watch) = &project.tsc_watch {
watch.stop();
}
project.documents.clear_workspace_edit_history();
project.agents.detach_sinks();
project.flutter.stop();
@@ -650,6 +661,9 @@ impl Host {
if let Some(phpstan) = &project.phpstan {
phpstan.stop();
}
if let Some(watch) = &project.tsc_watch {
watch.stop();
}
project.documents.clear_workspace_edit_history();
project.notebooks.stop_admission();
project.agents.shutdown();
@@ -689,6 +703,12 @@ impl Host {
self.requests.begin(id)
}
/// Settings › Tools › Download Mirrors › Use only the configured package registries: nothing
/// is fetched from public package registries the user's tools weren't pointed at.
pub fn configured_registries_only(&self) -> bool {
self.global_settings.effective().tool_downloads.configured_registries_only
}
pub fn begin_project_request(&self, window: &str, id: RequestId) -> CancellationToken {
let token = self.begin_project_read_request(window, id);
if self.project(window).is_ok_and(|p| !p.is_trusted()) {
+45 -2
Переглянути файл
@@ -446,9 +446,15 @@ pub fn stop_run() -> Tool {
"Stops the running command of an agent tab, the way the Run tool window's Stop does: it asks the \
process tree to exit and, with `force`, kills it. Waits up to `timeout` milliseconds (default {STOP_TIMEOUT_MS}) \
for it to end and returns the tab's status (`stoppedByAgent` once it ended). A process that ignores the request \
keeps `stopping`: call again with `force`. The tab stays open with its output."
keeps `stopping`: call again with `force`. The tab stays open with its output.
Pass `runId` instead of `name` to stop a run `execute_run_configuration` started and left running; the result is \
its `state` (`stopped` or `stopping`) and `exitCode` when it has one."
),
|call| async move {
if let Some(id) = call.opt_i64("runId")? {
return stop_configuration_run(&call, id).await;
}
let run = find(&call)?;
let id = run.live_process().ok_or_else(|| IdeError::invalid(format!("`{}` is not running", run.name)))?;
let force = call.flag("force", false)?;
@@ -467,11 +473,48 @@ keeps `stopping`: call again with `force`. The tab stays open with its output."
},
)
.write()
.param(Param::required("name", ParamType::String, NAME))
.param(Param::optional("name", ParamType::String, NAME))
.param(Param::optional("runId", ParamType::Integer, "`runId` from `execute_run_configuration`, instead of `name`"))
.param(Param::optional("force", ParamType::Boolean, "Kill the process tree instead of asking it to exit"))
.param(Param::optional("timeout", ParamType::Integer, "Milliseconds to wait for the command to end"))
}
/// `stop_run` for a run `execute_run_configuration` started (#6127).
async fn stop_configuration_run(call: &Call, raw: i64) -> IdeResult<Output> {
use super::configs::{forget_started, run_exit, started_by_mcp, wait_exit};
if call.opt_str("name")?.is_some() {
return Err(IdeError::invalid("pass either `name` or `runId`, not both"));
}
let id = u32::try_from(raw)
.ok()
.map(ide_core::RunId)
.filter(|id| started_by_mcp(*id))
.ok_or_else(|| IdeError::not_found(format!("no run {raw} started by execute_run_configuration")))?;
let host = call.host();
let deadline = std::time::Instant::now() + timeout(call, STOP_TIMEOUT_MS)?;
let exit = match run_exit(&host, id) {
Some(exit) => Some(exit),
None => {
crate::ops::run::run_stop(&host, call.window(), id)?;
if call.flag("force", false)? {
// A second Stop kills the tree.
crate::ops::run::run_stop(&host, call.window(), id)?;
}
wait_exit(call, id, Some(deadline)).await?
}
};
if exit.is_some() {
forget_started(id);
}
let mut out = Map::new();
out.insert("runId".into(), id.0.into());
out.insert("state".into(), if exit.is_some() { "stopped" } else { "stopping" }.into());
if let Some(Some(code)) = exit {
out.insert("exitCode".into(), code.into());
}
Output::json(Value::Object(out))
}
pub fn tools() -> Vec<Tool> {
vec![run_command(), wait_for_run(), read_run_output(), get_run_status(), send_run_input(), stop_run(), list_runs()]
}
+30 -6
Переглянути файл
@@ -15,8 +15,9 @@ use ide_core::{IdeError, IdeResult, RunId, Severity};
use ide_run::{OutputChunk, RunConfig};
use parking_lot::Mutex;
use serde_json::{Map, Value, json};
use std::collections::HashSet;
use std::path::Path;
use std::sync::Arc;
use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant};
const DEFAULT_TIMEOUT_MS: usize = 10_000;
@@ -281,7 +282,19 @@ workingDirectory, envs).",
}
/// Polls how run `id` ended: `None` while running, else its exit code (if known).
fn run_exit(host: &crate::Host, id: RunId) -> Option<Option<i32>> {
/// The runs `execute_run_configuration` started: `stop_run` takes their `runId`, and only theirs,
/// not the user's own runs.
static STARTED: LazyLock<Mutex<HashSet<RunId>>> = LazyLock::new(Default::default);
pub(super) fn started_by_mcp(id: RunId) -> bool {
STARTED.lock().contains(&id)
}
pub(super) fn forget_started(id: RunId) {
STARTED.lock().remove(&id);
}
pub(super) fn run_exit(host: &crate::Host, id: RunId) -> Option<Option<i32>> {
match host.processes.exit_code(id) {
Ok(exit) => exit,
// Remote (SSH) runs, or a finished run already forgotten: the run list knows whether it runs.
@@ -294,7 +307,7 @@ fn run_exit(host: &crate::Host, id: RunId) -> Option<Option<i32>> {
/// Waits for run `id` to exit, until `deadline`: `None` when it is still running. Cancelling
/// the call stops the run.
async fn wait_exit(call: &Call, id: RunId, deadline: Option<Instant>) -> IdeResult<Option<Option<i32>>> {
pub(super) async fn wait_exit(call: &Call, id: RunId, deadline: Option<Instant>) -> IdeResult<Option<Option<i32>>> {
let host = call.host();
loop {
if let Some(exit) = run_exit(&host, id) {
@@ -741,7 +754,8 @@ Behavior:
Returns the execution result including current output snapshot, optional exit code, and optional `fullOutputPath`.
In OpenIDEA the user is asked first for every call; `programArguments` replace the configuration's \
arguments (appended to a command that is one shell line, such as `npm run dev`); the run does not appear in the Run \
tool window; output files are private and deleted after a day.",
tool window: while it is still running, the result carries `runId`, which `stop_run` stops; output files are private \
and deleted after a day.",
|call| async move {
let target = execution_target(
call.opt_str("configurationName")?,
@@ -807,14 +821,24 @@ one by one",
}
};
STARTED.lock().insert(info.id);
let exit = match limit {
Some(limit) if !limit.is_zero() => wait_exit(&call, info.id, Some(Instant::now() + limit)).await?,
_ => None,
};
if exit.is_some() {
STARTED.lock().remove(&info.id);
}
let c = collector.lock();
let mut result = Map::new();
if let Some(Some(code)) = exit {
result.insert("exitCode".into(), code.into());
match exit {
Some(Some(code)) => {
result.insert("exitCode".into(), code.into());
}
Some(None) => {}
None => {
result.insert("runId".into(), info.id.0.into());
}
}
result.insert("output".into(), c.preview().into());
// An exited run whose whole output is in `output` needs no file.
+35 -1
Переглянути файл
@@ -493,7 +493,7 @@ fn test_kinds(rel: &str) -> &'static [&'static str] {
if JS_FILE.is_match(rel) {
&["npm", "deno", "bun"]
} else if rel.ends_with(".py") {
&["pytest", "python"]
&["pytest", "unittest", "python"]
} else if rel.ends_with(".go") {
&["go"]
} else if rel.ends_with(".rs") {
@@ -644,6 +644,11 @@ fn test_config_for(root: &Path, rel: &str, configs: &[RunConfig]) -> Option<RunC
"npm" | "bun" if base.args.iter().any(|a| a == "--") => derived(&base, rel, with(&[file])),
"npm" | "bun" => derived(&base, rel, with(&["--".into(), file])),
"deno" | "pytest" | "python" => derived(&base, rel, with(&[file])),
// `python -m unittest <file>`; a `discover` selection gives way to the file.
"unittest" => {
let end = base.args.iter().position(|a| a == "discover").unwrap_or(base.args.len());
derived(&base, rel, [base.args[..end].to_vec(), vec![file]].concat())
}
"go" => {
let dir = dir_of(&file);
let target = if dir.is_empty() { ".".to_owned() } else { format!("./{dir}") };
@@ -790,6 +795,11 @@ pub fn target_config(
"pytest" | "python" => {
Some(named(replace_last(file.args.clone(), |f| format!("{f}::{}", target.path.join("::")))))
}
// unittest names tests by dotted module path: `tests.test_calc.TestCalc.test_add`.
"unittest" => Some(named(replace_last(file.args.clone(), |f| {
let module = f.strip_suffix(".py").unwrap_or(f).replace(['/', '\\'], ".");
format!("{module}.{}", target.path.join("."))
}))),
"go" => {
let pattern = format!("^{}$", target.path.iter().map(|p| escape_regexp(p)).collect::<Vec<_>>().join("$/^"));
let benchmark = target.path.first().is_some_and(|p| p.starts_with("Benchmark"));
@@ -921,6 +931,30 @@ mod tests {
);
}
#[test]
fn narrows_unittest_configs_to_files_and_dotted_tests() {
let root = Path::new("/p");
let mut unittest =
blank("unittest".into(), "unittest", "unittest", "python3".into(), vec!["-m".into(), "unittest".into()]);
unittest.is_test = true;
let mut discover = unittest.clone();
discover.args.extend(["discover".into(), "-s".into(), "tests".into()]);
let src = "import unittest\n\nclass TestCalc(unittest.TestCase):\n def test_add(self):\n pass\n";
let rel = "tests/test_calc.py";
for configs in [vec![unittest], vec![discover]] {
let c = context_config(root, rel, &configs, src).unwrap();
assert_eq!(
(c.kind.as_str(), c.args.as_slice()),
("unittest", ["-m", "unittest", rel].map(String::from).as_slice())
);
let ts = detect(src, rel);
let c = target_config(root, &ts[1], rel, &configs, src).unwrap();
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc.test_add"]);
let c = target_config(root, &ts[0], rel, &configs, src).unwrap();
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc"]);
}
}
#[test]
fn narrows_cargo_test_configs() {
let root = Path::new("/p");
File diff suppressed because it is too large. Load diff
+148 -6
Переглянути файл
@@ -6,11 +6,11 @@ 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, AgentModelCatalog, AgentProbe,
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection,
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
RemoteSkillPreview, SkillsPolicy,
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource,
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
};
use ide_command::command;
use ide_core::error::ErrorKind;
@@ -80,6 +80,19 @@ pub fn agent_refresh_models(
host.project(window)?.agents.refresh_models(&provider, force, model.as_deref())
}
/// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply.
#[command(trust = trusted)]
pub async fn agent_preview_copilot_models(
host: &Host,
window: &str,
account: String,
model: Option<String>,
) -> IdeResult<AgentModelCatalog> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
agents.preview_copilot_models(&account, model.as_deref()).await
}
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
#[command(trust = trusted)]
@@ -88,6 +101,13 @@ pub fn agent_set_command(host: &Host, window: &str, id: String, command: Option<
host.project(window)?.agents.set_builtin_command(&id, command)
}
/// Sets additional launch arguments for a built-in ACP agent; an empty list resets them.
#[command(trust = trusted)]
pub fn agent_set_additional_args(host: &Host, window: &str, id: String, args: Vec<String>) -> IdeResult<()> {
host.require_trust(window)?;
host.project(window)?.agents.set_builtin_additional_args(&id, args)
}
/// Environment variables built-in agent `id` starts with (saved in its agent file);
/// an empty map clears them.
#[command(trust = trusted)]
@@ -101,6 +121,106 @@ pub fn agent_set_env(
host.project(window)?.agents.set_builtin_env(&id, env)
}
/// Default Copilot CLI sign-in status alongside authenticated `github.com` accounts in `gh`.
#[command(trust = outside_restricted)]
pub async fn agent_copilot_auth_status(host: &Host, window: &str) -> IdeResult<CopilotAuthStatus> {
host.require_trust_if_project(window)?;
match host.project(window) {
Ok(project) => Ok(project.agents.copilot_auth_status().await),
Err(_) => {
let custom_dir = host.config_dir.join("agents");
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
Ok(ide_agent::copilot_auth_status_with(Some(&custom_dir), None, &cwd).await)
}
}
}
fn spawn_login_pty(
host: &Host,
window: &str,
cwd: std::path::PathBuf,
launch: LoginLaunch,
cols: u16,
rows: u16,
on_event: Channel<AgentLoginEvent>,
) -> IdeResult<ide_terminal::TerminalInfo> {
crate::ops::term::apply_output_rate(host, window);
let cwd = if cwd.is_dir() { cwd } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
let options = ide_terminal::TerminalOptions {
cwd: cwd.into(),
shell: Some(launch.program.to_string_lossy().into_owned()),
args: launch.args,
env: launch.env,
cols: if cols == 0 { 80 } else { cols },
rows: if rows == 0 { 20 } else { rows },
shell_integration: false,
};
let exit_channel = on_event.clone();
host.terminals.spawn_program(
options,
format!("agent-login:{window}"),
host.window_sink(window),
Box::new(move |data| {
let _ = on_event.send(AgentLoginEvent::Output { data });
}),
Some(std::sync::Arc::new(move |code| {
let _ = exit_channel.send(AgentLoginEvent::Exited { code });
})),
)
}
/// Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code.
#[command(trust = outside_restricted)]
pub async fn agent_login_spawn(
host: &Host,
window: &str,
id: String,
cols: u16,
rows: u16,
on_event: Channel<AgentLoginEvent>,
) -> IdeResult<ide_terminal::TerminalInfo> {
host.require_trust_if_project(window)?;
let (cwd, launch) = match host.project(window) {
Ok(project) => {
let root = project.root.clone();
let agents = project.agents.clone();
let launch = host.blocking(move || agents.login_launch(&id)).await?;
(root, launch)
}
Err(_) => {
let custom_dir = host.config_dir.join("agents");
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
let cwd_for_lookup = cwd.clone();
let launch = host
.blocking(move || {
ide_agent::login_launch_without_project(Some(&custom_dir), None, &cwd_for_lookup, &id)
})
.await?;
(cwd, launch)
}
};
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
}
/// Starts `gh auth login --hostname github.com` in an IDE-managed PTY (with ambient token
/// variables cleared) and streams its output and exit code.
#[command(trust = outside_restricted)]
pub async fn agent_gh_login_spawn(
host: &Host,
window: &str,
cols: u16,
rows: u16,
on_event: Channel<AgentLoginEvent>,
) -> IdeResult<ide_terminal::TerminalInfo> {
host.require_trust_if_project(window)?;
let cwd = host
.project(window)
.map(|p| p.root.clone())
.unwrap_or_else(|_| dirs::home_dir().unwrap_or_else(std::env::temp_dir));
let launch = host.blocking(ide_agent::gh_login_launch).await?;
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
}
/// Saves a new custom ACP agent through its agent file.
pub fn save_custom_agent(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> {
host.require_trust(window)?;
@@ -178,6 +298,7 @@ pub async fn agent_registry_install(
) -> IdeResult<()> {
// The agent then shows in `agent_providers`.
let paths = registry_paths(host);
let public_npm_fallback = !host.configured_registries_only();
let installing = Installing::begin(&id)?;
let cancel = host.begin_request(request);
// Also a background task of every project window, so it stays visible and can be
@@ -204,7 +325,7 @@ pub async fn agent_registry_install(
move || cancel.cancel()
});
report(None, None, false);
let result = ide_agent::registry::install(&paths, &id, &cancel, &|e| {
let result = ide_agent::registry::install(&paths, &id, public_npm_fallback, &cancel, &|e| {
match &e {
InstallEvent::Line { text } => report(Some(text.clone()), None, false),
InstallEvent::Progress { fraction, message } => {
@@ -281,6 +402,21 @@ pub async fn agent_import_session(
blocking(move || agents.import_session(&provider, &session_id)).await
}
/// Forks a recorded external session into a new task: its first turn continues the recording
/// as the agent's own fork, under an id the host chooses. `cwd` must be where it was recorded.
#[command(trust = trusted)]
pub async fn agent_fork_session(
host: &Host,
window: &str,
provider: String,
session_id: String,
cwd: String,
) -> IdeResult<AgentTask> {
host.require_trust(window)?;
let agents = host.project(window)?.agents.clone();
blocking(move || agents.fork_session(&provider, &session_id, std::path::Path::new(&cwd))).await
}
#[command(trust = trusted)]
pub async fn agent_create(host: &Host, window: &str, request: NewAgentTask) -> IdeResult<AgentTask> {
host.require_trust(window)?;
@@ -1440,14 +1576,18 @@ ide_command::domain!(
agent_cli_update,
agent_cli_update_check,
agent_commands,
agent_copilot_auth_status,
agent_create,
agent_delete,
agent_entries,
agent_external_sessions,
agent_fork,
agent_fork_session,
agent_gh_login_spawn,
agent_grouped_changes,
agent_hermes_profiles,
agent_import_session,
agent_login_spawn,
agent_mcp_discover_sources,
agent_mcp_import,
agent_mcp_import_selected,
@@ -1457,6 +1597,7 @@ ide_command::domain!(
agent_mcp_save_json,
agent_mcp_set_enabled,
agent_mcp_test,
agent_preview_copilot_models,
agent_probe,
agent_prompt,
agent_providers,
@@ -1469,6 +1610,7 @@ ide_command::domain!(
agent_rollback,
agent_rollback_changes,
agent_send_queued_now,
agent_set_additional_args,
agent_set_command,
agent_shell,
agent_set_config,
+5 -1
Переглянути файл
@@ -767,6 +767,7 @@ pub async fn maven_dependency_completion(
use ide_build::maven::completion::{PomCompletionKind, local_options};
let project = host.project(window)?;
let cache = host.dependency_versions.clone();
let central = !host.configured_registries_only();
let cancel = host.begin_project_read_request(window, request);
let result = host
.blocking(move || {
@@ -785,7 +786,10 @@ pub async fn maven_dependency_completion(
// The local repository answers at once: Central gets `CENTRAL_WAIT`, then the
// lookup finishes in the background and fills the cache for the next request.
// Offline, behind a proxy or rate-limited, a failed fetch never fails completion.
let remote = {
// Only the configured package registries: the local repository alone.
let remote = if !central {
Vec::new()
} else {
let (cache, target) = (cache.clone(), target.clone());
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
+30 -1
Переглянути файл
@@ -34,9 +34,10 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
};
let mut config = config;
let enhanced = take_enhanced_redefinition(&mut config);
let executor = take_executor(&mut config);
let java_exec = java_exec_path(&config);
let mut agents = if is_jvm_launch(&config) {
ide_run::java_agent::current_for(java_exec.as_deref())
ide_run::java_agent::current_for_executor(java_exec.as_deref(), executor.as_deref())
} else {
ide_run::java_agent::Agents::default()
};
@@ -271,6 +272,19 @@ fn take_enhanced_redefinition(config: &mut LaunchConfig) -> Option<Result<&'stat
.then(|| ide_run::java_hotswap::enhanced_redefinition(java_exec_path(config).as_deref()))
}
/// The plugin executor the session launches through (`executor` in the launch extras, which
/// this removes): its plugin's executor-bound Java agent loads only then.
fn take_executor(config: &mut LaunchConfig) -> Option<String> {
let Some(serde_json::Value::Object(mut extra)) =
config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok())
else {
return None;
};
let executor = extra.remove("executor")?;
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
executor.as_str().filter(|s| !s.is_empty()).map(str::to_owned)
}
/// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options:
/// java-debug's and java-analyzer's `vmArgs` (one line, or a list) or the Kotlin debugger's
/// `vmArguments` (a list).
@@ -995,6 +1009,21 @@ mod tests {
}
}
#[test]
fn the_executor_is_taken_out_of_the_launch_extras() {
let extras = |config: &LaunchConfig| {
serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap()
};
let mut config =
launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g", "executor": "acme.reload"}));
assert_eq!(take_executor(&mut config).as_deref(), Some("acme.reload"));
assert!(extras(&config).get("executor").is_none(), "not passed on to the adapter");
assert_eq!(extras(&config)["vmArgs"], "-Xmx1g");
let mut plain = launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g"}));
assert_eq!(take_executor(&mut plain), None);
assert_eq!(extras(&plain)["vmArgs"], "-Xmx1g");
}
#[test]
fn debug_server_port_only_for_local_java_debug() {
let port = |adapter: &str, request: &str, extra| debug_server_port(&launch(adapter, request, extra));
+11
Переглянути файл
@@ -212,6 +212,8 @@ pub async fn dependency_versions(
let project = host.project(window)?;
let cache = host.dependency_versions.clone();
let config_dir = host.config_dir.clone();
// npm and crates.io are asked directly; `go` goes through the configured GOPROXY.
let public_registries = !host.configured_registries_only();
let cancel = host.begin_project_read_request(window, request);
let result = host
.blocking(move || {
@@ -228,6 +230,9 @@ pub async fn dependency_versions(
let versions = cache.versions(&source, &dependency.package, &cancel)?;
return Ok(vec![DependencyVersions { dependency, versions, update: None }]);
}
if !public_registries {
return Ok(Vec::new());
}
if snap.path.file_name().is_some_and(|name| name == "package.json") {
let Some(dependency) = offset.and_then(|offset| npm::dependency_at(&snap.text, offset)) else {
return Ok(Vec::new());
@@ -310,6 +315,9 @@ pub async fn pypi_package(
request: RequestId,
) -> IdeResult<Option<pypi::PypiPackage>> {
let url = pypi::project_url(name.trim()).ok_or_else(|| IdeError::invalid("not a package name"))?;
if host.configured_registries_only() {
return Ok(None);
}
let cancel = host.begin_project_read_request(window, request);
let result = host
.blocking(move || {
@@ -334,6 +342,9 @@ pub async fn pypi_package(
/// PyPI's name list, which the first search downloads and a search a day later refreshes.
#[command(trust = outside_restricted)]
pub async fn pypi_search(host: &Host, window: &str, query: String, request: RequestId) -> IdeResult<Vec<String>> {
if host.configured_registries_only() {
return Ok(Vec::new());
}
let names = host.pypi_names.clone();
let cancel = host.begin_project_read_request(window, request);
let result = host
+19 -3
Переглянути файл
@@ -67,7 +67,12 @@ pub async fn doc_edit(host: &Host, window: &str, doc: DocId, base_version: u32,
#[command(trust = always)]
pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
let project = host.project(window)?;
host.blocking(move || project.documents.save(doc)).await?;
host.blocking(move || {
project.documents.save(doc)?;
remember_saved_encodings(&project);
Ok(())
})
.await?;
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
@@ -83,7 +88,13 @@ pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeR
#[command(trust = always)]
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
let project = host.project(window)?;
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
let saved = host
.blocking(move || {
let saved = project.documents.autosave(doc)?;
remember_saved_encodings(&project);
Ok(saved)
})
.await?;
if saved {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
}
@@ -93,7 +104,12 @@ pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bo
#[command(trust = always)]
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
let project = host.project(window)?;
host.blocking(move || project.documents.save_all()).await?;
host.blocking(move || {
let saved = project.documents.save_all();
remember_saved_encodings(&project);
saved
})
.await?;
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
+52 -6
Переглянути файл
@@ -1,11 +1,13 @@
use crate::Host;
use crate::ops::blocking;
use crate::project::Project;
use ide_command::command;
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
use ide_core::{DocId, IdeEvent, IdeResult, OutlineItem, Range, TextEdit};
use ide_language::{FoldRange, SyntaxHighlights};
use ide_text::LineEnding;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
use std::path::PathBuf;
use ide_workspace::settings::SettingsScope;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
use std::path::{Path, PathBuf};
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
/// editor buffer, so syntax features and language-server requests work in it.
@@ -66,6 +68,49 @@ pub async fn doc_set_encoding(
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
}
/// Keeps the encoding the user chose for a project file in the project's File Encodings
/// mappings, so the file opens in it again. A converted document is kept once it is saved:
/// until then its file is still in the old encoding. Nothing is kept for a document without
/// a file in the project.
#[command(trust = always)]
pub async fn doc_remember_encoding(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
let info = project.documents.snapshot(doc)?;
if info.uri.is_some() || project.documents.keep_encoding_when_saved(doc)? {
return Ok(());
}
remember_encoding(&project, &info.path, &info.encoding)
})
.await
}
/// Keeps the encodings of the converted documents a save has just written.
pub(super) fn remember_saved_encodings(project: &Project) {
for (path, encoding) in project.documents.take_saved_encodings() {
if let Err(e) = remember_encoding(project, &path, &encoding) {
tracing::warn!("the encoding of {} was not kept: {e}", path.display());
}
}
}
fn remember_encoding(project: &Project, path: &Path, encoding: &str) -> IdeResult<()> {
const MAPPINGS: &str = "editor.encodings.mappings";
if project.light {
return Ok(());
}
let Some(file) = ide_workspace::file_defaults::mapping_key(&project.root, path) else {
return Ok(());
};
if project.settings.effective().editor.encodings.mappings.get(&file).is_some_and(|kept| kept == encoding) {
return Ok(());
}
let settings = project.settings.set_map_entry(SettingsScope::Project, MAPPINGS, &file, encoding.into())?;
project.documents.set_file_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
project.sink.emit(IdeEvent::SettingsChanged { key: MAPPINGS.into() });
Ok(())
}
#[command(trust = always)]
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
// Adds or removes the BOM on a UTF-8 document; the change is written on save.
@@ -81,8 +126,8 @@ pub async fn doc_set_line_ending(host: &Host, window: &str, doc: DocId, line_end
/// Structure view: LSP document symbols when available (with tree-sitter
/// visibility and type-alias kinds), tree-sitter otherwise.
/// Tree-sitter answers come from the per-document tree cache (incremental
/// re-parse); large documents get no syntax structure.
/// Normal files reuse the per-document tree cache. Large Markdown files use
/// the syntax parser's size limit for heading outlines.
#[command(trust = always)]
pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<OutlineItem>> {
let project = host.project(window)?;
@@ -118,7 +163,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
}
items
}
None if snap.large => Vec::new(),
None if snap.large && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
None => syntax(),
})
})
@@ -263,6 +308,7 @@ ide_command::domain!(
doc_outline,
doc_python_facts,
doc_rearrange,
doc_remember_encoding,
doc_selection_ranges,
doc_set_bom,
doc_set_encoding,
+95
Переглянути файл
@@ -221,3 +221,98 @@ async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
f.sync().await;
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
}
const MAPPINGS_CHANGED: &str = "editor.encodings.mappings";
impl Fixture {
fn project_settings(&self) -> PathBuf {
self.project.settings.file(ide_workspace::settings::SettingsScope::Project).unwrap().to_path_buf()
}
fn mappings_changed(&self) -> usize {
let events = self.events.lock();
events.iter().filter(|e| matches!(e, IdeEvent::SettingsChanged { key } if key == MAPPINGS_CHANGED)).count()
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remembered_encoding_is_written_once_and_used_when_the_file_is_reopened() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::write(&f.path, "ação\n").unwrap();
let doc = f.open(&f.path).await;
assert_eq!(doc.encoding, "utf-8");
// Changing the encoding alone (Reload from Disk, an RPC client) keeps nothing.
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
assert!(!settings.exists());
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
let written = std::fs::read_to_string(&settings).unwrap();
assert_eq!(written, "[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n");
assert_eq!(f.mappings_changed(), 1);
// The same choice again leaves the file alone.
let stamp = std::fs::metadata(&settings).unwrap().modified().unwrap();
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
assert_eq!(std::fs::metadata(&settings).unwrap().modified().unwrap(), stamp);
assert_eq!(f.mappings_changed(), 1);
doc_close(&f.host, "main", doc.id).await.unwrap();
let reopened = f.open(&f.path).await;
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", "ação\n"));
// A file outside the project has no place in the project's settings.
let outside = f.open(&f.outside).await;
doc_set_encoding(&f.host, "main", outside.id, "iso-8859-15".into(), true).await.unwrap();
doc_remember_encoding(&f.host, "main", outside.id).await.unwrap();
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn converted_encoding_is_remembered_once_the_file_is_saved_in_it() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::write(&f.path, "ação\n").unwrap();
let doc = f.open(&f.path).await;
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), false).await.unwrap();
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
// The file is still UTF-8 on disk: closing without saving must not leave it mapped.
assert!(!settings.exists());
doc_close(&f.host, "main", doc.id).await.unwrap();
let reopened = f.open(&f.path).await;
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("utf-8", "ação\n"));
doc_set_encoding(&f.host, "main", reopened.id, "iso-8859-15".into(), false).await.unwrap();
doc_remember_encoding(&f.host, "main", reopened.id).await.unwrap();
doc_save(&f.host, "main", reopened.id).await.unwrap();
assert_eq!(std::fs::read(&f.path).unwrap(), b"a\xe7\xe3o\n");
assert_eq!(
std::fs::read_to_string(&settings).unwrap(),
"[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n"
);
assert_eq!(f.mappings_changed(), 1);
// Later saves keep nothing more.
doc_save(&f.host, "main", reopened.id).await.unwrap();
assert_eq!(f.mappings_changed(), 1);
doc_close(&f.host, "main", reopened.id).await.unwrap();
let again = f.open(&f.path).await;
assert_eq!((again.encoding.as_str(), again.text.as_str()), ("iso-8859-15", "ação\n"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn encoding_stays_changed_when_it_cannot_be_remembered() {
let f = Fixture::new();
let settings = f.project_settings();
std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
std::fs::write(&settings, "[editor\n").unwrap();
let doc = f.open(&f.path).await;
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
let err = doc_remember_encoding(&f.host, "main", doc.id).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
assert_eq!(std::fs::read_to_string(&settings).unwrap(), "[editor\n");
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().encoding, "iso-8859-15");
assert_eq!(f.mappings_changed(), 0);
}
+91 -15
Переглянути файл
@@ -69,16 +69,15 @@ pub(crate) async fn resolve_launch(
progress("Resolving the module");
let project = host.project(window)?;
let module = ide_core::project_roots::resolve(&project.root, &module);
let scope = {
let scope = std::sync::Arc::new({
let (project, module) = (project.clone(), module.clone());
tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module))
.await
.map_err(|e| IdeError::internal(e.to_string()))??
};
});
if !project.lsp.java_served_by_jdtls(&module) {
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await;
}
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
@@ -110,6 +109,10 @@ pub(crate) async fn resolve_launch(
.await
.map_err(|e| IdeError::internal(e.to_string()))?
};
// A dependency-only POM has no Java project in jdtls, but is a valid launch classpath.
if is_maven_aggregator(&scope.root, &model, &module) {
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel, events).await;
}
// A Maven or Gradle module is built by the IDE's Java build ([`served_by_service`]), unless
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
@@ -139,7 +142,8 @@ pub(crate) async fn resolve_launch(
};
if let Some(outputs) = built {
progress("Resolving the classpath");
let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?;
let server = project.lsp.java_launch(&module, test, false, false, false, cancel);
let mut info = server_launch_extras(server, SERVER_EXTRAS_WAIT).await?;
let data_dir = host.local_data_dir.clone();
let cancel = cancel.clone();
return tokio::task::spawn_blocking(move || {
@@ -383,9 +387,40 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
}
fn is_maven_aggregator(root: &Path, model: &BuildModel, module: &Path) -> bool {
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module && p.packaging == "pom"))
}
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
/// when Settings › Gradle › Build and run using asks for the IDE.
/// How long a launch whose classpath the IDE's Java build resolved waits for what jdtls adds
/// (the JDK it compiles against, the Java project root). jdtls can be busy for minutes importing
/// a Maven project (resolving plugin dependencies), and the run doesn't need it:
/// [`finish_launch`] picks the project's JDK or an installed one.
const SERVER_EXTRAS_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
/// jdtls' launch info, or an empty one when it doesn't answer within `wait` or fails.
async fn server_launch_extras(
server: impl std::future::Future<Output = IdeResult<JavaLaunchInfo>>,
wait: std::time::Duration,
) -> IdeResult<JavaLaunchInfo> {
let fallback =
|| JavaLaunchInfo { path_list_separator: if cfg!(windows) { ";" } else { ":" }.into(), ..Default::default() };
match tokio::time::timeout(wait, server).await {
Ok(Ok(info)) => Ok(info),
Ok(Err(e)) if e.kind == ErrorKind::Cancelled => Err(e),
Ok(Err(e)) => {
tracing::warn!("Java launch without the language server's JDK: {}", e.message);
Ok(fallback())
}
Err(_) => {
tracing::info!(wait_ms = wait.as_millis(), "Java language server busy; launching without its JDK");
Ok(fallback())
}
}
}
pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool {
let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true)));
let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false)));
@@ -418,31 +453,32 @@ fn gradle_served(settings: &Settings) -> bool {
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
/// build tool compiles it, and the classpath comes from that server, else from Maven.
/// Dependency-only Maven POMs also use this path, without querying a Java language server.
#[allow(clippy::too_many_arguments)]
async fn resolve_launch_without_jdtls(
host: &Host,
project: &std::sync::Arc<crate::Project>,
module: PathBuf,
scope: workspace::Scope,
scope: std::sync::Arc<workspace::Scope>,
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
events: Option<LaunchEvents>,
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let scope = std::sync::Arc::new(scope);
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built, by_service) = {
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
tokio::task::spawn_blocking(move || {
let model = load_launch_model(&scope);
let aggregator = is_maven_aggregator(&scope.root, &model, &module);
let on_event = |event: BuildEvent| {
if let Some(events) = &events {
events(event);
}
};
if policy == BuildPolicy::NoBuild {
if policy == BuildPolicy::NoBuild && !aggregator {
return (model, None, false);
}
if served_by_service(&scope.root, &model, &scope.settings, &module)
@@ -455,7 +491,7 @@ async fn resolve_launch_without_jdtls(
&model,
&module,
test,
Some(kind),
(policy != BuildPolicy::NoBuild).then_some(kind),
&cancel,
&on_event,
) {
@@ -467,6 +503,9 @@ async fn resolve_launch_without_jdtls(
Err(e) => return (model, Some(Err(e)), false),
}
}
if policy == BuildPolicy::NoBuild {
return (model, None, false);
}
let built = compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event);
(model, Some(built), false)
})
@@ -486,14 +525,17 @@ async fn resolve_launch_without_jdtls(
)));
}
Some(Ok(built)) => {
info.build = Some(match built.failure {
let status = match built.failure {
None => JavaBuildStatus::Succeeded,
Some(failure) if policy == BuildPolicy::MakeAndContinueOnErrors => {
info.hints.push(failure);
JavaBuildStatus::Failed
}
Some(failure) => return Err(IdeError::internal(failure)),
});
};
if policy != BuildPolicy::NoBuild {
info.build = Some(status);
}
class_paths.extend(built.class_dirs.iter().map(|p| p.to_string_lossy().into_owned()));
}
}
@@ -501,7 +543,8 @@ async fn resolve_launch_without_jdtls(
if let Some(events) = &events {
events(BuildEvent::Progress { message: "Resolving the classpath".into(), fraction: None });
}
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
let aggregator = is_maven_aggregator(&scope.root, &model, &module);
let from_server = if aggregator { None } else { project.lsp.java_server_classpath(&module, test, cancel).await? };
let data_dir = host.local_data_dir.clone();
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
@@ -527,7 +570,11 @@ async fn resolve_launch_without_jdtls(
));
}
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
let classpath = if aggregator && policy == BuildPolicy::NoBuild {
compile::module_classpath_without_build(root, &model, &module, test, cache, &cancel)?
} else {
compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?
};
append_unique_class_paths(
&mut class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
@@ -903,7 +950,7 @@ pub async fn java_build_workspace(
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
/// classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
/// Maven Central), and,
/// Maven Central unless only the configured package registries are allowed), and,
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
#[command(trust = trusted)]
pub async fn java_junit_runner(
@@ -916,6 +963,7 @@ pub async fn java_junit_runner(
let project = host.project(window)?;
let module = ide_core::project_roots::resolve(&project.root, &module);
let data_dir = host.local_data_dir.clone();
let registries_only = host.configured_registries_only();
tokio::task::spawn_blocking(move || {
let scope = workspace::scope_for(&project, &module)?;
let model = load_launch_model(&scope);
@@ -929,7 +977,9 @@ pub async fn java_junit_runner(
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
ide_sdk::java::JunitLauncher::OnClasspath | ide_sdk::java::JunitLauncher::Junit4 => None,
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
ide_sdk::java::JunitLauncher::Missing(version) => {
Some(download_junit_launcher(&data_dir, &version, registries_only)?)
}
ide_sdk::java::JunitLauncher::NoPlatform => {
return Err(IdeError::unavailable(
"Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \
@@ -998,7 +1048,9 @@ fn junit_launch(
}
}
fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf> {
/// The launcher jar downloaded once from Maven Central; with only the configured package
/// registries allowed (Settings › Tools › Download Mirrors), only one downloaded before.
fn download_junit_launcher(data_dir: &Path, version: &str, registries_only: bool) -> IdeResult<PathBuf> {
if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) {
return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'")));
}
@@ -1007,6 +1059,14 @@ fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf>
if dest.is_file() {
return Ok(dest);
}
if registries_only {
return Err(IdeError::unavailable(format!(
"{name} is not on the test classpath, and Settings › Tools › Download Mirrors allows only the \
configured package registries, so it is not downloaded from Maven Central. Add \
org.junit.platform:junit-platform-launcher to the test dependencies, or set Settings › Build Tools › \
Maven › Run tests using to Maven."
)));
}
std::fs::create_dir_all(dest.parent().expect("has a parent"))?;
let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}");
let partial = dest.with_extension("jar.part");
@@ -1041,6 +1101,22 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) {
mod tests {
use super::*;
#[tokio::test(start_paused = true)]
async fn a_busy_or_failing_language_server_does_not_block_a_resolved_launch() {
let wait = std::time::Duration::from_secs(5);
// jdtls importing a Maven project: no answer for minutes (#6122).
let busy = server_launch_extras(std::future::pending(), wait).await.unwrap();
assert!(busy.java_home.is_none() && busy.class_paths.is_empty());
assert!(!busy.path_list_separator.is_empty());
let failed = server_launch_extras(async { Err(IdeError::unavailable("timed out")) }, wait).await.unwrap();
assert!(failed.java_home.is_none());
let home = JavaLaunchInfo { java_home: Some(PathBuf::from("/jdk").into()), ..Default::default() };
let answered = server_launch_extras(async { Ok(home) }, wait).await.unwrap();
assert!(answered.java_home.is_some());
let cancelled = server_launch_extras(async { Err(IdeError::cancelled()) }, wait).await;
assert_eq!(cancelled.unwrap_err().kind, ErrorKind::Cancelled);
}
#[test]
fn junit_launch_applies_the_surefire_configuration() {
let surefire = ide_build::surefire::SurefireConfig {
+3 -2
Переглянути файл
@@ -2292,6 +2292,7 @@ pub async fn plugin_language_visuals(host: &Host, window: &str, doc: DocId) -> I
let project = host.project(window)?;
let snap = project.documents.snapshot(doc)?;
let generation = project.lsp.injection_generation();
let root = project.root.clone();
blocking(move || {
let d = ProviderDocument {
path: snap.path.0,
@@ -2311,8 +2312,8 @@ pub async fn plugin_language_visuals(host: &Host, window: &str, doc: DocId) -> I
{
out.injections = plugins.provide_injections(&d);
out.colors = plugins.language_colors(&d);
out.gutter_actions = plugins.language_gutter_actions(&d);
out.hover_actions = plugins.language_hover_actions(&d);
out.gutter_actions = plugins.language_gutter_actions(&d, Some(&root));
out.hover_actions = plugins.language_hover_actions(&d, Some(&root));
}
project.lsp.set_injections_at(
doc,
+49 -1
Переглянути файл
@@ -7,7 +7,7 @@ use crate::Project;
use ide_command::command;
use ide_core::{DocId, IdeResult, IpcPath, LanguageId, Location, Pos};
use ide_index::{ExtensionCount, FileMatch, IndexStatus, SymbolFilter, SymbolMatch};
use ide_language::{FileReference, WebReference};
use ide_language::{CSS_VARIABLE, FileReference, WebReference};
use ide_workspace::file_refs::{self, PathCompletion};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -25,6 +25,18 @@ pub struct WebGoto {
const MAX_WEB_TARGETS: usize = 200;
/// A custom property declaration (`--accent: #3b82f6`), for `var(--…)` completion and hover.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct CssVariable {
pub name: String,
/// The declared value, whitespace collapsed.
pub value: Option<String>,
pub location: Location,
}
const MAX_CSS_VARIABLES: usize = 5000;
/// A Python class definition and the base names written in its source. The UI builds a
/// name → locations index from every class in the project (attached dependency roots
/// included) to compute ↑ overrides / ↓ overridden gutter markers without a language
@@ -185,6 +197,41 @@ pub async fn web_goto(host: &Host, window: &str, doc: DocId, pos: Pos) -> IdeRes
.await
}
/// Custom properties declared in `doc` (from its current text, first) and in the project's
/// other stylesheets (from the index, so kept up to date as files change).
#[command(trust = always)]
pub async fn web_css_variables(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec<CssVariable>> {
let project = host.project(window)?;
let syntax = host.syntax();
blocking(move || {
let snap = project.documents.snapshot(doc)?;
let own = if snap.large { Vec::new() } else { syntax.web_definitions(&snap.language, &snap.text) };
let mut out: Vec<CssVariable> = own
.into_iter()
.filter(|t| t.kind == CSS_VARIABLE)
.map(|t| CssVariable {
name: t.name,
value: t.container,
location: Location { path: snap.path.clone(), range: t.range, uri: None },
})
.collect();
out.extend(
project
.index
.symbols_prefixed("--", CSS_VARIABLE, MAX_CSS_VARIABLES)
.into_iter()
.filter(|m| *m.path != *snap.path)
.map(|m| CssVariable {
name: m.name,
value: m.container,
location: Location { path: m.path, range: m.range, uri: None },
}),
);
Ok(out)
})
.await
}
/// The file a Python import path (`a.b.c`, or `.x` relative to `from`) names; `None` when
/// no project or content root has it.
#[command(trust = always)]
@@ -450,6 +497,7 @@ ide_command::domain!(
recent_files,
remove_recent,
scope_files,
web_css_variables,
web_goto,
web_unresolved_references,
);
+103 -6
Переглянути файл
@@ -22,6 +22,8 @@ pub struct ProjectInfo {
pub workspace: Option<ide_workspace::workspace::Workspace>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unity: Option<ide_workspace::unity::UnityProjectInfo>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unreal: Option<ide_workspace::unreal::UnrealProjectInfo>,
}
pub fn info(project: &Project) -> ProjectInfo {
@@ -45,6 +47,7 @@ pub fn info(project: &Project) -> ProjectInfo {
root: project.root.clone().into(),
workspace,
unity: ide_workspace::unity::detect(&project.root),
unreal: ide_workspace::unreal::detect(&project.root),
}
}
@@ -107,6 +110,22 @@ pub fn settings_removed_theme(host: &Host, window: &str) -> Option<String> {
}
}
/// What a changed setting `key` starts or stops right away. Both `settings_set` commands (this
/// crate's and the desktop's) call it after writing the value.
pub fn apply_setting(host: &Arc<Host>, window: &str, key: &str) {
if key == "mcpServer" || key.starts_with("mcpServer.") {
host.mcp.apply(host);
}
if key == "terminal" || key.starts_with("terminal.") {
super::term::apply_output_rate(host, window);
}
if "languages.typescript.watchProblems".starts_with(key)
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
{
watch.apply(&host.runtime);
}
}
/// `value` is JSON text, e.g. `14` or `"dark"`. Every window (for a project
/// value: that project's windows) is told (`IdeEvent::SettingsChanged`) so it
/// re-reads its effective settings.
@@ -119,12 +138,7 @@ pub fn settings_set(
value: String,
) -> IdeResult<Settings> {
let applied = set_settings(host, window, scope, &key, &value)?;
if key == "mcpServer" || key.starts_with("mcpServer.") {
host.mcp.apply(host);
}
if key == "terminal" || key.starts_with("terminal.") {
super::term::apply_output_rate(host, window);
}
apply_setting(host, window, &key);
let sink = host.window_sink(window);
sink.emit(IdeEvent::SettingsChanged { key });
if let Some(root) = applied.roots_changed {
@@ -282,6 +296,36 @@ fn refresh_workspace(project: &Project) {
project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() });
}
/// Records `project` in `recent` (its branch, unless attached to a workspace, and display name).
pub fn record_recent(recent: &ide_workspace::RecentProjects, project: &Project) -> IdeResult<()> {
let info = info(project);
let attached = info.workspace.as_ref().is_some_and(|w| !w.is_container(&project.root));
let branch = if attached {
None
} else {
project.repos.read().primary().and_then(|r| r.branch_info().ok()).and_then(|b| b.head)
};
recent.touch(&project.root, branch)?;
recent.rename(&project.root, Some(&info.display_name))?;
Ok(())
}
/// File › Rename Project…: the display name of `window`'s project; an empty `name` restores the
/// folder name. A workspace container renames the workspace, else it is stored in project settings.
pub fn rename(host: &Host, window: &str, name: &str) -> IdeResult<Arc<Project>> {
let project = host.project(window)?;
let name = name.trim();
if let Some(workspace) = ide_workspace::workspace::Workspace::load(&project.root)?
&& workspace.is_container(&project.root)
{
save_workspace(host, window, name, workspace.projects)?;
} else {
let value = if name.is_empty() { serde_json::Value::Null } else { serde_json::Value::String(name.to_owned()) };
project.settings.set(SettingsScope::Project, "general.projectName", value)?;
}
Ok(project)
}
/// Attaches a trusted folder without replacing the current project.
pub fn attach_workspace(host: &Host, window: &str, path: &Path) -> IdeResult<ide_core::IpcPath> {
let project = host.project(window)?;
@@ -410,6 +454,14 @@ pub fn set_settings(
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
host.apply_git_executable();
}
if key == "vcs" || key == "vcs.github" || key.starts_with("vcs.github.") {
let affected = affected();
host.runtime.spawn_blocking(move || {
for project in affected {
crate::github_auth::apply_to_project(&project);
}
});
}
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
for project in affected() {
@@ -486,11 +538,56 @@ pub fn set_settings(
Ok(SettingsApplied { settings: host.with_proxy_password(settings), project_scope, roots_changed })
}
/// Reads the GitHub CLI (`gh`) keyring accounts and which account applies to `window`'s project.
#[command(trust = outside_restricted)]
pub async fn gh_project_account_status(
host: &Arc<Host>,
window: &str,
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
host.require_trust_if_project(window)?;
let current = host.project(window).ok().filter(|p| !p.light);
let global_account = host.global_settings.effective().vcs.github.account;
host.blocking(move || match current {
Some(project) => Ok(crate::github_auth::project_status(&project)),
None => Ok(crate::github_auth::global_status(global_account)),
})
.await
}
/// Sets `vcs.github.account` for `window`'s project (or globally when no project is open),
/// updates the project's `GH_TOKEN` environment immediately, and returns the updated status.
#[command(trust = outside_restricted)]
pub async fn gh_set_project_account(
host: &Arc<Host>,
window: &str,
account: String,
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
host.require_trust_if_project(window)?;
let trimmed = account.trim().to_owned();
if !trimmed.is_empty() && !crate::github_auth::is_valid_github_login(&trimmed) {
return Err(ide_core::IdeError::invalid(format!("invalid GitHub account login: {trimmed}")));
}
let current = host.project(window).ok().filter(|p| !p.light);
let scope = if current.is_some() { SettingsScope::Project } else { SettingsScope::Global };
let json = serde_json::to_string(&trimmed).map_err(|e| ide_core::IdeError::internal(e.to_string()))?;
set_settings(host, window, scope, "vcs.github.account", &json)?;
let sink = host.window_sink(window);
sink.emit(IdeEvent::SettingsChanged { key: "vcs.github.account".into() });
let global_account = host.global_settings.effective().vcs.github.account;
host.blocking(move || match current {
Some(project) => Ok(crate::github_auth::project_status(&project)),
None => Ok(crate::github_auth::global_status(global_account)),
})
.await
}
ide_command::domain!(
project:
cancel_request,
cancel_task,
close_project,
gh_project_account_status,
gh_set_project_account,
open_project,
project_current,
project_roots,
+4 -3
Переглянути файл
@@ -493,7 +493,7 @@ async fn start_inner(
}
// A Python configuration pointing at a missing interpreter fails in the depth of
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test");
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test");
if is_python && Path::new(&config.command).components().count() > 1 {
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
@@ -559,7 +559,8 @@ async fn start_inner(
/// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an
/// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a
/// run target gets none; the console says so, and why an approved agent was left out.
/// run target gets none; the console says so, and why an approved agent was left out. A launch
/// through a plugin executor (`extras.executor`) also gets that plugin's executor-bound agent.
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_dir: Option<&Path>) {
if !ide_run::java_agent::applies(&config.kind) {
return;
@@ -575,7 +576,7 @@ fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_di
.or_else(|| std::env::var_os("JAVA_HOME").map(std::path::PathBuf::from));
ide_run::java_agent::launched_java(&config.command, &search, home.as_deref())
});
let agents = ide_run::java_agent::current_for(java.as_deref());
let agents = ide_run::java_agent::current_for_executor(java.as_deref(), config.extras.executor.as_deref());
let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") });
if run_dir.is_none() {
if !agents.options.is_empty() {
+2 -2
Переглянути файл
@@ -110,8 +110,8 @@ pub(crate) fn search_project(
_ => true,
};
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
let defaults = project.documents.file_defaults();
let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned());
// Search's UTF-8 fast path does not need to resolve the configured encoding.
let fallback = |path: &Path| project.documents.configured_encoding_for(path);
let mut total = SearchSummary::default();
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
let mut remaining = query.clone();
+9 -2
Переглянути файл
@@ -30,8 +30,13 @@ impl ReplaceHost for DocumentsHost<'_> {
continue;
}
docs.apply_edits(doc, &edits)?;
if save {
// 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 {
docs.save(doc)?;
} else if save {
docs.autosave(doc)?;
}
return Ok(edits.len() as u32);
}
@@ -50,7 +55,9 @@ impl ReplaceHost for DocumentsHost<'_> {
/// Edits go through the document layer as one patch per file, so open editors
/// update live and undo the whole file's replacements in one step. Unsaved
/// editor buffers are replaced in place and left unsaved; other open documents
/// are saved, and files that were not open are opened transiently, saved and closed.
/// are saved unless the file changed on disk meanwhile (then the replacement stays
/// unsaved, as autosave does), and files that were not open are opened
/// transiently, saved and closed.
///
/// With `all_in_scope` (Replace All after the search hit its match limit) the
/// scope is searched again without the limit and every match in it is replaced,
+1 -1
Переглянути файл
@@ -11,7 +11,7 @@ use ide_spell::{Region, RegionKind, SpellScope, Speller, Typo};
use std::path::{Path, PathBuf};
/// Languages checked as prose (all text but code spans).
const PROSE: &[&str] = &["plaintext", "markdown", "restructuredtext", "asciidoc", "latex"];
const PROSE: &[&str] = &["plaintext", "markdown", "mdx", "restructuredtext", "asciidoc", "latex"];
/// Custom dictionary paths: `~/…` from home, relative ones from the project root.
fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec<PathBuf> {
+7 -3
Переглянути файл
@@ -29,15 +29,19 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
&root,
&settings,
));
// Godot is usually an app bundle / Flatpak outside the search path.
let found = ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p));
// Godot and GitHub CLI can live in app bundles / MSI / Snap folders outside the search path.
let mut found: std::collections::BTreeMap<_, _> =
ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p)).into_iter().collect();
if let Some(gh) = ide_core::tool_path::find_gh_outside_search_path() {
found.insert("gh".to_owned(), gh);
}
let runtime = ide_sdk::apply::tool_install_environment(&root, &settings);
let work_dir = (!root.as_os_str().is_empty()).then_some(root);
Ok(Tools::new(&data)
.with_downloads(settings.tool_downloads.clone())
.with_runtime(runtime.commands, runtime.env)
.with_custom_paths(custom)
.with_found_paths(found.into_iter().collect())
.with_found_paths(found)
.with_work_dir(work_dir))
}
+35 -9
Переглянути файл
@@ -24,6 +24,12 @@ struct LogAccess {
cache: PathBuf,
}
fn external_log_of(host: &Host, window: &str, path: &Path) -> Option<std::sync::Arc<Repo>> {
host.external_logs.read().get(host.owner_window(window)).and_then(|repos| {
repos.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
})
}
/// Immutable Git objects exposed through the editor's ordinary read-only VFS.
/// `encoding` re-decodes the blob with it ("Reload with Encoding") instead of
/// the project's detection.
@@ -81,9 +87,7 @@ async fn revision_text(
encoding: Option<&str>,
) -> IdeResult<Option<(String, &'static encoding_rs::Encoding, bool)>> {
let project = host.project(window).ok();
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
});
let external = external_log_of(host, window, path);
let (path, rev, encoding) = (path.to_path_buf(), rev.to_owned(), encoding.map(str::to_owned));
blocking(move || {
fn with_repo<T>(
@@ -622,9 +626,7 @@ pub async fn vcs_staging_line_hunks(
#[command(trust = always)]
pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
let project = host.project(window).ok();
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
});
let external = external_log_of(host, window, &path);
blocking(move || {
if let Some(project) = project {
return project.with_log_backend_of(&path, |r| {
@@ -640,14 +642,37 @@ pub async fn vcs_file_at(host: &Host, window: &str, path: PathBuf, rev: Option<S
.await
}
/// An image at the selected Git revision or index stage as a data URL, absent if the path is missing.
#[command(trust = always)]
pub async fn vcs_image_at(host: &Host, window: &str, path: PathBuf, rev: String) -> IdeResult<Option<String>> {
let project = host.project(window).ok();
let external = external_log_of(host, window, &path);
blocking(move || {
let mime = ide_vfs::image_mime(&path)
.ok_or_else(|| ide_core::IdeError::invalid(format!("{} is not a supported image", path.display())))?;
let read = |repo: &Repo| repo.file_bytes_at_bounded(&path, &rev, ide_vfs::MAX_IMAGE_SIZE as usize);
let bytes = if let Some(project) = project {
if !ide_vfs::on_local_drive(&path)
&& external.is_none()
&& !project.repos().all().iter().any(|repo| ide_vfs::same_share(repo.root(), &path))
{
return Err(ide_core::IdeError::invalid("image is not on a local drive or an opened share"));
}
project.with_log_repo_of(&path, read)?
} else {
read(external.as_deref().ok_or_else(|| ide_core::IdeError::unavailable("external Git log is not open"))?)?
};
Ok(bytes.map(|bytes| format!("data:{mime};base64,{}", ide_vfs::base64(&bytes))))
})
.await
}
/// The file's git mode at `rev` (`100644`, `100755`, `120000`…), `"WT"` for the
/// worktree; `None` when absent there. Lets the diff viewer report a mode-only change.
#[command(trust = trusted)]
pub async fn vcs_file_mode(host: &Host, window: &str, path: PathBuf, rev: Option<String>) -> IdeResult<Option<String>> {
let project = host.project(window).ok();
let external = host.external_logs.read().get(host.owner_window(window)).and_then(|rs| {
rs.iter().filter(|r| path.starts_with(r.root())).max_by_key(|r| r.root().components().count()).cloned()
});
let external = external_log_of(host, window, &path);
blocking(move || {
if let Some(project) = project {
return project.with_log_backend_of(&path, |r| r.file_mode_at(&path, rev.as_deref()));
@@ -3200,6 +3225,7 @@ ide_command::domain!(
vcs_discard,
vcs_edit_remote,
vcs_file_at,
vcs_image_at,
vcs_file_mode,
vcs_diff_entries,
vcs_git_version,
+368 -8
Переглянути файл
@@ -68,6 +68,17 @@ pub trait PluginWorkspace: Send + Sync {
fn problems(&self, _client: &str, _path: Option<&Path>) -> Result<Vec<ide_plugin::FileProblems>, HostError> {
Ok(Vec::new())
}
/// Fork a recorded native agent session into a new task in the invoking
/// window's project, returning the new task id (API 1.18).
fn fork_agent_session(
&self,
_client: &str,
_agent: &str,
_session_id: &str,
_cwd: &Path,
) -> Result<String, HostError> {
Err(HostError::Failed("agent fork unavailable".into()))
}
/// Roots of the open projects.
fn projects(&self) -> Vec<PathBuf>;
@@ -206,6 +217,61 @@ impl SecretStore for FileSecretStore {
}
}
/// Plugin secrets in the OS credential store (Secret Service, Windows Credential
/// Manager), like saved SSH and agent values. Without a credential store a value
/// stays in the owner-only [`FileSecretStore`] file, which also still answers for
/// values saved there by an older version until they are set again.
pub struct CredentialSecretStore {
store: ide_ssh::secrets::SecretFile,
fallback: FileSecretStore,
}
impl CredentialSecretStore {
/// `dir`: the plugins' data directory (the index file and the fallback files live there).
pub fn new(dir: PathBuf) -> Self {
Self::with_store(ide_ssh::secrets::SecretFile::new(dir.join("plugin-secrets.json")), dir)
}
fn with_store(store: ide_ssh::secrets::SecretFile, dir: PathBuf) -> Self {
Self { store, fallback: FileSecretStore { dir } }
}
fn key(plugin: &str, name: &str) -> String {
format!("{plugin}/{name}")
}
/// Drops a value from the fallback file, writing it only when it held one.
fn forget_fallback(&self, plugin: &str, name: &str) -> Result<(), String> {
if self.fallback.get(plugin, name).is_none() {
return Ok(());
}
self.fallback.set(plugin, name, None)
}
}
impl SecretStore for CredentialSecretStore {
fn get(&self, plugin: &str, name: &str) -> Option<String> {
self.store.get(&Self::key(plugin, name)).or_else(|| self.fallback.get(plugin, name))
}
fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> {
let key = Self::key(plugin, name);
match value {
Some(v) => match self.store.set(&key, v) {
Ok(()) => self.forget_fallback(plugin, name),
Err(e) => {
tracing::warn!("plugin secrets: {key} is kept in the plugin's data directory: {}", e.message);
self.fallback.set(plugin, name, Some(v))
}
},
None => {
self.store.delete(&key);
self.forget_fallback(plugin, name)
}
}
}
}
/// Largest response body a plugin receives.
const MAX_RESPONSE: usize = 16 << 20;
/// Largest stdout / stderr kept from a process by default.
@@ -675,6 +741,9 @@ pub(super) struct Shared {
net_prompts: Mutex<HashMap<String, Option<Instant>>>,
pub net_hosts_session_only: AtomicBool,
session_net_hosts: Mutex<HashMap<String, BTreeSet<String>>>,
/// Setting-derived approvals kept for the session only (remote hosts),
/// plugin → `net:setting:` grant → its approved host.
pub(super) session_setting_hosts: Mutex<HashMap<String, BTreeMap<String, String>>>,
pub(super) next_prompt: AtomicU64,
pub(super) run_configurations: super::run_detectors::DynamicConfigurations,
pub(super) run_targets: Mutex<super::run_targets::Targets>,
@@ -695,8 +764,11 @@ pub(super) struct Shared {
pub(super) closed_clients: Mutex<BTreeSet<String>>,
/// plugin → kinds subscribed at run time (kept across idle reclaim).
pub subscriptions: Mutex<super::event_paths::Subscriptions>,
/// Paths outside their project that plugins watch (kept across idle reclaim).
pub(super) external_watches: super::external_watch::ExternalWatches,
/// plugin → files it shows problems for, withdrawn when it stops.
diagnostics: Mutex<HashMap<String, BTreeSet<PathBuf>>>,
project_generations: Mutex<HashMap<PathBuf, u64>>,
pub secrets: RwLock<Arc<dyn SecretStore>>,
/// (plugin, `process:` capability) → the approved program.
pub pins: Arc<RwLock<HashMap<(String, String), ProgramPin>>>,
@@ -719,6 +791,29 @@ pub(super) struct Shared {
/// A window's log tabs of one plugin: key → what it runs, oldest first.
type LogTabs = Vec<(String, ide_plugin::ServiceLog)>;
/// The settings key a `net:setting:` grant derives its host from.
fn setting_key(cap: &Capability) -> String {
match cap {
Capability::NetSetting { key, .. } => key.clone(),
_ => String::new(),
}
}
/// The host a setting value names: a bare host, or a URL the user pasted
/// (`https://jira.corp.example/`), checked with the manifest host rules — a `*`
/// is refused. `Ok(None)` when the value is empty (the setting is cleared).
pub(super) fn setting_host(value: &str) -> Result<Option<String>, String> {
let value = value.trim();
if value.is_empty() {
return Ok(None);
}
let host =
if value.contains("://") { ide_plugin::net_host(value)? } else { value.trim_end_matches('.').to_owned() };
ide_extension::manifest_host(&host)
.map(Some)
.map_err(|_| format!("{value:?} is not a host (example.com) or a URL (https://example.com/)"))
}
/// Log tabs a plugin's code may have open in one window; opening more forgets
/// the oldest (that tab can no longer start its program).
const MAX_LOG_TABS: usize = 32;
@@ -757,6 +852,7 @@ impl Shared {
net_prompts: Mutex::default(),
net_hosts_session_only: AtomicBool::new(false),
session_net_hosts: Mutex::default(),
session_setting_hosts: Mutex::default(),
next_prompt: AtomicU64::new(1),
run_configurations: Arc::default(),
run_targets: Mutex::default(),
@@ -773,11 +869,35 @@ impl Shared {
contexts: Mutex::default(),
closed_clients: Mutex::default(),
subscriptions: Mutex::default(),
external_watches: Default::default(),
diagnostics: Mutex::default(),
project_generations: Mutex::default(),
log_tabs: Mutex::default(),
})
}
pub(super) fn project_generation(&self, root: &Path) -> Result<u64, HostError> {
let workspace = self.workspace().ok_or(HostError::Cancelled)?;
if !workspace.projects().iter().any(|r| r == root) {
return Err(HostError::NotFound("project is not open".into()));
}
let mut gens = self.project_generations.lock();
Ok(*gens.entry(root.to_path_buf()).or_insert(1))
}
pub(super) fn bump_project_generation(&self, root: &Path) -> u64 {
let mut gens = self.project_generations.lock();
let cur = gens.entry(root.to_path_buf()).or_insert(1);
*cur = cur.saturating_add(1);
*cur
}
/// Moves a closed project's generation on rather than forgetting it, so a handle
/// taken before the close stays stale if the project is opened again.
pub(super) fn close_project_generation(&self, root: &Path) {
self.bump_project_generation(root);
}
pub(super) fn workspace(&self) -> Option<Arc<dyn PluginWorkspace>> {
self.workspace.read().clone()
}
@@ -1000,6 +1120,7 @@ impl Shared {
self.withdraw_prompts(plugin);
self.net_prompts.lock().remove(plugin);
self.session_net_hosts.lock().remove(plugin);
self.session_setting_hosts.lock().remove(plugin);
let removed: Vec<(Option<String>, String)> = {
let mut contexts = self.contexts.lock();
let keys: Vec<_> = contexts.keys().filter(|(_, p, _)| p == plugin).cloned().collect();
@@ -1023,6 +1144,9 @@ impl Shared {
let _ = workspace.publish_diagnostics(plugin, &path, Vec::new());
}
}
if subscriptions {
self.external_watches.remove_plugin(plugin);
}
if subscriptions && self.subscriptions.lock().remove(plugin) {
self.sink.emit(None, PluginEvent::SubscriptionsChanged);
}
@@ -1493,6 +1617,73 @@ fn failed(e: impl std::fmt::Display) -> HostError {
HostError::Failed(e.to_string())
}
/// `cwd` of `open-terminal-session-in`: a directory of the project, relative to `root`
/// (`""` is the root), that exists and stays inside the project once symlinks are resolved.
fn project_subdirectory(root: &Path, cwd: &str) -> Result<PathBuf, HostError> {
let invalid = |why: &str| HostError::Invalid(format!("terminal directory {cwd:?}: {why}"));
if cwd.len() > 4096 || cwd.contains('\0') {
return Err(invalid("not a path"));
}
let relative = Path::new(cwd);
if relative.is_absolute() || relative.has_root() {
return Err(invalid("must be relative to the project root"));
}
let base = dunce::canonicalize(root).map_err(|_| invalid("the project root is gone"))?;
let dir = dunce::canonicalize(base.join(relative)).map_err(|_| invalid("no such directory"))?;
if !dir.starts_with(&base) {
return Err(invalid("outside the project"));
}
if !dir.is_dir() {
return Err(invalid("not a directory"));
}
Ok(dir)
}
impl PluginApi {
/// The value of `key` the user set for this plugin, as a plain string
/// (`None` when unset or not a string).
pub(super) fn setting_value(&self, key: &str) -> Option<String> {
let raw = self.setting(None, key)?;
serde_json::from_str::<String>(&raw).ok()
}
/// The plugin's `net:setting:` grants with their hosts: the approved host
/// while the setting still holds it, and the pending one to approve
/// otherwise (`None` when the value is unset or not a host).
pub(super) fn net_setting_hosts(&self, subject: &Subject) -> Vec<(Capability, Option<String>, Option<String>)> {
let derived: Vec<Capability> = self
.pkg
.manifest
.capabilities
.all()
.filter(|c| matches!(c, Capability::NetSetting { .. }))
.cloned()
.collect();
if derived.is_empty() {
return Vec::new();
}
let ledger = self.shared.ledger.lock();
let grant = ledger.get(subject).filter(|g| g.confirmed);
let session = self.shared.session_setting_hosts.lock().get(self.id()).cloned().unwrap_or_default();
derived
.into_iter()
.map(|cap| {
let current = self.setting_value(&setting_key(&cap)).and_then(|v| setting_host(&v).ok()).flatten();
let record = grant.and_then(|g| g.setting_hosts.get(&cap.to_string())).map(String::as_str);
let session_host = session.get(&cap.to_string()).map(String::as_str);
// An approval covers requests only while the setting still holds it.
let approved = [record, session_host]
.into_iter()
.flatten()
.find(|host| current.as_deref() == Some(host))
.map(str::to_owned);
let pending = current.filter(|host| approved.as_deref() != Some(host));
(cap, approved, pending)
})
.collect()
}
}
impl HostApi for PluginApi {
fn database_upsert(&self, root: &Path, source: ide_plugin::PluginDataSource) -> Result<(), HostError> {
let (host, db) = self.database_host(root)?;
@@ -1561,8 +1752,13 @@ impl HostApi for PluginApi {
}
}
fn register_run_target(&self, root: &Path, target: ide_plugin::PluginRunTarget) -> Result<(), HostError> {
self.register_target(root, target)
fn register_run_target(
&self,
root: &Path,
target: ide_plugin::PluginRunTarget,
generation: Option<u64>,
) -> Result<(), HostError> {
self.register_target(root, target, generation)
}
fn unregister_run_target(&self, root: &Path, id: &str) {
self.unregister_target(root, id);
@@ -1573,7 +1769,7 @@ impl HostApi for PluginApi {
client: &str,
config: &str,
args: Vec<String>,
debug: bool,
options: ide_plugin::PluginRunStartOptions,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<String, HostError> {
@@ -1584,15 +1780,40 @@ impl HostApi for PluginApi {
let mut run =
self.shared.workspace().ok_or(HostError::Cancelled)?.run_configuration(client, self.id(), config)?;
let binary = self.approved_program_in_project(&run.command, self.shared.project_of(client).as_deref())?;
let user_override = !run.detected;
let debug = options.debug;
if debug && run.debug_adapter.is_none() {
return Err(HostError::Invalid("this configuration has no debugger".into()));
}
let program = run.command.clone();
if debug && run.extras.target.as_ref().is_some_and(|t| !t.is_empty()) {
let has_target = run.extras.target.as_ref().is_some_and(|t| !t.is_empty());
if debug && has_target {
return Err(HostError::Invalid("debugging this target is not supported".into()));
}
if debug && options.output_mode == Some(ide_plugin::PluginOutputMode::Pty) {
return Err(HostError::Invalid("terminal emulation cannot be used when debugging".into()));
}
if debug {
run.extras.emulate_terminal = false;
run.command = binary.to_string_lossy().into_owned();
} else {
// Precedence: user-saved override > per-invocation override > plugin default.
if !user_override && let Some(mode) = options.output_mode {
run.extras.emulate_terminal = mode == ide_plugin::PluginOutputMode::Pty;
}
if run.extras.emulate_terminal {
if run.is_test {
return Err(HostError::Invalid("terminal emulation cannot be used for test configurations".into()));
}
if run.extras.stdin_file.is_some() {
return Err(HostError::Invalid(
"input cannot be redirected from a file when emulating a terminal".into(),
));
}
if has_target {
return Err(HostError::Invalid("terminal emulation on this target is not supported".into()));
}
}
}
run.args.extend(args);
let id = self.new_operation(
@@ -1613,6 +1834,7 @@ impl HostApi for PluginApi {
key: String,
title: String,
cmd: ProcessCommand,
cwd: Option<String>,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<String, HostError> {
@@ -1623,6 +1845,11 @@ impl HostApi for PluginApi {
if !self.shared.workspace().is_some_and(|w| w.trusted(&root)) {
return Err(HostError::Denied("project is not trusted".into()));
}
// Trust and the program pin stay the project's; the directory only moves the shell.
let dir = match &cwd {
Some(cwd) => project_subdirectory(&root, cwd)?,
None => root.clone(),
};
let binary = self.approved_program_in_project(&cmd.program, Some(&root))?;
let mut command = StdCommand::new(&binary);
append_process_env(&mut command, &cmd.env)?;
@@ -1654,7 +1881,7 @@ impl HostApi for PluginApi {
program: binary.into(),
args: cmd.args,
env: cmd.env.into_iter().collect(),
cwd: root.into(),
cwd: dir.into(),
};
if let Err(error) = self.window_request(client, request, cancel, timeout) {
self.shared.operations.lock().remove(&id);
@@ -1830,6 +2057,12 @@ impl HostApi for PluginApi {
fn file_icon_decorations(&self, set: &str, items: Vec<(PathBuf, String)>) -> Result<(), HostError> {
self.set_file_icon_decorations(set, items)
}
fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result<String, HostError> {
self.shared
.workspace()
.ok_or_else(|| HostError::NotFound("window project".into()))?
.fork_agent_session(client, agent, session_id, cwd)
}
fn console_rules(&self, rules: Vec<ide_plugin::ConsoleRule>) -> Result<(), HostError> {
let rules = super::console_rules::normalize(rules).map_err(HostError::Invalid)?;
let mut all = self.shared.console_rules.lock();
@@ -2196,7 +2429,10 @@ impl HostApi for PluginApi {
fn reveal_view(&self, client: Option<&str>, view: &str) -> Result<(), HostError> {
let client = from_window(client, "reveal a view")?;
let declared = self.shared.ui.items(super::ui_points::VIEWS, Some(self.id())).iter().any(|i| i.key == view);
// A tool window comes to the front; a dialog (API 1.18) opens.
let declared = [super::ui_points::VIEWS, super::ui_points::DIALOGS]
.into_iter()
.any(|point| self.shared.ui.items(point, Some(self.id())).iter().any(|i| i.key == view));
if !declared {
return Err(HostError::NotFound(format!("the plugin declares no view {view:?}")));
}
@@ -2690,6 +2926,16 @@ impl HostApi for PluginApi {
return Ok(None);
}
let host = host.trim_end_matches('.').to_ascii_lowercase();
// A host the plugin derives from a setting is approved in Settings,
// not asked about here: pending or revoked, it stays denied without a
// dialog (#3809).
if self.pkg.manifest.capabilities.all().any(|cap| {
matches!(cap, Capability::NetSetting { http: false, key: _ })
&& self.setting_value(&setting_key(cap)).and_then(|v| setting_host(&v).ok()).flatten().as_deref()
== Some(host.as_str())
}) {
return Ok(None);
}
{
let ledger = self.shared.ledger.lock();
if let Some(grant) = ledger.get(subject)
@@ -2932,14 +3178,36 @@ impl HostApi for PluginApi {
}
}
fn subscribe_paths(&self, kind: &str, globs: Vec<String>) -> Result<(), HostError> {
let filter = super::event_paths::PathFilter::new(kind, globs)?;
fn subscribe_paths_with_options(
&self,
kind: &str,
globs: Vec<String>,
debounce_ms: Option<u32>,
) -> Result<(), HostError> {
let debounce = match debounce_ms {
Some(ms) if ms > 60_000 => return Err(HostError::Invalid("debounce must not exceed 60000 ms".into())),
Some(ms) => Some(Duration::from_millis(ms as u64)),
None => None,
};
let filter = super::event_paths::PathFilter::with_debounce(kind, globs, debounce)?;
if self.shared.subscriptions.lock().set_paths(self.id(), kind, filter) {
self.shared.sink.emit(None, PluginEvent::SubscriptionsChanged);
}
Ok(())
}
fn subscribe_paths(&self, kind: &str, globs: Vec<String>) -> Result<(), HostError> {
self.subscribe_paths_with_options(kind, globs, None)
}
fn project_generation(&self, root: &Path) -> Result<u64, HostError> {
self.shared.project_generation(root)
}
fn watch_paths(&self, client: &str, project: &Path, paths: Vec<PathBuf>) -> Result<(), HostError> {
self.shared.external_watches.set(self.id(), client, project, paths)
}
fn unsubscribe(&self, kind: &str) {
if self.shared.subscriptions.lock().unsubscribe(self.id(), kind) {
self.shared.sink.emit(None, PluginEvent::SubscriptionsChanged);
@@ -3489,6 +3757,14 @@ impl PluginWorkspace for HostWorkspace {
Ok(config)
}
fn fork_agent_session(&self, client: &str, agent: &str, session_id: &str, cwd: &Path) -> Result<String, HostError> {
let host = self.0.upgrade().ok_or(HostError::Cancelled)?;
let project = host.project(client).map_err(failed)?;
project.require_trust().map_err(failed)?;
// Scans the recorded transcripts on disk; plugin calls already run off the UI thread.
Ok(project.agents.fork_session(agent, session_id, cwd).map_err(failed)?.id)
}
fn buffer_text_in(&self, client: Option<&str>, path: &Path) -> Option<String> {
client
.and_then(|w| self.0.upgrade()?.project(w).ok()?.documents.text_of(path))
@@ -3850,6 +4126,29 @@ impl PluginWorkspace for HostWorkspace {
mod tests {
use super::*;
#[test]
fn terminal_directories_stay_inside_the_project() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("project");
std::fs::create_dir_all(root.join("sub/deeper")).unwrap();
std::fs::write(root.join("file.txt"), "").unwrap();
let outside = tmp.path().join("outside");
std::fs::create_dir_all(&outside).unwrap();
assert_eq!(project_subdirectory(&root, "").unwrap(), root);
assert_eq!(project_subdirectory(&root, "sub/deeper").unwrap(), root.join("sub/deeper"));
assert_eq!(project_subdirectory(&root, "sub/../sub").unwrap(), root.join("sub"));
for bad in ["/tmp", "../outside", "sub/../../outside", "missing", "file.txt", "a\0b"] {
assert!(matches!(project_subdirectory(&root, bad), Err(HostError::Invalid(_))), "{bad:?}");
}
#[cfg(unix)]
{
std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap();
assert!(project_subdirectory(&root, "escape").is_err(), "a link out of the project");
std::os::unix::fs::symlink(root.join("sub"), root.join("inside")).unwrap();
assert_eq!(project_subdirectory(&root, "inside").unwrap(), root.join("sub"));
}
}
fn api(dir: &Path, pins: Arc<RwLock<HashMap<(String, String), ProgramPin>>>) -> PluginApi {
let manifest = ide_extension::Manifest::parse(
"id = \"acme.lint\"\nname = \"Lint\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.0\"\n",
@@ -3966,6 +4265,67 @@ mod tests {
assert_eq!(std::fs::read_to_string(&outside).unwrap(), "unchanged");
}
/// Plugin secrets go to the credential store; a value an older version left in
/// the owner-only file keeps working until it is set again, and then leaves the file.
#[test]
fn plugin_secrets_go_to_the_credential_store() {
ide_ssh::secrets::testing::use_memory_store();
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
FileSecretStore { dir: dir.clone() }.set("acme.lint", "old", Some("legacy-3f9a")).unwrap();
let secrets = CredentialSecretStore::new(dir.clone());
assert_eq!(secrets.get("acme.lint", "old").as_deref(), Some("legacy-3f9a"));
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
secrets.set("acme.lint", "old", Some("moved-5d2b")).unwrap();
let on_disk = ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e");
assert_eq!(on_disk, Vec::<PathBuf>::new());
assert_eq!(ide_ssh::secrets::testing::files_containing(tmp.path(), "legacy-3f9a"), Vec::<PathBuf>::new());
let again = CredentialSecretStore::new(dir);
assert_eq!(again.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
assert_eq!(again.get("acme.lint", "old").as_deref(), Some("moved-5d2b"));
assert_eq!(again.get("other.plugin", "token"), None);
again.set("acme.lint", "token", None).unwrap();
assert_eq!(again.get("acme.lint", "token"), None);
}
/// Without a credential store a value stays in the owner-only file.
#[test]
fn plugin_secrets_without_a_credential_store_stay_in_the_file() {
struct NoStore;
impl ide_ssh::secrets::Vault for NoStore {
fn available(&self) -> bool {
false
}
fn get(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<String> {
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
}
fn set(&self, _: &str, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
}
fn delete(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
}
}
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("plugins");
let store = ide_ssh::secrets::SecretFile::with_vault(
dir.join("plugin-secrets.json"),
|v| serde_json::from_value(v).ok(),
Arc::new(NoStore),
);
let secrets = CredentialSecretStore::with_store(store, dir.clone());
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
assert_eq!(
ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e"),
[dir.join("acme.lint").join("secrets.json")]
);
assert_eq!(secrets.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
secrets.set("acme.lint", "token", None).unwrap();
assert_eq!(secrets.get("acme.lint", "token"), None);
}
#[cfg(unix)]
#[test]
fn storage_and_secrets_refuse_symlinked_private_directories() {
+50
Переглянути файл
@@ -51,6 +51,53 @@ pub async fn plugin_run_command(
result
}
/// Run Anything entries of the plugin declaring `prefix` for the field's `text` (API 1.18).
#[command(trust = trusted)]
pub async fn plugin_run_anything_suggest(
host: &Host,
plugins: &Arc<PluginHost>,
window: &str,
plugin_id: String,
prefix: String,
text: String,
) -> IdeResult<Vec<ide_plugin::RunAnythingItem>> {
let (plugins, window_id) = (plugins.clone(), window.to_owned());
let root = host.project(window).ok().map(|p| p.root.clone());
host.blocking(move || plugins.run_anything_suggest(&plugin_id, &window_id, root, &prefix, &text)).await
}
/// Runs a Run Anything line starting with the plugin's `prefix` (API 1.18): whether
/// the plugin claimed it.
#[command(trust = trusted)]
pub async fn plugin_run_anything_run(
host: &Host,
plugins: &Arc<PluginHost>,
window: &str,
plugin_id: String,
prefix: String,
line: String,
) -> IdeResult<bool> {
let (plugins, window_id) = (plugins.clone(), window.to_owned());
let root = host.project(window).ok().map(|p| p.root.clone());
host.blocking(move || plugins.run_anything_run(&plugin_id, &window_id, root, &prefix, &line)).await
}
/// Completions for a field of a plugin's own run configuration (API 1.18).
#[command(trust = trusted)]
pub async fn plugin_run_configuration_complete(
host: &Host,
plugins: &Arc<PluginHost>,
window: &str,
config_id: String,
field: String,
text: String,
caret: u32,
) -> IdeResult<Vec<ide_plugin::RunConfigCompletion>> {
let (plugins, window_id) = (plugins.clone(), window.to_owned());
let root = host.project(window)?.root.clone();
host.blocking(move || plugins.run_configuration_complete(&window_id, &root, &config_id, &field, &text, caret)).await
}
/// The UI language (BCP 47) that plugin code reads with `ui.locale()`.
#[command(trust = always)]
pub async fn plugin_set_ui_locale(plugins: &Arc<PluginHost>, tag: String) -> IdeResult<()> {
@@ -316,7 +363,10 @@ ide_command::domain!(
plugin_post_events,
plugin_prepare_debug_run,
plugin_program,
plugin_run_anything_run,
plugin_run_anything_suggest,
plugin_run_command,
plugin_run_configuration_complete,
plugin_select_tests,
plugin_set_active_file,
plugin_set_ui_locale,
+14 -2
Переглянути файл
@@ -17,11 +17,21 @@ pub(super) struct Subscriptions {
#[derive(Clone)]
pub(super) struct PathFilter {
pub globs: Vec<String>,
pub debounce: Option<std::time::Duration>,
matchers: Vec<GlobMatcher>,
}
impl PathFilter {
#[allow(dead_code)]
pub fn new(kind: &str, globs: Vec<String>) -> Result<Self, HostError> {
Self::with_debounce(kind, globs, None)
}
pub fn with_debounce(
kind: &str,
globs: Vec<String>,
debounce: Option<std::time::Duration>,
) -> Result<Self, HostError> {
if !matches!(kind, "file-opened" | "file-saved" | "files-changed" | "document-changed") {
return Err(HostError::Invalid(
"subscribe-paths supports file-opened, file-saved, files-changed and document-changed".into(),
@@ -53,7 +63,7 @@ impl PathFilter {
.compile_matcher(),
);
}
Ok(Self { globs, matchers })
Ok(Self { globs, debounce, matchers })
}
pub fn matches(&self, root: &Path, path: &Path) -> bool {
@@ -78,7 +88,7 @@ impl Subscriptions {
changed = self.kinds.entry(plugin.to_owned()).or_default().insert(kind);
}
let previous = self.paths.entry(plugin.to_owned()).or_default().insert(kind.to_owned(), filter.clone());
previous.is_none_or(|old| old.globs != filter.globs) | changed
previous.is_none_or(|old| old.globs != filter.globs || old.debounce != filter.debounce) | changed
}
pub fn unsubscribe(&mut self, plugin: &str, kind: &str) -> bool {
let removed = self.paths.get_mut(plugin).is_some_and(|filters| filters.remove(kind).is_some());
@@ -120,6 +130,8 @@ impl PluginHost {
.collect::<Vec<_>>()
};
let batch = ide_plugin::FilesChanged {
project: batch.project.clone(),
generation: batch.generation,
created: paths(&batch.created),
modified: paths(&batch.modified),
removed: paths(&batch.removed),
+26 -6
Переглянути файл
@@ -244,12 +244,16 @@ impl PluginHost {
if self.shared.client_closed(client) {
return;
}
self.queues
.lock()
.entry((plugin.into(), Some(client.into())))
.or_insert_with(|| EventQueue { since: Instant::now(), events: Vec::new(), files_source: None })
.events
.push(event);
let now = Instant::now();
let mut queues = self.queues.lock();
let queue = queues.entry((plugin.into(), Some(client.into()))).or_insert_with(|| EventQueue {
since: now,
last_event: now,
events: Vec::new(),
files_source: None,
});
queue.last_event = now;
queue.events.push(event);
}
}
@@ -434,6 +438,9 @@ fn validate_configurations(
if let Some(cwd) = &c.cwd {
ide_plugin::resolve_new_in_root(root, cwd).map_err(HostError::Invalid)?;
}
if c.test && c.output_mode == ide_plugin::PluginOutputMode::Pty {
return Err(HostError::Invalid("test configurations cannot emulate a terminal".into()));
}
validate_env(&c.env)?;
validate_debugger(c.debugger.as_ref())?;
}
@@ -607,6 +614,7 @@ impl PluginHost {
.to_string_lossy()
.into_owned();
config.debug_adapter = owned.debug_adapter;
config.extras.emulate_terminal = false;
Ok(config)
}
}
@@ -801,4 +809,16 @@ mod tests {
assert!(ok(AttachChild { kind: "dotnet".into(), command_contains: Some("Worker.dll".into()) }));
assert!(!ok(AttachChild { kind: "dotnet".into(), command_contains: Some(String::new()) }));
}
#[test]
fn configurations_reject_pty_on_test_configurations() {
let root = std::env::temp_dir();
let mut c = launch(vec![], None);
c.output_mode = ide_plugin::PluginOutputMode::Pty;
assert!(validate_configurations(&root, std::slice::from_ref(&c)).is_ok());
c.test = true;
assert!(validate_configurations(&root, std::slice::from_ref(&c)).is_err());
c.output_mode = ide_plugin::PluginOutputMode::Pipes;
assert!(validate_configurations(&root, &[c]).is_ok());
}
}
+173
Переглянути файл
@@ -0,0 +1,173 @@
//! Paths outside a project that a plugin watches (`events.watch-paths`, API 1.18).
//!
//! A watch set belongs to (plugin, project) and the window that asked for it. Every
//! directory is watched flat (its own entries): a watched file through its parent, a
//! watched directory through itself plus its parent (so its own removal is seen).
//! Watcher threads only queue changes here; [`super::PluginHost::flush_events_at`]
//! delivers them while the set, its window and its project are still current.
use ide_core::{NullSink, ipc_path::to_ipc};
use ide_plugin::{FilesChanged, HostError};
use ide_vfs::{FsBatch, WatchMode, Watcher};
use parking_lot::Mutex;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Default)]
pub(super) struct ExternalWatches {
sets: Mutex<HashMap<(String, PathBuf), WatchSet>>,
pending: Arc<Mutex<Vec<Change>>>,
next: AtomicU64,
}
struct WatchSet {
id: u64,
client: String,
_watchers: Vec<Watcher>,
}
/// Changes seen by one watch set, waiting for delivery.
pub(super) struct Change {
pub plugin: String,
pub client: String,
pub project: PathBuf,
set: u64,
pub batch: FilesChanged,
}
/// What one flat directory watch reports: entries named exactly, or all of them.
#[derive(Default)]
struct Wanted {
exact: BTreeSet<PathBuf>,
entries: bool,
}
impl ExternalWatches {
/// Replaces what `plugin` watches for `project` from window `client`.
pub fn set(&self, plugin: &str, client: &str, project: &Path, paths: Vec<PathBuf>) -> Result<(), HostError> {
let key = (plugin.to_owned(), project.to_path_buf());
if paths.is_empty() {
self.sets.lock().remove(&key);
return Ok(());
}
let id = self.next.fetch_add(1, Ordering::Relaxed) + 1;
let mut dirs: BTreeMap<PathBuf, Wanted> = BTreeMap::new();
for path in &paths {
if let Some(parent) = path.parent() {
dirs.entry(parent.to_path_buf()).or_default().exact.insert(path.clone());
}
if path.is_dir() {
dirs.entry(path.clone()).or_default().entries = true;
}
}
let mut watchers = Vec::with_capacity(dirs.len());
for (dir, wanted) in dirs {
let pending = Arc::downgrade(&self.pending);
let (plugin, client, project) = (plugin.to_owned(), client.to_owned(), project.to_path_buf());
let watched = dir.clone();
let on_change = Box::new(move |batch: &FsBatch| {
let Some(pending) = pending.upgrade() else { return };
let Some(batch) = select(&watched, &wanted, batch) else { return };
// Drained on every event flush; bounded by the flat directories' entries.
pending.lock().push(Change {
plugin: plugin.clone(),
client: client.clone(),
project: project.clone(),
set: id,
batch,
});
});
let watcher = Watcher::start_with(&dir, Vec::new(), Arc::new(NullSink), on_change, WatchMode::Flat)
.map_err(|e| HostError::Failed(format!("cannot watch {}: {}", dir.display(), e.message)))?;
watchers.push(watcher);
}
let set = WatchSet { id, client: client.to_owned(), _watchers: watchers };
self.sets.lock().insert(key, set);
Ok(())
}
/// Changes of sets still in place, oldest first; others are dropped.
pub fn take(&self) -> Vec<Change> {
let changes = std::mem::take(&mut *self.pending.lock());
if changes.is_empty() {
return changes;
}
let sets = self.sets.lock();
changes
.into_iter()
.filter(|c| {
sets.get(&(c.plugin.clone(), c.project.clone())).is_some_and(|s| s.id == c.set && s.client == c.client)
})
.collect()
}
pub fn remove_plugin(&self, plugin: &str) {
self.sets.lock().retain(|(p, _), _| p != plugin);
}
pub fn remove_project(&self, root: &Path) {
self.sets.lock().retain(|(_, project), _| project != root);
}
pub fn remove_client(&self, client: &str) {
self.sets.lock().retain(|_, set| set.client != client);
}
}
/// The part of `batch` (from the flat watch on `dir`) the set asked for. Ignored
/// files are reported too: as modified while they exist, removed once they don't.
fn select(dir: &Path, wanted: &Wanted, batch: &FsBatch) -> Option<FilesChanged> {
let keep = |path: &&PathBuf| wanted.exact.contains(*path) || (wanted.entries && path.parent() == Some(dir));
let ipc = |paths: Vec<&PathBuf>| paths.into_iter().map(|p| to_ipc(p)).collect::<Vec<_>>();
let mut modified: Vec<&PathBuf> = batch.modified.iter().filter(keep).collect();
let mut removed: Vec<&PathBuf> = batch.removed.iter().filter(keep).collect();
for path in batch.ignored.iter().filter(keep) {
if path.symlink_metadata().is_ok() { modified.push(path) } else { removed.push(path) }
}
let changes = FilesChanged {
project: None,
generation: None,
created: ipc(batch.created.iter().filter(keep).collect()),
modified: ipc(modified),
removed: ipc(removed),
};
(!changes.created.is_empty() || !changes.modified.is_empty() || !changes.removed.is_empty()).then_some(changes)
}
#[cfg(test)]
mod tests {
use super::*;
fn batch(created: &[&Path], modified: &[&Path], removed: &[&Path], ignored: &[&Path]) -> FsBatch {
let v = |p: &[&Path]| p.iter().map(|p| p.to_path_buf()).collect();
FsBatch {
created: v(created),
modified: v(modified),
removed: v(removed),
ignored: v(ignored),
..Default::default()
}
}
#[test]
fn a_flat_watch_reports_only_what_the_set_names() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let (file, other, kept) = (dir.join("Taskfile.yml"), dir.join("other.yml"), dir.join("kept.yml"));
std::fs::write(&kept, "").unwrap();
let exact = Wanted { exact: [file.clone()].into(), entries: false };
let got = select(dir, &exact, &batch(&[&file], &[&other], &[], &[&kept])).unwrap();
assert_eq!(got.created, vec![to_ipc(&file)]);
assert!(got.modified.is_empty() && got.removed.is_empty());
assert!(select(dir, &exact, &batch(&[], &[&other], &[], &[])).is_none());
let nested = dir.join("sub").join("deep.yml");
let entries = Wanted { exact: BTreeSet::new(), entries: true };
let gone = dir.join("gone.yml");
let got = select(dir, &entries, &batch(&[&nested], &[&other], &[], &[&kept, &gone])).unwrap();
assert!(got.created.is_empty(), "entries below the directory are not watched");
assert_eq!(got.modified, vec![to_ipc(&other), to_ipc(&kept)]);
assert_eq!(got.removed, vec![to_ipc(&gone)]);
}
}
+267 -12
Переглянути файл
@@ -28,11 +28,21 @@ pub(super) fn retain_live(events: &mut Vec<WorkbenchEvent>, source: Option<&Sour
}
}
/// Queues `incoming`, folding a filesystem batch into the queued one it continues:
/// the project batch, or the watched-paths batch of the same project.
pub(super) fn append(events: &mut Vec<WorkbenchEvent>, incoming: Vec<WorkbenchEvent>) {
for event in incoming {
if let WorkbenchEvent::FilesChanged(batch) = &event
&& let Some(WorkbenchEvent::FilesChanged(previous)) =
events.iter_mut().find(|e| matches!(e, WorkbenchEvent::FilesChanged(_)))
let previous = events.iter_mut().find_map(|queued| match (queued, &event) {
(WorkbenchEvent::FilesChanged(previous), WorkbenchEvent::FilesChanged(_)) => Some(previous),
(WorkbenchEvent::WatchedFilesChanged(previous), WorkbenchEvent::WatchedFilesChanged(batch))
if previous.project == batch.project =>
{
Some(previous)
}
_ => None,
});
if let (WorkbenchEvent::FilesChanged(batch) | WorkbenchEvent::WatchedFilesChanged(batch), Some(previous)) =
(&event, previous)
{
use std::collections::BTreeMap;
#[derive(Clone, Copy)]
@@ -61,7 +71,9 @@ pub(super) fn append(events: &mut Vec<WorkbenchEvent>, incoming: Vec<WorkbenchEv
paths.insert(path.clone(), kind);
}
}
*previous = FilesChanged::default();
let project = batch.project.clone().or_else(|| previous.project.clone());
let generation = batch.generation.or(previous.generation);
*previous = FilesChanged { project, generation, ..Default::default() };
for (path, kind) in paths {
match kind {
Created => previous.created.push(path),
@@ -88,14 +100,15 @@ impl PluginHost {
}
let paths =
|paths: &[PathBuf]| paths.iter().filter(|p| p.starts_with(root)).map(|p| to_ipc(p)).collect::<Vec<_>>();
let batch = FilesChanged {
created: paths(&batch.created),
modified: paths(&batch.modified),
removed: paths(&batch.removed),
};
if batch.created.is_empty() && batch.modified.is_empty() && batch.removed.is_empty() {
let created = paths(&batch.created);
let modified = paths(&batch.modified);
let removed = paths(&batch.removed);
if created.is_empty() && modified.is_empty() && removed.is_empty() {
return;
}
let generation = self.shared.bump_project_generation(root);
let batch =
FilesChanged { project: Some(to_ipc(root)), generation: Some(generation), created, modified, removed };
self.post_events_from(
Some(client),
vec![WorkbenchEvent::FilesChanged(batch)],
@@ -189,7 +202,15 @@ mod tests {
let queues = host.queues.lock();
let queue = queues.values().next().expect("new session queue");
assert!(queue.files_source.as_ref().unwrap().same(&Source { active: Arc::downgrade(&new) }));
assert_eq!(queue.events, [delta(0, &to_ipc(&root.join("new.rs")))]);
assert_eq!(
queue.events,
[WorkbenchEvent::FilesChanged(FilesChanged {
project: Some(to_ipc(&root)),
generation: Some(2),
created: vec![to_ipc(&root.join("new.rs"))],
..Default::default()
})]
);
}
#[test]
@@ -291,6 +312,7 @@ mod tests {
created: vec![to_ipc(&root.join("config/a.yaml")), to_ipc(&root.join("src/a.rs"))],
modified: vec![to_ipc(&root.join("config/b.yaml"))],
removed: vec![to_ipc(&root.join("config/c.yaml"))],
..Default::default()
})],
);
host.flush_events();
@@ -306,6 +328,7 @@ mod tests {
created: vec![to_ipc(&root.join("config/a.yaml"))],
modified: vec![to_ipc(&root.join("config/b.yaml"))],
removed: vec![to_ipc(&root.join("config/c.yaml"))],
..Default::default()
}]
);
} else {
@@ -437,6 +460,7 @@ mod tests {
PendingFiles {
queue: super::super::EventQueue {
since: std::time::Instant::now(),
last_event: std::time::Instant::now(),
events: vec![delta(0, "/project/new")],
files_source: None,
},
@@ -475,6 +499,7 @@ mod tests {
created: vec![format!("/project/{i}")],
modified: vec!["/project/shared".into()],
removed: vec!["/project/gone".into()],
..Default::default()
})],
);
}
@@ -616,7 +641,15 @@ mod tests {
};
let data = host.run_command("files-events", "events", None, inv).unwrap().unwrap();
let received: Vec<FilesChanged> = serde_json::from_str(&data).unwrap();
assert_eq!(received, [FilesChanged { created: vec![to_ipc(&root.join("new.rs"))], ..Default::default() }]);
assert_eq!(
received,
[FilesChanged {
project: Some(to_ipc(&root)),
generation: Some(3),
created: vec![to_ipc(&root.join("new.rs"))],
..Default::default()
}]
);
}
#[test]
fn queued_filter_replacement_and_pause_do_not_activate() {
@@ -656,4 +689,226 @@ mod tests {
host.post_files_changed("main", &root, &active, &batch);
assert!(host.queues.lock().is_empty(), "paused paths never queue work");
}
#[test]
fn files_changed_debounce_coalesces_bursts_of_edits_without_repeated_delivery() {
use super::super::event_paths::PathFilter;
use std::time::Duration;
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let host = files_changed_host(&root);
host.shared.subscriptions.lock().set_paths(
"files-events",
"files-changed",
PathFilter::with_debounce("files-changed", vec!["**/*".into()], Some(Duration::from_millis(80))).unwrap(),
);
let active = Arc::new(AtomicBool::new(true));
// Post 3 bursts of file changes quickly within debounce window
host.post_files_changed(
"main",
&root,
&active,
&ide_vfs::FsBatch { created: vec![root.join("file1.rs")], ..Default::default() },
);
host.flush_events();
assert_eq!(host.instances(), 0, "first change must be debounced, not delivered immediately");
std::thread::sleep(Duration::from_millis(20));
host.post_files_changed(
"main",
&root,
&active,
&ide_vfs::FsBatch { modified: vec![root.join("file2.rs")], ..Default::default() },
);
host.flush_events();
assert_eq!(host.instances(), 0, "second change within debounce window resets debounce");
std::thread::sleep(Duration::from_millis(20));
host.post_files_changed(
"main",
&root,
&active,
&ide_vfs::FsBatch { removed: vec![root.join("file3.rs")], ..Default::default() },
);
host.flush_events();
assert_eq!(host.instances(), 0, "third change still debouncing");
// Wait until debounce expires (> 80 ms since last event)
std::thread::sleep(Duration::from_millis(100));
host.flush_events();
assert!(host.wait_events(Duration::from_secs(5)));
let inv = ide_plugin::Invocation {
client: Some("main".into()),
workspace_root: Some(root.clone()),
..Default::default()
};
let data = host.run_command("files-events", "events", None, inv).unwrap().unwrap();
let batches: Vec<FilesChanged> = serde_json::from_str(&data).unwrap();
assert_eq!(batches.len(), 1, "rapid edit bursts must coalesce into exactly 1 batch");
assert_eq!(batches[0].created, [to_ipc(&root.join("file1.rs"))]);
assert_eq!(batches[0].modified, [to_ipc(&root.join("file2.rs"))]);
assert_eq!(batches[0].removed, [to_ipc(&root.join("file3.rs"))]);
assert_eq!(host.shared.project_generation(&root).unwrap(), 4);
}
struct MultiWorkspace(std::sync::Mutex<Vec<PathBuf>>);
impl super::super::PluginWorkspace for MultiWorkspace {
fn projects(&self) -> Vec<PathBuf> {
self.0.lock().unwrap().clone()
}
fn buffer_text(&self, _: &Path) -> Option<String> {
None
}
fn document(&self, _: &Path) -> Option<(u64, String)> {
None
}
fn apply_edits(
&self,
_: &Path,
_: u64,
_: &[ide_core::TextEdit],
_: bool,
) -> Result<u64, ide_plugin::HostError> {
unreachable!()
}
fn trusted(&self, _: &Path) -> bool {
true
}
fn project_of(&self, window: &str) -> Option<PathBuf> {
let projects = self.0.lock().unwrap();
match window {
"main" => projects.first().cloned(),
"other" => projects.get(1).cloned(),
_ => None,
}
}
fn publish_diagnostics(
&self,
_: &str,
_: &Path,
_: Vec<ide_core::Diagnostic>,
) -> Result<(), ide_plugin::HostError> {
Ok(())
}
}
#[test]
fn stale_run_target_registration_rejected_after_generation_bump() {
use ide_plugin::HostError;
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let host = files_changed_host(&root);
let dummy = root.join("dummy");
std::fs::write(&dummy, b"dummy").unwrap();
host.shared.pins.write().insert(
("files-events".into(), "process:dummy".into()),
ide_language::ProgramPin::approve(&dummy).unwrap(),
);
let plugin = host.get("files-events").unwrap();
let api = super::super::api::PluginApi { pkg: plugin.pkg.clone(), shared: host.shared.clone() };
let target = ide_plugin::PluginRunTarget {
id: "target-1".into(),
name: "Target 1".into(),
program: "dummy".into(),
args: vec!["test".into()],
workdir_args: vec![],
container_root: None,
commands: vec![],
};
// Generation starts at 1
let gen1 = host.shared.project_generation(&root).unwrap();
assert_eq!(gen1, 1);
// Registering with matching generation succeeds
assert!(api.register_target(&root, target.clone(), Some(gen1)).is_ok());
// Bump generation (simulating filesystem change or manual bump)
let gen2 = host.shared.bump_project_generation(&root);
assert_eq!(gen2, 2);
// Registering with old generation is rejected with Stale
let err = api.register_target(&root, target.clone(), Some(gen1)).unwrap_err();
assert!(matches!(err, HostError::Stale));
// Registering with new generation succeeds
assert!(api.register_target(&root, target, Some(gen2)).is_ok());
}
#[test]
fn project_isolation_and_project_closed_lifecycle() {
let tmp = tempfile::tempdir().unwrap();
let root_a = dunce::canonicalize(tmp.path()).unwrap().join("project_a");
let root_b = dunce::canonicalize(tmp.path()).unwrap().join("project_b");
std::fs::create_dir_all(&root_a).unwrap();
std::fs::create_dir_all(&root_b).unwrap();
let host = files_changed_host(&root_a);
let ws = Arc::new(MultiWorkspace(std::sync::Mutex::new(vec![root_a.clone(), root_b.clone()])));
host.set_workspace(Some(ws.clone()));
let dummy = tmp.path().join("dummy");
std::fs::write(&dummy, b"dummy").unwrap();
host.shared.pins.write().insert(
("files-events".into(), "process:dummy".into()),
ide_language::ProgramPin::approve(&dummy).unwrap(),
);
let plugin = host.get("files-events").unwrap();
let api = super::super::api::PluginApi { pkg: plugin.pkg.clone(), shared: host.shared.clone() };
let active_a = Arc::new(AtomicBool::new(true));
let active_b = Arc::new(AtomicBool::new(true));
// Post changes to Project A and B
host.post_files_changed(
"main",
&root_a,
&active_a,
&ide_vfs::FsBatch { created: vec![root_a.join("a.rs")], ..Default::default() },
);
host.post_files_changed(
"other",
&root_b,
&active_b,
&ide_vfs::FsBatch { created: vec![root_b.join("b.rs")], ..Default::default() },
);
assert_eq!(host.shared.project_generation(&root_a).unwrap(), 2);
assert_eq!(host.shared.project_generation(&root_b).unwrap(), 2);
// Bumping project A does not bump project B
let bump_a = host.shared.bump_project_generation(&root_a);
assert_eq!(bump_a, 3);
assert_eq!(host.shared.project_generation(&root_b).unwrap(), 2);
// Register target for project A and B
let target = ide_plugin::PluginRunTarget {
id: "run".into(),
name: "Run".into(),
program: "dummy".into(),
args: vec![],
workdir_args: vec![],
container_root: None,
commands: vec![],
};
assert!(api.register_target(&root_a, target.clone(), None).is_ok());
assert!(api.register_target(&root_b, target.clone(), None).is_ok());
assert_eq!(host.run_targets(&root_a).len(), 1);
assert_eq!(host.run_targets(&root_b).len(), 1);
// Close project A
ws.0.lock().unwrap().retain(|p| p != &root_a);
host.project_closed(&root_a, "main");
// Project A targets withdrawn, Project B untouched
assert!(host.run_targets(&root_a).is_empty());
assert_eq!(host.run_targets(&root_b).len(), 1);
// Project A generation closed (NotFound on lookup), Project B intact
assert!(host.shared.project_generation(&root_a).is_err());
assert_eq!(host.shared.project_generation(&root_b).unwrap(), 2);
}
}
+58 -2
Переглянути файл
@@ -8,8 +8,13 @@
//! args = "optional-arguments" # optional
//! vmOptions = ["-XX:+AllowEnhancedClassRedefinition"] # optional, API 1.14
//! jdk = "jetbrains" # optional: only those VM options on JBR
//! executor = "Hot Reload" # optional, API 1.18: see below
//! ```
//!
//! With `executor`, the agent is not added to every launch: the plugin contributes an
//! executor beside Run and Debug ("Run with Hot Reload", "Debug with Hot Reload"), and only
//! launches through it get the agent and its `vmOptions`.
//!
//! One agent per plugin. The declaration derives the optional high-risk `java.agent`
//! capability; granting it records the jar's hash, and a launch adds the agent only
//! while the jar still has it ([`ide_run::java_agent`]).
@@ -28,6 +33,7 @@ pub const POINT_ID: &str = "javaAgents";
const MAX_ARGS: usize = 4096;
const MAX_VM_OPTION: usize = 512;
const MAX_VM_OPTIONS: usize = 32;
const MAX_EXECUTOR: usize = 40;
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -39,6 +45,8 @@ struct Decl {
vm_options: Vec<String>,
#[serde(default)]
jdk: Option<String>,
#[serde(default)]
executor: Option<String>,
}
#[derive(Clone, Debug)]
@@ -48,6 +56,8 @@ pub(super) struct Agent {
pub(super) args: Option<String>,
pub(super) vm_options: Vec<String>,
pub(super) jdk: Option<String>,
/// The executor title: only launches through it get the agent.
pub(super) executor: Option<String>,
}
/// Agents of enabled plugins.
@@ -111,9 +121,16 @@ impl ExtensionPoint for JavaAgentsPoint {
if !vm_options.is_empty() || jdk.is_some() {
pkg.manifest.needs_api("contributes.javaAgents.vmOptions", 14)?;
}
let label = label(&d.path, args.as_deref(), &vm_options);
let executor = validate_executor(d.executor)?;
if executor.is_some() {
pkg.manifest.needs_api("contributes.javaAgents.executor", 18)?;
}
let mut label = label(&d.path, args.as_deref(), &vm_options);
if let Some(title) = &executor {
label = format!("{label} (Run with {title})");
}
let (store, plugin) = (self.store.clone(), pkg.id().to_owned());
let agent = Agent { jar, args, vm_options, jdk };
let agent = Agent { jar, args, vm_options, jdk, executor };
Ok(Prepared::new(label, move || Ok(store.add(plugin, agent))).file(d.path).capability(Capability::JavaAgent))
}
}
@@ -153,6 +170,17 @@ fn validate_jdk(jdk: Option<String>) -> Result<Option<String>, String> {
Ok(Some(raw))
}
/// The executor's title: one line, short enough for "Debug '<configuration>' with <title>".
fn validate_executor(executor: Option<String>) -> Result<Option<String>, String> {
let Some(title) = executor.map(|s| s.trim().to_owned()) else { return Ok(None) };
if title.is_empty() || title.chars().count() > MAX_EXECUTOR || title.contains(|c: char| c.is_control()) {
return Err(format!(
"contributes.javaAgents: `executor` must be a title of 1–{MAX_EXECUTOR} characters on one line"
));
}
Ok(Some(title))
}
/// What Settings › Plugins shows: jar name, args, and any JVM options.
fn label(path: &Path, args: Option<&str>, vm_options: &[String]) -> String {
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
@@ -224,6 +252,7 @@ impl JavaAgentSource for PluginJavaAgents {
vm_options: agent.vm_options.clone(),
jdk: agent.jdk.clone(),
approved_hash: pins.get(&(plugin.clone(), cap.clone())).map(|pin| pin.hash.clone()),
executor: agent.executor.clone(),
})
.collect()
}
@@ -306,6 +335,33 @@ mod tests {
assert_eq!(agent.jdk.as_deref(), Some("jetbrains"));
}
#[test]
fn parses_an_executor_from_api_18() {
let tmp = tempfile::tempdir().unwrap();
let manifest = MANIFEST.replace("^1.10", "^1.18");
let decl = "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \" Hot Reload \"\n";
let pkg = package(&tmp.path().join("ok"), &format!("{manifest}{decl}"));
assert_eq!(prepare(&pkg).unwrap().label, "spring agent.jar (Run with Hot Reload)");
let store: Arc<JavaAgents> = Arc::default();
let point = JavaAgentsPoint::new(store.clone());
let _keep = (point.prepare(&pkg, pkg.manifest.declarations(POINT_ID).remove(0)).unwrap().commit)().unwrap();
assert_eq!(store.for_plugin("acme.spring").unwrap().executor.as_deref(), Some("Hot Reload"));
let source = PluginJavaAgents { store, pins: Arc::default() };
assert_eq!(source.agents()[0].executor.as_deref(), Some("Hot Reload"));
let old = package(&tmp.path().join("old"), &format!("{MANIFEST_14}{decl}"));
assert!(prepare(&old).map(|_| ()).unwrap_err().contains("new in plugin API 1.18"));
let long = format!(
"[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \"{}\"\n",
"x".repeat(41)
);
let long = package(&tmp.path().join("long"), &format!("{manifest}{long}"));
assert!(prepare(&long).map(|_| ()).unwrap_err().contains("`executor`"));
let empty = "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \" \"\n";
let empty = package(&tmp.path().join("empty"), &format!("{manifest}{empty}"));
assert!(prepare(&empty).map(|_| ()).unwrap_err().contains("`executor`"));
}
#[test]
fn refuses_what_would_fail_at_launch() {
let tmp = tempfile::tempdir().unwrap();
+19 -7
Переглянути файл
@@ -2,7 +2,7 @@
use super::{PluginHost, ProviderKind};
use ide_core::{IdeResult, Pos, Range};
use ide_plugin::{ProviderDocument, language_features::*};
use std::sync::Arc;
use std::{path::Path, sync::Arc};
pub(crate) fn valid_range(doc: &ProviderDocument, range: Range) -> bool {
valid_range_in(&ide_text::Document::new(&doc.text), range)
@@ -279,14 +279,18 @@ impl PluginHost {
/// Optional API 1.14 hover actions. Only plugins declaring the
/// `hover-actions` provider kind are asked; the released language-features
/// export remains unchanged.
pub fn language_hover_actions(&self, doc: &ProviderDocument) -> Vec<(String, HoverAction)> {
/// `project`: the root of the project whose editor shows `doc`, the providers' invocation project.
pub fn language_hover_actions(&self, doc: &ProviderDocument, project: Option<&Path>) -> Vec<(String, HoverAction)> {
let project = project.map(Path::to_path_buf);
let mut out = Vec::new();
for (d, _bounds) in self.feature_documents(doc, None) {
let snapshot = d.clone();
let text = ide_text::Document::new(&snapshot.text);
let d = Arc::new(d);
let results = self
.document_calls(ProviderKind::HoverActions, &snapshot, move |rt, t| rt.language_hover_actions(&d, t));
let project = project.clone();
let results = self.document_calls(ProviderKind::HoverActions, &snapshot, move |rt, t| {
rt.language_hover_actions(&d, project.as_deref(), t)
});
for (p, items) in results {
let commands: std::collections::HashSet<_> =
self.ui.items(super::COMMANDS, Some(p.id())).into_iter().map(|c| c.key).collect();
@@ -304,14 +308,22 @@ impl PluginHost {
out
}
pub fn language_gutter_actions(&self, doc: &ProviderDocument) -> Vec<(String, GutterAction)> {
/// `project`: the root of the project whose editor shows `doc`, the providers' invocation project.
pub fn language_gutter_actions(
&self,
doc: &ProviderDocument,
project: Option<&Path>,
) -> Vec<(String, GutterAction)> {
let project = project.map(Path::to_path_buf);
let mut out = Vec::new();
for (d, bounds) in self.feature_documents(doc, None) {
let lines = d.text.split('\n').count() as u32;
let snapshot = d.clone();
let d = Arc::new(d);
let results = self
.document_calls(ProviderKind::GutterActions, &snapshot, move |rt, t| rt.language_gutter_actions(&d, t));
let project = project.clone();
let results = self.document_calls(ProviderKind::GutterActions, &snapshot, move |rt, t| {
rt.language_gutter_actions(&d, project.as_deref(), t)
});
for (p, items) in results {
let commands: std::collections::HashSet<_> =
self.ui.items(super::COMMANDS, Some(p.id())).into_iter().map(|c| c.key).collect();
+12 -3
Переглянути файл
@@ -700,7 +700,10 @@ mod tests {
// tampered package — and the official host must still be asked.
let candidates = mirror::candidates(
"https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin",
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
&ide_core::settings::ToolDownloadSettings {
github_mirror: "https://gh-proxy.com/".into(),
..Default::default()
},
);
let asked: std::cell::RefCell<Vec<usize>> = std::cell::RefCell::new(Vec::new());
let picked = try_sources(&candidates, |index, candidate| {
@@ -731,7 +734,10 @@ mod tests {
let url = "https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin";
let through = mirror::candidates(
url,
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
&ide_core::settings::ToolDownloadSettings {
github_mirror: "https://gh-proxy.com/".into(),
..Default::default()
},
);
assert_eq!(through.len(), 2);
assert_eq!(through[0].url, format!("https://gh-proxy.com/{url}"));
@@ -741,7 +747,10 @@ mod tests {
// A local index's own package is not on GitHub: no prefix may carry it.
let local = mirror::candidates(
"/srv/market/a.oiplugin",
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
&ide_core::settings::ToolDownloadSettings {
github_mirror: "https://gh-proxy.com/".into(),
..Default::default()
},
);
assert_eq!(local.len(), 1);
assert_eq!(local[0].url, "/srv/market/a.oiplugin");
+442 -26
Переглянути файл
@@ -27,6 +27,7 @@ pub(crate) mod diagnostics;
pub mod endpoints;
mod event_paths;
mod execution;
mod external_watch;
mod files_changed;
mod hover;
mod icon_extensions;
@@ -62,7 +63,7 @@ pub mod views;
pub mod web;
mod websocket;
pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
pub use build_graph::{BuildGraph, GradleModule};
pub(crate) use hover::merge as merge_hover;
pub use icons::{
@@ -211,6 +212,7 @@ const LATENCY_WINDOW: usize = 128;
/// Events waiting for one plugin (from one window).
struct EventQueue {
since: Instant,
last_event: Instant,
events: Vec<WorkbenchEvent>,
files_source: Option<files_changed::Source>,
}
@@ -220,6 +222,8 @@ const MAX_QUEUED_EVENTS: usize = 500;
/// How long events for a plugin that is not running are collected before it
/// is activated to receive them.
const IDLE_BATCH: Duration = Duration::from_secs(2);
/// Maximum delay for debounced events before forcing delivery.
const MAX_DEBOUNCE_WAIT: Duration = Duration::from_secs(5);
struct LoadedPlugin {
pkg: Package,
@@ -1170,6 +1174,92 @@ impl PluginHost {
self.info_of(id)
}
/// Approves the host the plugin's `net:setting:<key>` grant derives from
/// the setting's value right now: the dialog when the user applies the
/// value in Settings, or the pending row's Approve action. `expected` is
/// the host the user was shown: when the setting changed since (the plugin
/// can write its own settings), nothing is approved. On a remote host the
/// approval is kept for the session only, like `net:ask` (#3809).
pub fn approve_net_setting(&self, id: &str, setting: &str, http: bool, expected: &str) -> IdeResult<PluginInfo> {
let _guard = self.lifecycle.lock();
let plugin = self.get(id)?;
self.check_not_uninstalling(&plugin)?;
let cap = Capability::NetSetting { http, key: setting.to_owned() };
if !plugin.manifest().declares(&cap) {
return Err(IdeError::invalid(format!("plugin {id:?} does not declare {cap}")));
}
let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() };
let value = api
.setting_value(setting)
.ok_or_else(|| IdeError::invalid(format!("setting {setting:?} holds no value")))?;
let host = api::setting_host(&value)
.map_err(IdeError::invalid)?
.ok_or_else(|| IdeError::invalid(format!("setting {setting:?} holds no host")))?;
if host != expected {
return Err(IdeError::invalid(format!(
"setting {setting:?} now holds {host}, not {expected}: approve the new value instead"
)));
}
let session_only = self.shared.net_hosts_session_only.load(std::sync::atomic::Ordering::Relaxed);
if !session_only {
let mut ledger = self.ledger.lock();
if !ledger.remember_setting_host(&plugin.subject(), &cap, &host) {
return Err(IdeError::invalid(format!("plugin {id:?} does not have {cap} granted")));
}
self.save_ledger(&ledger);
}
self.stop(&plugin);
if session_only {
self.shared.session_setting_hosts.lock().entry(id.to_owned()).or_default().insert(cap.to_string(), host);
}
if !self.state.lock().disabled.contains(id) {
self.start(&plugin);
}
// Plugins that need this one follow it: running again, or blocked while it can't run.
self.settle_dependents(id);
self.changed();
self.info_of(id)
}
/// The host a `net:setting:<key>` grant derives from `value` (a bare host
/// or a URL), for the approval dialog; an error refuses the value.
pub fn net_setting_host(&self, id: &str, setting: &str, value: &str) -> IdeResult<String> {
let plugin = self.get(id)?;
let cap = Capability::NetSetting { http: false, key: setting.to_owned() };
if !plugin.manifest().declares(&cap)
&& !plugin.manifest().declares(&Capability::NetSetting { http: true, key: setting.to_owned() })
{
return Err(IdeError::invalid(format!("plugin {id:?} does not declare a setting grant for {setting:?}")));
}
api::setting_host(value)
.map_err(IdeError::invalid)?
.ok_or_else(|| IdeError::invalid(format!("{value:?} holds no host")))
}
/// Drops the approved host of a `net:setting:<key>` grant (its revoke
/// action, or the setting's value being cleared). Nothing recorded: still
/// fine, the state is already as asked.
pub fn forget_net_setting(&self, id: &str, setting: &str, http: bool) -> IdeResult<PluginInfo> {
let _guard = self.lifecycle.lock();
let plugin = self.get(id)?;
self.check_not_uninstalling(&plugin)?;
let cap = Capability::NetSetting { http, key: setting.to_owned() };
{
let mut ledger = self.ledger.lock();
ledger.forget_setting_host(&plugin.subject(), &cap);
self.save_ledger(&ledger);
}
self.shared.session_setting_hosts.lock().get_mut(id).map(|hosts| hosts.remove(&cap.to_string()));
self.stop(&plugin);
if !self.state.lock().disabled.contains(id) {
self.start(&plugin);
}
// Plugins that need this one follow it: running again, or blocked while it can't run.
self.settle_dependents(id);
self.changed();
self.info_of(id)
}
/// Grants or revokes one declared capability (Settings › Plugins › Permissions).
/// Revoking a required one stops the plugin until consent is given again.
pub fn set_capability(&self, id: &str, capability: &str, granted: bool) -> IdeResult<PluginInfo> {
@@ -1187,6 +1277,10 @@ impl PluginHost {
return Err(IdeError::invalid(format!("plugin {id:?} has not been confirmed yet")));
}
ledger.set(&subject, &cap, granted);
if !granted {
// A session-only approval of a setting-derived host goes with its grant.
self.shared.session_setting_hosts.lock().get_mut(id).map(|hosts| hosts.remove(&cap.to_string()));
}
if granted
&& cap == Capability::JavaAgent
&& let Some(jar) = agent_jar_grant(plugin.manifest(), plugin.dir())
@@ -1433,6 +1527,110 @@ impl PluginHost {
})
}
/// Run Anything entries (API 1.18) of the plugin that declares `prefix`, for the
/// field's `text` in `window`'s project: from what it already knows, within 300 ms.
pub fn run_anything_suggest(
&self,
id: &str,
window: &str,
root: Option<PathBuf>,
prefix: &str,
text: &str,
) -> IdeResult<Vec<ide_plugin::RunAnythingItem>> {
self.declared_run_anything(id, prefix)?;
if text.len() > 4096 || !(prefix.starts_with(text) || text.starts_with(prefix)) {
return Err(IdeError::invalid("the text doesn't start with the plugin's prefix"));
}
let invocation = Invocation { client: Some(window.to_owned()), workspace_root: root, ..Default::default() };
let (prefix, text) = (prefix.to_owned(), text.to_owned());
let budget = Duration::from_millis(300);
self.code_call_with_budget(
id,
invocation,
"suggesting Run Anything entries",
None,
Some(budget),
move |rt, inv| rt.run_anything_suggest(&prefix, &text, inv, budget),
)
}
/// Runs a Run Anything line whose first word is `prefix` (API 1.18): whether the
/// plugin claimed it. A failed call is an error, which the caller treats as claimed.
pub fn run_anything_run(
&self,
id: &str,
window: &str,
root: Option<PathBuf>,
prefix: &str,
line: &str,
) -> IdeResult<bool> {
self.declared_run_anything(id, prefix)?;
if line.len() > 4096 || line.split_whitespace().next() != Some(prefix) {
return Err(IdeError::invalid("the line doesn't start with the plugin's prefix"));
}
let invocation = Invocation { client: Some(window.to_owned()), workspace_root: root, ..Default::default() };
let (prefix, line) = (prefix.to_owned(), line.to_owned());
let timeout = self.limits.timeout;
self.code_call(id, invocation, "running a Run Anything line", move |rt, inv| {
rt.run_anything_run(&prefix, &line, inv, timeout)
})
}
/// Completions (API 1.18) for `field` of the plugin run configuration `config_id`
/// (`plugin:<plugin>:<id>`, also a user's override of one), as `window`'s project
/// currently has it, for the field's `text` and UTF-16 `caret`: from what the owning
/// plugin already knows, within 300 ms.
pub fn run_configuration_complete(
&self,
window: &str,
root: &Path,
config_id: &str,
field: &str,
text: &str,
caret: u32,
) -> IdeResult<Vec<ide_plugin::RunConfigCompletion>> {
if text.len() > 16 * 1024 || caret as usize > text.encode_utf16().count() || field.len() > 64 {
return Err(IdeError::invalid("the field text or caret is out of range"));
}
if !self.run_detection().detect(root).iter().any(|c| c.id == config_id && c.kind == "plugin") {
return Err(IdeError::not_found("this plugin configuration is no longer provided"));
}
let owner = self
.plugins
.read()
.keys()
.filter(|id| {
config_id.strip_prefix(ide_run::EXTERNAL_PREFIX).is_some_and(|rest| rest.starts_with(&format!("{id}:")))
})
.max_by_key(|id| id.len())
.cloned()
.ok_or_else(|| IdeError::not_found("the plugin owning this configuration is not loaded"))?;
let own = config_id[ide_run::EXTERNAL_PREFIX.len() + owner.len() + 1..].to_owned();
let invocation = Invocation {
client: Some(window.to_owned()),
workspace_root: Some(root.to_path_buf()),
..Default::default()
};
let (field, text) = (field.to_owned(), text.to_owned());
let budget = Duration::from_millis(300);
self.code_call_with_budget(
&owner,
invocation,
"completing a run configuration field",
None,
Some(budget),
move |rt, inv| rt.run_configuration_complete(&own, &field, &text, caret, inv, budget),
)
}
fn declared_run_anything(&self, id: &str, prefix: &str) -> IdeResult<()> {
if self.ui.items(ui_points::RUN_ANYTHING, Some(id)).iter().any(|d| d.key == prefix) {
Ok(())
} else {
Err(IdeError::invalid(format!("plugin {id:?} declares no Run Anything prefix {prefix:?}")))
}
}
/// Content of a declared view, or of a custom editor (`invocation.editor`
/// is its document). Activates the plugin (`on-view`).
pub fn render_view(
@@ -1751,6 +1949,12 @@ impl PluginHost {
*self.shared.secrets.write() = store;
}
/// Keeps plugin secrets in the OS credential store, with the owner-only
/// files under the plugins directory as the fallback.
pub fn use_credential_store(&self) {
self.set_secret_store(Arc::new(CredentialSecretStore::new(self.shared.data_dir.clone())));
}
/// Stores (or, with `None`, deletes) a secret the plugin declares under
/// `[[contributes.secrets]]`.
pub fn set_secret(&self, id: &str, name: &str, value: Option<&str>) -> IdeResult<()> {
@@ -1805,10 +2009,57 @@ impl PluginHost {
/// events, and ignores context writes of commands still running for it.
pub fn forget_client(&self, label: &str) {
self.queues.lock().retain(|(_, client), _| client.as_deref() != Some(label));
self.shared.external_watches.remove_client(label);
self.shared.forget_client(label);
self.forget_web_ptys(label);
}
/// A project closed (or the last window for it detached). Closes the project
/// generation, drops queued events for that window and project, withdraws run
/// targets and run configurations, and delivers
/// `project-closed` to subscribed plugins.
pub fn project_closed(&self, root: &Path, window: &str) {
self.shared.close_project_generation(root);
self.shared.external_watches.remove_project(root);
self.withdraw_project_run_targets(root);
self.shared.run_configurations.write().retain(|(_, r), _| r != root);
let root_ipc = ide_core::ipc_path::to_ipc(root);
{
let mut queues = self.queues.lock();
queues.retain(|(_, client), q| {
if client.as_deref() == Some(window) {
return false;
}
q.events.retain(|e| {
if let WorkbenchEvent::FilesChanged(f) | WorkbenchEvent::WatchedFilesChanged(f) = e
&& f.project.as_deref() == Some(&root_ipc)
{
return false;
}
true
});
!q.events.is_empty()
});
}
let plugins = self.plugins.read();
for p in plugins.values() {
{
let mut batches = p.batches.lock();
batches.files_pending.retain(|(client, ws_root), _| {
client.as_deref() != Some(window) && ws_root.as_deref() != Some(root)
});
}
}
drop(plugins);
// In-flight work is not cancelled: an instance serves every project, and its
// results for this one are refused now that the project's generation moved on.
self.post_events(None, vec![WorkbenchEvent::ProjectClosed(root_ipc)]);
self.flush_events();
}
/// The user cancelled a plugin task (`task_id` from `TaskStarted`).
pub fn cancel_task(&self, task_id: &str) -> bool {
task_id.parse().is_ok_and(|id| self.shared.cancel_task(id))
@@ -1945,6 +2196,36 @@ impl PluginHost {
);
}
/// Queues what `events.watch-paths` watchers saw for their plugin and window,
/// while that window still shows the project the watch belongs to.
fn queue_watched_changes(&self, now: Instant) {
let changes = self.shared.external_watches.take();
if changes.is_empty() {
return;
}
let subs = self.shared.subscriptions.lock().clone();
let plugins = self.plugins.read();
let mut queues = self.queues.lock();
for change in changes {
let Some(p) = plugins.get(&change.plugin) else { continue };
if self.shared.project_of(&change.client).as_deref() != Some(change.project.as_path())
|| !Self::wants(p, EventKind::WatchedFilesChanged, subs.kinds.get(p.id()))
{
continue;
}
let batch =
ide_plugin::FilesChanged { project: Some(ide_core::ipc_path::to_ipc(&change.project)), ..change.batch };
let queue = queues.entry((change.plugin, Some(change.client))).or_insert_with(|| EventQueue {
since: now,
last_event: now,
events: Vec::new(),
files_source: None,
});
queue.last_event = now;
files_changed::append(&mut queue.events, vec![WorkbenchEvent::WatchedFilesChanged(batch)]);
}
}
pub fn post_events(&self, client: Option<&str>, events: Vec<WorkbenchEvent>) {
self.post_events_from(client, events, None);
}
@@ -1998,9 +2279,11 @@ impl PluginHost {
}
let queue = queues.entry((p.id().to_owned(), client.map(str::to_owned))).or_insert_with(|| EventQueue {
since: now,
last_event: now,
events: Vec::new(),
files_source: None,
});
queue.last_event = now;
if let Some(source) = &source {
if !queue.files_source.as_ref().is_some_and(|old| old.same(source)) {
queue.events.retain(|e| !matches!(e, WorkbenchEvent::FilesChanged(_)));
@@ -2015,6 +2298,7 @@ impl PluginHost {
&& !matches!(
event,
WorkbenchEvent::FilesChanged(_)
| WorkbenchEvent::WatchedFilesChanged(_)
| WorkbenchEvent::RunExited(_)
| WorkbenchEvent::TerminalExited(_)
| WorkbenchEvent::ContentTabAction(_)
@@ -2039,24 +2323,82 @@ impl PluginHost {
#[doc(hidden)]
pub fn flush_events_at(&self, now: Instant) {
self.queue_watched_changes(now);
let due: Vec<(QueueKey, EventQueue)> = {
let mut queues = self.queues.lock();
let plugins = self.plugins.read();
let keys: Vec<_> = queues
.iter()
.filter(|((id, _), q)| {
let running =
plugins.get(id).is_some_and(|p| p.runtime.lock().as_ref().is_some_and(|a| a.is_alive()));
running
let subs = self.shared.subscriptions.lock();
let mut due = Vec::new();
let mut keys_to_remove = Vec::new();
for (key, q) in queues.iter_mut() {
let (id, _client) = key;
let running = plugins.get(id).is_some_and(|p| p.runtime.lock().as_ref().is_some_and(|a| a.is_alive()));
let has_files = q.events.iter().any(|e| matches!(e, WorkbenchEvent::FilesChanged(_)));
let has_scheduled = q.events.iter().any(|e| matches!(e, WorkbenchEvent::Scheduled));
// Already debounced by the watcher, like project file changes.
let has_watched = q.events.iter().any(|e| matches!(e, WorkbenchEvent::WatchedFilesChanged(_)));
let debounce = subs.paths.get(id).and_then(|p| p.get("files-changed")).and_then(|f| f.debounce);
let (files_due, files_debouncing) = if has_files {
if let Some(debounce) = debounce {
let elapsed = now.saturating_duration_since(q.last_event) >= debounce
|| now.saturating_duration_since(q.since) >= MAX_DEBOUNCE_WAIT;
(elapsed, !elapsed)
} else {
(true, false)
}
} else {
(false, false)
};
let other_events_due = (running
|| has_watched
|| now.saturating_duration_since(q.since) >= IDLE_BATCH
|| q.events.len() >= MAX_QUEUED_EVENTS / 2
|| has_scheduled)
&& q.events.iter().any(|e| !matches!(e, WorkbenchEvent::FilesChanged(_)));
if files_debouncing {
if other_events_due {
let mut other_events = Vec::new();
q.events.retain(|e| {
if matches!(e, WorkbenchEvent::FilesChanged(_)) {
true
} else {
other_events.push(e.clone());
false
}
});
due.push((
key.clone(),
EventQueue {
since: q.since,
last_event: q.last_event,
events: other_events,
files_source: None,
},
));
}
} else {
let is_due = files_due
|| has_watched
|| running
|| now.saturating_duration_since(q.since) >= IDLE_BATCH
|| q.events.len() >= MAX_QUEUED_EVENTS / 2
|| q.events
.iter()
.any(|e| matches!(e, WorkbenchEvent::FilesChanged(_) | WorkbenchEvent::Scheduled))
})
.map(|(k, _)| k.clone())
.collect();
keys.into_iter().filter_map(|k| queues.remove(&k).map(|q| (k, q))).collect()
|| has_scheduled;
if is_due {
keys_to_remove.push(key.clone());
}
}
}
for k in keys_to_remove {
if let Some(q) = queues.remove(&k) {
due.push((k, q));
}
}
due
};
let mut changed = false;
for ((id, client), queue) in due {
@@ -2081,9 +2423,10 @@ impl PluginHost {
pub fn wait_events(&self, timeout: Duration) -> bool {
let deadline = Instant::now() + timeout;
loop {
let busy = self.plugins.read().values().any(|p| p.batches.lock().pending > 0);
self.flush_events_at(Instant::now());
let busy =
self.plugins.read().values().any(|p| p.batches.lock().pending > 0) || !self.queues.lock().is_empty();
if !busy {
self.flush_events_at(Instant::now());
return true;
}
if Instant::now() >= deadline {
@@ -2125,12 +2468,20 @@ impl PluginHost {
&& queue.events.iter().any(|e| !matches!(e, WorkbenchEvent::FilesChanged(_)))
{
let (files, other) = queue.events.into_iter().partition(|e| matches!(e, WorkbenchEvent::FilesChanged(_)));
let changed =
self.deliver(id, client.clone(), EventQueue { since: queue.since, events: other, files_source: None });
let changed = self.deliver(
id,
client.clone(),
EventQueue { since: queue.since, last_event: queue.last_event, events: other, files_source: None },
);
return self.deliver(
id,
client,
EventQueue { since: queue.since, events: files, files_source: queue.files_source },
EventQueue {
since: queue.since,
last_event: queue.last_event,
events: files,
files_source: queue.files_source,
},
) | changed;
}
let Ok(plugin) = self.get(id) else { return false };
@@ -2451,12 +2802,15 @@ impl PluginHost {
let restricted = p.dev_root.as_deref().is_some_and(|root| !(self.project_policy.read())(root));
if due && !restricted && self.startup_finished.load(Ordering::Acquire) {
// Activates it if needed and calls `handle([scheduled])`.
self.queues
.lock()
.entry((p.id().to_owned(), None))
.or_insert_with(|| EventQueue { since: now, events: Vec::new(), files_source: None })
.events
.push(WorkbenchEvent::Scheduled);
let mut q = self.queues.lock();
let queue = q.entry((p.id().to_owned(), None)).or_insert_with(|| EventQueue {
since: now,
last_event: now,
events: Vec::new(),
files_source: None,
});
queue.last_event = now;
queue.events.push(WorkbenchEvent::Scheduled);
}
}
if changed {
@@ -2490,6 +2844,7 @@ impl PluginHost {
fn prepare(&self, pkg: &Package) -> Result<ide_extension::PreparedSet, String> {
plugin_icon(pkg)?;
let mut set = self.registry.prepare(pkg)?;
check_setting_grants(pkg)?;
for icon in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten() {
if !set.files.contains(icon) {
set.files.push(icon.clone());
@@ -2648,7 +3003,7 @@ impl PluginHost {
meta.declared_extra = set.capabilities.clone();
meta.error = None;
}
let (granted, pending) = match decision {
let (mut granted, pending) = match decision {
Decision::Allowed { granted, pending } => (granted, pending),
Decision::NeedsConfirmation { new, .. } => {
let mut meta = plugin.meta.lock();
@@ -2661,6 +3016,19 @@ impl PluginHost {
if let Err(e) = self.registry.commit(set) {
return self.set_failed(plugin, e);
}
// Setting-derived network grants materialize their approved host while
// the setting holds it: `net:setting:server` acts as `net:<host>`, so
// the request path keeps its rules (`net_capability` / `covers`).
let api = api::PluginApi { pkg: plugin.pkg.clone(), shared: self.shared.clone() };
for (cap, approved, _pending) in api.net_setting_hosts(&plugin.subject()) {
if let Some(host) = approved {
match cap {
Capability::NetSetting { http: false, key: _ } => granted.push(Capability::Net(host)),
Capability::NetSetting { http: true, key: _ } => granted.push(Capability::NetHttp(host)),
_ => {}
}
}
}
{
let mut meta = plugin.meta.lock();
meta.granted = granted;
@@ -3116,6 +3484,21 @@ impl PluginHost {
.filter(|g| g.confirmed && g.has(&Capability::NetAsk) && m.declares(&Capability::NetAsk))
.map(|g| g.net_hosts.iter().cloned().collect())
.unwrap_or_default();
// Setting-derived hosts, listed next to the `net:ask` ones: the
// approved host, and a pending one the setting now holds.
let net_settings = if m.capabilities.all().any(|c| matches!(c, Capability::NetSetting { .. })) {
let api = api::PluginApi { pkg: p.pkg.clone(), shared: self.shared.clone() };
api.net_setting_hosts(&p.subject())
.into_iter()
.filter(|(cap, ..)| grant.as_ref().is_some_and(|g| g.confirmed && g.has(cap)))
.map(|(cap, approved, pending)| {
let Capability::NetSetting { http, key } = cap else { unreachable!() };
types::PluginNetSetting { setting: key, http, host: approved, pending }
})
.collect()
} else {
Vec::new()
};
PluginInfo {
id: m.id.clone(),
name: m.name.clone(),
@@ -3145,6 +3528,7 @@ impl PluginHost {
vm_options: agent.vm_options,
jdk: agent.jdk,
approved,
executor: agent.executor,
}
}),
source: p.source,
@@ -3155,6 +3539,7 @@ impl PluginHost {
has_code: m.wasm.is_some(),
capabilities,
net_hosts,
net_settings,
contributions: self.registry.contributions(&m.id),
activation: m.activation.iter().map(ToString::to_string).collect(),
warnings: meta.warnings.clone(),
@@ -3183,6 +3568,37 @@ fn agent_jar_grant(manifest: &Manifest, dir: &Path) -> Option<BinaryGrant> {
Some(BinaryGrant { path, hash })
}
/// `net:setting:<key>` grants name a `string` setting of the plugin's own
/// settings schema; checked like the other manifest checks, at install and
/// start (#3809).
fn check_setting_grants(pkg: &Package) -> Result<(), String> {
let derived: Vec<&Capability> =
pkg.manifest.capabilities.all().filter(|c| matches!(c, Capability::NetSetting { .. })).collect();
if derived.is_empty() {
return Ok(());
}
let mut strings = BTreeSet::new();
for decl in pkg.manifest.declarations(ui_points::SETTINGS) {
let decl = ui_points::settings(pkg, decl)?;
for property in decl.json.get("properties").and_then(|p| p.as_array()).into_iter().flatten() {
if property.get("type").and_then(|t| t.as_str()) == Some("string")
&& let Some(key) = property.get("key").and_then(|k| k.as_str())
{
strings.insert(key.to_owned());
}
}
}
for cap in derived {
let Capability::NetSetting { http: _, key } = cap else { continue };
if !strings.contains(key.as_str()) {
return Err(format!(
"capability `{cap}` needs a `string` setting {key:?} in the plugin's own settings schema"
));
}
}
Ok(())
}
/// Consent / Settings: surface exact contributed JVM flags on the `java.agent` permission.
fn annotate_java_agent_vm_options(capabilities: &mut [CapabilityInfo], manifest: &Manifest) {
let opts = java_agents::declared_vm_options(manifest);
+3
Переглянути файл
@@ -95,6 +95,9 @@ pub fn register_builtin_points(
registry.register(Arc::new(UiPoint::new(p::VIEWS, ui.clone(), p::view)))?;
registry.register(Arc::new(UiPoint::new(p::CUSTOM_EDITORS, ui.clone(), p::custom_editor)))?;
registry.register(Arc::new(UiPoint::new(p::EDITOR_PANELS, ui.clone(), p::editor_panel)))?;
registry.register(Arc::new(UiPoint::new(p::OVERLAYS, ui.clone(), p::overlay)))?;
registry.register(Arc::new(UiPoint::new(p::DIALOGS, ui.clone(), p::dialog)))?;
registry.register(Arc::new(UiPoint::new(p::RUN_ANYTHING, ui.clone(), p::run_anything)))?;
registry.register(Arc::new(UiPoint::new(p::MARKER_ICONS, ui.clone(), p::marker_icon)))?;
registry.register(Arc::new(UiPoint::new(p::FILE_ICONS, ui.clone(), p::file_icon)))?;
registry.register(Arc::new(UiPoint::new(p::FILE_TEMPLATES, ui.clone(), p::file_template)))?;
+45 -1
Переглянути файл
@@ -45,6 +45,9 @@ pub struct Detector {
/// Optional output parser, including the API 1.4 plugin export.
#[serde(default)]
pub framework: Option<String>,
/// Output stream transport (API 1.18): `"pipes"` (default) or `"pty"`.
#[serde(default, alias = "outputMode")]
pub output_mode: Option<ide_plugin::PluginOutputMode>,
}
/// Detectors of enabled plugins.
@@ -94,6 +97,12 @@ impl ExtensionPoint for RunDetectorsPoint {
if d.framework.as_ref().is_some_and(|v| v.is_empty() || v.len() > 64) {
return Err("invalid test framework".into());
}
if d.output_mode.is_some() {
pkg.manifest.needs_api("runDetectors.outputMode", 18)?;
}
if d.test && d.output_mode == Some(ide_plugin::PluginOutputMode::Pty) {
return Err(format!("run detector {:?}: test configurations cannot emulate a terminal", d.id));
}
validate_item_id(&d.id, "run detector id")?;
if d.name.trim().is_empty() || d.name.len() > 128 {
return Err(format!("run detector {:?}: `name` must be 1–128 bytes", d.id));
@@ -169,6 +178,7 @@ impl ExternalDetection for PluginRunDetection {
allow_parallel: false,
extras: ide_run::RunExtras {
params: d.framework.clone().map(|f| [("framework".into(), f)].into()).unwrap_or_default(),
emulate_terminal: d.output_mode == Some(ide_plugin::PluginOutputMode::Pty),
..Default::default()
},
})
@@ -193,7 +203,10 @@ impl ExternalDetection for PluginRunDetection {
is_test: c.test,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
extras: ide_run::RunExtras {
emulate_terminal: c.output_mode == ide_plugin::PluginOutputMode::Pty,
..Default::default()
},
};
config.id = config_id(plugin, &c.id);
config.cwd = Some(c.cwd.as_ref().map(|p| root.join(p)).unwrap_or_else(|| root.to_path_buf()).into());
@@ -250,3 +263,34 @@ impl ExternalDetection for PluginRunDetection {
pin.verify().map(Path::to_path_buf)
}
}
#[cfg(test)]
mod tests {
use super::*;
use ide_extension::ExtensionPoint;
#[test]
fn detector_output_mode_requires_api_18_and_rejects_tests() {
let point = RunDetectorsPoint::new(Arc::default());
let base_toml = |extra: &str| {
let src = format!("id = \"test\"\nname = \"Test\"\nversion = \"1.0.0\"\n{extra}\n");
let manifest = ide_extension::Manifest::parse(&src).unwrap();
ide_extension::Package::new(manifest, std::env::temp_dir())
};
let decl = |test: bool, mode: &str| -> toml::Value {
toml::from_str(&format!(
"id = \"run\"\nname = \"Run\"\nfiles = [\"m\"]\ncommand = \"tool\"\ntest = {test}\noutputMode = \"{mode}\"\n"
))
.unwrap()
};
let old = base_toml("engines.openidea = \"^1.17\"");
assert!(point.prepare(&old, decl(false, "pty")).unwrap_err().contains("1.18"));
let current = base_toml("engines.openidea = \"^1.18\"");
assert!(point.prepare(&current, decl(false, "pty")).is_ok());
assert!(point.prepare(&current, decl(false, "pipes")).is_ok());
assert!(point.prepare(&current, decl(true, "pipes")).is_ok());
assert!(point.prepare(&current, decl(true, "pty")).unwrap_err().contains("test"));
}
}
+12 -1
Переглянути файл
@@ -39,7 +39,12 @@ impl Shared {
}
}
impl PluginApi {
pub(super) fn register_target(&self, root: &Path, target: PluginRunTarget) -> Result<(), HostError> {
pub(super) fn register_target(
&self,
root: &Path,
target: PluginRunTarget,
generation: Option<u64>,
) -> Result<(), HostError> {
ide_remote::plugin_target::validate(&target).map_err(|e| HostError::Invalid(e.to_string()))?;
let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?;
if !workspace.projects().iter().any(|r| r == root) {
@@ -48,6 +53,12 @@ impl PluginApi {
if !workspace.trusted(root) {
return Err(HostError::Denied("project is not trusted".into()));
}
if let Some(expected) = generation {
let current = self.shared.project_generation(root)?;
if expected < current {
return Err(HostError::Stale);
}
}
self.approved_program_in_project(&target.program, Some(root))?;
let blocked = self.shared.prompts_blocked.lock();
if blocked.contains(self.pkg.id()) {
+20
Переглянути файл
@@ -70,6 +70,24 @@ pub struct PluginJavaAgent {
pub jdk: Option<String>,
/// The jar still has the hash recorded when `java.agent` was granted.
pub approved: bool,
/// The title of the executor the agent is bound to (API 1.18): "Run with <title>" and
/// "Debug with <title>" launch with it; other launches leave it out.
#[serde(default)]
pub executor: Option<String>,
}
/// A `net:setting:` grant's host for Settings › Plugins: the approved one while the setting holds it, else the pending one.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PluginNetSetting {
/// The setting key the host comes from (`server` of `net:setting:server`).
pub setting: String,
/// Plain HTTP (`net.http:setting:`) instead of HTTPS (and loopback HTTP).
pub http: bool,
/// The approved host, while the setting still holds it.
pub host: Option<String>,
/// The host the setting holds now when it is not the approved one.
pub pending: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
@@ -97,6 +115,8 @@ pub struct PluginInfo {
/// HTTPS hosts the user allowed through `net:ask` ("always allow"),
/// none of them declared by the manifest; each can be revoked.
pub net_hosts: Vec<String>,
/// Setting-derived hosts (`net:setting:`), approved in Settings, listed next to the `net:ask` ones.
pub net_settings: Vec<PluginNetSetting>,
/// What it contributes while live (point + label).
pub contributions: Vec<ContributionInfo>,
/// `activation` events of the manifest.
+320 -3
Переглянути файл
@@ -5,7 +5,8 @@
//!
//! ```toml
//! [[contributes.menus]]
//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context, commit.message
//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context, commit.message,
//! # services.context / services.toolbar (API 1.18: the Services tree's own nodes)
//! command = "check"
//! when = "editorLang == java"
//! # view = "<view id>" # required for (only allowed on) viewItem.context
@@ -44,6 +45,22 @@
//! width = 110 # pixels, 40–400
//! when = "plugin.<id>.enabled" # optional
//!
//! [[contributes.overlays]]
//! id = "stage"
//! web = "web/stage.html" # floats over the workbench, never takes the focus (API 1.18)
//! width = 320 # pixels, 40–800; the page can resize it within those bounds
//! height = 240
//! anchor = "bottom-right" # top-left … bottom-right (nine); the page can move it
//! when = "plugin.<id>.showing" # optional
//! interactive = true # optional; false lets every click through to the IDE
//!
//! [[contributes.dialogs]]
//! id = "preview"
//! title = "SQL Preview" # the dialog's title bar
//! web = "web/preview.html" # modal, resizable; opened by `views.reveal("preview")` (API 1.18)
//! width = 900 # pixels, 320–1600
//! height = 600 # pixels, 200–1200
//!
//! [[contributes.fileIcons]]
//! id = "drawing"
//! patterns = ["*.excalidraw"]
@@ -82,8 +99,11 @@ pub const SETTINGS: &str = "settings";
pub const VIEWS: &str = "views";
pub const CUSTOM_EDITORS: &str = "customEditors";
pub const EDITOR_PANELS: &str = "editorPanels";
pub const OVERLAYS: &str = "overlays";
pub const DIALOGS: &str = "dialogs";
pub const RUN_ANYTHING: &str = "runAnything";
/// The points whose declarations can name a `web` page (served, messaged, sent view events).
pub const WEB_POINTS: [&str; 3] = [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS];
pub const WEB_POINTS: [&str; 5] = [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS];
pub const FILE_ICONS: &str = "fileIcons";
pub const MARKER_ICONS: &str = "markerIcons";
pub const FILE_TEMPLATES: &str = "fileTemplates";
@@ -93,7 +113,10 @@ pub const SERVER_COMMANDS: &str = "serverCommands";
const VIEW_ITEM_MENU: &str = "viewItem.context";
/// The toolbar above the commit message (Commit tool window and dialog).
const COMMIT_MESSAGE_MENU: &str = "commit.message";
const MENU_IDS: [&str; 10] = [
/// The Services tool window's context menu and toolbar for the IDE's own nodes (run
/// configurations, Docker containers…): the command gets the selected services.
const SERVICES_MENUS: [&str; 2] = ["services.context", "services.toolbar"];
const MENU_IDS: [&str; 12] = [
"editor.context",
"projectView.context",
"editorTab.context",
@@ -104,6 +127,8 @@ const MENU_IDS: [&str; 10] = [
"mainToolbar",
"problems.context",
"searchResults.context",
SERVICES_MENUS[0],
SERVICES_MENUS[1],
];
const MAX_TITLE: usize = 256;
const MAX_SETTINGS: usize = 200;
@@ -168,6 +193,9 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
if d.menu == COMMIT_MESSAGE_MENU {
pkg.manifest.needs_api(&format!("contributes.menus: {COMMIT_MESSAGE_MENU}"), 3)?;
}
if SERVICES_MENUS.contains(&d.menu.as_str()) {
pkg.manifest.needs_api(&format!("contributes.menus: {}", d.menu), 18)?;
}
if let Some(w) = &d.when {
validate_when(w).map_err(|e| format!("contributes.menus: {e}"))?;
}
@@ -887,6 +915,109 @@ pub(super) fn editor_panel(pkg: &Package, decl: toml::Value) -> Result<UiDecl, S
Ok(out)
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct OverlayDecl {
id: String,
web: String,
width: u32,
height: u32,
#[serde(default = "default_overlay_anchor")]
anchor: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
when: Option<String>,
#[serde(default = "default_true")]
interactive: bool,
}
fn default_overlay_anchor() -> String {
"bottom-right".into()
}
fn default_true() -> bool {
true
}
/// Where an overlay can sit in the window (the page may move it to another).
pub const OVERLAY_ANCHORS: [&str; 9] = [
"top-left",
"top-center",
"top-right",
"middle-left",
"center",
"middle-right",
"bottom-left",
"bottom-center",
"bottom-right",
];
const OVERLAY_SIZE: std::ops::RangeInclusive<u32> = 40..=800;
/// `[[contributes.overlays]]` (API 1.18): a web page floating over the workbench at
/// one of nine anchors, shown while `when` holds. It never takes the keyboard focus,
/// sits under dialogs and popups, and sees nothing of the IDE, so it needs no
/// capability.
pub(super) fn overlay(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: OverlayDecl = decode(OVERLAYS, decl)?;
pkg.manifest.needs_api(&format!("contributes.{OVERLAYS}"), 18)?;
validate_item_id(&d.id, "overlay id")?;
let what = format!("overlay {:?}", d.id);
for (name, value) in [("width", d.width), ("height", d.height)] {
if !OVERLAY_SIZE.contains(&value) {
return Err(format!("{what}: `{name}` is {}–{} pixels", OVERLAY_SIZE.start(), OVERLAY_SIZE.end()));
}
}
if !OVERLAY_ANCHORS.contains(&d.anchor.as_str()) {
return Err(format!("{what}: `anchor` is one of {}", OVERLAY_ANCHORS.join(", ")));
}
if let Some(when) = &d.when {
validate_when(when).map_err(|e| format!("{what}: {e}"))?;
}
let files = super::web::web_files(pkg, &d.web, &what)?;
let mut out = UiDecl::new(d.id.clone(), d.id.clone(), json(&d)?);
out.files = files;
Ok(out)
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct DialogDecl {
id: String,
title: String,
web: String,
width: u32,
height: u32,
}
const DIALOG_WIDTH: std::ops::RangeInclusive<u32> = 320..=1600;
const DIALOG_HEIGHT: std::ops::RangeInclusive<u32> = 200..=1200;
/// `[[contributes.dialogs]]` (API 1.18): a package web page in a modal, resizable IDE
/// dialog with a title bar, opened by the plugin's code with `views.reveal(id)` in the
/// invoking window. Like a web view it sees nothing of the IDE beyond its messages, so
/// it needs no capability.
pub(super) fn dialog(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: DialogDecl = decode(DIALOGS, decl)?;
pkg.manifest.needs_api(&format!("contributes.{DIALOGS}"), 18)?;
validate_item_id(&d.id, "dialog id")?;
let what = format!("dialog {:?}", d.id);
// `views.reveal(id)` opens it, so it can't share an id with a tool window.
if pkg.manifest.declarations(VIEWS).iter().any(|v| v.get("id").and_then(|i| i.as_str()) == Some(&d.id)) {
return Err(format!("{what}: a view has the same id"));
}
if d.title.trim().is_empty() || d.title.len() > 256 {
return Err(format!("{what}: `title` is 1–256 bytes"));
}
for (name, value, range) in [("width", d.width, DIALOG_WIDTH), ("height", d.height, DIALOG_HEIGHT)] {
if !range.contains(&value) {
return Err(format!("{what}: `{name}` is {}–{} pixels", range.start(), range.end()));
}
}
let files = super::web::web_files(pkg, &d.web, &what)?;
let mut out = UiDecl::new(d.id.clone(), d.title.clone(), json(&d)?);
out.files = files;
Ok(out)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct FileIconDecl {
@@ -1112,6 +1243,44 @@ pub(super) fn commit_check(pkg: &Package, decl: toml::Value) -> Result<UiDecl, S
Ok(UiDecl::new(d.id.clone(), d.title.clone(), json(&d)?))
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct RunAnythingDecl {
/// The first word of the Run Anything lines the plugin answers (`task`).
prefix: String,
/// The heading of its entries (default: the plugin's name).
#[serde(default, skip_serializing_if = "Option::is_none")]
title: Option<String>,
}
/// Whether `prefix` can start a Run Anything line: a lowercase word of letters, digits,
/// `.`, `_` or `-` that commands begin with (`task`, `just`, `make`).
pub(super) fn valid_run_anything_prefix(prefix: &str) -> bool {
(1..=32).contains(&prefix.len())
&& prefix.starts_with(|c: char| c.is_ascii_lowercase() || c.is_ascii_digit())
&& prefix.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '.' | '_' | '-'))
}
/// `[[contributes.runAnything]]` (API 1.18): Run Anything lines starting with `prefix`
/// are suggested and run by the plugin's `run-anything-provider` export.
pub(super) fn run_anything(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: RunAnythingDecl = decode(RUN_ANYTHING, decl)?;
pkg.manifest.needs_api(&format!("contributes.{RUN_ANYTHING}"), 18)?;
if !valid_run_anything_prefix(&d.prefix) {
return Err(format!(
"contributes.{RUN_ANYTHING}: `prefix` {:?} is one lowercase word (letters, digits, `.`, `_`, `-`; at most 32)",
d.prefix
));
}
if let Some(t) = &d.title {
title(RUN_ANYTHING, t)?;
}
if pkg.manifest.wasm.is_none() {
return Err(format!("contributes.{RUN_ANYTHING}: needs `wasm` (its lines run in the plugin's code)"));
}
Ok(UiDecl::new(d.prefix.clone(), d.title.clone().unwrap_or_default(), json(&d)?))
}
/// A command a language server's code lens, code action or inlay hint carries and
/// leaves to the client, and the plugin command that runs it.
#[derive(Debug, Deserialize, Serialize)]
@@ -1212,6 +1381,27 @@ mod tests {
}
}
#[test]
fn services_menus_require_api_1_18() {
for location in SERVICES_MENUS {
for (api, valid) in [("^1.17", false), ("^1.18", true)] {
let manifest = ide_extension::Manifest::parse(&format!("id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='reload'\ntitle='Reload'")).unwrap();
let pkg = Package::new(manifest, std::path::PathBuf::from("/unused"));
let decl = toml::from_str(&format!(
"menu='{location}'\ncommand='reload'\nwhen=\"serviceKind == 'spring-boot' && serviceRunning\""
))
.unwrap();
assert_eq!(menu(&pkg, decl).is_ok(), valid, "{api}:{location}");
}
}
let manifest = ide_extension::Manifest::parse("id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='^1.18'\n[[contributes.commands]]\nid='reload'\ntitle='Reload'").unwrap();
let pkg = Package::new(manifest, std::path::PathBuf::from("/unused"));
let grouped = toml::from_str("menu='services.context'\ncommand='reload'\nsubmenu='Hot Reload'").unwrap();
assert!(menu(&pkg, grouped).is_ok());
let toolbar = toml::from_str("menu='services.toolbar'\ncommand='reload'\nsubmenu='Hot Reload'").unwrap();
assert!(menu(&pkg, toolbar).unwrap_err().contains("only for context menus"));
}
#[test]
fn escape_bindings_need_api_1_10_and_a_when_clause() {
let pkg = |api: &str| {
@@ -1518,6 +1708,133 @@ web = "web/view.html"
assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &ask).unwrap_err().contains("capability"));
}
#[test]
fn overlays_validate_api_size_anchor_when_and_page() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/overlay");
// A Windows checkout may have CRLF line ends; the edits below match on `\n`.
let source = std::fs::read_to_string(root.join("plugin.toml")).unwrap().replace("\r\n", "\n");
let check = |source: &str| {
let manifest = ide_extension::Manifest::parse(source)?;
let decl = manifest.declarations(OVERLAYS).into_iter().next().unwrap();
overlay(&Package::new(manifest, root.clone()), decl)
};
let valid = check(&source).unwrap();
assert_eq!(valid.key, "probe");
assert_eq!(
valid.json,
serde_json::json!({
"id": "probe", "web": "web/index.html", "width": 260, "height": 140,
"anchor": "bottom-right", "interactive": true,
})
);
assert_eq!(valid.files, [PathBuf::from("web/index.html")]);
let placed =
check(&source.replace("height = 140", "height = 140\nanchor = \"top-center\"\ninteractive = false"));
let placed = placed.unwrap();
assert_eq!(placed.json["anchor"], "top-center");
assert_eq!(placed.json["interactive"], false);
let when = source.replace("height = 140", "height = 140\nwhen = \"plugin.overlay.showing\"");
assert_eq!(check(&when).unwrap().json["when"], "plugin.overlay.showing");
for size in ["40", "800"] {
assert!(check(&source.replace("width = 260", &format!("width = {size}"))).is_ok(), "{size}");
}
for (bad, error) in [
(source.replace("^1.18", "^1.17"), "1.18"),
(source.replace("width = 260", "width = 39"), "40–800"),
(source.replace("height = 140", "height = 801"), "`height`"),
(source.replace("height = 140\n", ""), "height"),
(source.replace("height = 140", "height = 140\nanchor = \"left\""), "anchor"),
(source.replace("height = 140", "height = 140\nwhen = \"a &&\""), "when"),
(source.replace("height = 140", "height = 140\nfocus = true"), "focus"),
(source.replace("web/index.html", "index.html"), "directory of its own"),
(source.replace("web/index.html", "web/missing.html"), "no such file"),
(source.replace(r#"id = "probe""#, r#"id = "Pro Be""#), "id"),
] {
let err = check(&bad).unwrap_err();
assert!(err.contains(error), "{bad}\n→ {err}");
}
}
#[test]
fn dialogs_validate_api_title_size_id_and_page() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("web")).unwrap();
std::fs::write(dir.path().join("web/preview.html"), "<p>SQL</p>").unwrap();
let source = r#"id = "sql"
name = "SQL"
version = "0.1.0"
engines.openidea = "^1.18"
[[contributes.dialogs]]
id = "preview"
title = "SQL Preview"
web = "web/preview.html"
width = 900
height = 600
"#;
let check = |source: &str| {
let manifest = ide_extension::Manifest::parse(source)?;
let decl = manifest.declarations(DIALOGS).into_iter().next().unwrap();
dialog(&Package::new(manifest, dir.path().to_path_buf()), decl)
};
let valid = check(source).unwrap();
assert_eq!((valid.key.as_str(), valid.label.as_str()), ("preview", "SQL Preview"));
assert_eq!(
valid.json,
serde_json::json!({"id": "preview", "title": "SQL Preview", "web": "web/preview.html", "width": 900, "height": 600})
);
assert_eq!(valid.files, [PathBuf::from("web/preview.html")]);
for (bad, error) in [
(source.replace("^1.18", "^1.17"), "1.18"),
(source.replace("width = 900", "width = 319"), "320–1600"),
(source.replace("height = 600", "height = 1201"), "`height`"),
(source.replace(r#"title = "SQL Preview""#, r#"title = " ""#), "title"),
(
source.replace(
"height = 600",
"height = 600
modal = false",
),
"modal",
),
(source.replace("web/preview.html", "web/missing.html"), "no such file"),
(source.replace(r#"id = "preview""#, r#"id = "Pre View""#), "id"),
(format!("{source}\n[[contributes.views]]\nid = \"preview\"\ntitle = \"P\"\n"), "same id"),
] {
let err = check(&bad).unwrap_err();
assert!(err.contains(error), "{bad}\n→ {err}");
}
}
#[test]
fn run_anything_validates_api_prefix_title_and_code() {
let source = "id = \"go\"\nname = \"Go\"\nversion = \"0.1.0\"\nengines.openidea = \"^1.18\"\nwasm = \"p.wasm\"\n\n[[contributes.runAnything]]\nprefix = \"task\"\n";
let check = |source: &str| {
let manifest = ide_extension::Manifest::parse(source)?;
let decl = manifest.declarations(RUN_ANYTHING).into_iter().next().unwrap();
run_anything(&Package::new(manifest, std::env::temp_dir()), decl)
};
let valid = check(source).unwrap();
assert_eq!((valid.key.as_str(), valid.json.clone()), ("task", serde_json::json!({"prefix": "task"})));
assert_eq!(check(&format!("{source}title = \"Go Task\"\n")).unwrap().json["title"], "Go Task");
for prefix in ["go-task", "mvn.w", "x2"] {
assert!(check(&source.replace("\"task\"", &format!("{prefix:?}"))).is_ok(), "{prefix}");
}
for (bad, error) in [
(source.replace("^1.18", "^1.17"), "1.18".to_owned()),
(source.replace("wasm = \"p.wasm\"\n", ""), "wasm".to_owned()),
(format!("{source}command = \"x\"\n"), "command".to_owned()),
]
.into_iter()
.chain(
["Task", "task build", "", "-x", "t/x", &"t".repeat(33)]
.map(|p| (source.replace("\"task\"", &format!("{p:?}")), "prefix".to_owned())),
) {
let err = check(&bad).unwrap_err();
assert!(err.contains(&error), "{bad}\n→ {err}");
}
}
fn package_with_catalogs(files: &[(&str, &str)]) -> (tempfile::TempDir, Package) {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join(LOCALES_DIR)).unwrap();
+165 -13
Переглянути файл
@@ -73,6 +73,7 @@ pub struct Project {
pub(crate) widget_preview: ide_flutter::ToolServer,
pub(crate) kotlin_bridge: Option<Arc<crate::kotlin_bridge::KotlinBridge>>,
pub(crate) phpstan: Option<Arc<crate::phpstan::Phpstan>>,
pub(crate) tsc_watch: Option<Arc<crate::tsc_watch::TscWatch>>,
pub(crate) watcher: Arc<Watcher>,
/// Watchers of the Project Structure content roots outside the project folder.
pub(crate) content_watchers: Mutex<Vec<(PathBuf, Watcher)>>,
@@ -207,7 +208,11 @@ impl Host {
let root = member.as_ref().unwrap_or(window_root);
ide_sdk::apply::server_launch_overrides(cfg, &effective);
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
crate::ts_code_style::configure(cfg, server_root, &effective);
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
// After the global plugins: they keep the IDE's copies.
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
let container_python = effective.languages.python.run_target().is_some();
crate::ops::sdk::container_python::configure_server(cfg, &data_dir, root, &effective);
// Attached dependency projects are source, so basedpyright/Pyright should
@@ -318,7 +323,13 @@ impl Host {
ide_sdk::php::configure_intelephense_storage(cfg, &data_dir);
if cfg.name == "jdtls" {
let (excluded_poms, build_files) = jdtls_maven_import(root, &effective);
ide_sdk::apply::configure_maven_import(cfg, root, &excluded_poms, build_files.as_deref());
ide_sdk::apply::configure_maven_import(
cfg,
root,
&excluded_poms,
&effective.project_structure.excluded,
build_files.as_deref(),
);
ide_sdk::apply::configure_gradle_import(
cfg,
effective.languages.java.gradle.linked_projects.as_deref(),
@@ -390,6 +401,8 @@ impl Host {
trusted.clone(),
);
documents.add_observer(phpstan.clone());
let tsc_watch = crate::tsc_watch::TscWatch::new(root.clone(), settings.clone(), sink.clone(), trusted.clone());
documents.add_observer(tsc_watch.clone());
let repos = Arc::new(RwLock::new(Repos::enclosing(&root)?));
for repo in repos.read().all() {
repo.set_execution_allowed(trusted.load(Ordering::Acquire));
@@ -441,7 +454,9 @@ impl Host {
phpstan.files_removed(batch.removed.iter());
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
if composer_changed(&root, changed.iter().chain(&batch.removed))
|| ts_config_changed(changed.iter().chain(&batch.removed))
{
lsp.reconfigure_soon();
}
// Not while loading: a first `use flake` may write `flake.lock` itself.
@@ -684,6 +699,7 @@ impl Host {
notebooks,
kotlin_bridge: Some(kotlin_bridge),
phpstan: Some(phpstan),
tsc_watch: Some(tsc_watch),
watcher,
content_watchers: Mutex::new(content_watchers),
lsp_watchers: Mutex::new(Vec::new()),
@@ -744,9 +760,18 @@ impl Host {
if let Some(phpstan) = &project.phpstan {
phpstan.start(&self.runtime);
}
if let Some(watch) = &project.tsc_watch {
watch.apply(&self.runtime);
}
if let Some(cmd) = post_start {
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
}
if project.is_trusted() {
let p = project.clone();
self.runtime.spawn_blocking(move || {
crate::github_auth::apply_to_project(&p);
});
}
crate::ops::sdk::container_python::ensure(self, &project);
Ok(project)
}
@@ -944,6 +969,7 @@ impl Host {
notebooks,
kotlin_bridge: None,
phpstan: None,
tsc_watch: None,
watcher: Arc::new(watcher),
content_watchers: Mutex::new(Vec::new()),
lsp_watchers: Mutex::new(Vec::new()),
@@ -1508,8 +1534,7 @@ impl Project {
}
pub fn staged_file_encoding(&self, path: &Path, bytes: &[u8]) -> ide_vcs::TextEncoding {
let defaults = self.documents.file_defaults();
let charset = ide_vfs::detect_encoding(bytes, defaults.fallback_for(path));
let charset = self.documents.detect_encoding(path, bytes);
self.vcs_text_encoding(path, charset)
}
@@ -1868,7 +1893,9 @@ fn content_root_watcher(
index.ignore_rules_changed(&batch.ignore_rules);
index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat());
// A workspace member's PHP language level follows its own composer.json.
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
if composer_changed(&root, changed.iter().chain(&batch.removed))
|| ts_config_changed(changed.iter().chain(&batch.removed))
{
lsp.reconfigure_soon();
}
if let Some(bridge) = &kotlin_bridge {
@@ -1890,6 +1917,17 @@ fn content_root_watcher(
.ok()
}
/// A tsconfig.json / jsconfig.json (or a `tsconfig.*.json` one extends) changed: the tsserver
/// plugins it declares are part of vtsls' configuration.
fn ts_config_changed<'a>(mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
paths.any(|p| {
let name = p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
!p.components().any(|c| c.as_os_str() == "node_modules")
&& (name.starts_with("tsconfig") || name.starts_with("jsconfig"))
&& name.ends_with(".json")
})
}
/// Whether the `composer.json` of `root` is among `paths`: the PHP language level follows it
/// (`ide_sdk::php`).
fn composer_changed<'a>(root: &Path, mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
@@ -1999,7 +2037,9 @@ fn independent_eclipse_projects(root: &Path) -> Vec<PathBuf> {
/// The detected roots with the last Gradle sync's source sets first: Gradle evaluated what
/// static detection guesses. Folders outside the project keep their absolute path, which
/// `normalize` turns into the same form the UI compares (`Users/me/svc/src/main/java`).
/// `normalize` turns into the same form the UI compares (`Users/me/svc/src/main/java`);
/// their `detected_from` owner keeps its leading `/` or drive (`<project>/Gradle`) so
/// module lists still address them as absolute paths.
fn with_gradle_roots(
root: &Path,
build_cache: &Path,
@@ -2023,12 +2063,22 @@ fn with_gradle_roots(
};
if !out.iter().any(|f| f.path == path) {
// `<module>/Gradle`, like the `<module>/build.gradle` static detection reports, so the
// UI still finds the module after a sync. Projects outside the root stay `Gradle`:
// the UI reads the folder as project-relative.
// UI still finds the module after a sync. Projects outside the root keep their
// absolute owner (without `normalize`, which strips a leading `/`), except an ancestor
// of the root (opened from a subproject) or a filesystem/drive root, which stay
// `Gradle` so they cannot shadow in-project modules or collapse to a bare drive `D:`.
let project = dunce::canonicalize(&project).unwrap_or(project);
let detected_from = match project.strip_prefix(root) {
Ok(rel) if !rel.as_os_str().is_empty() => {
format!("{}/Gradle", ide_workspace::roots::normalize(&rel.to_string_lossy()))
}
Err(_) if !root.starts_with(&project) && project.parent().is_some() => {
let raw = project.to_string_lossy().replace('\\', "/");
let owner = raw.trim_end_matches('/');
let drive_root =
owner.len() == 2 && owner.as_bytes()[0].is_ascii_alphabetic() && owner.as_bytes()[1] == b':';
if owner.is_empty() || drive_root { "Gradle".into() } else { format!("{owner}/Gradle") }
}
_ => "Gradle".into(),
};
out.push(SourceFolder { path, kind, detected_from: Some(detected_from) });
@@ -2366,7 +2416,7 @@ mod maven_linkage_tests {
serde_json::json!({"name": "jdtls", "command": "jdtls"}),
)
.unwrap();
ide_sdk::apply::configure_maven_import(&mut server, tmp.path(), &excluded_poms, None);
ide_sdk::apply::configure_maven_import(&mut server, tmp.path(), &excluded_poms, &[], None);
let options = serde_json::to_value(server.initialization_options).unwrap();
let exclusions = options.pointer("/settings/java/import/exclusions").unwrap().as_array().unwrap();
assert!(exclusions.contains(&serde_json::json!(tmp.path().join("a").to_string_lossy().replace('\\', "/"))));
@@ -2476,18 +2526,109 @@ mod gradle_roots_tests {
std::fs::write(root.join("build.gradle"), "").unwrap();
let out = with_gradle_roots(&root, &cache, &Default::default(), &[guessed, other.clone()]);
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
let owner = format!("{}/Gradle", svc.to_string_lossy().replace('\\', "/"));
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.kind, f.detected_from.as_deref())).collect();
// A project outside the root is not a module the UI could address.
// A project outside the root keeps its absolute owner so module lists still address it.
assert_eq!(
got,
[
("src/it/java".into(), RootKind::Test, Some("Gradle")),
(abs(svc.join("src/main/java")), RootKind::Source, Some("Gradle")),
(abs(svc.join("build")), RootKind::Excluded, Some("Gradle")),
(abs(svc.join("src/main/java")), RootKind::Source, Some(owner.as_str())),
(abs(svc.join("build")), RootKind::Excluded, Some(owner.as_str())),
("web".into(), RootKind::Source, None),
]
);
}
#[test]
fn gradle_sync_roots_keep_plain_gradle_for_ancestors_and_fs_roots() {
let tmp = tempfile::tempdir().unwrap();
let composite = dunce::canonicalize(tmp.path()).unwrap();
let app = composite.join("app");
let lib = app.join("lib");
let cache = composite.join("cache");
let ext_posix = composite.join("ext-posix/src/main/java");
let ext_win = composite.join("ext-win/src/main/java");
for d in [
composite.join("src/main/java"),
app.join("src/main/java"),
lib.join("src/main/java"),
ext_posix.clone(),
ext_win.clone(),
cache.clone(),
] {
std::fs::create_dir_all(d).unwrap();
}
let s = |p: PathBuf| p.to_string_lossy().into_owned();
// Opened at `composite/app` while Gradle discovers parent `composite/settings.gradle`
// (so `composite` is an ancestor of `root`), plus external roots owned by `/` or `D:/`.
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
{ "path": ":", "dir": s(composite.clone()), "sourceSets": [
{ "name": "main", "test": false, "src": [s(composite.join("src/main/java"))], "res": [] } ] },
{ "path": ":app", "dir": s(app.clone()), "sourceSets": [
{ "name": "main", "test": false, "src": [s(app.join("src/main/java"))], "res": [] } ] },
{ "path": ":app:lib", "dir": s(lib.clone()), "sourceSets": [
{ "name": "main", "test": false, "src": [s(lib.join("src/main/java"))], "res": [] } ] },
{ "path": ":posix-root", "dir": "/", "sourceSets": [
{ "name": "main", "test": false, "src": [s(ext_posix.clone())], "res": [] } ] },
{ "path": ":win-drive", "dir": "D:/", "sourceSets": [
{ "name": "main", "test": false, "src": [s(ext_win.clone())], "res": [] } ] },
]});
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
std::fs::write(app.join("build.gradle"), "").unwrap();
let out = with_gradle_roots(&app, &cache, &Default::default(), &[]);
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.detected_from.as_deref())).collect();
assert_eq!(
got,
[
(abs(composite.join("src/main/java")), Some("Gradle")),
("src/main/java".into(), Some("Gradle")),
("lib/src/main/java".into(), Some("lib/Gradle")),
(abs(ext_posix), Some("Gradle")),
(abs(ext_win), Some("Gradle")),
]
);
}
#[cfg(unix)]
#[test]
fn gradle_sync_roots_canonicalize_symlinked_project_dirs() {
let tmp = tempfile::tempdir().unwrap();
let ws = dunce::canonicalize(tmp.path()).unwrap();
let real = ws.join("real");
let link = ws.join("link");
let app = real.join("app");
let lib = app.join("lib");
let cache = ws.join("cache");
for d in [real.join("src/main/java"), app.join("src/main/java"), lib.join("src/main/java"), cache.clone()] {
std::fs::create_dir_all(d).unwrap();
}
std::os::unix::fs::symlink(&real, &link).unwrap();
let s = |p: PathBuf| p.to_string_lossy().into_owned();
// Opened at canonical `real/app`, while Gradle reports projects through the symlink `link`.
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
{ "path": ":", "dir": s(link.clone()), "sourceSets": [
{ "name": "main", "test": false, "src": [s(real.join("src/main/java"))], "res": [] } ] },
{ "path": ":app", "dir": s(link.join("app")), "sourceSets": [
{ "name": "main", "test": false, "src": [s(app.join("src/main/java"))], "res": [] } ] },
{ "path": ":app:lib", "dir": s(link.join("app/lib")), "sourceSets": [
{ "name": "main", "test": false, "src": [s(lib.join("src/main/java"))], "res": [] } ] },
]});
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
std::fs::write(app.join("build.gradle"), "").unwrap();
let out = with_gradle_roots(&app, &cache, &Default::default(), &[]);
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.detected_from.as_deref())).collect();
assert_eq!(
got,
[
(abs(real.join("src/main/java")), Some("Gradle")),
("src/main/java".into(), Some("Gradle")),
("lib/src/main/java".into(), Some("lib/Gradle")),
]
);
}
}
#[cfg(test)]
@@ -2612,9 +2753,20 @@ mod agent_worktree_tests {
#[cfg(test)]
mod composer_tests {
use super::composer_changed;
use super::{composer_changed, ts_config_changed};
use std::path::{Path, PathBuf};
#[test]
fn tsconfig_and_jsconfig_files_count_outside_node_modules() {
let changed = |p: &str| ts_config_changed([PathBuf::from(p)].iter());
for yes in ["/p/tsconfig.json", "/p/apps/web/jsconfig.json", "/p/tsconfig.base.json"] {
assert!(changed(yes), "{yes}");
}
for no in ["/p/package.json", "/p/tsconfig.ts", "/p/node_modules/x/tsconfig.json"] {
assert!(!changed(no), "{no}");
}
}
#[test]
fn only_the_roots_own_composer_json_counts() {
let root = Path::new("/work/app");
+90 -15
Переглянути файл
@@ -77,6 +77,31 @@ pub struct ChannelMessage {
pub data: Value,
}
/// Streaming lifecycle signal delivered through a [`ChannelSink`].
#[derive(Debug, Clone)]
pub enum ChannelSignal {
/// Emitted when a command claims a `{ "$channel": id }` argument.
Opened(u64),
/// One serialized streaming payload.
Data(ChannelMessage),
/// Emitted automatically when the last clone of the command's channel emitter is dropped.
End(u64),
}
/// Delivers streaming values and lifecycle signals from a command back to its caller.
pub type ChannelSink = Arc<dyn Fn(ChannelSignal) + Send + Sync>;
struct ChannelDropGuard {
id: u64,
sink: ChannelSink,
}
impl Drop for ChannelDropGuard {
fn drop(&mut self) {
(self.sink)(ChannelSignal::End(self.id));
}
}
/// Holds the active client [`Peer`]: once for `--stdio` ([`OnceLock<Peer>`]) or
/// rebound across client reconnects for a persistent daemon ([`PeerSlot`]).
pub trait PeerHandle: Send + Sync + 'static {
@@ -141,7 +166,7 @@ pub struct Call {
pub host: Arc<Host>,
pub window: String,
pub args: Value,
peer: Arc<dyn PeerHandle>,
channel_sink: ChannelSink,
}
impl Call {
@@ -165,19 +190,26 @@ impl Call {
.and_then(|v| v.get("$channel"))
.and_then(Value::as_u64)
.ok_or_else(|| IdeError::invalid(format!("argument {name}: expected a channel")))?;
let peer = self.peer.clone();
Ok(Arc::new(move |data: T| {
let Some(peer) = peer.current() else { return };
match serde_json::to_value(&data) {
Ok(data) => {
let _ = peer.notify("channel", ChannelMessage { id, data });
}
Err(e) => tracing::warn!("channel {id}: {e}"),
}
let sink = self.channel_sink.clone();
sink(ChannelSignal::Opened(id));
let guard = ChannelDropGuard { id, sink };
Ok(Arc::new(move |data: T| match serde_json::to_value(&data) {
Ok(data) => (guard.sink)(ChannelSignal::Data(ChannelMessage { id: guard.id, data })),
Err(e) => tracing::warn!("channel {}: {e}", guard.id),
}))
}
}
fn peer_channel_sink(peer: Arc<dyn PeerHandle>) -> ChannelSink {
Arc::new(move |signal: ChannelSignal| {
if let ChannelSignal::Data(msg) = signal
&& let Some(peer) = peer.current()
{
let _ = peer.notify("channel", msg);
}
})
}
type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
type HandlerFn = Arc<dyn Fn(Call) -> BoxFuture<IdeResult<Value>> + Send + Sync>;
@@ -188,24 +220,45 @@ pub struct Dispatcher {
}
impl Dispatcher {
pub fn add<F, Fut, T>(&mut self, name: &'static str, trust: TrustClass, f: F) -> &mut Self
fn wrap_handler<F, Fut, T>(f: F) -> HandlerFn
where
F: Fn(Call) -> Fut + Send + Sync + 'static,
Fut: Future<Output = IdeResult<T>> + Send + 'static,
T: Serialize,
{
let f = Arc::new(f);
let handler: HandlerFn = Arc::new(move |call| {
Arc::new(move |call| {
let fut = f(call);
Box::pin(async move {
let value = fut.await?;
serde_json::to_value(value).map_err(|e| IdeError::internal(e.to_string()))
})
});
})
}
pub fn add<F, Fut, T>(&mut self, name: &'static str, trust: TrustClass, f: F) -> &mut Self
where
F: Fn(Call) -> Fut + Send + Sync + 'static,
Fut: Future<Output = IdeResult<T>> + Send + 'static,
T: Serialize,
{
let handler = Self::wrap_handler(f);
assert!(self.handlers.insert(name, (trust, handler)).is_none(), "command {name} is registered twice");
self
}
/// Registers or replaces `name` (used by the web server to add shell-level hooks such as recent-project tracking).
pub fn replace<F, Fut, T>(&mut self, name: &'static str, trust: TrustClass, f: F) -> &mut Self
where
F: Fn(Call) -> Fut + Send + Sync + 'static,
Fut: Future<Output = IdeResult<T>> + Send + 'static,
T: Serialize,
{
let handler = Self::wrap_handler(f);
self.handlers.insert(name, (trust, handler));
self
}
pub fn commands(&self) -> Vec<&'static str> {
let mut out: Vec<_> = self.handlers.keys().copied().collect();
out.sort_unstable();
@@ -223,6 +276,23 @@ impl Dispatcher {
ops::register_domains(&mut d);
d
}
/// Invokes a command asynchronously with trust enforcement and a caller-supplied channel sink.
pub async fn invoke(
&self,
host: Arc<Host>,
window: String,
cmd: &str,
args: Value,
channel_sink: ChannelSink,
) -> IdeResult<Value> {
let Some((trust, handler)) = self.handlers.get(cmd).cloned() else {
return Err(IdeError::unavailable(format!("command {cmd} is not available")));
};
host.authorize(&window, trust)?;
let call = Call { host, window, args, channel_sink };
handler(call).await
}
}
/// Serves `host` over `reader` / `writer` until the client disconnects.
@@ -346,7 +416,7 @@ struct ServerHandler {
daemon: Option<(ide_core::CancellationToken, RemoteIdlePolicy)>,
}
fn server_info(idle_policy: Option<RemoteIdlePolicy>) -> ServerInfo {
pub(crate) fn server_info(idle_policy: Option<RemoteIdlePolicy>) -> ServerInfo {
ServerInfo {
version: env!("CARGO_PKG_VERSION").into(),
protocol: PROTOCOL_VERSION,
@@ -378,7 +448,12 @@ impl Handler for ServerHandler {
return Err((codes::METHOD_NOT_FOUND, format!("command {} is not available remotely", call.cmd)));
};
self.host.authorize(&call.window, trust).map_err(error_reply)?;
let c = Call { host: self.host.clone(), window: call.window, args: call.args, peer: self.peer.clone() };
let c = Call {
host: self.host.clone(),
window: call.window,
args: call.args,
channel_sink: peer_channel_sink(self.peer.clone()),
};
// Requests run on blocking-capable threads: wait for the command here.
self.host.runtime.block_on(handler(c)).map_err(error_reply)
}
+10
Переглянути файл
@@ -267,6 +267,9 @@ impl crate::Host {
if let Some(phpstan) = &project.phpstan {
phpstan.interrupt();
}
if let Some(watch) = &project.tsc_watch {
watch.apply(&self.runtime);
}
if !trusted {
if let Some(plugins) = self.plugin_host() {
plugins.withdraw_project_run_targets(&project.root);
@@ -279,11 +282,18 @@ impl crate::Host {
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
}
self.environment.direnv_opened(&project.root, &project.sink);
{
let p = project.clone();
self.runtime.spawn_blocking(move || {
crate::github_auth::apply_to_project(&p);
});
}
project.lsp.set_execution_allowed(true);
project.lsp.prewarm_java_configuration();
} else {
self.environment.project_closed();
self.environment.direnv_closed(&project.root);
crate::github_auth::clear_project_env(&project);
project.agents.shutdown();
project.flutter.stop();
project.devtools.stop();
+251
Переглянути файл
@@ -0,0 +1,251 @@
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation, Imports) as the TypeScript
//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for
//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes:
//! quick fixes, auto-imports, refactorings and organize imports.
use ide_core::editor_settings::LanguageCodeStyle;
use ide_core::settings::Settings;
use ide_language::LanguageServerConfig;
use ide_workspace::EditorConfig;
use serde_json::{Map, Value, json};
use std::collections::HashMap;
use std::path::Path;
const SERVERS: [&str; 2] = ["vtsls", "typescript-language-server"];
/// tsserver's space options the Spaces tab sets, with the IntelliJ `.editorconfig` property
/// (`ij_<language>_<name>`) that sets the same thing.
const SPACES: [(&str, Option<&str>); 14] = [
("insertSpaceAfterCommaDelimiter", Some("space_after_comma")),
("insertSpaceAfterSemicolonInForStatements", Some("space_after_semicolon")),
("insertSpaceBeforeAndAfterBinaryOperators", None),
("insertSpaceAfterKeywordsInControlFlowStatements", None),
("insertSpaceAfterFunctionKeywordForAnonymousFunctions", Some("space_before_function_left_parenth")),
("insertSpaceBeforeFunctionParenthesis", Some("space_before_method_parentheses")),
("insertSpaceAfterConstructor", None),
("insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis", None),
("insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets", Some("spaces_within_brackets")),
("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces", Some("spaces_within_object_literal_braces")),
("insertSpaceAfterOpeningAndBeforeClosingEmptyBraces", None),
("insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces", Some("spaces_within_interpolation_expressions")),
("insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces", None),
("insertSpaceAfterTypeAssertion", None),
];
/// Adds the code style of JavaScript and TypeScript to a TypeScript server's settings. A file's
/// `.editorconfig` comes first, as in the editor (resolved for the server root's `index.ts` /
/// `index.js`: the servers take one configuration per project); the server's own settings win.
pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &Settings) {
if !SERVERS.contains(&cfg.name.as_str()) {
return;
}
let code_style = &settings.editor.code_style;
let editorconfig = code_style.editorconfig.then(EditorConfig::new);
let mut layer = Map::new();
for (language, ext) in [("typescript", "ts"), ("javascript", "js")] {
let pairs = editorconfig
.as_ref()
.and_then(|e| e.resolve_pairs(&server_root.join(format!("index.{ext}"))))
.unwrap_or_default();
let section = section(language, code_style.languages.get(language), &pairs);
layer.insert(language.into(), Value::Object(section));
}
let mut merged = Value::Object(layer);
if let Some(own) = cfg.settings.take() {
ide_sdk::apply::merge(&mut merged, own);
}
cfg.settings = Some(merged);
}
/// The `format` and `preferences` of one language's section.
fn section(
language: &str,
style: Option<&LanguageCodeStyle>,
editorconfig: &HashMap<String, String>,
) -> Map<String, Value> {
let get = |key: &str| editorconfig.get(key).map(|v| v.to_ascii_lowercase());
let flag = |name: &str| match get(&format!("ij_{language}_{name}")).as_deref() {
Some("true") => Some(true),
Some("false") => Some(false),
_ => None,
};
let pick = |value: Option<&String>, allowed: &[&str]| value.filter(|v| allowed.contains(&v.as_str())).cloned();
let mut format = Map::new();
for (key, ij) in SPACES {
if let Some(on) = ij.and_then(flag).or_else(|| style.and_then(|s| s.spaces.get(key).copied())) {
format.insert(key.into(), json!(on));
}
}
let semicolons = flag("use_semicolon_after_statement")
.map(|on| if on { "insert" } else { "remove" }.to_owned())
.or_else(|| pick(style.and_then(|s| s.semicolons.as_ref()), &["ignore", "insert", "remove"]));
if let Some(semicolons) = semicolons {
format.insert("semicolons".into(), json!(semicolons));
}
let quotes = pick(get("quote_type").as_ref(), &["auto", "single", "double"])
.or_else(|| flag("use_double_quotes").map(|on| if on { "double" } else { "single" }.to_owned()))
.or_else(|| pick(style.and_then(|s| s.quotes.as_ref()), &["auto", "single", "double"]));
let mut section = Map::new();
if !format.is_empty() {
section.insert("format".into(), Value::Object(format));
}
// vtsls reads VS Code's names (`quoteStyle`, `importModuleSpecifier`), typescript-language-server
// tsserver's (`quotePreference`, `importModuleSpecifierPreference`).
let mut preferences = Map::new();
if let Some(quotes) = quotes {
preferences.insert("quoteStyle".into(), json!(quotes));
preferences.insert("quotePreference".into(), json!(quotes));
}
let paths = ["shortest", "relative", "non-relative", "project-relative"];
if let Some(paths) = pick(style.and_then(|s| s.import_module_specifier.as_ref()), &paths) {
preferences.insert("importModuleSpecifier".into(), json!(paths));
preferences.insert("importModuleSpecifierPreference".into(), json!(paths));
}
let endings = ["auto", "minimal", "index", "js"];
if let Some(ending) = pick(style.and_then(|s| s.import_module_specifier_ending.as_ref()), &endings) {
preferences.insert("importModuleSpecifierEnding".into(), json!(ending));
}
// Sent even when empty: vtsls has no default for these, so a list left out keeps tsserver's
// previous one, and clearing it would only apply after a restart. `[]` excludes nothing.
let none = Vec::new();
let patterns = style.map_or(&none, |s| &s.auto_import_file_exclude_patterns);
let regexes = style.map_or(&none, |s| &s.auto_import_specifier_exclude_regexes);
preferences.insert("autoImportFileExcludePatterns".into(), json!(patterns));
preferences.insert("autoImportSpecifierExcludeRegexes".into(), json!(regexes));
section.insert("preferences".into(), Value::Object(preferences));
section
}
#[cfg(test)]
mod tests {
use super::*;
fn server(name: &str) -> LanguageServerConfig {
serde_json::from_value(json!({ "name": name, "command": name })).unwrap()
}
#[test]
fn code_style_reaches_typescript_and_javascript_sections() {
let mut settings = Settings::default();
let ts = LanguageCodeStyle {
semicolons: Some("remove".into()),
quotes: Some("single".into()),
spaces: [("insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces".into(), false)].into(),
..Default::default()
};
settings.editor.code_style.languages.insert("typescript".into(), ts);
let js = LanguageCodeStyle { semicolons: Some("insert".into()), ..Default::default() };
settings.editor.code_style.languages.insert("javascript".into(), js);
let dir = tempfile::tempdir().unwrap();
let mut cfg = server("vtsls");
cfg.settings = Some(json!({ "typescript": { "preferences": { "quoteStyle": "double" } } }));
configure(&mut cfg, dir.path(), &settings);
assert_eq!(
cfg.settings.unwrap(),
json!({
"typescript": {
"format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false },
// The server's own settings win.
"preferences": {
"quoteStyle": "double",
"quotePreference": "single",
"autoImportFileExcludePatterns": [],
"autoImportSpecifierExcludeRegexes": [],
},
},
"javascript": {
"format": { "semicolons": "insert" },
"preferences": { "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] },
},
})
);
let mut eslint = server("eslint");
configure(&mut eslint, dir.path(), &settings);
assert_eq!(eslint.settings, None);
let mut untouched = server("vtsls");
configure(&mut untouched, dir.path(), &Settings::default());
// Nothing set: the server's defaults, and empty exclusion lists so that clearing one reaches
// a running server.
let empty = json!({ "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] });
let empty = json!({ "typescript": { "preferences": empty }, "javascript": { "preferences": empty } });
assert_eq!(untouched.settings, Some(empty));
}
#[test]
fn import_style_reaches_the_preferences_of_each_language() {
let mut settings = Settings::default();
let ts = LanguageCodeStyle {
import_module_specifier: Some("relative".into()),
import_module_specifier_ending: Some("index".into()),
auto_import_file_exclude_patterns: vec!["**/index.ts".into()],
auto_import_specifier_exclude_regexes: vec!["^node:".into()],
..Default::default()
};
settings.editor.code_style.languages.insert("typescript".into(), ts);
let js = LanguageCodeStyle {
import_module_specifier: Some("non-relative".into()),
// Not a tsserver value: left out.
import_module_specifier_ending: Some("ts".into()),
..Default::default()
};
settings.editor.code_style.languages.insert("javascript".into(), js);
let dir = tempfile::tempdir().unwrap();
let mut cfg = server("vtsls");
configure(&mut cfg, dir.path(), &settings);
assert_eq!(
cfg.settings.unwrap(),
json!({
"typescript": { "preferences": {
"importModuleSpecifier": "relative",
"importModuleSpecifierPreference": "relative",
"importModuleSpecifierEnding": "index",
"autoImportFileExcludePatterns": ["**/index.ts"],
"autoImportSpecifierExcludeRegexes": ["^node:"],
} },
"javascript": { "preferences": {
"importModuleSpecifier": "non-relative",
"importModuleSpecifierPreference": "non-relative",
"autoImportFileExcludePatterns": [],
"autoImportSpecifierExcludeRegexes": [],
} },
})
);
}
#[test]
fn editorconfig_comes_first() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join(".editorconfig"),
"root = true\n[*.ts]\nquote_type = double\nij_typescript_use_semicolon_after_statement = false\n\
ij_typescript_space_after_comma = false\n[*.js]\nij_javascript_use_double_quotes = false\n",
)
.unwrap();
let mut settings = Settings::default();
let ts = LanguageCodeStyle {
semicolons: Some("insert".into()),
quotes: Some("single".into()),
..Default::default()
};
settings.editor.code_style.languages.insert("typescript".into(), ts);
let mut cfg = server("typescript-language-server");
configure(&mut cfg, dir.path(), &settings);
let s = cfg.settings.unwrap();
assert_eq!(
s["typescript"]["format"],
json!({ "semicolons": "remove", "insertSpaceAfterCommaDelimiter": false })
);
assert_eq!(s["typescript"]["preferences"]["quotePreference"], "double");
assert_eq!(s["javascript"]["preferences"]["quoteStyle"], "single");
settings.editor.code_style.editorconfig = false;
let mut cfg = server("vtsls");
configure(&mut cfg, dir.path(), &settings);
let s = cfg.settings.unwrap();
assert_eq!(s["typescript"]["format"], json!({ "semicolons": "insert" }));
assert_eq!(s["javascript"].get("format"), None);
}
}
+359
Переглянути файл
@@ -0,0 +1,359 @@
//! Problems › TypeScript project errors (`languages.typescript.watchProblems`): the project's own
//! `tsc --watch` per root `tsconfig.json` -> `tsc` diagnostics. Files open in an editor keep only
//! the language server's errors, so the watcher's are held back for them until they close.
use ide_core::{CancellationToken, Diagnostic, IdeEvent, SharedSink};
use ide_workspace::SettingsStore;
use ide_workspace::documents::{DocumentInfo, DocumentObserver};
use parking_lot::Mutex;
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
const SOURCE: &str = "tsc";
/// How deep below the project the walk looks for `tsconfig.json` (`apps/web/tsconfig.json` is 3).
const MAX_DEPTH: usize = 4;
/// Folders whose configurations are not the project's own: test inputs and samples, often
/// broken on purpose.
const SKIPPED: [&str; 6] = ["node_modules", "fixtures", "__fixtures__", "testdata", "examples", "example"];
/// The `tsconfig.json` files of the project, without the ones in ignored (`.gitignore`), hidden,
/// excluded (`excludes`) or [`SKIPPED`] folders.
fn configs(root: &Path, excludes: &[String]) -> Vec<PathBuf> {
let excludes = ide_vfs::ExcludeMatcher::new(excludes);
let base = root.to_path_buf();
let mut walk = ignore::WalkBuilder::new(root);
walk.max_depth(Some(MAX_DEPTH)).require_git(ide_core::ignored::inside_git_repo(root)).follow_links(false);
walk.filter_entry(move |entry| {
let skipped = entry.file_type().is_some_and(|t| t.is_dir())
&& entry.file_name().to_str().is_some_and(|name| SKIPPED.contains(&name));
!skipped && entry.path().strip_prefix(&base).is_ok_and(|rel| !excludes.is_match(rel))
});
let mut found: Vec<PathBuf> = walk
.build()
.flatten()
.filter(|e| e.file_name() == "tsconfig.json" && e.file_type().is_some_and(|t| t.is_file()))
.map(ignore::DirEntry::into_path)
.collect();
found.sort();
found
}
pub(crate) struct TscWatch {
root: PathBuf,
settings: Arc<SettingsStore>,
sink: SharedSink,
trusted: Arc<AtomicBool>,
state: Mutex<State>,
}
#[derive(Default)]
struct State {
/// The running watchers, cancelled to stop them.
running: Option<CancellationToken>,
/// The project closed: nothing starts again.
closed: bool,
/// The last compilation's diagnostics of each root configuration.
results: BTreeMap<PathBuf, BTreeMap<PathBuf, Vec<Diagnostic>>>,
/// Files open in an editor.
open: HashSet<PathBuf>,
/// What the UI was last sent.
shown: BTreeMap<PathBuf, Vec<Diagnostic>>,
}
impl State {
/// Every root's diagnostics of the files not open, a problem two roots report listed once.
fn wanted(&self) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
let mut out: BTreeMap<PathBuf, Vec<Diagnostic>> = BTreeMap::new();
for files in self.results.values() {
for (path, items) in files.iter().filter(|(p, _)| !self.open.contains(*p)) {
let list = out.entry(path.clone()).or_default();
for d in items {
if !list.iter().any(|o| o.range == d.range && o.message == d.message) {
list.push(d.clone());
}
}
}
}
out
}
/// The files whose diagnostics change, with their new list (empty clears them).
fn refresh(&mut self) -> Vec<(PathBuf, Vec<Diagnostic>)> {
let wanted = self.wanted();
let mut changes: Vec<(PathBuf, Vec<Diagnostic>)> =
self.shown.keys().filter(|p| !wanted.contains_key(*p)).map(|p| (p.clone(), Vec::new())).collect();
changes.extend(
wanted.iter().filter(|(p, items)| self.shown.get(*p) != Some(items)).map(|(p, i)| (p.clone(), i.clone())),
);
self.shown = wanted;
changes
}
}
impl TscWatch {
pub(crate) fn new(
root: PathBuf,
settings: Arc<SettingsStore>,
sink: SharedSink,
trusted: Arc<AtomicBool>,
) -> Arc<Self> {
Arc::new(Self { root, settings, sink, trusted, state: Mutex::new(State::default()) })
}
/// Starts the watchers when the option is on in a trusted project, else stops them and
/// clears their errors. Called on open, on a settings change and on a trust change.
pub(crate) fn apply(self: &Arc<Self>, runtime: &tokio::runtime::Handle) {
let wanted =
self.trusted.load(Ordering::Acquire) && self.settings.effective().languages.typescript.watch_problems;
if !wanted {
return self.halt(false);
}
let mut state = self.state.lock();
if !state.closed && state.running.is_none() {
let cancel = CancellationToken::new();
state.running = Some(cancel.clone());
let this = self.clone();
runtime.spawn_blocking(move || this.start(&cancel));
}
}
/// The project closed.
pub(crate) fn stop(&self) {
self.halt(true);
}
fn halt(&self, closed: bool) {
let mut state = self.state.lock();
state.closed |= closed;
if let Some(cancel) = state.running.take() {
cancel.cancel();
state.results.clear();
self.publish(&mut state);
}
}
/// One thread per root configuration, each running its `tsc --watch` until `cancel`.
fn start(self: &Arc<Self>, cancel: &CancellationToken) {
let excludes = self.settings.effective().exclude_globs();
for config in ide_build::compile::tsc_watch_roots(configs(&self.root, &excludes)) {
if cancel.is_cancelled() {
return;
}
let (this, cancel) = (self.clone(), cancel.clone());
std::thread::spawn(move || this.watch(&config, &cancel));
}
}
fn watch(&self, config: &Path, cancel: &CancellationToken) {
let result = ide_build::compile::tsc_watch(&self.root, config, cancel, |messages| {
tracing::debug!(config = %config.display(), messages = messages.len(), "tsc --watch compiled");
let mut files = ide_build::compile::diagnostics_from(&messages, SOURCE);
// Messages about the scratch configurations or files outside the project.
files.retain(|path, _| path.starts_with(&self.root));
self.compiled(config, files, cancel);
});
match result {
Ok(()) => tracing::debug!(config = %config.display(), "tsc --watch ended"),
Err(e) => tracing::debug!(config = %config.display(), %e, "tsc --watch did not run"),
}
// Without a watcher its errors would go stale.
self.compiled(config, BTreeMap::new(), cancel);
}
fn compiled(&self, config: &Path, files: BTreeMap<PathBuf, Vec<Diagnostic>>, cancel: &CancellationToken) {
let mut state = self.state.lock();
// Under the lock: `apply` cancels and clears under it, so a stopped watcher adds nothing.
if cancel.is_cancelled() {
return;
}
if files.is_empty() {
state.results.remove(config);
} else {
state.results.insert(config.to_path_buf(), files);
}
self.publish(&mut state);
}
/// Sends the changes, under the lock so they reach the UI in the order decided here.
fn publish(&self, state: &mut State) {
for (path, items) in state.refresh() {
self.sink.emit(IdeEvent::Diagnostics { path: path.into(), source: SOURCE.into(), items });
}
}
fn set_open(&self, path: &Path, open: bool) {
let mut state = self.state.lock();
let changed = if open { state.open.insert(path.to_path_buf()) } else { state.open.remove(path) };
if changed {
self.publish(&mut state);
}
}
}
impl DocumentObserver for TscWatch {
fn opened(&self, info: &DocumentInfo) {
self.set_open(&info.path.0, true);
}
fn closed(&self, _doc: ide_core::DocId, path: &Path) {
self.set_open(path, false);
}
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::{Pos, Range, Severity};
fn diag(line: u32, message: &str) -> Diagnostic {
Diagnostic {
range: Range::new(Pos::new(line, 0), Pos::new(line, 1)),
severity: Severity::Error,
message: message.into(),
source: Some(SOURCE.into()),
code: None,
unnecessary: false,
deprecated: false,
server: Some(SOURCE.into()),
}
}
fn files(entries: &[(&str, Vec<Diagnostic>)]) -> BTreeMap<PathBuf, Vec<Diagnostic>> {
entries.iter().map(|(p, d)| (PathBuf::from(p), d.clone())).collect()
}
#[test]
fn open_files_keep_only_the_language_servers_errors() {
let mut state = State::default();
let b = diag(0, "Type 'string' is not assignable to type 'number'.");
state
.results
.insert("/p/tsconfig.json".into(), files(&[("/p/b.ts", vec![b.clone()]), ("/p/c.ts", vec![diag(1, "c")])]));
// The same problem from a second root is listed once.
state.results.insert("/p/src/tsconfig.json".into(), files(&[("/p/b.ts", vec![b.clone()])]));
assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![b.clone()]), ("/p/c.ts".into(), vec![diag(1, "c")])]);
assert!(state.refresh().is_empty(), "nothing changed, nothing sent");
state.open.insert("/p/b.ts".into());
assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![])]);
state.open.remove(Path::new("/p/b.ts"));
assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![b])]);
// Fixed: the next compilation reports nothing for the files.
state.results.clear();
assert_eq!(state.refresh(), [("/p/b.ts".into(), vec![]), ("/p/c.ts".into(), vec![])]);
}
#[test]
fn configs_skip_ignored_excluded_and_sample_folders() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
for dir in
["", "apps/web", "test/fixtures/broken", "examples/demo", "generated", "vendor/lib", ".cache", "a/b/c/d"]
{
std::fs::create_dir_all(root.join(dir)).unwrap();
std::fs::write(root.join(dir).join("tsconfig.json"), "{}").unwrap();
}
std::fs::write(root.join(".gitignore"), "/vendor/\n").unwrap();
let found = configs(root, &["generated".into()]);
assert_eq!(found, [root.join("apps/web/tsconfig.json"), root.join("tsconfig.json")]);
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_option_starts_and_stops_the_projects_tsc() {
use std::os::unix::fs::PermissionsExt;
use std::time::{Duration, Instant};
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("p");
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::create_dir_all(root.join("node_modules/.bin")).unwrap();
std::fs::write(root.join("tsconfig.json"), "{}").unwrap();
std::fs::write(root.join("src/b.ts"), "export const b: number = a;\n").unwrap();
// Records its process, prints one compilation and keeps watching, like `tsc --watch`.
let tsc = root.join("node_modules/.bin/tsc");
std::fs::write(
&tsc,
"#!/bin/sh\necho $$ >> pids.txt\n\
echo 'src/b.ts(1,26): error TS2322: Type string is not assignable to type number.'\n\
echo '1:00:00 PM - Found 1 error. Watching for file changes.'\nexec sleep 60\n",
)
.unwrap();
std::fs::set_permissions(&tsc, std::fs::Permissions::from_mode(0o755)).unwrap();
let settings = Arc::new(SettingsStore::load(&tmp.path().join("config"), Some(&root)));
let events: Arc<Mutex<Vec<(PathBuf, usize)>>> = Arc::default();
let sink: SharedSink = Arc::new({
let events = events.clone();
move |e: IdeEvent| {
if let IdeEvent::Diagnostics { path, source, items } = e {
assert_eq!(source, SOURCE);
events.lock().push((path.0, items.len()));
}
}
});
let trusted = Arc::new(AtomicBool::new(true));
let watch = TscWatch::new(root.clone(), settings.clone(), sink, trusted.clone());
let runtime = tokio::runtime::Handle::current();
let b = root.join("src/b.ts");
let pids = || -> Vec<u32> {
std::fs::read_to_string(root.join("pids.txt"))
.unwrap_or_default()
.lines()
.filter_map(|l| l.parse().ok())
.collect()
};
let until = |what: &str, ok: &dyn Fn() -> bool| {
let deadline = Instant::now() + Duration::from_secs(10);
while !ok() {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
std::thread::sleep(Duration::from_millis(50));
}
};
let last = || events.lock().iter().rev().find(|(p, _)| *p == b).map(|(_, n)| *n);
let set = |on: bool| {
settings
.set(ide_workspace::settings::SettingsScope::Project, "languages.typescript.watchProblems", on.into())
.unwrap();
watch.apply(&runtime);
};
// Off by default: nothing runs.
watch.apply(&runtime);
tokio::time::sleep(Duration::from_millis(500)).await;
assert!(pids().is_empty() && events.lock().is_empty());
set(true);
until("the error of b.ts", &|| last() == Some(1));
let first = pids()[0];
// Applying again (another setting changed) keeps the one watcher.
watch.apply(&runtime);
tokio::time::sleep(Duration::from_millis(300)).await;
assert_eq!(pids(), [first]);
set(false);
assert_eq!(last(), Some(0), "turning it off clears its errors at once");
until("tsc to stop", &|| !ide_core::process::process_alive(first));
// Restricted Mode stops it too, and trusting the project starts it again.
set(true);
until("a second tsc", &|| pids().len() == 2 && last() == Some(1));
trusted.store(false, Ordering::Release);
watch.apply(&runtime);
assert_eq!(last(), Some(0));
until("tsc to stop", &|| !ide_core::process::process_alive(pids()[1]));
trusted.store(true, Ordering::Release);
watch.apply(&runtime);
until("a third tsc", &|| pids().len() == 3 && last() == Some(1));
// Closing the project stops it for good.
watch.stop();
assert_eq!(last(), Some(0));
until("tsc to stop", &|| !ide_core::process::process_alive(pids()[2]));
watch.apply(&runtime);
tokio::time::sleep(Duration::from_millis(500)).await;
assert_eq!(pids().len(), 3, "nothing starts after the project closed");
}
}
+502
Переглянути файл
@@ -0,0 +1,502 @@
//! Shell-level commands registered in web server mode alongside `Dispatcher::standard()`.
//!
//! Project-host commands (`#[command]`) already live in `ide-host::ops` and are served directly.
//! This module supplies the web equivalents of desktop shell commands (`app_info`, `languages`,
//! `recent_projects`, `window_take_launch`, `menu_model`, `light_edit_open`, workspace helpers,
//! HTTP client helpers, and benign no-ops for native-window-only commands).
use crate::Host;
use crate::catalogue::TrustClass::{self, Always, Trusted};
use crate::menu;
use crate::ops::project::ProjectInfo;
use crate::rpc::Dispatcher;
use ide_core::settings::Settings;
use ide_core::{IdeError, IpcPath, RequestId};
use ide_language::LanguageInfo;
use ide_workspace::{RecentProject, RecentProjectGroup, RecentProjects};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
/// Shared state for shell-level commands in a web server process.
pub struct WebShellState {
pub recent: RecentProjects,
/// Per-window pending launch (taken once by `window_take_launch`).
launches: Mutex<HashMap<String, PathBuf>>,
/// Default workspace directory configured via `--project` / `OPENIDEA_WORKSPACE_DIR`.
default_project: Option<PathBuf>,
/// Whether the default project should be auto-trusted on startup.
trust_default_project: bool,
}
impl WebShellState {
pub fn new(config_dir: &std::path::Path, default_project: Option<PathBuf>, trust_default_project: bool) -> Self {
Self {
recent: RecentProjects::load(config_dir),
launches: Mutex::new(HashMap::new()),
default_project,
trust_default_project,
}
}
/// Seeds a pending project launch for `window` (from URL `?project=...` or `--project`),
/// or the project the window already has open when its page reloads.
pub fn seed_launch(&self, host: &Host, window: &str, requested_project: Option<PathBuf>) {
if let Ok(project) = host.project(window) {
// A reloaded page gets the project the window still has: reopening it keeps its
// index, language servers and runs.
if !project.light {
self.launches.lock().insert(window.to_owned(), project.root.clone());
}
return;
}
let target = requested_project.or_else(|| self.default_project.clone());
if let Some(path) = target {
if self.trust_default_project
&& self.default_project.as_ref().is_some_and(|p| p == &path)
&& let Err(e) = host.trust.inherit(&path)
{
tracing::warn!("cannot trust {}: {e}", path.display());
}
self.launches.lock().insert(window.to_owned(), path);
}
}
pub fn take_launch(&self, window: &str) -> Option<PathBuf> {
self.launches.lock().remove(window)
}
pub fn record_project(&self, project: &crate::Project) {
if !project.light
&& let Err(e) = crate::ops::project::record_recent(&self.recent, project)
{
tracing::warn!("cannot record {} in recent projects: {e}", project.root.display());
}
}
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct AppInfo {
version: String,
platform: String,
windows_build_number: Option<u32>,
config_dir: IpcPath,
data_dir: IpcPath,
wayland: bool,
window_buttons: ide_core::platform::WindowButtonLayout,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct BuildInfo {
version: String,
build: String,
profile: String,
os: String,
arch: String,
tauri: String,
updates: bool,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct CloseContext {
quitting: bool,
windows: u32,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct OpenProject {
name: String,
root: PathBuf,
current: bool,
remote: Option<Value>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct LocalDataInfo {
current: String,
default_dir: String,
custom_root: Option<String>,
env_override: bool,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct LogLocation {
dir: IpcPath,
file: Option<IpcPath>,
}
/// The menu bar the browser draws: the desktop spec as on Windows and Linux, without the
/// update check (updates are managed with the server).
fn web_menu_model(recent: &[RecentProject]) -> Vec<menu::MenuNode> {
let spec = menu::without_action(menu::spec(menu::Os::Linux), "app.checkForUpdates");
menu::model(&spec, &menu::recent_items(recent, &[], dirs::home_dir().as_deref()), &menu::MenuConfig::default())
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum LogLevel {
Error,
Warn,
Info,
Debug,
}
/// Registers all web-mode shell commands onto `dispatcher` (which should already contain
/// `Dispatcher::standard()`).
pub fn register(dispatcher: &mut Dispatcher, shell: Arc<WebShellState>) {
// Wrap `open_project` so opened projects are recorded in RecentProjects.
let s = shell.clone();
dispatcher.replace("open_project", TrustClass::Always, move |c| {
let s = s.clone();
async move {
let path: PathBuf = c.arg("path")?;
let project = crate::ops::project::open(&c.host, &c.window, &path).await?;
s.record_project(&project);
Ok(crate::ops::project::info(&project))
}
});
// App info & metadata.
dispatcher.add("app_info", TrustClass::Always, |c| async move {
Ok(AppInfo {
version: env!("CARGO_PKG_VERSION").into(),
platform: std::env::consts::OS.into(),
windows_build_number: None,
config_dir: c.host.config_dir.clone().into(),
data_dir: c.host.data_dir.clone().into(),
wayland: false,
window_buttons: ide_core::platform::WindowButtonLayout { left: vec![], right: vec![] },
})
});
dispatcher.add("app_build_info", TrustClass::Always, |_| async move {
Ok(BuildInfo {
version: env!("CARGO_PKG_VERSION").into(),
build: option_env!("OPENIDEA_BUILD").unwrap_or("web").into(),
profile: if cfg!(debug_assertions) { "debug" } else { "release" }.into(),
os: std::env::consts::OS.into(),
arch: std::env::consts::ARCH.into(),
tauri: "web".into(),
updates: false,
})
});
dispatcher.add("app_log_location", TrustClass::Always, |c| async move {
Ok(LogLocation { dir: c.host.local_data_dir.join("logs").into(), file: None })
});
dispatcher.add("app_update_status", TrustClass::Always, |_| async move {
Ok(json!({ "lastChecked": null, "checking": false }))
});
dispatcher.add("app_update_announcement", TrustClass::Always, |_| async move { Ok(false) });
dispatcher.add("app_update_window_ready", TrustClass::Always, |_| async move { Ok(Value::Null) });
dispatcher.add("app_check_update", TrustClass::Always, |_| async move {
Err::<Value, _>(IdeError::unavailable("Software updates are managed externally in web server mode"))
});
dispatcher.add("app_release_notes", TrustClass::Always, |_| async move { Ok(Value::Null) });
dispatcher.add("app_quit", TrustClass::Always, |_| async move { Ok(Value::Null) });
dispatcher.add("app_cancel_quit", TrustClass::Always, |_| async move { Ok(Value::Null) });
dispatcher.add("app_restart", TrustClass::Always, |_| async move { Ok(Value::Null) });
dispatcher.add("languages", TrustClass::Always, |c| async move {
Ok(c.host.languages.all().iter().map(LanguageInfo::from).collect::<Vec<_>>())
});
dispatcher.add("log_frontend", TrustClass::Always, |c| async move {
let level: LogLevel = c.arg("level")?;
let message: String = c.arg("message")?;
match level {
LogLevel::Error => tracing::error!(target: "frontend", "{message}"),
LogLevel::Warn => tracing::warn!(target: "frontend", "{message}"),
LogLevel::Info => tracing::info!(target: "frontend", "{message}"),
LogLevel::Debug => tracing::debug!(target: "frontend", "{message}"),
}
Ok(Value::Null)
});
// Recent projects & groups.
let s = shell.clone();
dispatcher.add("recent_projects", TrustClass::Always, move |c| {
let s = s.clone();
async move {
let items = s.recent.list();
c.host
.blocking(move || Ok(ide_workspace::recent::with_live_branches(items)))
.await
.or_else(|_| Ok(s.recent.list()))
}
});
let s = shell.clone();
dispatcher.add("remove_recent_project", TrustClass::Always, move |c| {
let s = s.clone();
async move {
let path: PathBuf = c.arg("path")?;
s.recent.remove(&path)?;
Ok(Value::Null)
}
});
let s = shell.clone();
dispatcher.add("recent_project_groups", TrustClass::Always, move |_| {
let s = s.clone();
async move { Ok(s.recent.groups()) }
});
let s = shell.clone();
dispatcher.add("set_recent_project_groups", TrustClass::Always, move |c| {
let s = s.clone();
async move {
let groups: Vec<RecentProjectGroup> = c.arg("groups")?;
s.recent.set_groups(groups)
}
});
// LightEdit.
dispatcher.add("light_edit_open", TrustClass::Always, |c| async move {
let path: PathBuf = c.arg("path")?;
let (host, window) = (c.host.clone(), c.window.clone());
let project = c.host.blocking(move || host.open_light(&window, &path)).await?;
Ok::<Settings, IdeError>(project.settings.effective())
});
dispatcher.add("light_edit_open_untitled", TrustClass::Always, |c| async move {
let (host, window) = (c.host.clone(), c.window.clone());
let project = c.host.blocking(move || host.open_light_empty(&window)).await?;
Ok::<Settings, IdeError>(project.settings.effective())
});
// Project rename & trust locations.
let s = shell.clone();
dispatcher.add("project_rename", TrustClass::Always, move |c| {
let s = s.clone();
async move {
let name: String = c.arg("name")?;
let project = crate::ops::project::rename(&c.host, &c.window, &name)?;
s.record_project(&project);
Ok::<ProjectInfo, IdeError>(crate::ops::project::info(&project))
}
});
dispatcher.add("project_trust_add_location", TrustClass::Always, |c| async move {
let path: PathBuf = c.arg("path")?;
c.host.trust.add_location(&path)?;
Ok(Value::Null)
});
// Launch & window lifecycle.
let s = shell.clone();
dispatcher.add("window_take_launch", TrustClass::Always, move |c| {
let s = s.clone();
async move {
let Some(project) = s.take_launch(&c.window) else {
return Ok(Value::Null);
};
Ok(json!({
"project": IpcPath::from(project),
"files": [],
"remote": null,
"settingsPage": null,
"newProjects": false,
"positions": [],
"comparison": null,
"diffWindow": null,
"diff": null,
"diffBeforeFiles": false,
"deployment": null,
"editor": null
}))
}
});
dispatcher.add("window_complete_launch", TrustClass::Always, |_| async move { Ok(Value::Null) });
dispatcher.add("window_open_projects", TrustClass::Always, |c| async move {
let current_root = c.host.project(&c.window).ok().filter(|p| !p.light).map(|p| p.root.clone());
let list: Vec<OpenProject> = c
.host
.projects()
.into_iter()
.filter(|p| !p.light)
.map(|p| OpenProject {
name: p.root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
current: current_root.as_ref() == Some(&p.root),
root: p.root.clone(),
remote: None,
})
.collect();
Ok(list)
});
dispatcher.add("window_open_project", TrustClass::Always, |_| async move { Ok(json!({ "kind": "current" })) });
dispatcher.add("window_open_files", TrustClass::Always, |c| async move {
let files: Vec<IpcPath> = c.arg("files")?;
Ok(files)
});
dispatcher.add("window_is_fullscreen", TrustClass::Always, |_| async move { Ok(false) });
dispatcher.add("window_close_context", TrustClass::Always, |_| async move {
Ok(CloseContext { quitting: false, windows: 1 })
});
for (noop, trust) in [
("window_set_titlebar_height", Always),
("window_set_smooth_scrolling", Always),
("window_flash_taskbar", Always),
("window_cycle", Always),
("menu_configure", Always),
("menu_refresh", Always),
("menu_set_disabled", Always),
("show_system_notification", Trusted),
("window_group_cancel_close", Always),
("window_group_restore", Always),
("plugin_subscribe", Always),
("plugin_activation_event", Trusted),
("plugin_set_theme_frame", Always),
] {
dispatcher.add(noop, trust, |_| async move { Ok(Value::Null) });
}
for (noop_false, trust) in [
("window_toggle_fullscreen", Always),
("window_toggle_zoom", Always),
("window_start_drag", Always),
("window_drag_files", Always),
("file_dialog_needs_gtk", Trusted),
("clipboard_has_files", Always),
("clipboard_has_image", Always),
] {
dispatcher.add(noop_false, trust, |_| async move { Ok(false) });
}
let s = shell.clone();
dispatcher.add("menu_model", TrustClass::Always, move |_| {
let s = s.clone();
async move { Ok(web_menu_model(&s.recent.list())) }
});
// Empty desktop-only collections so UI components render cleanly without errors.
for (empty_list, trust) in [
("window_group_current", Always),
("system_font_families", Always),
("system_probe_hotkeys", Trusted),
("wsl_distros", Always),
("web_browsers", Always),
("plugin_catalog", Always),
("plugin_installed_intellij_themes", Always),
("git_credentials", Always),
("android_devices", Trusted),
("clipboard_file_list", Always),
] {
dispatcher.add(empty_list, trust, |_| async move { Ok(Vec::<Value>::new()) });
}
for (null_opt, trust) in [
("wsl_resolve", Always),
("remote_current", Always),
("plugin_market_url", Always),
("clipboard_text", Trusted),
("clipboard_image", Always),
] {
dispatcher.add(null_opt, trust, |_| async move { Ok(Value::Null) });
}
dispatcher.add("plugin_list", TrustClass::Always, |_| async move {
Ok(json!({ "plugins": [], "activeTheme": null, "ui": [] }))
});
// Caches & LSP & Web & Workspace & HTTP helpers already available through ide-host dependencies.
dispatcher.add("caches_local_data_info", TrustClass::Trusted, |c| async move {
let current = c.host.local_data_dir.to_string_lossy().into_owned();
Ok(LocalDataInfo {
default_dir: current.clone(),
current,
custom_root: None,
env_override: std::env::var_os("OPENIDEA_SERVER_HOME").is_some(),
})
});
dispatcher.add("caches_schedule_invalidation", TrustClass::Always, |_| async move { Ok(Value::Null) });
dispatcher.add("lsp_restart_named", TrustClass::Trusted, |c| async move {
let name: String = c.arg("name")?;
crate::ops::lsp::lsp_restart_named(&c.host, &name).await?;
Ok(Value::Null)
});
dispatcher.add("web_serves_page", TrustClass::Trusted, |c| async move {
let url: String = c.arg("url")?;
Ok(crate::ops::web::serves_page(&url).await)
});
dispatcher.add("workspace_discover_projects", TrustClass::Always, |c| async move {
let request: RequestId = c.arg("request")?;
let folders: Vec<PathBuf> = c.arg("folders")?;
let cancel = c.host.begin_request(request);
let result = c.host.blocking(move || ide_workspace::project_discovery::discover(folders, &cancel)).await;
c.host.end_request(request);
result
});
dispatcher.add("workspace_create", TrustClass::Always, |c| async move {
let path: PathBuf = c.arg("path")?;
let name: String = c.arg("name")?;
let projects: Vec<PathBuf> = c.arg("projects")?;
c.host
.blocking(move || {
ide_workspace::workspace::Workspace::save(&path, &name, projects, true)?;
Ok(IpcPath::from(dunce::canonicalize(path)?))
})
.await
});
let s = shell.clone();
dispatcher.add("workspace_update", TrustClass::Always, move |c| {
let s = s.clone();
async move {
let name: String = c.arg("name")?;
let projects: Vec<PathBuf> = c.arg("projects")?;
let (host, window) = (c.host.clone(), c.window.clone());
let info =
c.host.blocking(move || crate::ops::project::save_workspace(&host, &window, &name, projects)).await?;
if let Ok(project) = c.host.project(&c.window) {
s.record_project(&project);
}
Ok(info)
}
});
let s = shell.clone();
dispatcher.add("workspace_attach", TrustClass::Always, move |c| {
let s = s.clone();
async move {
let path: PathBuf = c.arg("path")?;
let (host, window) = (c.host.clone(), c.window.clone());
let root = c.host.blocking(move || crate::ops::project::attach_workspace(&host, &window, &path)).await?;
if let Ok(project) = c.host.project(&c.window) {
s.record_project(&project);
}
Ok(root)
}
});
dispatcher.add("http_requests", TrustClass::Trusted, |c| async move {
let text: String = c.arg("text")?;
Ok(ide_http::parse::requests(&text))
});
dispatcher.add("http_from_curl", TrustClass::Trusted, |c| async move {
let command: String = c.arg("command")?;
Ok(ide_http::curl::from_curl(&command))
});
dispatcher.add("ssh_askpass_answer", TrustClass::Always, |_| async move { Ok(Value::Null) });
}
File diff suppressed because it is too large. Load diff
+1 -1
Переглянути файл
@@ -211,7 +211,7 @@ fn write_index(
/// The download sources setting with `mirror` as the GitHub proxy prefix (Tools › Download sources).
fn download_sources(mirror: &str) -> ide_core::settings::ToolDownloadSettings {
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into() }
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into(), ..Default::default() }
}
/// Security audit lead 5: an index entry's id and version name the download file,
+46
Переглянути файл
@@ -110,3 +110,49 @@ async fn external_history_is_readable_and_never_becomes_a_write_target() {
assert!(!deleted.exists());
host.close_project("main");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn revision_images_use_the_selected_git_blob_and_window() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("repo");
std::fs::create_dir(&root).unwrap();
git(&root, &["init", "-b", "main"]);
let old = root.join("old.PNG");
let new = root.join("new.webp");
std::fs::write(&old, [0x89, 0x00, 0xff]).unwrap();
std::fs::write(root.join("icon.svg"), b"<svg/>").unwrap();
std::fs::write(root.join("photo.jpeg"), [0xff, 0xd8]).unwrap();
git(&root, &["add", "."]);
git(&root, &["commit", "-m", "old image"]);
let first = git(&root, &["rev-parse", "HEAD"]);
git(&root, &["mv", "old.PNG", "new.webp"]);
std::fs::write(&new, [0xff, 0xfe]).unwrap();
git(&root, &["commit", "-am", "rename and change image"]);
std::fs::write(&new, [0x00, 0x80]).unwrap();
git(&root, &["add", "new.webp"]);
std::fs::write(&new, "working tree only").unwrap();
let host = Host::new(common::host_config(&base));
let read = |window, path: &Path, rev: &str| vcs::vcs_image_at(&host, window, path.to_owned(), rev.to_owned());
assert!(read("standalone", &old, &first).await.is_err());
vcs::vcs_open_external_log(&host, "standalone", root.clone()).await.unwrap();
assert_eq!(read("standalone", &old, &first).await.unwrap().as_deref(), Some("data:image/png;base64,iQD/"));
assert!(read("another-window", &old, &first).await.is_err());
host.trust.decide(&root, false, false).unwrap();
host.open_project("project", &root).unwrap();
assert_eq!(read("project", &new, "HEAD").await.unwrap().as_deref(), Some("data:image/webp;base64,//4="));
assert_eq!(read("project", &new, ":0").await.unwrap().as_deref(), Some("data:image/webp;base64,AIA="));
assert_eq!(read("project", &old, "HEAD").await.unwrap(), None);
assert_eq!(
read("project", &root.join("icon.svg"), "HEAD").await.unwrap().as_deref(),
Some("data:image/svg+xml;base64,PHN2Zy8+")
);
assert_eq!(
read("project", &root.join("photo.jpeg"), "HEAD").await.unwrap().as_deref(),
Some("data:image/jpeg;base64,/9g=")
);
assert!(read("project", &base.join("outside.png"), "HEAD").await.is_err());
assert!(read("project", &root.join("file.txt"), "HEAD").await.is_err());
}
+103
Переглянути файл
@@ -15,6 +15,109 @@ fn write(root: &Path, rel: &str, text: &str) {
fs::write(path, text).unwrap();
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pom_launch_uses_dependency_classpath_without_a_java_project() {
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
if !has_jdk || ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path()).is_none() {
eprintln!("skipped: needs JAVA_HOME and mvn");
return;
}
for (jdtls, delegate) in [(false, false), (true, false), (true, true)] {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
let pom = include_str!("../../ide-build/tests/fixtures/jbuild-maven/pom.xml")
.replace("</modules>", "<module>assembly</module></modules>");
write(&root, "pom.xml", &pom);
write(&root, "lib/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/lib/pom.xml"));
write(&root, "app/pom.xml", include_str!("../../ide-build/tests/fixtures/jbuild-maven/app/pom.xml"));
write(
&root,
"assembly/pom.xml",
r#"<project><modelVersion>4.0.0</modelVersion>
<parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent>
<artifactId>assembly</artifactId><packaging>pom</packaging>
<dependencies>
<dependency><groupId>t</groupId><artifactId>app</artifactId><version>1</version><scope>runtime</scope></dependency>
<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.36</version></dependency>
</dependencies></project>"#,
);
write(
&root,
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
);
let main = "package a;\npublic class A { public static void main(String[] args) throws Exception { Class.forName(\"org.slf4j.Logger\"); System.out.println(l.L.name()); } }\n";
write(&root, "app/src/main/java/a/A.java", main);
let global = SettingsStore::load(&base.join("config"), None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(
SettingsScope::Global,
&format!("languageServers.{server}.enabled"),
serde_json::json!(server == "jdtls" && jdtls),
)
.unwrap();
}
global.set(SettingsScope::Global, "languages.java.maven.delegateBuild", serde_json::json!(delegate)).unwrap();
global
.set(
SettingsScope::Global,
"languageServers.jdtls.command",
serde_json::json!(root.join("must-not-start-jdtls")),
)
.unwrap();
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
host.open_project("main", &root).unwrap();
let module = root.join("assembly");
assert_eq!(host.project("main").unwrap().lsp.java_served_by_jdtls(&module), jdtls);
for (policy, debug) in [
(BuildPolicy::Make, false),
(BuildPolicy::NoBuild, false),
(BuildPolicy::NoBuild, true),
(BuildPolicy::Rebuild, true),
] {
if policy == BuildPolicy::NoBuild {
write(&root, "app/src/main/java/a/A.java", "this must not be compiled");
} else {
write(&root, "app/src/main/java/a/A.java", main);
}
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
let info = ops::java::java_resolve_launch(
&host,
"main",
module.clone(),
false,
debug,
policy,
RequestId::next(),
ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event)),
)
.await
.unwrap_or_else(|e| panic!("jdtls={jdtls}, delegate={delegate}, policy={policy:?}: {e:?}"));
assert_eq!(info.build.is_some(), policy != BuildPolicy::NoBuild);
assert!(info.class_paths.iter().any(|p| p.ends_with("slf4j-api-1.7.36.jar")), "{:?}", info.class_paths);
assert!(!info.class_paths.iter().any(|p| p.contains("t.assembly/classes")), "{:?}", info.class_paths);
let cp = std::env::join_paths(&info.class_paths).unwrap();
let out = std::process::Command::new(info.java_exec.as_ref().expect("resolved Java executable"))
.arg("-cp")
.arg(cp)
.arg("a.A")
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "lib");
if policy == BuildPolicy::NoBuild {
assert!(!events.lock().unwrap().iter().any(|e| matches!(e, BuildEvent::Step { .. })));
}
}
host.shutdown().await;
}
}
/// A Maven launch compiles with the IDE's Java build (javac, outputs in the project cache)
/// and runs from its outputs. Needs `mvn` and a JDK (`JAVA_HOME`), else it is skipped.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+136
Переглянути файл
@@ -0,0 +1,136 @@
//! A Maven build in an excluded folder (a `.worktrees` checkout of the same repository)
//! repeats the coordinates of the project's own build. jdtls keeps one Eclipse project per
//! name, so it must not import the excluded copy: Go to Definition and implementations would
//! otherwise land in it instead of the project's sources.
//!
//! `#[ignore]`d because it needs jdtls on `PATH` and a JDK 21+:
//! `cargo test -p ide-host --test jdtls_excluded_checkout -- --ignored`.
use ide_core::{IdeEvent, Pos};
use ide_host::{Host, HostConfig, ops};
use ide_lsp::types::GotoKind;
use ide_workspace::settings::SettingsScope;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
const WINDOW: &str = "main";
fn pom(artifact: &str, deps: &str) -> String {
format!(
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\"><modelVersion>4.0.0</modelVersion>\
<groupId>com.x</groupId><artifactId>{artifact}</artifactId><version>1.0</version>\
<properties><maven.compiler.release>17</maven.compiler.release></properties>\
<dependencies>{deps}</dependencies></project>"
)
}
fn write_lib(dir: &Path) -> std::path::PathBuf {
let source = dir.join("src/main/java/lib/Foo.java");
std::fs::create_dir_all(source.parent().unwrap()).unwrap();
std::fs::write(dir.join("pom.xml"), pom("lib", "")).unwrap();
std::fs::write(&source, "package lib;\npublic class Foo {\n public static int answer() { return 42; }\n}\n")
.unwrap();
source
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "needs jdtls on PATH and a JDK 21+"]
async fn excluded_checkout_does_not_shadow_the_projects_own_build() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
// The opened folder has no build of its own; its builds sit side by side.
let root = base.join("workspace");
let own = write_lib(&root.join("lib"));
write_lib(&root.join(".worktrees/topic/lib"));
// Only in the checkout: imported at all, it shows the folder was scanned.
let extra = root.join(".worktrees/topic/extra");
std::fs::create_dir_all(&extra).unwrap();
std::fs::write(extra.join("pom.xml"), pom("extra", "")).unwrap();
let dep = "<dependency><groupId>com.x</groupId><artifactId>lib</artifactId><version>1.0</version></dependency>";
let app = root.join("app/src/main/java/app/App.java");
std::fs::create_dir_all(app.parent().unwrap()).unwrap();
std::fs::write(root.join("app/pom.xml"), pom("app", dep)).unwrap();
std::fs::write(
&app,
"package app;\nimport lib.Foo;\npublic class App {\n int run() { return Foo.answer(); }\n}\n",
)
.unwrap();
let events: Arc<Mutex<Vec<IdeEvent>>> = Arc::default();
let host = Arc::new(Host::new(HostConfig {
config_dir: base.join("app/config"),
data_dir: base.join("app/data"),
local_data_dir: base.join("app/data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new({
let events = events.clone();
move |_| {
let events = events.clone();
Arc::new(move |e: IdeEvent| events.lock().unwrap().push(e))
}
}),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
}));
host.trust.decide(&root, true, false).unwrap();
host.open_project(WINDOW, &root).unwrap();
let set =
|key: &str, value: &str| ops::project::set_settings(&host, WINDOW, SettingsScope::Project, key, value).unwrap();
set("projectStructure.excluded", r#"[".worktrees"]"#);
set("languages.java.jdtlsShared", "true");
let repo = base.join("m2").to_string_lossy().replace('\\', "/");
set("languages.java.maven.localRepository", &serde_json::to_string(&repo).unwrap());
let doc = ops::doc::doc_open(&host, WINDOW, app.clone()).await.unwrap().id;
// `Foo` in `return Foo.answer();`
let at = Pos::new(3, 24);
let deadline = Instant::now() + Duration::from_secs(420);
let found = loop {
let found = ops::lsp::lsp_goto(&host, WINDOW, doc, at, GotoKind::Definition).await;
if let Ok(locs) = &found
&& let Some(first) = locs.first()
{
break first.path.0.clone();
}
assert!(Instant::now() < deadline, "no definition for Foo: {found:?}");
tokio::time::sleep(Duration::from_millis(500)).await;
};
assert_eq!(found, own, "Foo resolved to the excluded checkout");
let imported = imported_projects(&base.join("app/data"));
assert!(imported.iter().any(|p| p.ends_with("/workspace/lib")), "lib not imported: {imported:?}");
assert!(!imported.iter().any(|p| p.contains("/.worktrees/")), "imported the excluded checkout: {imported:?}");
host.shutdown().await;
}
/// The folders of the Eclipse projects jdtls has imported, from its workspaces under `data`.
fn imported_projects(data: &Path) -> Vec<String> {
let mut found = Vec::new();
for entry in walkdir(data) {
if entry.file_name().is_some_and(|n| n == ".location")
&& let Ok(bytes) = std::fs::read(&entry)
{
let text = String::from_utf8_lossy(&bytes);
if let Some(at) = text.find("file:") {
let path: String = text[at + 5..].chars().take_while(|c| !c.is_control()).collect();
found.push(path.trim_end_matches('/').to_owned());
}
}
}
found.sort();
found
}
fn walkdir(dir: &Path) -> Vec<std::path::PathBuf> {
let mut out = Vec::new();
let mut stack = vec![dir.to_path_buf()];
while let Some(dir) = stack.pop() {
for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {
let path = entry.path();
if path.is_dir() { stack.push(path) } else { out.push(path) }
}
}
out
}
+208
Переглянути файл
@@ -542,6 +542,23 @@ impl Smoke {
self.restore(doc, &before).await;
}
/// Completion at the end of the typed line, once it offers the auto-import `control`, has
/// none labelled `label`.
async fn not_offered(&self, typed: Typed, label: &str, control: &str) {
let (doc, pos, before) = self.type_line(typed).await;
self.retry("completion without the item", self.warm_up, || async {
let list = ops::lsp::lsp_completion(&self.host, WINDOW, RequestId(7), doc, pos, None).await;
let labels: Vec<String> = match list {
Ok(l) => l.items.into_iter().map(|i| i.label).collect(),
Err(e) => vec![e.to_string()],
};
let has = |name: &str| labels.iter().any(|l| l == name);
if has(control) && !has(label) { Ok(()) } else { Err(labels) }
})
.await;
self.restore(doc, &before).await;
}
async fn organize_imports(&self, import: Typed, expect: Imports) {
let (doc, _, before) = self.type_line(import).await;
let typed = import.text.trim();
@@ -696,6 +713,197 @@ async fn typescript() {
smoke("typescript", TYPESCRIPT).await;
}
/// Code Style › TypeScript › Imports (#6072): each change reaches the running vtsls, and its
/// auto-imports follow it: relative or path alias, `/index` or not, and excluded files and
/// specifiers left out.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "language smoke: needs vtsls"]
async fn typescript_import_style() {
let checks = Checks {
files: &[
(
"tsconfig.json",
r#"{"compilerOptions": {"module": "ESNext", "moduleResolution": "Bundler", "strict": true,
"noEmit": true, "allowImportingTsExtensions": true, "paths": {"@/*": ["./src/*"]}},
"include": ["src"]}"#,
),
("src/lib/alpha.ts", "export function alphaHelper(): number {\n return 1;\n}\n"),
// Never excluded, and matching what is typed (tsserver offers only those): the
// auto-import candidates are in the completion list.
("src/lib/betaWord.ts", "export function betaWord(): number {\n return 3;\n}\n"),
("src/lib/hints.ts", "export function alphaHint(): number {\n return 4;\n}\n"),
("src/app/components/index.ts", "export function betaWidget(): number {\n return 2;\n}\n"),
("src/app/main.ts", "export const ready = true;\n"),
("src/app/other.ts", "export const other = true;\n"),
("src/app/third.ts", "export const third = true;\n"),
("src/app/fourth.ts", "export const fourth = true;\n"),
("src/app/fifth.ts", "export const fifth = true;\n"),
],
..TYPESCRIPT
};
let smoke = Smoke::start("typescript", &checks).await;
let set = |key: &str, value: &str| {
let scope = ide_workspace::settings::SettingsScope::Project;
let key = format!("editor.codeStyle.languages.typescript.{key}");
ops::project::settings_set(&smoke.host, WINDOW, scope, key, value.into()).unwrap();
};
let alpha = typed("src/app/main.ts", "export const ready", "alphaH");
let beta = typed("src/app/main.ts", "export const ready", "betaW");
let import = |typed, label, result| AutoImport { typed, label, result };
set("importModuleSpecifier", r#""relative""#);
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
set("importModuleSpecifier", r#""non-relative""#);
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
set("importModuleSpecifier", r#""relative""#);
set("importModuleSpecifierEnding", r#""index""#);
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
set("importModuleSpecifierEnding", r#""minimal""#);
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
// tsserver keeps the auto-import candidates of the file it last completed in until the
// program changes; other files see an exclusion at once.
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#);
smoke.not_offered(typed("src/app/other.ts", "export const other", "betaW"), "betaWidget", "betaWord").await;
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#);
smoke.not_offered(typed("src/app/third.ts", "export const third", "alphaH"), "alphaHelper", "alphaHint").await;
// Emptied lists reach the server too: the symbols are offered again.
set("autoImportFileExcludePatterns", "[]");
let beta = typed("src/app/fourth.ts", "export const fourth", "betaW");
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
set("autoImportSpecifierExcludeRegexes", "[]");
let alpha = typed("src/app/fifth.ts", "export const fifth", "alphaH");
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
}
/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any.
#[cfg(unix)]
fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> {
events.lock().unwrap().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path: p, source, items } if source == "tsc" && **p == *path => {
Some(items.iter().map(|d| d.message.clone()).collect())
}
_ => None,
})
}
/// Problems › TypeScript Project Errors (#6073): the project's own `tsc --watch` reports the error
/// an edit of one file causes in another that is not open, holds it back while that file is open,
/// clears it once fixed, checks a solution with project references as well, and writes nothing
/// into the project. TypeScript comes from `OPENIDEA_SMOKE_TYPESCRIPT` (a `typescript` package
/// folder), else the global npm install.
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "language smoke: needs typescript"]
async fn typescript_project_errors() {
let typescript = std::env::var_os("OPENIDEA_SMOKE_TYPESCRIPT").map_or_else(
|| {
let out = std::process::Command::new("npm").args(["root", "-g"]).output().expect("npm root -g");
PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()).join("typescript")
},
PathBuf::from,
);
assert!(typescript.join("bin/tsc").is_file(), "no TypeScript in {}", typescript.display());
let checks = Checks {
files: &[
// Fails from the start: its error marks the end of the first compilation.
("src/probe.ts", "export const probe: number = \"x\";\n"),
("packages/tsconfig.json", r#"{"files": [], "references": [{"path": "./core"}, {"path": "./app"}]}"#),
(
"packages/core/tsconfig.json",
r#"{"compilerOptions": {"composite": true, "strict": true, "outDir": "out"}}"#,
),
("packages/core/index.ts", "export const version: number = 1;\n"),
(
"packages/app/tsconfig.json",
r#"{"compilerOptions": {"composite": true, "strict": true, "outDir": "out"}, "references": [{"path": "../core"}]}"#,
),
(
"packages/app/index.ts",
"import { version } from \"../core/index\";\nexport const label: string = version;\n",
),
],
..TYPESCRIPT
};
let smoke = Smoke::start("typescript", &checks).await;
let root = smoke.root.clone();
std::fs::create_dir_all(root.join("node_modules/.bin")).unwrap();
std::os::unix::fs::symlink(&typescript, root.join("node_modules/typescript")).unwrap();
std::os::unix::fs::symlink("../typescript/bin/tsc", root.join("node_modules/.bin/tsc")).unwrap();
async fn wait(what: &str, ok: impl Fn() -> bool) {
let deadline = Instant::now() + Duration::from_secs(60);
while !ok() {
assert!(Instant::now() < deadline, "timed out waiting for {what}");
tokio::time::sleep(Duration::from_millis(200)).await;
}
}
let errors = |file: &str| tsc_errors(&smoke.events, &root.join(file));
let has = |file: &'static str, text: &'static str| {
move || errors(file).is_some_and(|e| e.iter().any(|m| m.contains(text)))
};
let clear = |file: &'static str| move || errors(file).is_some_and(|e| e.is_empty());
let set = |on: bool| {
let scope = ide_workspace::settings::SettingsScope::Project;
ops::project::settings_set(
&smoke.host,
WINDOW,
scope,
"languages.typescript.watchProblems".into(),
on.to_string(),
)
.unwrap();
};
set(true);
wait("the first compilation", has("src/probe.ts", "not assignable")).await;
wait("the solution's error", has("packages/app/index.ts", "not assignable to type 'string'")).await;
// Renaming an export in money.ts breaks index.ts, which is not open.
let money = root.join("src/money.ts");
let original = std::fs::read_to_string(&money).unwrap();
std::fs::write(&money, original.replace("export function formatMoney", "export function formatPrice")).unwrap();
wait("index.ts to break", has("src/index.ts", "formatMoney")).await;
assert_eq!(errors("src/money.ts"), None, "the edited file itself is fine");
// Open, it shows the language server's errors only; closed again, the watcher's.
let doc = ops::doc::doc_open(&smoke.host, WINDOW, root.join("src/index.ts")).await.unwrap();
wait("index.ts held back while open", clear("src/index.ts")).await;
ops::doc::doc_close(&smoke.host, WINDOW, doc.id).await.unwrap();
wait("index.ts back once closed", has("src/index.ts", "formatMoney")).await;
std::fs::write(&money, &original).unwrap();
// The fixture's own error (an unused function) stays.
let fixed =
move || errors("src/index.ts").is_some_and(|e| !e.is_empty() && !e.iter().any(|m| m.contains("formatMoney")));
wait("index.ts fixed", fixed).await;
set(false);
wait("every error cleared", || {
["src/probe.ts", "src/index.ts", "packages/app/index.ts"].into_iter().all(|f| clear(f)())
})
.await;
// A background check writes nothing into the project: no `.js`, `.d.ts` or `.tsbuildinfo`.
fn outputs(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in std::fs::read_dir(dir).unwrap().flatten() {
let path = entry.path();
if entry.file_name() == "node_modules" {
continue;
}
if path.is_dir() {
outputs(&path, out);
} else if [".js", ".d.ts", ".tsbuildinfo"].iter().any(|ext| path.to_string_lossy().ends_with(ext)) {
out.push(path);
}
}
}
let mut written = Vec::new();
outputs(&root, &mut written);
assert_eq!(written, Vec::<PathBuf>::new());
}
const PYTHON: Checks = Checks {
fixture: "python-app",
// Ruff (lint, quick fixes, formatting) starts in projects configured for it.
+28 -1
Переглянути файл
@@ -2,7 +2,7 @@
mod common;
use ide_core::{ChangeSet, TextChange};
use ide_core::{ChangeSet, Pos, Range, SymbolKind, TextChange};
use ide_host::{Host, catalogue::TrustClass, ops};
use std::sync::Arc;
use std::time::Duration;
@@ -51,6 +51,33 @@ async fn edits_loose_files_without_project_services() {
assert!(!Arc::ptr_eq(&project, &light));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn large_markdown_has_structure_after_embedded_images() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("paper.md");
let image = format!("![Figure](data:image/png;base64,{})\n\n", "A".repeat(64 * 1024));
let text = format!("# Paper\n\n{}```text\n## Inside code\n```\n\n## Results\n", image.repeat(84));
std::fs::write(&path, text).unwrap();
let host = host(&tmp.path().join("app"));
host.open_light("main", &path).unwrap();
let doc = ops::doc::doc_open(&host, "main", path).await.unwrap();
assert!(doc.large);
let outline = ops::doc::doc_outline(&host, "main", doc.id).await.unwrap();
assert_eq!(outline.len(), 1);
let paper = &outline[0];
assert_eq!(paper.kind, SymbolKind::Key);
assert_eq!(paper.name, "Paper");
assert_eq!(paper.selection_range, Range::new(Pos::new(0, 2), Pos::new(0, 7)));
assert_eq!(paper.children.len(), 1);
let results = &paper.children[0];
assert_eq!(results.kind, SymbolKind::Key);
assert_eq!(results.name, "Results");
assert_eq!(results.selection_range, Range::new(Pos::new(174, 3), Pos::new(174, 10)));
assert!(results.children.is_empty());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn light_windows_ignore_project_scoped_settings() {
let tmp = tempfile::tempdir().unwrap();
+36
Переглянути файл
@@ -775,6 +775,42 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
assert!(result["output"].as_str().unwrap().contains("captured-output"));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_configuration_left_running_is_stopped_by_its_run_id() {
let h = Harness::new();
h.trust().await;
let config = ide_run::RunConfig {
id: "server".into(),
name: "Server".into(),
kind: "shell".into(),
command: if cfg!(windows) { "ping -n 60 127.0.0.1" } else { "sleep 60" }.into(),
args: vec![],
cwd: None,
env: Default::default(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
ide_run::save_user_configs(&h.root, &[config]).unwrap();
h.host.mcp_requests.set_ready("main", true);
let run = h.json("execute_run_configuration", json!({"configurationName":"Server","waitForExit":false}));
let allow = async {
let id = h.request().await;
h.host.mcp_requests.answer("main", id, true, None).unwrap();
};
let (result, ()) = tokio::join!(run, allow);
assert!(result.get("exitCode").is_none());
let id = result["runId"].as_u64().expect("a run left running carries its id");
let user_run = id + 1000;
assert!(h.error("stop_run", json!({"runId": user_run})).await.contains("started by execute_run_configuration"));
let stopped = h.json("stop_run", json!({"runId": id, "force": true, "timeout": 10000})).await;
assert_eq!(stopped["state"], "stopped", "{stopped}");
assert!(h.error("stop_run", json!({"runId": id})).await.contains("started by execute_run_configuration"));
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires rust-analyzer, like language_smoke::rust"]
async fn rust_references_and_rename_through_mcp() {
+1 -1
Переглянути файл
@@ -274,7 +274,7 @@ async fn official_api_examples_install_and_render_real_component_contributions()
ide_plugin::ProviderDocument { path: f.root.join("example.tests"), text: "test adds\n".into(), ..doc };
assert!(eventually(|| {
f.plugins
.language_gutter_actions(&doc)
.language_gutter_actions(&doc, Some(&f.root))
.iter()
.any(|(owner, action)| owner == "openidea.test-runner" && action.argument.as_deref() == Some("adds"))
}));
+60
Переглянути файл
@@ -376,3 +376,63 @@ async fn injected_lsp(host: &Host, plugins: &PluginHost, root: &Path, remote: &i
peer.kill();
}
}
/// Two open projects, one inside the other.
struct Nested {
roots: Vec<std::path::PathBuf>,
}
impl ide_host::plugins::PluginWorkspace for Nested {
fn projects(&self) -> Vec<std::path::PathBuf> {
self.roots.clone()
}
fn buffer_text(&self, _: &Path) -> Option<String> {
None
}
fn document(&self, _: &Path) -> Option<(u64, String)> {
None
}
fn apply_edits(&self, _: &Path, _: u64, _: &[ide_core::TextEdit], _: bool) -> Result<u64, ide_plugin::HostError> {
Err(ide_plugin::HostError::NotFound("not open".into()))
}
fn trusted(&self, _: &Path) -> bool {
true
}
fn project_of(&self, _: &str) -> Option<std::path::PathBuf> {
None
}
fn publish_diagnostics(
&self,
_: &str,
_: &Path,
_: Vec<ide_core::Diagnostic>,
) -> Result<(), ide_plugin::HostError> {
Ok(())
}
}
#[test]
fn gutter_actions_see_the_editors_window_project() {
let tmp = tempfile::tempdir().unwrap();
let outer = dunce::canonicalize(tmp.path()).unwrap().join("outer");
let inner = outer.join("inner");
std::fs::create_dir_all(&inner).unwrap();
let p = plugins(tmp.path());
p.set_workspace(Some(Arc::new(Nested { roots: vec![outer.clone(), inner.clone()] })));
let doc = ProviderDocument {
path: inner.join("Taskfile.txt"),
language: "text".into(),
version: 1,
text: "build\n".into(),
};
let argument = |project: Option<&Path>| {
let actions = p.language_gutter_actions(&doc, project);
assert_eq!(actions.len(), 1);
actions[0].1.argument.clone().unwrap()
};
// The outer project's window: the file is its, though the inner project holds it too.
assert_eq!(argument(Some(&outer)), outer.to_string_lossy());
assert_eq!(argument(Some(&inner)), inner.to_string_lossy());
// No window, or a root that is no open project: no invoking project.
assert_eq!(argument(None), "gutter");
assert_eq!(argument(Some(&tmp.path().join("elsewhere"))), "gutter");
}
+83
Переглянути файл
@@ -0,0 +1,83 @@
//! API 1.18 `[[contributes.runAnything]]`: lines starting with a plugin's prefix are
//! suggested and run by its `run-anything-provider` export; other lines are refused.
use ide_host::plugins::{Consent, PluginHost};
use ide_plugin::{Invocation, Limits};
use std::{path::Path, sync::Arc};
const ID: &str = "test.run-anything";
fn plugins(base: &Path) -> Arc<PluginHost> {
let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/run-anything");
let p =
Arc::new(PluginHost::new(base.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap());
p.install_from_dir(&fixture, &Consent::all()).unwrap();
p
}
#[test]
fn the_plugin_suggests_and_claims_lines_of_its_prefix() {
let tmp = tempfile::tempdir().unwrap();
let p = plugins(tmp.path());
let root = Some(tmp.path().to_path_buf());
let labels = |text: &str| -> Vec<String> {
p.run_anything_suggest(ID, "main", root.clone(), "task", text).unwrap().into_iter().map(|i| i.label).collect()
};
assert_eq!(labels("ta"), ["task build", "task test", "task docs:serve"]);
assert_eq!(labels("task d"), ["task docs:serve"]);
assert!(labels("task x").is_empty());
// Only text for the declared prefix reaches the plugin.
assert!(p.run_anything_suggest(ID, "main", root.clone(), "make", "make").is_err());
assert!(p.run_anything_suggest(ID, "main", root.clone(), "task", "echo task").is_err());
assert!(p.run_anything_run(ID, "main", root.clone(), "task", "task build").unwrap());
assert!(p.run_anything_run(ID, "main", root.clone(), "task", "task docs:serve ").unwrap());
// Left to the shell by the plugin.
assert!(!p.run_anything_run(ID, "main", root.clone(), "task", "task deploy").unwrap());
assert!(p.run_anything_run(ID, "main", root.clone(), "task", "tasks build").is_err());
let invocation = Invocation { workspace_root: root, ..Default::default() };
let ran = p.run_command(ID, "ran", None, invocation).unwrap();
assert_eq!(ran.as_deref(), Some("build\ndocs:serve"));
}
#[test]
fn the_plugins_configuration_completes_only_the_argument_under_the_caret() {
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let (root, other) = (base.join("project"), base.join("other"));
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&other).unwrap();
std::fs::write(root.join("Taskfile.yml"), "version: '3'\n").unwrap();
let p = plugins(&base);
let config = "plugin:test.run-anything:tasks";
// Not provided until its program is approved.
assert!(p.run_configuration_complete("main", &root, config, "arguments", "b", 1).is_err());
p.choose_program(ID, "process:task", Some(&root), Some(Path::new("/bin/echo"))).unwrap();
assert!(p.run_detection().detect(&root).iter().any(|c| c.id == config));
let complete = |text: &str, caret: u32| -> Vec<(String, String, u32, u32)> {
p.run_configuration_complete("main", &root, config, "arguments", text, caret)
.unwrap()
.into_iter()
.map(|c| (c.label, c.insert, c.replace_start, c.replace_end))
.collect()
};
// Options, quoted values and the task's own arguments after `--` stay outside the range.
let text = "--dry 'a b' d -- x";
assert_eq!(complete(text, 13), [("docs:serve".into(), "docs:serve".into(), 12, 13)]);
assert!(complete(text, 18).is_empty(), "after `--` the arguments are the task's");
assert!(complete(text, 3).is_empty(), "an option is not a task");
// UTF-16 offsets.
assert_eq!(complete("é b", 3), [("build".into(), "build".into(), 2, 3)]);
assert_eq!(complete("", 0).len(), 3);
assert!(p.run_configuration_complete("main", &root, config, "env", "b", 1).unwrap().is_empty());
// Out-of-range carets, other configurations and projects without it are refused.
assert!(p.run_configuration_complete("main", &root, config, "arguments", "b", 2).is_err());
assert!(
p.run_configuration_complete("main", &root, "plugin:test.run-anything:other", "arguments", "b", 1).is_err()
);
assert!(p.run_configuration_complete("main", &root, "npm:dev", "arguments", "b", 1).is_err());
assert!(p.run_configuration_complete("main", &other, config, "arguments", "b", 1).is_err());
// Revoking the program withdraws the configuration, and with it the completion.
p.set_capability(ID, "process:task", false).unwrap();
assert!(p.run_configuration_complete("main", &root, config, "arguments", "b", 1).is_err());
}
Loaded 100 of 1192 files, more files were not shown because too many files have changed in this diff. Show more