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

...
Автор SHA1 Повідомлення Дата
Deng Liu 42d2bea84c feat(remote-dev): add remote host resource indicator and dashboard
Add a compact CPU + RAM micro-meter widget beside the Remote Host status bar item in remote development windows, staying calm at rest and badging network or disk saturation on pressure. Clicking the indicator (or running Show Remote Host Resources) opens a popover dashboard with rolling CPU, memory, network (+ SSH/RPC RTT) and disk graphs, plus attributed OpenIDEA remote processes (confirming before calling host_end_process) and top external host processes.
2026-11-27 02:52:43 -08:00
LU XIANGRUIтаwildcatDownstairs 660becbaa4 feat(coverage): import coverage.py data files (.coverage) (#6450)
Import a Coverage Report now reads coverage.py's .coverage data file; choosing one .coverage.* file of a parallel run imports all of them. The data only records executed lines and arcs, so coverage.py in the project's interpreter combines it into a scratch file (combine --keep, the user's files untouched) and writes Cobertura XML (xml -i) for the existing importer, run in the project directory so [paths] and excluded lines apply. Running the interpreter needs a trusted project; without trust, an interpreter or coverage.py the error says so and points to coverage xml output. Files without source in the project are listed without lines and the notification says to map them with [paths].

Closes #6392

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:50:40 +08:00
LU XIANGRUIтаwildcatDownstairs a0afc478c1 fix(debugger): stop at breakpoints in Jinja2 and Flask templates (#6453)
debugpy reads a breakpoint in a non-.py file as a template breakpoint only when the launch has jinja: true, which was never set. A Python debug launch now gets it when it starts Flask (flask, -m flask) or when a breakpoint is already in a Jinja2 template (.jinja / .jinja2 / .j2, or markup or text in a templates folder). Django launches keep django: true alone, since debugpy reads one or the other. .jinja / .jinja2 / .j2 files now accept breakpoints.

Closes #6371

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:47:37 +08:00
LU XIANGRUIтаwildcatDownstairs 07a88c6fa4 fix(debugger): accept breakpoints in Django templates without the any-file setting (#6452)
Only languages with a debugger accept new breakpoints, and the Django Template language (files in a Django project's templates folders) had none, so breakpoints there needed "Allow placing breakpoints in any file". It now declares debugpy. debugpy also gets django: true for python -m django and django-admin launches, not only manage.py, and django-admin now runs as python -m django instead of a module that doesn't exist.

Closes #6370

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:46:23 +08:00
Bake Yam 46bd6fad3c fix(notebook): refresh cell documents when the backend changes their DocId (#6440)
The backend hands a notebook cell a new DocId when its servers open the notebook again (a restarted language server, a reopened notebook) while the cell ids stay the same. The session refetched cell documents only when the set of code cells changed, so it kept a spent DocId and editor shortcuts in a cell answered "DocId#N is not open". The lookup now runs on every snapshot, ordered by a sequence number, and publishes only when a cell's document or uri moved.

Part of #5846

Co-authored-by: Renjiankang <[email protected]>
2026-11-27 18:44:46 +08:00
薛纪克таxuejike f64dbe65b4 feat(agents): show the command a tool call ran in the session UI (#6429)
A command tool call showed only the agent's own title ("Run command"). The timeline now keeps the command from the call's structured input (rawInput.command / rawInput.cmd, a string or an argv array, <shell> -c <script> unwrapped), and the session UI uses it as the row title, its tooltip and the $ line of the expanded terminal block, falling back to the output's $ line and then the title. Saved sessions without the field still load.

Closes #6428

Co-authored-by: xuejike <[email protected]>
2026-11-27 18:42:02 +08:00
l0ng-ai e2a5a5db81 fix(debugger): flash only the stopped project's window on a breakpoint (#6449)
A breakpoint hit while the app was in the background requested attention for every webview window, so on Windows the taskbar button of another open project flashed too. Only the window of the project whose session stopped asks now; an event without a window still reaches every window. No other place requests attention for all windows.

Fixes #6404
2026-11-27 18:35:01 +08:00
LU XIANGRUIтаwildcatDownstairs 6eb7abff9f feat(debugger): add Python Debug Server configurations (#6421)
Python Debug Server run configuration (Debug only): the IDE's debugpy adapter listens (attach with listen) and the program connects with debugpy.connect. The form shows the line to add; a loopback host listens on 127.0.0.1 only, any other host on all interfaces (with a warning, since debugpy's listen mode has no authentication); local/remote roots map paths and redirectOutput sends the program's output to the console. While waiting, the session is Starting and the console shows the address and the line; Stop cancels the wait. When the connected program ends by itself, the configuration listens again in the same tab, keeping the output. A port in use fails the start up front (debugpy's adapter would otherwise wait forever), and on the first stop the program's debugpy version is compared with the IDE's, with a warning when they differ. VS Code attach configurations with listen import as Python Debug Server.

Closes #6369

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:30:11 +08:00
Waiting-Night b46112fe0b feat(database): organize data sources into folders (#6423)
Project-local data source folders in the Database tree: New › Folder…, rename and delete (members move back to the root), Move to Folder (also for several selected sources, including a new folder) and drag-and-drop onto a folder. Folders live in .openidea/data-source-folders.toml, written atomically and validated (one folder per source, known parents, no cycles), and are reloaded when the file changes on disk; removing data sources drops them from their folders.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 18:20:04 +08:00
Waiting-Night 4507dc172d feat(database): support batch actions on selected data sources (#6420)
Several selected data sources in the Database tree share Refresh, Deactivate and Remove: the context menu shows only those, with the number of affected sources. Refresh runs every selected source and reports failures once; Deactivate disconnects only the connected ones; Remove asks once (listing the names), disconnects, saves the project once and keeps the rest of the selection. The toolbar's Deactivate and Properties follow the multi-selection.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 18:08:08 +08:00
LU XIANGRUIтаwildcatDownstairs 8442c0c339 feat(typescript): CSS Modules navigation through CSS Modules Kit (#6345)
Go to Declaration, completion, Find Usages and Rename for CSS Module class names between TS/JSX and *.module.css, through the CSS Modules Kit tsserver plugin on vtsls. The plugin is an IDE-managed tool pinned to @css-modules-kit/[email protected]; a project turns it on with "cmkOptions": { "enabled": true } in tsconfig.json (also inherited through a local extends), which the editor offers to add, installing the plugin if needed. CSS files reach vtsls only once the plugin is installed; references from a selector drop the CSS server's own rule, and rename takes vtsls' edit so the selector keeps its dot.

CSS Modules Kit loads before the Vue tsserver plugin outside a Vue project: both are Volar plugins sharing one @volar/typescript, which decorates a project once, so with the Vue language server installed the Vue plugin had claimed every vtsls and CSS Modules Kit did nothing.

Closes #6071

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 18:00:08 +08:00
l0ng-ai 8ffe3bd230 fix(i18n): translate the Run tool window's agent configuration action (#6436)
The hidden run.mcpStart action added in #6431 had no Chinese title and description, which the locale catalog tests require.
2026-11-27 17:41:48 +08:00
l0ng-ai 1babff55fc feat(mcp): run execute_run_configuration's runs in the Run tool window (#6431)
A run configuration started through execute_run_configuration ran out of sight, with no Run tool window tab, console or Stop. The tool now asks the project window to start the prepared configuration (before launch tasks already done), tagged with mcp.configRun; run_start recognises the tag on the first start, tees the output into the call's output file and reports the run it started, so exitCode, runId, stop_run and fullOutputPath keep working. A project loaded for MCP alone (no window, brave mode) still runs it directly.

Fixes #6330
2026-11-27 17:30:39 +08:00
l0ng-ai 2ad95150eb fix(refactoring): undo an extract refactoring with its rename and reformatting in one step (#6424)
The history group around a server refactoring kept every transaction out of the undo history, including the workspace refactoring's history marker, so Cmd+Z reverted only the current file's text locally and the notification's Undo failed with "Undo newer editor changes".

The marker now stays in the history. Local edits after the server's within the group (reformatting, the in-place rename) are recorded as the refactoring's follow-up edits: undoing the refactoring reverts them before the backend restores the files, redoing applies them again, and a refused restore puts them back. The notification's Undo first finishes an open in-place rename. Quick fixes group the server's edit with its reformatting the same way, so their reformatting no longer sits above the marker as a separate step.

Fixes #6327
2026-11-27 17:19:13 +08:00
Waiting-Night fe3e647abb feat(database): list query consoles under a Database Consoles root (#6408)
Query consoles stay in <dataDir>/consoles/db; the database feature registers that folder as a Database Consoles root in the Project view's Scratches and Consoles scope, re-registered when a remote session starts or ends. Console folders show the data source's name and icon ("Orders", "Orders: sales") through new display-only label/icon file decorations, which also order siblings when sorting by name. Consoles announce their creation so the tree refreshes, deleted console files close their editors, and a console's data source is recovered from its path when the binding is missing.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 17:06:51 +08:00
Waiting-Night 62cc6768fe feat(search): show data source names for recent query consoles (#6411)
Recent Files listed every query console as console.sql, so consoles of different data sources looked the same. Rows for files without an open editor now use the file decoration's tab title and icon, so a console shows as console [Orders] with its data source icon; match highlighting is dropped when the shown title differs from the file name.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 16:49:38 +08:00
Waiting-Night 2e93422270 feat(database): show table comments in the database tree (#6416)
Tables and views in the Database tree now show their comment in grey after the name, with the full comment as the row tooltip. Built-in drivers read it in the same catalog query that lists relations (PostgreSQL, MySQL, Oracle, ClickHouse, Snowflake, SQL Server extended properties) and JDBC sources from REMARKS. The new Show Table Comments view option is on by default and toggles from the Database window options; TableInfo.comment is optional on the wire.

Co-authored-by: wangyuewen-china <[email protected]>
2026-11-27 16:48:31 +08:00
audichuang 3a1353cc0e feat(vcs): show a file's diff from the Rollback, Shelve and Create Patch file lists (#6417)
In the Rollback Changes dialog, double-click and Enter only toggled a file's checkbox and Show Diff did nothing. The file checklist shared by Rollback, Shelve and Create Patch now opens the file's diff in a front dialog on double-click, Enter and Show Diff, with the listed files as the next/previous chain; Space toggles the selected rows and clicking a box still toggles it. Rollback Unstaged Changes shows the index against the working copy. Closes #5295.

Co-authored-by: audichuang <[email protected]>
2026-11-27 16:44:28 +08:00
audichuang c5eab0a4a3 fix(editor): show color swatches for Java new Color(0x...) literals (#6413)
The hex rule required a leading #, so java.awt.Color int literals never matched. In Java files, a 0x literal that is the whole argument of new Color(...) or new ColorUIResource(...) (unqualified or qualified as java.awt / javax.swing.plaf) is now a color, read as Color(int) reads it (the low 24 bits); picking a color writes it back as 0x hex in the literal's case. Other overloads, suffixed literals, other Color classes and Kotlin stay without a swatch. Closes #5529 together with #6412.

Co-authored-by: audichuang <[email protected]>
2026-11-27 16:42:28 +08:00
audichuang 581c8cf025 fix(editor): show color swatches for HTML style attributes and embedded scripts (#6412)
Named colors only counted in style sheet languages, and in markup only matches inside style nodes were kept, so embedded script code was dropped. Named colors now count in markup (still limited to <style> and style attributes by the syntax tree), and a match inside a Script node is kept when a standalone script file would accept it: quoted hex and color functions, never names. The property-colon check now looks only after the last colon, so long markup lines no longer cost quadratic time. Refs #5529.

Co-authored-by: audichuang <[email protected]>
2026-11-27 16:41:56 +08:00
l0ng-ai 807c447792 feat(database): Revert Selected and Copy Aggregation Result in the data grid (#6418)
Revert Selected drops the pending edits, deletes and added rows of the selected rows only, from the row menu of the table editor and editable results; it takes Cmd+Alt+Z / Ctrl+Alt+Z while the selection has changes, and Revert keeps the shortcut otherwise. Copy Aggregation Result copies one aggregate of the selected cells as the Aggregates panel shows it: Cmd+Shift+C / Ctrl+Shift+C copies the Sum of numbers or the Count otherwise, and the grid context menu lists every aggregate the selection has. Fixes #6308.
2026-11-27 16:40:46 +08:00
l0ng-ai 217693a56f test: make three Rust tests pass on Windows (#6386)
Three tests failed on the Windows Rust job after Clippy: the tsc solution test built expected paths with mixed separators, the gutter plugin test compared a path argument as a string although the plugin sees /-separated Windows paths, and the run configuration completion fixture approved /bin/echo, which is not executable on Windows. Expectations use chained joins, the gutter test compares paths, and the fixture approves the test binary itself.
2026-11-27 16:21:12 +08:00
Deng Liuтаdengliu 557295b1df feat(agents): surface OAuth device-code banner in Sign In dialog (#6399)
The agent Sign In dialog parses OAuth device-authorization URLs and one-time codes from the sign-in PTY output and shows them above the terminal with Copy and Copy Code & Open Browser, using the desktop clipboard and browser. On openidea-server, sign-in PTYs are marked as a remote session (REMOTE_CONTAINERS=1 when no SSH or Codespaces marker exists, GH_BROWSER=true for gh without a browser override), so CLIs pick device-code sign-in instead of a remote-only loopback callback.

Co-authored-by: dengliu <[email protected]>
2026-11-27 16:20:24 +08:00
Deng Liuтаdengliu 7c674e70e5 fix(agents): pick Linux Copilot archive from host dynamic linker (#6398)
openidea-server on Linux is a static musl binary, so choosing the Copilot archive with cfg!(target_env = "musl") installed the linuxmusl build on glibc hosts, where execve fails with ENOENT. The archive variant now comes from the host's runtime dynamic linker: linuxmusl only when ld-musl is present and glibc's loader is absent or symlinked to musl.

Co-authored-by: dengliu <[email protected]>
2026-11-27 16:17:35 +08:00
Deng Liuтаdengliu 1602a5d010 fix(services): route Docker Services to the remote host daemon (#6379)
Docker commands moved from the desktop crate into the ide-host project_host domain, so a remote window reaches the Docker daemon on the remote host through openidea-server instead of the local one. The SSH tunnel reuses the existing resolve logic, docker_executable only caches a found path, and the Services store drops event streams, timers and in-flight requests when the host changes.

Co-authored-by: dengliu <[email protected]>
2026-11-27 16:16:20 +08:00
wangfeiтаhapput a6d135d66f feat(agents): add separate chat and code font settings (#6395)
Settings > Agents > Chat gets Font and Code Font groups like Terminal's: chat text and code each take a family, a fallback and a size. Defaults follow the interface font and the built-in code font, so nothing changes until a choice is made. Chat zoom steps on top of the chosen size, and a chosen code size also applies to fenced code blocks while inline code stays with the chat text.

Co-authored-by: happut <[email protected]>
2026-11-27 16:07:51 +08:00
LU XIANGRUIтаwildcatDownstairs 924bf6d3b9 feat(coverage): import Cobertura XML reports (#6390)
Import a Coverage Report now reads Cobertura XML (coverage.py's coverage xml and many other tools): line hits, partial branches from condition-coverage, relative file names resolved against <sources>, foreign paths mapped by suffix as for the other formats, and <methods> lines not counted twice. The import notification says how many files of a report are not in the project. Missing directories are now looked up once, which makes reports with CI paths under macOS's autofs /home import in under a second instead of tens of seconds.

Closes #6359

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-27 16:03:41 +08:00
l0ng-ai 318c227b0c fix(database): show column comments in the SQL table and column hover (#6402)
The completion metadata the SQL console hover reads carried no column comments, though Modify Table and the Database view already read them. completion_columns now returns the comment on PostgreSQL, MySQL, Oracle, ClickHouse and Snowflake (NULL on SQL Server and SQLite), Snowflake's SHOW COLUMNS path and the JDBC bridge's schemaColumns (REMARKS, jar rebuilt) carry it too, and the hover shows a comment column in the table card and the comment under a single column.

Fixes #6374
2026-11-27 16:01:45 +08:00
l0ng-ai 2ce7621abb fix(terminal): write shell integration scripts atomically into a content-keyed folder (#6400)
The shell integration scripts went to a temp folder named by version only and were rewritten in place, so a shell starting while another process rewrote them could source a truncated file, and two builds of the same version with different scripts (a dev build next to a release, two checkouts' tests on one runner) overwrote each other; zsh_restores_zdotdir_and_histfile_for_login_shells failed on macOS CI that way. The folder name now carries a hash of the scripts, and each file is written to a unique temporary name and renamed into place.
2026-11-27 15:54:12 +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
625 змінених файлів з 28634 додано та 2512 видалено

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
Створено
+49 -49
Переглянути файл
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "ide-agent"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4182,7 +4182,7 @@ dependencies = [
[[package]]
name = "ide-analysis"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ast-grep-core",
"ide-core",
@@ -4194,7 +4194,7 @@ dependencies = [
[[package]]
name = "ide-android"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"serde",
@@ -4205,7 +4205,7 @@ dependencies = [
[[package]]
name = "ide-build"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"chardetng",
@@ -4223,7 +4223,7 @@ dependencies = [
[[package]]
name = "ide-cli"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dirs 6.0.0",
"serde",
@@ -4237,7 +4237,7 @@ dependencies = [
[[package]]
name = "ide-clipboard"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4248,7 +4248,7 @@ dependencies = [
[[package]]
name = "ide-command"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@@ -4259,7 +4259,7 @@ dependencies = [
[[package]]
name = "ide-core"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4281,7 +4281,7 @@ dependencies = [
[[package]]
name = "ide-coverage"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-run",
@@ -4294,7 +4294,7 @@ dependencies = [
[[package]]
name = "ide-dap"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"futures",
@@ -4323,7 +4323,7 @@ dependencies = [
[[package]]
name = "ide-db"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"bb8",
@@ -4362,7 +4362,7 @@ dependencies = [
[[package]]
name = "ide-docker"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"serde",
@@ -4375,7 +4375,7 @@ dependencies = [
[[package]]
name = "ide-drag-out"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"gtk",
"objc2 0.6.5",
@@ -4389,7 +4389,7 @@ dependencies = [
[[package]]
name = "ide-extension"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4409,7 +4409,7 @@ dependencies = [
[[package]]
name = "ide-flutter"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-android",
"ide-core",
@@ -4420,7 +4420,7 @@ dependencies = [
[[package]]
name = "ide-fonts"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"objc2-core-foundation",
"objc2-core-text",
@@ -4432,7 +4432,7 @@ dependencies = [
[[package]]
name = "ide-github"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-vcs",
@@ -4440,12 +4440,11 @@ dependencies = [
"serde_json",
"specta",
"tracing",
"which",
]
[[package]]
name = "ide-heap"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"ide-core",
@@ -4464,7 +4463,7 @@ dependencies = [
[[package]]
name = "ide-host"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
@@ -4545,7 +4544,7 @@ dependencies = [
[[package]]
name = "ide-http"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"hyper-util",
"ide-core",
@@ -4564,7 +4563,7 @@ dependencies = [
[[package]]
name = "ide-index"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"criterion",
@@ -4587,7 +4586,7 @@ dependencies = [
[[package]]
name = "ide-jdwp"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-jvm-inspect",
"proptest",
@@ -4599,7 +4598,7 @@ dependencies = [
[[package]]
name = "ide-jsonrpc"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"encoding_rs",
"ide-core",
@@ -4615,7 +4614,7 @@ dependencies = [
[[package]]
name = "ide-jvm-attach"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"libc",
"tempfile",
@@ -4624,7 +4623,7 @@ dependencies = [
[[package]]
name = "ide-jvm-inspect"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"futures",
"serde",
@@ -4635,7 +4634,7 @@ dependencies = [
[[package]]
name = "ide-language"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"criterion",
@@ -4694,7 +4693,7 @@ dependencies = [
[[package]]
name = "ide-lsp"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"dunce",
@@ -4705,6 +4704,7 @@ dependencies = [
"ide-jsonrpc",
"ide-jvm-inspect",
"ide-language",
"ide-sdk",
"ide-text",
"ide-vfs",
"ignore",
@@ -4723,7 +4723,7 @@ dependencies = [
[[package]]
name = "ide-mcp"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"bytes",
"dunce",
@@ -4742,7 +4742,7 @@ dependencies = [
[[package]]
name = "ide-notebook"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-vfs",
@@ -4763,7 +4763,7 @@ dependencies = [
[[package]]
name = "ide-plugin"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"dunce",
@@ -4785,7 +4785,7 @@ dependencies = [
[[package]]
name = "ide-profiler"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-jvm-attach",
@@ -4799,7 +4799,7 @@ dependencies = [
[[package]]
name = "ide-remote"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dunce",
"futures",
@@ -4819,7 +4819,7 @@ dependencies = [
[[package]]
name = "ide-run"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dunce",
"encoding_rs",
@@ -4844,7 +4844,7 @@ dependencies = [
[[package]]
name = "ide-scaffold"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-tools",
@@ -4860,7 +4860,7 @@ dependencies = [
[[package]]
name = "ide-sdk"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"dirs 6.0.0",
@@ -4886,7 +4886,7 @@ dependencies = [
[[package]]
name = "ide-search"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"encoding_rs",
@@ -4907,7 +4907,7 @@ dependencies = [
[[package]]
name = "ide-spell"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"parking_lot 0.12.5",
@@ -4920,7 +4920,7 @@ dependencies = [
[[package]]
name = "ide-ssh"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dirs 6.0.0",
"flate2",
@@ -4945,7 +4945,7 @@ dependencies = [
[[package]]
name = "ide-streams"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-language",
@@ -4958,7 +4958,7 @@ dependencies = [
[[package]]
name = "ide-syntax"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"ide-language",
@@ -4973,7 +4973,7 @@ dependencies = [
[[package]]
name = "ide-terminal"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"ide-core",
"libc",
@@ -4987,7 +4987,7 @@ dependencies = [
[[package]]
name = "ide-text"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"criterion",
"ide-core",
@@ -5000,7 +5000,7 @@ dependencies = [
[[package]]
name = "ide-tools"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"flate2",
"hex",
@@ -5023,7 +5023,7 @@ dependencies = [
[[package]]
name = "ide-vcs"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"dunce",
@@ -5045,7 +5045,7 @@ dependencies = [
[[package]]
name = "ide-vfs"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"chardetng",
"dunce",
@@ -5072,7 +5072,7 @@ dependencies = [
[[package]]
name = "ide-web"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"dirs 6.0.0",
"ide-core",
@@ -5088,7 +5088,7 @@ dependencies = [
[[package]]
name = "ide-workspace"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"blake3",
"dunce",
@@ -6727,7 +6727,7 @@ dependencies = [
[[package]]
name = "openidea"
version = "0.1.53"
version = "0.1.54"
dependencies = [
"base64 0.22.1",
"blake3",
+1 -1
Переглянути файл
@@ -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"
+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(
+99 -2
Переглянути файл
@@ -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).
@@ -706,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),
@@ -785,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);
@@ -802,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, _| {
@@ -815,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<()> {
@@ -837,7 +922,9 @@ impl AgentManager {
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.
@@ -3509,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);
@@ -5010,7 +5105,8 @@ fn tool_event(
i: usize,
entry: &AgentEntry,
) -> Option<AgentEvent> {
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms } = entry
let AgentEntry::Tool { id, title, kind, status, locations, images, output, diffs, started_ms, ended_ms, command } =
entry
else {
return None;
};
@@ -5025,6 +5121,7 @@ fn tool_event(
diffs: diffs.clone(),
started_ms: *started_ms,
ended_ms: *ended_ms,
command: command.clone(),
};
let text = output.as_deref().unwrap_or_default();
let key = (subagent, i);
+34
Переглянути файл
@@ -547,6 +547,9 @@ pub enum AgentEntry {
started_ms: Option<f64>,
#[serde(default)]
ended_ms: Option<f64>,
/// The command an `execute` call runs, from its structured input; `None` when the agent gave none.
#[serde(default)]
command: Option<String>,
},
Plan {
items: Vec<AgentPlanItem>,
@@ -623,6 +626,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,
@@ -647,6 +653,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")]
+1 -2
Переглянути файл
@@ -1481,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",
+84
Переглянути файл
@@ -455,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",
+20 -6
Переглянути файл
@@ -740,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,
}
@@ -780,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>,
+338 -22
Переглянути файл
@@ -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;
@@ -73,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."),
@@ -151,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)
}
@@ -166,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);
@@ -176,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"];
@@ -194,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);
@@ -229,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)
}
@@ -237,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`:
@@ -259,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(
@@ -389,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![],
@@ -901,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() {
@@ -1160,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();
@@ -1174,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));
}
@@ -1458,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(""));
}
}
+156 -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>;
@@ -663,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> {
@@ -704,6 +747,7 @@ fn install_npm_with(
},
&specs,
false,
public_fallback,
cancel,
emit,
)?;
@@ -1004,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();
@@ -1043,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:?}");
@@ -1052,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]
@@ -1183,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)];
@@ -1275,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
);
}
}
}
+1 -1
Переглянути файл
@@ -32,7 +32,7 @@ pub fn widens_access(params: &Value) -> bool {
tool.and_then(|t| t.pointer("/rawInput/networkApprovalContext")).is_some_and(|c| !c.is_null())
}
fn command_from_value(val: &Value) -> Option<String> {
pub(crate) fn command_from_value(val: &Value) -> Option<String> {
match val {
Value::String(s) => {
let trimmed = s.trim();
+1
Переглянути файл
@@ -4369,6 +4369,7 @@ fn a_running_tools_output_is_sent_as_appends() {
diffs: Vec::new(),
started_ms: Some(1.0),
ended_ms: None,
command: None,
};
let running = |output| call(AgentToolStatus::Running, output);
let event = |streamed: &mut Streamed, session: Session, i, entry: &AgentEntry| {
+35 -1
Переглянути файл
@@ -91,6 +91,7 @@ impl Timeline {
diffs: Vec::new(),
started_ms: Some(crate::now_ms()),
ended_ms: None,
command: None,
};
let index = match self.tools.get(&id) {
Some(&i) => {
@@ -154,7 +155,7 @@ impl Timeline {
}
fn merge_tool(&mut self, index: usize, update: &Value) {
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, .. } =
let AgentEntry::Tool { title, kind, status, locations: locs, output, images, diffs, ended_ms, command, .. } =
&mut self.entries[index]
else {
return;
@@ -171,6 +172,11 @@ impl Timeline {
*ended_ms = Some(crate::now_ms());
}
}
if let Some(raw) = update.pointer("/rawInput/command").or_else(|| update.pointer("/rawInput/cmd"))
&& let Some(cmd) = crate::security::command_from_value(raw)
{
*command = Some(crate::shell_script(&cmd).unwrap_or(cmd));
}
if update.get("locations").is_some_and(Value::is_array) {
*locs = locations(update.get("locations"));
}
@@ -471,6 +477,34 @@ mod tests {
assert!(matches!(&t.entries[0], AgentEntry::Question { chosen: Some(answer), .. } if answer == "One"));
}
#[test]
fn an_execute_call_keeps_the_command_from_its_structured_input() {
let mut t = Timeline::default();
let command = |t: &Timeline, i: usize| match &t.entries[i] {
AgentEntry::Tool { command, .. } => command.clone(),
_ => panic!(),
};
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "a", "title": "Run command", "kind": "execute",
"rawInput": {"command": "python hello_world.py"}}));
assert_eq!(command(&t, 0).as_deref(), Some("python hello_world.py"));
// An argv array whose shell wraps the script, sent with a later update.
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "b", "title": "Run command", "kind": "execute"}));
assert_eq!(command(&t, 1), None);
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "b",
"rawInput": {"cmd": ["bash", "-lc", "cargo test -p ide-agent"]}}));
assert_eq!(command(&t, 1).as_deref(), Some("cargo test -p ide-agent"));
// One shell line, unwrapped as the permission card does.
t.apply(&json!({"sessionUpdate": "tool_call", "toolCallId": "c", "kind": "execute",
"rawInput": {"command": "/bin/zsh -lc 'node hello.js'"}}));
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
// A later update without one keeps it; tasks saved before the field load without it.
t.apply(&json!({"sessionUpdate": "tool_call_update", "toolCallId": "c", "status": "completed"}));
assert_eq!(command(&t, 2).as_deref(), Some("node hello.js"));
let mut old = serde_json::to_value(&t.entries[2]).unwrap();
old.as_object_mut().unwrap().remove("command");
assert!(matches!(serde_json::from_value(old).unwrap(), AgentEntry::Tool { command: None, .. }));
}
#[test]
fn tool_images_survive_updates_text_truncation_and_serialization() {
use base64::Engine;
+4 -3
Переглянути файл
@@ -323,7 +323,8 @@ mod tests {
"exclude": [path(&root.join("node_modules"))],
})
);
let a = root.join("packages/a");
// Chained joins: the configurations name native paths, `packages/a` would mix separators on Windows.
let a = root.join("packages").join("a");
assert_eq!(
copy(1),
json!({
@@ -336,14 +337,14 @@ mod tests {
"exclude": [path(&a.join("node_modules"))],
})
);
let b = root.join("packages/b");
let b = root.join("packages").join("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")),
"declarationDir": path(&scratch.join("2")), "outFile": path(&scratch.join("2").join("out.js")),
},
"references": [{"path": s("1.json")}],
"exclude": [path(&b.join("node_modules")), path(&root.join("dist"))],
+62
Переглянути файл
@@ -486,6 +486,16 @@ 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>,
@@ -495,6 +505,19 @@ pub struct LanguageCodeStyle {
/// 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).
@@ -552,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 {
@@ -562,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};
+25 -4
Переглянути файл
@@ -13,13 +13,34 @@ use std::sync::Arc;
/// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell
/// line) in the Run tool window's agent tab `name`, on pipes, answered once the process
/// started or failed to.
/// started or failed to. `RunConfiguration` starts a run configuration (a serialized
/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's
/// Run would, answered the same way.
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")]
pub enum McpUiRequest {
Confirm { client: String, tool: String, subject: String, project: String, detail: Option<String> },
OpenFile { path: crate::IpcPath, line: Option<u32>, column: Option<u32> },
AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap<String, String> },
Confirm {
client: String,
tool: String,
subject: String,
project: String,
detail: Option<String>,
},
OpenFile {
path: crate::IpcPath,
line: Option<u32>,
column: Option<u32>,
},
AgentRun {
name: String,
command: String,
cwd: crate::IpcPath,
env: BTreeMap<String, String>,
},
RunConfiguration {
#[specta(type = specta_typescript::Unknown)]
config: serde_json::Value,
},
}
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
+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());
}
}
+32
Переглянути файл
@@ -99,6 +99,20 @@ pub struct AgentSettings {
pub smooth_text: bool,
/// Conversations and the composer expand to the full width of the pane instead of staying in a centred column.
pub fit_window_width: bool,
/// Chat text follows the interface font (Appearance › Use custom font).
pub chat_use_ui_font: bool,
/// Chat text family when it does not follow the interface font.
pub chat_font_family: String,
/// Covers characters the chat font lacks.
pub chat_font_fallback: String,
pub chat_font_size: u32,
/// Code in chat follows the built-in code font.
pub code_use_default_font: bool,
/// Code family when it does not follow the built-in code font.
pub code_font_family: String,
/// Covers characters the code font lacks.
pub code_font_fallback: String,
pub code_font_size: u32,
#[serde(deserialize_with = "or_default")]
#[specta(type = ThinkingDisplay)]
pub thinking: ThinkingDisplay,
@@ -145,6 +159,14 @@ impl Default for AgentSettings {
show_cost: false,
smooth_text: true,
fit_window_width: false,
chat_use_ui_font: true,
chat_font_family: "Inter".into(),
chat_font_fallback: String::new(),
chat_font_size: 13,
code_use_default_font: true,
code_font_family: "JetBrains Mono".into(),
code_font_fallback: String::new(),
code_font_size: 13,
thinking: ThinkingDisplay::Auto,
tool_calls: ToolCallDisplay::Grouped,
expand_tool_output: false,
@@ -432,6 +454,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.
@@ -1420,6 +1448,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 {
@@ -1432,6 +1463,7 @@ impl Default for PythonSettings {
hide_other_project_interpreters: false,
show_interpreter_paths: true,
interpreter_paths: BTreeMap::new(),
test_runner: "auto".into(),
}
}
}
+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(),
}
}
}
+1 -1
Переглянути файл
@@ -1,6 +1,6 @@
[package]
name = "ide-coverage"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo XML)"
description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)"
version.workspace = true
edition.workspace = true
license.workspace = true
+171
Переглянути файл
@@ -0,0 +1,171 @@
//! Cobertura XML reports (`coverage xml` of coverage.py, and many other tools):
//!
//! ```xml
//! <coverage>
//! <sources><source>/home/runner/work/app/app</source></sources>
//! <packages><package name="calc"><classes>
//! <class filename="src/calc/__init__.py">
//! <methods/>
//! <lines>
//! <line number="2" hits="1" branch="true" condition-coverage="50% (1/2)"/>
//! ```
//!
//! A relative `filename` belongs to the first `<source>` it exists under, else to the
//! first `<source>` (whose path may be another machine's; the importer relocates it).
//! Lines repeated under `<methods>` are skipped so their hits don't count twice.
use crate::Accumulator;
use quick_xml::events::{BytesStart, Event};
use quick_xml::{Reader, XmlVersion};
use std::path::{Path, PathBuf};
fn attr(e: &BytesStart, name: &str) -> Option<String> {
e.attributes()
.flatten()
.find(|a| a.key.as_ref() == name)
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok())
.map(Into::into)
}
/// `"50% (1/2)"` → `(1, 2)`.
fn conditions(text: &str) -> Option<(u32, u32)> {
let (_, rest) = text.split_once('(')?;
let (covered, total) = rest.trim_end_matches(')').split_once('/')?;
Some((covered.trim().parse().ok()?, total.trim().parse().ok()?))
}
/// `sources` pairs each `<source>` with whether it exists here (asked once: another
/// machine's `/home/…` is slow to look up on macOS).
fn resolve(filename: &str, sources: &[(PathBuf, bool)], base: &Path) -> PathBuf {
let p = Path::new(filename);
if p.is_absolute() {
return p.to_path_buf();
}
sources
.iter()
.filter(|(_, here)| *here)
.map(|(s, _)| s.join(p))
.find(|c| c.is_file())
.unwrap_or_else(|| sources.first().map_or_else(|| base.join(p), |(s, _)| s.join(p)))
}
/// Relative sources (and filenames without sources) resolve against `base`.
pub(crate) fn parse(xml: &str, base: &Path) -> Result<Accumulator, quick_xml::Error> {
let mut reader = Reader::from_str(xml);
let mut acc = Accumulator::default();
let mut sources: Vec<(PathBuf, bool)> = Vec::new();
let mut source: Option<String> = None;
let mut file: Option<PathBuf> = None;
let mut in_methods = false;
loop {
match reader.read_event()? {
Event::Start(e) if e.name().as_ref() == "methods" => in_methods = true,
Event::Start(e) | Event::Empty(e) => match e.name().as_ref() {
"source" => source = Some(String::new()),
"class" => {
let path = resolve(&attr(&e, "filename").unwrap_or_default(), &sources, base);
acc.file(&path);
file = Some(path);
}
"line" if !in_methods => {
let Some(path) = &file else { continue };
let Some(number) = attr(&e, "number").and_then(|n| n.parse::<u32>().ok()) else { continue };
let line = number.saturating_sub(1);
acc.line(path, line, attr(&e, "hits").and_then(|h| h.parse().ok()).unwrap_or(0));
if attr(&e, "branch").as_deref() == Some("true")
&& let Some((covered, total)) = attr(&e, "condition-coverage").as_deref().and_then(conditions)
{
acc.has_branches = true;
for i in 0..total {
acc.branch(path, line, i.to_string(), i < covered);
}
}
}
_ => {}
},
Event::Text(t) => {
if let Some(s) = &mut source {
s.push_str(t.as_ref());
}
}
Event::GeneralRef(r) => {
if let Some(s) = &mut source {
s.push('&');
s.push_str(r.as_ref());
s.push(';');
}
}
Event::End(e) => match e.name().as_ref() {
"source" => {
let raw = source.take().unwrap_or_default();
let text = quick_xml::escape::unescape(raw.trim()).map(|t| t.into_owned()).unwrap_or(raw);
if !text.is_empty() {
let dir = base.join(text);
let here = dir.is_dir();
sources.push((dir, here));
}
}
"methods" => in_methods = false,
"class" => file = None,
_ => {}
},
Event::Eof => break,
_ => {}
}
}
Ok(acc)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_lines_branches_and_skips_method_lines() {
let tmp = tempfile::tempdir().unwrap();
let second = tmp.path().join("b&c");
std::fs::create_dir_all(&second).unwrap();
std::fs::write(second.join("m.py"), "").unwrap();
let xml = format!(
r#"<?xml version="1.0" ?>
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">
<coverage><sources><source>/elsewhere/a</source><source>{}</source></sources>
<packages><package name="p"><classes>
<class name="m" filename="m.py">
<methods><method name="f"><lines><line number="2" hits="5"/></lines></method></methods>
<lines>
<line number="1" hits="1"/>
<line number="2" hits="5" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
<line number="3" hits="0"/>
</lines>
</class>
<class name="n" filename="n.py"><lines><line number="1" hits="0"/></lines></class>
<class name="abs" filename="/abs/x.py"><lines><line number="7" hits="2"/></lines></class>
</classes></package></packages></coverage>"#,
tmp.path().join("b&amp;c").display()
);
let suite = parse(&xml, Path::new("/root")).unwrap().finish("Cobertura");
assert!(suite.has_branches);
let paths: Vec<&Path> = suite.files.iter().map(|f| f.path.as_ref() as &Path).collect();
// `m.py` exists under the second source; `n.py` falls back to the first.
assert_eq!(paths, [Path::new("/abs/x.py"), Path::new("/elsewhere/a/n.py"), second.join("m.py").as_path()]);
let m = &suite.files[2];
assert_eq!(
m.lines.iter().map(|l| (l.line, l.hits, l.branches_total, l.branches_covered)).collect::<Vec<_>>(),
[(0, 1, 0, 0), (1, 5, 2, 1), (2, 0, 0, 0)]
);
assert!(m.lines[1].partial());
assert_eq!(suite.files[0].lines[0].line, 6);
assert!(parse("<coverage><packages></coverage>", Path::new("/root")).is_err());
}
#[test]
fn filenames_without_sources_resolve_against_the_base() {
let xml = r#"<coverage><packages><package><classes><class filename="a/b.py"><lines><line number="1" hits="1"/></lines></class></classes></package></packages></coverage>"#;
let suite = parse(xml, Path::new("/root")).unwrap().finish("Cobertura");
assert_eq!(suite.files[0].path.as_ref() as &Path, Path::new("/root/a/b.py"));
assert!(!suite.has_branches);
assert_eq!(conditions("100% (4/4)"), Some((4, 4)));
assert_eq!(conditions("100%"), None);
}
}
+180
Переглянути файл
@@ -0,0 +1,180 @@
//! coverage.py data files (`.coverage`, and `.coverage.*` of parallel runs): SQLite databases of
//! executed lines and arcs. Which lines are statements, excluded or branches only comes from
//! analysing the source, so coverage.py in the project's interpreter combines the data into a
//! scratch file (`[paths]` of the project's configuration applies) and writes Cobertura XML.
use crate::{CoverageSuite, cobertura};
use ide_core::{IdeError, IdeResult};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::Command;
/// Whether `path` is an SQLite database (coverage.py 5+ data).
pub fn is_data_file(path: &Path) -> bool {
let mut head = [0u8; 16];
std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && &head == b"SQLite format 3\0"
}
/// `path`, or every `.coverage.*` file next to it when it is one of a parallel run's.
fn inputs(path: &Path) -> Vec<PathBuf> {
let parallel = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage."));
let mut files: Vec<PathBuf> = match (parallel, path.parent()) {
(true, Some(dir)) => std::fs::read_dir(dir)
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| {
p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage.")) && is_data_file(p)
})
.collect(),
_ => Vec::new(),
};
if files.is_empty() {
files.push(path.to_path_buf());
}
files.sort();
files
}
/// The files a `coverage xml -i` run skipped: `… No source for code: '<path>'. …`.
fn missing_sources(stderr: &str) -> Vec<PathBuf> {
stderr
.lines()
.filter_map(|l| l.split_once("No source for code: '")?.1.split_once("'.").map(|(p, _)| PathBuf::from(p)))
.collect()
}
fn coverage(python: &Path, root: &Path, args: &[&std::ffi::OsStr]) -> IdeResult<String> {
let out = ide_core::process::prepare(Command::new(python).current_dir(root))
.args(["-m", "coverage"])
.args(args)
.output()
.map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", python.display())))?;
let stderr = ide_core::output_encoding::decode_tool_output(&out.stderr);
if out.status.success() {
return Ok(stderr);
}
if stderr.contains("No module named coverage") {
return Err(IdeError::unavailable(format!(
"Reading a .coverage data file needs coverage.py in the project's interpreter ({}). Install it, or import the output of `coverage xml`.",
python.display()
)));
}
let text =
if stderr.trim().is_empty() { ide_core::output_encoding::decode_tool_output(&out.stdout) } else { stderr };
Err(IdeError::invalid(format!("coverage.py could not read the data: {}", text.trim())))
}
/// Reads the data file at `path` with `python`'s coverage.py, run in `root`; `out` holds the
/// scratch files. Blocking.
pub(crate) fn import(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult<CoverageSuite> {
let data = out.join(".coverage");
let xml = out.join("coverage.xml");
let inputs = inputs(path);
let mut args: Vec<&std::ffi::OsStr> =
vec!["combine".as_ref(), "--keep".as_ref(), "--data-file".as_ref(), data.as_ref()];
args.extend(inputs.iter().map(|p| p.as_os_str()));
coverage(python, root, &args)?;
// `-i`: report what has source here instead of failing on the first file that has none.
let stderr = coverage(
python,
root,
&["xml".as_ref(), "-i".as_ref(), "--data-file".as_ref(), data.as_ref(), "-o".as_ref(), xml.as_ref()],
)?;
let text = std::fs::read_to_string(&xml)?;
let mut acc = cobertura::parse(&text, root).map_err(|e| IdeError::invalid(format!("{}: {e}", xml.display())))?;
for file in missing_sources(&stderr) {
acc.file(&file);
}
Ok(acc.finish("coverage.py"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_the_files_of_a_parallel_run() {
let tmp = tempfile::tempdir().unwrap();
let db = |name: &str| {
let p = tmp.path().join(name);
std::fs::write(&p, b"SQLite format 3\0rest").unwrap();
p
};
let a = db(".coverage.host.1.x");
let b = db(".coverage.host.2.y");
let single = db(".coverage");
std::fs::write(tmp.path().join(".coverage.notes"), "text").unwrap();
std::fs::write(tmp.path().join(".coveragerc"), "[run]\n").unwrap();
assert!(is_data_file(&a) && !is_data_file(&tmp.path().join(".coveragerc")));
assert_eq!(inputs(&a), [a.clone(), b]);
assert_eq!(inputs(&single), [single]);
}
/// Two parallel runs recorded on another machine (`…/ci/app`), mapped by the project's `[paths]`.
/// Needs coverage.py in `python3`; skipped without it.
#[test]
fn combines_parallel_data_with_the_projects_paths() {
let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output();
if !has_coverage.is_ok_and(|o| o.status.success()) {
eprintln!("skipped: no coverage.py in python3");
return;
}
let tmp = tempfile::tempdir().unwrap();
// coverage.py reports real paths (`/private/var/…` for macOS's `/var/…`).
let base = tmp.path().canonicalize().unwrap();
let ci = base.join("ci/app");
let root = base.join("project");
let calc = "def sign(n):\n if n < 0:\n return -1\n return 1\n";
for dir in [&ci, &root] {
std::fs::create_dir_all(dir).unwrap();
std::fs::write(dir.join("calc.py"), calc).unwrap();
}
std::fs::write(ci.join("gone.py"), "x = 1\n").unwrap();
std::fs::write(ci.join("neg.py"), "import calc, gone\ncalc.sign(-1)\n").unwrap();
std::fs::write(ci.join("pos.py"), "import calc\ncalc.sign(1)\n").unwrap();
for script in ["neg.py", "pos.py"] {
let ok = Command::new("python3")
.current_dir(&ci)
.args(["-m", "coverage", "run", "--branch", "--parallel-mode", script])
.status()
.unwrap();
assert!(ok.success());
}
let data = root.join("data");
std::fs::create_dir_all(&data).unwrap();
for e in std::fs::read_dir(&ci).unwrap().flatten() {
if e.file_name().to_string_lossy().starts_with(".coverage.") {
std::fs::rename(e.path(), data.join(e.file_name())).unwrap();
}
}
std::fs::remove_dir_all(&ci).unwrap();
std::fs::write(root.join(".coveragerc"), "[paths]\nsource =\n ./\n */ci/app/\n").unwrap();
let first = std::fs::read_dir(&data).unwrap().flatten().next().unwrap().path();
let out = base.join("out");
std::fs::create_dir_all(&out).unwrap();
let suite = import(&first, &root, Path::new("python3"), &out).unwrap();
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("calc.py")).unwrap();
// Both runs together take both branches of line 2.
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (4, 4, 2, 2));
// The scripts and `gone.py` have no source in the project: listed without lines.
let empty: Vec<&str> = suite
.files
.iter()
.filter(|f| f.lines.is_empty())
.filter_map(|f| (f.path.as_ref() as &Path).file_name()?.to_str())
.collect();
assert_eq!(empty, ["gone.py", "neg.py", "pos.py"]);
// They keep the recorded path, so the import notification counts them as not in the project.
assert!(suite.files.iter().filter(|f| f.lines.is_empty()).all(|f| (f.path.as_ref() as &Path).starts_with(&ci)));
assert_eq!(std::fs::read_dir(&data).unwrap().count(), 2, "the user's data files are kept");
}
#[test]
fn reads_files_without_source_from_warnings() {
let stderr = "/v/lib/coverage/report_core.py:122: CoverageWarning: Couldn't parse '/ci/app/a.py': No source for code: '/ci/app/a.py'. (couldnt-parse); see https://coverage.readthedocs.io\n coverage._warn(msg, slug=\"couldnt-parse\")\n";
assert_eq!(missing_sources(stderr), [PathBuf::from("/ci/app/a.py")]);
}
}
+118 -8
Переглянути файл
@@ -1,9 +1,10 @@
//! "Import a report collected in CI from disk": the format is sniffed from the
//! content (lcov, Go cover profile, JaCoCo XML, SimpleCov resultset) and paths recorded on another
//! content (lcov, Go cover profile, JaCoCo or Cobertura XML, SimpleCov resultset) and paths recorded on another
//! machine are mapped into the project by their longest existing suffix.
use crate::{Accumulator, CoverageSuite, goprofile, jacoco, lcov, simplecov};
use crate::{Accumulator, CoverageSuite, cobertura, goprofile, jacoco, lcov, simplecov};
use ide_core::{IdeError, IdeResult};
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -11,13 +12,19 @@ pub(crate) enum Format {
Lcov,
GoProfile,
Jacoco,
Cobertura,
SimpleCov,
}
pub(crate) fn detect(text: &str) -> Option<Format> {
let head = text.trim_start_matches('\u{feff}').trim_start();
if head.starts_with('<') {
return head.contains("<report").then_some(Format::Jacoco);
// The root element, after any prolog or DOCTYPE naming it.
return match (head.find("<report"), head.find("<coverage")) {
(Some(r), c) if c.is_none_or(|c| r < c) => Some(Format::Jacoco),
(_, Some(_)) => Some(Format::Cobertura),
_ => None,
};
}
if head.starts_with('{') {
return head.contains("\"coverage\"").then_some(Format::SimpleCov);
@@ -39,6 +46,9 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
let (module, module_dir) = go_module_for(root, &text);
goprofile::parse(&text, &module, &module_dir).finish("go test -cover")
}
Some(Format::Cobertura) => cobertura::parse(&text, root)
.map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?
.finish("Cobertura"),
Some(Format::Jacoco) => {
// A report inside the project (`<module>/target/site/jacoco/…`) knows its module.
let module = jacoco::module_dir(path);
@@ -55,16 +65,16 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
}
None => {
return Err(IdeError::invalid(format!(
"{} is not an lcov tracefile, Go cover profile, JaCoCo XML report or SimpleCov resultset",
"{} is not an lcov tracefile, Go cover profile, JaCoCo or Cobertura XML report or SimpleCov resultset",
path.display()
)));
}
};
let mut dirs = HashMap::new();
for f in &mut suite.files {
let p: &Path = f.path.as_ref();
if !p.exists()
&& let Some(found) = relocate(p, root)
{
let present = p.parent().is_none_or(|d| dir_exists(d, &mut dirs)) && p.exists();
if !present && let Some(found) = relocate(p, root) {
f.path = found.into();
}
}
@@ -72,6 +82,24 @@ pub fn import(path: &Path, root: &Path) -> IdeResult<CoverageSuite> {
Ok(suite)
}
/// Reads a coverage.py data file (see [`crate::is_data_file`]) with the coverage.py of `python`,
/// run in `root`; `out` is an empty scratch directory. Blocking.
pub fn import_data(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult<CoverageSuite> {
crate::coveragepy::import(path, root, python, out)
}
/// Whether `dir` exists, without asking again below a directory known to be missing: every
/// lookup under macOS's `/home` (autofs) takes tens of milliseconds, and CI reports
/// (`/home/runner/work/…`) name thousands of files there.
fn dir_exists(dir: &Path, known: &mut HashMap<PathBuf, bool>) -> bool {
if let Some(&e) = known.get(dir) {
return e;
}
let e = dir.parent().is_none_or(|p| dir_exists(p, known)) && dir.is_dir();
known.insert(dir.to_path_buf(), e);
e
}
/// `/home/runner/work/app/app/src/lib.rs` → `<root>/src/lib.rs`: the longest suffix of
/// `path` that exists under `root`.
pub(crate) fn relocate(path: &Path, root: &Path) -> Option<PathBuf> {
@@ -129,12 +157,30 @@ mod tests {
detect("<?xml version=\"1.0\"?><!DOCTYPE report><report name=\"x\"></report>"),
Some(Format::Jacoco)
);
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), None);
assert_eq!(detect("<?xml version=\"1.0\"?><coverage/>"), Some(Format::Cobertura));
assert_eq!(
detect("<?xml version=\"1.0\"?><!DOCTYPE coverage SYSTEM \"x.dtd\"><coverage/>"),
Some(Format::Cobertura)
);
assert_eq!(detect("<?xml version=\"1.0\"?><html/>"), None);
assert_eq!(detect("{\"RSpec\": {\"coverage\": {}}}"), Some(Format::SimpleCov));
assert_eq!(detect("{\"name\": \"package.json\"}"), None);
assert_eq!(detect("hello"), None);
}
#[test]
fn missing_directories_are_looked_up_once() {
let tmp = tempfile::tempdir().unwrap();
let mut known = HashMap::new();
assert!(dir_exists(tmp.path(), &mut known));
let gone = tmp.path().join("gone");
assert!(!dir_exists(&gone.join("a/b"), &mut known));
std::fs::create_dir_all(gone.join("a/c")).unwrap();
// Known to be missing, so its subdirectories are not looked up.
assert!(!dir_exists(&gone.join("a/c"), &mut known));
assert_eq!(known.get(&gone), Some(&false));
}
#[test]
fn imports_ci_simplecov_with_foreign_paths() {
let tmp = tempfile::tempdir().unwrap();
@@ -170,6 +216,70 @@ mod tests {
assert!(import(&report, &root).is_err());
}
/// `coverage xml` (coverage.py 7.17, `--branch`) of a project checked out on a CI runner.
#[test]
fn imports_coverage_py_xml_with_foreign_sources() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("app");
std::fs::create_dir_all(root.join("src/calc")).unwrap();
std::fs::write(root.join("src/calc/__init__.py"), "").unwrap();
let report = tmp.path().join("coverage.xml");
std::fs::write(&report, COVERAGE_PY_XML).unwrap();
let suite = import(&report, &root).unwrap();
assert_eq!(suite.runner, "Cobertura");
assert!(suite.has_branches);
let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("src/calc/__init__.py")).unwrap();
assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (8, 5, 4, 2));
assert_eq!(calc.lines.iter().filter(|l| l.partial()).map(|l| l.line).collect::<Vec<_>>(), [1, 3]);
// The test file is not in this checkout: it keeps the runner's path.
assert!(
suite.files.iter().any(|f| f.path.as_ref() as &Path == Path::new("/home/runner/work/app/app/test_calc.py"))
);
}
const COVERAGE_PY_XML: &str = r#"<?xml version="1.0" ?>
<coverage version="7.17.5" timestamp="1795754882920" lines-valid="13" lines-covered="10" line-rate="0.7692" branches-valid="4" branches-covered="2" branch-rate="0.5" complexity="0">
<!-- Generated by coverage.py: https://coverage.readthedocs.io/en/7.17.5 -->
<!-- Based on https://raw.githubusercontent.com/cobertura/web/master/htdocs/xml/coverage-04.dtd -->
<sources>
<source>/home/runner/work/app/app</source>
</sources>
<packages>
<package name="." line-rate="1" branch-rate="1" complexity="0">
<classes>
<class name="test_calc.py" filename="test_calc.py" complexity="0" line-rate="1" branch-rate="1">
<methods/>
<lines>
<line number="1" hits="1"/>
<line number="2" hits="1"/>
<line number="3" hits="1"/>
<line number="6" hits="1"/>
<line number="7" hits="1"/>
</lines>
</class>
</classes>
</package>
<package name="src.calc" line-rate="0.625" branch-rate="0.5" complexity="0">
<classes>
<class name="__init__.py" filename="src/calc/__init__.py" complexity="0" line-rate="0.625" branch-rate="0.5">
<methods/>
<lines>
<line number="1" hits="1"/>
<line number="2" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="3"/>
<line number="3" hits="0"/>
<line number="4" hits="1" branch="true" condition-coverage="50% (1/2)" missing-branches="5"/>
<line number="5" hits="0"/>
<line number="6" hits="1"/>
<line number="13" hits="1"/>
<line number="14" hits="0"/>
</lines>
</class>
</classes>
</package>
</packages>
</coverage>
"#;
#[test]
fn imports_go_profiles_of_nested_modules() {
let tmp = tempfile::tempdir().unwrap();
+4 -1
Переглянути файл
@@ -16,6 +16,8 @@
//!
//! Lines in the model are 0-based, like every IPC coordinate.
mod cobertura;
mod coveragepy;
mod goprofile;
mod import;
mod jacoco;
@@ -23,7 +25,8 @@ mod lcov;
mod plan;
mod simplecov;
pub use import::import;
pub use coveragepy::is_data_file;
pub use import::{import, import_data};
pub use plan::prepare;
use ide_core::{IdeError, IdeResult, IpcPath};
+83
Переглянути файл
@@ -0,0 +1,83 @@
//! Python Debug Server (`attach` with `listen`): the program connects with its own debugpy,
//! which may differ from the IDE's adapter. Nothing in the protocol compares them.
use crate::session::Session;
use ide_core::IdeError;
use ide_core::event::DebugEvent;
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
pub(crate) fn listens(adapter: &str, request: &str, arguments: &Value) -> bool {
adapter == "debugpy" && request == "attach" && arguments.get("listen").is_some()
}
/// debugpy's adapter leaves an `attach` whose port is taken unanswered (it only logs the error),
/// which would wait for the program forever: find out before starting it.
pub(crate) fn require_free_port(arguments: &Value) -> Result<(), IdeError> {
let listen = &arguments["listen"];
let host = listen["host"].as_str().unwrap_or("127.0.0.1");
let Some(port) = listen["port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { return Ok(()) };
std::net::TcpListener::bind((host, port))
.map(drop)
.map_err(|e| IdeError::unavailable(format!("Cannot listen on {host}:{port}: {e}")))
}
/// On the program's first stop: warns in the Debug console when its debugpy is not the adapter's.
/// Evaluated in the stopped frame as a hover: without a frame, debugpy before 1.8 runs the
/// expression as a statement and prints its value into the program's output.
pub(crate) async fn check_version(s: Arc<Session>, thread: i64) {
const WAIT: Duration = Duration::from_secs(5);
let request = |command: &'static str, arguments: Value| s.conn.request_timeout(command, arguments, WAIT);
let Ok(info) = request("debugpySystemInfo", json!({})).await else { return };
let Some(ide) = info.pointer("/debugpy/version").and_then(Value::as_str) else { return };
let Ok(trace) = request("stackTrace", json!({ "threadId": thread, "levels": 1 })).await else { return };
let Some(frame) = trace.pointer("/stackFrames/0/id").and_then(Value::as_i64) else { return };
let expression = json!({ "expression": "__import__('debugpy').__version__", "frameId": frame, "context": "hover" });
let Ok(reply) = request("evaluate", expression).await else { return };
let Some(program) = reply.get("result").and_then(Value::as_str) else { return };
if let Some(warning) = version_warning(ide, program) {
s.emit(DebugEvent::Output { category: "console".into(), output: warning });
}
}
fn version_warning(ide: &str, program: &str) -> Option<String> {
let program = program.trim_matches(|c| c == '\'' || c == '"');
(program != ide).then(|| {
format!(
"The program uses debugpy {program}, the IDE's debugger debugpy {ide}. If breakpoints or stepping \
misbehave, install the same version where the program runs: pip install debugpy=={ide}\n"
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn warns_only_when_versions_differ() {
assert_eq!(version_warning("1.8.22", "'1.8.22'"), None);
assert_eq!(version_warning("1.8.22", "1.8.22"), None);
let w = version_warning("1.8.22", "'1.8.0'").unwrap();
assert!(w.contains("debugpy 1.8.0") && w.ends_with("pip install debugpy==1.8.22\n"), "{w}");
}
#[test]
fn a_taken_port_is_reported_before_the_adapter_starts() {
let taken = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let port = taken.local_addr().unwrap().port();
let listen = json!({"listen": {"host": "127.0.0.1", "port": port}});
let e = require_free_port(&listen).unwrap_err();
assert!(e.to_string().contains(&format!("Cannot listen on 127.0.0.1:{port}")), "{e}");
drop(taken);
assert!(require_free_port(&listen).is_ok());
}
#[test]
fn only_debugpy_listen_attaches_check() {
assert!(listens("debugpy", "attach", &json!({"listen": {"port": 5678}})));
assert!(!listens("debugpy", "attach", &json!({"connect": {"port": 5678}})));
assert!(!listens("debugpy", "launch", &json!({"listen": {}})));
}
}
+7
Переглянути файл
@@ -12,6 +12,7 @@ pub mod adapter;
pub mod attach;
mod cargo;
pub mod connection;
mod debugpy;
mod exception_classes;
pub mod jdwp;
mod js_cdp;
@@ -901,6 +902,9 @@ impl DebugManager {
exception_classes: Option<Arc<dyn ide_jvm_inspect::ExceptionClassBreakpoints>>,
) -> IdeResult<DebugSessionId> {
let mut arguments = launch_arguments(&config)?;
if debugpy::listens(&config.adapter, &config.request, &arguments) {
debugpy::require_free_port(&arguments)?;
}
// An IDE-side marker (never sent to the adapter): the session is a Flutter
// one regardless of what the working directory holds.
let force_flutter =
@@ -1149,6 +1153,9 @@ impl DebugManager {
});
tokio::spawn(session::event_loop(self.me.clone(), session.clone(), incoming));
if debugpy::listens(&session.adapter, &session.request, &arguments) {
session.debugpy_version_unchecked.store(true, Ordering::Release);
}
let configured = tokio::select! {
biased;
_ = session.startup_cancel.cancelled() => return Err(IdeError::cancelled()),
+8
Переглянути файл
@@ -75,6 +75,8 @@ pub(crate) struct Session {
pub jdwp_port: std::sync::OnceLock<u16>,
/// The attach goes through the listen-mode relay of [`crate::jdwp::listen_for_jvm`].
pub listen_relay: AtomicBool,
/// A Python Debug Server session whose program's debugpy version is checked on its first stop.
pub(crate) debugpy_version_unchecked: AtomicBool,
pub suspended: Suspension,
/// Pids signalled for the current stop: the reported pid and everything it started (an
/// adapter may report the launcher shell, whose child is the program).
@@ -316,6 +318,7 @@ impl Session {
jvm_pid: AtomicI64::new(0),
jdwp_port: std::sync::OnceLock::new(),
listen_relay: AtomicBool::new(false),
debugpy_version_unchecked: AtomicBool::new(false),
suspended: Suspension::default(),
stop_pids: parking_lot::Mutex::new(Vec::new()),
#[cfg(windows)]
@@ -854,6 +857,11 @@ async fn on_event(mgr: &Arc<DebugManager>, s: &Arc<Session>, event: &str, mut bo
all_threads_stopped: all,
});
});
if let Some(thread) = int("threadId")
&& s.debugpy_version_unchecked.swap(false, Ordering::AcqRel)
{
tokio::spawn(crate::debugpy::check_version(s.clone(), thread));
}
}
"continued" => {
let all = body.get("allThreadsContinued").and_then(Value::as_bool);
+4 -1
Переглянути файл
@@ -127,7 +127,10 @@ mod tests {
fn schema(name: &str, tables: &[&str]) -> CatalogSchema {
CatalogSchema {
name: name.into(),
tables: tables.iter().map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table }).collect(),
tables: tables
.iter()
.map(|t| TableInfo { name: (*t).into(), kind: DbTableKind::Table, comment: None })
.collect(),
}
}
+12 -7
Переглянути файл
@@ -655,7 +655,7 @@ impl DbManager {
}
}
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default, comment) by table.
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
for row in rows {
@@ -664,12 +664,15 @@ fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::
let data_type = it.next().flatten().unwrap_or_default();
let nullable = it.next().flatten().as_deref() != Some("0");
let has_default = it.next().flatten().is_some();
// Bridges built before the comment column send five fields.
let comment = it.next().flatten().filter(|c| !c.trim().is_empty());
by_table.entry(table).or_default().push(crate::CompletionColumn {
name,
data_type,
nullable,
primary_key: false,
has_default,
comment,
});
}
by_table
@@ -684,16 +687,18 @@ mod tests {
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
};
let by_table = schema_columns(vec![
row("orders", "id", "0", None),
row("orders", "note", "1", Some("'none'")),
row("items", "sku", "1", None),
vec![None, Some("orphan".into())],
]);
let mut commented = row("orders", "note", "1", Some("'none'"));
commented.push(Some("free text".into()));
let mut blank = row("items", "sku", "1", None);
blank.push(Some(" ".into()));
let by_table =
schema_columns(vec![row("orders", "id", "0", None), commented, blank, vec![None, Some("orphan".into())]]);
let orders = &by_table["orders"];
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
assert_eq!((orders[0].comment.as_deref(), orders[1].comment.as_deref()), (None, Some("free text")));
assert_eq!(by_table["items"][0].comment, None);
assert_eq!(by_table["items"].len(), 1);
assert_eq!(by_table.len(), 2);
}
+55 -5
Переглянути файл
@@ -31,7 +31,7 @@ pub use history::HistoryEntry;
pub use plan::{PlanNode, PlanProperty};
pub use source::{
DataSource, DbColor, DbDriver, DbExternalTunnel, DbIntrospection, DbOptions, DbProperty, DbSchemaSelection,
DbSnowflake, DbSnowflakeAuth, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
DbSnowflake, DbSnowflakeAuth, DbSourceFolder, DbSsh, DbSshAuth, DbSslMode, DbTxMode, DbVisibilityChange,
};
pub use sql::{CellValue, DbRowEdit, SortKey};
@@ -146,6 +146,10 @@ pub struct SchemaObject {
pub struct TableInfo {
pub name: String,
pub kind: DbTableKind,
/// The table's or view's comment; `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)]
@@ -157,6 +161,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 +180,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>,
@@ -200,6 +212,10 @@ pub struct CompletionColumn {
pub primary_key: bool,
/// Has a default (or is generated): optional in INSERT.
pub has_default: bool,
/// The column's comment; `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)]
@@ -560,6 +576,18 @@ impl DbManager {
None => {}
}
source::save(&self.root, &project)?;
if let Ok(mut folders) = source::load_folders(&self.root) {
let known: std::collections::HashSet<&str> = sources.iter().map(|source| source.id.as_str()).collect();
let mut changed = false;
for folder in &mut folders {
let before = folder.sources.len();
folder.sources.retain(|id| known.contains(id.as_str()));
changed |= folder.sources.len() != before;
}
if changed {
source::save_folders(&self.root, &folders)?;
}
}
old
};
for o in old {
@@ -1095,7 +1123,11 @@ impl DbManager {
.filter_map(|r| {
let mut it = r.into_iter();
let name = it.next().flatten()?;
Some(TableInfo { name, kind: DbTableKind::from_catalog(it.next().flatten().as_deref()) })
Some(TableInfo {
name,
kind: DbTableKind::from_catalog(it.next().flatten().as_deref()),
comment: it.next().flatten().filter(|comment| !comment.is_empty()),
})
})
.collect())
}
@@ -1119,11 +1151,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 +1214,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
@@ -1470,6 +1519,7 @@ impl DbManager {
nullable: flag(&Some(next())),
primary_key: flag(&Some(next())),
has_default: flag(&Some(next())),
comment: Some(next()).filter(|c| !c.trim().is_empty()),
};
if name.is_empty() || column.name.is_empty() {
continue;
+22 -3
Переглянути файл
@@ -113,7 +113,11 @@ pub(crate) async fn tables(pool: &SnowflakePool, schema: &str) -> IdeResult<Vec<
Ok(shown
.records()
.filter_map(|r| {
Some(TableInfo { name: r.get("name")?.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) })
Some(TableInfo {
name: r.get("name")?.to_owned(),
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
})
})
.collect())
}
@@ -132,6 +136,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 +145,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> {
@@ -228,7 +242,11 @@ pub(crate) async fn catalog(pool: &SnowflakePool, database: &str) -> IdeResult<V
let (Some(&index), Some(name)) = (at.get(r.get("schema_name").unwrap_or_default()), r.get("name")) else {
continue;
};
out[index].tables.push(TableInfo { name: name.to_owned(), kind: table_kind(r.get("kind").unwrap_or("TABLE")) });
out[index].tables.push(TableInfo {
name: name.to_owned(),
kind: table_kind(r.get("kind").unwrap_or("TABLE")),
comment: r.get("comment").filter(|comment| !comment.is_empty()).map(str::to_owned),
});
}
for schema in &mut out {
schema.tables.sort_by(|a, b| a.name.cmp(&b.name));
@@ -437,6 +455,7 @@ pub(crate) async fn completion(pool: &SnowflakePool) -> IdeResult<Vec<Completion
primary_key: false,
has_default: r.get("default").is_some_and(|d| !d.is_empty())
|| r.get("autoincrement").is_some_and(|a| !a.is_empty()),
comment: r.get("comment").filter(|c| !c.trim().is_empty()).map(str::to_owned),
});
}
Ok(tables)
+138 -2
Переглянути файл
@@ -1,15 +1,17 @@
//! Data sources: per-project connection settings in `.openidea/data-sources.toml`, and
//! global ones (IDEA's Make Global: listed in every project) in `data-sources.toml` of the
//! app data directory. Passwords never go there: saved ones live in [`crate::secrets`],
//! app data directory. Project folder grouping is in `.openidea/data-source-folders.toml`.
//! Passwords never go there: saved ones live in [`crate::secrets`],
//! the others only in memory for the session.
use ide_core::{IdeError, IdeResult, IpcPath, project_dir};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashSet};
use std::path::Path;
pub(crate) const FILE: &str = "data-sources.toml";
pub(crate) const FOLDERS_FILE: &str = "data-source-folders.toml";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -697,6 +699,108 @@ fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> {
Ok(())
}
/// A user folder grouping data sources in one project's Database tree.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct DbSourceFolder {
pub id: String,
pub name: String,
/// Reserved for nested folders; the first UI version only creates root folders.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<String>,
pub order: i32,
pub sources: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
struct SourceFoldersFile {
#[serde(default = "folders_version")]
version: u32,
#[serde(default, rename = "folder")]
folders: Vec<DbSourceFolder>,
}
fn folders_version() -> u32 {
1
}
/// The project's data source folders and their members.
pub fn load_folders(root: &Path) -> IdeResult<Vec<DbSourceFolder>> {
let path = project_dir::path(root, FOLDERS_FILE);
let text = match std::fs::read_to_string(&path) {
Ok(text) => text,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(e.into()),
};
let file: SourceFoldersFile =
toml::from_str(&text).map_err(|e| IdeError::invalid(format!("{}: {e}", path.display())))?;
if file.version > 1 {
return Err(IdeError::invalid(format!(
"{}: folder format version {} is newer than this OpenIDEA",
path.display(),
file.version
)));
}
Ok(file.folders)
}
/// Replaces the project's data source folders after validating ids, parents and memberships.
pub fn save_folders(root: &Path, folders: &[DbSourceFolder]) -> IdeResult<()> {
validate_folders(folders)?;
let path = project_dir::path(root, FOLDERS_FILE);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let file = SourceFoldersFile { version: folders_version(), folders: folders.to_vec() };
let text = toml::to_string_pretty(&file).map_err(|e| IdeError::internal(e.to_string()))?;
let tmp = path.with_file_name(format!(".{FOLDERS_FILE}.{}.tmp", uuid::Uuid::new_v4()));
std::fs::write(&tmp, text)?;
if let Err(e) = std::fs::rename(&tmp, &path) {
let _ = std::fs::remove_file(&tmp);
return Err(e.into());
}
Ok(())
}
fn validate_folders(folders: &[DbSourceFolder]) -> IdeResult<()> {
let mut ids = HashSet::new();
let mut members = HashSet::new();
for folder in folders {
if folder.id.trim().is_empty() || folder.name.trim().is_empty() {
return Err(IdeError::invalid("every data source folder needs an id and a name"));
}
if !ids.insert(folder.id.as_str()) {
return Err(IdeError::invalid(format!("duplicate data source folder id '{}'", folder.id)));
}
for source in &folder.sources {
if source.is_empty() {
return Err(IdeError::invalid(format!("folder '{}' has an empty data source id", folder.name)));
}
if !members.insert(source.as_str()) {
return Err(IdeError::invalid(format!("data source '{source}' belongs to more than one folder")));
}
}
}
for folder in folders {
let mut seen = HashSet::new();
let mut parent = folder.parent.as_deref();
while let Some(id) = parent {
if id == folder.id || !seen.insert(id) {
return Err(IdeError::invalid(format!("data source folder '{}' has a parent cycle", folder.name)));
}
parent =
folders.iter().find(|candidate| candidate.id == id).and_then(|candidate| candidate.parent.as_deref());
if parent.is_none() && !folders.iter().any(|candidate| candidate.id == id) {
return Err(IdeError::invalid(format!(
"data source folder '{}' has an unknown parent '{id}'",
folder.name
)));
}
}
}
Ok(())
}
/// Credential store access. Blocking (may show an OS prompt): call off the async runtime.
/// Keys are data source ids; [`secrets::ssh_key`] names the SSH password / passphrase.
#[cfg(test)]
@@ -724,6 +828,38 @@ mod tests {
assert!(save(tmp.path(), &[DataSource::default()]).is_err());
}
#[test]
fn source_folders_round_trip_and_reject_invalid_memberships() {
let tmp = tempfile::tempdir().unwrap();
let folders = vec![
DbSourceFolder {
id: "prod".into(),
name: "Production".into(),
parent: None,
order: 0,
sources: vec!["pg".into(), "mysql".into()],
},
DbSourceFolder { id: "empty".into(), name: "Empty".into(), parent: None, order: 1, sources: vec![] },
];
save_folders(tmp.path(), &folders).unwrap();
assert_eq!(load_folders(tmp.path()).unwrap(), folders);
let duplicate = vec![
DbSourceFolder { sources: vec!["pg".into()], ..folders[0].clone() },
DbSourceFolder { id: "other".into(), sources: vec!["pg".into()], ..folders[1].clone() },
];
assert!(save_folders(tmp.path(), &duplicate).is_err());
let cycle = vec![
DbSourceFolder { parent: Some("b".into()), ..folders[0].clone() },
DbSourceFolder { id: "b".into(), parent: Some("prod".into()), ..folders[1].clone() },
];
assert!(save_folders(tmp.path(), &cycle).is_err());
let missing = vec![DbSourceFolder { parent: Some("missing".into()), ..folders[0].clone() }];
assert!(save_folders(tmp.path(), &missing).is_err());
}
#[test]
fn reads_configs_written_before_the_new_settings() {
let tmp = tempfile::tempdir().unwrap();
+97 -25
Переглянути файл
@@ -95,46 +95,52 @@ pub fn schemas(driver: DbDriver, system: bool) -> &'static str {
}
}
/// Rows: `name, kind` where kind is `table`, `view` or `materialized view`.
/// Rows: `name, kind, comment` where kind is `table`, `view` or `materialized view`.
pub fn tables(driver: DbDriver, schema: &str) -> String {
match driver {
DbDriver::Jdbc => unreachable!("JDBC introspection uses DatabaseMetaData"),
DbDriver::Clickhouse => format!(
"SELECT name, CASE engine WHEN 'View' THEN 'view' WHEN 'MaterializedView' THEN 'materialized view' \
WHEN 'WindowView' THEN 'view' ELSE 'table' END FROM system.tables \
WHEN 'WindowView' THEN 'view' ELSE 'table' END, comment FROM system.tables \
WHERE database = {} AND is_temporary = 0 ORDER BY name",
quote_literal(driver, schema)
),
DbDriver::Sqlite => format!(
"SELECT name, type FROM {}.sqlite_master WHERE type IN ('table', 'view') \
"SELECT name, type, NULL FROM {}.sqlite_master WHERE type IN ('table', 'view') \
AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name",
quote_ident(driver, schema)
),
DbDriver::Snowflake => format!(
"SELECT table_name, CASE table_type WHEN 'VIEW' THEN 'view' WHEN 'MATERIALIZED VIEW' THEN 'materialized view' \
ELSE 'table' END FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
ELSE 'table' END, comment FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::Oracle => format!(
"SELECT table_name, 'table' FROM all_tables WHERE owner = {} \
UNION ALL SELECT view_name, 'view' FROM all_views WHERE owner = {} ORDER BY 1",
quote_literal(driver, schema),
"SELECT table_name, CASE WHEN table_type = 'VIEW' THEN 'view' ELSE 'table' END, comments \
FROM all_tab_comments WHERE owner = {} ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::Postgres => format!(
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END \
"SELECT c.relname, CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' ELSE 'table' END, \
obj_description(c.oid, 'pg_class') \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \
WHERE n.nspname = {} AND c.relkind IN ('r', 'v', 'm', 'p', 'f') ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::Mysql => format!(
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
"SELECT table_name, CASE WHEN table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
CASE WHEN table_type LIKE '%VIEW%' THEN NULL ELSE NULLIF(table_comment, '') END \
FROM information_schema.tables WHERE table_schema = {} ORDER BY 1",
quote_literal(driver, schema)
),
DbDriver::SqlServer => format!(
"SELECT TABLE_NAME, CASE WHEN TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END \
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = {} ORDER BY 1",
"SELECT t.TABLE_NAME, CASE WHEN t.TABLE_TYPE LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
CAST(ep.value AS nvarchar(max)) \
FROM INFORMATION_SCHEMA.TABLES t \
LEFT JOIN sys.extended_properties ep \
ON ep.major_id = OBJECT_ID(QUOTENAME(t.TABLE_SCHEMA) + '.' + QUOTENAME(t.TABLE_NAME)) \
AND ep.minor_id = 0 AND ep.name = 'MS_Description' \
WHERE t.TABLE_SCHEMA = {} ORDER BY 1",
quote_literal(driver, schema)
),
}
@@ -145,7 +151,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 +160,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 +173,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 +200,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 +214,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
@@ -275,7 +307,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
"SELECT c.database, c.table, CASE t.engine WHEN 'View' THEN 'view' \
WHEN 'MaterializedView' THEN 'materialized view' WHEN 'WindowView' THEN 'view' ELSE 'table' END, \
c.name, c.type, CASE WHEN startsWith(c.type, 'Nullable(') \
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1 \
OR startsWith(c.type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, c.is_in_primary_key, 1, c.comment \
FROM system.columns c JOIN system.tables t ON t.database = c.database AND t.name = c.table \
WHERE lower(c.database) NOT IN ('system', 'information_schema') AND t.is_temporary = 0",
"c.database",
@@ -286,7 +318,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
CASE WHEN p.pk > 0 THEN 1 ELSE 0 END, \
CASE WHEN p.dflt_value IS NOT NULL THEN 1 \
WHEN p.pk = 1 AND upper(p.type) = 'INTEGER' \
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END \
AND (SELECT count(*) FROM pragma_table_info(m.name) k WHERE k.pk > 0) = 1 THEN 1 ELSE 0 END, NULL \
FROM sqlite_master m JOIN pragma_table_info(m.name) p \
WHERE m.type IN ('table', 'view') AND m.name NOT LIKE 'sqlite\\_%' ESCAPE '\\'",
"'main'",
@@ -299,7 +331,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
AND a.attnum = ANY(i.indkey)) THEN 1 ELSE 0 END, \
CASE WHEN a.atthasdef OR EXISTS (SELECT 1 FROM pg_depend d WHERE d.refclassid = 'pg_class'::regclass \
AND d.refobjid = c.oid AND d.refobjsubid = a.attnum AND d.classid = 'pg_class'::regclass \
AND d.deptype = 'i') THEN 1 ELSE 0 END \
AND d.deptype = 'i') THEN 1 ELSE 0 END, col_description(c.oid, a.attnum) \
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = c.oid \
WHERE c.relkind IN ('r', 'v', 'm', 'p', 'f') AND a.attnum > 0 AND NOT a.attisdropped \
AND n.nspname NOT IN ('pg_catalog', 'information_schema') \
@@ -310,7 +342,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
DbDriver::Mysql => (
"SELECT c.table_schema, c.table_name, CASE WHEN t.table_type LIKE '%VIEW%' THEN 'view' ELSE 'table' END, \
c.column_name, c.column_type, c.is_nullable, CASE WHEN c.column_key = 'PRI' THEN 1 ELSE 0 END, \
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END \
CASE WHEN c.column_default IS NOT NULL OR c.extra LIKE '%auto_increment%' THEN 1 ELSE 0 END, c.column_comment \
FROM information_schema.columns c JOIN information_schema.tables t \
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
WHERE c.table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')",
@@ -325,7 +357,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
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, \
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END \
CASE WHEN c.COLUMN_DEFAULT IS NOT NULL THEN 1 ELSE 0 END, NULL \
FROM INFORMATION_SCHEMA.COLUMNS c JOIN INFORMATION_SCHEMA.TABLES t \
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME \
WHERE c.TABLE_SCHEMA NOT IN ('sys', 'INFORMATION_SCHEMA')",
@@ -335,7 +367,7 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
DbDriver::Snowflake => (
"SELECT c.table_schema, c.table_name, CASE t.table_type WHEN 'VIEW' THEN 'view' \
WHEN 'MATERIALIZED VIEW' THEN 'materialized view' ELSE 'table' END, c.column_name, c.data_type, \
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END \
c.is_nullable, 0, CASE WHEN c.column_default IS NOT NULL THEN 1 ELSE 0 END, c.comment \
FROM information_schema.columns c JOIN information_schema.tables t \
ON t.table_schema = c.table_schema AND t.table_name = c.table_name \
WHERE c.table_schema <> 'INFORMATION_SCHEMA'",
@@ -346,8 +378,10 @@ pub fn completion_columns(driver: DbDriver, scope: CompletionScope) -> String {
"SELECT c.owner, c.table_name, CASE WHEN v.view_name IS NOT NULL THEN 'view' ELSE 'table' END, \
c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), \
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, \
CASE WHEN c.data_default IS NOT NULL THEN 1 ELSE 0 END \
CASE WHEN c.data_default 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 all_views v ON v.owner = c.owner AND v.view_name = c.table_name \
LEFT JOIN (SELECT con.owner, con.table_name, kc.column_name FROM all_constraints con \
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
@@ -956,6 +990,40 @@ 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"));
assert!(tables(DbDriver::Postgres, "public").contains("obj_description(c.oid, 'pg_class')"));
assert!(tables(DbDriver::Mysql, "db").contains("table_comment"));
assert!(tables(DbDriver::Oracle, "S").contains("all_tab_comments"));
assert!(tables(DbDriver::Clickhouse, "db").contains("END, comment FROM system.tables"));
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
// Completion (the hover card of a table or column) carries them too, as the ninth field.
let completion = |driver| completion_columns(driver, CompletionScope::All);
assert!(completion(DbDriver::Postgres).contains("col_description(c.oid, a.attnum)"));
assert!(completion(DbDriver::Mysql).contains("ELSE 0 END, c.column_comment"));
assert!(
completion(DbDriver::Oracle).contains("cc.comments")
&& completion(DbDriver::Oracle).contains("all_col_comments")
);
assert!(completion(DbDriver::Clickhouse).contains("c.is_in_primary_key, 1, c.comment"));
assert!(completion(DbDriver::Snowflake).contains("ELSE 0 END, c.comment"));
for driver in [DbDriver::Sqlite, DbDriver::SqlServer] {
assert!(completion(driver).contains("ELSE 0 END, NULL"), "{driver:?}");
}
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;
@@ -973,6 +1041,7 @@ mod tests {
assert_eq!(current_schema(driver), Some("SELECT currentDatabase()"));
let relations = tables(driver, "event's\\db");
assert!(relations.contains("WHEN 'MaterializedView' THEN 'materialized view'"));
assert!(relations.contains(r"END, comment FROM system.tables"));
assert!(relations.contains(r"WHERE database = 'event''s\\db' AND is_temporary = 0"));
let fields = columns(driver, "default", "events");
assert!(fields.starts_with("SELECT name, type, CASE WHEN startsWith(type, 'Nullable(')"));
@@ -1088,6 +1157,7 @@ mod tests {
#[test]
fn sqlserver_introspection_queries() {
assert!(tables(DbDriver::SqlServer, "dbo").contains("INFORMATION_SCHEMA.TABLES"));
assert!(tables(DbDriver::SqlServer, "dbo").contains("sys.extended_properties"));
assert!(columns(DbDriver::SqlServer, "dbo", "t").contains("INFORMATION_SCHEMA.COLUMNS"));
assert!(indexes(DbDriver::SqlServer, "dbo", "t").contains("sys.indexes"));
assert!(foreign_keys(DbDriver::SqlServer).contains("sys.foreign_key_columns"));
@@ -1164,8 +1234,10 @@ mod tests {
assert_eq!(DbDriver::Oracle.default_port(), Some(1521));
assert!(schemas(DbDriver::Oracle, true).contains("all_users"));
assert!(schemas(DbDriver::Oracle, false).contains("'MDSYS'"));
assert!(tables(DbDriver::Oracle, "hr").contains("all_tables"));
assert!(tables(DbDriver::Oracle, "hr").contains("all_views"));
let relations = tables(DbDriver::Oracle, "hr");
assert!(relations.contains("all_tab_comments"));
assert!(relations.contains("table_type = 'VIEW'"));
assert!(relations.contains("comments"));
let cols = columns(DbDriver::Oracle, "hr", "employees");
assert!(cols.contains("all_tab_columns"));
assert!(cols.contains("DECODE(c.nullable, 'Y', 'YES', 'NO')"));
+10 -6
Переглянути файл
@@ -1,9 +1,9 @@
//! Data source files edited outside the Database tool window (by hand, by a coding
//! agent, by `git checkout`) are picked up while the project is open, as IDEA does
//! Data source and data source folder files edited outside the Database tool window
//! (by hand, by a coding agent, by `git checkout`) are picked up while the project is open, as IDEA does
//! for `dataSources.xml`. The project file tree's watcher is no help here: it never
//! reports a modification inside a gitignored `.openidea/`.
use crate::source::FILE;
use crate::source::{FILE, FOLDERS_FILE};
use ide_core::{IdeError, IdeResult, project_dir};
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use parking_lot::Mutex;
@@ -15,8 +15,8 @@ use std::time::Duration;
/// the files are read.
const SETTLE: Duration = Duration::from_millis(200);
/// Watches `<root>/.openidea/data-sources.toml` and `<global>/data-sources.toml`;
/// stops when dropped.
/// Watches `<root>/.openidea/data-sources.toml`, `data-source-folders.toml` and
/// `<global>/data-sources.toml`; stops when dropped.
pub struct SourcesWatch {
_watcher: Arc<Mutex<RecommendedWatcher>>,
}
@@ -29,7 +29,7 @@ impl SourcesWatch {
let (tx, rx) = mpsc::channel::<()>();
let relevant = {
let config = config.clone();
move |p: &Path| p.file_name().is_some_and(|n| n == FILE) || p == config
move |p: &Path| p.file_name().is_some_and(|n| n == FILE || n == FOLDERS_FILE) || p == config
};
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
if let Ok(e) = res
@@ -131,6 +131,10 @@ mod tests {
std::fs::write(project.join(".openidea/data-sources.toml"), "").unwrap();
assert!(wait_for(&count, seen + 1), "project file");
let seen = count.load(Ordering::SeqCst);
std::fs::write(project.join(".openidea/data-source-folders.toml"), "").unwrap();
assert!(wait_for(&count, seen + 1), "project folders file");
let seen = count.load(Ordering::SeqCst);
std::fs::write(global.join("data-sources.toml"), "").unwrap();
assert!(wait_for(&count, seen + 1), "global file");
+6 -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)"),
@@ -56,9 +57,13 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
assert!(schemas.iter().any(|n| n == s), "{s} missing from {schemas:?}");
let tables = db.tables("m", s).await?;
assert_eq!(tables.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["用户"], "tables of {s}");
assert_eq!(tables[0].comment.as_deref(), Some("用户表"));
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 `用户`"));
}
+9
Переглянути файл
@@ -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,13 @@ 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 listed = db.tables("p", "oi_meta").await?;
let listed_orders = listed.iter().find(|table| table.name == "orders").expect("orders in the table list");
assert_eq!(listed_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"]);
+22 -13
Переглянути файл
@@ -27,18 +27,24 @@ const QUICK: Duration = Duration::from_secs(20);
/// Stop / restart wait for the container's grace period (10 s by default).
const LIFECYCLE: Duration = Duration::from_secs(90);
/// Locates the docker executable once per process. GUI apps on macOS start with a
/// minimal `PATH`, so the usual install locations are probed after the lookup.
/// Locates the docker executable. GUI apps on macOS start with a minimal `PATH`, so
/// the login/reloaded `PATH` and usual install locations are probed after the lookup.
/// Only a found path is cached, so installing Docker while the backend runs is picked up.
pub fn docker_executable() -> Option<PathBuf> {
static DOCKER: OnceLock<Option<PathBuf>> = OnceLock::new();
DOCKER
.get_or_init(|| {
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
return Some(explicit);
}
if let Ok(found) = which::which("docker") {
return Some(found);
}
if let Some(explicit) = std::env::var_os("OPENIDEA_DOCKER").map(PathBuf::from).filter(|p| p.is_file()) {
return Some(explicit);
}
static DOCKER: OnceLock<PathBuf> = OnceLock::new();
if let Some(cached) = DOCKER.get().filter(|p| p.is_file()) {
return Some(cached.clone());
}
let found = which::which("docker")
.ok()
.or_else(|| {
let path = ide_core::process::host_var_os("PATH")?;
which::which_in("docker", Some(path), ".").ok()
})
.or_else(|| {
let home = std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from);
let mut candidates: Vec<PathBuf> = if cfg!(windows) {
vec![PathBuf::from(r"C:\Program Files\Docker\Docker\resources\bin\docker.exe")]
@@ -60,8 +66,11 @@ pub fn docker_executable() -> Option<PathBuf> {
candidates.push(home.join(".docker/bin/docker"));
}
candidates.into_iter().find(|p| p.is_file())
})
.clone()
});
if let Some(ref path) = found {
let _ = DOCKER.set(path.clone());
}
found
}
/// Environment for docker command lines a run configuration launches: the endpoint's
-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);
}
}
+5
Переглянути файл
@@ -82,6 +82,11 @@ impl Environment {
}
}
/// True on `openidea-server`, where the backend runs on a remote/headless host rather than the desktop shell.
pub fn is_remote(&self) -> bool {
self.project_env
}
/// A trusted project at `root` opened or became trusted: loads its direnv environment in
/// the background, unless another window of it already did. Its language servers wait.
pub(crate) fn direnv_opened(&self, root: &Path, sink: &SharedSink) {
+26 -1
Переглянути файл
@@ -261,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,
@@ -295,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)
@@ -897,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();
+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);
}
}
+10
Переглянути файл
@@ -12,6 +12,7 @@ pub mod diagnostics_store;
mod direnv;
pub mod environment;
mod formatter;
pub mod github_auth;
mod java_runtime;
mod kotlin_bridge;
pub mod mcp;
@@ -124,6 +125,7 @@ pub struct Host {
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
/// The IDE's Java build: resident javac processes shared by every window's launches.
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
pub(crate) metrics_sampler: Mutex<ops::host_metrics::HostMetricsSampler>,
/// SSH connections of Settings › SSH Configurations.
pub ssh: Arc<ide_ssh::SshManager>,
/// SFTP deployment, remote file editing and runs on run targets.
@@ -254,6 +256,7 @@ impl Host {
heap_requests: Default::default(),
rebase_editors: Default::default(),
java_build: Default::default(),
metrics_sampler: Default::default(),
languages,
syntax,
config_dir,
@@ -419,6 +422,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 {
@@ -701,6 +705,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()) {
+5
Переглянути файл
@@ -38,6 +38,11 @@ impl Requests {
let _ = pending.answer.send(error.map_or(Ok(allow), Err));
Ok(())
}
/// Whether `window` answers requests (a project loaded for MCP alone has no window).
pub(super) fn window_ready(&self, window: &str) -> bool {
self.0.lock().ready.contains(window)
}
pub(super) async fn ask(&self, call: &Call, request: McpUiRequest) -> IdeResult<()> {
let id = super::tool::request_id().0;
let (tx, rx) = oneshot::channel();
+87 -7
Переглянути файл
@@ -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::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant};
@@ -286,6 +287,79 @@ workingDirectory, envs).",
/// not the user's own runs.
static STARTED: LazyLock<Mutex<HashSet<RunId>>> = LazyLock::new(Default::default);
/// Run configuration parameter naming the `execute_run_configuration` call a start belongs to.
pub const CONFIG_RUN_PARAM: &str = "mcp.configRun";
/// The `execute_run_configuration` calls waiting for the Run tool window to start their run.
struct ConfigLaunch {
output: Arc<Mutex<OutputCollector>>,
started: Option<Result<ide_run::RunInfo, String>>,
}
static LAUNCHES: LazyLock<Mutex<HashMap<u64, ConfigLaunch>>> = LazyLock::new(Default::default);
static NEXT_LAUNCH: AtomicU64 = AtomicU64::new(1);
/// The Run tool window's start of an `execute_run_configuration` run: its output also goes to
/// the call's output file, and the call learns the run it started.
pub(crate) struct ConfigRunLaunch {
token: u64,
output: Arc<Mutex<OutputCollector>>,
}
/// The call `config` was started for (its first start only; a rerun from the tab is the user's).
pub(crate) fn config_run_launch(config: &RunConfig) -> Option<ConfigRunLaunch> {
let token = config.extras.params.get(CONFIG_RUN_PARAM)?.parse().ok()?;
let launches = LAUNCHES.lock();
let launch = launches.get(&token).filter(|l| l.started.is_none())?;
Some(ConfigRunLaunch { token, output: launch.output.clone() })
}
impl ConfigRunLaunch {
pub(crate) fn wrap_output(&self, on_output: crate::ops::Emit<OutputChunk>) -> crate::ops::Emit<OutputChunk> {
let output = self.output.clone();
Arc::new(move |chunk: OutputChunk| {
// As JetBrains skips `ProcessOutputType.SYSTEM` (`Process finished…`).
if let OutputChunk::Stdout { text } | OutputChunk::Stderr { text } = &chunk {
output.lock().append(text);
}
on_output(chunk);
})
}
pub(crate) fn started(&self, result: &IdeResult<ide_run::RunInfo>) {
if let Some(launch) = LAUNCHES.lock().get_mut(&self.token) {
launch.started = Some(result.clone().map_err(|e| e.message));
}
}
}
/// Starts `config` in the Run tool window, as the user's Run would: a tab with its console and
/// Stop. Its before launch tasks already ran.
async fn start_in_run_window(
call: &Call,
mut config: RunConfig,
output: Arc<Mutex<OutputCollector>>,
) -> IdeResult<ide_run::RunInfo> {
struct Forget(u64);
impl Drop for Forget {
fn drop(&mut self) {
LAUNCHES.lock().remove(&self.0);
}
}
let token = NEXT_LAUNCH.fetch_add(1, Ordering::Relaxed);
LAUNCHES.lock().insert(token, ConfigLaunch { output, started: None });
let _forget = Forget(token);
config.extras.params.insert(CONFIG_RUN_PARAM.into(), token.to_string());
let config = serde_json::to_value(&config).map_err(|e| IdeError::invalid(e.to_string()))?;
let asked = call.ask(ide_core::event::McpUiRequest::RunConfiguration { config }).await;
let started = LAUNCHES.lock().get_mut(&token).and_then(|l| l.started.take());
match (asked, started) {
(_, Some(Ok(info))) => Ok(info),
(_, Some(Err(message))) => Err(IdeError::invalid(message)),
(Err(e), None) => Err(e),
(Ok(()), None) => Err(IdeError::invalid("the run did not start")),
}
}
pub(super) fn started_by_mcp(id: RunId) -> bool {
STARTED.lock().contains(&id)
}
@@ -753,9 +827,9 @@ 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: while it is still running, the result carries `runId`, which `stop_run` stops; output files are private \
and deleted after a day.",
arguments (appended to a command that is one shell line, such as `npm run dev`); the run appears in the Run tool \
window like a run the user started, with its console and Stop; 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")?,
@@ -811,9 +885,15 @@ one by one",
};
let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?));
let output_path = collector.lock().path.clone();
let sink = collector.clone();
let emit = process_output(move |text| sink.lock().append(text));
let info = match crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await {
let started = if call.has_window() {
start_in_run_window(&call, config, collector.clone()).await
} else {
// A project loaded for MCP alone has no Run tool window to show it in.
let sink = collector.clone();
let emit = process_output(move |text| sink.lock().append(text));
crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await
};
let info = match started {
Ok(info) => info,
Err(e) => {
let _ = std::fs::remove_file(&output_path);
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@
pub(crate) mod agent;
mod agent_tools;
mod build;
mod configs;
pub(crate) mod configs;
mod output;
mod process;
mod targets;
+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");
+4
Переглянути файл
@@ -70,6 +70,10 @@ impl Call {
pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> {
self.host.mcp_requests.ask(self, request).await
}
/// Whether the project has a window to show what the tool starts (not one loaded for MCP alone).
pub fn has_window(&self) -> bool {
self.host.mcp_requests.window_ready(&self.window)
}
/// Asks the user before a tool changes the project or starts a process, unless brave mode
/// is on — read from the IDE's own settings only, which a project's settings can't set.
pub async fn confirm(&self, subject: &str, detail: Option<String>) -> IdeResult<()> {
+2
Переглянути файл
@@ -754,6 +754,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
));
let mut tools = vec![
act("code.saveAsLiveTemplate", "Save as Live Template…"),
SEP,
act("http.newRequest", "New HTTP Request"),
act("http.showToolWindow", "HTTP Client"),
SEP,
+182 -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)]
@@ -108,6 +121,141 @@ 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)
}
}
}
const REMOTE_SESSION_ENV_VARS: [&str; 5] =
["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "CODESPACES", "REMOTE_CONTAINERS"];
fn prepare_login_launch_env(
is_remote: bool,
target_is_gh: bool,
env: &mut std::collections::BTreeMap<String, String>,
host_has: impl Fn(&str) -> bool,
) {
if !is_remote {
return;
}
let has_non_empty = |env: &std::collections::BTreeMap<String, String>, key: &str| {
env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key)
};
// `openidea-server` spawns sign-in commands in a real PTY even inside WSL, dev containers,
// and `--web`, where `SSH_*` variables are absent; mark the session remote so CLIs such as
// `copilot login` choose OAuth device-code sign-in over a remote-only loopback server.
if !REMOTE_SESSION_ENV_VARS.iter().any(|key| has_non_empty(env, key)) {
env.insert("REMOTE_CONTAINERS".into(), "1".into());
}
if target_is_gh && !has_non_empty(env, "GH_BROWSER") && !has_non_empty(env, "BROWSER") {
env.insert("GH_BROWSER".into(), "true".into());
}
}
fn apply_remote_login_env(host: &Host, cwd: &std::path::Path, target_is_gh: bool, launch: &mut LoginLaunch) {
let cwd = if cwd.is_dir() { cwd.to_path_buf() } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
prepare_login_launch_env(host.environment.is_remote(), target_is_gh, &mut launch.env, |key| {
ide_core::process::host_var_os_in(&cwd, key).is_some_and(|v| !v.is_empty())
});
}
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, mut 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)
}
};
apply_remote_login_env(host, &cwd, false, &mut 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 mut launch = host.blocking(ide_agent::gh_login_launch).await?;
apply_remote_login_env(host, &cwd, true, &mut launch);
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)?;
@@ -185,6 +333,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
@@ -211,7 +360,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 } => {
@@ -1448,6 +1597,29 @@ mod tests {
assert!(reloaded.approved(&root, "extra", &extra));
assert!(!reloaded.approved(&tmp.path().join("other"), "extra", &extra));
}
#[test]
fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() {
let mut desktop_env = std::collections::BTreeMap::new();
prepare_login_launch_env(false, true, &mut desktop_env, |_| false);
assert!(desktop_env.is_empty());
let mut remote_agent_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, false, &mut remote_agent_env, |_| false);
assert_eq!(remote_agent_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
assert!(!remote_agent_env.contains_key("GH_BROWSER"));
let mut remote_gh_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, true, &mut remote_gh_env, |_| false);
assert_eq!(remote_gh_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
assert_eq!(remote_gh_env.get("GH_BROWSER").map(String::as_str), Some("true"));
// Preserves existing SSH/remote indicators and explicit browser settings.
let mut ssh_env = std::collections::BTreeMap::new();
prepare_login_launch_env(true, true, &mut ssh_env, |k| matches!(k, "SSH_CONNECTION" | "BROWSER"));
assert!(!ssh_env.contains_key("REMOTE_CONTAINERS"));
assert!(!ssh_env.contains_key("GH_BROWSER"));
}
}
ide_command::domain!(
@@ -1462,15 +1634,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,
@@ -1480,6 +1655,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,
+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 || {
+25 -4
Переглянути файл
@@ -3,7 +3,7 @@ use crate::Host;
use ide_command::command;
use super::blocking;
use ide_core::{IdeResult, IpcPath};
use ide_core::{IdeError, IdeResult, IpcPath};
use ide_coverage::{CoveragePrepared, CoverageReportSpec, CoverageSuite};
use ide_run::RunConfig;
@@ -35,9 +35,30 @@ pub async fn coverage_collect(host: &Host, window: &str, report: CoverageReportS
/// with paths mapped into this project.
#[command(trust = always)]
pub async fn coverage_import(host: &Host, window: &str, path: IpcPath) -> IdeResult<CoverageSuite> {
// Also reads a SimpleCov resultset.
let root = host.project(window)?.root.clone();
blocking(move || ide_coverage::import(&path, &root)).await
// Also reads Cobertura XML, a SimpleCov resultset and coverage.py data files.
let project = host.project(window)?;
let (root, cache, config_dir) =
(project.root.clone(), project.cache_dir.join("coverage-import"), host.config_dir.clone());
let trusted = project.require_trust();
blocking(move || {
if !ide_coverage::is_data_file(&path) {
return ide_coverage::import(&path, &root);
}
// coverage.py analyses the sources with the project's interpreter: that runs project code.
trusted.map_err(|_| {
IdeError::unavailable(
"Reading a .coverage data file runs the project's Python. Trust the project, or import the output of `coverage xml`.",
)
})?;
let python = super::sdk::effective_python(&config_dir, &project, path.parent()).ok_or_else(|| {
IdeError::unavailable(
"Reading a .coverage data file needs the project's Python interpreter. Choose one, or import the output of `coverage xml`.",
)
})?;
let out = ide_run::wrap::new_output_dir(&cache, KEEP_RUNS)?;
ide_coverage::import_data(&path, &root, &python, &out)
})
.await
}
ide_command::domain!(coverage: coverage_collect, coverage_import, coverage_prepare);
+29 -3
Переглянути файл
@@ -8,8 +8,8 @@ use ide_command::command;
use ide_core::{IdeError, IdeResult, IpcPath, RequestId};
use ide_db::split::SqlStatement;
use ide_db::{
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbVisibilityChange, HistoryEntry, PlanNode,
QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
CompletionModel, DataSource, Databases, DbObjectKind, DbRowEdit, DbSourceFolder, DbVisibilityChange, HistoryEntry,
PlanNode, QueryResult, SchemaObjects, SortKey, TableDetails, TableGrant, TableInfo, TablePage,
};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -75,6 +75,20 @@ pub async fn db_save_sources(host: &Host, window: &str, sources: Vec<DataSource>
sources_changed(host, window)
}
#[command(trust = trusted)]
pub fn db_source_folders(host: &Host, window: &str) -> IdeResult<Vec<DbSourceFolder>> {
// The project's user-created folders and their data source members.
ide_db::source::load_folders(&host.project(window)?.root)
}
#[command(trust = trusted)]
pub fn db_save_source_folders(host: &Host, window: &str, folders: Vec<DbSourceFolder>) -> IdeResult<()> {
// Replaces the project's data source folders; only grouping changes, never a source.
let root = host.project(window)?.root.clone();
ide_db::source::save_folders(&root, &folders)?;
sources_changed(host, window)
}
#[command(trust = trusted)]
pub async fn db_save_source_visibility(
host: &Host,
@@ -612,7 +626,16 @@ pub fn db_consoles(host: &Host, id: String, create: bool) -> IdeResult<Vec<IpcPa
Ok(out)
}
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database, `<id>.<database>` for the others.
/// The project view root for every data source's query consoles (`<dataDir>/consoles/db`).
#[command(trust = always)]
pub fn db_consoles_dir(host: &Host) -> IdeResult<IpcPath> {
let dir = host.data_dir.join("consoles").join("db");
std::fs::create_dir_all(&dir)?;
Ok(dir.into())
}
/// `<dataDir>/consoles/db/<id>`: `<id>` for the default database,
/// `<id>.<database>` for the others.
fn console_dir(host: &Host, id: &str) -> IdeResult<PathBuf> {
let (source, database) = ide_db::split_target(id);
if source.is_empty() || !source.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
@@ -670,6 +693,7 @@ ide_command::domain!(
db_connect,
db_connected,
db_console_path,
db_consoles_dir,
db_consoles,
db_create_database,
db_database_catalog,
@@ -692,6 +716,7 @@ ide_command::domain!(
db_result_row,
db_remove_history,
db_retain_catalog,
db_save_source_folders,
db_save_source_visibility,
db_save_sources,
db_saved_catalog,
@@ -701,6 +726,7 @@ ide_command::domain!(
db_set_manual_commit,
db_set_password,
db_set_ssh_secret,
db_source_folders,
db_sources,
db_statements,
db_table_details,
+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
}
+50 -4
Переглянути файл
@@ -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.
@@ -118,7 +163,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
}
items
}
None if snap.large && snap.language.as_str() != "markdown" => 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);
}
+267 -5
Переглянути файл
@@ -1,9 +1,14 @@
//! Docker run configurations: the environment their `docker` command line runs with; and Docker
//! connections through an SSH configuration, tunnelled with the IDE's own SSH client.
//! Services tool window › Docker (`ide-docker`) and Docker run configurations: run on the
//! project host (`Host` locally, `openidea-server` in a remote window), with SSH connections
//! tunnelled through the host's own SSH client.
use super::Channel;
use crate::Host;
use ide_command::command;
use ide_core::{IdeError, IdeResult};
use ide_docker::DockerEndpoint;
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
use ide_docker::{
ComposeOp, ContainerOp, DockerContainerStats, DockerEndpoint, DockerEvent, DockerImageLayer, DockerLogLine,
DockerObject, DockerProcessList, DockerRegistry, DockerSettings, DockerSnapshot, PruneTarget, RegistryAuth,
};
use ide_ssh::Tunnel;
use std::collections::{BTreeMap, HashMap};
@@ -54,6 +59,242 @@ pub async fn disconnect(host: &Host, endpoint: &DockerEndpoint) {
host.ssh.release(id);
}
/// Runs a cancellable docker command (`request` → `cancel_request`) off the async workers.
async fn cancellable<T: Send + 'static>(
host: &Host,
request: RequestId,
f: impl FnOnce(&CancellationToken) -> IdeResult<T> + Send + 'static,
) -> IdeResult<T> {
let cancel = host.begin_request(request);
let result = host.blocking(move || f(&cancel)).await;
host.end_request(request);
result
}
/// Closes the connection's SSH tunnel and, when nothing else uses it, its SSH connection
/// (Services › Disconnect); other endpoints keep nothing open.
#[command(trust = always)]
pub async fn docker_disconnect(host: &Host, endpoint: DockerEndpoint) -> IdeResult<()> {
disconnect(host, &endpoint).await;
Ok(())
}
/// Availability plus containers, images, volumes and networks.
#[command(trust = trusted)]
pub async fn docker_snapshot(host: &Host, endpoint: DockerEndpoint) -> IdeResult<DockerSnapshot> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || Ok(ide_docker::snapshot(&endpoint))).await
}
#[command(trust = trusted)]
pub async fn docker_container_op(
host: &Host,
endpoint: DockerEndpoint,
ids: Vec<String>,
op: ContainerOp,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_op(&endpoint, &ids, op)).await
}
#[command(trust = trusted)]
pub async fn docker_remove(
host: &Host,
endpoint: DockerEndpoint,
object: DockerObject,
ids: Vec<String>,
force: bool,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::remove(&endpoint, object, &ids, force)).await
}
/// Pretty-printed `docker inspect` JSON.
#[command(trust = trusted)]
pub async fn docker_inspect(
host: &Host,
endpoint: DockerEndpoint,
object: DockerObject,
id: String,
) -> IdeResult<String> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::inspect(&endpoint, object, &id)).await
}
/// Layers of an image (`docker image history`).
#[command(trust = trusted)]
pub async fn docker_image_history(
host: &Host,
endpoint: DockerEndpoint,
id: String,
) -> IdeResult<Vec<DockerImageLayer>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::image_history(&endpoint, &id)).await
}
/// Processes running inside a container (`docker top`).
#[command(trust = trusted)]
pub async fn docker_container_top(host: &Host, endpoint: DockerEndpoint, id: String) -> IdeResult<DockerProcessList> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_top(&endpoint, &id)).await
}
/// One-shot resource usage snapshot of a running container (`docker stats --no-stream`).
#[command(trust = trusted)]
pub async fn docker_container_stats(
host: &Host,
endpoint: DockerEndpoint,
id: String,
) -> IdeResult<DockerContainerStats> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::container_stats(&endpoint, &id)).await
}
/// Disk usage per volume name (`docker system df -v`).
#[command(trust = trusted)]
pub async fn docker_volume_sizes(host: &Host, endpoint: DockerEndpoint) -> IdeResult<BTreeMap<String, String>> {
let endpoint = resolve(host, endpoint).await?;
host.blocking(move || ide_docker::volume_sizes(&endpoint)).await
}
/// Streams a container's log lines, in batches, until it stops or the request is cancelled.
#[command(trust = trusted)]
#[allow(clippy::too_many_arguments)]
pub async fn docker_logs(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
id: String,
tail: u32,
follow: bool,
timestamps: bool,
on_lines: Channel<Vec<DockerLogLine>>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::logs(&endpoint, &id, tail, follow, timestamps, cancel, &|lines| {
let _ = on_lines.send(lines);
})
})
.await
}
/// Follows `docker events` until the daemon goes away or the request is cancelled.
#[command(trust = trusted)]
pub async fn docker_events(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
on_event: Channel<DockerEvent>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::watch_events(&endpoint, cancel, &|e| {
let _ = on_event.send(e);
})
})
.await
}
/// `docker pull`, logging in first when a saved registry with a password serves the image.
#[command(trust = trusted)]
pub async fn docker_pull(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
reference: String,
on_output: Channel<String>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
let data_dir = host.data_dir.clone();
cancellable(host, request, move |cancel| {
let auth = ide_docker::auth_for(&data_dir, &reference);
ide_docker::pull(&endpoint, &reference, auth.as_ref(), cancel, &|line| {
let _ = on_output.send(line);
})
})
.await
}
#[command(trust = trusted)]
pub async fn docker_prune(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
target: PruneTarget,
on_output: Channel<String>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::prune(&endpoint, target, cancel, &|line| {
let _ = on_output.send(line);
})
})
.await
}
/// `docker compose` start / stop / restart / down of a project found through labels.
#[command(trust = trusted)]
#[allow(clippy::too_many_arguments)]
pub async fn docker_compose_op(
host: &Host,
request: RequestId,
endpoint: DockerEndpoint,
project: String,
files: Vec<String>,
working_dir: Option<String>,
op: ComposeOp,
on_output: Channel<String>,
) -> IdeResult<()> {
let endpoint = resolve(host, endpoint).await?;
cancellable(host, request, move |cancel| {
ide_docker::compose_op(&endpoint, &project, &files, working_dir.as_deref(), op, cancel, &|line| {
let _ = on_output.send(line);
})
})
.await
}
/// Docker connections and registries of the project host.
#[command(trust = always)]
pub async fn docker_settings(host: &Host) -> IdeResult<DockerSettings> {
let data_dir = host.data_dir.clone();
host.blocking(move || Ok(ide_docker::load_settings(&data_dir))).await
}
#[command(trust = always)]
pub async fn docker_save_settings(host: &Host, settings: DockerSettings) -> IdeResult<()> {
let data_dir = host.data_dir.clone();
host.blocking(move || ide_docker::save_settings(&data_dir, &settings)).await
}
/// Saves (`None`: forgets) a registry's password.
#[command(trust = always)]
pub async fn docker_set_registry_password(host: &Host, id: String, password: Option<String>) -> IdeResult<()> {
let data_dir = host.data_dir.clone();
host.blocking(move || ide_docker::set_registry_password(&data_dir, &id, password.as_deref())).await
}
/// Test login to `registry` (`password`, else the saved one) through `endpoint`'s daemon.
#[command(trust = trusted)]
pub async fn docker_registry_login(
host: &Host,
endpoint: DockerEndpoint,
registry: DockerRegistry,
password: Option<String>,
) -> IdeResult<String> {
let endpoint = resolve(host, endpoint).await?;
let data_dir = host.data_dir.clone();
host.blocking(move || {
let password = password
.or_else(|| ide_docker::registry_password(&data_dir, &registry.id))
.ok_or_else(|| IdeError::invalid("enter the registry password"))?;
let auth = RegistryAuth { address: registry.address, username: registry.username, password };
ide_docker::login(&endpoint, &auth)
})
.await
}
/// Environment for a Docker run configuration's command line: selects `endpoint`'s
/// daemon and puts the docker executable on `PATH`.
#[command(trust = always)]
@@ -64,4 +305,25 @@ pub async fn docker_run_env(host: &Host, endpoint: DockerEndpoint) -> IdeResult<
host.blocking(move || Ok(ide_docker::run_env(&endpoint))).await
}
ide_command::domain!(docker: docker_run_env);
ide_command::domain!(
docker:
docker_compose_op,
docker_container_op,
docker_container_stats,
docker_container_top,
docker_disconnect,
docker_events,
docker_image_history,
docker_inspect,
docker_logs,
docker_prune,
docker_pull,
docker_registry_login,
docker_remove,
docker_run_env,
docker_save_settings,
docker_set_registry_password,
docker_settings,
docker_snapshot,
docker_volume_sizes,
);
+264
Переглянути файл
@@ -0,0 +1,264 @@
//! Host resource metrics (`host_metrics`, `host_end_process`) for the Remote Host
//! Resources status bar widget and popover dashboard.
use crate::Host;
use ide_command::command;
use ide_core::IdeResult;
use ide_workspace::memory::{self, CpuSampler, MemoryCategory, MemoryRoot, ProcessMemory, ProcessTable};
use ide_workspace::system::SystemSampler;
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
#[derive(Default)]
pub(crate) struct HostMetricsSampler {
system: SystemSampler,
cpu: CpuSampler,
}
/// One process outside OpenIDEA's own process tree on the host (read-only in the UI).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostProcess {
pub pid: u32,
pub name: String,
pub cpu_percent: Option<f32>,
pub memory_bytes: Option<u64>,
}
/// Snapshot of host-wide CPU, memory, network, disk and process usage.
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostMetrics {
/// Overall CPU utilization across all logical cores (`0..=100`); `null` on the first sample.
pub cpu_percent: Option<f32>,
/// Logical CPU cores available to this host or container.
pub cpu_cores: u32,
/// Unix 1m, 5m, 15m load averages; `null` on Windows.
pub load_average: Option<[f32; 3]>,
/// Host or container memory in use, in bytes.
pub memory_used_bytes: Option<u64>,
/// Total physical (or container limit) memory, in bytes.
pub memory_total_bytes: Option<u64>,
/// Bytes/s received across non-loopback network interfaces; `null` on the first sample or unsupported OS.
pub net_rx_bytes_per_sec: Option<f64>,
/// Bytes/s sent across non-loopback network interfaces; `null` on the first sample or unsupported OS.
pub net_tx_bytes_per_sec: Option<f64>,
/// Bytes/s read from block storage; `null` on the first sample or unsupported OS.
pub disk_read_bytes_per_sec: Option<f64>,
/// Bytes/s written to block storage; `null` on the first sample or unsupported OS.
pub disk_write_bytes_per_sec: Option<f64>,
/// Free bytes available to the user on the project volume (or `$HOME` fallback).
pub disk_available_bytes: Option<u64>,
/// Total capacity in bytes of the project volume (or `$HOME` fallback).
pub disk_total_bytes: Option<u64>,
/// Uptime of the backend process in milliseconds.
pub uptime_ms: f64,
/// OpenIDEA backend, language servers, runs, terminals, debug adapters and agents (`includeProcesses = true`).
pub processes: Vec<ProcessMemory>,
/// Highest-usage processes on the host outside OpenIDEA's own process tree (`includeProcesses = true`).
pub external_processes: Vec<HostProcess>,
}
const MAX_EXTERNAL_PROCESSES: usize = 5;
const MIN_EXTERNAL_CPU_PERCENT: f32 = 0.5;
const MIN_EXTERNAL_MEMORY_BYTES: u64 = 32 << 20;
fn project_name(root: &Path) -> String {
root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| root.display().to_string())
}
fn process_root(pid: u32, label: String, kind: &str) -> MemoryRoot {
MemoryRoot { pid, category: MemoryCategory::Process, label, detail: Some(kind.into()), with_children: true }
}
fn volume_path(host: &Host, window: &str) -> PathBuf {
if let Ok(p) = host.project(window) {
return p.root.clone();
}
if let Some(p) = host.projects().into_iter().next() {
return p.root.clone();
}
dirs::home_dir().unwrap_or_else(|| host.data_dir.clone())
}
fn disk_space(path: &Path) -> Option<(u64, u64)> {
#[cfg(unix)]
#[allow(clippy::unnecessary_cast)]
{
let stat = rustix::fs::statvfs(path).ok()?;
let frsize = stat.f_frsize as u64;
let total = (stat.f_blocks as u64).saturating_mul(frsize);
let avail = (stat.f_bavail as u64).saturating_mul(frsize);
(total > 0).then_some((avail.min(total), total))
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
let (mut avail, mut total, mut free) = (0u64, 0u64, 0u64);
// SAFETY: `wide` is NUL-terminated and all three u64 out-pointers are writable.
let ok = unsafe {
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
wide.as_ptr(),
&mut avail,
&mut total,
&mut free,
)
};
(ok != 0 && total > 0).then_some((avail.min(total), total))
}
#[cfg(not(any(unix, windows)))]
{
let _ = path;
None
}
}
fn collect_roots(host: &Host) -> Vec<MemoryRoot> {
let mut roots = Vec::new();
for p in host.projects() {
for s in p.lsp.servers() {
if let Some(pid) = s.pid {
roots.push(MemoryRoot {
pid,
category: MemoryCategory::LanguageServer,
label: s.name,
detail: Some(project_name(s.root.as_ref())),
with_children: true,
});
}
}
}
for r in host.processes.list().into_iter().filter(|r| r.running) {
if let Some(pid) = r.pid {
roots.push(process_root(pid, r.name, "Run"));
}
}
for t in host.terminals.list() {
if let Some(pid) = t.pid {
roots.push(process_root(pid, t.title, "Terminal"));
}
}
roots
}
fn resource_share(p: &HostProcess, cores: u32, total_memory: Option<u64>) -> f64 {
let cpu_share = p.cpu_percent.map(|c| c as f64 / (cores.max(1) as f64 * 100.0)).unwrap_or(0.0);
let mem_share = match (p.memory_bytes, total_memory.filter(|&t| t > 0)) {
(Some(b), Some(t)) => b as f64 / t as f64,
_ => 0.0,
};
cpu_share.max(mem_share)
}
/// Snapshot of host-wide resource counters (CPU, memory, network, disk) and, when
/// `include_processes` is true, the process breakdown of OpenIDEA and top host processes.
#[command(trust = always)]
pub async fn host_metrics(host: &Arc<Host>, window: &str, include_processes: bool) -> IdeResult<HostMetrics> {
let disk_target = volume_path(host, window);
let roots = if include_processes { collect_roots(host) } else { Vec::new() };
let h = host.clone();
host.blocking(move || {
let table = include_processes.then(ProcessTable::snapshot);
let (disk_available_bytes, disk_total_bytes) = match disk_space(&disk_target) {
Some((a, t)) => (Some(a), Some(t)),
None => (None, None),
};
let uptime_ms =
ide_workspace::process::process_age().unwrap_or_else(ide_workspace::process::uptime).as_secs_f64() * 1000.0;
let mut sampler = h.metrics_sampler.lock();
let rates = sampler.system.sample();
let (processes, external_processes) = if let Some(table) = table {
sampler.cpu.retain(&table);
let me = std::process::id();
let processes =
memory::attribute(&table, me, &roots, memory::footprint_bytes, |pid| sampler.cpu.percent(pid));
let claimed: HashSet<u32> = table.tree(me).into_iter().collect();
let mut external: Vec<HostProcess> = table
.entries()
.filter(|e| e.pid != 0 && !claimed.contains(&e.pid))
.filter_map(|e| {
let cpu_percent = sampler.cpu.percent(e.pid);
let memory_bytes = memory::fast_resident_bytes(e.pid);
let active = cpu_percent.unwrap_or(0.0) >= MIN_EXTERNAL_CPU_PERCENT
|| memory_bytes.unwrap_or(0) >= MIN_EXTERNAL_MEMORY_BYTES;
active.then(|| HostProcess { pid: e.pid, name: e.name.clone(), cpu_percent, memory_bytes })
})
.collect();
external.sort_by(|a, b| {
resource_share(b, rates.cpu_cores, rates.memory_total_bytes)
.total_cmp(&resource_share(a, rates.cpu_cores, rates.memory_total_bytes))
.then_with(|| b.memory_bytes.unwrap_or(0).cmp(&a.memory_bytes.unwrap_or(0)))
.then_with(|| a.pid.cmp(&b.pid))
});
external.truncate(MAX_EXTERNAL_PROCESSES);
(processes, external)
} else {
(Vec::new(), Vec::new())
};
Ok(HostMetrics {
cpu_percent: rates.cpu_percent,
cpu_cores: rates.cpu_cores,
load_average: rates.load_average,
memory_used_bytes: rates.memory_used_bytes,
memory_total_bytes: rates.memory_total_bytes,
net_rx_bytes_per_sec: rates.net_rx_bytes_per_sec,
net_tx_bytes_per_sec: rates.net_tx_bytes_per_sec,
disk_read_bytes_per_sec: rates.disk_read_bytes_per_sec,
disk_write_bytes_per_sec: rates.disk_write_bytes_per_sec,
disk_available_bytes,
disk_total_bytes,
uptime_ms,
processes,
external_processes,
})
})
.await
}
/// Ends a child process started by this OpenIDEA host (language server, run, terminal,
/// debug adapter or agent) and its descendants; refuses processes outside this host's tree.
#[command(trust = trusted)]
pub async fn host_end_process(host: &Arc<Host>, pid: u32) -> IdeResult<bool> {
host.blocking(move || Ok(memory::end_process_tree(std::process::id(), pid, Duration::from_secs(3)))).await
}
ide_command::domain!(host_metrics: host_metrics, host_end_process);
#[cfg(test)]
mod tests {
use super::*;
use crate::HostConfig;
#[tokio::test]
async fn collects_light_and_detailed_host_metrics() {
let dir = tempfile::tempdir().unwrap();
let host = Arc::new(Host::new(HostConfig::for_test(dir.path())));
let light = host_metrics(&host, "main", false).await.unwrap();
assert!(light.cpu_cores >= 1);
assert!(light.processes.is_empty());
assert!(light.external_processes.is_empty());
if cfg!(any(unix, windows)) {
let avail = light.disk_available_bytes.expect("disk_available_bytes");
let total = light.disk_total_bytes.expect("disk_total_bytes");
assert!(total > 0 && avail <= total, "{avail} / {total}");
}
let detailed = host_metrics(&host, "main", true).await.unwrap();
assert!(!detailed.processes.is_empty());
assert_eq!(detailed.processes[0].label, "Backend");
assert!(detailed.external_processes.len() <= MAX_EXTERNAL_PROCESSES);
// Refuses to terminate the backend itself or PID 1.
assert!(!host_end_process(&host, std::process::id()).await.unwrap());
assert!(!host_end_process(&host, 1).await.unwrap());
}
}
+61 -4
Переглянути файл
@@ -142,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 || {
@@ -393,6 +394,33 @@ fn is_maven_aggregator(root: &Path, model: &BuildModel, module: &Path) -> bool {
/// 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)));
@@ -922,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(
@@ -935,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);
@@ -948,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 \
@@ -1017,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}'")));
}
@@ -1026,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");
@@ -1060,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 {
+2
Переглянути файл
@@ -19,6 +19,7 @@ pub mod flutter;
pub mod fs;
pub mod heap;
pub mod history;
pub mod host_metrics;
pub mod http;
pub mod java;
pub mod jvm_icons;
@@ -93,6 +94,7 @@ ide_command::domains!(
fs: crate::ops::fs,
heap: crate::ops::heap,
history: crate::ops::history,
host_metrics: crate::ops::host_metrics,
http: crate::ops::http,
java: crate::ops::java,
jvm_icons: crate::ops::jvm_icons,
+70 -11
Переглянути файл
@@ -110,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.
@@ -122,17 +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);
}
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);
}
apply_setting(host, window, &key);
let sink = host.window_sink(window);
sink.emit(IdeEvent::SettingsChanged { key });
if let Some(root) = applied.roots_changed {
@@ -448,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() {
@@ -524,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,
+10 -1
Переглянути файл
@@ -334,10 +334,19 @@ pub async fn run_start(
Some(agent) => agent.wrap_output(on_output),
None => on_output,
};
// `execute_run_configuration` asked the Run tool window to start it.
let mcp = crate::mcp::run::configs::config_run_launch(&config);
let on_output = match &mcp {
Some(mcp) => mcp.wrap_output(on_output),
None => on_output,
};
let result = start_inner(host, window, config, on_output, agent.as_ref(), &cancel).await;
if let Some(agent) = &agent {
agent.started(&result);
}
if let Some(mcp) = &mcp {
mcp.started(&result);
}
if let Some(id) = request {
host.end_request(id);
}
@@ -493,7 +502,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));
+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();
+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))
}
+116
Переглянути файл
@@ -217,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.
@@ -4210,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() {
+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");
+7 -1
Переглянути файл
@@ -63,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::{
@@ -1949,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<()> {
+157 -15
Переглянути файл
@@ -211,6 +211,10 @@ impl Host {
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);
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
ide_sdk::apply::configure_css_modules(cfg, server_root, css_modules.as_deref());
// 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
@@ -360,8 +364,13 @@ impl Host {
}
{
let settings = settings.clone();
let data_dir = self.local_data_dir.clone();
lsp.set_servers_hook(Box::new(move |language, defined| {
ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective())
let mut servers = ide_sdk::apply::language_servers(language.as_str(), defined, &settings.effective());
if language.as_str() == "css" && ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit").is_none() {
ide_sdk::apply::drop_css_modules_route(&mut servers);
}
servers
}));
}
{
@@ -452,7 +461,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.
@@ -762,6 +773,12 @@ impl Host {
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)
}
@@ -1034,9 +1051,8 @@ fn db_sources_watch(
let Some(db) = weak.upgrade() else { return };
let sink = sink.clone();
runtime.spawn(async move {
if db.reconcile_sources().await {
sink.emit(IdeEvent::DbSourcesChanged);
}
db.reconcile_sources().await;
sink.emit(IdeEvent::DbSourcesChanged);
});
}))
.inspect_err(|e| tracing::warn!("{}", e.message))
@@ -1524,8 +1540,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)
}
@@ -1884,7 +1899,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 {
@@ -1906,6 +1923,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 {
@@ -2015,7 +2043,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,
@@ -2039,12 +2069,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) });
@@ -2492,18 +2532,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)]
@@ -2628,9 +2759,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");
+7
Переглянути файл
@@ -282,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();
+81 -13
Переглянути файл
@@ -1,4 +1,4 @@
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation) as the TypeScript
//! 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.
@@ -48,12 +48,7 @@ pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &
.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);
if !section.is_empty() {
layer.insert(language.into(), Value::Object(section));
}
}
if layer.is_empty() {
return;
layer.insert(language.into(), Value::Object(section));
}
let mut merged = Value::Object(layer);
if let Some(own) = cfg.settings.take() {
@@ -96,10 +91,30 @@ fn section(
if !format.is_empty() {
section.insert("format".into(), Value::Object(format));
}
// vtsls reads `quoteStyle` (VS Code's name), typescript-language-server tsserver's `quotePreference`.
// 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 {
section.insert("preferences".into(), json!({ "quoteStyle": quotes, "quotePreference": 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
}
@@ -133,9 +148,17 @@ mod tests {
"typescript": {
"format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false },
// The server's own settings win.
"preferences": { "quoteStyle": "double", "quotePreference": "single" },
"preferences": {
"quoteStyle": "double",
"quotePreference": "single",
"autoImportFileExcludePatterns": [],
"autoImportSpecifierExcludeRegexes": [],
},
},
"javascript": {
"format": { "semicolons": "insert" },
"preferences": { "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] },
},
"javascript": { "format": { "semicolons": "insert" } },
})
);
@@ -144,7 +167,52 @@ mod tests {
assert_eq!(eslint.settings, None);
let mut untouched = server("vtsls");
configure(&mut untouched, dir.path(), &Settings::default());
assert_eq!(untouched.settings, None, "nothing set: the server's defaults");
// 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]
@@ -178,6 +246,6 @@ mod tests {
configure(&mut cfg, dir.path(), &settings);
let s = cfg.settings.unwrap();
assert_eq!(s["typescript"]["format"], json!({ "semicolons": "insert" }));
assert_eq!(s.get("javascript"), None);
assert_eq!(s["javascript"].get("format"), None);
}
}
+14 -1
Переглянути файл
@@ -9,12 +9,15 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let host = Arc::new(Host::new(common::host_config(base)));
let root = base.join("data/consoles/db/pg");
let names = |paths: Vec<ide_core::IpcPath>| -> Vec<String> {
paths.iter().map(|p| p.0.file_name().unwrap().to_string_lossy().into_owned()).collect()
};
assert!(db::db_consoles(&host, "pg".into(), false).unwrap().is_empty());
// The first new console is the default one, then console_1, console_2…
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql"]);
let first = db::db_consoles(&host, "pg".into(), true).unwrap();
assert_eq!(names(first.clone()), ["console.sql"]);
assert_eq!(first[0].0, root.join("console.sql"));
assert_eq!(names(db::db_consoles(&host, "pg".into(), true).unwrap()), ["console.sql", "console_1.sql"]);
let all = db::db_consoles(&host, "pg".into(), true).unwrap();
assert_eq!(names(all.clone()), ["console.sql", "console_1.sql", "console_2.sql"]);
@@ -26,3 +29,13 @@ async fn new_query_consoles_are_numbered_after_the_default_one() {
assert!(db::db_consoles(&host, "pg:other".into(), false).unwrap().is_empty());
assert!(db::db_consoles(&host, "../x".into(), true).is_err());
}
#[tokio::test]
async fn consoles_root_is_the_directory_listed_in_the_project_view() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let host = Arc::new(Host::new(common::host_config(base)));
let root = db::db_consoles_dir(&host).unwrap();
assert_eq!(root.0, base.join("data/consoles/db"));
assert!(root.0.is_dir());
}
+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,
+83
Переглянути файл
@@ -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,7 +713,73 @@ 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 => {
+67
Переглянути файл
@@ -731,6 +731,38 @@ async fn reformat_uses_the_formatter_chain_and_preserves_a_dirty_buffer() {
assert!(p.documents.is_dirty(doc.id).unwrap());
}
/// Answers `execute_run_configuration`'s window requests the way the Run tool window does:
/// starts the configuration in a tab and says whether it started. Returns what it started.
fn config_run_window(h: &Harness) -> Arc<std::sync::Mutex<Vec<ide_run::RunConfig>>> {
let started = Arc::new(std::sync::Mutex::new(Vec::new()));
let (host, events, out) = (h.host.clone(), h.events.clone(), started.clone());
tokio::spawn(async move {
let mut handled = std::collections::HashSet::new();
loop {
let request = events.lock().unwrap().iter().find_map(|e| match e {
IdeEvent::McpRequest { id, request: ide_core::event::McpUiRequest::RunConfiguration { config } }
if !handled.contains(id) =>
{
Some((*id, config.clone()))
}
_ => None,
});
let Some((id, config)) = request else {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
continue;
};
handled.insert(id);
let config: ide_run::RunConfig = serde_json::from_value(config).unwrap();
out.lock().unwrap().push(config.clone());
let result =
ide_host::ops::run::run_start(&host, "main", config, ide_host::ops::Channel::new(|_| {}), None).await;
let error = result.err().map(|e| e.message);
let _ = host.mcp_requests.answer("main", id, error.is_none(), error);
}
});
started
}
#[tokio::test(flavor = "multi_thread")]
async fn execute_reports_output_exit_code_and_requires_confirmation() {
let h = Harness::new();
@@ -765,6 +797,7 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
assert!(error.contains("denied by the user"));
assert!(h.host.processes.list().is_empty());
h.events.lock().unwrap().clear();
let tabs = config_run_window(&h);
let run = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000}));
let allow = async {
let id = h.request().await;
@@ -773,6 +806,39 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() {
let (result, ()) = tokio::join!(run, allow);
assert_eq!(result["exitCode"], 7);
assert!(result["output"].as_str().unwrap().contains("captured-output"));
// It ran in a Run tool window tab, as the user's Run would.
let tabs = tabs.lock().unwrap();
assert_eq!(tabs.len(), 1);
assert_eq!(tabs[0].name, "MCP test");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_project_without_a_window_runs_a_configuration_on_its_own() {
let h = Harness::new();
h.trust().await;
let config = ide_run::RunConfig {
id: "test".into(),
name: "MCP test".into(),
kind: "shell".into(),
command: if cfg!(windows) { "echo windowless& exit 3" } else { "echo windowless; exit 3" }.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
.global_settings
.set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true))
.unwrap();
let result = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000})).await;
assert_eq!(result["exitCode"], 3, "{result}");
assert!(result["output"].as_str().unwrap().contains("windowless"));
assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked");
}
#[tokio::test(flavor = "multi_thread")]
@@ -795,6 +861,7 @@ async fn a_configuration_left_running_is_stopped_by_its_run_id() {
};
ide_run::save_user_configs(&h.root, &[config]).unwrap();
h.host.mcp_requests.set_ready("main", true);
let _tabs = config_run_window(&h);
let run = h.json("execute_run_configuration", json!({"configurationName":"Server","waitForExit":false}));
let allow = async {
let id = h.request().await;
+4 -3
Переглянути файл
@@ -429,9 +429,10 @@ fn gutter_actions_see_the_editors_window_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());
// The outer project's window: the file is its, though the inner project holds it too. Compared
// as paths: the plugin sees Windows paths `/`-separated.
assert_eq!(Path::new(&argument(Some(&outer))), outer);
assert_eq!(Path::new(&argument(Some(&inner))), inner);
// 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");
+2 -1
Переглянути файл
@@ -52,7 +52,8 @@ fn the_plugins_configuration_completes_only_the_argument_under_the_caret() {
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();
// Any approved executable will do; the test binary exists on every host.
p.choose_program(ID, "process:task", Some(&root), Some(&std::env::current_exe().unwrap())).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)
+1 -1
Переглянути файл
@@ -6,7 +6,6 @@ use ide_host::{Host, HostConfig};
use ide_plugin::TextQuery;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
struct Harness {
host: Arc<Host>,
@@ -510,6 +509,7 @@ async fn plugin_run_output_mode_executes_pty_and_pipes_with_input_exit_and_stop(
use ide_host::plugins::{Consent, PluginEvent, PluginHost, WindowRequest};
use ide_plugin::{Invocation, Limits};
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
let f = Harness::new();
f.host.set_project_trust(&f.root, true, false).await.unwrap();
+2 -1
Переглянути файл
@@ -6794,6 +6794,8 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
let mut req = vec![0; len];
let _ = reader.read_exact(&mut req);
let body = "plain ok";
// Recorded before the reply: the client may assert as soon as it reads it.
seen.lock().push("served".into());
let _ = writer.write_all(
format!(
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\n\r\n{body}",
@@ -6801,7 +6803,6 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
)
.as_bytes(),
);
seen.lock().push("served".into());
}
});
}
+19 -4
Переглянути файл
@@ -80,14 +80,23 @@ async fn serves_projects_files_documents_search_and_runs() {
assert_eq!(opened["name"], "demo");
assert_eq!(opened["trusted"], false);
invoke(&peer, "index_status", json!({})).await.unwrap();
let metrics = invoke(&peer, "host_metrics", json!({ "includeProcesses": true })).await.unwrap();
assert!(metrics["cpuCores"].as_u64().unwrap() >= 1);
assert_eq!(metrics["processes"][0]["label"], "Backend");
assert_eq!(invoke(&peer, "lsp_servers", json!({})).await.unwrap(), json!([]));
invoke(&peer, "lsp_resend_diagnostics", json!({})).await.unwrap();
let files = invoke(&peer, "find_files", json!({"query": "main", "limit": 10})).await.unwrap();
assert!(files.is_array());
for command in
["build_sync", "run_start", "sdk_locate_tools", "notebook_execute", "debug_start", "agent_refresh_models"]
{
let error = invoke(&peer, command, json!({})).await.unwrap_err();
for (command, args) in [
("build_sync", json!({})),
("run_start", json!({})),
("sdk_locate_tools", json!({})),
("notebook_execute", json!({})),
("debug_start", json!({})),
("agent_refresh_models", json!({})),
("host_end_process", json!({ "pid": 1 })),
] {
let error = invoke(&peer, command, args).await.unwrap_err();
assert!(error.message.contains("Restricted Mode"), "{command}: {error:?}");
}
let call = Invoke { window: "unknown".into(), cmd: "coverage_collect".into(), args: json!({}) };
@@ -271,6 +280,9 @@ async fn serves_projects_files_documents_search_and_runs() {
.await
.unwrap();
assert_eq!(env["DOCKER_HOST"], "unix:///run/user/1/docker.sock");
// Services › Docker commands are served by the project host too.
assert!(Dispatcher::standard().commands().contains(&"docker_snapshot"));
assert_eq!(invoke(&peer, "docker_settings", json!({})).await.unwrap()["connections"], json!([]));
// Real project-host ignore writes travel through the remote command dispatcher.
assert!(Dispatcher::standard().commands().contains(&"vcs_add_to_ignore"));
@@ -391,6 +403,8 @@ async fn local_deployment_runs_on_the_project_host() {
"http_curl",
"http_environment_file",
"http_variable_definitions",
"db_source_folders",
"db_save_source_folders",
"db_sources",
"db_save_sources",
"db_set_password",
@@ -420,6 +434,7 @@ async fn local_deployment_runs_on_the_project_host() {
"db_table_page",
"db_apply_edits",
"db_console_path",
"db_consoles_dir",
"db_consoles",
"ssh_test",
"ssh_set_secret",
+22
Переглянути файл
@@ -50,3 +50,25 @@ async fn find_in_files_decodes_closed_files_with_the_project_encoding() {
project.documents.set_file_defaults(defaults);
assert!(find(&host, "中文搜索验证").await.is_empty());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn find_in_files_decodes_closed_files_with_the_editorconfig_charset() {
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let root = base.join("project");
std::fs::create_dir(&root).unwrap();
std::fs::write(root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
std::fs::write(root.join("A.java"), b"// a\xe7\xe3o \xa4 needle\n").unwrap();
let host = Host::new(common::host_config(&base));
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
let mut defaults = project.documents.file_defaults();
defaults.project_fallback = "gbk".into();
project.documents.set_file_defaults(defaults);
let files = find(&host, "ação €").await;
assert_eq!(files.len(), 1);
assert_eq!(files[0].matches[0].text, "// ação € needle", "the text the editor shows");
assert_eq!(find(&host, "needle").await[0].matches[0].text, "// ação € needle");
}
+57 -5
Переглянути файл
@@ -89,12 +89,42 @@ fn has_toml_table(file: &Path, table: &str) -> bool {
table.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(toml::Value::is_table)
}
/// `file` parses as JSON and has the dotted `key` with a value other than `null`:
/// an object (`eslintConfig`) or a dependency's version (`dependencies.tailwindcss`).
/// `file` parses as JSON (with comments: `tsconfig.json`) and has the dotted `key` with a value
/// other than `null` or `false`: an object (`eslintConfig`), a dependency's version
/// (`dependencies.tailwindcss`) or a switch that is on (`cmkOptions.enabled`).
fn has_json_key(file: &Path, key: &str) -> bool {
let Ok(text) = std::fs::read_to_string(file) else { return false };
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else { return false };
key.split('.').try_fold(&value, |v, key| v.get(key)).is_some_and(|v| !v.is_null())
json_key(file, key, 0).is_some_and(|v| !v.is_null() && v != serde_json::Value::Bool(false))
}
/// The dotted `key` of the JSON `file`. A tsconfig.json / jsconfig.json without it inherits it
/// through `extends` from a local file (`./base`, `../tsconfig.base.json`), the first one defining
/// it winning, as CSS Modules Kit reads `cmkOptions`.
fn json_key(file: &Path, key: &str, depth: usize) -> Option<serde_json::Value> {
// ponytail: package `extends` (`@tsconfig/node20`) are not resolved; only local files.
const MAX_DEPTH: usize = 8;
let text = std::fs::read_to_string(file).ok()?;
let value = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(&text)).ok()?;
if let Some(v) = key.split('.').try_fold(&value, |v, key| v.get(key)) {
return Some(v.clone());
}
let name = file.file_name()?.to_string_lossy();
if depth >= MAX_DEPTH || !(name.starts_with("tsconfig") || name.starts_with("jsconfig")) {
return None;
}
let extends = match value.get("extends")? {
serde_json::Value::String(s) => vec![s.as_str()],
serde_json::Value::Array(a) => a.iter().filter_map(serde_json::Value::as_str).collect(),
_ => return None,
};
extends.into_iter().filter(|e| e.starts_with("./") || e.starts_with("../")).find_map(|e| {
let base = file.parent()?.join(e);
let base = if base.is_file() {
base
} else {
base.with_file_name(format!("{}.json", base.file_name()?.to_string_lossy()))
};
json_key(&base, key, depth + 1)
})
}
/// `path` is (or, after its creation or removal, was) a root marker of the
@@ -191,6 +221,28 @@ mod tests {
std::fs::write(dir.join("package.json"), r#"{"eslintConfig": null}"#).unwrap();
assert!(!has_marker(dir, "package.json#eslintConfig"));
assert!(is_marker_path(&dir.join("package.json"), marker));
// tsconfig.json is JSON with comments; a switch that is off is no marker.
let cmk = "tsconfig.json#cmkOptions.enabled";
let tsconfig =
|enabled: &str| format!("{{\n // CSS Modules Kit\n \"cmkOptions\": {{ \"enabled\": {enabled} }},\n}}");
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
assert!(has_marker(dir, cmk));
std::fs::write(dir.join("tsconfig.json"), tsconfig("false")).unwrap();
assert!(!has_marker(dir, cmk));
// Inherited through a local `extends`, which the file itself can turn off.
std::fs::create_dir_all(dir.join("app")).unwrap();
std::fs::write(dir.join("tsconfig.json"), tsconfig("true")).unwrap();
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": ["@tsconfig/strictest", "../tsconfig"] }"#)
.unwrap();
assert!(has_marker(&dir.join("app"), cmk));
std::fs::write(
dir.join("app/tsconfig.json"),
r#"{ "extends": "../tsconfig.json", "cmkOptions": { "enabled": false } }"#,
)
.unwrap();
assert!(!has_marker(&dir.join("app"), cmk));
std::fs::write(dir.join("app/tsconfig.json"), r#"{ "extends": "./tsconfig.json" }"#).unwrap();
assert!(!has_marker(&dir.join("app"), cmk), "a cycle ends");
}
#[test]
+21
Переглянути файл
@@ -63,6 +63,7 @@ const BUILTIN: &[(&str, &str)] = &[
("lua", include_str!("../../../languages/lua.toml")),
("makefile", include_str!("../../../languages/makefile.toml")),
("markdown", include_str!("../../../languages/markdown.toml")),
("mdx", include_str!("../../../languages/mdx.toml")),
("nix", include_str!("../../../languages/nix.toml")),
("objective-c", include_str!("../../../languages/objective-c.toml")),
("objective-cpp", include_str!("../../../languages/objective-cpp.toml")),
@@ -1073,6 +1074,9 @@ mod tests {
assert_eq!(detect("shop/templates/shop/product_list.html"), "django-html");
assert_eq!(detect("shop/templates/shop/email/order.txt"), "django-html");
assert_eq!(detect("pages/promo.html"), "html");
// Breakpoints in templates go to debugpy without "Allow placing breakpoints in any file".
let template = reg.get(&LanguageId::new("django-html")).unwrap();
assert_eq!(template.debugger.unwrap().adapter, "debugpy");
}
/// #4061: the project root is canonical; a template reached under another
@@ -1281,6 +1285,7 @@ mod tests {
("Views/MainWindow.axaml", "axaml"),
("MainWindow.xaml", "xml"),
("README.md", "markdown"),
("Intro.mdx", "mdx"),
("Dockerfile", "dockerfile"),
("Dockerfile.dev", "dockerfile"),
("Makefile", "makefile"),
@@ -1362,6 +1367,22 @@ mod tests {
);
}
#[test]
fn indented_sass_has_its_own_server() {
let reg = reg();
let names = |lang: &str| -> Vec<String> {
reg.get(&LanguageId::new(lang)).unwrap().language_servers.iter().map(|s| s.name.clone()).collect()
};
assert_eq!(names("sass"), ["some-sass-language-server"]);
let sass = &reg.get(&LanguageId::new("sass")).unwrap().language_servers[0];
assert_eq!(sass.settings.as_ref().and_then(|s| s.get("somesass")), Some(&serde_json::json!({})));
for lang in ["scss", "css", "less"] {
let names = names(lang);
assert_eq!(names[0], "vscode-css-language-server", "{lang}");
assert!(!names.iter().any(|n| n == "some-sass-language-server"), "{lang}");
}
}
#[test]
fn astro_server_leaves_typescript_sdk_resolution_to_the_launcher() {
let reg = reg();
+1
Переглянути файл
@@ -28,6 +28,7 @@ percent-encoding = "2"
zip.workspace = true
[dev-dependencies]
ide-sdk.workspace = true
tempfile.workspace = true
encoding_rs.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "test-util"] }
+53
Переглянути файл
@@ -34,6 +34,20 @@ fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, Strin
Some(settings)
}
/// Java organize-imports thresholds as jdtls settings (IDEA's "Class count to use import with
/// '*'" and "Names count to use static import with '*'"). Unset ones are IDEA's defaults, 5 and 3:
/// jdtls' own are 99 (single imports), and it keeps a value it was sent until another one comes.
/// A threshold the server configuration sets explicitly is kept.
fn organize_imports_settings(style: Option<&LanguageCodeStyle>, inherited: &serde_json::Value) -> serde_json::Value {
let explicit = |key: &str| inherited.pointer(&format!("/java/sources/organizeImports/{key}")).cloned();
let class_count = style.and_then(|s| s.class_count_to_use_import_with_star).unwrap_or(5);
let static_count = style.and_then(|s| s.names_count_to_use_static_import_with_star).unwrap_or(3);
json!({
"starThreshold": explicit("starThreshold").unwrap_or(json!(class_count)),
"staticStarThreshold": explicit("staticStarThreshold").unwrap_or(json!(static_count)),
})
}
fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String {
for (id, value) in settings {
let marker = format!(r#"<setting id="{id}" value=""#);
@@ -84,6 +98,7 @@ pub fn configure_formatter(
});
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides);
settings["java"]["sources"]["organizeImports"] = organize_imports_settings(style, &inherited);
cfg.settings = Some(settings);
let Some(style) = style else { return Ok(()) };
let indent = indent_settings(style);
@@ -300,6 +315,44 @@ mod tests {
}
}
#[test]
fn organize_imports_thresholds_default_to_idea_and_keep_explicit_server_settings() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir_all(&root).unwrap();
let imports = |cfg: &LanguageServerConfig| {
crate::handler::all_settings(cfg)["java"]["sources"]["organizeImports"].clone()
};
let mut cfg = config("jdtls");
let style = LanguageCodeStyle {
class_count_to_use_import_with_star: Some(7),
names_count_to_use_static_import_with_star: Some(4),
..Default::default()
};
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 7, "staticStarThreshold": 4}));
// Unset: IDEA's 5 and 3, not jdtls' 99 (#6026).
let mut cfg = config("jdtls");
let style = LanguageCodeStyle { names_count_to_use_static_import_with_star: Some(2), ..Default::default() };
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 2}));
let mut cfg = config("jdtls");
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 3}));
// A threshold set in the server configuration wins.
let mut cfg = config("jdtls");
cfg.settings = Some(json!({"java": {"sources": {"organizeImports": {"starThreshold": 99}}}}));
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 99, "staticStarThreshold": 2}));
let mut cfg = config("rust-analyzer");
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
assert!(crate::handler::all_settings(&cfg)["java"].is_null());
}
#[test]
fn default_keeps_explicit_server_configuration_and_custom_accepts_absolute_paths() {
let dir = tempfile::tempdir().unwrap();
+22 -2
Переглянути файл
@@ -352,6 +352,9 @@ fn user_did_open(server: &Server, run: &Running, path: &Path, uri: &lsp::Uri, pa
/// No target for `feature`: names the running servers that lack it, so the UI can
/// tell "the server can't do this" from "no server is running" (the UI's
/// `unavailableText` matches the "… doesn't support …" wording).
/// vscode-css-language-server, which lists a selector's own rule among its references.
const CSS_SERVER: &str = "vscode-css-language-server";
fn unsupported(servers: &[Arc<Server>], feature: &str) -> IdeError {
let running: Vec<&str> = servers.iter().filter(|s| s.running().is_some()).map(|s| s.name.as_str()).collect();
if running.is_empty() {
@@ -2332,9 +2335,13 @@ impl LspManager {
}
});
// The Angular server lists the declaration even when not asked to: the one
// the definition at `pos` points to is taken out of its answer.
// the definition at `pos` points to is taken out of its answer. So does the CSS server
// with a selector's own rule (`.button`), always: where CSS Modules Kit defines the class
// name (`button`), vtsls lists the declaration itself when asked.
let declarations = async {
if include_declaration || !targets.iter().any(|t| t.server.name == angular::SERVER) {
let listed =
|t: &Target| (t.server.name == angular::SERVER && !include_declaration) || t.server.name == CSS_SERVER;
if !targets.iter().any(listed) {
return Vec::new();
}
let defining = self.ready_targets(&snap.servers, |c| c.has("definitionProvider")).await;
@@ -2351,6 +2358,14 @@ impl LspManager {
let mut locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
if t.server.name == angular::SERVER {
locs.retain(|l| !declarations.contains(l));
} else if t.server.name == CSS_SERVER {
let overlaps = |a: &Location, b: &Location| {
a.path == b.path
&& a.uri == b.uri
&& a.range.start <= b.range.end
&& b.range.start <= a.range.end
};
locs.retain(|l| !declarations.iter().any(|d| overlaps(d, l)));
}
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
self.note_arduino_sources(&t.server, &locs);
@@ -2922,6 +2937,11 @@ impl LspManager {
let prepared = join_all(targets.iter().map(|t| self.prepare_rename_on(snap, t, pos))).await;
let able: Vec<&Target> =
targets.iter().zip(prepared).filter(|(_, r)| matches!(r, Ok(Some(_)))).map(|(t, _)| t).collect();
// CSS Modules Kit (vtsls) renames a class in the stylesheet and its scripts; the CSS
// server's own edit replaces the whole selector (`.button`) and would drop the dot.
if able.iter().any(|t| t.server.name == "vtsls") {
return able.into_iter().filter(|t| t.server.name != CSS_SERVER).collect();
}
if !able.is_empty() {
return able;
}
+51
Переглянути файл
@@ -4768,6 +4768,57 @@ async fn angular_references_leave_out_the_declaration_unless_asked() {
assert_eq!(vtsls.requested("textDocument/definition").len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn css_references_leave_out_the_selector_where_css_modules_kit_defines_it() {
let servers = [("vscode-css-language-server", incremental_caps()), ("vtsls", incremental_caps())];
let h = harness_for("css", "css", &servers, &[]);
let (doc, path) = h.open("a.module.css", ".button { color: red; }\n");
h.wait_status("vscode-css-language-server", ServerStatus::Ready).await;
h.wait_status("vtsls", ServerStatus::Ready).await;
let tsx = h.root.join("a.tsx");
let at = |uri: &str, line: u32, from: u32, to: u32| json!({ "uri": uri, "range": {"start":{"line":line,"character":from},"end":{"line":line,"character":to}} });
let (css, tsx_uri) = (uri_of(&path), uri_of(&tsx));
// The CSS server lists the rule itself (`.button`) whatever `includeDeclaration` says;
// CSS Modules Kit (vtsls) defines the class at `button` and lists the TSX use.
h.launcher.state("vscode-css-language-server").respond("textDocument/references", json!([at(&css, 0, 0, 7)]));
let vtsls = h.launcher.state("vtsls");
vtsls.respond("textDocument/references", json!([at(&tsx_uri, 4, 30, 36)]));
vtsls.respond("textDocument/definition", json!([at(&css, 0, 1, 7)]));
let mgr = &h.mgr;
let found = |include_declaration: bool| async move {
let refs =
mgr.references_streaming(doc, Pos::new(0, 3), include_declaration, false, true, Default::default(), None);
let mut v: Vec<(PathBuf, Range)> =
refs.await.unwrap().locations.iter().map(|l| (l.path.to_path_buf(), l.range)).collect();
v.sort();
v
};
assert_eq!(found(false).await, [(tsx.clone(), rng(4, 30, 4, 36))]);
// Asked for the declaration, vtsls lists it once, as the class name.
vtsls.respond("textDocument/references", json!([at(&css, 0, 1, 7), at(&tsx_uri, 4, 30, 36)]));
assert_eq!(found(true).await, [(path.clone(), rng(0, 1, 0, 7)), (tsx, rng(4, 30, 4, 36))]);
// Rename: CSS Modules Kit's edit, not the CSS server's, which would replace `.button`.
let css_server = h.launcher.state("vscode-css-language-server");
let range = |from: u32, to: u32| json!({"start":{"line":0,"character":from},"end":{"line":0,"character":to}});
css_server.respond("textDocument/prepareRename", range(0, 7));
css_server.respond(
"textDocument/rename",
json!({ "changes": { css.clone(): [{ "range": range(0, 7), "newText": "primary" }] } }),
);
vtsls.respond("textDocument/prepareRename", range(1, 7));
vtsls.respond(
"textDocument/rename",
json!({ "changes": { css.clone(): [{ "range": range(1, 7), "newText": "primary" }] } }),
);
let edit = h.mgr.rename(doc, Pos::new(0, 3), "primary".into(), Default::default()).await.unwrap().edit;
assert!(
matches!(&edit.files[..], [FileEdit::Edit { edits, .. }] if edits.len() == 1 && edits[0].range == rng(0, 1, 0, 7)),
"{edit:?}"
);
assert!(css_server.requested("textDocument/rename").is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn utf8_server_positions_are_converted() {
let h = harness(&[(
+330
Переглянути файл
@@ -969,6 +969,258 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// CSS Modules Kit (`@css-modules-kit/ts-plugin`) on vtsls, which serves the `.module.css`
/// files too (`languages: ["css"]`): definition and completion from TSX, references and rename
/// from the stylesheet (#6071), with the settings hook's own plugin configuration. Exactly the
/// IDE's copy loads, once: also when the project has the package in its `node_modules`, and when
/// its tsconfig declares it in `compilerOptions.plugins` (#6336's probe location leaves it out,
/// and tsserver resolves the declared name from the global plugin's location). Set
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @vtsls/language-server typescript@6 @css-modules-kit/[email protected]`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @vtsls/language-server and @css-modules-kit/ts-plugin (OPENIDEA_TEST_NPM_TOOLS)"]
async fn css_modules_kit_navigates_between_tsx_and_module_css() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
// (the project has its own package, its tsconfig declares the plugin)
for (project_copy, declared) in [(false, false), (true, false), (true, true)] {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
if project_copy {
// Says so in every file if it is ever loaded.
let package = root.join("node_modules/@css-modules-kit/ts-plugin");
std::fs::create_dir_all(&package).unwrap();
std::fs::write(package.join("package.json"), r#"{"name":"@css-modules-kit/ts-plugin","version":"0.0.1"}"#)
.unwrap();
std::fs::write(package.join("index.js"), DIAGNOSTIC_PLUGIN.replace("NAME", "'the project copy'")).unwrap();
}
let plugins = if declared { r#", "plugins": [{ "name": "@css-modules-kit/ts-plugin" }]"# } else { "" };
std::fs::write(
root.join("tsconfig.json"),
format!(
"{{\n // JSON with comments\n \"compilerOptions\": {{ \"strict\": true, \"jsx\": \"preserve\", \"module\": \"ESNext\", \"moduleResolution\": \"Bundler\"{plugins} }},\n \"include\": [\"src\"],\n \"cmkOptions\": {{ \"enabled\": true }}\n}}\n"
),
)
.unwrap();
let css_path = root.join("src/Button.module.css");
let css = ".button { color: red; }\n.label { color: blue; }\n";
std::fs::write(&css_path, css).unwrap();
let tsx_path = root.join("src/Button.tsx");
let tsx =
"import styles from './Button.module.css';\nexport const a = styles.button;\nexport const b = styles.";
std::fs::write(&tsx_path, tsx).unwrap();
let mut vtsls = npm_server(&tools, "vtsls", "vtsls", None);
vtsls.tsserver_project = true;
assert!(ide_sdk::apply::configure_css_modules(&mut vtsls, &root, Some(&tools)));
let data = tempfile::tempdir().unwrap();
// The plugin is the IDE's global one: no probe location for it.
assert!(!ide_sdk::apply::configure_tsconfig_plugins(&mut vtsls, &root, data.path()));
let registry = LanguageRegistry::from_configs(vec![
lang("typescriptreact", "tsx", vtsls.clone()),
lang("css", "css", vtsls),
]);
let (mgr, events) = manager(&root, registry);
let tsx_doc = DocId::next();
mgr.did_open(tsx_doc, &tsx_path, &LanguageId::new("typescriptreact"), 1, tsx);
let css_doc = DocId::next();
mgr.did_open(css_doc, &css_path, &LanguageId::new("css"), 1, css);
assert_eq!(mgr.servers().iter().filter(|s| s.name == "vtsls").count(), 1, "one vtsls for both");
let case = format!("project copy: {project_copy}, declared: {declared}");
// `styles.button` → `.button`.
let defs = retry("definition in the stylesheet", Duration::from_secs(90), || {
let (mgr, css_path) = (mgr.clone(), css_path.clone());
async move {
let defs = mgr.goto(tsx_doc, Pos::new(1, 26), GotoKind::Definition).await.ok()?;
defs.iter().any(|d| d.path == css_path).then_some(defs)
}
})
.await;
assert_eq!(defs.len(), 1, "{case}: {defs:?}");
assert_eq!((defs[0].range.start.line, defs[0].range.start.col), (0, 1), "{case}");
let list = retry("class name completion", Duration::from_secs(30), || {
let mgr = mgr.clone();
async move {
let list = mgr.completion(tsx_doc, Pos::new(2, 24), Some(".".into()), Default::default()).await.ok()?;
list.items.iter().any(|i| i.label == "label").then_some(list)
}
})
.await;
let labels: Vec<&str> =
list.items.iter().map(|i| i.label.as_str()).filter(|l| ["button", "label"].contains(l)).collect();
assert_eq!(labels.len(), 2, "{case}: each class once, {labels:?}");
// `.button` in the stylesheet → its use in the component, once.
let refs = retry("references from the stylesheet", Duration::from_secs(30), || {
let (mgr, tsx_path) = (mgr.clone(), tsx_path.clone());
async move {
let refs = mgr
.references_streaming(css_doc, Pos::new(0, 3), false, true, false, Default::default(), None)
.await
.ok()?;
Some(refs.locations).filter(|l| l.iter().any(|l| l.path == tsx_path))
}
})
.await;
assert_eq!(refs.len(), 1, "{case}: {refs:?}");
assert_eq!((refs[0].path.to_path_buf(), refs[0].range.start.line), (tsx_path.clone(), 1), "{case}");
let renamed = mgr.rename(css_doc, Pos::new(0, 3), "primary".into(), Default::default()).await.unwrap().edit;
assert_eq!(edited_lines(&renamed, &css_path), [0], "{case}");
assert_eq!(edited_lines(&renamed, &tsx_path), [1], "{case}");
// The component's diagnostics are in: the plugins have run on it.
retry("diagnostics of the component", Duration::from_secs(30), || {
let found =
events.lock().iter().any(|e| matches!(e, IdeEvent::Diagnostics { path, .. } if path == &tsx_path));
async move { found.then_some(()) }
})
.await;
let project_copy_loaded = events.lock().iter().any(|e| {
matches!(e, IdeEvent::Diagnostics { items, .. } if items.iter().any(|d| d.message.contains("the project copy")))
});
assert!(!project_copy_loaded, "{case}");
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
}
const MDX_BUTTON: &str =
"export function Button(props: { label: string }) {\n return <button>{props.label}</button>;\n}\n";
const MDX_DOC: &str = "import { Button } from \"./Button\"\n\nexport const count = 2\n\n# Hello\n\n<Button label=\"hi\" />\n\n<Button label={count} />\n\n{count.toFixed()}\n";
/// The MDX Language Server with the `typescript.tsdk` the launcher adds. Set
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @mdx-js/language-server
/// typescript@6 @types/react`; the project is created inside it, so that it
/// resolves the React types.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @mdx-js/language-server, typescript and @types/react (OPENIDEA_TEST_NPM_TOOLS)"]
async fn mdx_language_server_end_to_end() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir_in(&tools).unwrap();
let root = dir.path().canonicalize().unwrap();
std::fs::write(
root.join("tsconfig.json"),
"{\"compilerOptions\":{\"strict\":true,\"jsx\":\"react-jsx\",\"moduleResolution\":\"bundler\",\"module\":\"esnext\"},\"mdx\":{\"checkMdx\":true}}",
)
.unwrap();
let (button, file) = (root.join("Button.tsx"), root.join("doc.mdx"));
std::fs::write(&button, MDX_BUTTON).unwrap();
std::fs::write(&file, MDX_DOC).unwrap();
let mut mdx = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("mdx")).unwrap();
let server = &mut mdx.language_servers[0];
server.command = tools.join("node_modules/.bin/mdx-language-server").to_string_lossy().into_owned();
let tsdk = tools.join("node_modules/typescript/lib").to_string_lossy().into_owned();
server.initialization_options.as_mut().unwrap()["typescript"]
.as_table_mut()
.unwrap()
.insert("tsdk".into(), toml::Value::String(tsdk));
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![mdx]));
let doc = DocId::next();
mgr.did_open(doc, &file, &LanguageId::new("mdx"), 1, MDX_DOC);
// `Button` in `<Button label="hi" />`.
let hover = retry("hover", Duration::from_secs(90), || {
let mgr = mgr.clone();
async move { mgr.hover(doc, Pos::new(6, 3), Default::default()).await.ok().flatten() }
})
.await;
assert!(hover.contents.value.contains("label: string"), "{}", hover.contents.value);
let defs = mgr.goto(doc, Pos::new(6, 3), GotoKind::Definition).await.unwrap();
assert!(defs.iter().any(|d| d.path == button), "{defs:?}");
// Members of `count` inside `{…}`, and the imported component in JSX.
for (pos, label) in [(Pos::new(10, 7), "toFixed"), (Pos::new(6, 3), "Button")] {
retry(label, Duration::from_secs(30), || {
let mgr = mgr.clone();
async move {
let list = mgr.completion(doc, pos, None, Default::default()).await.ok()?;
list.items.iter().any(|i| i.label == label).then_some(())
}
})
.await;
}
// Markdown headings come from the server too (marksman skips `.mdx` by default).
let symbols = mgr.document_symbols(doc).await.unwrap().unwrap();
assert!(symbols.iter().any(|s| s.name.contains("Hello")), "{symbols:?}");
// `label={count}`: number is not assignable to string.
retry("prop type error", Duration::from_secs(60), || {
let found = events.lock().iter().any(|e| {
matches!(e, IdeEvent::Diagnostics { path, items, .. }
if path == &file && items.iter().any(|d| d.range.start.line == 8 && d.message.contains("string")))
});
async move { found.then_some(()) }
})
.await;
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// A tsserver plugin reporting `from <name>` at the start of every file.
const DIAGNOSTIC_PLUGIN: &str = "module.exports = () => ({ create(info) {\n const ls = info.languageService;\n const proxy = Object.create(null);\n for (const k of Object.keys(ls)) proxy[k] = (...a) => ls[k](...a);\n proxy.getSemanticDiagnostics = (f) => [...ls.getSemanticDiagnostics(f), { file: ls.getProgram().getSourceFile(f), start: 0, length: 1, messageText: 'from ' + NAME, category: 1, code: 99001 }];\n return proxy;\n} });\n";
/// tsconfig `compilerOptions.plugins` load from the project's `node_modules` with vtsls' own
/// TypeScript through the probe location `configure_tsconfig_plugins` writes (#6336); one that
/// isn't installed is skipped, and the IDE's global plugins keep loading their own copies,
/// also when the project has a package of the same name. Set `OPENIDEA_TEST_NPM_TOOLS` to a
/// dir with `npm i @vtsls/language-server typescript@5`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @vtsls/language-server (OPENIDEA_TEST_NPM_TOOLS)"]
async fn tsconfig_plugins_load_from_the_project_with_the_bundled_typescript() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
// Outside the project: a probe location resolves plugins from its ancestors' node_modules too.
let ide = tempfile::tempdir().unwrap();
let ide = dunce::canonicalize(ide.path()).unwrap();
let plugin = |dir: &Path, name: &str, says: &str| {
let dir = dir.join("node_modules").join(name);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("index.js"), DIAGNOSTIC_PLUGIN.replace("NAME", &format!("'{says}'"))).unwrap();
};
plugin(&root, "project-plugin", "project-plugin");
plugin(&root, "global-plugin", "the project's global-plugin");
plugin(&ide, "global-plugin", "global-plugin");
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
let plugins = r#"[{"name":"not-installed"},{"name":"project-plugin"}]"#;
std::fs::write(root.join("tsconfig.json"), format!("{{\"compilerOptions\":{{\"plugins\":{plugins}}}}}")).unwrap();
let main = root.join("main.ts");
let text = "export const n: number = 1;\n";
std::fs::write(&main, text).unwrap();
let global = serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [{
"name": "global-plugin",
"location": ide.to_string_lossy(),
"enableForWorkspaceTypeScriptVersions": true,
}] } } });
for configured in [false, true] {
let mut server = npm_server(&tools, "vtsls", "vtsls", Some(global.clone()));
server.tsserver_project = true;
if configured {
assert!(ide_sdk::apply::configure_tsconfig_plugins(&mut server, &root, &ide.join("data")));
}
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)]));
let doc = DocId::next();
mgr.did_open(doc, &main, &LanguageId::new("typescript"), 1, text);
let mut messages = retry("the plugins' diagnostics", Duration::from_secs(90), || {
let found = events.lock().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path, items, .. } if path == &main && !items.is_empty() => {
Some(items.iter().map(|d| d.message.clone()).collect::<Vec<_>>())
}
_ => None,
});
async move { found }
})
.await;
messages.sort();
let expected: &[&str] =
if configured { &["from global-plugin", "from project-plugin"] } else { &["from global-plugin"] };
assert_eq!(messages, expected);
let crashed = matches!(last_status(&events, "vtsls"), Some((ServerStatus::Crashed, _)));
assert!(!crashed, "{:?}", last_status(&events, "vtsls"));
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
}
const NG_APP_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.html',\n})\nexport class App {\n title = 'demo';\n}\n";
const NG_APP_HTML: &str = "<h1>{{ title }}</h1>\n<p>{{ missing }}</p>\n";
const NG_INLINE_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-inline',\n template: `<b>{{ count }}</b>`,\n})\nexport class Inline {\n count = 1;\n}\n";
@@ -1425,3 +1677,81 @@ async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() {
.await;
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
/// Indented Sass through the built-in `sass` definition: completion, Go to
/// Declaration and hover across `@use`, and syntax errors as diagnostics.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires some-sass-language-server on PATH"]
async fn some_sass_indented_end_to_end() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let theme = root.join("_theme.sass");
std::fs::write(
&theme,
"/// Brand colour\n$brand: #336699\n\n/// Rounded corners\n@mixin rounded($r: 4px)\n border-radius: $r\n",
)
.unwrap();
let main = root.join("main.sass");
let source = "@use \"theme\"\n\n.button\n color: theme.$brand\n +theme.rounded(2px)\n";
std::fs::write(&main, source).unwrap();
let sass = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("sass")).unwrap();
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![sass]));
let doc = DocId::next();
mgr.did_open(doc, &main, &LanguageId::new("sass"), 1, source);
let name = "some-sass-language-server";
retry("some-sass ready", Duration::from_secs(30), || {
let status = last_status(&events, name);
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
panic!("some-sass failed: {msg:?}");
}
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
})
.await;
// `theme.$brand` and the `+theme.rounded` mixin, both in `_theme.sass`.
for (pos, line) in [(Pos::new(3, 17), 1), (Pos::new(4, 10), 4)] {
let defs = retry("definition", Duration::from_secs(30), || {
let mgr = mgr.clone();
async move { mgr.goto(doc, pos, GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
})
.await;
assert_eq!((defs[0].path.to_path_buf(), defs[0].range.start.line), (theme.clone(), line), "{pos:?}");
}
// The `@use` path is a document link, which Go to Declaration follows.
let links = mgr.document_links(doc).await.unwrap();
assert!(
links
.iter()
.any(|l| l.range.start.line == 0 && l.path.as_ref().map(|p| p.to_path_buf()) == Some(theme.clone())),
"{links:?}"
);
let hover = mgr.hover(doc, Pos::new(3, 17), Default::default()).await.unwrap().unwrap();
assert!(hover.contents.value.contains("#336699") && hover.contents.value.contains("Brand colour"));
let hover = mgr.hover(doc, Pos::new(4, 10), Default::default()).await.unwrap().unwrap();
assert!(hover.contents.value.contains("Rounded corners"), "{}", hover.contents.value);
// `$` lists the module's variables, `+` its mixins.
let edited = format!("{source} margin: theme.$\n +theme.\n");
mgr.did_change(
doc,
2,
&[AppliedChange { range: Range::point(Pos::new(5, 0)), text: edited[source.len()..].into() }],
&|| unreachable!(),
);
let labels = |list: ide_lsp::types::CompletionList| list.items.into_iter().map(|i| i.label).collect::<Vec<_>>();
let vars = labels(mgr.completion(doc, Pos::new(5, 16), Some("$".into()), Default::default()).await.unwrap());
assert!(vars.iter().any(|l| l.contains("$brand")), "{vars:?}");
let mixins = labels(mgr.completion(doc, Pos::new(6, 9), Some(".".into()), Default::default()).await.unwrap());
assert!(mixins.iter().any(|l| l.contains("rounded")), "{mixins:?}");
let errors = retry("diagnostics", Duration::from_secs(30), || {
let found = events.lock().iter().rev().find_map(|event| match event {
IdeEvent::Diagnostics { source, items, .. } if source == name && !items.is_empty() => Some(items.clone()),
_ => None,
});
async move { found }
})
.await;
assert!(errors.iter().any(|d| d.range.start.line >= 5), "{errors:?}");
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
04c8f881e25aae1b7298f554f3c4ab38251eec48e8d88656d73cad019eb1644c
db06d81fb37a51711e2b76ab0192eb23293ef498e8ff6e5e46e0b5099d6ba038
+1 -1
Переглянути файл
@@ -78,7 +78,7 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
// Variables go by name (`-e NAME`) so their values stay out of the command line
// echoed in the console; the docker CLI reads them from its own environment.
let mut env: BTreeMap<String, String> = run.file_env.clone();
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test")
&& !command.env.contains_key("PYTHONUNBUFFERED")
{
env.insert("PYTHONUNBUFFERED".into(), "1".into());
+37 -1
Переглянути файл
@@ -1227,7 +1227,10 @@ fn uses_pytest(root: &Path) -> bool {
if read(&root.join("setup.cfg")).is_some_and(|s| s.contains("[tool:pytest]")) {
return true;
}
if read(&root.join("pyproject.toml")).is_some_and(|py| py.contains("pytest") || root.join("tests").is_dir()) {
// A `tests` folder alone means pytest unless its tests are the standard library's unittest.
if read(&root.join("pyproject.toml"))
.is_some_and(|py| py.contains("pytest") || (root.join("tests").is_dir() && !uses_unittest(root)))
{
return true;
}
["requirements.txt", "requirements-dev.txt", "requirements_dev.txt", "dev-requirements.txt"]
@@ -1235,6 +1238,34 @@ fn uses_pytest(root: &Path) -> bool {
.any(|f| read(&root.join(f)).is_some_and(|s| s.contains("pytest")))
}
/// Whether the project's test modules (`test*.py` at the root and in `tests/` / `test/`) use the
/// standard library's unittest and none of them pytest.
fn uses_unittest(root: &Path) -> bool {
let mut found = false;
for dir in [root.to_path_buf(), root.join("tests"), root.join("test")] {
let Ok(entries) = fs::read_dir(&dir) else { continue };
// ponytail: the first 50 modules of each folder decide; enough to tell a project's style.
for entry in entries.flatten().take(50) {
let name = entry.file_name().to_string_lossy().into_owned();
if !name.starts_with("test") || !name.ends_with(".py") {
continue;
}
let Some(text) = read(&entry.path()) else { continue };
if text
.lines()
.any(|l| l.trim_start().starts_with("import pytest") || l.trim_start().starts_with("from pytest"))
{
return false;
}
found |= text.lines().any(|l| {
let l = l.trim_start();
l.starts_with("import unittest") || l.starts_with("from unittest")
});
}
}
found
}
/// Python configurations of the project at `root`, a folder of the opened project `top`.
fn detect_python(top: &Path, root: &Path, out: &mut Vec<RunConfig>) {
let markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "pytest.ini", "tox.ini", "manage.py"];
@@ -1280,6 +1311,11 @@ fn detect_python(top: &Path, root: &Path, out: &mut Vec<RunConfig>) {
let own_pytest = matches!(env, PyEnv::Venv(ref v) if !v.starts_with("../")) && env.has_tool(root, "pytest");
if uses_pytest(root) || own_pytest {
out.push(py_config("pytest".into(), "pytest".into(), "pytest", env.tool(root, "pytest"), &[]).test());
} else if !root.join("manage.py").is_file() && uses_unittest(root) {
out.push(
py_config("unittest".into(), "python -m unittest".into(), "unittest", env.python(), &["-m", "unittest"])
.test(),
);
}
// After pytest: a project set up for pytest (pytest-django) keeps it as the default test runner.
if root.join("manage.py").is_file() {
+33
Переглянути файл
@@ -341,6 +341,7 @@ impl Cx<'_> {
DJANGO_SERVER => self.django_server(name, c, &mut ignored)?,
DJANGO_TESTS => self.django_tests(name, c, &mut ignored)?,
PYTHON_TESTS if matches!(factory, "py.test" | "pytest") => self.pytest(name, c, &mut ignored)?,
PYTHON_TESTS if factory == "Unittests" => self.unittest(name, c, &mut ignored)?,
NPM => self.npm(name, c, &mut ignored)?,
JEST | VITEST => self.js_tests(name, c, ty == VITEST, &mut ignored)?,
NODE => self.node(name, c, &mut ignored)?,
@@ -667,6 +668,38 @@ impl Cx<'_> {
Ok(rc)
}
/// PyCharm's Unittests: a Python target (`tests.test_money.TestRound`) as unittest's name, a
/// file as its path, a folder discovered (`discover -s`, with the configuration's pattern).
fn unittest(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
let (exe, mut args, dir, cwd) = self.interpreter(c, ignored)?;
args.extend(["-m".to_owned(), "unittest".to_owned()]);
let field = |key: &str| c.option(key).map(json_string).filter(|v| !v.trim().is_empty());
if let Some(target) = field("_new_target") {
let target = self.expand(&target)?;
match field("_new_targetType").as_deref() {
Some("PYTHON") => args.push(target),
Some("CUSTOM") => {}
_ => {
let path = path_from(self.root, file_url_path(&target), &dir);
if path.ends_with(".py") {
args.push(path);
} else {
args.extend(["discover".to_owned(), "-s".to_owned(), path]);
if let Some(pattern) = field("_new_pattern") {
args.extend(["-p".to_owned(), strip_quotes(&pattern).to_owned()]);
}
}
}
}
}
args.extend(self.args_quoted(field("_new_additionalArguments").as_deref(), Quotes::Single, &dir)?);
let mut rc = config(name, "unittest", exe, args, Some("debugpy"));
rc.cwd = cwd.map(Into::into);
rc.is_test = true;
self.python_env(c, &mut rc, ignored)?;
Ok(rc)
}
/// A pytest Python target (`tests.test_money.TestRound.test_eur`) as the node id PyCharm
/// passes (`tests/test_money.py::TestRound::test_eur`, intellij-community `PyTestsShared.kt:366-400`):
/// the longest prefix that is a module on disk (`a/b.py` or `a/b/__init__.py`, from the working
+7 -3
Переглянути файл
@@ -311,15 +311,19 @@ impl Cx<'_> {
}
fn python_attach(&self, name: &str, obj: &Map<String, Value>) -> Res<RunConfig> {
if obj.contains_key("processId") || obj.contains_key("listen") {
if obj.contains_key("processId") {
return Err(SkipReason::UnsupportedAttach);
}
let connect = obj.get("connect").and_then(Value::as_object).unwrap_or(obj);
// `listen`: the program connects with `debugpy.connect` (Python Debug Server).
let (kind, connect) = match obj.get("listen").and_then(Value::as_object) {
Some(listen) => ("python-debug-server", listen),
None => ("python-remote", obj.get("connect").and_then(Value::as_object).unwrap_or(obj)),
};
let host = self.string(connect, "host")?.unwrap_or_else(|| "localhost".into());
let Some(port) = self.string(connect, "port")? else {
return Err(SkipReason::UnsupportedAttach);
};
let mut c = config(name, "python-remote", String::new(), Vec::new(), Some("debugpy"));
let mut c = config(name, kind, String::new(), Vec::new(), Some("debugpy"));
c.extras.params = BTreeMap::from([("host".into(), host), ("port".into(), port)]);
if let Some(Value::Object(m)) = obj.get("pathMappings").and_then(|m| m.get(0)) {
self.roots(m, &mut c)?;
Loaded 100 of 625 files, more files were not shown because too many files have changed in this diff. Show more